// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol



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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// 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/token/ERC20/utils/SafeERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

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



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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

// File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

// File: contracts/common/CommonEventsAndErrors.sol



pragma solidity 0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (common/CommonEventsAndErrors.sol)

/// @notice A collection of common errors thrown within the Temple contracts
library CommonEventsAndErrors {
    error InsufficientBalance(address token, uint256 required, uint256 balance);
    error InvalidParam();
    error InvalidAddress();
    error InvalidAccess();
    error InvalidAmount(address token, uint256 amount);
    error ExpectedNonZero();
    error Unimplemented();
    event TokenRecovered(address indexed to, address indexed token, uint256 amount);
}

// File: contracts/interfaces/v2/access/ITempleElevatedAccess.sol



pragma solidity 0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (interfaces/v2/access/ITempleElevatedAccess.sol)

/**
 * @notice Inherit to add Executor and Rescuer roles for DAO elevated access.
 */ 
interface ITempleElevatedAccess {
    event ExplicitAccessSet(address indexed account, bytes4 indexed fnSelector, bool indexed value);
    event RescueModeSet(bool indexed value);

    event NewRescuerProposed(address indexed oldRescuer, address indexed oldProposedRescuer, address indexed newProposedRescuer);
    event NewRescuerAccepted(address indexed oldRescuer, address indexed newRescuer);

    event NewExecutorProposed(address indexed oldExecutor, address indexed oldProposedExecutor, address indexed newProposedExecutor);
    event NewExecutorAccepted(address indexed oldExecutor, address indexed newExecutor);

    struct ExplicitAccess {
        bytes4 fnSelector;
        bool allowed;
    }

    /**
     * @notice A set of addresses which are approved to execute emergency operations.
     */ 
    function rescuer() external returns (address);

    /**
     * @notice A set of addresses which are approved to execute normal operations on behalf of the DAO.
     */ 
    function executor() external returns (address);

    /**
     * @notice Explicit approval for an address to execute a function.
     * allowedCaller => function selector => true/false
     */
    function explicitFunctionAccess(address contractAddr, bytes4 functionSelector) external returns (bool);

    /**
     * @notice Under normal circumstances, rescuers don't have access to admin/operational functions.
     * However when rescue mode is enabled (by rescuers or executors), they claim the access rights.
     */
    function inRescueMode() external returns (bool);
    
    /**
     * @notice Set the contract into or out of rescue mode.
     * Only the rescuers or executors are allowed to set.
     */
    function setRescueMode(bool value) external;

    /**
     * @notice Proposes a new Rescuer.
     * Can only be called by the current rescuer.
     */
    function proposeNewRescuer(address account) external;

    /**
     * @notice Caller accepts the role as new Rescuer.
     * Can only be called by the proposed rescuer
     */
    function acceptRescuer() external;

    /**
     * @notice Proposes a new Executor.
     * Can only be called by the current executor or resucer (if in resuce mode)
     */
    function proposeNewExecutor(address account) external;

    /**
     * @notice Caller accepts the role as new Executor.
     * Can only be called by the proposed executor
     */
    function acceptExecutor() external;

    /**
     * @notice Grant `allowedCaller` the rights to call the function selectors in the access list.
     * @dev fnSelector == bytes4(keccak256("fn(argType1,argType2,...)"))
     */
    function setExplicitAccess(address allowedCaller, ExplicitAccess[] calldata access) external;
}

// File: contracts/interfaces/v2/ITempleDebtToken.sol



pragma solidity 0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (interfaces/v2/ITempleDebtToken.sol)

import { IERC20, IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { ITempleElevatedAccess } from "contracts/interfaces/v2/access/ITempleElevatedAccess.sol";

interface ITempleDebtToken is IERC20, IERC20Metadata, ITempleElevatedAccess {
    error NonTransferrable();
    error CannotMintOrBurn(address caller);

    event BaseInterestRateSet(uint96 rate);
    event RiskPremiumInterestRateSet(address indexed debtor, uint96 rate);
    event AddedMinter(address indexed account);
    event RemovedMinter(address indexed account);
    event DebtorBalance(address indexed debtor, uint128 principal, uint128 baseInterest, uint128 riskPremiumInterest);

    /**
     * @notice Track the deployed version of this contract. 
     */
    function version() external view returns (string memory);

    /**
     * @notice The current (base rate) interest common for all users. This can be updated by governance
     * @dev 1e18 format, where 0.01e18 = 1%
     */
    function baseRate() external view returns (uint96);

    /**
     * @notice The last checkpoint time of the (base rate) principal and interest checkpoint
     */
    function baseCheckpointTime() external view returns (uint32);

    /**
     * @notice The (base rate) total principal and interest owed across all debtors as of the latest checkpoint
     */
    function baseCheckpoint() external view returns (uint128);

    /**
     * @notice The (base rate) total number of shares allocated out to users for internal book keeping
     */
    function baseShares() external view returns (uint128);

    /**
     * @notice The net amount of principal amount of debt minted across all users.
     */
    function totalPrincipal() external view returns (uint128);

    /**
     * @notice The latest estimate of the (risk premium) interest (no principal) owed.
     * @dev Indicative only. This total is only updated on a per strategy basis when that strategy gets 
     * checkpointed (on borrow/repay rate change).
     * So it is generally always going to be out of date as each strategy will accrue interest independently 
     * on different rates.
     */
    function estimatedTotalRiskPremiumInterest() external view returns (uint128);

    /// @dev byte packed into two slots.
    struct Debtor {
        /// @notice The current principal owed by this debtor
        uint128 principal;

        /// @notice The number of this shares this debtor is allocated of the base interest.
        uint128 baseShares;

        /// @notice The current (risk premium) interest rate specific to this debtor. This can be updated by governance
        /// @dev 1e18 format, where 0.01e18 = 1%
        uint96 rate;

        /// @notice The debtor's (risk premium only) interest (no principal or base interest) owed as of the last checkpoint
        uint128 checkpoint;

        /// @notice The last checkpoint time of this debtor's (risk premium) interest
        /// @dev uint32 => max time of Feb 7 2106
        uint32 checkpointTime;
    }

    /**
     * @notice Per address status of debt
     */
    function debtors(address account) external view returns (
        /// @notice The current principal owed by this debtor
        uint128 principal,

        /// @notice The number of this shares this debtor is allocated of the base interest.
        uint128 baseShares,

        /// @notice The current (risk premium) interest rate specific to this debtor. This can be updated by governance
        /// @dev 1e18 format, where 0.01e18 = 1%
        uint96 rate,

        /// @notice The debtor's (risk premium only) interest (no principal or base interest) owed as of the last checkpoint
        uint128 checkpoint,

        /// @notice The last checkpoint time of this debtor's (risk premium) interest
        uint32 checkpointTime
    );

    /// @notice A set of addresses which are approved to mint/burn
    function minters(address account) external view returns (bool);

    /**
     * @notice Governance can add an address which is able to mint or burn debt
     * positions on behalf of users.
     */
    function addMinter(address account) external;

    /**
     * @notice Governance can remove an address which is able to mint or burn debt
     * positions on behalf of users.
     */
    function removeMinter(address account) external;

    /**
     * @notice Governance can update the continuously compounding (base) interest rate of all debtors, from this block onwards.
     */
    function setBaseInterestRate(uint96 _rate) external;

    /**
     * @notice Governance can update the continuously compounding (risk premium) interest rate for a given debtor, from this block onwards
     */
    function setRiskPremiumInterestRate(address _debtor, uint96 _rate) external;

    /**
     * @notice Approved Minters can add a new debt position on behalf of a user.
     * @param _debtor The address of the debtor who is issued new debt
     * @param _mintAmount The notional amount of debt tokens to issue.
     */
    function mint(address _debtor, uint256 _mintAmount) external;

    /**
     * @notice Approved Minters can burn debt on behalf of a user.
     * @dev Interest is repaid in preference:
     *   1/ Firstly to the higher interest rate of (baseRate, debtor risk premium rate)
     *   2/ Any remaining of the repayment is then paid of the other interest amount.
     *   3/ Finally if there is still some repayment amount unallocated, 
     *      then the principal will be paid down. This is like a new debt is issued for the lower balance,
     *      where interest accrual starts fresh.
     * More debt than the user has cannot be burned - it is capped. The actual amount burned is returned
     * @param _debtor The address of the debtor
     * @param _burnAmount The notional amount of debt tokens to repay.
     */
    function burn(address _debtor, uint256 _burnAmount) external returns (uint256 burnedAmount);

    /**
     * @notice Approved Minters can burn the entire debt on behalf of a user.
     * @param _debtor The address of the debtor
     */
    function burnAll(address _debtor) external returns (uint256 burnedAmount);

    /**
     * @notice Checkpoint the base interest owed by all debtors up to this block.
     */
    function checkpointBaseInterest() external returns (uint256);

    /**
     * @notice Checkpoint a debtor's (risk premium) interest (no principal) owed up to this block.
     */
    function checkpointDebtorInterest(address debtor) external returns (uint256);

    /**
     * @notice Checkpoint multiple accounts (risk premium) interest (no principal) owed up to this block.
     * @dev Provided in case there needs to be block synchronisation on the total debt.
     */
    function checkpointDebtorsInterest(address[] calldata _debtors) external;

    struct DebtOwed {
        uint256 principal;
        uint256 baseInterest;
        uint256 riskPremiumInterest;
    }

    /**
     * @notice The current debt for a given user split out by
     * principal, base interest, risk premium (per debtor) interest
     */
    function currentDebtOf(address _debtor) external view returns (
        DebtOwed memory debtOwed
    );

    /**
     * @notice The current debt for a given set of users split out by
     * principal, base interest, risk premium (per debtor) interest
     */
    function currentDebtsOf(address[] calldata _debtors) external view returns (
        DebtOwed[] memory debtsOwed
    );

    /**
      * @notice The current total principal + total base interest, total (estimate) debtor specific risk premium interest owed by all debtors.
      * @dev Note the (total principal + total base interest) portion is up to date.
      * However the (debtor specific risk premium interest) portion is likely stale.
      * The `estimatedTotalDebtorInterest` is only updated when each debtor checkpoints, so it's going to be out of date.
      * For more up to date current totals, off-chain aggregation of balanceOf() will be required - eg via subgraph.
      */
    function currentTotalDebt() external view returns (
        DebtOwed memory debtOwed
    );

    /**
     * @notice Convert a (base interest) debt amount into proportional amount of shares
     */
    function baseDebtToShares(uint128 debt) external view returns (uint128);

    /**
     * @notice Convert a number of (base interest) shares into proportional amount of debt
     */
    function baseSharesToDebt(uint128 shares) external view returns (uint128);
}
// File: contracts/interfaces/v2/ITreasuryPriceIndexOracle.sol



pragma solidity 0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (interfaces/v2/ITreasuryPriceIndexOracle.sol)

import { ITempleElevatedAccess } from "contracts/interfaces/v2/access/ITempleElevatedAccess.sol";

/**
 * @title Treasury Price Index Oracle
 * @notice The custom oracle (not dependant on external markets/AMMs/dependencies) to give the
 * Treasury Price Index, representing the target Treasury Value per token.
 * This rate is updated manually with elevated permissions. The new TPI doesn't take effect until after a cooldown.
 */
interface ITreasuryPriceIndexOracle is ITempleElevatedAccess {
    event TreasuryPriceIndexSet(uint96 oldTpi, uint96 newTpi);
    event TpiCooldownSet(uint32 cooldownSecs);
    event MaxTreasuryPriceIndexDeltaSet(uint256 maxDelta);

    error BreachedMaxTpiDelta(uint96 oldTpi, uint96 newTpi, uint256 maxDelta);

    /**
     * @notice The current Treasury Price Index (TPI) value
     * @dev If the TPI has just been updated, the old TPI will be used until `cooldownSecs` has elapsed
     */
    function treasuryPriceIndex() external view returns (uint96);

    /**
     * @notice The maximum allowed TPI change on any single `setTreasuryPriceIndex()`, in absolute terms.
     * @dev Used as a bound to avoid unintended/fat fingering when updating TPI
     */
    function maxTreasuryPriceIndexDelta() external view returns (uint256);

    /**
     * @notice The current internal TPI data along with when it was last reset, and the prior value
     */
    function tpiData() external view returns (
        uint96 currentTpi,
        uint96 previousTpi,
        uint32 lastUpdatedAt,
        uint32 cooldownSecs
    );

    /**
     * @notice Set the Treasury Price Index (TPI)
     */
    function setTreasuryPriceIndex(uint96 value) external;

    /**
     * @notice Set the number of seconds to elapse before a new TPI will take effect.
     */
    function setTpiCooldown(uint32 cooldownSecs) external;

    /**
     * @notice Set the maximum allowed TPI change on any single `setTreasuryPriceIndex()`, in absolute terms.
     * @dev 18 decimal places, 0.20e18 == $0.20
     */
    function setMaxTreasuryPriceIndexDelta(uint256 maxDelta) external;

    /**
     * @notice The decimal precision of Temple Price Index (TPI)
     * @dev 18 decimals, so 1.02e18 == $1.02
     */
    // solhint-disable-next-line func-name-mixedcase
    function TPI_DECIMALS() external view returns (uint256);
}
// File: contracts/interfaces/v2/ITreasuryReservesVault.sol



pragma solidity 0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (interfaces/v2/ITreasuryReservesVault.sol)

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

import { ITempleDebtToken } from "contracts/interfaces/v2/ITempleDebtToken.sol";
import { ITempleStrategy } from "contracts/interfaces/v2/strategies/ITempleStrategy.sol";
import { ITempleBaseStrategy } from "contracts/interfaces/v2/strategies/ITempleBaseStrategy.sol";
import { ITempleElevatedAccess } from "contracts/interfaces/v2/access/ITempleElevatedAccess.sol";
import { ITreasuryPriceIndexOracle } from "contracts/interfaces/v2/ITreasuryPriceIndexOracle.sol";

/**
 * @title Treasury Reserves Vault (TRV)
 *
 * @notice Temple has various strategies which utilise the treasury funds to generate 
 * gains for token holders.
 * 
 * The maximum amount of funds allocated to each strategy is determined by governance, 
 * and then each strategy can borrow/repay as required (up to the cap).
 * 
 * When strategies borrow funds, they are issued `dToken`, an accruing debt token representing
 * the debt to the temple treasury. This is used to compare strategies performance, where
 * we can determine an equity value (assets - debt).
 *
 *    Strategies can borrow different types of tokens from the TRV, and are minted equivalent internal debt tokens eg:
 *      DAI => minted dUSD
 *      TEMPLE => minted dTEMPLE
 *      ETH => minted dETH
 *   
 *   Each of the dTokens are compounding at different risk free rates, eg:
 *      dUSD: At DAIs Savings Rate (DSR)
 *      dTEMPLE: 0% interest (no opportunity cost)
 *      dETH: ~avg LST rate
 *   
 *   And so each token which can be borrowed has separate config on how to pull/deposit idle funds.
 *   For example, this may be:
 *      DAI => DSR base strategy
 *      TEMPLE => direct Temple mint/burn 
 *      ETH => just hold in a vault
 */
interface ITreasuryReservesVault is ITempleElevatedAccess {
    event GlobalPausedSet(bool borrow, bool repay);
    event StrategyPausedSet(address indexed strategy, bool borrow, bool repay);

    event StrategyAdded(address indexed strategy, int256 underperformingEquityThreshold);
    event StrategyRemoved(address indexed strategy);
    event DebtCeilingUpdated(address indexed strategy, address indexed token, uint256 oldDebtCeiling, uint256 newDebtCeiling);
    event UnderperformingEquityThresholdUpdated(address indexed strategy, int256 oldThreshold, int256 newThreshold);
    event StrategyIsShuttingDownSet(address indexed strategy, bool isShuttingDown);
    event StrategyShutdownCreditAndDebt(address indexed strategy, address indexed token, uint256 outstandingCredit, uint256 outstandingDebt);
    event StrategyCreditAndDebtBalance(address indexed strategy, address indexed token, uint256 credit, uint256 debt);

    event BorrowTokenSet(address indexed token, address baseStrategy, uint256 baseStrategyWithdrawalBuffer, uint256 baseStrategyDepositThreshold, address dToken);
    event BorrowTokenRemoved(address indexed token);

    event Borrow(address indexed strategy, address indexed token, address indexed recipient, uint256 amount);
    event Repay(address indexed strategy, address indexed token, address indexed from, uint256 amount);

    event TpiOracleSet(address indexed tpiOracle);

    error BorrowTokenNotEnabled();
    error StrategyNotEnabled();

    error AlreadyEnabled();
    error BorrowPaused();
    error RepaysPaused();
    error StrategyIsShutdown();
    error DebtCeilingBreached(uint256 available, uint256 borrowAmount);
    error NotShuttingDown();

    struct BorrowTokenConfig {
        /**
         * @notice The base strategy used to hold idle treasury funds
         */
        ITempleBaseStrategy baseStrategy;

        /**
         * @notice A buffer of tokens are maintained in the TRV such that it doesn't have to churn through small base strategy
         * deposits/withdrawals. 
         * On a borrow if tokens need to be pulled from the base strategy, more than the requested amount is withdrawn such that
         * this extra buffer of tokens ends up in the TRV
         */
        uint256 baseStrategyWithdrawalBuffer;

        /**
         * @notice When repayments are made to the TRV, tokens are only deposited into the base strategy once this threshold is met.
         * The amount deposited will ensure that the `baseStrategyWithdrawalBuffer` amount remains in the TRV
         */
        uint256 baseStrategyDepositThreshold;

        /**
         * @notice The address of the internal debt token for this borrow token
         * @dev eg Temple => dTEMPLE, DAI => dUSD
         */
        ITempleDebtToken dToken;
    }
    
    struct StrategyConfig {
        /**
         * @notice Pause borrows
         */
        bool borrowPaused;

        /**
         * @notice Pause repayments
         */
        bool repaysPaused;

        /**
         * @notice Governance nominates this strategy to be shutdown.
         * The strategy executor then needs to unwind (may be manual) 
         * and the strategy needs to then call shutdown() when ready.
         */
        bool isShuttingDown;

        /**
         * @notice Each strategy will have a different threshold of expected performance.
         * This underperforming threshold is used for reporting to determine if the strategy is underperforming.
         */
        int256 underperformingEquityThreshold;

        /**
         * @notice The strategy can borrow up to this limit of accrued debt for each token.
         * The `dToken` is minted on any borrows 1:1 (which then accrues interest)
         * When a strategy repays, the `dToken` is burned 1:1
         */
        mapping(IERC20 => uint256) debtCeiling;

        /**
         * @notice The tokens that this strategy is allowed to borrow from TRV
         * @dev This must be one of the configured Borrow Tokens
         */
        mapping(IERC20 => bool) enabledBorrowTokens;
    }

    /**
     * @notice True if all borrows are paused for all strategies.
     */
    function globalBorrowPaused() external view returns (bool);

    /**
     * @notice True if all repayments are paused for all strategies.
     */
    function globalRepaysPaused() external view returns (bool);

    /**
     * @notice The configuration for a given strategy
     */
    function strategies(address strategy) external view returns (
        bool borrowPaused,
        bool repaysPaused,
        bool isShuttingDown,
        int256 underperformingEquityThreshold
    );

    /**
     * @notice The list of all strategies currently added to the TRV
     */
    function strategiesList() external view returns (address[] memory);

    /**
     * @notice The configuration for a given token which can be borrowed by strategies
     */
    function borrowTokens(IERC20 token) external view returns (
        ITempleBaseStrategy baseStrategy,
        uint256 baseStrategyWithdrawalBuffer,
        uint256 baseStrategyDepositThreshold,
        ITempleDebtToken dToken
    );

    /**
     * @notice The list of all tokens which can be borrowed by the TRV
     */
    function borrowTokensList() external view returns (address[] memory);

    /**
     * @notice When strategies repay a token which covers more than their dToken debt for the token
     * They receive credits. When they next need to borrow tokens this credit is used prior to
     * issuing more dTokens
     */
    function strategyTokenCredits(address strategy, IERC20 token) external view returns (uint256);

    /**
     * @notice The Treasury Price Index Oracle
     */
    function tpiOracle() external view returns (ITreasuryPriceIndexOracle);

    /**
     * @notice Set the Treasury Price Index (TPI) Oracle
     */
    function setTpiOracle(address tpiOracleAddress) external;

    /**
     * @notice The Treasury Price Index - the target price of the Treasury, in `stableToken` terms.
     */
    function treasuryPriceIndex() external view returns (uint96);

    /**
     * @notice API version to help with future integrations/migrations
     */
    function apiVersion() external pure returns (string memory);

    /**
     * @notice Set the borrow token configuration. 
     * @dev This can either add a new token or update an existing token.
     */
    function setBorrowToken(
        IERC20 token, 
        address baseStrategy,
        uint256 baseStrategyWithdrawalBuffer,
        uint256 baseStrategyDepositThreshold,
        address dToken
    ) external;

    /**
     * @notice Enable and/or disable tokens which a strategy can borrow from the (configured) TRV borrow tokens
     */
    function updateStrategyEnabledBorrowTokens(
        address strategy, 
        IERC20[] calldata enableBorrowTokens, 
        IERC20[] calldata disableBorrowTokens
    ) external;

    /**
     * @notice Remove the borrow token configuration. 
     */
    function removeBorrowToken(
        IERC20 token
    ) external;

    /**
     * @notice A helper to collate information about a given strategy for reporting purposes.
     * @dev Note the current assets may not be 100% up to date, as some strategies may need to checkpoint based
     * on the underlying strategy protocols (eg DSR for DAI would need to checkpoint to get the latest valuation).
     */
    function strategyDetails(address strategy) external view returns (
        string memory name,
        string memory version,
        bool borrowPaused,
        bool repaysPaused,
        bool isShuttingDown,
        int256 underperformingEquityThreshold,
        ITempleStrategy.AssetBalance[] memory debtCeiling
    );

    /**
     * @notice A strategy's current asset balances, any manual adjustments and the current debt
     * of the strategy.
     * 
     * This will be used to report equity performance: `sum($assetValue +- $manualAdj) - debt`
     * The conversion of each asset price into the stable token (eg DAI) will be done off-chain
     * along with formulating the union of asset balances and manual adjustments
     */
    function strategyBalanceSheet(address strategyAddr) external view returns (
        ITempleStrategy.AssetBalance[] memory assetBalances,
        ITempleStrategy.AssetBalanceDelta[] memory manualAdjustments, 
        ITempleStrategy.AssetBalance[] memory dTokenBalances,
        ITempleStrategy.AssetBalance[] memory dTokenCreditBalances
    );

    /**
     * @notice The current max debt ceiling that a strategy is allowed to borrow up to.
     */
    function strategyDebtCeiling(address strategy, IERC20 token) external view returns (uint256);
    
    /**
     * @notice Whether a token is enabled to be borrowed for a given strategy
     */
    function strategyEnabledBorrowTokens(address strategy, IERC20 token) external view returns (bool);

    /**
     * @notice The total available stables, both as a balance in this contract and
     * any available to withdraw from the baseStrategy
     */
    function totalAvailable(IERC20 token) external view returns (uint256);

    /**
     * @notice The amount remaining that a strategy can borrow for a given token
     * taking into account: the approved debt ceiling, current dToken debt, and any credits
     * @dev available == min(ceiling - debt + credit, 0)
     */
    function availableForStrategyToBorrow(
        address strategy, 
        IERC20 token
    ) external view returns (uint256);

    /**
     * @notice Pause all strategy borrow and repays
     */
    function setGlobalPaused(bool borrow, bool repays) external;

    /**
     * @notice Set whether borrows and repayments are paused for a given strategy.
     */
    function setStrategyPaused(address strategy, bool borrow, bool repays) external;

    /**
     * @notice Register a new strategy which can borrow tokens from Treasury Reserves
     */
    function addStrategy(
        address strategy, 
        int256 underperformingEquityThreshold,
        ITempleStrategy.AssetBalance[] calldata debtCeiling
    ) external;

    /**
     * @notice Update the debt ceiling for a given strategy
     */
    function setStrategyDebtCeiling(address strategy, IERC20 token, uint256 newDebtCeiling) external;

    /**
     * @notice Update the underperforming equity threshold.
     */
    function setStrategyUnderperformingThreshold(address strategy, int256 underperformingEquityThreshold) external;

    /**
     * @notice The first step in a two-phase shutdown. Executor first sets whether a strategy is slated for shutdown.
     * The strategy then needs to call shutdown as a separate call once ready.
     */
    function setStrategyIsShuttingDown(address strategy, bool isShuttingDown) external;

    /**
     * @notice The second step in a two-phase shutdown. A strategy (automated) or executor (manual) calls
     * to effect the shutdown. isShuttingDown must be true for the strategy first.
     * The strategy executor is responsible for unwinding all it's positions first and repaying the debt to the TRV.
     * All outstanding dToken debt is burned, leaving a net gain/loss of equity for the shutdown strategy.
     */
    function shutdown(address strategy) external;   

    /**
     * @notice A strategy calls to request more funding.
     * @dev This will revert if the strategy requests more stables than it's able to borrow.
     * `dToken` will be minted 1:1 for the amount of stables borrowed
     */
    function borrow(IERC20 token, uint256 borrowAmount, address recipient) external;

    /**
     * @notice A strategy calls to request the most funding it can.
     * @dev This will revert if the strategy requests more stables than it's able to borrow.
     * `dToken` will be minted 1:1 for the amount of stables borrowed
     */
    function borrowMax(IERC20 token, address recipient) external returns (uint256);

    /**
     * @notice A strategy calls to paydown it's debt
     * This will pull the stables, and will burn the equivalent amount of dToken from the strategy.
     */
    function repay(IERC20 token, uint256 repayAmount, address strategy) external;

    /**
     * @notice A strategy calls to paydown all of it's debt
     * This will pull the stables for the entire dToken balance of the strategy, and burn the dToken.
     */
    function repayAll(IERC20 token, address strategy) external returns (uint256 amountRepaid);
}
// File: contracts/interfaces/v2/strategies/ITempleBaseStrategy.sol



pragma solidity 0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (interfaces/v2/strategies/ITempleBaseStrategy.sol)

import { ITempleStrategy } from "contracts/interfaces/v2/strategies/ITempleStrategy.sol";

/**
 * @title Temple Base Strategy
 * @notice A special Temple Strategy which is eligable to transiently apply capital
 * into a very safe yield bearing protocol (eg DAI Savings Rate).
 * 
 * The Treasury Reserves Vault will have permission to pull back funds from this strategy
 * at any time, for example when another strategy wants to borrow funds.
 */
interface ITempleBaseStrategy {
    /**
     * @notice The latest checkpoint of each asset balance this strategy holds.
     *
     * @dev The asset value may be stale at any point in time, depending on the strategy. 
     * It may optionally implement `checkpointAssetBalances()` in order to update those balances.
     */
    function latestAssetBalances() external view returns (ITempleStrategy.AssetBalance[] memory assetBalances);

    /**
     * @notice The same as `borrowMax()` but for a pre-determined amount to borrow,
     * such that something upstream/off-chain can determine the amount.
     */
    function borrowAndDeposit(uint256 amount) external;

    /**
     * @notice When the TRV has a surplus of funds (over the configured buffer threshold)
     * it will transfer tokens to the base strategy, and call this function to apply
     * the new captial.
     */
    function trvDeposit(uint256 amount) external;

    /**
     * @notice The TRV is able to withdraw on demand in order to fund other strategies which 
     * wish to borrow from the TRV.
     * @dev It may withdraw less than requested if there isn't enough balance in the DSR.
     */
    function trvWithdraw(uint256 requestedAmount) external returns (uint256 amountWithdrawn);

}
// File: contracts/interfaces/v2/strategies/ITempleStrategy.sol



pragma solidity 0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (interfaces/v2/strategies/ITempleStrategy.sol)

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

import { ITreasuryReservesVault } from "contracts/interfaces/v2/ITreasuryReservesVault.sol";
import { ITempleElevatedAccess } from "contracts/interfaces/v2/access/ITempleElevatedAccess.sol";

/**
 * @title Temple Strategy
 * @notice The Temple Strategy is responsible for borrowing funds from the Treasury Reserve Vault
 * and generating positive equity from that capital.
 * 
 * When it borrows funds it is issued systematic debt (`dToken`) which accrues interest at a common base rate
 * plus a risk premium rate specific to this strategy, agreed and set by governance.
 *
 * The strategy reports it's assets (total available funds in investments)
 * in order to report the equity of the strategy -- ie a comparable performance metric across all strategy's.
 *
 * The Strategy Executor role is responsible for applying the capital within the strategy, and can borrow funds from
 * the TRV up to a cap (set by governance). Similarly the Executor is responsible for operations - borrow/repay/liquidate/etc.
 *
 * The strategy can be shutdown - first by Executors giving the go-ahead by setting it to `isShuttingDown` in the TRV
 * and then the Executor can either:
 *   a/ Graceful shutdown, where any liquidation can happen automatically
 *   b/ Force shutdown, where the Executor needs to handle any liquidations manually and send funds back to Treasury first.
 */
interface ITempleStrategy is ITempleElevatedAccess {
    struct AssetBalance {
        address asset;
        uint256 balance;
    }

    struct AssetBalanceDelta {
        address asset;
        int256 delta;
    }

    event TreasuryReservesVaultSet(address indexed trv);
    event Shutdown();
    event AssetBalancesCheckpoint(AssetBalance[] assetBalances);
    event ManualAdjustmentsSet(AssetBalanceDelta[] adjustments);
    event TokenAllowanceSet(address token, address spender, uint256 amount);
    
    error InvalidVersion(string expected, string actual);
    error OnlyTreasuryReserveVault(address caller);

    /**
     * @notice API version to help with future integrations/migrations
     */
    function apiVersion() external view returns (string memory);

    /**
     * @notice A human readable name of the strategy
     */
    function strategyName() external view returns (string memory);

    /**
     * @notice The version of this particular strategy
     */
    function strategyVersion() external view returns (string memory);

    /**
     * @notice The address of the treasury reserves vault.
     */
    function treasuryReservesVault() external view returns (ITreasuryReservesVault);

    /**
     * @notice Executors can set the address of the treasury reserves vault.
     */
    function setTreasuryReservesVault(address _trv) external;

    /**
     * @notice The Strategy Executor may set manual adjustments to asset balances
     * if they cannot be reported automatically - eg a staked position with no receipt token.
     */
    function setManualAdjustments(AssetBalanceDelta[] calldata adjustments) external;

    /**
     * @notice Get the set of manual asset balance deltas, set by the Strategy Executor.
     */
    function manualAdjustments() external view returns (AssetBalanceDelta[] memory adjustments);

    /**
     * @notice The latest checkpoint of each asset balance this strategy holds.
     *
     * @dev The asset value may be stale at any point in time, depending on the strategy. 
     * It may optionally implement `checkpointAssetBalances()` in order to update those balances.
     */
    function latestAssetBalances() external view returns (AssetBalance[] memory assetBalances);

    /**
     * @notice By default, we assume there is no checkpoint required for a strategy
     * In which case it would be identical to just calling `latestAssetBalances()`
     *
     * A strategy can override this if on-chain functions are required to run to force balance
     * updates first - eg checkpoint DSR
     */
    function checkpointAssetBalances() external returns (AssetBalance[] memory assetBalances);

    /**
     * @notice populate data required for shutdown - for example quote data.
     * This may/may not be required in order to do a shutdown. For example to avoid frontrunning/MEV
     * quotes to exit an LP position may need to be obtained off-chain prior to the actual shutdown.
     * Each strategy can abi encode params that it requires.
     * @dev Intentionally not a view - as some quotes require a non-view (eg Balancer)
     * The intention is for clients to call as 'static', like a view
     */
    function populateShutdownData(bytes calldata populateParamsData) external returns (bytes memory shutdownParamsData);

    /**
     * @notice The strategy executor can shutdown this strategy, only after Executors have
     * marked the strategy as `isShuttingDown` in the TRV.
     * This should handle all liquidations and send all funds back to the TRV, and will then call `TRV.shutdown()`
     * to apply the shutdown.
     * @dev Each strategy may require a different set of params to do the shutdown. It can abi encode/decode
     * that data off chain, or by first calling populateShutdownData()
     */
    function automatedShutdown(bytes calldata shutdownParamsData) external;

    /**
     * @notice Executors can recover any token from the strategy.
     */
    function recoverToken(address token, address to, uint256 amount) external;

    /**
     * @notice Executors can set the allowance of any token spend from the strategy
     */
    function setTokenAllowance(IERC20 token, address spender, uint256 amount) external;

    /**
     * @notice A hook which is called by the Treasury Reserves Vault when the debt ceiling
     * for this strategy is updated
     * @dev by default it's a no-op unless the strategy implements `_debtCeilingUpdated()`
     */
    function debtCeilingUpdated(IERC20 token, uint256 newDebtCeiling) external;
}
// File: contracts/v2/access/TempleElevatedAccess.sol



pragma solidity 0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (v2/access/TempleElevatedAccess.sol)

import { ITempleElevatedAccess } from "contracts/interfaces/v2/access/ITempleElevatedAccess.sol";
import { CommonEventsAndErrors } from "contracts/common/CommonEventsAndErrors.sol";

/**
 * @notice Inherit to add Executor and Rescuer roles for DAO elevated access.
 */ 
abstract contract TempleElevatedAccess is ITempleElevatedAccess {
    /**
     * @notice The address which is approved to execute emergency operations.
     */ 
    address public override rescuer;

    /**
     * @notice The address which is approved to execute normal operations on behalf of the DAO.
     */ 
    address public override executor;

    /**
     * @notice Explicit approval for an address to execute a function.
     * allowedCaller => function selector => true/false
     */
    mapping(address => mapping(bytes4 => bool)) public override explicitFunctionAccess;

    /**
     * @notice Under normal circumstances, rescuers don't have access to admin/operational functions.
     * However when rescue mode is enabled (by rescuers or executors), they claim the access rights.
     */
    bool public override inRescueMode;

    /// @dev Track proposed rescuer/executor
    address private _proposedNewRescuer;
    address private _proposedNewExecutor;

    constructor(address initialRescuer, address initialExecutor) {
        if (initialRescuer == address(0)) revert CommonEventsAndErrors.InvalidAddress();
        if (initialExecutor == address(0)) revert CommonEventsAndErrors.InvalidAddress();
        if (initialExecutor == initialRescuer) revert CommonEventsAndErrors.InvalidAddress();

        rescuer = initialRescuer;
        executor = initialExecutor;
    }

    /**
     * @notice Set the contract into or out of rescue mode.
     * Only the rescuers are allowed to set.
     */
    function setRescueMode(bool value) external override {
        if (msg.sender != rescuer) revert CommonEventsAndErrors.InvalidAccess();
        emit RescueModeSet(value);
        inRescueMode = value;
    }

    /**
     * @notice Proposes a new Rescuer.
     * Can only be called by the current rescuer.
     */
    function proposeNewRescuer(address account) external override {
        if (msg.sender != rescuer) revert CommonEventsAndErrors.InvalidAccess();
        if (account == address(0)) revert CommonEventsAndErrors.InvalidAddress();
        emit NewRescuerProposed(msg.sender, _proposedNewRescuer, account);
        _proposedNewRescuer = account;
    }

    /**
     * @notice Caller accepts the role as new Rescuer.
     * Can only be called by the proposed rescuer
     */
    function acceptRescuer() external override {
        if (msg.sender != _proposedNewRescuer) revert CommonEventsAndErrors.InvalidAccess();
        if (msg.sender == executor) revert CommonEventsAndErrors.InvalidAddress();

        emit NewRescuerAccepted(rescuer, msg.sender);
        rescuer = msg.sender;
        delete _proposedNewRescuer;
    }

    /**
     * @notice Proposes a new Executor.
     * Can only be called by the current executor or rescuer (if in resuce mode)
     */
    function proposeNewExecutor(address account) external override onlyElevatedAccess {
        if (account == address(0)) revert CommonEventsAndErrors.InvalidAddress();
        emit NewExecutorProposed(executor, _proposedNewExecutor, account);
        _proposedNewExecutor = account;
    }

    /**
     * @notice Caller accepts the role as new Executor.
     * Can only be called by the proposed executor
     */
    function acceptExecutor() external override {
        if (msg.sender != _proposedNewExecutor) revert CommonEventsAndErrors.InvalidAccess();
        if (msg.sender == rescuer) revert CommonEventsAndErrors.InvalidAddress();

        emit NewExecutorAccepted(executor, msg.sender);
        executor = msg.sender;
        delete _proposedNewExecutor;
    }

    /**
     * @notice Grant `allowedCaller` the rights to call the function selectors in the access list.
     * @dev fnSelector == bytes4(keccak256("fn(argType1,argType2,...)"))
     */
    function setExplicitAccess(address allowedCaller, ExplicitAccess[] calldata access) external override onlyElevatedAccess {
        if (allowedCaller == address(0)) revert CommonEventsAndErrors.InvalidAddress();
        uint256 _length = access.length;
        ExplicitAccess memory _access;
        for (uint256 i; i < _length; ++i) {
            _access = access[i];
            emit ExplicitAccessSet(allowedCaller, _access.fnSelector, _access.allowed);
            explicitFunctionAccess[allowedCaller][_access.fnSelector] = _access.allowed;
        }
    }

    function isElevatedAccess(address caller, bytes4 fnSelector) internal view returns (bool) {
        if (inRescueMode) {
            // If we're in rescue mode, then only the rescuers can call
            return caller == rescuer;
        } else if (caller == executor || explicitFunctionAccess[caller][fnSelector]) {
            // If we're not in rescue mode, the executor can call all functions
            // or the caller has been given explicit access on this function
            return true;
        }
        return false;
    }

    /**
     * @notice Under normal operations, only the executors are allowed to call.
     * If 'rescue mode' has been enabled, then only the rescuers are allowed to call.
     * @dev Important: Only for use when called from an *external* contract. 
     * If a function with this modifier is called internally then the `msg.sig` 
     * will still refer to the top level externally called function.
     */
    modifier onlyElevatedAccess() {
        if (!isElevatedAccess(msg.sender, msg.sig)) revert CommonEventsAndErrors.InvalidAccess();
        _;
    }

    /**
     * @notice Only the executors or rescuers can call.
     */
    modifier onlyInRescueMode() {
        if (!(inRescueMode && msg.sender == rescuer)) revert CommonEventsAndErrors.InvalidAccess();
        _;
    }

    modifier notInRescueMode() {
        if (inRescueMode) revert CommonEventsAndErrors.InvalidAccess();
        _;
    }
}

// File: contracts/v2/TreasuryReservesVault.sol



pragma solidity 0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (v2/TreasuryReservesVault.sol)

import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

import { ITreasuryReservesVault } from "contracts/interfaces/v2/ITreasuryReservesVault.sol";
import { ITreasuryPriceIndexOracle } from "contracts/interfaces/v2/ITreasuryPriceIndexOracle.sol";
import { ITempleStrategy, ITempleBaseStrategy } from "contracts/interfaces/v2/strategies/ITempleBaseStrategy.sol";
import { ITempleDebtToken } from "contracts/interfaces/v2/ITempleDebtToken.sol";

import { CommonEventsAndErrors } from "contracts/common/CommonEventsAndErrors.sol";
import { TempleElevatedAccess } from "contracts/v2/access/TempleElevatedAccess.sol";

/**
 * @title Treasury Reserves Vault (TRV)
 *
 * @notice Temple has various strategies which utilise the treasury funds to generate 
 * gains for token holders.
 * 
 * The maximum amount of funds allocated to each strategy is determined by governance, 
 * and then each strategy can borrow/repay as required (up to the cap).
 * 
 * When strategies borrow funds, they are issued `dToken`, an accruing debt token representing
 * the debt to the temple treasury. This is used to compare strategies performance, where
 * we can determine an equity value (assets - debt).
 *
 *    Strategies can borrow different types of tokens from the TRV, and are minted equivalent internal debt tokens eg:
 *      DAI => minted dUSD
 *      TEMPLE => minted dTEMPLE
 *      ETH => minted dETH
 *   
 *   Each of the dTokens are compounding at different risk free rates, eg:
 *      dUSD: At DAIs Savings Rate (DSR)
 *      dTEMPLE: 0% interest (no opportunity cost)
 *      dETH: ~avg LST rate
 *   
 *   And so each token which can be borrowed has separate config on how to pull/deposit idle funds.
 *   For example, this may be:
 *      DAI => DSR base strategy
 *      TEMPLE => direct Temple mint/burn 
 *      ETH => just hold in a vault
 */
contract TreasuryReservesVault is ITreasuryReservesVault, TempleElevatedAccess {
    using SafeERC20 for IERC20;
    using EnumerableSet for EnumerableSet.AddressSet;

    string private constant API_VERSION = "1.0.0";

    /**
     * @notice The configuration for a given strategy
     */
    mapping(address => StrategyConfig) public override strategies;

    /**
     * @notice The list of all strategies currently added to the TRV
     */
    EnumerableSet.AddressSet internal _strategySet;

    /**
     * @notice The configuration for a given token which can be borrowed by strategies
     */
    mapping(IERC20 => BorrowTokenConfig) public override borrowTokens;

    /**
     * @notice The list of all tokens which can be borrowed by the TRV
     */
    EnumerableSet.AddressSet internal _borrowTokenSet;

    /**
     * @notice A strategy may pay off more than it's entire debt token balance, 
     * in which case the TRV maintains a 'credit' balance which will contribute
     * towards realised gain/loss at full liquidation.
     * These credits are also a contributing factor to the strategy equity calculations.
     */
    mapping(address => mapping(IERC20 => uint256)) public override strategyTokenCredits;

    /**
     * @notice True if all borrows are paused for all strategies.
     */
    bool public override globalBorrowPaused;

    /**
     * @notice True if all repayments are paused for all strategies.
     */
    bool public override globalRepaysPaused;

    /**
     * @notice The Treasury Price Index Oracle
     */
    ITreasuryPriceIndexOracle public override tpiOracle;

    constructor(
        address _initialRescuer,
        address _initialExecutor,
        address _tpiOracle
    ) TempleElevatedAccess(_initialRescuer, _initialExecutor)
    {
        tpiOracle = ITreasuryPriceIndexOracle(_tpiOracle);
    }

    /**
     * @notice Set the borrow token configuration. 
     * @dev This can either add a new token or update an existing token.
     */
    function setBorrowToken(
        IERC20 token, 
        address baseStrategy,
        uint256 baseStrategyWithdrawalBuffer,
        uint256 baseStrategyDepositThreshold,
        address dToken
    ) external override onlyElevatedAccess {
        if (address(token) == address(0)) revert CommonEventsAndErrors.InvalidAddress();
        if (address(dToken) == address(0)) revert CommonEventsAndErrors.InvalidAddress();
        if (baseStrategyDepositThreshold < baseStrategyWithdrawalBuffer) revert CommonEventsAndErrors.InvalidParam();

        emit BorrowTokenSet(address(token), baseStrategy, baseStrategyWithdrawalBuffer, baseStrategyDepositThreshold, dToken);
        borrowTokens[token] = BorrowTokenConfig({
            baseStrategy: ITempleBaseStrategy(baseStrategy),
            baseStrategyWithdrawalBuffer: baseStrategyWithdrawalBuffer,
            baseStrategyDepositThreshold: baseStrategyDepositThreshold,
            dToken: ITempleDebtToken(dToken)
        });
        _borrowTokenSet.add(address(token));
    }

    /**
     * @notice Remove the borrow token configuration. 
     */
    function removeBorrowToken(
        IERC20 token
    ) external override onlyElevatedAccess {
        if (!_borrowTokenSet.contains(address(token))) revert BorrowTokenNotEnabled();
        emit BorrowTokenRemoved(address(token));
        delete borrowTokens[token];
        _borrowTokenSet.remove(address(token));
    }

    /**
     * @notice Set the Treasury Price Index (TPI) Oracle
     */
    function setTpiOracle(address newTpiOracle) external override onlyElevatedAccess {
        if (address(newTpiOracle) == address(0)) revert CommonEventsAndErrors.InvalidAddress();

        ITreasuryPriceIndexOracle _tpiOracle = ITreasuryPriceIndexOracle(newTpiOracle);
        if (_tpiOracle.treasuryPriceIndex() == 0) revert CommonEventsAndErrors.InvalidParam();

        emit TpiOracleSet(newTpiOracle);
        tpiOracle = _tpiOracle;
    }

    /**
     * @notice Pause all strategy borrow and repays
     */
    function setGlobalPaused(bool _pauseBorrow, bool _pauseRepays) external override onlyElevatedAccess {
        emit GlobalPausedSet(_pauseBorrow, _pauseRepays);
        globalBorrowPaused = _pauseBorrow;
        globalRepaysPaused = _pauseRepays;
    }

    /**
     * @dev sum(debt ceiling, credits) need to be checked that they don't overflow, on write.
     */
    function _checkAddOverflow(uint256 a, uint256 b) internal pure {
        a + b;
    }

    /**
     * @notice Register a new strategy which can borrow tokens from Treasury Reserves
     */
    function addStrategy(
        address strategy, 
        int256 underperformingEquityThreshold,
        ITempleStrategy.AssetBalance[] calldata debtCeiling
    ) external override onlyElevatedAccess {
        if (!_strategySet.add(strategy)) revert AlreadyEnabled();
        emit StrategyAdded(strategy, underperformingEquityThreshold);

        StrategyConfig storage strategyConfig = strategies[strategy];
        strategyConfig.underperformingEquityThreshold = underperformingEquityThreshold;

        ITempleStrategy.AssetBalance calldata _assetBalance;
        uint256 _length = debtCeiling.length;
        IERC20 _token;
        for (uint256 i; i < _length; ++i) {
            _assetBalance = debtCeiling[i];
            _token = IERC20(_assetBalance.asset);
            emit DebtCeilingUpdated(
                strategy, 
                address(_token), 
                strategyConfig.debtCeiling[_token], 
                _assetBalance.balance
            );

            if (!_borrowTokenSet.contains(address(_token))) revert BorrowTokenNotEnabled();
            strategyConfig.debtCeiling[_token] = _assetBalance.balance;
            strategyConfig.enabledBorrowTokens[_token] = true;
        }
    }

    /**
     * @notice Enable and/or disable tokens which a strategy can borrow from the (configured) TRV borrow tokens
     */
    function updateStrategyEnabledBorrowTokens(
        address strategy, 
        IERC20[] calldata enableBorrowTokens, 
        IERC20[] calldata disableBorrowTokens
    ) external override onlyElevatedAccess {
        StrategyConfig storage _strategyConfig = _getStrategyConfig(strategy);

        uint256 i;
        IERC20 token;
        uint256 _length = enableBorrowTokens.length;
        for (; i < _length; ++i) {
            token = enableBorrowTokens[i];
            if (!_borrowTokenSet.contains(address(token))) revert BorrowTokenNotEnabled();
            _strategyConfig.enabledBorrowTokens[token] = true;
        }

        _length = disableBorrowTokens.length;
        for (i = 0; i < _length; ++i) {
            // Don't need to validate that the borrow token is configured when disabling.
            _strategyConfig.enabledBorrowTokens[disableBorrowTokens[i]] = false;
        }
    }

    /**
     * @notice Set whether borrows and repayments are paused for a given strategy.
     */
    function setStrategyPaused(address strategy, bool pauseBorrow, bool pauseRepays) external override onlyElevatedAccess {
        StrategyConfig storage _strategyConfig = _getStrategyConfig(strategy);
        emit StrategyPausedSet(strategy, pauseBorrow, pauseRepays);
        _strategyConfig.borrowPaused = pauseBorrow;
        _strategyConfig.repaysPaused = pauseRepays;
    }

    /**
     * @notice Update the debt ceiling for a given strategy
     */
    function setStrategyDebtCeiling(address strategy, IERC20 token, uint256 newDebtCeiling) external override onlyElevatedAccess {
        if (!_borrowTokenSet.contains(address(token))) revert BorrowTokenNotEnabled();
        StrategyConfig storage _strategyConfig = _getStrategyConfig(strategy);
        if (!_strategyConfig.enabledBorrowTokens[token]) revert BorrowTokenNotEnabled();

        emit DebtCeilingUpdated(strategy, address(token), _strategyConfig.debtCeiling[token], newDebtCeiling);

        // Revert if the debt ceiling + credit overflows
        _checkAddOverflow(newDebtCeiling, strategyTokenCredits[strategy][token]);

        _strategyConfig.debtCeiling[token] = newDebtCeiling;

        ITempleStrategy(strategy).debtCeilingUpdated(token, newDebtCeiling);
    }

    /**
     * @notice Update the underperforming equity threshold.
     */
    function setStrategyUnderperformingThreshold(address strategy, int256 underperformingEquityThreshold) external override onlyElevatedAccess {
        StrategyConfig storage _strategyConfig = _getStrategyConfig(strategy);

        emit UnderperformingEquityThresholdUpdated(strategy, _strategyConfig.underperformingEquityThreshold, underperformingEquityThreshold);
        _strategyConfig.underperformingEquityThreshold = underperformingEquityThreshold;
    }
    
    /**
     * @notice The first step in a two-phase shutdown. Executor first sets whether a strategy is slated for shutdown.
     * The strategy then needs to call shutdown as a separate call once ready.
     */
    function setStrategyIsShuttingDown(address strategy, bool isShuttingDown) external override onlyElevatedAccess {
        StrategyConfig storage _strategyConfig = _getStrategyConfig(strategy);
        emit StrategyIsShuttingDownSet(strategy, isShuttingDown);
        _strategyConfig.isShuttingDown = isShuttingDown;
    }

    /**
     * @notice The second step in a two-phase shutdown. A strategy (automated) or executor (manual) calls
     * to effect the shutdown. isShuttingDown must be true for the strategy first.
     * The strategy executor is responsible for unwinding all it's positions first and sending stables to the TRV.
     * All outstanding dToken debt is burned, leaving a net gain/loss of equity for the shutdown strategy.
     */
    function shutdown(address strategy) external override {
        if (msg.sender != strategy && !isElevatedAccess(msg.sender, msg.sig)) revert CommonEventsAndErrors.InvalidAccess();

        StrategyConfig storage _strategyConfig = _getStrategyConfig(strategy);
        if (!_strategyConfig.isShuttingDown) revert NotShuttingDown();

        // Burn any remaining dToken debt.
        IERC20 _token;
        mapping(IERC20 => uint256) storage credits = strategyTokenCredits[strategy];
        uint256 _length = _borrowTokenSet.length();
        uint256 _outstandingDebt;
        for (uint256 i; i < _length; ++i) {
            _token = IERC20(_borrowTokenSet.at(i));
            _outstandingDebt = borrowTokens[_token].dToken.burnAll(strategy);
            emit StrategyShutdownCreditAndDebt({
                strategy: strategy,
                token: address(_token), 
                outstandingCredit: credits[_token], 
                outstandingDebt: _outstandingDebt
            });

            // Clean up the debtCeiling approvals for this borrow token.
            // Old borrow ceilings may not be removed, but not an issue
            delete _strategyConfig.debtCeiling[_token];
            delete _strategyConfig.enabledBorrowTokens[_token];
            delete credits[_token];
        }

        // Remove the strategy
        emit StrategyRemoved(strategy);

        // Required since the debt ceiling above is a nested mapping. 
        // It's been cleaned up as much as possible.
        // slither-disable-next-line mapping-deletion
        delete strategies[strategy];
        _strategySet.remove(strategy);
    }

    /**
     * @notice Recover any token from the TRV
     * @param token Token to recover
     * @param to Recipient address
     * @param amount Amount to recover
     */
    function recoverToken(address token, address to, uint256 amount) external onlyElevatedAccess {
        emit CommonEventsAndErrors.TokenRecovered(to, token, amount);
        IERC20(token).safeTransfer(to, amount);
    }

    /**
     * @notice A strategy calls to request more funding.
     * @dev This will revert if the strategy requests more stables than it's able to borrow.
     * `dToken` will be minted 1:1 for the amount of stables borrowed
     */
    function borrow(IERC20 token, uint256 borrowAmount, address recipient) external override {
        BorrowTokenConfig storage _tokenConfig = _getBorrowTokenConfig(token);
        StrategyConfig storage _strategyConfig = _getStrategyConfig(msg.sender);
        if (!_strategyConfig.enabledBorrowTokens[token]) revert BorrowTokenNotEnabled();
        uint256 _dTokenBalance = _tokenConfig.dToken.balanceOf(msg.sender);

        // This is not allowed to take the borrower over the debt ceiling
        uint256 available = _availableForStrategyToBorrow(msg.sender, _strategyConfig, token, _dTokenBalance);
        if (borrowAmount > available) revert DebtCeilingBreached(available, borrowAmount);

        _borrow(msg.sender, token, recipient, _tokenConfig, _strategyConfig, borrowAmount, _dTokenBalance);
    }

    /**
     * @notice A strategy calls to request the most funding it can.
     * @dev This will revert if the strategy requests more stables than it's able to borrow.
     * `dToken` will be minted 1:1 for the amount of stables borrowed
     */
    function borrowMax(IERC20 token, address recipient) external override returns (uint256 borrowedAmount) {
        BorrowTokenConfig storage _tokenConfig = _getBorrowTokenConfig(token);
        StrategyConfig storage _strategyConfig = _getStrategyConfig(msg.sender);
        if (!_strategyConfig.enabledBorrowTokens[token]) revert BorrowTokenNotEnabled();
        uint256 _dTokenBalance = _tokenConfig.dToken.balanceOf(msg.sender);
        borrowedAmount = _availableForStrategyToBorrow(msg.sender, _strategyConfig, token, _dTokenBalance);
        _borrow(msg.sender, token, recipient, _tokenConfig, _strategyConfig, borrowedAmount, _dTokenBalance);
    }

    /**
     * @notice A strategy calls to paydown it's debt
     * This will pull the stables, and will burn the equivalent amount of dToken from the strategy.
     */
    function repay(IERC20 token, uint256 repayAmount, address strategy) external override {
        BorrowTokenConfig storage _tokenConfig = _getBorrowTokenConfig(token);
        uint256 _dTokenBalance = _tokenConfig.dToken.balanceOf(strategy);
        _repay(msg.sender, strategy, token, _tokenConfig, repayAmount, _dTokenBalance);
        _depositIntoBaseStrategy(token, _tokenConfig, strategy);
    }

    /**
     * @notice A strategy calls to paydown all of it's debt
     * This will pull the stables for the entire dToken balance of the strategy, and burn the dToken.
     */
    function repayAll(IERC20 token, address strategy) external override returns (uint256 amountRepaid) {
        BorrowTokenConfig storage _tokenConfig = _getBorrowTokenConfig(token);
        amountRepaid = _tokenConfig.dToken.balanceOf(strategy);
        _repay(msg.sender, strategy, token, _tokenConfig, amountRepaid, amountRepaid);
        _depositIntoBaseStrategy(token, _tokenConfig, strategy);
    }

    /**
     * @notice Track the deployed version of this contract. 
     */
    function apiVersion() external pure override returns (string memory) {
        return API_VERSION;
    }

    /**
     * @notice The list of all tokens which can be borrowed by the TRV
     */
    function borrowTokensList() external view returns (address[] memory) {
        return _borrowTokenSet.values();
    }

    /**
     * @notice The Treasury Price Index - the target price of the Treasury, in `stableToken` terms.
     */
    function treasuryPriceIndex() external view override returns (uint96) {
        return tpiOracle.treasuryPriceIndex();
    }

    /**
     * @notice A helper to collate information about a given strategy for reporting purposes.
     * @dev Note the current assets may not be 100% up to date, as some strategies may need to checkpoint based
     * on the underlying strategy protocols (eg DSR for DAI would need to checkpoint to get the latest valuation).
     */
    function strategyDetails(address strategy) external override view returns (
        string memory name,
        string memory version,
        bool borrowPaused,
        bool repaysPaused,
        bool isShuttingDown,
        int256 underperformingEquityThreshold,
        ITempleStrategy.AssetBalance[] memory debtCeiling
    ) {
        ITempleStrategy _strategy = ITempleStrategy(strategy);
        StrategyConfig storage strategyConfig = _getStrategyConfig(strategy);
        name = _strategy.strategyName();
        version = _strategy.strategyVersion();
        borrowPaused = strategyConfig.borrowPaused;
        repaysPaused = strategyConfig.repaysPaused;
        isShuttingDown = strategyConfig.isShuttingDown;
        underperformingEquityThreshold = strategyConfig.underperformingEquityThreshold;

        address _token;
        uint256 _length = _borrowTokenSet.length();
        debtCeiling = new ITempleStrategy.AssetBalance[](_length);
        for (uint256 i; i < _length; ++i) {
            _token = _borrowTokenSet.at(i);
            debtCeiling[i] = ITempleStrategy.AssetBalance(_token, strategyConfig.debtCeiling[IERC20(_token)]);
        }
    }

    /**
     * @notice A strategy's current asset balances, any manual adjustments and the current debt
     * of the strategy.
     * 
     * This will be used to report equity performance: `sum($assetValue +- $manualAdj) - debt`
     * The conversion of each asset price into the stable token (eg DAI) will be done off-chain
     * along with formulating the union of asset balances and manual adjustments
     */
    function strategyBalanceSheet(address strategy) external override view returns (
        ITempleStrategy.AssetBalance[] memory assetBalances,
        ITempleStrategy.AssetBalanceDelta[] memory manualAdjustments, 
        ITempleStrategy.AssetBalance[] memory dTokenBalances,
        ITempleStrategy.AssetBalance[] memory dTokenCreditBalances
    ) {
        ITempleStrategy _strategy = ITempleStrategy(strategy);
        assetBalances = _strategy.latestAssetBalances();
        manualAdjustments = _strategy.manualAdjustments();

        uint256 _length = _borrowTokenSet.length();
        dTokenBalances = new ITempleStrategy.AssetBalance[](_length);
        dTokenCreditBalances = new ITempleStrategy.AssetBalance[](_length);
        address _token;
        mapping(IERC20 => uint256) storage _strategyTokenCredits = strategyTokenCredits[strategy];
        for (uint256 i; i < _length; ++i) {
            _token = _borrowTokenSet.at(i);
            dTokenBalances[i] = ITempleStrategy.AssetBalance(_token, borrowTokens[IERC20(_token)].dToken.balanceOf(strategy));
            dTokenCreditBalances[i] = ITempleStrategy.AssetBalance(_token, _strategyTokenCredits[IERC20(_token)]);
        }
    }

    /**
     * @notice The total available balance available to be borrowed, both as a balance in this contract and
     * any available to withdraw from the baseStrategy
     */
    function totalAvailable(IERC20 token) external override view returns (uint256) {
        BorrowTokenConfig storage _tokenConfig = _getBorrowTokenConfig(token);

        uint256 baseStrategyAvailable;
        ITempleBaseStrategy _baseStrategy = _tokenConfig.baseStrategy;

        // Pull the available from the baseStrategy if it's set.
        if (address(_baseStrategy) != address(0)) {
            ITempleStrategy.AssetBalance[] memory assetBalances = _baseStrategy.latestAssetBalances();

            // The base strategy will only have one Asset balance, which should be the requested token
            if (assetBalances.length != 1 || assetBalances[0].asset != address(token)) revert CommonEventsAndErrors.InvalidParam();
            baseStrategyAvailable = assetBalances[0].balance;
        }

        return token.balanceOf(address(this)) + baseStrategyAvailable;
    }

    /**
     * @notice The amount remaining that a strategy can borrow for a given token
     * taking into account: the approved debt ceiling, current dToken debt, and any credits
     * @dev available == min(ceiling - debt + credit, 0)
     */
    function availableForStrategyToBorrow(
        address strategy, 
        IERC20 token
    ) external override view returns (uint256) {
        BorrowTokenConfig storage _tokenConfig = _getBorrowTokenConfig(token);
        uint256 _dTokenBalance = _tokenConfig.dToken.balanceOf(strategy);
        StrategyConfig storage _strategyConfig = _getStrategyConfig(strategy);
        if (!_strategyConfig.enabledBorrowTokens[token]) revert BorrowTokenNotEnabled();
        return _availableForStrategyToBorrow(strategy, _strategyConfig, token, _dTokenBalance);
    }

    /**
     * @notice The list of all strategies currently added to the TRV
     */
    function strategiesList() external override view returns (address[] memory) {
        return _strategySet.values();
    }

    /**
     * @notice The current max debt ceiling that a strategy is allowed to borrow up to.
     */
    function strategyDebtCeiling(address strategy, IERC20 token) external override view returns (uint256) {
        if (!_borrowTokenSet.contains(address(token))) revert BorrowTokenNotEnabled();
        StrategyConfig storage _strategyConfig = _getStrategyConfig(strategy);
        if (!_strategyConfig.enabledBorrowTokens[token]) revert BorrowTokenNotEnabled();
        return _strategyConfig.debtCeiling[token];
    }

    /**
     * @notice Whether a token is enabled to be borrowed for a given strategy
     */
    function strategyEnabledBorrowTokens(address strategy, IERC20 token) external override view returns (bool) {
        return _getStrategyConfig(strategy).enabledBorrowTokens[token];
    }

    /// @dev Calculate the amount remaining that a strategy can borrow for a given token
    /// taking the allowed ceiling, current dToken debt, and any credits into consideration
    function _availableForStrategyToBorrow(
        address strategy,
        StrategyConfig storage strategyConfig,
        IERC20 token,
        uint256 dTokenBalance
    ) internal view returns (uint256) {
        // available == max(ceiling + credit - debt, 0)
        uint256 _ceiling = strategyConfig.debtCeiling[token];
        uint256 _credit = strategyTokenCredits[strategy][token];

        unchecked {
            // The sum of debtCeiling and credits cannot overflow as they're verified upon write.
            uint256 _totalAvailable = _ceiling + _credit;

            return _totalAvailable > dTokenBalance
                ? _totalAvailable - dTokenBalance
                : 0;
        } 
    }

    function _borrow(
        address strategy, 
        IERC20 token, 
        address recipient, 
        BorrowTokenConfig storage tokenConfig, 
        StrategyConfig storage strategyConfig, 
        uint256 borrowAmount,
        uint256 dTokenBalance
    ) internal {
        // slither-disable-next-line incorrect-equality
        if (borrowAmount == 0) revert CommonEventsAndErrors.ExpectedNonZero();
        if (globalBorrowPaused) revert BorrowPaused();
        if (strategyConfig.borrowPaused) revert BorrowPaused();
        if (strategyConfig.isShuttingDown) revert StrategyIsShutdown();

        emit Borrow(strategy, address(token), recipient, borrowAmount);

        // Mint any required dToken (after taking into consideration any credits)
        _mintDToken(strategy, token, tokenConfig, borrowAmount, dTokenBalance);

        // Source the token from the baseStrategy and send to the strategy.
        _withdrawFromBaseStrategy(strategy, token, tokenConfig, recipient, borrowAmount);
    }
    
    /**
     * @dev Pull tokens from the defined base strategy for this token config.
     * If the base strategy isn't set, or the requesting strategy IS the base strategy, then
     * this is a no-op. Token are sent directly from the TRV (this contract)
     */
    function _withdrawFromBaseStrategy(
        address strategy,
        IERC20 token, 
        BorrowTokenConfig storage tokenConfig, 
        address recipient, 
        uint256 amount
    ) internal {
        ITempleBaseStrategy _baseStrategy = tokenConfig.baseStrategy;
        address _baseStrategyAddr = address(_baseStrategy);
        uint256 _balance = token.balanceOf(address(this));
        if (_baseStrategyAddr != address(0) && _baseStrategyAddr != strategy) {
            // There may be idle tokens sitting idle in the TRV (ie these are not yet deposited into the baseStrategy)
            // So use these first, and only then fallback to pulling the rest from base strategy.
            uint256 _withdrawFromBaseStrategyAmount;
            unchecked {
                _withdrawFromBaseStrategyAmount = _balance > amount ? 0 : amount - _balance;
            }

            // Pull any remainder required from the base strategy.
            if (_withdrawFromBaseStrategyAmount > 0) {
                // So there aren't lots of small withdrawals, pull the amount required for this transaction
                // plus the threshold amount. Then future borrows don't need to withdraw from base every time.
                _withdrawFromBaseStrategyAmount += tokenConfig.baseStrategyWithdrawalBuffer;

                // The amount actually withdrawn may be less than requested
                // as it's capped to any actual remaining balance in the base strategy
                uint256 _withdrawnAmount = _baseStrategy.trvWithdraw(_withdrawFromBaseStrategyAmount);

                // Burn the dTokens from the base strategy.
                if (_withdrawnAmount > 0) {
                    _balance += _withdrawnAmount;

                    _burnDToken(
                        _baseStrategyAddr, 
                        strategies[_baseStrategyAddr], 
                        token, 
                        tokenConfig, 
                        _withdrawnAmount, 
                        tokenConfig.dToken.balanceOf(_baseStrategyAddr)
                    );
                }
            }
        }

        // The tokens are transferred straight from TRV, no withdrawal from the base strategy
        // Do an extra check that it at least has the requested amount in case the token isn't a standard ERC20 which already does a check.
        if (amount > _balance) revert CommonEventsAndErrors.InsufficientBalance(address(token), amount, _balance);

        // Finally send the stables.
        token.safeTransfer(recipient, amount);
    }

    /**
     * @dev Increase the dToken debt balance by `toMintAmount`. 
     * Use up any available 'token credits' first, and only mint the balance outstanding.
     */
    function _mintDToken(
        address strategy, 
        IERC20 token, 
        BorrowTokenConfig storage tokenConfig, 
        uint256 toMintAmount,
        uint256 dTokenBalance
    ) internal {
        mapping(IERC20 => uint256) storage _tokenCredits = strategyTokenCredits[strategy];
        uint256 _creditBalance = _tokenCredits[token];

        if (toMintAmount > _creditBalance) {
            // Mint new dToken for the amount not covered by prior credit balance credit
            uint256 _newDebt;
            unchecked {
                _newDebt = toMintAmount - _creditBalance;

                // Safe to be unchecked as it's also overflow checked within the dToken.mint() below
                dTokenBalance += _newDebt;
            }
            tokenConfig.dToken.mint(strategy, _newDebt);

            // The credit is now 0
            _tokenCredits[token] = _creditBalance = 0;
        } else {
            // Use up remaining credits
            unchecked {
              _creditBalance -= toMintAmount;
            }
            _tokenCredits[token] = _creditBalance;
        }

        emit StrategyCreditAndDebtBalance(strategy, address(token), _creditBalance, dTokenBalance);
    }

    /**
     * @dev Decrease the dToken debt balance by `toBurnAmount`. 
     * If there is no more dToken balance (ie fully repaid), then the strategy can go into 'credit'
     * which is just kept as state on this contract (no aToken is minted)
     */
    function _burnDToken(
        address strategy, 
        StrategyConfig storage strategyConfig,
        IERC20 token, 
        BorrowTokenConfig storage tokenConfig, 
        uint256 toBurnAmount,
        uint256 dTokenBalance
    ) internal {
        mapping(IERC20 => uint256) storage _tokenCredits = strategyTokenCredits[strategy];
        uint256 _creditBalance = _tokenCredits[token];

        uint256 _burnedAmount = tokenConfig.dToken.burn(strategy, toBurnAmount);
        uint256 _remaining;
        unchecked {
            dTokenBalance -= _burnedAmount;
            _remaining = toBurnAmount - _burnedAmount;
        }

        // If there is any remaining which is not burned, then the debt is now 0
        // Add the remainder as a credit.
        if (_remaining > 0) {
            unchecked {
                _creditBalance += _remaining;
            }

            // Revert if the debt ceiling + credit overflows
            _checkAddOverflow(strategyConfig.debtCeiling[token], _creditBalance);

            _tokenCredits[token] = _creditBalance;
        }

        emit StrategyCreditAndDebtBalance(strategy, address(token), _creditBalance, dTokenBalance);
    }

    function _getStrategyConfig(address strategy) internal view returns (StrategyConfig storage strategyConfig) {
        if (!_strategySet.contains(strategy)) revert StrategyNotEnabled();
        return strategies[strategy];
    }

    function _getBorrowTokenConfig(IERC20 token) internal view returns (BorrowTokenConfig storage tokenConfig) {
        if (!_borrowTokenSet.contains(address(token))) revert BorrowTokenNotEnabled();
        return borrowTokens[token];
    }

    /**
     * @dev Deposit any surplus token balances into the base strategy,
     * only when the token balance is greater than `baseStrategyDepositThreshold`
     * `baseStrategyWithdrawalBuffer` is always left for future withdrawals.
     * If the base strategy isn't set, or the requesting strategy IS the base strategy, then
     * don't do anything -- the tokens are just left in the TRV for future withdrawals.
     * 
     */
    function _depositIntoBaseStrategy(
        IERC20 token, 
        BorrowTokenConfig storage tokenConfig,
        address strategy
    ) internal {
        ITempleBaseStrategy _baseStrategy = tokenConfig.baseStrategy;
        if (address(_baseStrategy) != address(0) && address(_baseStrategy) != strategy) {
            uint256 _balance = token.balanceOf(address(this));

            // Do nothing if the balance isn't greater than the threshold
            if (_balance > tokenConfig.baseStrategyDepositThreshold) {
                unchecked {
                    _balance -= tokenConfig.baseStrategyWithdrawalBuffer;
                }

                // Mint new dTokens for this base strategy.
                uint256 _dTokenBalance = tokenConfig.dToken.balanceOf(address(_baseStrategy));
                _mintDToken(address(_baseStrategy), token, tokenConfig, _balance, _dTokenBalance);

                // Deposit the tokens into the base strategy
                token.safeTransfer(address(_baseStrategy), _balance);
                _baseStrategy.trvDeposit(_balance);
            }
        }
    }

    function _repay(
        address from, 
        address strategy, 
        IERC20 token, 
        BorrowTokenConfig storage tokenConfig, 
        uint256 repayAmount,
        uint256 dTokenBalance
    ) internal {
        // slither-disable-next-line incorrect-equality
        if (repayAmount == 0) revert CommonEventsAndErrors.ExpectedNonZero();
        if (globalRepaysPaused) revert RepaysPaused();
        StrategyConfig storage _strategyConfig = _getStrategyConfig(strategy);
        if (!_strategyConfig.enabledBorrowTokens[token]) revert BorrowTokenNotEnabled();

        if (_strategyConfig.repaysPaused) revert RepaysPaused();
        emit Repay(strategy, address(token), from, repayAmount);

        // Burn the dToken tokens / add credits
        _burnDToken(strategy, _strategyConfig, token, tokenConfig, repayAmount, dTokenBalance);

        // Pull the stables from the strategy.
        token.safeTransferFrom(from, address(this), repayAmount);
    }
}