// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* 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.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) 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 FailedInnerCall();
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @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 is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @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._positions[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 cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 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 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[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._positions[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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @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.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
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].
*
* CAUTION: See Security Considerations above.
*/
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IManager } from "./IManager.sol";
/**
* @title IHolding
* @dev Interface for the Holding Contract.
*/
interface IHolding {
// -- Events --
/**
* @notice Emitted when the emergency invoker is set.
*/
event EmergencyInvokerSet(address indexed oldInvoker, address indexed newInvoker);
// -- State variables --
/**
* @notice Returns the emergency invoker address.
* @return The address of the emergency invoker.
*/
function emergencyInvoker() external view returns (address);
/**
* @notice Contract that contains all the necessary configs of the protocol.
*/
function manager() external view returns (IManager);
// -- User specific methods --
/**
* @notice Sets the emergency invoker address for this holding.
*
* @notice Requirements:
* - The caller must be the owner of this holding.
*
* @notice Effects:
* - Updates the emergency invoker address to the provided value.
* - Emits an event to track the change for off-chain monitoring.
*
* @param _emergencyInvoker The address to set as the emergency invoker.
*/
function setEmergencyInvoker(
address _emergencyInvoker
) external;
/**
* @notice Approves an `_amount` of a specified token to be spent on behalf of the `msg.sender` by `_destination`.
*
* @notice Requirements:
* - The caller must be allowed to make this call.
*
* @notice Effects:
* - Safe approves the `_amount` of `_tokenAddress` to `_destination`.
*
* @param _tokenAddress Token user to be spent.
* @param _destination Destination address of the approval.
* @param _amount Withdrawal amount.
*/
function approve(address _tokenAddress, address _destination, uint256 _amount) external;
/**
* @notice Transfers `_token` from the holding contract to `_to` address.
*
* @notice Requirements:
* - The caller must be allowed.
*
* @notice Effects:
* - Safe transfers `_amount` of `_token` to `_to`.
*
* @param _token Token address.
* @param _to Address to move token to.
* @param _amount Transfer amount.
*/
function transfer(address _token, address _to, uint256 _amount) external;
/**
* @notice Executes generic call on the `contract`.
*
* @notice Requirements:
* - The caller must be allowed.
*
* @notice Effects:
* - Makes a low-level call to the `_contract` with the provided `_call` data.
*
* @param _contract The contract address for which the call will be invoked.
* @param _call Abi.encodeWithSignature data for the call.
*
* @return success Indicates if the call was successful.
* @return result The result returned by the call.
*/
function genericCall(
address _contract,
bytes calldata _call
) external payable returns (bool success, bytes memory result);
/**
* @notice Executes an emergency generic call on the specified contract.
*
* @notice Requirements:
* - The caller must be the designated emergency invoker.
* - The emergency invoker must be an allowed invoker in the Manager contract.
* - Protected by nonReentrant modifier to prevent reentrancy attacks.
*
* @notice Effects:
* - Makes a low-level call to the `_contract` with the provided `_call` data.
* - Forwards any ETH value sent with the transaction.
*
* @param _contract The contract address for which the call will be invoked.
* @param _call Abi.encodeWithSignature data for the call.
*
* @return success Indicates if the call was successful.
* @return result The result returned by the call.
*/
function emergencyGenericCall(
address _contract,
bytes calldata _call
) external payable returns (bool success, bytes memory result);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IManager } from "./IManager.sol";
/**
* @title IHoldingManager
* @notice Interface for the Holding Manager.
*/
interface IHoldingManager {
// -- Custom types --
/**
* @notice Data used for multiple borrow.
*/
struct BorrowData {
address token;
uint256 amount;
uint256 minJUsdAmountOut;
}
/**
* @notice Data used for multiple repay.
*/
struct RepayData {
address token;
uint256 amount;
}
// -- Events --
/**
* @notice Emitted when a new Holding is created.
* @param user The address of the user.
* @param holdingAddress The address of the created holding.
*/
event HoldingCreated(address indexed user, address indexed holdingAddress);
/**
* @notice Emitted when a deposit is made.
* @param holding The address of the holding.
* @param token The address of the token.
* @param amount The amount deposited.
*/
event Deposit(address indexed holding, address indexed token, uint256 amount);
/**
* @notice Emitted when a borrow action is performed.
* @param holding The address of the holding.
* @param token The address of the token.
* @param jUsdMinted The amount of jUSD minted.
* @param mintToUser Indicates if the amount is minted directly to the user.
*/
event Borrowed(address indexed holding, address indexed token, uint256 jUsdMinted, bool mintToUser);
/**
* @notice Emitted when a borrow event happens using multiple collateral types.
* @param holding The address of the holding.
* @param length The number of borrow operations.
* @param mintedToUser Indicates if the amounts are minted directly to the users.
*/
event BorrowedMultiple(address indexed holding, uint256 length, bool mintedToUser);
/**
* @notice Emitted when a repay action is performed.
* @param holding The address of the holding.
* @param token The address of the token.
* @param amount The amount repaid.
* @param repayFromUser Indicates if the repayment is from the user's wallet.
*/
event Repaid(address indexed holding, address indexed token, uint256 amount, bool repayFromUser);
/**
* @notice Emitted when a multiple repay operation happens.
* @param holding The address of the holding.
* @param length The number of repay operations.
* @param repaidFromUser Indicates if the repayments are from the users' wallets.
*/
event RepaidMultiple(address indexed holding, uint256 length, bool repaidFromUser);
/**
* @notice Emitted when the user wraps native coin.
* @param user The address of the user.
* @param amount The amount wrapped.
*/
event NativeCoinWrapped(address user, uint256 amount);
/**
* @notice Emitted when the user unwraps into native coin.
* @param user The address of the user.
* @param amount The amount unwrapped.
*/
event NativeCoinUnwrapped(address user, uint256 amount);
/**
* @notice Emitted when tokens are withdrawn from the holding.
* @param holding The address of the holding.
* @param token The address of the token.
* @param totalAmount The total amount withdrawn.
* @param feeAmount The fee amount.
*/
event Withdrawal(address indexed holding, address indexed token, uint256 totalAmount, uint256 feeAmount);
/**
* @notice Emitted when the contract receives ETH.
* @param from The address of the sender.
* @param amount The amount received.
*/
event Received(address indexed from, uint256 amount);
// -- State variables --
/**
* @notice Returns the holding for a user.
* @param _user The address of the user.
* @return The address of the holding.
*/
function userHolding(
address _user
) external view returns (address);
/**
* @notice Returns the user for a holding.
* @param holding The address of the holding.
* @return The address of the user.
*/
function holdingUser(
address holding
) external view returns (address);
/**
* @notice Returns true if the holding was created.
* @param _holding The address of the holding.
* @return True if the holding was created, false otherwise.
*/
function isHolding(
address _holding
) external view returns (bool);
/**
* @notice Returns the address of the holding implementation to be cloned from.
* @return The address of the current holding implementation.
*/
function holdingImplementationReference() external view returns (address);
/**
* @notice Contract that contains all the necessary configs of the protocol.
* @return The manager contract.
*/
function manager() external view returns (IManager);
/**
* @notice Returns the address of the WETH contract to save on `manager.WETH()` calls.
* @return The address of the WETH contract.
*/
function WETH() external view returns (address);
// -- User specific methods --
/**
* @notice Creates holding for the msg.sender.
*
* @notice Requirements:
* - `msg.sender` must not have a holding within the protocol, as only one holding is allowed per address.
* - Must be called from an EOA or whitelisted contract.
*
* @notice Effects:
* - Clones `holdingImplementationReference`.
* - Updates `userHolding` and `holdingUser` mappings with newly deployed `newHoldingAddress`.
* - Initiates the `newHolding`.
*
* @notice Emits:
* - `HoldingCreated` event indicating successful Holding creation.
*
* @return The address of the new holding.
*/
function createHolding() external returns (address);
/**
* @notice Deposits a whitelisted token into the Holding.
*
* @notice Requirements:
* - `_token` must be a whitelisted token.
* - `_amount` must be greater than zero.
* - `msg.sender` must have a valid holding.
*
* @param _token Token's address.
* @param _amount Amount to deposit.
*/
function deposit(address _token, uint256 _amount) external;
/**
* @notice Wraps native coin and deposits WETH into the holding.
*
* @dev This function must receive ETH in the transaction.
*
* @notice Requirements:
* - WETH must be whitelisted within protocol.
* - `msg.sender` must have a valid holding.
*/
function wrapAndDeposit() external payable;
/**
* @notice Withdraws a token from a Holding to a user.
*
* @notice Requirements:
* - `_token` must be a valid address.
* - `_amount` must be greater than zero.
* - `msg.sender` must have a valid holding.
*
* @notice Effects:
* - Withdraws the `_amount` of `_token` from the holding.
* - Transfers the `_amount` of `_token` to `msg.sender`.
* - Deducts any applicable fees.
*
* @param _token Token user wants to withdraw.
* @param _amount Withdrawal amount.
*/
function withdraw(address _token, uint256 _amount) external;
/**
* @notice Withdraws WETH from holding and unwraps it before sending it to the user.
*
* @notice Requirements:
* - `_amount` must be greater than zero.
* - `msg.sender` must have a valid holding.
* - The low level native coin transfers must succeed.
*
* @notice Effects
* - Transfers WETH from Holding address to address(this).
* - Unwraps the WETH into native coin.
* - Withdraws the `_amount` of WETH from the holding.
* - Deducts any applicable fees.
* - Transfers the unwrapped amount to `msg.sender`.
*
* @param _amount Withdrawal amount.
*/
function withdrawAndUnwrap(
uint256 _amount
) external;
/**
* @notice Borrows jUSD stablecoin to the user or to the holding contract.
*
* @dev The _amount does not account for the collateralization ratio and is meant to represent collateral's amount
* equivalent to jUSD's value the user wants to receive.
* @dev Ensure that the user will not become insolvent after borrowing before calling this function, as this
* function will revert ("3009") if the supplied `_amount` does not adhere to the collateralization ratio set in
* the registry for the specific collateral.
*
* @notice Requirements:
* - `msg.sender` must have a valid holding.
*
* @notice Effects:
* - Calls borrow function on `Stables Manager` Contract resulting in minting stablecoin based on the `_amount` of
* `_token` collateral.
*
* @notice Emits:
* - `Borrowed` event indicating successful borrow operation.
*
* @param _token Collateral token.
* @param _amount The collateral amount equivalent for borrowed jUSD.
* @param _mintDirectlyToUser If true, mints to user instead of holding.
* @param _minJUsdAmountOut The minimum amount of jUSD that is expected to be received.
*
* @return jUsdMinted The amount of jUSD minted.
*/
function borrow(
address _token,
uint256 _amount,
uint256 _minJUsdAmountOut,
bool _mintDirectlyToUser
) external returns (uint256 jUsdMinted);
/**
* @notice Borrows jUSD stablecoin to the user or to the holding contract using multiple collaterals.
*
* @dev This function will fail if any `amount` supplied in the `_data` does not adhere to the collateralization
* ratio set in the registry for the specific collateral. For instance, if the collateralization ratio is 200%, the
* maximum `_amount` that can be used to borrow is half of the user's free collateral, otherwise the user's holding
* will become insolvent after borrowing.
*
* @notice Requirements:
* - `msg.sender` must have a valid holding.
* - `_data` must contain at least one entry.
*
* @notice Effects:
* - Mints jUSD stablecoin for each entry in `_data` based on the collateral amounts.
*
* @notice Emits:
* - `Borrowed` event for each entry indicating successful borrow operation.
* - `BorrowedMultiple` event indicating successful multiple borrow operation.
*
* @param _data Struct containing data for each collateral type.
* @param _mintDirectlyToUser If true, mints to user instead of holding.
*
* @return The amount of jUSD minted for each collateral type.
*/
function borrowMultiple(
BorrowData[] calldata _data,
bool _mintDirectlyToUser
) external returns (uint256[] memory);
/**
* @notice Repays jUSD stablecoin debt from the user's or to the holding's address and frees up the locked
* collateral.
*
* @notice Requirements:
* - `msg.sender` must have a valid holding.
*
* @notice Effects:
* - Repays `_amount` jUSD stablecoin.
*
* @notice Emits:
* - `Repaid` event indicating successful debt repayment operation.
*
* @param _token Collateral token.
* @param _amount The repaid amount.
* @param _repayFromUser If true, Stables Manager will burn jUSD from the msg.sender, otherwise user's holding.
*/
function repay(address _token, uint256 _amount, bool _repayFromUser) external;
/**
* @notice Repays multiple jUSD stablecoin debts from the user's or to the holding's address and frees up the locked
* collateral assets.
*
* @notice Requirements:
* - `msg.sender` must have a valid holding.
* - `_data` must contain at least one entry.
*
* @notice Effects:
* - Repays stablecoin for each entry in `_data.
*
* @notice Emits:
* - `Repaid` event indicating successful debt repayment operation.
* - `RepaidMultiple` event indicating successful multiple repayment operation.
*
* @param _data Struct containing data for each collateral type.
* @param _repayFromUser If true, it will burn from user's wallet, otherwise from user's holding.
*/
function repayMultiple(RepayData[] calldata _data, bool _repayFromUser) external;
// -- Administration --
/**
* @notice Triggers stopped state.
*/
function pause() external;
/**
* @notice Returns to normal state.
*/
function unpause() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IManager } from "./IManager.sol";
/**
* @title IJigsawUSD
* @dev Interface for the Jigsaw Stablecoin Contract.
*/
interface IJigsawUSD is IERC20 {
/**
* @notice event emitted when the mint limit is updated
*/
event MintLimitUpdated(uint256 oldLimit, uint256 newLimit);
/**
* @notice Contract that contains all the necessary configs of the protocol.
* @return The manager contract.
*/
function manager() external view returns (IManager);
/**
* @notice Returns the max mint limit.
*/
function mintLimit() external view returns (uint256);
/**
* @notice Sets the maximum mintable amount.
*
* @notice Requirements:
* - Must be called by the contract owner.
*
* @notice Effects:
* - Updates the `mintLimit` state variable.
*
* @notice Emits:
* - `MintLimitUpdated` event indicating mint limit update operation.
* @param _limit The new mint limit.
*/
function updateMintLimit(
uint256 _limit
) external;
/**
* @notice Mints tokens.
*
* @notice Requirements:
* - Must be called by the Stables Manager Contract
* .
* @notice Effects:
* - Mints the specified amount of tokens to the given address.
*
* @param _to Address of the user receiving minted tokens.
* @param _amount The amount to be minted.
*/
function mint(address _to, uint256 _amount) external;
/**
* @notice Burns tokens from the `msg.sender`.
*
* @notice Requirements:
* - Must be called by the token holder.
*
* @notice Effects:
* - Burns the specified amount of tokens from the caller's balance.
*
* @param _amount The amount of tokens to be burnt.
*/
function burn(
uint256 _amount
) external;
/**
* @notice Burns tokens from an address.
*
* - Must be called by the Stables Manager Contract
*
* @notice Effects: Burns the specified amount of tokens from the specified address.
*
* @param _user The user to burn it from.
* @param _amount The amount of tokens to be burnt.
*/
function burnFrom(address _user, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IOracle } from "../oracle/IOracle.sol";
/**
* @title IManager.
* @dev Interface for the Manager Contract.
*/
interface IManager {
// -- Events --
/**
* @notice Emitted when a new contract is whitelisted.
* @param contractAddress The address of the contract that is whitelisted.
*/
event ContractWhitelisted(address indexed contractAddress);
/**
* @notice Emitted when a contract is removed from the whitelist.
* @param contractAddress The address of the contract that is removed from the whitelist.
*/
event ContractBlacklisted(address indexed contractAddress);
/**
* @notice Emitted when a new token is whitelisted.
* @param token The address of the token that is whitelisted.
*/
event TokenWhitelisted(address indexed token);
/**
* @notice Emitted when a new token is removed from the whitelist.
* @param token The address of the token that is removed from the whitelist.
*/
event TokenRemoved(address indexed token);
/**
* @notice Emitted when a withdrawable token is added.
* @param token The address of the withdrawable token.
*/
event WithdrawableTokenAdded(address indexed token);
/**
* @notice Emitted when a withdrawable token is removed.
* @param token The address of the withdrawable token.
*/
event WithdrawableTokenRemoved(address indexed token);
/**
* @notice Emitted when invoker is updated.
* @param component The address of the invoker component.
* @param allowed Boolean indicating if the invoker is allowed or not.
*/
event InvokerUpdated(address indexed component, bool allowed);
/**
* @notice Emitted when the holding manager is set.
* @param oldAddress The previous address of the holding manager.
* @param newAddress The new address of the holding manager.
*/
event HoldingManagerUpdated(address indexed oldAddress, address indexed newAddress);
/**
* @notice Emitted when a new liquidation manager is requested.
* @param oldAddress The previous address of the liquidation manager.
* @param newAddress The new address of the liquidation manager.
*/
event NewLiquidationManagerRequested(address indexed oldAddress, address indexed newAddress);
/**
* @notice Emitted when the liquidation manager is set.
* @param oldAddress The previous address of the liquidation manager.
* @param newAddress The new address of the liquidation manager.
*/
event LiquidationManagerUpdated(address indexed oldAddress, address indexed newAddress);
/**
* @notice Emitted when the stablecoin manager is set.
* @param oldAddress The previous address of the stablecoin manager.
* @param newAddress The new address of the stablecoin manager.
*/
event StablecoinManagerUpdated(address indexed oldAddress, address indexed newAddress);
/**
* @notice Emitted when the strategy manager is set.
* @param oldAddress The previous address of the strategy manager.
* @param newAddress The new address of the strategy manager.
*/
event StrategyManagerUpdated(address indexed oldAddress, address indexed newAddress);
/**
* @notice Emitted when a new swap manager is requested.
* @param oldAddress The previous address of the swap manager.
* @param newAddress The new address of the swap manager.
*/
event NewSwapManagerRequested(address indexed oldAddress, address indexed newAddress);
/**
* @notice Emitted when the swap manager is set.
* @param oldAddress The previous address of the swap manager.
* @param newAddress The new address of the swap manager.
*/
event SwapManagerUpdated(address indexed oldAddress, address indexed newAddress);
/**
* @notice Emitted when the default fee is updated.
* @param oldFee The previous fee.
* @param newFee The new fee.
*/
event PerformanceFeeUpdated(uint256 indexed oldFee, uint256 indexed newFee);
/**
* @notice Emitted when the withdraw fee is updated.
* @param oldFee The previous withdraw fee.
* @param newFee The new withdraw fee.
*/
event WithdrawalFeeUpdated(uint256 indexed oldFee, uint256 indexed newFee);
/**
* @notice Emitted when the liquidator's bonus is updated.
* @param oldAmount The previous amount of the liquidator's bonus.
* @param newAmount The new amount of the liquidator's bonus.
*/
event LiquidatorBonusUpdated(uint256 oldAmount, uint256 newAmount);
/**
* @notice Emitted when the fee address is changed.
* @param oldAddress The previous fee address.
* @param newAddress The new fee address.
*/
event FeeAddressUpdated(address indexed oldAddress, address indexed newAddress);
/**
* @notice Emitted when the receipt token factory is updated.
* @param oldAddress The previous address of the receipt token factory.
* @param newAddress The new address of the receipt token factory.
*/
event ReceiptTokenFactoryUpdated(address indexed oldAddress, address indexed newAddress);
/**
* @notice Emitted when the liquidity gauge factory is updated.
* @param oldAddress The previous address of the liquidity gauge factory.
* @param newAddress The new address of the liquidity gauge factory.
*/
event LiquidityGaugeFactoryUpdated(address indexed oldAddress, address indexed newAddress);
/**
* @notice Emitted when new oracle is requested.
* @param newOracle The address of the new oracle.
*/
event NewOracleRequested(address newOracle);
/**
* @notice Emitted when the oracle is updated.
* @param oldOracle The address of the old oracle.
* @param newOracle The address of the new oracle.
*/
event OracleUpdated(address indexed oldOracle, address indexed newOracle);
/**
* @notice Emitted when oracle data is updated.
* @param oldData The address of the old oracle data.
* @param newData The address of the new oracle data.
*/
event OracleDataUpdated(bytes indexed oldData, bytes indexed newData);
/**
* @notice Emitted when a new timelock amount is requested.
* @param oldVal The previous timelock amount.
* @param newVal The new timelock amount.
*/
event TimelockAmountUpdateRequested(uint256 oldVal, uint256 newVal);
/**
* @notice Emitted when timelock amount is updated.
* @param oldVal The previous timelock amount.
* @param newVal The new timelock amount.
*/
event TimelockAmountUpdated(uint256 oldVal, uint256 newVal);
// -- Mappings --
/**
* @notice Returns true/false for contracts' whitelist status.
* @param _contract The address of the contract.
*/
function isContractWhitelisted(
address _contract
) external view returns (bool);
/**
* @notice Returns true if token is whitelisted.
* @param _token The address of the token.
*/
function isTokenWhitelisted(
address _token
) external view returns (bool);
/**
* @notice Returns true if the token can be withdrawn from a holding.
* @param _token The address of the token.
*/
function isTokenWithdrawable(
address _token
) external view returns (bool);
/**
* @notice Returns true if caller is allowed invoker.
* @param _invoker The address of the invoker.
*/
function allowedInvokers(
address _invoker
) external view returns (bool);
// -- Essential tokens --
/**
* @notice WETH address.
*/
function WETH() external view returns (address);
// -- Protocol's stablecoin oracle config --
/**
* @notice Oracle contract associated with protocol's stablecoin.
*/
function jUsdOracle() external view returns (IOracle);
/**
* @notice Extra oracle data if needed.
*/
function oracleData() external view returns (bytes calldata);
// -- Managers --
/**
* @notice Returns the address of the HoldingManager Contract.
*/
function holdingManager() external view returns (address);
/**
* @notice Returns the address of the LiquidationManager Contract.
*/
function liquidationManager() external view returns (address);
/**
* @notice Returns the address of the StablesManager Contract.
*/
function stablesManager() external view returns (address);
/**
* @notice Returns the address of the StrategyManager Contract.
*/
function strategyManager() external view returns (address);
/**
* @notice Returns the address of the SwapManager Contract.
*/
function swapManager() external view returns (address);
// -- Fees --
/**
* @notice Returns the default performance fee.
* @dev Uses 2 decimal precision, where 1% is represented as 100.
*/
function performanceFee() external view returns (uint256);
/**
* @notice Returns the maximum performance fee.
* @dev Uses 2 decimal precision, where 1% is represented as 100.
*/
function MAX_PERFORMANCE_FEE() external view returns (uint256);
/**
* @notice Fee for withdrawing from a holding.
* @dev Uses 2 decimal precision, where 1% is represented as 100.
*/
function withdrawalFee() external view returns (uint256);
/**
* @notice Returns the maximum withdrawal fee.
* @dev Uses 2 decimal precision, where 1% is represented as 100.
*/
function MAX_WITHDRAWAL_FEE() external view returns (uint256);
/**
* @notice Returns the fee address, where all the fees are collected.
*/
function feeAddress() external view returns (address);
// -- Factories --
/**
* @notice Returns the address of the ReceiptTokenFactory.
*/
function receiptTokenFactory() external view returns (address);
// -- Utility values --
/**
* @notice Minimum allowed jUSD debt amount for a holding to ensure successful liquidation.
*/
function minDebtAmount() external view returns (uint256);
/**
* @notice Returns the collateral rate precision.
* @dev Should be less than exchange rate precision due to optimization in math.
*/
function PRECISION() external view returns (uint256);
/**
* @notice Returns the exchange rate precision.
*/
function EXCHANGE_RATE_PRECISION() external view returns (uint256);
/**
* @notice Timelock amount in seconds for changing the oracle data.
*/
function timelockAmount() external view returns (uint256);
/**
* @notice Returns the old timelock value for delayed timelock update.
*/
function oldTimelock() external view returns (uint256);
/**
* @notice Returns the new timelock value for delayed timelock update.
*/
function newTimelock() external view returns (uint256);
/**
* @notice Returns the timestamp when the new timelock was requested.
*/
function newTimelockTimestamp() external view returns (uint256);
/**
* @notice Returns the new oracle address for delayed oracle update.
*/
function newOracle() external view returns (address);
/**
* @notice Returns the timestamp when the new oracle was requested.
*/
function newOracleTimestamp() external view returns (uint256);
/**
* @notice Returns the new swap manager address for delayed swap manager update.
*/
function newSwapManager() external view returns (address);
/**
* @notice Returns the timestamp when the new swap manager was requested.
*/
function newSwapManagerTimestamp() external view returns (uint256);
/**
* @notice Returns the new liquidation manager address for delayed liquidation manager update.
*/
function newLiquidationManager() external view returns (address);
/**
* @notice Returns the timestamp when the new liquidation manager was requested.
*/
function newLiquidationManagerTimestamp() external view returns (uint256);
// -- Setters --
/**
* @notice Whitelists a contract.
*
* @notice Requirements:
* - `_contract` must not be whitelisted.
*
* @notice Effects:
* - Updates the `isContractWhitelisted` mapping.
*
* @notice Emits:
* - `ContractWhitelisted` event indicating successful contract whitelist operation.
*
* @param _contract The address of the contract to be whitelisted.
*/
function whitelistContract(
address _contract
) external;
/**
* @notice Blacklists a contract.
*
* @notice Requirements:
* - `_contract` must be whitelisted.
*
* @notice Effects:
* - Updates the `isContractWhitelisted` mapping.
*
* @notice Emits:
* - `ContractBlacklisted` event indicating successful contract blacklist operation.
*
* @param _contract The address of the contract to be blacklisted.
*/
function blacklistContract(
address _contract
) external;
/**
* @notice Whitelists a token.
*
* @notice Requirements:
* - `_token` must not be whitelisted.
*
* @notice Effects:
* - Updates the `isTokenWhitelisted` mapping.
*
* @notice Emits:
* - `TokenWhitelisted` event indicating successful token whitelist operation.
*
* @param _token The address of the token to be whitelisted.
*/
function whitelistToken(
address _token
) external;
/**
* @notice Removes a token from whitelist.
*
* @notice Requirements:
* - `_token` must be whitelisted.
*
* @notice Effects:
* - Updates the `isTokenWhitelisted` mapping.
*
* @notice Emits:
* - `TokenRemoved` event indicating successful token removal operation.
*
* @param _token The address of the token to be whitelisted.
*/
function removeToken(
address _token
) external;
/**
* @notice Registers the `_token` as withdrawable.
*
* @notice Requirements:
* - `msg.sender` must be owner or `strategyManager`.
* - `_token` must not be withdrawable.
*
* @notice Effects:
* - Updates the `isTokenWithdrawable` mapping.
*
* @notice Emits:
* - `WithdrawableTokenAdded` event indicating successful withdrawable token addition operation.
*
* @param _token The address of the token to be added as withdrawable.
*/
function addWithdrawableToken(
address _token
) external;
/**
* @notice Unregisters the `_token` as withdrawable.
*
* @notice Requirements:
* - `_token` must be withdrawable.
*
* @notice Effects:
* - Updates the `isTokenWithdrawable` mapping.
*
* @notice Emits:
* - `WithdrawableTokenRemoved` event indicating successful withdrawable token removal operation.
*
* @param _token The address of the token to be removed as withdrawable.
*/
function removeWithdrawableToken(
address _token
) external;
/**
* @notice Sets invoker as allowed or forbidden.
*
* @notice Effects:
* - Updates the `allowedInvokers` mapping.
*
* @notice Emits:
* - `InvokerUpdated` event indicating successful invoker update operation.
*
* @param _component Invoker's address.
* @param _allowed True/false.
*/
function updateInvoker(address _component, bool _allowed) external;
/**
* @notice Sets the Holding Manager Contract's address.
*
* @notice Requirements:
* - `_val` must be different from previous `holdingManager` address.
*
* @notice Effects:
* - Updates the `holdingManager` state variable.
*
* @notice Emits:
* - `HoldingManagerUpdated` event indicating the successful setting of the Holding Manager's address.
*
* @param _val The holding manager's address.
*/
function setHoldingManager(
address _val
) external;
/**
* @notice Sets the Liquidation Manager Contract's address.
*
* @notice Requirements:
* - Can only be called once.
* - `_val` must be non-zero address.
*
* @notice Effects:
* - Updates the `liquidationManager` state variable.
*
* @notice Emits:
* - `LiquidationManagerUpdated` event indicating the successful setting of the Liquidation Manager's address.
*
* @param _val The liquidation manager's address.
*/
function setLiquidationManager(
address _val
) external;
/**
* @notice Initiates the process to update the Liquidation Manager Contract's address.
*
* @notice Requirements:
* - `_val` must be non-zero address.
* - `_val` must be different from previous `liquidationManager` address.
*
* @notice Effects:
* - Updates the the `_newLiquidationManager` state variable.
* - Updates the the `_newLiquidationManagerTimestamp` state variable.
*
* @notice Emits:
* - `LiquidationManagerUpdateRequested` event indicating successful liquidation manager change request.
*
* @param _val The new liquidation manager's address.
*/
function requestNewLiquidationManager(
address _val
) external;
/**
* @notice Sets the Liquidation Manager Contract's address.
*
* @notice Requirements:
* - `_val` must be different from previous `liquidationManager` address.
* - Timelock must expire.
*
* @notice Effects:
* - Updates the `liquidationManager` state variable.
* - Updates the the `_newLiquidationManager` state variable.
* - Updates the the `_newLiquidationManagerTimestamp` state variable.
*
* @notice Emits:
* - `LiquidationManagerUpdated` event indicating the successful setting of the Liquidation Manager's address.
*/
function acceptNewLiquidationManager() external;
/**
* @notice Sets the Stablecoin Manager Contract's address.
*
* @notice Requirements:
* - `_val` must be different from previous `stablesManager` address.
*
* @notice Effects:
* - Updates the `stablesManager` state variable.
*
* @notice Emits:
* - `StablecoinManagerUpdated` event indicating the successful setting of the Stablecoin Manager's address.
*
* @param _val The Stablecoin manager's address.
*/
function setStablecoinManager(
address _val
) external;
/**
* @notice Sets the Strategy Manager Contract's address.
*
* @notice Requirements:
* - `_val` must be different from previous `strategyManager` address.
*
* @notice Effects:
* - Updates the `strategyManager` state variable.
*
* @notice Emits:
* - `StrategyManagerUpdated` event indicating the successful setting of the Strategy Manager's address.
*
* @param _val The Strategy manager's address.
*/
function setStrategyManager(
address _val
) external;
/**
* @notice Sets the Swap Manager Contract's address.
*
* @notice Requirements:
* - Can only be called once.
* - `_val` must be non-zero address.
*
* @notice Effects:
* - Updates the `swapManager` state variable.
*
* @notice Emits:
* - `SwapManagerUpdated` event indicating the successful setting of the Swap Manager's address.
*
* @param _val The Swap manager's address.
*/
function setSwapManager(
address _val
) external;
/**
* @notice Initiates the process to update the Swap Manager Contract's address.
*
* @notice Requirements:
* - `_val` must be non-zero address.
* - `_val` must be different from previous `swapManager` address.
*
* @notice Effects:
* - Updates the the `_newSwapManager` state variable.
* - Updates the the `_newSwapManagerTimestamp` state variable.
*
* @notice Emits:
* - `NewSwapManagerRequested` event indicating successful swap manager change request.
*
* @param _val The new swap manager's address.
*/
function requestNewSwapManager(
address _val
) external;
/**
* @notice Updates the Swap Manager Contract .
*
* @notice Requirements:
* - Timelock must expire.
*
* @notice Effects:
* - Updates the `swapManager` state variable.
* - Resets `_newSwapManager` to address(0).
* - Resets `_newSwapManagerTimestamp` to 0.
*
* @notice Emits:
* - `SwapManagerUpdated` event indicating the successful setting of the Swap Manager's address.
*/
function acceptNewSwapManager() external;
/**
* @notice Sets the performance fee.
*
* @notice Requirements:
* - `_val` must be smaller than `FEE_FACTOR` to avoid wrong computations.
*
* @notice Effects:
* - Updates the `performanceFee` state variable.
*
* @notice Emits:
* - `PerformanceFeeUpdated` event indicating successful performance fee update operation.
*
* @dev `_val` uses 2 decimal precision, where 1% is represented as 100.
*
* @param _val The new performance fee value.
*/
function setPerformanceFee(
uint256 _val
) external;
/**
* @notice Sets the withdrawal fee.
*
* @notice Requirements:
* - `_val` must be smaller than `FEE_FACTOR` to avoid wrong computations.
*
* @notice Effects:
* - Updates the `withdrawalFee` state variable.
*
* @notice Emits:
* - `WithdrawalFeeUpdated` event indicating successful withdrawal fee update operation.
*
* @dev `_val` uses 2 decimal precision, where 1% is represented as 100.
*
* @param _val The new withdrawal fee value.
*/
function setWithdrawalFee(
uint256 _val
) external;
/**
* @notice Sets the global fee address.
*
* @notice Requirements:
* - `_val` must be different from previous `holdingManager` address.
*
* @notice Effects:
* - Updates the `feeAddress` state variable.
*
* @notice Emits:
* - `FeeAddressUpdated` event indicating successful setting of the global fee address.
*
* @param _val The new fee address.
*/
function setFeeAddress(
address _val
) external;
/**
* @notice Sets the receipt token factory's address.
*
* @notice Requirements:
* - `_val` must be different from previous `receiptTokenFactory` address.
*
* @notice Effects:
* - Updates the `receiptTokenFactory` state variable.
*
* @notice Emits:
* - `ReceiptTokenFactoryUpdated` event indicating successful setting of the `receiptTokenFactory` address.
*
* @param _factory Receipt token factory's address.
*/
function setReceiptTokenFactory(
address _factory
) external;
/**
* @notice Registers jUSD's oracle change request.
*
* @notice Requirements:
* - Contract must not be in active change.
*
* @notice Effects:
* - Updates the the `_isActiveChange` state variable.
* - Updates the the `_newOracle` state variable.
* - Updates the the `_newOracleTimestamp` state variable.
*
* @notice Emits:
* - `NewOracleRequested` event indicating successful jUSD's oracle change request.
*
* @param _oracle Liquidity gauge factory's address.
*/
function requestNewJUsdOracle(
address _oracle
) external;
/**
* @notice Updates jUSD's oracle.
*
* @notice Requirements:
* - Contract must be in active change.
* - Timelock must expire.
*
* @notice Effects:
* - Updates the the `jUsdOracle` state variable.
* - Updates the the `_isActiveChange` state variable.
* - Updates the the `_newOracle` state variable.
* - Updates the the `_newOracleTimestamp` state variable.
*
* @notice Emits:
* - `OracleUpdated` event indicating successful jUSD's oracle change.
*/
function acceptNewJUsdOracle() external;
/**
* @notice Updates the jUSD's oracle data.
*
* @notice Requirements:
* - `_newOracleData` must be different from previous `oracleData`.
*
* @notice Effects:
* - Updates the `oracleData` state variable.
*
* @notice Emits:
* - `OracleDataUpdated` event indicating successful update of the oracle Data.
*
* @param _newOracleData New data used for jUSD's oracle data.
*/
function setJUsdOracleData(
bytes calldata _newOracleData
) external;
/**
* @notice Sets the minimum debt amount.
*
* @notice Requirements:
* - `_minDebtAmount` must be greater than zero.
* - `_minDebtAmount` must be different from previous `minDebtAmount`.
*
* @param _minDebtAmount The new minimum debt amount.
*/
function setMinDebtAmount(
uint256 _minDebtAmount
) external;
/**
* @notice Registers timelock change request.
*
* @notice Requirements:
* - `_oldTimelock` must be set zero.
* - `_newVal` must be greater than zero.
*
* @notice Effects:
* - Updates the the `_oldTimelock` state variable.
* - Updates the the `_newTimelock` state variable.
* - Updates the the `_newTimelockTimestamp` state variable.
*
* @notice Emits:
* - `TimelockAmountUpdateRequested` event indicating successful timelock change request.
*
* @param _newVal The new timelock value in seconds.
*/
function requestNewTimelock(
uint256 _newVal
) external;
/**
* @notice Updates the timelock amount.
*
* @notice Requirements:
* - Contract must be in active change.
* - `_newTimelock` must be greater than zero.
* - The old timelock must expire.
*
* @notice Effects:
* - Updates the the `timelockAmount` state variable.
* - Updates the the `_oldTimelock` state variable.
* - Updates the the `_newTimelock` state variable.
* - Updates the the `_newTimelockTimestamp` state variable.
*
* @notice Emits:
* - `TimelockAmountUpdated` event indicating successful timelock amount change.
*/
function acceptNewTimelock() external;
// -- Getters --
/**
* @notice Returns the up to date exchange rate of the protocol's stablecoin jUSD.
*
* @notice Requirements:
* - Oracle must have updated rate.
* - Rate must be a non zero positive value.
*
* @return The current exchange rate.
*/
function getJUsdExchangeRate() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IOracle {
// -- State variables --
/**
* @notice Returns the address of the token the oracle is for.
*/
function underlying() external view returns (address);
// -- Functions --
/**
* @notice Returns a human readable name of the underlying of the oracle.
*/
function name() external view returns (string memory);
/**
* @notice Returns a human readable symbol of the underlying of the oracle.
*/
function symbol() external view returns (string memory);
/**
* @notice Check the last exchange rate without any state changes.
*
* @param data Implementation specific data that contains information and arguments to & about the oracle.
*
* @return success If no valid (recent) rate is available, returns false else true.
* @return rate The rate of the requested asset / pair / pool.
*/
function peek(
bytes calldata data
) external view returns (bool success, uint256 rate);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IERC20Errors } from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import { IERC20, IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
// Receipt token interface
interface IReceiptToken is IERC20, IERC20Metadata, IERC20Errors {
// -- Events --
/**
* @notice Emitted when the minter address is updated
* @param oldMinter The address of the old minter
* @param newMinter The address of the new minter
*/
event MinterUpdated(address oldMinter, address newMinter);
// --- Initialization ---
/**
* @notice This function initializes the contract (instead of a constructor) to be cloned.
*
* @notice Requirements:
* - The contract must not be already initialized.
* - The `__minter` must not be the zero address.
*
* @notice Effects:
* - Sets `_initialized` to true.
* - Updates `_name`, `_symbol`, `minter` state variables.
* - Stores `__owner` as owner.
*
* @param __name Receipt token name.
* @param __symbol Receipt token symbol.
* @param __minter Receipt token minter.
* @param __owner Receipt token owner.
*/
function initialize(string memory __name, string memory __symbol, address __minter, address __owner) external;
/**
* @notice Mints receipt tokens.
*
* @notice Requirements:
* - Must be called by the Minter or Owner of the Contract.
*
* @notice Effects:
* - Mints the specified amount of tokens to the given address.
*
* @param _user Address of the user receiving minted tokens.
* @param _amount The amount to be minted.
*/
function mint(address _user, uint256 _amount) external;
/**
* @notice Burns tokens from an address.
*
* @notice Requirements:
* - Must be called by the Minter or Owner of the Contract.
*
* @notice Effects:
* - Burns the specified amount of tokens from the specified address.
*
* @param _user The user to burn it from.
* @param _amount The amount of tokens to be burnt.
*/
function burnFrom(address _user, uint256 _amount) external;
/**
* @notice Sets minter.
*
* @notice Requirements:
* - Must be called by the Minter or Owner of the Contract.
* - The `_minter` must be different from `minter`.
*
* @notice Effects:
* - Updates minter state variable.
*
* @notice Emits:
* - `MinterUpdated` event indicating minter update operation.
*
* @param _minter The user to burn it from.
*/
function setMinter(
address _minter
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IOracle } from "../oracle/IOracle.sol";
import { IManager } from "./IManager.sol";
/**
* @title ISharesRegistry
* @dev Interface for the Shares Registry Contract.
* @dev Based on MIM CauldraonV2 contract.
*/
interface ISharesRegistry {
/**
* @notice Configuration struct for registry parameters.
* @dev Used to store key parameters that control collateral and liquidation behavior.
*
* @param collateralizationRate The minimum collateral ratio required, expressed as a percentage with precision.
* @param liquidationBuffer Is a value, that represents the buffer between the collateralization rate and the
* liquidation threshold, upon which the liquidation is allowed.
* @param liquidatorBonus The bonus percentage given to liquidators as incentive, expressed with precision.
*/
struct RegistryConfig {
uint256 collateralizationRate;
uint256 liquidationBuffer;
uint256 liquidatorBonus;
}
/**
* @notice Event emitted when borrowed amount is set.
* @param _holding The address of the holding.
* @param oldVal The old value.
* @param newVal The new value.
*/
event BorrowedSet(address indexed _holding, uint256 oldVal, uint256 newVal);
/**
* @notice Event emitted when collateral is registered.
* @param user The address of the user.
* @param share The amount of shares.
*/
event CollateralAdded(address indexed user, uint256 share);
/**
* @notice Event emitted when collateral was unregistered.
* @param user The address of the user.
* @param share The amount of shares.
*/
event CollateralRemoved(address indexed user, uint256 share);
/**
* @notice Event emitted when the collateralization rate is updated.
* @param oldVal The old value.
* @param newVal The new value.
*/
event CollateralizationRateUpdated(uint256 oldVal, uint256 newVal);
/**
* @notice Event emitted when a new oracle is requested.
* @param newOracle The new oracle address.
*/
event NewOracleRequested(address newOracle);
/**
* @notice Event emitted when the oracle is updated.
*/
event OracleUpdated();
/**
* @notice Event emitted when new oracle data is requested.
* @param newData The new data.
*/
event NewOracleDataRequested(bytes newData);
/**
* @notice Event emitted when oracle data is updated.
*/
event OracleDataUpdated();
/**
* @notice Event emitted when a new timelock amount is requested.
* @param oldVal The old value.
* @param newVal The new value.
*/
event TimelockAmountUpdateRequested(uint256 oldVal, uint256 newVal);
/**
* @notice Event emitted when timelock amount is updated.
* @param oldVal The old value.
* @param newVal The new value.
*/
event TimelockAmountUpdated(uint256 oldVal, uint256 newVal);
/**
* @notice Event emitted when the config is updated.
* @param token The token address.
* @param oldVal The old config.
* @param newVal The new config.
*/
event ConfigUpdated(address indexed token, RegistryConfig oldVal, RegistryConfig newVal);
/**
* @notice Returns holding's borrowed amount.
* @param _holding The address of the holding.
* @return The borrowed amount.
*/
function borrowed(
address _holding
) external view returns (uint256);
/**
* @notice Returns holding's available collateral amount.
* @param _holding The address of the holding.
* @return The collateral amount.
*/
function collateral(
address _holding
) external view returns (uint256);
/**
* @notice Returns the token address for which this registry was created.
* @return The token address.
*/
function token() external view returns (address);
/**
* @notice Contract that contains all the necessary configs of the protocol.
* @return The manager contract.
*/
function manager() external view returns (IManager);
/**
* @notice Oracle contract associated with this share registry.
* @return The oracle contract.
*/
function oracle() external view returns (IOracle);
/**
* @notice Extra oracle data if needed.
* @return The oracle data.
*/
function oracleData() external view returns (bytes calldata);
/**
* @notice Current timelock amount.
* @return The timelock amount.
*/
function timelockAmount() external view returns (uint256);
// -- User specific methods --
/**
* @notice Updates `_holding`'s borrowed amount.
*
* @notice Requirements:
* - `msg.sender` must be the Stables Manager Contract.
* - `_newVal` must be greater than or equal to the minimum debt amount.
*
* @notice Effects:
* - Updates `borrowed` mapping.
*
* @notice Emits:
* - `BorrowedSet` indicating holding's borrowed amount update operation.
*
* @param _holding The address of the user's holding.
* @param _newVal The new borrowed amount.
*/
function setBorrowed(address _holding, uint256 _newVal) external;
/**
* @notice Registers collateral for user's `_holding`.
*
* @notice Requirements:
* - `msg.sender` must be the Stables Manager Contract.
*
* @notice Effects:
* - Updates `collateral` mapping.
*
* @notice Emits:
* - `CollateralAdded` event indicating collateral addition operation.
*
* @param _holding The address of the user's holding.
* @param _share The new collateral shares.
*/
function registerCollateral(address _holding, uint256 _share) external;
/**
* @notice Registers a collateral removal operation for user's `_holding`.
*
* @notice Requirements:
* - `msg.sender` must be the Stables Manager Contract.
*
* @notice Effects:
* - Updates `collateral` mapping.
*
* @notice Emits:
* - `CollateralRemoved` event indicating collateral removal operation.
*
* @param _holding The address of the user's holding.
* @param _share The new collateral shares.
*/
function unregisterCollateral(address _holding, uint256 _share) external;
// -- Administration --
/**
* @notice Updates the registry configuration parameters.
*
* @notice Effects:
* - Updates `config` state variable.
*
* @notice Emits:
* - `ConfigUpdated` event indicating config update operation.
*
* @param _newConfig The new configuration parameters.
*/
function updateConfig(
RegistryConfig memory _newConfig
) external;
/**
* @notice Requests a change for the oracle address.
*
* @notice Requirements:
* - Previous oracle change request must have expired or been accepted.
* - No timelock or oracle data change requests should be active.
* - `_oracle` must not be the zero address.
*
* @notice Effects:
* - Updates `_isOracleActiveChange` state variable.
* - Updates `_newOracle` state variable.
* - Updates `_newOracleTimestamp` state variable.
*
* @notice Emits:
* - `NewOracleRequested` event indicating new oracle request.
*
* @param _oracle The new oracle address.
*/
function requestNewOracle(
address _oracle
) external;
/**
* @notice Updates the oracle.
*
* @notice Requirements:
* - Oracle change must have been requested and the timelock must have passed.
*
* @notice Effects:
* - Updates `oracle` state variable.
* - Updates `_isOracleActiveChange` state variable.
* - Updates `_newOracle` state variable.
* - Updates `_newOracleTimestamp` state variable.
*
* @notice Emits:
* - `OracleUpdated` event indicating oracle update.
*/
function setOracle() external;
/**
* @notice Requests a change for oracle data.
*
* @notice Requirements:
* - Previous oracle data change request must have expired or been accepted.
* - No timelock or oracle change requests should be active.
*
* @notice Effects:
* - Updates `_isOracleDataActiveChange` state variable.
* - Updates `_newOracleData` state variable.
* - Updates `_newOracleDataTimestamp` state variable.
*
* @notice Emits:
* - `NewOracleDataRequested` event indicating new oracle data request.
*
* @param _data The new oracle data.
*/
function requestNewOracleData(
bytes calldata _data
) external;
/**
* @notice Updates the oracle data.
*
* @notice Requirements:
* - Oracle data change must have been requested and the timelock must have passed.
*
* @notice Effects:
* - Updates `oracleData` state variable.
* - Updates `_isOracleDataActiveChange` state variable.
* - Updates `_newOracleData` state variable.
* - Updates `_newOracleDataTimestamp` state variable.
*
* @notice Emits:
* - `OracleDataUpdated` event indicating oracle data update.
*/
function setOracleData() external;
/**
* @notice Requests a timelock update.
*
* @notice Requirements:
* - `_newVal` must not be zero.
* - Previous timelock change request must have expired or been accepted.
* - No oracle or oracle data change requests should be active.
*
* @notice Effects:
* - Updates `_isTimelockActiveChange` state variable.
* - Updates `_oldTimelock` state variable.
* - Updates `_newTimelock` state variable.
* - Updates `_newTimelockTimestamp` state variable.
*
* @notice Emits:
* - `TimelockAmountUpdateRequested` event indicating timelock change request.
*
* @param _newVal The new value in seconds.
*/
function requestTimelockAmountChange(
uint256 _newVal
) external;
/**
* @notice Updates the timelock amount.
*
* @notice Requirements:
* - Timelock change must have been requested and the timelock must have passed.
* - The timelock for timelock change must have already expired.
*
* @notice Effects:
* - Updates `timelockAmount` state variable.
* - Updates `_oldTimelock` state variable.
* - Updates `_newTimelock` state variable.
* - Updates `_newTimelockTimestamp` state variable.
*
* @notice Emits:
* - `TimelockAmountUpdated` event indicating timelock amount change operation.
*/
function acceptTimelockAmountChange() external;
// -- Getters --
/**
* @notice Returns the up to date exchange rate of the `token`.
*
* @notice Requirements:
* - Oracle must provide an updated rate.
*
* @return The updated exchange rate.
*/
function getExchangeRate() external view returns (uint256);
/**
* @notice Returns the configuration parameters for the registry.
* @return The RegistryConfig struct containing the parameters.
*/
function getConfig() external view returns (RegistryConfig memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IJigsawUSD } from "../core/IJigsawUSD.sol";
import { ISharesRegistry } from "../core/ISharesRegistry.sol";
import { IManager } from "./IManager.sol";
/**
* @title IStablesManager
* @notice Interface for the Stables Manager.
*/
interface IStablesManager {
// -- Custom types --
/**
* @notice Structure to store state and deployment address for a share registry
*/
struct ShareRegistryInfo {
bool active; // Flag indicating if the registry is active
address deployedAt; // Address where the registry is deployed
}
/**
* @notice Temporary struct used to store data during borrow operations to avoid stack too deep errors.
* @dev This struct helps organize variables used in the borrow function.
* @param registry The shares registry contract for the collateral token
* @param exchangeRatePrecision The precision used for exchange rate calculations
* @param amount The normalized amount (18 decimals) of collateral being borrowed against
* @param amountValue The USD value of the collateral amount
*/
struct BorrowTempData {
ISharesRegistry registry;
uint256 exchangeRatePrecision;
uint256 amount;
uint256 amountValue;
}
// -- Events --
/**
* @notice Emitted when collateral is registered.
* @param holding The address of the holding.
* @param token The address of the token.
* @param amount The amount of collateral.
*/
event AddedCollateral(address indexed holding, address indexed token, uint256 amount);
/**
* @notice Emitted when collateral is unregistered.
* @param holding The address of the holding.
* @param token The address of the token.
* @param amount The amount of collateral.
*/
event RemovedCollateral(address indexed holding, address indexed token, uint256 amount);
/**
* @notice Emitted when a borrow action is performed.
* @param holding The address of the holding.
* @param jUsdMinted The amount of jUSD minted.
* @param mintToUser Boolean indicating if the amount is minted directly to the user.
*/
event Borrowed(address indexed holding, uint256 jUsdMinted, bool mintToUser);
/**
* @notice Emitted when a repay action is performed.
* @param holding The address of the holding.
* @param amount The amount repaid.
* @param burnFrom The address to burn from.
*/
event Repaid(address indexed holding, uint256 amount, address indexed burnFrom);
/**
* @notice Emitted when a registry is added.
* @param token The address of the token.
* @param registry The address of the registry.
*/
event RegistryAdded(address indexed token, address indexed registry);
/**
* @notice Emitted when a registry is updated.
* @param token The address of the token.
* @param registry The address of the registry.
*/
event RegistryUpdated(address indexed token, address indexed registry);
/**
* @notice Returns total borrowed jUSD amount using `token`.
* @param _token The address of the token.
* @return The total borrowed amount.
*/
function totalBorrowed(
address _token
) external view returns (uint256);
/**
* @notice Returns config info for each token.
* @param _token The address of the token to get registry info for.
* @return Boolean indicating if the registry is active and the address of the registry.
*/
function shareRegistryInfo(
address _token
) external view returns (bool, address);
/**
* @notice Returns protocol's stablecoin address.
* @return The address of the Jigsaw stablecoin.
*/
function jUSD() external view returns (IJigsawUSD);
/**
* @notice Contract that contains all the necessary configs of the protocol.
* @return The manager contract.
*/
function manager() external view returns (IManager);
// -- User specific methods --
/**
* @notice Registers new collateral.
*
* @dev The amount will be transformed to shares.
*
* @notice Requirements:
* - The caller must be allowed to perform this action directly. If user - use Holding Manager Contract.
* - The `_token` must be whitelisted.
* - The `_token`'s registry must be active.
*
* @notice Effects:
* - Adds collateral for the holding.
*
* @notice Emits:
* - `AddedCollateral` event indicating successful collateral addition operation.
*
* @param _holding The holding for which collateral is added.
* @param _token Collateral token.
* @param _amount Amount of tokens to be added as collateral.
*/
function addCollateral(address _holding, address _token, uint256 _amount) external;
/**
* @notice Unregisters collateral.
*
* @notice Requirements:
* - The contract must not be paused.
* - The caller must be allowed to perform this action directly. If user - use Holding Manager Contract.
* - The token's registry must be active.
* - `_holding` must stay solvent after collateral removal.
*
* @notice Effects:
* - Removes collateral for the holding.
*
* @notice Emits:
* - `RemovedCollateral` event indicating successful collateral removal operation.
*
* @param _holding The holding for which collateral is removed.
* @param _token Collateral token.
* @param _amount Amount of collateral.
*/
function removeCollateral(address _holding, address _token, uint256 _amount) external;
/**
* @notice Unregisters collateral.
*
* @notice Requirements:
* - The caller must be the LiquidationManager.
* - The token's registry must be active.
*
* @notice Effects:
* - Force removes collateral from the `_holding` in case of liquidation, without checking if user is solvent after
* collateral removal.
*
* @notice Emits:
* - `RemovedCollateral` event indicating successful collateral removal operation.
*
* @param _holding The holding for which collateral is added.
* @param _token Collateral token.
* @param _amount Amount of collateral.
*/
function forceRemoveCollateral(address _holding, address _token, uint256 _amount) external;
/**
* @notice Mints stablecoin to the user.
*
* @notice Requirements:
* - The caller must be allowed to perform this action directly. If user - use Holding Manager Contract.
* - The token's registry must be active.
* - `_amount` must be greater than zero.
*
* @notice Effects:
* - Mints stablecoin based on the collateral amount.
* - Updates the total borrowed jUSD amount for `_token`, used for borrowing.
* - Updates `_holdings`'s borrowed amount in `token`'s registry contract.
* - Ensures the holding remains solvent.
*
* @notice Emits:
* - `Borrowed`.
*
* @param _holding The holding for which collateral is added.
* @param _token Collateral token.
* @param _amount The collateral amount equivalent for borrowed jUSD.
* @param _minJUsdAmountOut The minimum amount of jUSD that is expected to be received.
* @param _mintDirectlyToUser If true, mints to user instead of holding.
*
* @return jUsdMintAmount The amount of jUSD minted.
*/
function borrow(
address _holding,
address _token,
uint256 _amount,
uint256 _minJUsdAmountOut,
bool _mintDirectlyToUser
) external returns (uint256 jUsdMintAmount);
/**
* @notice Repays debt.
*
* @notice Requirements:
* - The caller must be allowed to perform this action directly. If user - use Holding Manager Contract.
* - The token's registry must be active.
* - The holding must have a positive borrowed amount.
* - `_amount` must not exceed `holding`'s borrowed amount.
* - `_amount` must be greater than zero.
* - `_burnFrom` must not be the zero address.
*
* @notice Effects:
* - Updates the total borrowed jUSD amount for `_token`, used for borrowing.
* - Updates `_holdings`'s borrowed amount in `token`'s registry contract.
* - Burns `_amount` jUSD tokens from `_burnFrom` address
*
* @notice Emits:
* - `Repaid` event indicating successful repay operation.
*
* @param _holding The holding for which repay is performed.
* @param _token Collateral token.
* @param _amount The repaid jUSD amount.
* @param _burnFrom The address to burn from.
*/
function repay(address _holding, address _token, uint256 _amount, address _burnFrom) external;
// -- Administration --
/**
* @notice Triggers stopped state.
*/
function pause() external;
/**
* @notice Returns to normal state.
*/
function unpause() external;
// -- Getters --
/**
* @notice Returns true if user is solvent for the specified token.
*
* @dev The method reverts if block.timestamp - _maxTimeRange > exchangeRateUpdatedAt.
*
* @notice Requirements:
* - `_holding` must not be the zero address.
* - There must be registry for `_token`.
*
* @param _token The token for which the check is done.
* @param _holding The user address.
*
* @return flag indicating whether `holding` is solvent.
*/
function isSolvent(address _token, address _holding) external view returns (bool);
/**
* @notice Checks if a holding can be liquidated for a specific token.
*
* @notice Requirements:
* - `_holding` must not be the zero address.
* - There must be registry for `_token`.
*
* @param _token The token for which the check is done.
* @param _holding The user address.
*
* @return flag indicating whether `holding` is liquidatable.
*/
function isLiquidatable(address _token, address _holding) external view returns (bool);
/**
* @notice Computes the solvency ratio.
*
* @dev Solvency ratio is calculated based on the used collateral type, its collateralization and exchange rates,
* and `_holding`'s borrowed amount.
*
* @param _holding The holding address to check for.
* @param registry The Shares Registry Contract for the token.
* @param rate The rate to compute ratio for (either collateralization rate for `isSolvent` or liquidation
* threshold for `isLiquidatable`).
*
* @return The calculated solvency ratio.
*/
function getRatio(address _holding, ISharesRegistry registry, uint256 rate) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IReceiptToken } from "../core/IReceiptToken.sol";
/**
* @title IStrategy
* @notice Interface for a Strategies.
*
* @dev This interface defines the standard functions and events for a strategy contract.
* @dev The strategy allows for the deposit, withdrawal, and reward claiming functionalities.
* @dev It also provides views for essential information about the strategy's token and rewards.
*/
interface IStrategy {
// -- Custom types --
/**
* @notice Struct containing parameters for a withdrawal operation.
* @param shares The number of shares to withdraw.
* @param totalShares The total shares owned by the user.
* @param shareRatio The ratio of the shares to withdraw relative to the total shares owned by the user.
* @param shareDecimals The number of decimals of the strategy's shares.
* @param investment The amount of initial investment corresponding to the shares being withdrawn.
* @param assetsToWithdraw The underlying assets withdrawn by the user, including yield and excluding fee.
* @param balanceBefore The user's `tokenOut` balance before the withdrawal transaction.
* @param withdrawnAmount The amount of underlying assets withdrawn by the user, excluding fee.
* @param yield The yield generated by the strategy excluding fee, as fee are taken from the yield.
* @param fee The amount of fee taken by the protocol.
*/
struct WithdrawParams {
uint256 shares;
uint256 totalShares;
uint256 shareRatio;
uint256 shareDecimals;
uint256 investment;
uint256 assetsToWithdraw;
uint256 balanceBefore;
uint256 withdrawnAmount;
int256 yield;
uint256 fee;
}
/**
* @notice Emitted when funds are deposited.
*
* @param asset The address of the asset.
* @param tokenIn The address of the input token.
* @param assetAmount The amount of the asset.
* @param tokenInAmount The amount of the input token.
* @param shares The number of shares received.
* @param recipient The address of the recipient.
*/
event Deposit(
address indexed asset,
address indexed tokenIn,
uint256 assetAmount,
uint256 tokenInAmount,
uint256 shares,
address indexed recipient
);
/**
* @notice Emitted when funds are withdrawn.
*
* @param asset The address of the asset.
* @param recipient The address of the recipient.
* @param shares The number of shares withdrawn.
* @param withdrawnAmount The amount of the asset withdrawn.
* @param yield The amount of yield generated by the user beyond their initial investment.
*/
event Withdraw(
address indexed asset,
address indexed recipient,
uint256 shares,
uint256 withdrawnAmount,
uint256 initialInvestment,
int256 yield
);
/**
* @notice Emitted when rewards are claimed.
*
* @param recipient The address of the recipient.
* @param rewards The array of reward amounts.
* @param rewardTokens The array of reward token addresses.
*/
event Rewards(address indexed recipient, uint256[] rewards, address[] rewardTokens);
/**
* @notice Returns investments details.
* @param _recipient The address of the recipient.
* @return investedAmount The amount invested.
* @return totalShares The total shares.
*/
function recipients(
address _recipient
) external view returns (uint256 investedAmount, uint256 totalShares);
/**
* @notice Returns the address of the token accepted by the strategy's underlying protocol as input.
* @return tokenIn The address of the tokenIn.
*/
function tokenIn() external view returns (address);
/**
* @notice Returns the address of token issued by the strategy's underlying protocol after deposit.
* @return tokenOut The address of the tokenOut.
*/
function tokenOut() external view returns (address);
/**
* @notice Returns the address of the strategy's main reward token.
* @return rewardToken The address of the reward token.
*/
function rewardToken() external view returns (address);
/**
* @notice Returns the address of the receipt token minted by the strategy itself.
* @return receiptToken The address of the receipt token.
*/
function receiptToken() external view returns (IReceiptToken);
/**
* @notice Returns the number of decimals of the strategy's shares.
* @return sharesDecimals The number of decimals.
*/
function sharesDecimals() external view returns (uint256);
/**
* @notice Returns the address of the receipt token.
* @return receiptTokenAddress The address of the receipt token.
*/
function getReceiptTokenAddress() external view returns (address receiptTokenAddress);
/**
* @notice Deposits funds into the strategy.
*
* @dev Some strategies won't give back any receipt tokens; in this case 'tokenOutAmount' will be 0.
* 'tokenInAmount' will be equal to '_amount' in case the '_asset' is the same as strategy 'tokenIn()'.
*
* @param _asset The token to be invested.
* @param _amount The token's amount.
* @param _recipient The address of the recipient.
* @param _data Extra data.
*
* @return tokenOutAmount The receipt tokens amount/obtained shares.
* @return tokenInAmount The returned token in amount.
*/
function deposit(
address _asset,
uint256 _amount,
address _recipient,
bytes calldata _data
) external returns (uint256 tokenOutAmount, uint256 tokenInAmount);
/**
* @notice Withdraws deposited funds.
*
* @param _shares The amount to withdraw.
* @param _recipient The address of the recipient.
* @param _asset The token to be withdrawn.
* @param _data Extra data.
*
* @return withdrawnAmount The actual amount of asset withdrawn from the strategy.
* @return initialInvestment The amount of initial investment.
* @return yield The amount of yield generated by the user beyond their initial investment.
* @return fee The amount of fee charged by the strategy.
*/
function withdraw(
uint256 _shares,
address _recipient,
address _asset,
bytes calldata _data
) external returns (uint256 withdrawnAmount, uint256 initialInvestment, int256 yield, uint256 fee);
/**
* @notice Claims rewards from the strategy.
*
* @param _recipient The address of the recipient.
* @param _data Extra data.
*
* @return amounts The reward tokens amounts.
* @return tokens The reward tokens addresses.
*/
function claimRewards(
address _recipient,
bytes calldata _data
) external returns (uint256[] memory amounts, address[] memory tokens);
/**
* @notice Participants info.
*/
struct RecipientInfo {
uint256 investedAmount;
uint256 totalShares;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IStrategy } from ".//IStrategy.sol";
import { IManager } from "./IManager.sol";
import { IStrategyManagerMin } from "./IStrategyManagerMin.sol";
/**
* @title IStrategyManager
* @dev Interface for the StrategyManager contract.
*/
interface IStrategyManager is IStrategyManagerMin {
// -- Custom Types --
/**
* @notice Contains details about a specific strategy, such as its performance fee, active status, and whitelisted
* status.
* @param performanceFee fee charged as a percentage of the profits generated by the strategy.
* @param active flag indicating whether the strategy is active.
* @param whitelisted flag indicating whether strategy is approved for investment.
*/
struct StrategyInfo {
uint256 performanceFee;
bool active;
bool whitelisted;
}
/**
* @notice Contains data required for moving investment from one strategy to another.
* @param strategyFrom strategy's address where investment is taken from.
* @param strategyTo strategy's address where to invest.
* @param shares investment amount.
* @param dataFrom data required by `strategyFrom` to perform `_claimInvestment`.
* @param dataTo data required by `strategyTo` to perform `_invest`.
* @param strategyToMinSharesAmountOut minimum amount of shares to receive.
*/
struct MoveInvestmentData {
address strategyFrom;
address strategyTo;
uint256 shares;
bytes dataFrom;
bytes dataTo;
uint256 strategyToMinSharesAmountOut;
}
/**
* @dev Struct used for _claimInvestment function
* @param strategyContract The strategy contract instance being interacted with
* @param withdrawnAmount The amount of the asset withdrawn from the strategy
* @param initialInvestment The amount of initial investment
* @param yield The yield amount (positive for profit, negative for loss)
* @param fee The amount of fee charged by the strategy
* @param remainingShares The number of shares remaining after the withdrawal
*/
struct ClaimInvestmentData {
IStrategy strategyContract;
uint256 withdrawnAmount;
uint256 initialInvestment;
int256 yield;
uint256 fee;
uint256 remainingShares;
}
// -- Events --
/**
* @notice Emitted when a new strategy is added to the whitelist.
* @param strategy The address of the strategy that was added.
*/
event StrategyAdded(address indexed strategy);
/**
* @notice Emitted when an existing strategy is removed from the whitelist.
* @param strategy The address of the strategy that was removed.
*/
event StrategyRemoved(address indexed strategy);
/**
* @notice Emitted when an existing strategy info is updated.
* @param strategy The address of the strategy that was updated.
* @param active Indicates if the strategy is active.
* @param fee The fee associated with the strategy.
*/
event StrategyUpdated(address indexed strategy, bool active, uint256 fee);
/**
* @notice Emitted when an investment is created.
* @param holding The address of the holding.
* @param user The address of the user.
* @param token The address of the token invested.
* @param strategy The address of the strategy used for investment.
* @param amount The amount of tokens invested.
* @param tokenOutResult The result amount of the output token.
* @param tokenInResult The result amount of the input token.
*/
event Invested(
address indexed holding,
address indexed user,
address indexed token,
address strategy,
uint256 amount,
uint256 tokenOutResult,
uint256 tokenInResult
);
/**
* @notice Emitted when an investment is moved between strategies.
* @param holding The address of the holding.
* @param user The address of the user.
* @param token The address of the token invested.
* @param strategyFrom The address of the strategy from which the investment is moved.
* @param strategyTo The address of the strategy to which the investment is moved.
* @param shares The amount of shares moved.
* @param tokenOutResult The result amount of the output token.
* @param tokenInResult The result amount of the input token.
*/
event InvestmentMoved(
address indexed holding,
address indexed user,
address indexed token,
address strategyFrom,
address strategyTo,
uint256 shares,
uint256 tokenOutResult,
uint256 tokenInResult
);
/**
* @notice Emitted when collateral is adjusted from a claim investment or claim rewards operation.
* @param holding The address of the holding.
* @param token The address of the token.
* @param value The value of the collateral adjustment.
* @param add Indicates if the collateral is added (true) or removed (false).
*/
event CollateralAdjusted(address indexed holding, address indexed token, uint256 value, bool add);
/**
* @notice Emitted when an investment is withdrawn.
* @param holding The address of the holding.
* @param user The address of the user.
* @param token The address of the token withdrawn.
* @param strategy The address of the strategy from which the investment is withdrawn.
* @param shares The amount of shares withdrawn.
* @param withdrawnAmount The amount of tokens withdrawn.
* @param initialInvestment The amount of initial investment.
* @param yield The yield amount (positive for profit, negative for loss)
* @param fee The amount of fee charged by the strategy
*/
event StrategyClaim(
address indexed holding,
address indexed user,
address indexed token,
address strategy,
uint256 shares,
uint256 withdrawnAmount,
uint256 initialInvestment,
int256 yield,
uint256 fee
);
/**
* @notice Emitted when rewards are claimed.
* @param token The address of the token rewarded.
* @param holding The address of the holding.
* @param amount The amount of rewards claimed.
*/
event RewardsClaimed(address indexed token, address indexed holding, uint256 amount);
/**
* @notice Contract that contains all the necessary configs of the protocol.
* @return The manager contract.
*/
function manager() external view returns (IManager);
// -- User specific methods --
/**
* @notice Invests `_token` into `_strategy`.
*
* @notice Requirements:
* - Strategy must be whitelisted.
* - Amount must be non-zero.
* - Token specified for investment must be whitelisted.
* - Msg.sender must have holding.
*
* @notice Effects:
* - Performs investment to the specified `_strategy`.
* - Deposits holding's collateral to the specified `_strategy`.
* - Adds `_strategy` used for investment to the holdingToStrategy data structure.
*
* @notice Emits:
* - Invested event indicating successful investment operation.
*
* @param _token address.
* @param _strategy address.
* @param _amount to be invested.
* @param _minSharesAmountOut minimum amount of shares to receive.
* @param _data needed by each individual strategy.
*
* @return tokenOutAmount receipt tokens amount.
* @return tokenInAmount tokenIn amount.
*/
function invest(
address _token,
address _strategy,
uint256 _amount,
uint256 _minSharesAmountOut,
bytes calldata _data
) external returns (uint256 tokenOutAmount, uint256 tokenInAmount);
/**
* @notice Claims investment from one strategy and invests it into another.
*
* @notice Requirements:
* - The `strategyFrom` and `strategyTo` must be valid and active.
* - The `strategyFrom` and `strategyTo` must be different.
* - Msg.sender must have a holding.
*
* @notice Effects:
* - Claims the investment from `strategyFrom`.
* - Invests the claimed amount into `strategyTo`.
*
* @notice Emits:
* - InvestmentMoved event indicating successful investment movement operation.
*
* @dev Some strategies won't give back any receipt tokens; in this case 'tokenOutAmount' will be 0.
* @dev 'tokenInAmount' will be equal to '_amount' in case the '_asset' is the same as strategy 'tokenIn()'.
*
* @param _token The address of the token.
* @param _data The MoveInvestmentData object containing strategy and amount details.
*
* @return tokenOutAmount The amount of receipt tokens returned.
* @return tokenInAmount The amount of tokens invested in the new strategy.
*/
function moveInvestment(
address _token,
MoveInvestmentData calldata _data
) external returns (uint256 tokenOutAmount, uint256 tokenInAmount);
/**
* @notice Claims a strategy investment.
*
* @notice Requirements:
* - The `_strategy` must be valid.
* - Msg.sender must be allowed to execute the call.
* - `_shares` must be of valid amount.
* - Specified `_holding` must exist within protocol.
*
* @notice Effects:
* - Withdraws investment from `_strategy`.
* - Updates `holdingToStrategy` if needed.
*
* @notice Emits:
* - StrategyClaim event indicating successful claim operation.
*
* @dev Withdraws investment from a strategy.
* @dev Some strategies will allow only the tokenIn to be withdrawn.
* @dev 'AssetAmount' will be equal to 'tokenInAmount' in case the '_asset' is the same as strategy 'tokenIn()'.
*
* @param _holding holding's address.
* @param _token address to be received.
* @param _strategy strategy to invest into.
* @param _shares shares amount.
* @param _data extra data.
*
* @return withdrawnAmount The amount of tokens withdrawn.
* @return initialInvestment The amount of initial investment.
* @return yield The yield amount (positive for profit, negative for loss)
* @return fee The amount of fee charged by the strategy
*/
function claimInvestment(
address _holding,
address _token,
address _strategy,
uint256 _shares,
bytes calldata _data
) external returns (uint256 withdrawnAmount, uint256 initialInvestment, int256 yield, uint256 fee);
/**
* @notice Claims rewards from strategy.
*
* @notice Requirements:
* - The `_strategy` must be valid.
* - Msg.sender must have valid holding within protocol.
*
* @notice Effects:
* - Claims rewards from strategies.
* - Adds accrued rewards as a collateral for holding.
*
* @param _strategy strategy to invest into.
* @param _data extra data.
*
* @return rewards reward amounts.
* @return tokens reward tokens.
*/
function claimRewards(
address _strategy,
bytes calldata _data
) external returns (uint256[] memory rewards, address[] memory tokens);
// -- Administration --
/**
* @notice Adds a new strategy to the whitelist.
* @param _strategy strategy's address.
*/
function addStrategy(
address _strategy
) external;
/**
* @notice Updates an existing strategy info.
* @param _strategy strategy's address.
* @param _info info.
*/
function updateStrategy(address _strategy, StrategyInfo calldata _info) external;
/**
* @notice Triggers stopped state.
*/
function pause() external;
/**
* @notice Returns to normal state.
*/
function unpause() external;
// -- Getters --
/**
* @notice Returns all the strategies holding has invested in.
* @dev Should be only called off-chain as can be high gas consuming.
* @param _holding address for which the strategies are requested.
*/
function getHoldingToStrategy(
address _holding
) external view returns (address[] memory);
/**
* @notice Returns the number of strategies the holding has invested in.
* @param _holding address for which the strategy count is requested.
* @return uint256 The number of strategies the holding has invested in.
*/
function getHoldingToStrategyLength(
address _holding
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IStrategyManagerMin {
/**
* @notice Returns the strategy info.
*/
function strategyInfo(
address _strategy
) external view returns (uint256, bool, bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title Operations Library
* @notice A library containing common mathematical operations used throughout the protocol
*/
library OperationsLib {
/**
* @notice The denominator used for fee calculations (10,000 = 100%)
* @dev Fees are expressed in basis points, where 1 basis point = 0.01%
* For example, 100 = 1%, 500 = 5%, 1000 = 10%
*/
uint256 internal constant FEE_FACTOR = 10_000;
/**
* @notice Calculates the absolute fee amount based on the input amount and fee rate
* @dev The calculation rounds up to ensure the protocol always collects the full fee
* @param amount The base amount on which the fee is calculated
* @param fee The fee rate in basis points (e.g., 100 = 1%)
* @return The absolute fee amount, rounded up if there's any remainder
*/
function getFeeAbsolute(uint256 amount, uint256 fee) internal pure returns (uint256) {
// Calculate fee amount with rounding up to avoid precision loss
return (amount * fee) / FEE_FACTOR + (amount * fee % FEE_FACTOR == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../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 An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @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.encodeCall(token.transfer, (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.encodeCall(token.transferFrom, (from, to, 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);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @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.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @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);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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(token).code.length > 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { IERC20, IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SignedMath } from "@openzeppelin/contracts/utils/math/SignedMath.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { OperationsLib } from "./libraries/OperationsLib.sol";
import { IHolding } from "./interfaces/core/IHolding.sol";
import { IHoldingManager } from "./interfaces/core/IHoldingManager.sol";
import { IManager } from "./interfaces/core/IManager.sol";
import { ISharesRegistry } from "./interfaces/core/ISharesRegistry.sol";
import { IStablesManager } from "./interfaces/core/IStablesManager.sol";
import { IStrategy } from "./interfaces/core/IStrategy.sol";
import { IStrategyManager } from "./interfaces/core/IStrategyManager.sol";
/**
* @title StrategyManager
*
* @notice Manages investments of the user's assets into the whitelisted strategies to generate applicable revenue.
*
* @dev This contract inherits functionalities from `Ownable2Step`, `ReentrancyGuard`, and `Pausable`.
*
* @author Hovooo (@hovooo), Cosmin Grigore (@gcosmintech).
*
* @custom:security-contact support@jigsaw.finance
*/
contract StrategyManager is IStrategyManager, Ownable2Step, ReentrancyGuard, Pausable {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
using SignedMath for int256;
/**
* @notice Returns whitelisted Strategies' info.
*/
mapping(address strategy => StrategyInfo info) public override strategyInfo;
/**
* @notice Stores the strategies holding has invested in.
*/
mapping(address holding => EnumerableSet.AddressSet strategies) private holdingToStrategy;
/**
* @notice Contract that contains all the necessary configs of the protocol.
*/
IManager public immutable override manager;
/**
* @notice Creates a new StrategyManager contract.
* @param _initialOwner The initial owner of the contract.
* @param _manager Contract that holds all the necessary configs of the protocol.
*/
constructor(address _initialOwner, address _manager) Ownable(_initialOwner) {
require(_manager != address(0), "3065");
manager = IManager(_manager);
}
// -- User specific methods --
/**
* @notice Invests `_token` into `_strategy`.
*
* @notice Requirements:
* - Strategy must be whitelisted.
* - Amount must be non-zero.
* - Token specified for investment must be whitelisted.
* - Msg.sender must have holding.
*
* @notice Effects:
* - Performs investment to the specified `_strategy`.
* - Deposits holding's collateral to the specified `_strategy`.
* - Adds `_strategy` used for investment to the holdingToStrategy data structure.
*
* @notice Emits:
* - Invested event indicating successful investment operation.
*
* @param _token address.
* @param _strategy address.
* @param _amount to be invested.
* @param _minSharesAmountOut minimum amount of shares to receive.
* @param _data needed by each individual strategy.
*
* @return tokenOutAmount receipt tokens amount.
* @return tokenInAmount tokenIn amount.
*/
function invest(
address _token,
address _strategy,
uint256 _amount,
uint256 _minSharesAmountOut,
bytes calldata _data
)
external
override
validStrategy(_strategy)
validAmount(_amount)
validToken(_token)
whenNotPaused
nonReentrant
returns (uint256 tokenOutAmount, uint256 tokenInAmount)
{
address _holding = _getHoldingManager().userHolding(msg.sender);
require(_getHoldingManager().isHolding(_holding), "3002");
require(strategyInfo[_strategy].active, "1202");
require(IStrategy(_strategy).tokenIn() == _token, "3085");
(tokenOutAmount, tokenInAmount) = _invest({
_holding: _holding,
_token: _token,
_strategy: _strategy,
_amount: _amount,
_minSharesAmountOut: _minSharesAmountOut,
_data: _data
});
emit Invested(_holding, msg.sender, _token, _strategy, _amount, tokenOutAmount, tokenInAmount);
return (tokenOutAmount, tokenInAmount);
}
/**
* @notice Claims investment from one strategy and invests it into another.
*
* @notice Requirements:
* - The `strategyTo` must be valid and active.
* - The `strategyFrom` and `strategyTo` must be different.
* - Msg.sender must have a holding.
*
* @notice Effects:
* - Claims the investment from `strategyFrom`.
* - Invests the claimed amount into `strategyTo`.
*
* @notice Emits:
* - InvestmentMoved event indicating successful investment movement operation.
*
* @dev Some strategies won't give back any receipt tokens; in this case 'tokenOutAmount' will be 0.
* @dev 'tokenInAmount' will be equal to '_amount' in case the '_asset' is the same as strategy 'tokenIn()'.
*
* @param _token The address of the token.
* @param _data The MoveInvestmentData object containing strategy and amount details.
*
* @return tokenOutAmount The amount of receipt tokens returned.
* @return tokenInAmount The amount of tokens invested in the new strategy.
*/
function moveInvestment(
address _token,
MoveInvestmentData calldata _data
)
external
override
validStrategy(_data.strategyFrom)
validStrategy(_data.strategyTo)
nonReentrant
whenNotPaused
returns (uint256 tokenOutAmount, uint256 tokenInAmount)
{
address _holding = _getHoldingManager().userHolding(msg.sender);
require(_getHoldingManager().isHolding(_holding), "3002");
require(_data.strategyFrom != _data.strategyTo, "3086");
require(strategyInfo[_data.strategyTo].active, "1202");
require(IStrategy(_data.strategyFrom).tokenIn() == _token, "3001");
require(IStrategy(_data.strategyTo).tokenIn() == _token, "3085");
(uint256 claimResult,,,) = _claimInvestment({
_holding: _holding,
_token: _token,
_strategy: _data.strategyFrom,
_shares: _data.shares,
_data: _data.dataFrom
});
(tokenOutAmount, tokenInAmount) = _invest({
_holding: _holding,
_token: _token,
_strategy: _data.strategyTo,
_amount: claimResult,
_minSharesAmountOut: _data.strategyToMinSharesAmountOut,
_data: _data.dataTo
});
emit InvestmentMoved(
_holding,
msg.sender,
_token,
_data.strategyFrom,
_data.strategyTo,
_data.shares,
tokenOutAmount,
tokenInAmount
);
return (tokenOutAmount, tokenInAmount);
}
/**
* @notice Claims a strategy investment.
*
* @notice Requirements:
* - The `_strategy` must be valid.
* - Msg.sender must be allowed to execute the call.
* - `_shares` must be of valid amount.
* - Specified `_holding` must exist within protocol.
*
* @notice Effects:
* - Withdraws investment from `_strategy`.
* - Updates `holdingToStrategy` if needed.
*
* @notice Emits:
* - StrategyClaim event indicating successful claim operation.
*
* @dev Withdraws investment from a strategy.
* @dev Some strategies will allow only the tokenIn to be withdrawn.
* @dev 'AssetAmount' will be equal to 'tokenInAmount' in case the '_asset' is the same as strategy 'tokenIn()'.
*
* @param _holding holding's address.
* @param _token address to be received.
* @param _strategy strategy to invest into.
* @param _shares shares amount.
* @param _data extra data.
*
* @return withdrawnAmount returned asset amount obtained from the operation.
* @return initialInvestment returned token in amount.
* @return yield The yield amount (positive for profit, negative for loss)
* @return fee The amount of fee charged by the strategy
*/
function claimInvestment(
address _holding,
address _token,
address _strategy,
uint256 _shares,
bytes calldata _data
)
external
override
validStrategy(_strategy)
onlyAllowed(_holding)
validAmount(_shares)
nonReentrant
whenNotPaused
returns (uint256 withdrawnAmount, uint256 initialInvestment, int256 yield, uint256 fee)
{
require(_getHoldingManager().isHolding(_holding), "3002");
(withdrawnAmount, initialInvestment, yield, fee) = _claimInvestment({
_holding: _holding,
_token: _token,
_strategy: _strategy,
_shares: _shares,
_data: _data
});
emit StrategyClaim({
holding: _holding,
user: msg.sender,
token: _token,
strategy: _strategy,
shares: _shares,
withdrawnAmount: withdrawnAmount,
initialInvestment: initialInvestment,
yield: yield,
fee: fee
});
}
/**
* @notice Claims rewards from strategy.
*
* @notice Requirements:
* - The `_strategy` must be valid.
* - Msg.sender must have valid holding within protocol.
*
* @notice Effects:
* - Claims rewards from strategies.
* - Adds accrued rewards as a collateral for holding.
*
* @param _strategy strategy to invest into.
* @param _data extra data.
*
* @return rewards reward amounts.
* @return tokens reward tokens.
*/
function claimRewards(
address _strategy,
bytes calldata _data
)
external
override
validStrategy(_strategy)
nonReentrant
whenNotPaused
returns (uint256[] memory rewards, address[] memory tokens)
{
address _holding = _getHoldingManager().userHolding(msg.sender);
require(_getHoldingManager().isHolding(_holding), "3002");
(rewards, tokens) = IStrategy(_strategy).claimRewards({ _recipient: _holding, _data: _data });
for (uint256 i = 0; i < rewards.length; i++) {
_accrueRewards({ _token: tokens[i], _amount: rewards[i], _holding: _holding });
}
}
// -- Administration --
/**
* @notice Adds a new strategy to the whitelist.
* @param _strategy strategy's address.
*/
function addStrategy(
address _strategy
) public override onlyOwner validAddress(_strategy) {
require(!strategyInfo[_strategy].whitelisted, "3014");
StrategyInfo memory info = StrategyInfo(0, false, false);
info.performanceFee = manager.performanceFee();
info.active = true;
info.whitelisted = true;
strategyInfo[_strategy] = info;
emit StrategyAdded(_strategy);
}
/**
* @notice Updates an existing strategy info.
* @param _strategy strategy's address.
* @param _info info.
*/
function updateStrategy(
address _strategy,
StrategyInfo calldata _info
) external override onlyOwner validStrategy(_strategy) {
require(_info.whitelisted, "3104");
require(_info.performanceFee <= OperationsLib.FEE_FACTOR, "3105");
strategyInfo[_strategy] = _info;
emit StrategyUpdated(_strategy, _info.active, _info.performanceFee);
}
/**
* @notice Triggers stopped state.
*/
function pause() external override onlyOwner whenNotPaused {
_pause();
}
/**
* @notice Returns to normal state.
*/
function unpause() external override onlyOwner whenPaused {
_unpause();
}
/**
* @notice Override to avoid losing contract ownership.
*/
function renounceOwnership() public pure override {
revert("1000");
}
// -- Getters --
/**
* @notice Returns all the strategies holding has invested in.
* @dev Should be only called off-chain as can be high gas consuming.
* @param _holding address for which the strategies are requested.
*/
function getHoldingToStrategy(
address _holding
) external view returns (address[] memory) {
return holdingToStrategy[_holding].values();
}
/**
* @notice Returns the number of strategies the holding has invested in.
* @param _holding address for which the strategy count is requested.
* @return uint256 The number of strategies the holding has invested in.
*/
function getHoldingToStrategyLength(
address _holding
) external view returns (uint256) {
return holdingToStrategy[_holding].length();
}
// -- Private methods --
/**
* @notice Accrues rewards for a specific token and amount to a holding address.
*
* @notice Effects:
* - Adds collateral to the holding if the amount is greater than 0 and the share registry address is not zero.
*
* @notice Emits:
* - CollateralAdjusted event indicating successful collateral adjustment operation.
*
* @param _token address for which rewards are being accrued.
* @param _amount of the token to accrue as rewards.
* @param _holding address to which the rewards are accrued.
*/
function _accrueRewards(address _token, uint256 _amount, address _holding) private {
if (_amount > 0) {
(bool active, address shareRegistry) = _getStablesManager().shareRegistryInfo(_token);
if (shareRegistry != address(0) && active) {
//add collateral
emit CollateralAdjusted(_holding, _token, _amount, true);
_getStablesManager().addCollateral(_holding, _token, _amount);
}
}
}
/**
* @notice Invests a specified amount of a token from a holding into a strategy.
*
* @notice Effects:
* - Deposits the specified amount of the token into the given strategy.
* - Updates the holding's invested strategies set.
*
* @param _holding address from which the investment is made.
* @param _token address to be invested.
* @param _strategy address into which the token is invested.
* @param _amount token to invest.
* @param _minSharesAmountOut minimum amount of shares to receive.
* @param _data required by the strategy's deposit function.
*
* @return tokenOutAmount The amount of tokens received from the strategy.
* @return tokenInAmount The amount of tokens invested into the strategy.
*/
function _invest(
address _holding,
address _token,
address _strategy,
uint256 _amount,
uint256 _minSharesAmountOut,
bytes calldata _data
) private returns (uint256 tokenOutAmount, uint256 tokenInAmount) {
(tokenOutAmount, tokenInAmount) = IStrategy(_strategy).deposit(_token, _amount, _holding, _data);
require(tokenOutAmount != 0 && tokenOutAmount >= _minSharesAmountOut, "3030");
// Ensure holding is not liquidatable after investment
require(!_getStablesManager().isLiquidatable(_token, _holding), "3103");
// Add strategy to the set, which stores holding's all invested strategies
holdingToStrategy[_holding].add(_strategy);
}
/**
* @notice Withdraws invested amount from a strategy.
*
* @notice Effects:
* - Withdraws investment from `_strategy`.
* - Removes strategy from holding's invested strategies set if `remainingShares` == 0.
*
* @param _holding address from which the investment is being claimed.
* @param _token address to be withdrawn from the strategy.
* @param _strategy address from which the investment is being claimed.
* @param _shares number to be withdrawn from the strategy.
* @param _data data required by the strategy's withdraw function.
*
* @return assetResult The amount of the asset withdrawn from the strategy.
* @return tokenInResult The amount of tokens received in exchange for the withdrawn asset.
*/
function _claimInvestment(
address _holding,
address _token,
address _strategy,
uint256 _shares,
bytes calldata _data
) private returns (uint256, uint256, int256, uint256) {
ClaimInvestmentData memory tempData = ClaimInvestmentData({
strategyContract: IStrategy(_strategy),
withdrawnAmount: 0,
initialInvestment: 0,
yield: 0,
fee: 0,
remainingShares: 0
});
// First check if holding has enough receipt tokens to burn.
_checkReceiptTokenAvailability({ _strategy: tempData.strategyContract, _shares: _shares, _holding: _holding });
(tempData.withdrawnAmount, tempData.initialInvestment, tempData.yield, tempData.fee) =
tempData.strategyContract.withdraw({ _shares: _shares, _recipient: _holding, _asset: _token, _data: _data });
require(tempData.withdrawnAmount > 0, "3016");
if (tempData.yield > 0) {
_getStablesManager().addCollateral({ _holding: _holding, _token: _token, _amount: uint256(tempData.yield) });
}
if (tempData.yield < 0) {
_getStablesManager().removeCollateral({ _holding: _holding, _token: _token, _amount: tempData.yield.abs() });
}
// Ensure user doesn't harm themselves by becoming liquidatable after claiming investment.
// If function is called by liquidation manager, we don't need to check if holding is liquidatable,
// as we need to save as much collateral as possible.
if (manager.liquidationManager() != msg.sender) {
require(!_getStablesManager().isLiquidatable(_token, _holding), "3103");
}
// If after the claim holding no longer has shares in the strategy remove that strategy from the set.
(, tempData.remainingShares) = tempData.strategyContract.recipients(_holding);
if (0 == tempData.remainingShares) holdingToStrategy[_holding].remove(_strategy);
return (tempData.withdrawnAmount, tempData.initialInvestment, tempData.yield, tempData.fee);
}
/**
* @notice Checks the availability of receipt tokens in the holding.
*
* @notice Requirements:
* - Holding must have enough receipt tokens for the specified number of shares.
*
* @param _strategy contract's instance.
* @param _shares number being checked for receipt token availability.
* @param _holding address for which the receipt token availability is being checked.
*/
function _checkReceiptTokenAvailability(IStrategy _strategy, uint256 _shares, address _holding) private view {
uint256 tokenDecimals = _strategy.sharesDecimals();
(, uint256 totalShares) = _strategy.recipients(_holding);
uint256 rtAmount = _shares > totalShares ? totalShares : _shares;
if (tokenDecimals > 18) {
rtAmount = rtAmount / (10 ** (tokenDecimals - 18));
} else {
rtAmount = rtAmount * (10 ** (18 - tokenDecimals));
}
require(IERC20(_strategy.getReceiptTokenAddress()).balanceOf(_holding) >= rtAmount);
}
/**
* @notice Retrieves the instance of the Holding Manager contract.
* @return IHoldingManager contract's instance.
*/
function _getHoldingManager() private view returns (IHoldingManager) {
return IHoldingManager(manager.holdingManager());
}
/**
* @notice Retrieves the instance of the Stables Manager contract.
* @return IStablesManager contract's instance.
*/
function _getStablesManager() private view returns (IStablesManager) {
return IStablesManager(manager.stablesManager());
}
// -- Modifiers --
/**
* @dev Modifier to check if the address is valid (not zero address).
* @param _address being checked.
*/
modifier validAddress(
address _address
) {
require(_address != address(0), "3000");
_;
}
/**
* @dev Modifier to check if the strategy address is valid (whitelisted).
* @param _strategy address being checked.
*/
modifier validStrategy(
address _strategy
) {
require(strategyInfo[_strategy].whitelisted, "3029");
_;
}
/**
* @dev Modifier to check if the amount is valid (greater than zero).
* @param _amount being checked.
*/
modifier validAmount(
uint256 _amount
) {
require(_amount > 0, "2001");
_;
}
/**
* @dev Modifier to check if the sender is allowed to perform the action.
* @param _holding address being accessed.
*/
modifier onlyAllowed(
address _holding
) {
require(
manager.liquidationManager() == msg.sender || _getHoldingManager().holdingUser(_holding) == msg.sender,
"1000"
);
_;
}
/**
* @dev Modifier to check if the token is valid (whitelisted).
* @param _token address being checked.
*/
modifier validToken(
address _token
) {
require(manager.isTokenWhitelisted(_token), "3001");
_;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
{
"compilationTarget": {
"src/StrategyManager.sol": "StrategyManager"
},
"evmVersion": "cancun",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 100000
},
"remappings": [
":@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
":@pyth/=lib/pyth-sdk-solidity/",
":@uniswap/v3-core/=lib/v3-core/",
":@uniswap/v3-periphery/=lib/v3-periphery/",
":ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/",
":pyth-sdk-solidity/=lib/pyth-sdk-solidity/",
":v3-core/=lib/v3-core/contracts/",
":v3-periphery/=lib/v3-periphery/contracts/"
]
}
[{"inputs":[{"internalType":"address","name":"_initialOwner","type":"address"},{"internalType":"address","name":"_manager","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"holding","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"bool","name":"add","type":"bool"}],"name":"CollateralAdjusted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"holding","type":"address"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"address","name":"strategy","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tokenOutResult","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tokenInResult","type":"uint256"}],"name":"Invested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"holding","type":"address"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"address","name":"strategyFrom","type":"address"},{"indexed":false,"internalType":"address","name":"strategyTo","type":"address"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tokenOutResult","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tokenInResult","type":"uint256"}],"name":"InvestmentMoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"address","name":"holding","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"RewardsClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"strategy","type":"address"}],"name":"StrategyAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"holding","type":"address"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"address","name":"strategy","type":"address"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"withdrawnAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"initialInvestment","type":"uint256"},{"indexed":false,"internalType":"int256","name":"yield","type":"int256"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"}],"name":"StrategyClaim","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"strategy","type":"address"}],"name":"StrategyRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"strategy","type":"address"},{"indexed":false,"internalType":"bool","name":"active","type":"bool"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"}],"name":"StrategyUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_strategy","type":"address"}],"name":"addStrategy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_holding","type":"address"},{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_strategy","type":"address"},{"internalType":"uint256","name":"_shares","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"claimInvestment","outputs":[{"internalType":"uint256","name":"withdrawnAmount","type":"uint256"},{"internalType":"uint256","name":"initialInvestment","type":"uint256"},{"internalType":"int256","name":"yield","type":"int256"},{"internalType":"uint256","name":"fee","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_strategy","type":"address"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"claimRewards","outputs":[{"internalType":"uint256[]","name":"rewards","type":"uint256[]"},{"internalType":"address[]","name":"tokens","type":"address[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_holding","type":"address"}],"name":"getHoldingToStrategy","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_holding","type":"address"}],"name":"getHoldingToStrategyLength","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_strategy","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint256","name":"_minSharesAmountOut","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"invest","outputs":[{"internalType":"uint256","name":"tokenOutAmount","type":"uint256"},{"internalType":"uint256","name":"tokenInAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"contract IManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"components":[{"internalType":"address","name":"strategyFrom","type":"address"},{"internalType":"address","name":"strategyTo","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"bytes","name":"dataFrom","type":"bytes"},{"internalType":"bytes","name":"dataTo","type":"bytes"},{"internalType":"uint256","name":"strategyToMinSharesAmountOut","type":"uint256"}],"internalType":"struct IStrategyManager.MoveInvestmentData","name":"_data","type":"tuple"}],"name":"moveInvestment","outputs":[{"internalType":"uint256","name":"tokenOutAmount","type":"uint256"},{"internalType":"uint256","name":"tokenInAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"}],"name":"strategyInfo","outputs":[{"internalType":"uint256","name":"performanceFee","type":"uint256"},{"internalType":"bool","name":"active","type":"bool"},{"internalType":"bool","name":"whitelisted","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_strategy","type":"address"},{"components":[{"internalType":"uint256","name":"performanceFee","type":"uint256"},{"internalType":"bool","name":"active","type":"bool"},{"internalType":"bool","name":"whitelisted","type":"bool"}],"internalType":"struct IStrategyManager.StrategyInfo","name":"_info","type":"tuple"}],"name":"updateStrategy","outputs":[],"stateMutability":"nonpayable","type":"function"}]