diff --git a/README.md b/README.md index 4d9d15e..b64c2f2 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,8 @@ or ```source .env && forge test --fork-url $MAINNET_RPC_URL -m test_frxETHMinter ### Other Scipts tsx validate-msig-add-validators.ts +DepositDataToCalldata: SEE THE DepositDataToCalldata.s.sol FILE ITSELF FOR INSTRUCTIONS + ### Slither 1) Install [slither](https://github.com/crytic/slither#how-to-install) 2) Slither a single contract diff --git a/flattened.sol b/flattened.sol index 4b55ea3..e922e42 100644 --- a/flattened.sol +++ b/flattened.sol @@ -1,6 +1,26 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -pragma solidity >=0.8.0; +// SPDX-License-Identifier: AGPL-3.0-only +pragma solidity ^0.8.0; +// ==================================================================== +// | ______ _______ | +// | / _____________ __ __ / ____(_____ ____ _____ ________ | +// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | +// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | +// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | +// | | +// ==================================================================== +// ============================ frxETHMinter ========================== +// ==================================================================== +// Frax Finance: https://github.com/FraxFinance + +// Primary Author(s) +// Jack Corddry: https://github.com/corddry +// Justin Moore: https://github.com/0xJM + +// Reviewer(s) / Contributor(s) +// Travis Moore: https://github.com/FortisFortuna +// Dennis: https://github.com/denett +// Jamie Turley: https://github.com/jyturley // ==================================================================== // | ______ _______ | @@ -10,7 +30,7 @@ pragma solidity >=0.8.0; // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== -// ============================== sfrxETH ============================= +// ============================== frxETH ============================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance @@ -20,978 +40,1640 @@ pragma solidity >=0.8.0; // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian -// Dennett: https://github.com/denett +// Dennis: https://github.com/denett // Travis Moore: https://github.com/FortisFortuna // Jamie Turley: https://github.com/jyturley -// Rewards logic inspired by xERC20 (https://github.com/ZeframLou/playpen/blob/main/src/xERC20.sol) +/// @title Stablecoin pegged to Ether for use within the Frax ecosystem +/** @notice Does not accrue ETH 2.0 staking yield: it must be staked at the sfrxETH contract first. + ETH -> frxETH conversion is permanent, so a market will develop for the latter. + Withdraws are not live (as of deploy time) so loosely pegged to eth but is possible will float */ +/// @dev frxETH adheres to EIP-712/EIP-2612 and can use permits -/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. -/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol) -/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) -/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. -abstract contract ERC20 { - /*////////////////////////////////////////////////////////////// - EVENTS - //////////////////////////////////////////////////////////////*/ +// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol) - event Transfer(address indexed from, address indexed to, uint256 amount); +// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) - event Approval(address indexed owner, address indexed spender, uint256 amount); +/** + * @dev Interface of the ERC20 standard as defined in the EIP. + */ +interface IERC20 { + /** + * @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); - /*////////////////////////////////////////////////////////////// - METADATA STORAGE - //////////////////////////////////////////////////////////////*/ + /** + * @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 Returns the amount of tokens in existence. + */ + function totalSupply() external view returns (uint256); - string public name; + /** + * @dev Returns the amount of tokens owned by `account`. + */ + function balanceOf(address account) external view returns (uint256); - string public symbol; + /** + * @dev Moves `amount` tokens from the caller's account to `to`. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * Emits a {Transfer} event. + */ + function transfer(address to, uint256 amount) external returns (bool); + + /** + * @dev Returns the remaining number of tokens that `spender` will be + * allowed to spend on behalf of `owner` through {transferFrom}. This is + * zero by default. + * + * This value changes when {approve} or {transferFrom} are called. + */ + function allowance(address owner, address spender) external view returns (uint256); + + /** + * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * IMPORTANT: Beware that changing an allowance with this method brings the risk + * that someone may use both the old and the new allowance by unfortunate + * transaction ordering. One possible solution to mitigate this race + * condition is to first reduce the spender's allowance to 0 and set the + * desired value afterwards: + * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 + * + * Emits an {Approval} event. + */ + function approve(address spender, uint256 amount) external returns (bool); + + /** + * @dev Moves `amount` tokens from `from` to `to` using the + * allowance mechanism. `amount` is then deducted from the caller's + * allowance. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * Emits a {Transfer} event. + */ + function transferFrom( + address from, + address to, + uint256 amount + ) external returns (bool); +} - uint8 public immutable decimals; +// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) - /*////////////////////////////////////////////////////////////// - ERC20 STORAGE - //////////////////////////////////////////////////////////////*/ +/** + * @dev Interface for the optional metadata functions from the ERC20 standard. + * + * _Available since v4.1._ + */ +interface IERC20Metadata is IERC20 { + /** + * @dev Returns the name of the token. + */ + function name() external view returns (string memory); - uint256 public totalSupply; + /** + * @dev Returns the symbol of the token. + */ + function symbol() external view returns (string memory); - mapping(address => uint256) public balanceOf; + /** + * @dev Returns the decimals places of the token. + */ + function decimals() external view returns (uint8); +} - mapping(address => mapping(address => uint256)) public allowance; +// OpenZeppelin Contracts v4.4.1 (utils/Context.sol) - /*////////////////////////////////////////////////////////////// - EIP-2612 STORAGE - //////////////////////////////////////////////////////////////*/ +/** + * @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; + } - uint256 internal immutable INITIAL_CHAIN_ID; + function _msgData() internal view virtual returns (bytes calldata) { + return msg.data; + } +} - bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; +/** + * @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.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How + * to implement supply mechanisms]. + * + * We have followed general OpenZeppelin Contracts guidelines: functions revert + * instead returning `false` on failure. This behavior is nonetheless + * conventional and does not conflict with the expectations of ERC20 + * applications. + * + * Additionally, an {Approval} event is emitted on calls to {transferFrom}. + * This allows applications to reconstruct the allowance for all accounts just + * by listening to said events. Other implementations of the EIP may not emit + * these events, as it isn't required by the specification. + * + * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} + * functions have been added to mitigate the well-known issues around setting + * allowances. See {IERC20-approve}. + */ +contract ERC20 is Context, IERC20, IERC20Metadata { + mapping(address => uint256) private _balances; - mapping(address => uint256) public nonces; + mapping(address => mapping(address => uint256)) private _allowances; - /*////////////////////////////////////////////////////////////// - CONSTRUCTOR - //////////////////////////////////////////////////////////////*/ + uint256 private _totalSupply; - constructor( - string memory _name, - string memory _symbol, - uint8 _decimals - ) { - name = _name; - symbol = _symbol; - decimals = _decimals; + string private _name; + string private _symbol; - INITIAL_CHAIN_ID = block.chainid; - INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); + /** + * @dev Sets the values for {name} and {symbol}. + * + * The default value of {decimals} is 18. To select a different value for + * {decimals} you should overload it. + * + * All two of these values are immutable: they can only be set once during + * construction. + */ + constructor(string memory name_, string memory symbol_) { + _name = name_; + _symbol = symbol_; } - /*////////////////////////////////////////////////////////////// - ERC20 LOGIC - //////////////////////////////////////////////////////////////*/ + /** + * @dev Returns the name of the token. + */ + function name() public view virtual override returns (string memory) { + return _name; + } - function approve(address spender, uint256 amount) public virtual returns (bool) { - allowance[msg.sender][spender] = amount; + /** + * @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; + } - emit Approval(msg.sender, spender, amount); + /** + * @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; + } - return true; + /** + * @dev See {IERC20-totalSupply}. + */ + function totalSupply() public view virtual override returns (uint256) { + return _totalSupply; } - function transfer(address to, uint256 amount) public virtual returns (bool) { - balanceOf[msg.sender] -= amount; + /** + * @dev See {IERC20-balanceOf}. + */ + function balanceOf(address account) public view virtual override returns (uint256) { + return _balances[account]; + } - // Cannot overflow because the sum of all user - // balances can't exceed the max uint256 value. - unchecked { - balanceOf[to] += amount; - } + /** + * @dev See {IERC20-transfer}. + * + * Requirements: + * + * - `to` cannot be the zero address. + * - the caller must have a balance of at least `amount`. + */ + function transfer(address to, uint256 amount) public virtual override returns (bool) { + address owner = _msgSender(); + _transfer(owner, to, amount); + return true; + } - emit Transfer(msg.sender, to, amount); + /** + * @dev See {IERC20-allowance}. + */ + function allowance(address owner, address spender) public view virtual override returns (uint256) { + return _allowances[owner][spender]; + } + /** + * @dev See {IERC20-approve}. + * + * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on + * `transferFrom`. This is semantically equivalent to an infinite approval. + * + * Requirements: + * + * - `spender` cannot be the zero address. + */ + function approve(address spender, uint256 amount) public virtual override returns (bool) { + address owner = _msgSender(); + _approve(owner, spender, amount); return true; } + /** + * @dev See {IERC20-transferFrom}. + * + * Emits an {Approval} event indicating the updated allowance. This is not + * required by the EIP. See the note at the beginning of {ERC20}. + * + * NOTE: Does not update the allowance if the current allowance + * is the maximum `uint256`. + * + * Requirements: + * + * - `from` and `to` cannot be the zero address. + * - `from` must have a balance of at least `amount`. + * - the caller must have allowance for ``from``'s tokens of at least + * `amount`. + */ function transferFrom( address from, address to, uint256 amount - ) public virtual returns (bool) { - uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. - - if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; + ) public virtual override returns (bool) { + address spender = _msgSender(); + _spendAllowance(from, spender, amount); + _transfer(from, to, amount); + return true; + } - balanceOf[from] -= amount; + /** + * @dev Atomically increases the allowance granted to `spender` by the caller. + * + * This is an alternative to {approve} that can be used as a mitigation for + * problems described in {IERC20-approve}. + * + * Emits an {Approval} event indicating the updated allowance. + * + * Requirements: + * + * - `spender` cannot be the zero address. + */ + function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { + address owner = _msgSender(); + _approve(owner, spender, allowance(owner, spender) + addedValue); + return true; + } - // Cannot overflow because the sum of all user - // balances can't exceed the max uint256 value. + /** + * @dev Atomically decreases the allowance granted to `spender` by the caller. + * + * This is an alternative to {approve} that can be used as a mitigation for + * problems described in {IERC20-approve}. + * + * Emits an {Approval} event indicating the updated allowance. + * + * Requirements: + * + * - `spender` cannot be the zero address. + * - `spender` must have allowance for the caller of at least + * `subtractedValue`. + */ + function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { + address owner = _msgSender(); + uint256 currentAllowance = allowance(owner, spender); + require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { - balanceOf[to] += amount; + _approve(owner, spender, currentAllowance - subtractedValue); } - emit Transfer(from, to, amount); - return true; } - /*////////////////////////////////////////////////////////////// - EIP-2612 LOGIC - //////////////////////////////////////////////////////////////*/ + /** + * @dev Moves `amount` of tokens from `from` to `to`. + * + * This internal function is equivalent to {transfer}, and can be used to + * e.g. implement automatic token fees, slashing mechanisms, etc. + * + * Emits a {Transfer} event. + * + * Requirements: + * + * - `from` cannot be the zero address. + * - `to` cannot be the zero address. + * - `from` must have a balance of at least `amount`. + */ + function _transfer( + address from, + address to, + uint256 amount + ) internal virtual { + require(from != address(0), "ERC20: transfer from the zero address"); + require(to != address(0), "ERC20: transfer to the zero address"); - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual { - require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); + _beforeTokenTransfer(from, to, amount); - // Unchecked because the only math done is incrementing - // the owner's nonce which cannot realistically overflow. + uint256 fromBalance = _balances[from]; + require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { - address recoveredAddress = ecrecover( - keccak256( - abi.encodePacked( - "\x19\x01", - DOMAIN_SEPARATOR(), - keccak256( - abi.encode( - keccak256( - "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" - ), - owner, - spender, - value, - nonces[owner]++, - deadline - ) - ) - ) - ), - v, - r, - s - ); - - require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); - - allowance[recoveredAddress][spender] = value; + _balances[from] = fromBalance - amount; + // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by + // decrementing then incrementing. + _balances[to] += amount; } - emit Approval(owner, spender, value); - } - - function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { - return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); - } + emit Transfer(from, to, amount); - function computeDomainSeparator() internal view virtual returns (bytes32) { - return - keccak256( - abi.encode( - keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), - keccak256(bytes(name)), - keccak256("1"), - block.chainid, - address(this) - ) - ); + _afterTokenTransfer(from, to, amount); } - /*////////////////////////////////////////////////////////////// - INTERNAL MINT/BURN LOGIC - //////////////////////////////////////////////////////////////*/ + /** @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"); - function _mint(address to, uint256 amount) internal virtual { - totalSupply += amount; + _beforeTokenTransfer(address(0), account, amount); - // Cannot overflow because the sum of all user - // balances can't exceed the max uint256 value. + _totalSupply += amount; unchecked { - balanceOf[to] += amount; + // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. + _balances[account] += amount; } + emit Transfer(address(0), account, amount); - emit Transfer(address(0), to, amount); + _afterTokenTransfer(address(0), account, amount); } - function _burn(address from, uint256 amount) internal virtual { - balanceOf[from] -= 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); - // Cannot underflow because a user's balance - // will never be larger than the total supply. + uint256 accountBalance = _balances[account]; + require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { - totalSupply -= amount; + _balances[account] = accountBalance - amount; + // Overflow not possible: amount <= accountBalance <= totalSupply. + _totalSupply -= amount; } - emit Transfer(from, address(0), amount); + emit Transfer(account, address(0), amount); + + _afterTokenTransfer(account, address(0), amount); } -} -/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. -/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol) -/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. -/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller. -library SafeTransferLib { - /*////////////////////////////////////////////////////////////// - ETH OPERATIONS - //////////////////////////////////////////////////////////////*/ - - function safeTransferETH(address to, uint256 amount) internal { - bool success; - - assembly { - // Transfer the ETH and store if it succeeded or not. - success := call(gas(), to, amount, 0, 0, 0, 0) - } + /** + * @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"); - require(success, "ETH_TRANSFER_FAILED"); + _allowances[owner][spender] = amount; + emit Approval(owner, spender, amount); } - /*////////////////////////////////////////////////////////////// - ERC20 OPERATIONS - //////////////////////////////////////////////////////////////*/ - - function safeTransferFrom( - ERC20 token, - address from, - address to, + /** + * @dev Updates `owner` s allowance for `spender` based on spent `amount`. + * + * Does not update the allowance amount in case of infinite allowance. + * Revert if not enough allowance is available. + * + * Might emit an {Approval} event. + */ + function _spendAllowance( + address owner, + address spender, uint256 amount - ) internal { - bool success; - - assembly { - // Get a pointer to some free memory. - let freeMemoryPointer := mload(0x40) - - // Write the abi-encoded calldata into memory, beginning with the function selector. - mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) - mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument. - mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument. - mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. - - success := and( - // Set success to whether the call reverted, if not we check it either - // returned exactly 1 (can't just be non-zero data), or had no return data. - or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())), - // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3. - // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. - // Counterintuitively, this call must be positioned second to the or() call in the - // surrounding and() call or else returndatasize() will be zero during the computation. - call(gas(), token, 0, freeMemoryPointer, 100, 0, 32) - ) + ) internal virtual { + uint256 currentAllowance = allowance(owner, spender); + if (currentAllowance != type(uint256).max) { + require(currentAllowance >= amount, "ERC20: insufficient allowance"); + unchecked { + _approve(owner, spender, currentAllowance - amount); + } } - - require(success, "TRANSFER_FROM_FAILED"); } - function safeTransfer( - ERC20 token, + /** + * @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 { - bool success; - - assembly { - // Get a pointer to some free memory. - let freeMemoryPointer := mload(0x40) - - // Write the abi-encoded calldata into memory, beginning with the function selector. - mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) - mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument. - mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. - - success := and( - // Set success to whether the call reverted, if not we check it either - // returned exactly 1 (can't just be non-zero data), or had no return data. - or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())), - // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2. - // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. - // Counterintuitively, this call must be positioned second to the or() call in the - // surrounding and() call or else returndatasize() will be zero during the computation. - call(gas(), token, 0, freeMemoryPointer, 68, 0, 32) - ) - } + ) internal virtual {} - require(success, "TRANSFER_FAILED"); - } - - function safeApprove( - ERC20 token, + /** + * @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 { - bool success; - - assembly { - // Get a pointer to some free memory. - let freeMemoryPointer := mload(0x40) - - // Write the abi-encoded calldata into memory, beginning with the function selector. - mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) - mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument. - mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. - - success := and( - // Set success to whether the call reverted, if not we check it either - // returned exactly 1 (can't just be non-zero data), or had no return data. - or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())), - // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2. - // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. - // Counterintuitively, this call must be positioned second to the or() call in the - // surrounding and() call or else returndatasize() will be zero during the computation. - call(gas(), token, 0, freeMemoryPointer, 68, 0, 32) - ) - } + ) internal virtual {} +} - require(success, "APPROVE_FAILED"); - } +// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/extensions/draft-ERC20Permit.sol) + +// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) + +/** + * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in + * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. + * + * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by + * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't + * need to send a transaction, and thus is not required to hold Ether at all. + */ +interface IERC20Permit { + /** + * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, + * given ``owner``'s signed approval. + * + * IMPORTANT: The same issues {IERC20-approve} has related to transaction + * ordering also apply here. + * + * Emits an {Approval} event. + * + * Requirements: + * + * - `spender` cannot be the zero address. + * - `deadline` must be a timestamp in the future. + * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` + * over the EIP712-formatted function arguments. + * - the signature must use ``owner``'s current nonce (see {nonces}). + * + * For more information on the signature format, see the + * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP + * section]. + */ + function permit( + address owner, + address spender, + uint256 value, + uint256 deadline, + uint8 v, + bytes32 r, + bytes32 s + ) external; + + /** + * @dev Returns the current nonce for `owner`. This value must be + * included whenever a signature is generated for {permit}. + * + * Every successful call to {permit} increases ``owner``'s nonce by one. This + * prevents a signature from being used multiple times. + */ + function nonces(address owner) external view returns (uint256); + + /** + * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. + */ + // solhint-disable-next-line func-name-mixedcase + function DOMAIN_SEPARATOR() external view returns (bytes32); } -/// @notice Arithmetic library with operations for fixed-point numbers. -/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol) -/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol) -library FixedPointMathLib { - /*////////////////////////////////////////////////////////////// - SIMPLIFIED FIXED POINT OPERATIONS - //////////////////////////////////////////////////////////////*/ +// OpenZeppelin Contracts (last updated v4.7.0) (utils/cryptography/ECDSA.sol) + +// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol) - uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s. +// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol) - function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) { - return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down. +/** + * @dev Standard math utilities missing in the Solidity language. + */ +library Math { + enum Rounding { + Down, // Toward negative infinity + Up, // Toward infinity + Zero // Toward zero } - function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) { - return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up. + /** + * @dev Returns the largest of two numbers. + */ + function max(uint256 a, uint256 b) internal pure returns (uint256) { + return a > b ? a : b; } - function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) { - return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down. + /** + * @dev Returns the smallest of two numbers. + */ + function min(uint256 a, uint256 b) internal pure returns (uint256) { + return a < b ? a : b; } - function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) { - return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up. + /** + * @dev Returns the average of two numbers. The result is rounded towards + * zero. + */ + function average(uint256 a, uint256 b) internal pure returns (uint256) { + // (a + b) / 2 can overflow. + return (a & b) + (a ^ b) / 2; } - /*////////////////////////////////////////////////////////////// - LOW LEVEL FIXED POINT OPERATIONS - //////////////////////////////////////////////////////////////*/ + /** + * @dev Returns the ceiling of the division of two numbers. + * + * This differs from standard division with `/` in that it rounds up instead + * of rounding down. + */ + function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { + // (a + b - 1) / b can overflow on addition, so we distribute. + return a == 0 ? 0 : (a - 1) / b + 1; + } - function mulDivDown( + /** + * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 + * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) + * with further edits by Uniswap Labs also under MIT license. + */ + function mulDiv( uint256 x, uint256 y, uint256 denominator - ) internal pure returns (uint256 z) { - assembly { - // Store x * y in z for now. - z := mul(x, y) - - // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) - if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { - revert(0, 0) + ) internal pure returns (uint256 result) { + unchecked { + // 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) { + return prod0 / denominator; + } + + // Make sure the result is less than 2^256. Also prevents denominator == 0. + require(denominator > prod1); + + /////////////////////////////////////////////// + // 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. + + // Does not overflow because the denominator cannot be zero at this stage in the function. + uint256 twos = denominator & (~denominator + 1); + assembly { + // Divide denominator by twos. + denominator := div(denominator, twos) + + // Divide [prod1 prod0] by twos. + prod0 := div(prod0, twos) + + // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. + twos := add(div(sub(0, twos), twos), 1) } - // Divide z by the denominator. - z := div(z, denominator) + // Shift in bits from prod1 into prod0. + prod0 |= prod1 * twos; + + // 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; } } - function mulDivUp( + /** + * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. + */ + function mulDiv( uint256 x, uint256 y, - uint256 denominator - ) internal pure returns (uint256 z) { - assembly { - // Store x * y in z for now. - z := mul(x, y) - - // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) - if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { - revert(0, 0) - } - - // First, divide z - 1 by the denominator and add 1. - // We allow z - 1 to underflow if z is 0, because we multiply the - // end result by 0 if z is zero, ensuring we return 0 if z is zero. - z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1)) + uint256 denominator, + Rounding rounding + ) internal pure returns (uint256) { + uint256 result = mulDiv(x, y, denominator); + if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { + result += 1; } + return result; } - function rpow( - uint256 x, - uint256 n, - uint256 scalar - ) internal pure returns (uint256 z) { - assembly { - switch x - case 0 { - switch n - case 0 { - // 0 ** 0 = 1 - z := scalar - } - default { - // 0 ** n = 0 - z := 0 - } - } - default { - switch mod(n, 2) - case 0 { - // If n is even, store scalar in z for now. - z := scalar - } - default { - // If n is odd, store x in z for now. - z := x - } + /** + * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. + * + * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). + */ + function sqrt(uint256 a) internal pure returns (uint256) { + if (a == 0) { + return 0; + } - // Shifting right by 1 is like dividing by 2. - let half := shr(1, scalar) - - for { - // Shift n right by 1 before looping to halve it. - n := shr(1, n) - } n { - // Shift n right by 1 each iteration to halve it. - n := shr(1, n) - } { - // Revert immediately if x ** 2 would overflow. - // Equivalent to iszero(eq(div(xx, x), x)) here. - if shr(128, x) { - revert(0, 0) - } - - // Store x squared. - let xx := mul(x, x) - - // Round to the nearest number. - let xxRound := add(xx, half) - - // Revert if xx + half overflowed. - if lt(xxRound, xx) { - revert(0, 0) - } - - // Set x to scaled xxRound. - x := div(xxRound, scalar) - - // If n is even: - if mod(n, 2) { - // Compute z * x. - let zx := mul(z, x) - - // If z * x overflowed: - if iszero(eq(div(zx, x), z)) { - // Revert if x is non-zero. - if iszero(iszero(x)) { - revert(0, 0) - } - } - - // Round to the nearest number. - let zxRound := add(zx, half) - - // Revert if zx + half overflowed. - if lt(zxRound, zx) { - revert(0, 0) - } - - // Return properly scaled zxRound. - z := div(zxRound, scalar) - } - } - } + // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. + // + // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have + // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. + // + // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` + // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` + // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` + // + // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. + uint256 result = 1 << (log2(a) >> 1); + + // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, + // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at + // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision + // into the expected uint128 result. + unchecked { + result = (result + a / result) >> 1; + result = (result + a / result) >> 1; + result = (result + a / result) >> 1; + result = (result + a / result) >> 1; + result = (result + a / result) >> 1; + result = (result + a / result) >> 1; + result = (result + a / result) >> 1; + return min(result, a / result); } } - /*////////////////////////////////////////////////////////////// - GENERAL NUMBER UTILITIES - //////////////////////////////////////////////////////////////*/ - - function sqrt(uint256 x) internal pure returns (uint256 z) { - assembly { - let y := x // We start y at x, which will help us make our initial estimate. + /** + * @notice Calculates sqrt(a), following the selected rounding direction. + */ + function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { + unchecked { + uint256 result = sqrt(a); + return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); + } + } - z := 181 // The "correct" value is 1, but this saves a multiplication later. + /** + * @dev Return the log in base 2, rounded down, of a positive value. + * Returns 0 if given 0. + */ + function log2(uint256 value) internal pure returns (uint256) { + uint256 result = 0; + unchecked { + if (value >> 128 > 0) { + value >>= 128; + result += 128; + } + if (value >> 64 > 0) { + value >>= 64; + result += 64; + } + if (value >> 32 > 0) { + value >>= 32; + result += 32; + } + if (value >> 16 > 0) { + value >>= 16; + result += 16; + } + if (value >> 8 > 0) { + value >>= 8; + result += 8; + } + if (value >> 4 > 0) { + value >>= 4; + result += 4; + } + if (value >> 2 > 0) { + value >>= 2; + result += 2; + } + if (value >> 1 > 0) { + result += 1; + } + } + return result; + } - // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad - // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. + /** + * @dev Return the log in base 2, following the selected rounding direction, of a positive value. + * Returns 0 if given 0. + */ + function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { + unchecked { + uint256 result = log2(value); + return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); + } + } - // We check y >= 2^(k + 8) but shift right by k bits - // each branch to ensure that if x >= 256, then y >= 256. - if iszero(lt(y, 0x10000000000000000000000000000000000)) { - y := shr(128, y) - z := shl(64, z) + /** + * @dev Return the log in base 10, rounded down, of a positive value. + * Returns 0 if given 0. + */ + function log10(uint256 value) internal pure returns (uint256) { + uint256 result = 0; + unchecked { + if (value >= 10**64) { + value /= 10**64; + result += 64; } - if iszero(lt(y, 0x1000000000000000000)) { - y := shr(64, y) - z := shl(32, z) + if (value >= 10**32) { + value /= 10**32; + result += 32; } - if iszero(lt(y, 0x10000000000)) { - y := shr(32, y) - z := shl(16, z) + if (value >= 10**16) { + value /= 10**16; + result += 16; } - if iszero(lt(y, 0x1000000)) { - y := shr(16, y) - z := shl(8, z) + if (value >= 10**8) { + value /= 10**8; + result += 8; + } + if (value >= 10**4) { + value /= 10**4; + result += 4; + } + if (value >= 10**2) { + value /= 10**2; + result += 2; + } + if (value >= 10**1) { + result += 1; } - - // Goal was to get z*z*y within a small factor of x. More iterations could - // get y in a tighter range. Currently, we will have y in [256, 256*2^16). - // We ensured y >= 256 so that the relative difference between y and y+1 is small. - // That's not possible if x < 256 but we can just verify those cases exhaustively. - - // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256. - // Correctness can be checked exhaustively for x < 256, so we assume y >= 256. - // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps. - - // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range - // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256. - - // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate - // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18. - - // There is no overflow risk here since y < 2^136 after the first branch above. - z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181. - - // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. - z := shr(1, add(z, div(x, z))) - z := shr(1, add(z, div(x, z))) - z := shr(1, add(z, div(x, z))) - z := shr(1, add(z, div(x, z))) - z := shr(1, add(z, div(x, z))) - z := shr(1, add(z, div(x, z))) - z := shr(1, add(z, div(x, z))) - - // If x+1 is a perfect square, the Babylonian method cycles between - // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor. - // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division - // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case. - // If you don't care whether the floor or ceil square root is returned, you can remove this statement. - z := sub(z, lt(div(x, z), z)) } + return result; } - function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) { - assembly { - // Mod x by y. Note this will return - // 0 instead of reverting if y is zero. - z := mod(x, y) + /** + * @dev Return the log in base 10, following the selected rounding direction, of a positive value. + * Returns 0 if given 0. + */ + function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { + unchecked { + uint256 result = log10(value); + return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0); } } - function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) { - assembly { - // Divide x by y. Note this will return - // 0 instead of reverting if y is zero. - r := div(x, y) + /** + * @dev Return the log in base 256, rounded down, of a positive value. + * Returns 0 if given 0. + * + * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. + */ + function log256(uint256 value) internal pure returns (uint256) { + uint256 result = 0; + unchecked { + if (value >> 128 > 0) { + value >>= 128; + result += 16; + } + if (value >> 64 > 0) { + value >>= 64; + result += 8; + } + if (value >> 32 > 0) { + value >>= 32; + result += 4; + } + if (value >> 16 > 0) { + value >>= 16; + result += 2; + } + if (value >> 8 > 0) { + result += 1; + } } + return result; } - function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) { - assembly { - // Add 1 to x * y if x % y > 0. Note this will - // return 0 instead of reverting if y is zero. - z := add(gt(mod(x, y), 0), div(x, y)) + /** + * @dev Return the log in base 10, following the selected rounding direction, of a positive value. + * Returns 0 if given 0. + */ + function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { + unchecked { + uint256 result = log256(value); + return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); } } } -/// @notice Minimal ERC4626 tokenized Vault implementation. -/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/mixins/ERC4626.sol) -abstract contract ERC4626 is ERC20 { - using SafeTransferLib for ERC20; - using FixedPointMathLib for uint256; - - /*////////////////////////////////////////////////////////////// - EVENTS - //////////////////////////////////////////////////////////////*/ - - event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares); - - event Withdraw( - address indexed caller, - address indexed receiver, - address indexed owner, - uint256 assets, - uint256 shares - ); - - /*////////////////////////////////////////////////////////////// - IMMUTABLES - //////////////////////////////////////////////////////////////*/ - - ERC20 public immutable asset; +/** + * @dev String operations. + */ +library Strings { + bytes16 private constant _SYMBOLS = "0123456789abcdef"; + uint8 private constant _ADDRESS_LENGTH = 20; - constructor( - ERC20 _asset, - string memory _name, - string memory _symbol - ) ERC20(_name, _symbol, _asset.decimals()) { - asset = _asset; + /** + * @dev Converts a `uint256` to its ASCII `string` decimal representation. + */ + function toString(uint256 value) internal pure returns (string memory) { + unchecked { + uint256 length = Math.log10(value) + 1; + string memory buffer = new string(length); + uint256 ptr; + /// @solidity memory-safe-assembly + assembly { + ptr := add(buffer, add(32, length)) + } + while (true) { + ptr--; + /// @solidity memory-safe-assembly + assembly { + mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) + } + value /= 10; + if (value == 0) break; + } + return buffer; + } } - /*////////////////////////////////////////////////////////////// - DEPOSIT/WITHDRAWAL LOGIC - //////////////////////////////////////////////////////////////*/ - - function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) { - // Check for rounding error since we round down in previewDeposit. - require((shares = previewDeposit(assets)) != 0, "ZERO_SHARES"); - - // Need to transfer before minting or ERC777s could reenter. - asset.safeTransferFrom(msg.sender, address(this), assets); - - _mint(receiver, shares); - - emit Deposit(msg.sender, receiver, assets, shares); - - afterDeposit(assets, shares); + /** + * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. + */ + function toHexString(uint256 value) internal pure returns (string memory) { + unchecked { + return toHexString(value, Math.log256(value) + 1); + } } - function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) { - assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up. - - // Need to transfer before minting or ERC777s could reenter. - asset.safeTransferFrom(msg.sender, address(this), assets); - - _mint(receiver, shares); - - emit Deposit(msg.sender, receiver, assets, shares); - - afterDeposit(assets, shares); + /** + * @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] = _SYMBOLS[value & 0xf]; + value >>= 4; + } + require(value == 0, "Strings: hex length insufficient"); + return string(buffer); } - function withdraw( - uint256 assets, - address receiver, - address owner - ) public virtual returns (uint256 shares) { - shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up. - - if (msg.sender != owner) { - uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals. + /** + * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. + */ + function toHexString(address addr) internal pure returns (string memory) { + return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); + } +} - if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares; +/** + * @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 // Deprecated in v4.8 + } + + 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"); } + } - beforeWithdraw(assets, shares); + /** + * @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) { + 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. + /// @solidity memory-safe-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 { + return (address(0), RecoverError.InvalidSignatureLength); + } + } - _burn(owner, shares); + /** + * @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; + } - emit Withdraw(msg.sender, receiver, owner, assets, shares); + /** + * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. + * + * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] + * + * _Available since v4.3._ + */ + function tryRecover( + bytes32 hash, + bytes32 r, + bytes32 vs + ) internal pure returns (address, RecoverError) { + bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); + uint8 v = uint8((uint256(vs) >> 255) + 27); + return tryRecover(hash, v, r, s); + } - asset.safeTransfer(receiver, assets); + /** + * @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; } - function redeem( - uint256 shares, - address receiver, - address owner - ) public virtual returns (uint256 assets) { - if (msg.sender != owner) { - uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals. + /** + * @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 (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares; + // 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); } - // Check for rounding error since we round down in previewRedeem. - require((assets = previewRedeem(shares)) != 0, "ZERO_ASSETS"); + return (signer, RecoverError.NoError); + } - beforeWithdraw(assets, shares); + /** + * @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; + } - _burn(owner, shares); + /** + * @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)); + } - emit Withdraw(msg.sender, receiver, owner, assets, shares); + /** + * @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)); + } - asset.safeTransfer(receiver, assets); + /** + * @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)); } +} - /*////////////////////////////////////////////////////////////// - ACCOUNTING LOGIC - //////////////////////////////////////////////////////////////*/ +/** + * @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; - function totalAssets() public view virtual returns (uint256); + bytes32 private immutable _HASHED_NAME; + bytes32 private immutable _HASHED_VERSION; + bytes32 private immutable _TYPE_HASH; - function convertToShares(uint256 assets) public view virtual returns (uint256) { - uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. + /* solhint-enable var-name-mixedcase */ - return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets()); + /** + * @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; } - function convertToAssets(uint256 shares) public view virtual returns (uint256) { - uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. - - return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply); + /** + * @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 previewDeposit(uint256 assets) public view virtual returns (uint256) { - return convertToShares(assets); + function _buildDomainSeparator( + bytes32 typeHash, + bytes32 nameHash, + bytes32 versionHash + ) private view returns (bytes32) { + return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } - function previewMint(uint256 shares) public view virtual returns (uint256) { - uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. - - return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply); + /** + * @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); } +} - function previewWithdraw(uint256 assets) public view virtual returns (uint256) { - uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. - - return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets()); - } +// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) - function previewRedeem(uint256 shares) public view virtual returns (uint256) { - return convertToAssets(shares); +/** + * @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 } - /*////////////////////////////////////////////////////////////// - DEPOSIT/WITHDRAWAL LIMIT LOGIC - //////////////////////////////////////////////////////////////*/ - - function maxDeposit(address) public view virtual returns (uint256) { - return type(uint256).max; + function current(Counter storage counter) internal view returns (uint256) { + return counter._value; } - function maxMint(address) public view virtual returns (uint256) { - return type(uint256).max; + function increment(Counter storage counter) internal { + unchecked { + counter._value += 1; + } } - function maxWithdraw(address owner) public view virtual returns (uint256) { - return convertToAssets(balanceOf[owner]); + function decrement(Counter storage counter) internal { + uint256 value = counter._value; + require(value > 0, "Counter: decrement overflow"); + unchecked { + counter._value = value - 1; + } } - function maxRedeem(address owner) public view virtual returns (uint256) { - return balanceOf[owner]; + function reset(Counter storage counter) internal { + counter._value = 0; } +} - /*////////////////////////////////////////////////////////////// - INTERNAL HOOKS LOGIC - //////////////////////////////////////////////////////////////*/ +/** + * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in + * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. + * + * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by + * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't + * need to send a transaction, and thus is not required to hold Ether at all. + * + * _Available since v3.4._ + */ +abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { + using Counters for Counters.Counter; - function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {} + mapping(address => Counters.Counter) private _nonces; - function afterDeposit(uint256 assets, uint256 shares) internal virtual {} -} + // solhint-disable-next-line var-name-mixedcase + bytes32 private constant _PERMIT_TYPEHASH = + keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); + /** + * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`. + * However, to ensure consistency with the upgradeable transpiler, we will continue + * to reserve a slot. + * @custom:oz-renamed-from _PERMIT_TYPEHASH + */ + // solhint-disable-next-line var-name-mixedcase + bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT; -/// @notice Safe unsigned integer casting library that reverts on overflow. -/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeCastLib.sol) -/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol) -library SafeCastLib { - function safeCastTo248(uint256 x) internal pure returns (uint248 y) { - require(x < 1 << 248); + /** + * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. + * + * It's a good idea to use the same `name` that is defined as the ERC20 token name. + */ + constructor(string memory name) EIP712(name, "1") {} - y = uint248(x); - } + /** + * @dev See {IERC20Permit-permit}. + */ + function permit( + address owner, + address spender, + uint256 value, + uint256 deadline, + uint8 v, + bytes32 r, + bytes32 s + ) public virtual override { + require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); - function safeCastTo224(uint256 x) internal pure returns (uint224 y) { - require(x < 1 << 224); + bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); - y = uint224(x); - } + bytes32 hash = _hashTypedDataV4(structHash); - function safeCastTo192(uint256 x) internal pure returns (uint192 y) { - require(x < 1 << 192); + address signer = ECDSA.recover(hash, v, r, s); + require(signer == owner, "ERC20Permit: invalid signature"); - y = uint192(x); + _approve(owner, spender, value); } - function safeCastTo160(uint256 x) internal pure returns (uint160 y) { - require(x < 1 << 160); - - y = uint160(x); + /** + * @dev See {IERC20Permit-nonces}. + */ + function nonces(address owner) public view virtual override returns (uint256) { + return _nonces[owner].current(); } - function safeCastTo128(uint256 x) internal pure returns (uint128 y) { - require(x < 1 << 128); - - y = uint128(x); + /** + * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. + */ + // solhint-disable-next-line func-name-mixedcase + function DOMAIN_SEPARATOR() external view override returns (bytes32) { + return _domainSeparatorV4(); } - function safeCastTo96(uint256 x) internal pure returns (uint96 y) { - require(x < 1 << 96); - - y = uint96(x); + /** + * @dev "Consume a nonce": return the current value and increment. + * + * _Available since v4.1._ + */ + function _useNonce(address owner) internal virtual returns (uint256 current) { + Counters.Counter storage nonce = _nonces[owner]; + current = nonce.current(); + nonce.increment(); } +} - function safeCastTo64(uint256 x) internal pure returns (uint64 y) { - require(x < 1 << 64); +// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) - y = uint64(x); +/** + * @dev Extension of {ERC20} that allows token holders to destroy both their own + * tokens and those that they have an allowance for, in a way that can be + * recognized off-chain (via event analysis). + */ +abstract contract ERC20Burnable is Context, ERC20 { + /** + * @dev Destroys `amount` tokens from the caller. + * + * See {ERC20-_burn}. + */ + function burn(uint256 amount) public virtual { + _burn(_msgSender(), amount); } - function safeCastTo32(uint256 x) internal pure returns (uint32 y) { - require(x < 1 << 32); - - y = uint32(x); + /** + * @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 { + _spendAllowance(account, _msgSender(), amount); + _burn(account, amount); } +} - function safeCastTo24(uint256 x) internal pure returns (uint24 y) { - require(x < 1 << 24); +// https://docs.synthetix.io/contracts/Owned +// NO NEED TO AUDIT +contract Owned { + address public owner; + address public nominatedOwner; - y = uint24(x); + constructor (address _owner) { + require(_owner != address(0), "Owner address cannot be 0"); + owner = _owner; + emit OwnerChanged(address(0), _owner); } - function safeCastTo16(uint256 x) internal pure returns (uint16 y) { - require(x < 1 << 16); - - y = uint16(x); + function nominateNewOwner(address _owner) external onlyOwner { + nominatedOwner = _owner; + emit OwnerNominated(_owner); } - function safeCastTo8(uint256 x) internal pure returns (uint8 y) { - require(x < 1 << 8); - - y = uint8(x); + function acceptOwnership() external { + require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); + emit OwnerChanged(owner, nominatedOwner); + owner = nominatedOwner; + nominatedOwner = address(0); } -} -// Rewards logic inspired by xERC20 (https://github.com/ZeframLou/playpen/blob/main/src/xERC20.sol) - -/** - @title An xERC4626 Single Staking Contract Interface - @notice This contract allows users to autocompound rewards denominated in an underlying reward token. - It is fully compatible with [ERC4626](https://eips.ethereum.org/EIPS/eip-4626) allowing for DeFi composability. - It maintains balances using internal accounting to prevent instantaneous changes in the exchange rate. - NOTE: an exception is at contract creation, when a reward cycle begins before the first deposit. After the first deposit, exchange rate updates smoothly. - - Operates on "cycles" which distribute the rewards surplus over the internal balance to users linearly over the remainder of the cycle window. -*/ -interface IxERC4626 { - /*//////////////////////////////////////////////////////// - Custom Errors - ////////////////////////////////////////////////////////*/ - - /// @dev thrown when syncing before cycle ends. - error SyncError(); - - /*//////////////////////////////////////////////////////// - Events - ////////////////////////////////////////////////////////*/ - - /// @dev emit every time a new rewards cycle starts - event NewRewardsCycle(uint32 indexed cycleEnd, uint256 rewardAmount); - - /*//////////////////////////////////////////////////////// - View Methods - ////////////////////////////////////////////////////////*/ + modifier onlyOwner { + require(msg.sender == owner, "Only the contract owner may perform this action"); + _; + } - /// @notice the maximum length of a rewards cycle - function rewardsCycleLength() external view returns (uint32); + event OwnerNominated(address newOwner); + event OwnerChanged(address oldOwner, address newOwner); +} - /// @notice the effective start of the current cycle - /// NOTE: This will likely be after `rewardsCycleEnd - rewardsCycleLength` as this is set as block.timestamp of the last `syncRewards` call. - function lastSync() external view returns (uint32); +/// @title Parent contract for frxETH.sol +/** @notice Combines Openzeppelin's ERC20Permit and ERC20Burnable with Synthetix's Owned. + Also includes a list of authorized minters */ +/// @dev frxETH adheres to EIP-712/EIP-2612 and can use permits +contract ERC20PermitPermissionedMint is ERC20Permit, ERC20Burnable, Owned { + // Core + address public timelock_address; - /// @notice the end of the current cycle. Will always be evenly divisible by `rewardsCycleLength`. - function rewardsCycleEnd() external view returns (uint32); + // Minters + address[] public minters_array; // Allowed to mint + mapping(address => bool) public minters; // Mapping is also used for faster verification - /// @notice the amount of rewards distributed in a the most recent cycle - function lastRewardAmount() external view returns (uint192); + /* ========== CONSTRUCTOR ========== */ - /*//////////////////////////////////////////////////////// - State Changing Methods - ////////////////////////////////////////////////////////*/ + constructor( + address _creator_address, + address _timelock_address, + string memory _name, + string memory _symbol + ) + ERC20(_name, _symbol) + ERC20Permit(_name) + Owned(_creator_address) + { + timelock_address = _timelock_address; + } - /// @notice Distributes rewards to xERC4626 holders. - /// All surplus `asset` balance of the contract over the internal balance becomes queued for the next cycle. - function syncRewards() external; -} + /* ========== MODIFIERS ========== */ -/** - @title An xERC4626 Single Staking Contract - @notice This contract allows users to autocompound rewards denominated in an underlying reward token. - It is fully compatible with [ERC4626](https://eips.ethereum.org/EIPS/eip-4626) allowing for DeFi composability. - It maintains balances using internal accounting to prevent instantaneous changes in the exchange rate. - NOTE: an exception is at contract creation, when a reward cycle begins before the first deposit. After the first deposit, exchange rate updates smoothly. + modifier onlyByOwnGov() { + require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); + _; + } - Operates on "cycles" which distribute the rewards surplus over the internal balance to users linearly over the remainder of the cycle window. -*/ -abstract contract xERC4626 is IxERC4626, ERC4626 { - using SafeCastLib for *; + modifier onlyMinters() { + require(minters[msg.sender] == true, "Only minters"); + _; + } - /// @notice the maximum length of a rewards cycle - uint32 public immutable rewardsCycleLength; + /* ========== RESTRICTED FUNCTIONS ========== */ - /// @notice the effective start of the current cycle - uint32 public lastSync; + // Used by minters when user redeems + function minter_burn_from(address b_address, uint256 b_amount) public onlyMinters { + super.burnFrom(b_address, b_amount); + emit TokenMinterBurned(b_address, msg.sender, b_amount); + } - /// @notice the end of the current cycle. Will always be evenly divisible by `rewardsCycleLength`. - uint32 public rewardsCycleEnd; + // This function is what other minters will call to mint new tokens + function minter_mint(address m_address, uint256 m_amount) public onlyMinters { + super._mint(m_address, m_amount); + emit TokenMinterMinted(msg.sender, m_address, m_amount); + } - /// @notice the amount of rewards distributed in a the most recent cycle. - uint192 public lastRewardAmount; + // Adds whitelisted minters + function addMinter(address minter_address) public onlyByOwnGov { + require(minter_address != address(0), "Zero address detected"); - uint256 internal storedTotalAssets; + require(minters[minter_address] == false, "Address already exists"); + minters[minter_address] = true; + minters_array.push(minter_address); - constructor(uint32 _rewardsCycleLength) { - rewardsCycleLength = _rewardsCycleLength; - // seed initial rewardsCycleEnd - rewardsCycleEnd = (block.timestamp.safeCastTo32() / rewardsCycleLength) * rewardsCycleLength; + emit MinterAdded(minter_address); } - /// @notice Compute the amount of tokens available to share holders. - /// Increases linearly during a reward distribution period from the sync call, not the cycle start. - function totalAssets() public view override returns (uint256) { - // cache global vars - uint256 storedTotalAssets_ = storedTotalAssets; - uint192 lastRewardAmount_ = lastRewardAmount; - uint32 rewardsCycleEnd_ = rewardsCycleEnd; - uint32 lastSync_ = lastSync; + // Remove a minter + function removeMinter(address minter_address) public onlyByOwnGov { + require(minter_address != address(0), "Zero address detected"); + require(minters[minter_address] == true, "Address nonexistant"); + + // Delete from the mapping + delete minters[minter_address]; - if (block.timestamp >= rewardsCycleEnd_) { - // no rewards or rewards fully unlocked - // entire reward amount is available - return storedTotalAssets_ + lastRewardAmount_; + // 'Delete' from the array by setting the address to 0x0 + for (uint i = 0; i < minters_array.length; i++){ + if (minters_array[i] == minter_address) { + minters_array[i] = address(0); // This will leave a null in the array and keep the indices the same + break; + } } - // rewards not fully unlocked - // add unlocked rewards to stored total - uint256 unlockedRewards = (lastRewardAmount_ * (block.timestamp - lastSync_)) / (rewardsCycleEnd_ - lastSync_); - return storedTotalAssets_ + unlockedRewards; - } - - // Update storedTotalAssets on withdraw/redeem - function beforeWithdraw(uint256 amount, uint256 shares) internal virtual override { - super.beforeWithdraw(amount, shares); - storedTotalAssets -= amount; + emit MinterRemoved(minter_address); } - // Update storedTotalAssets on deposit/mint - function afterDeposit(uint256 amount, uint256 shares) internal virtual override { - storedTotalAssets += amount; - super.afterDeposit(amount, shares); + function setTimelock(address _timelock_address) public onlyByOwnGov { + require(_timelock_address != address(0), "Zero address detected"); + timelock_address = _timelock_address; + emit TimelockChanged(_timelock_address); } - /// @notice Distributes rewards to xERC4626 holders. - /// All surplus `asset` balance of the contract over the internal balance becomes queued for the next cycle. - function syncRewards() public virtual { - uint192 lastRewardAmount_ = lastRewardAmount; - uint32 timestamp = block.timestamp.safeCastTo32(); - - if (timestamp < rewardsCycleEnd) revert SyncError(); - - uint256 storedTotalAssets_ = storedTotalAssets; - uint256 nextRewards = asset.balanceOf(address(this)) - storedTotalAssets_ - lastRewardAmount_; - - storedTotalAssets = storedTotalAssets_ + lastRewardAmount_; // SSTORE + /* ========== EVENTS ========== */ + + event TokenMinterBurned(address indexed from, address indexed to, uint256 amount); + event TokenMinterMinted(address indexed from, address indexed to, uint256 amount); + event MinterAdded(address minter_address); + event MinterRemoved(address minter_address); + event TimelockChanged(address timelock_address); +} - uint32 end = ((timestamp + rewardsCycleLength) / rewardsCycleLength) * rewardsCycleLength; +contract frxETH is ERC20PermitPermissionedMint { - if (end - timestamp < rewardsCycleLength / 20) { - end += rewardsCycleLength; - } + /* ========== CONSTRUCTOR ========== */ + constructor( + address _creator_address, + address _timelock_address + ) + ERC20PermitPermissionedMint(_creator_address, _timelock_address, "Frax Ether", "frxETH") + {} - // Combined single SSTORE - lastRewardAmount = nextRewards.safeCastTo192(); - lastSync = timestamp; - rewardsCycleEnd = end; +} - emit NewRewardsCycle(end, nextRewards); - } +// Primarily added to prevent ERC20 name collisions in frxETHMinter.sol +interface IsfrxETH { + function DOMAIN_SEPARATOR() external view returns (bytes32); + function allowance(address, address) external view returns (uint256); + function approve(address spender, uint256 amount) external returns (bool); + function asset() external view returns (address); + function balanceOf(address) external view returns (uint256); + function convertToAssets(uint256 shares) external view returns (uint256); + function convertToShares(uint256 assets) external view returns (uint256); + function decimals() external view returns (uint8); + function deposit(uint256 assets, address receiver) external returns (uint256 shares); + function depositWithSignature(uint256 assets, address receiver, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint256 shares); + function lastRewardAmount() external view returns (uint192); + function lastSync() external view returns (uint32); + function maxDeposit(address) external view returns (uint256); + function maxMint(address) external view returns (uint256); + function maxRedeem(address owner) external view returns (uint256); + function maxWithdraw(address owner) external view returns (uint256); + function mint(uint256 shares, address receiver) external returns (uint256 assets); + function name() external view returns (string memory); + function nonces(address) external view returns (uint256); + function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; + function previewDeposit(uint256 assets) external view returns (uint256); + function previewMint(uint256 shares) external view returns (uint256); + function previewRedeem(uint256 shares) external view returns (uint256); + function previewWithdraw(uint256 assets) external view returns (uint256); + function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets); + function rewardsCycleEnd() external view returns (uint32); + function rewardsCycleLength() external view returns (uint32); + function symbol() external view returns (string memory); + function syncRewards() external; + function totalAssets() external view returns (uint256); + function totalSupply() external view returns (uint256); + function transfer(address to, uint256 amount) external returns (bool); + function transferFrom(address from, address to, uint256 amount) external returns (bool); + function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares); } // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) @@ -1061,76 +1743,579 @@ abstract contract ReentrancyGuard { } } -/// @title Vault token for staked frxETH -/// @notice Is a vault that takes frxETH and gives you sfrxETH erc20 tokens -/** @dev Exchange rate between frxETH and sfrxETH floats, you can convert your sfrxETH for more frxETH over time. - Exchange rate increases as the frax msig mints new frxETH corresponding to the staking yield and drops it into the vault (sfrxETH contract). - There is a short time period, “cycles” which the exchange rate increases linearly over. This is to prevent gaming the exchange rate (MEV). - The cycles are constant length, but calling syncRewards slightly into a would-be cycle keeps the same would-be endpoint (so cycle ends are every X seconds). - Someone must call syncRewards, which queues any new frxETH in the contract to be added to the redeemable amount. - sfrxETH adheres to ERC-4626 vault specs - Mint vs Deposit - mint() - deposit targeting a specific number of sfrxETH out - deposit() - deposit knowing a specific number of frxETH in */ -contract sfrxETH is xERC4626, ReentrancyGuard { - - modifier andSync { - if (block.timestamp >= rewardsCycleEnd) { syncRewards(); } +// ┏━━━┓━┏┓━┏┓━━┏━━━┓━━┏━━━┓━━━━┏━━━┓━━━━━━━━━━━━━━━━━━━┏┓━━━━━┏━━━┓━━━━━━━━━┏┓━━━━━━━━━━━━━━┏┓━ +// ┃┏━━┛┏┛┗┓┃┃━━┃┏━┓┃━━┃┏━┓┃━━━━┗┓┏┓┃━━━━━━━━━━━━━━━━━━┏┛┗┓━━━━┃┏━┓┃━━━━━━━━┏┛┗┓━━━━━━━━━━━━┏┛┗┓ +// ┃┗━━┓┗┓┏┛┃┗━┓┗┛┏┛┃━━┃┃━┃┃━━━━━┃┃┃┃┏━━┓┏━━┓┏━━┓┏━━┓┏┓┗┓┏┛━━━━┃┃━┗┛┏━━┓┏━┓━┗┓┏┛┏━┓┏━━┓━┏━━┓┗┓┏┛ +// ┃┏━━┛━┃┃━┃┏┓┃┏━┛┏┛━━┃┃━┃┃━━━━━┃┃┃┃┃┏┓┃┃┏┓┃┃┏┓┃┃━━┫┣┫━┃┃━━━━━┃┃━┏┓┃┏┓┃┃┏┓┓━┃┃━┃┏┛┗━┓┃━┃┏━┛━┃┃━ +// ┃┗━━┓━┃┗┓┃┃┃┃┃┃┗━┓┏┓┃┗━┛┃━━━━┏┛┗┛┃┃┃━┫┃┗┛┃┃┗┛┃┣━━┃┃┃━┃┗┓━━━━┃┗━┛┃┃┗┛┃┃┃┃┃━┃┗┓┃┃━┃┗┛┗┓┃┗━┓━┃┗┓ +// ┗━━━┛━┗━┛┗┛┗┛┗━━━┛┗┛┗━━━┛━━━━┗━━━┛┗━━┛┃┏━┛┗━━┛┗━━┛┗┛━┗━┛━━━━┗━━━┛┗━━┛┗┛┗┛━┗━┛┗┛━┗━━━┛┗━━┛━┗━┛ +// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┃┃━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┗┛━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +// SPDX-License-Identifier: CC0-1.0 + +// This interface is designed to be compatible with the Vyper version. +/// @notice This is the Ethereum 2.0 deposit contract interface. +/// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs +interface IDepositContract { + /// @notice A processed deposit event. + event DepositEvent( + bytes pubkey, + bytes withdrawal_credentials, + bytes amount, + bytes signature, + bytes index + ); + + /// @notice Submit a Phase 0 DepositData object. + /// @param pubkey A BLS12-381 public key. + /// @param withdrawal_credentials Commitment to a public key for withdrawals. + /// @param signature A BLS12-381 signature. + /// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object. + /// Used as a protection against malformed input. + function deposit( + bytes calldata pubkey, + bytes calldata withdrawal_credentials, + bytes calldata signature, + bytes32 deposit_data_root + ) external payable; + + /// @notice Query the current deposit root hash. + /// @return The deposit root hash. + function get_deposit_root() external view returns (bytes32); + + /// @notice Query the current deposit count. + /// @return The deposit count encoded as a little endian 64-bit number. + function get_deposit_count() external view returns (bytes memory); +} + +// Based on official specification in https://eips.ethereum.org/EIPS/eip-165 +interface ERC165 { + /// @notice Query if a contract implements an interface + /// @param interfaceId The interface identifier, as specified in ERC-165 + /// @dev Interface identification is specified in ERC-165. This function + /// uses less than 30,000 gas. + /// @return `true` if the contract implements `interfaceId` and + /// `interfaceId` is not 0xffffffff, `false` otherwise + function supportsInterface(bytes4 interfaceId) external pure returns (bool); +} + +// This is a rewrite of the Vyper Eth2.0 deposit contract in Solidity. +// It tries to stay as close as possible to the original source code. +/// @notice This is the Ethereum 2.0 deposit contract interface. +/// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs +contract DepositContract is IDepositContract, ERC165 { + uint constant DEPOSIT_CONTRACT_TREE_DEPTH = 32; + // NOTE: this also ensures `deposit_count` will fit into 64-bits + uint constant MAX_DEPOSIT_COUNT = 2**DEPOSIT_CONTRACT_TREE_DEPTH - 1; + + bytes32[DEPOSIT_CONTRACT_TREE_DEPTH] branch; + uint256 deposit_count; + + bytes32[DEPOSIT_CONTRACT_TREE_DEPTH] zero_hashes; + + constructor() public { + // Compute hashes in empty sparse Merkle tree + for (uint height = 0; height < DEPOSIT_CONTRACT_TREE_DEPTH - 1; height++) + zero_hashes[height + 1] = sha256(abi.encodePacked(zero_hashes[height], zero_hashes[height])); + } + + function get_deposit_root() override external view returns (bytes32) { + bytes32 node; + uint size = deposit_count; + for (uint height = 0; height < DEPOSIT_CONTRACT_TREE_DEPTH; height++) { + if ((size & 1) == 1) + node = sha256(abi.encodePacked(branch[height], node)); + else + node = sha256(abi.encodePacked(node, zero_hashes[height])); + size /= 2; + } + return sha256(abi.encodePacked( + node, + to_little_endian_64(uint64(deposit_count)), + bytes24(0) + )); + } + + function get_deposit_count() override external view returns (bytes memory) { + return to_little_endian_64(uint64(deposit_count)); + } + + function deposit( + bytes calldata pubkey, + bytes calldata withdrawal_credentials, + bytes calldata signature, + bytes32 deposit_data_root + ) override external payable { + // Extended ABI length checks since dynamic types are used. + require(pubkey.length == 48, "DepositContract: invalid pubkey length"); + require(withdrawal_credentials.length == 32, "DepositContract: invalid withdrawal_credentials length"); + require(signature.length == 96, "DepositContract: invalid signature length"); + + // Check deposit amount + require(msg.value >= 1 ether, "DepositContract: deposit value too low"); + require(msg.value % 1 gwei == 0, "DepositContract: deposit value not multiple of gwei"); + uint deposit_amount = msg.value / 1 gwei; + require(deposit_amount <= type(uint64).max, "DepositContract: deposit value too high"); + + // Emit `DepositEvent` log + bytes memory amount = to_little_endian_64(uint64(deposit_amount)); + emit DepositEvent( + pubkey, + withdrawal_credentials, + amount, + signature, + to_little_endian_64(uint64(deposit_count)) + ); + + // Compute deposit data root (`DepositData` hash tree root) + bytes32 pubkey_root = sha256(abi.encodePacked(pubkey, bytes16(0))); + bytes32 signature_root = sha256(abi.encodePacked( + sha256(abi.encodePacked(signature[:64])), + sha256(abi.encodePacked(signature[64:], bytes32(0))) + )); + bytes32 node = sha256(abi.encodePacked( + sha256(abi.encodePacked(pubkey_root, withdrawal_credentials)), + sha256(abi.encodePacked(amount, bytes24(0), signature_root)) + )); + + // Verify computed and expected deposit data roots match + require(node == deposit_data_root, "DepositContract: reconstructed DepositData does not match supplied deposit_data_root"); + + // Avoid overflowing the Merkle tree (and prevent edge case in computing `branch`) + require(deposit_count < MAX_DEPOSIT_COUNT, "DepositContract: merkle tree full"); + + // Add deposit data root to Merkle tree (update a single `branch` node) + deposit_count += 1; + uint size = deposit_count; + for (uint height = 0; height < DEPOSIT_CONTRACT_TREE_DEPTH; height++) { + if ((size & 1) == 1) { + branch[height] = node; + return; + } + node = sha256(abi.encodePacked(branch[height], node)); + size /= 2; + } + // As the loop should always end prematurely with the `return` statement, + // this code should be unreachable. We assert `false` just to be safe. + assert(false); + } + + function supportsInterface(bytes4 interfaceId) override external pure returns (bool) { + return interfaceId == type(ERC165).interfaceId || interfaceId == type(IDepositContract).interfaceId; + } + + function to_little_endian_64(uint64 value) internal pure returns (bytes memory ret) { + ret = new bytes(8); + bytes8 bytesValue = bytes8(value); + // Byteswapping during copying to bytes. + ret[0] = bytesValue[7]; + ret[1] = bytesValue[6]; + ret[2] = bytesValue[5]; + ret[3] = bytesValue[4]; + ret[4] = bytesValue[3]; + ret[5] = bytesValue[2]; + ret[6] = bytesValue[1]; + ret[7] = bytesValue[0]; + } +} + +// ==================================================================== +// | ______ _______ | +// | / _____________ __ __ / ____(_____ ____ _____ ________ | +// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | +// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | +// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | +// | | +// ==================================================================== +// ========================= OperatorRegistry ========================= +// ==================================================================== +// Frax Finance: https://github.com/FraxFinance + +// Primary Author(s) +// Jack Corddry: https://github.com/corddry +// Justin Moore: https://github.com/0xJM + +// Reviewer(s) / Contributor(s) +// Travis Moore: https://github.com/FortisFortuna +// Dennis: https://github.com/denett + +/// @title Keeps track of validators used for ETH 2.0 staking +/// @notice A permissioned owner can add and removed them at will +contract OperatorRegistry is Owned { + + struct Validator { + bytes pubKey; + bytes signature; + bytes32 depositDataRoot; + } + + Validator[] validators; // Array of unused / undeposited validators that can be used at a future time + bytes curr_withdrawal_pubkey; // Pubkey for ETH 2.0 withdrawal creds. If you change it, you must empty the validators array + address public timelock_address; + + constructor(address _owner, address _timelock_address, bytes memory _withdrawal_pubkey) Owned(_owner) { + timelock_address = _timelock_address; + curr_withdrawal_pubkey = _withdrawal_pubkey; + } + + modifier onlyByOwnGov() { + require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } - /* ========== CONSTRUCTOR ========== */ - constructor(ERC20 _underlying, uint32 _rewardsCycleLength) - ERC4626(_underlying, "Staked Frax Ether", "sfrxETH") - xERC4626(_rewardsCycleLength) - {} + /// @notice Add a new validator + /** @dev You should verify offchain that the validator is indeed valid before adding it + Reason we don't do that here is for gas */ + function addValidator(Validator calldata validator) public onlyByOwnGov { + validators.push(validator); + emit ValidatorAdded(validator.pubKey, curr_withdrawal_pubkey); + } - /// @notice inlines syncRewards with deposits when able - function deposit(uint256 assets, address receiver) public override andSync returns (uint256 shares) { - return super.deposit(assets, receiver); + /// @notice Add multiple new validators in one function call + /** @dev You should verify offchain that the validators are indeed valid before adding them + Reason we don't do that here is for gas */ + function addValidators(Validator[] calldata validatorArray) external onlyByOwnGov { + uint arrayLength = validatorArray.length; + for (uint256 i = 0; i < arrayLength; ++i) { + addValidator(validatorArray[i]); + } } - - /// @notice inlines syncRewards with mints when able - function mint(uint256 shares, address receiver) public override andSync returns (uint256 assets) { - return super.mint(shares, receiver); + + /// @notice Swap the location of one validator with another + function swapValidator(uint256 from_idx, uint256 to_idx) public onlyByOwnGov { + // Get the original values + Validator memory fromVal = validators[from_idx]; + Validator memory toVal = validators[to_idx]; + + // Set the swapped values + validators[to_idx] = fromVal; + validators[from_idx] = toVal; + + emit ValidatorsSwapped(fromVal.pubKey, toVal.pubKey, from_idx, to_idx); } - /// @notice inlines syncRewards with withdrawals when able - function withdraw( - uint256 assets, - address receiver, - address owner - ) public override andSync returns (uint256 shares) { - return super.withdraw(assets, receiver, owner); + /// @notice Remove validators from the end of the validators array, in case they were added in error + function popValidators(uint256 times) public onlyByOwnGov { + // Loop through and remove validator entries at the end + for (uint256 i = 0; i < times; ++i) { + validators.pop(); + } + + emit ValidatorsPopped(times); } - /// @notice inlines syncRewards with redemptions when able - function redeem( - uint256 shares, - address receiver, - address owner - ) public override andSync returns (uint256 assets) { - return super.redeem(shares, receiver, owner); + /** @notice Remove a validator from the array. If dont_care_about_ordering is true, + a swap and pop will occur instead of a more gassy loop */ + function removeValidator(uint256 remove_idx, bool dont_care_about_ordering) public onlyByOwnGov { + // Get the pubkey for the validator to remove (for informational purposes) + bytes memory removed_pubkey = validators[remove_idx].pubKey; + + // Less gassy to swap and pop + if (dont_care_about_ordering){ + // Swap the (validator to remove) with the (last validator in the array) + swapValidator(remove_idx, validators.length - 1); + + // Pop off the validator to remove, which is now at the end of the array + validators.pop(); + } + // More gassy, loop + else { + // Save the original validators + Validator[] memory original_validators = validators; + + // Clear the original validators list + delete validators; + + // Fill the new validators array with all except the value to remove + for (uint256 i = 0; i < original_validators.length; ++i) { + if (i != remove_idx) { + validators.push(original_validators[i]); + } + } + } + + emit ValidatorRemoved(removed_pubkey, remove_idx, dont_care_about_ordering); + } + + // Internal + /// @dev Remove the last validator from the validators array and return its information + function getNextValidator() + internal + returns ( + bytes memory pubKey, + bytes memory withdrawalCredentials, + bytes memory signature, + bytes32 depositDataRoot + ) + { + // Make sure there are free validators available + uint numVals = numValidators(); + require(numVals != 0, "Validator stack is empty"); + + // Pop the last validator off the array + Validator memory popped = validators[numVals - 1]; + validators.pop(); + + // Return the validator's information + pubKey = popped.pubKey; + withdrawalCredentials = curr_withdrawal_pubkey; + signature = popped.signature; + depositDataRoot = popped.depositDataRoot; + } + + /// @notice Return the information of the i'th validator in the registry + function getValidator(uint i) + view + external + returns ( + bytes memory pubKey, + bytes memory withdrawalCredentials, + bytes memory signature, + bytes32 depositDataRoot + ) + { + Validator memory v = validators[i]; + + // Return the validator's information + pubKey = v.pubKey; + withdrawalCredentials = curr_withdrawal_pubkey; + signature = v.signature; + depositDataRoot = v.depositDataRoot; + } + + /// @notice Returns a Validator struct of the given inputs to make formatting addValidator inputs easier + function getValidatorStruct( + bytes memory pubKey, + bytes memory signature, + bytes32 depositDataRoot + ) external pure returns (Validator memory) { + return Validator(pubKey, signature, depositDataRoot); + } + + /// @notice Requires empty validator stack as changing withdrawal creds invalidates signature + /// @dev May need to call clearValidatorArray() first + function setWithdrawalCredential(bytes memory _new_withdrawal_pubkey) external onlyByOwnGov { + require(numValidators() == 0, "Clear validator array first"); + curr_withdrawal_pubkey = _new_withdrawal_pubkey; + + emit WithdrawalCredentialSet(_new_withdrawal_pubkey); + } + + /// @notice Empties the validator array + /// @dev Need to do this before setWithdrawalCredential() + function clearValidatorArray() external onlyByOwnGov { + delete validators; + + emit ValidatorArrayCleared(); + } + + /// @notice Returns the number of validators + function numValidators() public view returns (uint256) { + return validators.length; + } + + /// @notice Set the timelock contract + function setTimelock(address _timelock_address) external onlyByOwnGov { + require(_timelock_address != address(0), "Zero address detected"); + timelock_address = _timelock_address; + emit TimelockChanged(_timelock_address); + } + + event TimelockChanged(address timelock_address); + event WithdrawalCredentialSet(bytes _withdrawalCredential); + event ValidatorAdded(bytes pubKey, bytes withdrawalCredential); + event ValidatorArrayCleared(); + event ValidatorRemoved(bytes pubKey, uint256 remove_idx, bool dont_care_about_ordering); + event ValidatorsPopped(uint256 times); + event ValidatorsSwapped(bytes from_pubKey, bytes to_pubKey, uint256 from_idx, uint256 to_idx); + event KeysCleared(); +} + +/// @title Authorized minter contract for frxETH +/// @notice Accepts user-supplied ETH and converts it to frxETH (submit()), and also optionally inline stakes it for sfrxETH (submitAndDeposit()) +/** @dev Has permission to mint frxETH. + Once +32 ETH has accumulated, adds it to a validator, which then deposits it for ETH 2.0 staking (depositEther()) + Withhold ratio refers to what percentage of ETH this contract keeps whenever a user makes a deposit. 0% is kept initially */ +contract frxETHMinter is OperatorRegistry, ReentrancyGuard { + uint256 public constant DEPOSIT_SIZE = 32 ether; // ETH 2.0 minimum deposit size + uint256 public constant RATIO_PRECISION = 1e6; // 1,000,000 + + uint256 public withholdRatio; // What we keep and don't deposit whenever someone submit()'s ETH + uint256 public currentWithheldETH; // Needed for internal tracking + mapping(bytes => bool) public activeValidators; // Tracks validators (via their pubkeys) that already have 32 ETH in them + + IDepositContract public immutable depositContract; // ETH 2.0 deposit contract + frxETH public immutable frxETHToken; + IsfrxETH public immutable sfrxETHToken; + + bool public submitPaused; + bool public depositEtherPaused; + + constructor( + address depositContractAddress, + address frxETHAddress, + address sfrxETHAddress, + address _owner, + address _timelock_address, + bytes memory _withdrawalCredential + ) OperatorRegistry(_owner, _timelock_address, _withdrawalCredential) { + depositContract = IDepositContract(depositContractAddress); + frxETHToken = frxETH(frxETHAddress); + sfrxETHToken = IsfrxETH(sfrxETHAddress); + withholdRatio = 0; // No ETH is withheld initially + currentWithheldETH = 0; + } + + /// @notice Mint frxETH and deposit it to receive sfrxETH in one transaction + /** @dev Could try using EIP-712 / EIP-2612 here in the future if you replace this contract, + but you might run into msg.sender vs tx.origin issues with the ERC4626 */ + function submitAndDeposit(address recipient) external payable returns (uint256 shares) { + // Give the frxETH to this contract after it is generated + _submit(address(this)); + + // Approve frxETH to sfrxETH for staking + frxETHToken.approve(address(sfrxETHToken), msg.value); + + // Deposit the frxETH and give the generated sfrxETH to the final recipient + uint256 sfrxeth_recieved = sfrxETHToken.deposit(msg.value, recipient); + require(sfrxeth_recieved > 0, 'No sfrxETH was returned'); + + return sfrxeth_recieved; + } + + /// @notice Mint frxETH to the recipient using sender's funds. Internal portion + function _submit(address recipient) internal nonReentrant { + // Initial pause and value checks + require(!submitPaused, "Submit is paused"); + require(msg.value != 0, "Cannot submit 0"); + + // Give the sender frxETH + frxETHToken.minter_mint(recipient, msg.value); + + // Track the amount of ETH that we are keeping + uint256 withheld_amt = 0; + if (withholdRatio != 0) { + withheld_amt = (msg.value * withholdRatio) / RATIO_PRECISION; + currentWithheldETH += withheld_amt; + } + + emit ETHSubmitted(msg.sender, recipient, msg.value, withheld_amt); } - /// @notice How much frxETH is 1E18 sfrxETH worth. Price is in ETH, not USD - function pricePerShare() public view returns (uint256) { - return convertToAssets(1e18); + /// @notice Mint frxETH to the sender depending on the ETH value sent + function submit() external payable { + _submit(msg.sender); } - /// @notice Approve and deposit() in one transaction - function depositWithSignature( - uint256 assets, - address receiver, - uint256 deadline, - bool approveMax, - uint8 v, - bytes32 r, - bytes32 s - ) external nonReentrant returns (uint256 shares) { - uint256 amount = approveMax ? type(uint256).max : assets; - asset.permit(msg.sender, address(this), amount, deadline, v, r, s); - return (deposit(assets, receiver)); + /// @notice Mint frxETH to the recipient using sender's funds + function submitAndGive(address recipient) external payable { + _submit(recipient); + } + + /// @notice Fallback to minting frxETH to the sender + receive() external payable { + _submit(msg.sender); + } + + /// @notice Deposit batches of ETH to the ETH 2.0 deposit contract + /// @dev Usually a bot will call this periodically + /// @param max_deposits Used to prevent gassing out if a whale drops in a huge amount of ETH. Break it down into batches. + function depositEther(uint256 max_deposits) external nonReentrant { + // Initial pause check + require(!depositEtherPaused, "Depositing ETH is paused"); + + // See how many deposits can be made. Truncation desired. + uint256 numDeposits = (address(this).balance - currentWithheldETH) / DEPOSIT_SIZE; + require(numDeposits > 0, "Not enough ETH in contract"); + + uint256 loopsToUse = numDeposits; + if (max_deposits == 0) loopsToUse = numDeposits; + else if (numDeposits > max_deposits) loopsToUse = max_deposits; + + // Give each deposit chunk to an empty validator + for (uint256 i = 0; i < loopsToUse; ++i) { + // Get validator information + ( + bytes memory pubKey, + bytes memory withdrawalCredential, + bytes memory signature, + bytes32 depositDataRoot + ) = getNextValidator(); // Will revert if there are not enough free validators + + // Make sure the validator hasn't been deposited into already, to prevent stranding an extra 32 eth + // until withdrawals are allowed + require(!activeValidators[pubKey], "Validator already has 32 ETH"); + + // Deposit the ether in the ETH 2.0 deposit contract + depositContract.deposit{value: DEPOSIT_SIZE}( + pubKey, + withdrawalCredential, + signature, + depositDataRoot + ); + + // Set the validator as used so it won't get an extra 32 ETH + activeValidators[pubKey] = true; + + emit DepositSent(pubKey, withdrawalCredential); + } + } + + /// @param newRatio of ETH that is sent to deposit contract vs withheld, 1e6 precision + /// @notice An input of 1e6 results in 100% of Eth deposited, 0% withheld + function setWithholdRatio(uint256 newRatio) external onlyByOwnGov { + require (newRatio <= RATIO_PRECISION, "Ratio cannot surpass 100%"); + withholdRatio = newRatio; + emit WithholdRatioSet(newRatio); + } + + /// @notice Give the withheld ETH to the "to" address + function moveWithheldETH(address payable to, uint256 amount) external onlyByOwnGov { + require(amount <= currentWithheldETH, "Not enough withheld ETH in contract"); + currentWithheldETH -= amount; + + (bool success,) = payable(to).call{ value: amount }(""); + require(success, "Invalid transfer"); + + emit WithheldETHMoved(to, amount); + } + + /// @notice Toggle allowing submites + function togglePauseSubmits() external onlyByOwnGov { + submitPaused = !submitPaused; + + emit SubmitPaused(submitPaused); + } + + /// @notice Toggle allowing depositing ETH to validators + function togglePauseDepositEther() external onlyByOwnGov { + depositEtherPaused = !depositEtherPaused; + + emit DepositEtherPaused(depositEtherPaused); + } + + /// @notice For emergencies if something gets stuck + function recoverEther(uint256 amount) external onlyByOwnGov { + (bool success,) = address(owner).call{ value: amount }(""); + require(success, "Invalid transfer"); + + emit EmergencyEtherRecovered(amount); + } + + /// @notice For emergencies if someone accidentally sent some ERC20 tokens here + function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { + require(IERC20(tokenAddress).transfer(owner, tokenAmount), "recoverERC20: Transfer failed"); + + emit EmergencyERC20Recovered(tokenAddress, tokenAmount); } + event EmergencyEtherRecovered(uint256 amount); + event EmergencyERC20Recovered(address tokenAddress, uint256 tokenAmount); + event ETHSubmitted(address indexed sender, address indexed recipient, uint256 sent_amount, uint256 withheld_amt); + event DepositEtherPaused(bool new_status); + event DepositSent(bytes indexed pubKey, bytes withdrawalCredential); + event SubmitPaused(bool new_status); + event WithheldETHMoved(address indexed to, uint256 amount); + event WithholdRatioSet(uint256 newRatio); } diff --git a/script/DepositDataToCalldata.s.sol b/script/DepositDataToCalldata.s.sol index ffa4818..e68c94c 100644 --- a/script/DepositDataToCalldata.s.sol +++ b/script/DepositDataToCalldata.s.sol @@ -14,37 +14,49 @@ pragma solidity ^0.8.0; Usage: 1. Specify the path to your deposit_data.json in your .env as DEPOSIT_DATA_PATH 2. $ source .env - 3. $ forge script script/DepositDataToCalldata.s.sol + 3. $ forge script --no-auto-detect script/DepositDataToCalldata.s.sol --sig "run(uint256 startIdx, uint256 count)" 0 50 4. Use the final log output as data in a transaction to the frxETHMinter + 5. Test with "cd node-scripts" then "tsx validate-msig-add-validators.ts" /////////////////////////////////////////////////////////////////////////////////////////*/ import { stdJson } from "forge-std/StdJson.sol"; import { Script } from "forge-std/Script.sol"; import { Test } from "forge-std/Test.sol"; +import { console } from "forge-std/console.sol"; import { frxETHMinter, OperatorRegistry } from "../src/frxETHMinter.sol"; -contract jsonToMinter is Script, Test { + +contract DepositDataToCalldata is Script, Test { using stdJson for string; OperatorRegistry.Validator[] public validators; - + function run() public { + this.run(0, 100000); + } + + function run(uint256 startIdx, uint256 count) public { + console.log("startIdx: ", startIdx); + console.log("count: ", count); string memory target = vm.envString("DEPOSIT_DATA_PATH"); string memory json = vm.readFile(target); - for(uint i = 0; ; i++) { + for(uint i = startIdx; i < (startIdx + count); i++) { // Build Json query string using i to access ith validator - string memory baseQuery = string.concat("$[", vm.toString(i)); + + // EXAMPLE QUERY SYNTAX https://crates.io/crates/jsonpath-rust + // DO NOT ADD $. HERE!!! IT will do it automatically + string memory baseQuery = string.concat("[", vm.toString(i)); // First query to see if there's Json at i at all string memory rawQuery = string.concat(baseQuery, "]"); + console.log("rawQuery: ", rawQuery); bytes memory raw = json.parseRaw(rawQuery); // Ends if the Json has ran out if (raw.length == 0) { break; } - // Finish building queries for necessary deposit parameters string memory pkQuery = string.concat(baseQuery, "].pubkey"); string memory sigQuery = string.concat(baseQuery, "].signature");