// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @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);

    /**
     * @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);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

// File: @openzeppelin/contracts/utils/math/Math.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @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 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) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 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)
            }

            // 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;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, 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;
    }

    /**
     * @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;
        }

        // 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);
        }
    }

    /**
     * @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);
        }
    }

    /**
     * @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;
    }

    /**
     * @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);
        }
    }

    /**
     * @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 (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            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;
            }
        }
        return result;
    }

    /**
     * @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);
        }
    }

    /**
     * @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;
    }

    /**
     * @dev Return the log in base 256, 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);
        }
    }
}

// File: @openzeppelin/contracts/utils/math/SafeMath.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

// File: @openzeppelin/contracts/utils/math/SignedMath.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

// File: @openzeppelin/contracts/utils/Strings.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @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;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @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);
        }
    }

    /**
     * @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);
    }

    /**
     * @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);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// File: contracts/interfaces/IDai.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IDai is IERC20 {
  function DOMAIN_SEPARATOR() external view returns (bytes32);

  function permit(
    address holder,
    address spender,
    uint256 nonce,
    uint256 expiry,
    bool allowed,
    uint8 v,
    bytes32 r,
    bytes32 s
  ) external;

  function nonces(address owner) external view returns (uint256);
}

// File: contracts/interfaces/IJoin.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

interface IJoin {
  function join(address, uint256) external;

  function exit(address, uint256) external;
}

// File: contracts/interfaces/ILSDai.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/**
 * @title LSDai interface
 * @dev extention of ERC20 interface, with LSDai-specific events
 */
interface ILSDai is IERC20 {
  /**
   * @notice An executed shares transfer from `sender` to `recipient`.
   *
   * @dev emitted in pair with an ERC20-defined `Transfer` event.
   */
  event TransferShares(address indexed from, address indexed to, uint256 sharesValue);

  /**
   * @notice An executed `burnShares` request
   *
   * @dev Reports simultaneously burnt shares amount
   * and corresponding stETH amount.
   * The stETH amount is calculated twice: before and after the burning incurred rebase.
   *
   * @param account holder of the burnt shares
   * @param preRebaseTokenAmount amount of stETH the burnt shares corresponded to before the burn
   * @param postRebaseTokenAmount amount of stETH the burnt shares corresponded to after the burn
   * @param sharesAmount amount of burnt shares
   */
  event SharesBurnt(
    address indexed account, uint256 preRebaseTokenAmount, uint256 postRebaseTokenAmount, uint256 sharesAmount
  );

  /**
   * @dev emitted when the DAI deposit cap is set. set `setDepositCap` for more details.
   */
  event DepositCapSet(uint256 depositCap);

  /**
   * @dev emitted when the withdrawal fee is set. set `setWithdrawalFee` for more details.
   */
  event WithdrawalFeeSet(uint256 withdrawalFee);

  /**
   * @dev emitted when the interest fee is set. set `setInterestFee` for more details.
   */
  event InterestFeeSet(uint256 interestFee);

  /**
   * @dev emitted when the fee recipient is set. set `setFeeRecipient` for more details.
   */
  event FeeRecipientSet(address indexed recipient);

  /**
   * @notice The DAI deposit cap.
   * @dev can be changed by the owner of the contract.
   */
  function depositCap() external view returns (uint256);

  /**
   * @notice the fee recipient.
   * @dev can be changed by the owner of the contract.
   */
  function feeRecipient() external view returns (address);

  /**
   * @dev Updates the fee recipient. Only callable by the owner.
   * @param recipient The new fee recipient.
   */
  function setFeeRecipient(address recipient) external;

  /**
   * @notice sets the DAI deposit cap.
   * @dev can be changed by the owner of the contract.
   * @param cap the new DAI deposit cap.
   */
  function setDepositCap(uint256 cap) external;

  /**
   * @notice the interest fee percentage in basis points (1/100 of a percent)
   */
  function interestFee() external view returns (uint256);

  /**
   * @notice sets the interest fee percentage in basis points (1/100 of a percent)
   * @param fee the new interest fee percentage in basis points (1/100 of a percent)
   */
  function setInterestFee(uint256 fee) external;

  /**
   * @notice the withdrawal fee percentage in basis points (1/100 of a percent)
   */
  function withdrawalFee() external view returns (uint256);

  /**
   * @notice sets the withdrawal fee percentage in basis points (1/100 of a percent)
   * @param fee the new withdrawal fee percentage in basis points (1/100 of a percent)
   */
  function setWithdrawalFee(uint256 fee) external;

  /**
   * @dev initializes the contract.
   * @param _depositCap the DAI deposit cap.
   * @param _interestFee the interest fee percentage in basis points (1/100 of a percent)
   * @param _withdrawalFee the withdrawal fee percentage in basis points (1/100 of a percent)
   * @param _feeRecipient the address of the fee recipient
   */
  function initialize(uint256 _depositCap, uint256 _interestFee, uint256 _withdrawalFee, address _feeRecipient)
    external
    returns (bool);

  /**
   * @dev rebase the total pooled DAI, user balance and total supply of LSDAI.
   * Can only be called by anyone
   */
  function rebase() external;

  /**
   * @return the amount of tokens in existence.
   *
   * @dev Always equals to `_getTotalPooledDai()` since token amount
   * is pegged to the total amount of DAI controlled by the protocol.
   */
  function totalSupply() external view returns (uint256);

  /**
   * @return the amount of total LSDAI shares
   */
  function totalShares() external view returns (uint256);

  ////////////////////////////////////////
  // User functions //////////////////////
  ////////////////////////////////////////

  /// getters ///
  /**
   * @return the amount of shares owned by `_account`.
   */
  function sharesOf(address account) external view returns (uint256);

  /**
   * @notice Returns the amount of LSDai tokens owned by the `account`.
   * @dev Balances are dynamic and equal the `account`'s share in the amount of the
   * total DAI controlled by the protocol. See `sharesOf`.
   * @param account The address of the account to check the balance of.
   * @return The amount of LSDai tokens owned by the `account`.
   */
  function balanceOf(address account) external view returns (uint256);

  /**
   * @dev Deposit DAI and mint LSDAI.
   * @param to The address to mint LSDAI to.
   * @param daiAmount The amount of DAI to deposit.
   * @return amount of LSDAI minted.
   */
  function deposit(address to, uint256 daiAmount) external returns (uint256);

  /**
   * @dev Deposit DAI and mint LSDAI using ERC20 permit.
   * @param to The address to mint LSDAI to.
   * @param daiAmount The amount of DAI to deposit.
   * @param permitNonce The nonce of the permit signature.
   * @param permitExpiry The deadline timestamp, type(uint256).max for no deadline.
   * @param permitV The recovery byte of the signature.
   * @param permitR Half of the ECDSA signature pair.
   * @param permitS Half of the ECDSA signature pair.
   * @return amount amount of LSDAI minted.
   */
  function depositWithPermit(
    address to,
    uint256 daiAmount,
    uint256 permitNonce,
    uint256 permitExpiry,
    uint8 permitV,
    bytes32 permitR,
    bytes32 permitS
  ) external returns (uint256);

  /**
   * Withdraw DAI from the contract
   * @param daiAmount The amount of LSDAI to withdraw. wad is denominated in dai
   */
  function withdraw(uint256 daiAmount) external returns (bool);

  /**
   * @notice Returns the amount of LSDai shares that corresponds to `daiAmount` protocol-controlled DAI.
   * @param daiAmount The amount of protocol-controlled DAI.
   * @return The amount of LSDai shares that corresponds to `daiAmount` protocol-controlled DAI.
   */
  function getSharesByPooledDai(uint256 daiAmount) external view returns (uint256);

  /**
   * @notice Returns the amount of protocol-controlled DAI that corresponds to `sharesAmount` LSDai shares.
   * @param sharesAmount The amount of LSDai shares.
   * @return The amount of protocol-controlled DAI that corresponds to `sharesAmount` LSDai shares.
   */
  function getPooledDaiByShares(uint256 sharesAmount) external view returns (uint256);
}

// File: contracts/interfaces/IPot.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

interface IPot {
  function chi() external view returns (uint256);

  function rho() external view returns (uint256);

  function dsr() external view returns (uint256);

  function drip() external returns (uint256);

  function join(uint256) external;

  function exit(uint256) external;

  /**
   * @notice Return the balance of a given address in this contract. Normalised Savings Dai [wad]
   */
  function pie(address) external view returns (uint256);
}

// File: contracts/interfaces/IVat.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

interface IVat {
  function hope(address) external;
}

// File: contracts/libraries/RMath.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";

/**
 * @title RMath - math library
 * @notice based on MakerDAO's math function in DSRManager
 */
library RMath {
  // --- Math ---
  uint256 constant RAY = 10 ** 27;

  function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
    // always rounds down
    z = SafeMath.mul(x, y) / RAY;
  }

  function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
    // always rounds down
    z = SafeMath.mul(x, RAY) / y;
  }

  function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) {
    // always rounds up
    z = SafeMath.add(SafeMath.mul(x, RAY), SafeMath.sub(y, 1)) / y;
  }

  function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
    assembly {
      switch x
      case 0 {
        switch n
        case 0 { z := RAY }
        default { z := 0 }
      }
      default {
        switch mod(n, 2)
        case 0 { z := RAY }
        default { z := x }
        let half := div(RAY, 2) // for rounding.
        for { n := div(n, 2) } n { n := div(n, 2) } {
          let xx := mul(x, x)
          if iszero(eq(div(xx, x), x)) { revert(0, 0) }
          let xxRound := add(xx, half)
          if lt(xxRound, xx) { revert(0, 0) }
          x := div(xxRound, RAY)
          if mod(n, 2) {
            let zx := mul(z, x)
            if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0, 0) }
            let zxRound := add(zx, half)
            if lt(zxRound, zx) { revert(0, 0) }
            z := div(zxRound, RAY)
          }
        }
      }
    }
  }
}

// File: contracts/LSDai.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
// Custom Ownable logic from OZ
import {Ownable} from "./Ownable.sol";

// Interfaces
import {ILSDai} from "./interfaces/ILSDai.sol";

// DSR helpers
import {RMath} from "./libraries/RMath.sol";
import {IDai} from "./interfaces/IDai.sol";
import {IPot} from "./interfaces/IPot.sol";
import {IJoin} from "./interfaces/IJoin.sol";
import {IVat} from "./interfaces/IVat.sol";

/**
 * @title LSDAI
 * @dev LSDai is a rebasing token that earns interest on DAI deposited in the MakerDAO DSR.
 */
contract LSDai is Ownable, ILSDai {
  error LSDai__AlreadyInitialized();
  error LSDai__DepositCapLowerThanTotalPooledDai();
  error LSDai__DepositCap();
  error LSDai__WithdrawalFeeLow();
  error LSDai__InterestFeeLow();
  error LSDai__TransferToZeroAddress();
  error LSDai__TransferFromZeroAddress();
  error LSDai__TransferToLSDaiContract();
  error LSDai__MintToZeroAddress();
  error LSDai__BurnFromZeroAddress();
  error LSDai__SharesAmountExceedsBalance();
  error LSDai__AmountExceedsBalance();
  error LSDai__FeeRecipientZeroAddress();
  error LSDai__RebaseOverflow(uint256 preRebaseTotalPooledDai, uint256 postRebaseTotalPooledDai);

  using SafeMath for uint256;
  ///////////////////////////
  //     ERC20 storage     //
  ///////////////////////////

  /**
   * @dev Returns the name of the token.
   */
  string public name;

  /**
   * @dev Returns the symbol of the token, usually a shorter version of the
   * name.
   */
  string public symbol;

  /**
   * @dev Returns the number of decimals used to get its user representation.
   */
  uint256 public immutable decimals = 18;

  /**
   * @dev Returns the amount of tokens in existence.
   */
  mapping(address => mapping(address => uint256)) private _allowances;

  /*//////////////////////////////////////////////////////////////
                                 LSDAI STORAGE
    //////////////////////////////////////////////////////////////*/

  /**
   * @dev LSDAI is initialized.
   */
  bool private _initialized;

  /**
   * @dev LSDAI deposit cap. This is the maximum amount of DAI that can be deposited.
   */
  uint256 public depositCap;

  /**
   * @dev Address shares
   */
  mapping(address => uint256) private _shares;

  /**
   * @dev Total shares of LSDAI
   */
  uint256 private _totalLsdaiShares;

  /**
   * @notice Total amount of DAI controlled by LSDAI at MakerDAO DSR.
   * @dev This value must be updated before depositing or withdrawing.
   */
  uint256 private _totalPooledDai;

  /**
   * @dev the total amount of pot shares
   */
  uint256 private _totalPotShares;

  ///////////////////////////
  // LSDAI Fee Information //
  ///////////////////////////
  /**
   * @notice Interest fee taken on interest earned, in basis points.
   */
  uint256 public interestFee = 250; // 2.5%

  /**
   * @notice Withdrawal fee taken on exit, in basis points.
   */
  uint256 public withdrawalFee = 1; // 0.01%

  /**
   * @notice Fee recipient address.
   */
  address public feeRecipient;

  ///////////////////////////
  // MakerDAO DSR Contracts //
  ///////////////////////////
  IVat public immutable vat = IVat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
  IPot public immutable pot = IPot(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7);
  IJoin public immutable daiJoin = IJoin(0x9759A6Ac90977b93B58547b4A71c78317f391A28);
  IDai public immutable dai = IDai(0x6B175474E89094C44Da98b954EedeAC495271d0F);

  /**
   * @dev initializes the contract.
   * @param _depositCap the DAI deposit cap.
   * @param _interestFee the interest fee percentage in basis points (1/100 of a percent)
   * @param _withdrawalFee the withdrawal fee percentage in basis points (1/100 of a percent)
   * @param _feeRecipient the address of the fee recipient
   */
  function initialize(uint256 _depositCap, uint256 _interestFee, uint256 _withdrawalFee, address _feeRecipient)
    external
    returns (bool)
  {
    if (_initialized) {
      revert LSDai__AlreadyInitialized();
    }

    // Transfer ownership to message sender
    _transferOwnership(msg.sender);

    // Set ERC20 name and symbol
    name = "Liquid Savings DAI";
    symbol = "LSDAI";

    // Set initial deposit cap to 10m DAI
    setDepositCap(_depositCap);
    // Set fee information
    setFeeRecipient(_feeRecipient);
    setWithdrawalFee(_withdrawalFee);
    setInterestFee(_interestFee);

    _initialized = true;

    // Setup the LSDAI contract to be able to interact with the MakerDAO contracts and DAI token
    vat.hope(address(daiJoin));
    vat.hope(address(pot));
    dai.approve(address(daiJoin), type(uint256).max);

    return true;
  }

  /**
   * @return the amount of shares owned by `_account`.
   */
  function sharesOf(address account) public view returns (uint256) {
    return _shares[account];
  }

  /**
   * @dev returns the amount of pot shares the LSDAI contract has in the DSR pot contract
   */
  function potShares() public view returns (uint256) {
    return pot.pie(address(this));
  }

  /**
   * @dev Deposit DAI and mint LSDAI.
   * @param to The address to mint LSDAI to.
   * @param daiAmount The amount of DAI to deposit.
   * @return amount of LSDAI minted.
   */
  function deposit(address to, uint256 daiAmount) external returns (uint256) {
    dai.transferFrom(msg.sender, address(this), daiAmount);
    return _deposit(to, daiAmount);
  }

  /**
   * @dev Deposit DAI and mint LSDAI.
   * @param to The address to mint LSDAI to.
   * @param daiAmount The amount of DAI to deposit.
   * @param permitNonce The nonce of the permit signature.
   * @param permitExpiry The deadline timestamp, type(uint256).max for no deadline.
   * @param permitV The recovery byte of the signature.
   * @param permitR Half of the ECDSA signature pair.
   * @param permitS Half of the ECDSA signature pair.
   * @return amount of LSDAI minted.
   */
  function depositWithPermit(
    address to,
    uint256 daiAmount,
    uint256 permitNonce,
    uint256 permitExpiry,
    uint8 permitV,
    bytes32 permitR,
    bytes32 permitS
  ) external returns (uint256) {
    dai.permit(msg.sender, address(this), permitNonce, permitExpiry, true, permitV, permitR, permitS);
    dai.transferFrom(msg.sender, address(this), daiAmount);
    return _deposit(to, daiAmount);
  }

  /**
   * Withdraw DAI from the contract
   * @param daiAmount The amount of LSDAI to withdraw. wad is denominated in dai
   */
  function withdraw(uint256 daiAmount) external returns (bool) {
    return _withdraw(daiAmount, withdrawalFee);
  }

  /**
   * @dev withdraws the pending protocol fees from the DSR pot to the owner. Only callable by the owner.
   */
  function collectFees() external onlyOwner returns (bool) {
    return _withdraw(balanceOf(feeRecipient), 0);
  }

  /**
   * @dev Updates the withdrawal fee. Only callable by the owner.
   * @param fee The new withdrawal fee, in basis points.
   */
  function setWithdrawalFee(uint256 fee) public onlyOwner {
    if (fee < 0) {
      revert LSDai__WithdrawalFeeLow();
    }

    withdrawalFee = fee;

    emit WithdrawalFeeSet(fee);
  }

  /**
   * @dev Updates the interest fee. Only callable by the owner.
   * @param fee The new interest fee, in basis points.
   */
  function setInterestFee(uint256 fee) public onlyOwner {
    if (fee < 0) {
      revert LSDai__InterestFeeLow();
    }

    interestFee = fee;

    emit InterestFeeSet(fee);
  }

  /**
   * @dev Updates the fee recipient. Only callable by the owner.
   * @param recipient The new fee recipient.
   */
  function setFeeRecipient(address recipient) public onlyOwner {
    if (recipient == address(0)) {
      revert LSDai__FeeRecipientZeroAddress();
    }

    feeRecipient = recipient;

    emit FeeRecipientSet(recipient);
  }

  /**
   * @return the amount of tokens owned by the `account`.
   *
   * @dev Balances are dynamic and equal the `account`'s share in the amount of the
   * total DAI controlled by the protocol. See `sharesOf`.
   */
  function balanceOf(address account) public view virtual override returns (uint256) {
    return getPooledDaiByShares(sharesOf(account));
  }

  /**
   * @return the amount of shares that corresponds to `daiAmount` protocol-controlled DAI.
   * @param daiAmount The amount of protocol-controlled DAI.
   */
  function getSharesByPooledDai(uint256 daiAmount) public view returns (uint256) {
    // Prevent division by zero
    if (_totalPooledDai == 0) {
      return daiAmount;
    }

    return daiAmount.mul(_totalLsdaiShares).div(_totalPooledDai);
  }

  /**
   * @return the amount of DAI that corresponds to `sharesAmount` token shares.
   * @param sharesAmount The amount of LSDAI shares.
   */
  function getPooledDaiByShares(uint256 sharesAmount) public view returns (uint256) {
    return sharesAmount.mul(_totalPooledDai).div(_totalLsdaiShares);
  }

  /**
   * @return the amount of tokens in existence.
   *
   * @dev Always equals to `_getTotalPooledDai()` since token amount
   * is pegged to the total amount of DAI controlled by the protocol.
   */
  function totalSupply() public view override returns (uint256) {
    return _getTotalPooledDai();
  }

  /**
   * @return the amount of total LSDAI shares
   */
  function totalShares() public view returns (uint256) {
    return _totalLsdaiShares;
  }

  /**
   * @dev rebase the total pooled DAI, user balance and total supply of LSDAI.
   * Can only be called by anyone
   */
  function rebase() external {
    uint256 chi = _getMostRecentChi();
    _rebase(chi, true);
  }

  /**
   * @notice Sets deposit cap. Exclusive for the owner.
   */
  function setDepositCap(uint256 cap) public onlyOwner {
    // Must be higher than total pooled DAI
    if (cap < _getTotalPooledDai()) {
      revert LSDai__DepositCapLowerThanTotalPooledDai();
    }

    depositCap = cap;

    emit DepositCapSet(cap);
  }

  /**
   * Returns DAI balance at the MakerDAO DSR contract.
   */
  function getTotalPotSharesValue() external view returns (uint256) {
    uint256 chi = (block.timestamp > pot.rho())
      ? (RMath.rpow(pot.dsr(), block.timestamp - pot.rho()) * pot.chi()) / RMath.RAY
      : pot.chi();

    // total pooled DAI is the total shares times the chi
    return (_totalPotShares * chi) / RMath.RAY;
  }

  ///////////////////////////////////////
  ///////// Internal functions /////////
  /////////////////////////////////////

  /**
   * @dev Deposit DAI and mint LSDAI.
   * @param _to The address to mint LSDAI to.
   * @param _daiAmount The amount of DAI to deposit.
   * @return shares amount of LSDAI minted.
   */
  function _deposit(address _to, uint256 _daiAmount) internal returns (uint256 shares) {
    // Check if the deposit cap is reached
    if (depositCap > 0 && _getTotalPooledDai().add(_daiAmount) > depositCap) {
      revert LSDai__DepositCap();
    }

    uint256 chi = _getMostRecentChi();

    // Calculate the amount of pot shares to mint
    uint256 potSharesAmount = RMath.rdiv(_daiAmount, chi);

    // Mint the shares to the user
    shares = getSharesByPooledDai(_daiAmount);
    _mintShares(_to, shares);

    // Increase the total amount of DAI pooled
    _totalPooledDai = _totalPooledDai.add(_daiAmount);
    // Keep track of total pot shares controlled by LSDAI
    _totalPotShares = _totalPotShares.add(potSharesAmount);

    // Mint LSDAI at 1:1 ratio to DAI
    emit Transfer(address(0), _to, _daiAmount);

    // Join the DSR on behalf of the user
    daiJoin.join(address(this), _daiAmount);
    pot.join(potSharesAmount);
  }

  /**
   * Withdraw shares back to DAI
   * @param _daiAmount The amount of LSDAI to withdraw. wad is denominated in (1/chi) * dai
   * @param _withdrawFee The fee to be charged on the withdrawal, in basis points.
   */
  function _withdraw(uint256 _daiAmount, uint256 _withdrawFee) internal returns (bool) {
    uint256 currentDaiBalance = balanceOf(msg.sender);
    // Check if the user has enough LSDAI
    if (_daiAmount > currentDaiBalance) {
      revert LSDai__AmountExceedsBalance();
    }
    uint256 chi = _getMostRecentChi();

    // Split the amount into the fee and the actual withdrawal
    uint256 feeAmount = _daiAmount.mul(_withdrawFee).div(10_000);
    // Amount going to the user
    uint256 withdrawAmount = _daiAmount.sub(feeAmount);

    // Transfer the fee shares to fee recipient
    // and burn the withdraw shares from the user
    uint256 feeShares = getSharesByPooledDai(feeAmount);
    uint256 withdrawShares = getSharesByPooledDai(withdrawAmount);

    // Decrease the total amount of DAI pooled
    _totalPooledDai = _totalPooledDai.sub(withdrawAmount);

    _transferShares(msg.sender, feeRecipient, feeShares);
    _burnShares(msg.sender, withdrawShares);

    // Withdraw from the DSR, roudning up ensures we get at least the amount of DAI requested
    uint256 withdrawPotShares = RMath.rdivup(withdrawAmount, chi);
    // Reduce the total pot shares controlled by LSDAI
    _totalPotShares = _totalPotShares.sub(withdrawPotShares);

    // Burn LSDAI at 1:1 ratio to DAI
    emit Transfer(msg.sender, address(0), withdrawAmount);

    // Get back the DAI from the DSR to the contract
    pot.exit(withdrawPotShares);

    //  daiJoin.exit(msg.sender, rmul(chi, wad)); // wad is in dai units
    daiJoin.exit(address(this), withdrawAmount); // wad is in dai units

    // Send it over
    return dai.transfer(msg.sender, withdrawAmount);
  }

  /**
   * @notice Destroys `_sharesAmount` shares from `_account`'s holdings, decreasing the total amount of shares.
   * @dev This doesn't decrease the token total supply.
   *
   * Requirements:
   *
   * - `_account` cannot be the zero address.
   * - `_account` must hold at least `_sharesAmount` shares.
   * - the contract must not be paused.
   */
  function _burnShares(address _account, uint256 _sharesAmount) internal returns (uint256 newTotalShares) {
    if (_account == address(0)) {
      revert LSDai__BurnFromZeroAddress();
    }

    uint256 accountShares = _shares[_account];

    if (_sharesAmount > accountShares) {
      revert LSDai__SharesAmountExceedsBalance();
    }

    uint256 preRebaseTokenAmount = getPooledDaiByShares(_sharesAmount);

    newTotalShares = _totalLsdaiShares.sub(_sharesAmount);

    _totalLsdaiShares = newTotalShares;

    _shares[_account] = accountShares.sub(_sharesAmount);

    uint256 postRebaseTokenAmount = getPooledDaiByShares(_sharesAmount);

    emit SharesBurnt(_account, preRebaseTokenAmount, postRebaseTokenAmount, _sharesAmount);

    // Notice: we're not emitting a Transfer event to the zero address here since shares burn
    // works by redistributing the amount of tokens corresponding to the burned shares between
    // all other token holders. The total supply of the token doesn't change as the result.
    // This is equivalent to performing a send from `address` to each other token holder address,
    // but we cannot reflect this as it would require sending an unbounded number of events.

    // We're emitting `SharesBurnt` event to provide an explicit rebase log record nonetheless.
  }

  /**
   * @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 = msg.sender;
    _approve(owner, spender, amount);
    return true;
  }

  /**
   * @notice Moves `_amount` tokens from the caller's account to the `_recipient` account.
   *
   * @return a boolean value indicating whether the operation succeeded.
   * Emits a `Transfer` event.
   * Emits a `TransferShares` event.
   *
   * Requirements:
   *
   * - `_recipient` cannot be the zero address.
   * - the caller must have a balance of at least `_amount`.
   * - the contract must not be paused.
   *
   * @dev The `_amount` argument is the amount of tokens, not shares.
   */
  function transfer(address _recipient, uint256 _amount) public override returns (bool) {
    _transfer(msg.sender, _recipient, _amount);
    return true;
  }

  /**
   * @notice Moves `_amount` tokens from `_sender` to `_recipient` using the
   * allowance mechanism. `_amount` is then deducted from the caller's
   * allowance.
   *
   * @return a boolean value indicating whether the operation succeeded.
   *
   * Emits a `Transfer` event.
   * Emits a `TransferShares` event.
   * Emits an `Approval` event indicating the updated allowance.
   *
   * Requirements:
   *
   * - `_sender` and `_recipient` cannot be the zero addresses.
   * - `_sender` must have a balance of at least `_amount`.
   * - the caller must have allowance for `_sender`'s tokens of at least `_amount`.
   * - the contract must not be paused.
   *
   * @dev The `_amount` argument is the amount of tokens, not shares.
   */
  function transferFrom(address _sender, address _recipient, uint256 _amount) external override returns (bool) {
    _spendAllowance(_sender, msg.sender, _amount);
    _transfer(_sender, _recipient, _amount);
    return true;
  }

  /**
   * @notice Moves `_sharesAmount` token shares from the caller's account to the `_recipient` account.
   *
   * @return amount of transferred tokens.
   * Emits a `TransferShares` event.
   * Emits a `Transfer` event.
   *
   * Requirements:
   *
   * - `_recipient` cannot be the zero address.
   * - the caller must have at least `_sharesAmount` shares.
   * - the contract must not be paused.
   *
   * @dev The `_sharesAmount` argument is the amount of shares, not tokens.
   */
  function transferShares(address _recipient, uint256 _sharesAmount) external returns (uint256) {
    _transferShares(msg.sender, _recipient, _sharesAmount);
    uint256 tokensAmount = getPooledDaiByShares(_sharesAmount);
    _emitTransferEvents(msg.sender, _recipient, tokensAmount, _sharesAmount);
    return tokensAmount;
  }

  /**
   * @notice Moves `_sharesAmount` token shares from the `_sender` account to the `_recipient` account.
   *
   * @return amount of transferred tokens.
   * Emits a `TransferShares` event.
   * Emits a `Transfer` event.
   *
   * Requirements:
   *
   * - `_sender` and `_recipient` cannot be the zero addresses.
   * - `_sender` must have at least `_sharesAmount` shares.
   * - the caller must have allowance for `_sender`'s tokens of at least `getPooledDaiByShares(_sharesAmount)`.
   * - the contract must not be paused.
   *
   * @dev The `_sharesAmount` argument is the amount of shares, not tokens.
   */
  function transferSharesFrom(address _sender, address _recipient, uint256 _sharesAmount) external returns (uint256) {
    uint256 tokensAmount = getPooledDaiByShares(_sharesAmount);
    _spendAllowance(_sender, msg.sender, tokensAmount);
    _transferShares(_sender, _recipient, _sharesAmount);
    _emitTransferEvents(_sender, _recipient, tokensAmount, _sharesAmount);
    return tokensAmount;
  }

  /**
   * @notice Moves `_amount` tokens from `_sender` to `_recipient`.
   * Emits a `Transfer` event.
   * Emits a `TransferShares` event.
   */
  function _transfer(address _sender, address _recipient, uint256 _amount) internal {
    uint256 _sharesToTransfer = getSharesByPooledDai(_amount);
    _transferShares(_sender, _recipient, _sharesToTransfer);
    _emitTransferEvents(_sender, _recipient, _amount, _sharesToTransfer);
  }

  /**
   * @notice Moves `_sharesAmount` shares from `_sender` to `_recipient`.
   *
   * Requirements:
   *
   * - `_sender` cannot be the zero address.
   * - `_recipient` cannot be the zero address or the `LSDai` token contract itself
   * - `_sender` must hold at least `_sharesAmount` shares.
   * - the contract must not be paused.
   */
  function _transferShares(address _sender, address _recipient, uint256 _sharesAmount) internal {
    if (_sender == address(0)) {
      revert LSDai__TransferFromZeroAddress();
    }
    if (_recipient == address(0)) {
      revert LSDai__TransferToZeroAddress();
    }

    if (_recipient == address(this)) {
      revert LSDai__TransferToLSDaiContract();
    }

    // _whenNotStopped();

    uint256 currentSenderShares = _shares[_sender];

    if (_sharesAmount > currentSenderShares) {
      revert LSDai__SharesAmountExceedsBalance();
    }

    _shares[_sender] = currentSenderShares.sub(_sharesAmount);
    _shares[_recipient] = _shares[_recipient].add(_sharesAmount);
  }

  /**
   * @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 {
    require(owner != address(0), "ERC20: approve from the zero address");
    require(spender != address(0), "ERC20: approve to the zero address");

    _allowances[owner][spender] = amount;
    emit Approval(owner, spender, amount);
  }

  /**
   * @dev 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 {
    uint256 currentAllowance = allowance(owner, spender);
    if (currentAllowance != type(uint256).max) {
      require(currentAllowance >= amount, "ERC20: insufficient allowance");
      unchecked {
        _approve(owner, spender, currentAllowance - amount);
      }
    }
  }

  /**
   * @dev Emits {Transfer} and {TransferShares} events
   */
  function _emitTransferEvents(address _from, address _to, uint256 _tokenAmount, uint256 _sharesAmount) internal {
    emit Transfer(_from, _to, _tokenAmount);
    emit TransferShares(_from, _to, _sharesAmount);
  }

  /**
   * @notice Creates `_sharesAmount` shares and assigns them to `_recipient`, increasing the total amount of shares.
   * @dev This doesn't increase the token total supply.
   *
   * NB: The method doesn't check protocol pause relying on the external enforcement.
   *
   * Requirements:
   *
   * - `_to` cannot be the zero address.
   * - the contract must not be paused.
   */
  function _mintShares(address _to, uint256 _sharesAmount) internal returns (uint256 newTotalShares) {
    if (_to == address(0)) {
      revert LSDai__TransferToZeroAddress();
    }

    newTotalShares = _totalLsdaiShares.add(_sharesAmount);

    /// @todo research a better place for the storage location for the total shares
    _totalLsdaiShares = newTotalShares;

    _shares[_to] = _shares[_to].add(_sharesAmount);
  }

  /**
   * @dev updates the total amount of DAI controlled by LSDai.
   * @param chi If overrideChi is greater than 0, it will use that chi instead of the most recent chi.
   * @param requireSuccess If true, it will revert if the delta pooled DAI underflows or overflows.
   * It also calcuates the fees on the accrued interest and appends them to the protocol fee pot.chi();
   */
  function _rebase(uint256 chi, bool requireSuccess) internal {
    uint256 preRebaseTotalPooledDai = _totalPooledDai;
    // total pooled DAI is the total shares times the chi
    uint256 postRebaseTotalPooledDai = (_totalPotShares * chi) / RMath.RAY;

    // Change in total pooled DAI is the total pooled DAI before fees minus the total pooled DAI after fees
    (bool isOk, uint256 deltaTotalPooledDai) = postRebaseTotalPooledDai.trySub(_totalPooledDai); // Interest earned since last rebase

    // Revert with custom error in event of underflow/overflow
    if (isOk == false && requireSuccess == true) {
      revert LSDai__RebaseOverflow(preRebaseTotalPooledDai, postRebaseTotalPooledDai);
    } else if (isOk == false) {
      return;
    }

    // Update total pooled DAI
    _totalPooledDai = postRebaseTotalPooledDai;

    // Get the fees on accrued interest
    uint256 protocolFeeDaiAmount = _calcInterestFees(deltaTotalPooledDai);

    // Mint LSdai shares to the protocol
    uint256 protocolFeeLsdaiShares = getSharesByPooledDai(protocolFeeDaiAmount);
    _mintShares(feeRecipient, protocolFeeLsdaiShares);
  }

  /**
   * Returns the total supply of LSDAI by converting the DSR shares to DAI
   */
  function _getTotalPooledDai() internal view returns (uint256) {
    return _totalPooledDai;
  }

  /**
   * @dev Calculates the fees on the accrued interest
   * @param _daiAmount The change in total pooled DAI since the last rebase
   */
  function _calcInterestFees(uint256 _daiAmount) internal view returns (uint256 protocolFee) {
    if (interestFee == 0) {
      return 0;
    }

    protocolFee = _daiAmount.mul(interestFee).div(10_000);
  }

  /**
   * @dev returns most recent chi (the rate accumulator) by calling drip if necessary
   */
  function _getMostRecentChi() internal returns (uint256) {
    if (block.timestamp > pot.rho()) {
      return pot.drip();
    }
    return pot.chi();
  }
}

// File: contracts/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
contract Ownable {
  address private _owner;

  event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

  /**
   * @dev Throws if called by any account other than the owner.
   */
  modifier onlyOwner() {
    _checkOwner();
    _;
  }

  /**
   * @dev Returns the address of the current owner.
   */
  function owner() public view virtual returns (address) {
    return _owner;
  }

  /**
   * @dev Throws if the sender is not the owner.
   */
  function _checkOwner() internal view virtual {
    require(owner() == msg.sender, "Ownable: caller is not the owner");
  }

  /**
   * @dev Leaves the contract without owner. It will not be possible to call
   * `onlyOwner` functions. Can only be called by the current owner.
   *
   * NOTE: Renouncing ownership will leave the contract without an owner,
   * thereby disabling any functionality that is only available to the owner.
   */
  function renounceOwnership() public virtual onlyOwner {
    _transferOwnership(address(0));
  }

  /**
   * @dev Transfers ownership of the contract to a new account (`newOwner`).
   * Can only be called by the current owner.
   */
  function transferOwnership(address newOwner) public virtual onlyOwner {
    require(newOwner != address(0), "Ownable: new owner is the zero address");
    _transferOwnership(newOwner);
  }

  /**
   * @dev Transfers ownership of the contract to a new account (`newOwner`).
   * Internal function without access restriction.
   */
  function _transferOwnership(address newOwner) internal virtual {
    address oldOwner = _owner;
    _owner = newOwner;
    emit OwnershipTransferred(oldOwner, newOwner);
  }
}