Description:
Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"contracts/release/extensions/external-position-manager/external-positions/alice-v2/AliceV2PositionLib.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.8.19;
import {Address} from "openzeppelin-solc-0.8/utils/Address.sol";
import {IAliceInstantOrderV2} from "../../../../../external-interfaces/IAliceInstantOrderV2.sol";
import {IAliceReferenceIdReceiver} from "../../../../../external-interfaces/IAliceReferenceIdReceiver.sol";
import {IERC20} from "../../../../../external-interfaces/IERC20.sol";
import {IWETH} from "../../../../../external-interfaces/IWETH.sol";
import {IExternalPositionProxy} from "../../../../../persistent/external-positions/IExternalPositionProxy.sol";
import {AddressArrayLib} from "../../../../../utils/0.8.19/AddressArrayLib.sol";
import {Uint256ArrayLib} from "../../../../../utils/0.8.19/Uint256ArrayLib.sol";
import {AssetHelpers} from "../../../../../utils/0.8.19/AssetHelpers.sol";
import {WrappedSafeERC20 as SafeERC20} from "../../../../../utils/0.8.19/open-zeppelin/WrappedSafeERC20.sol";
import {AliceV2PositionLibBase1} from "./bases/AliceV2PositionLibBase1.sol";
import {IAliceV2Position} from "./IAliceV2Position.sol";
/// @title AliceV2PositionLib Contract
/// @author Enzyme Foundation <security@enzyme.finance>
/// @notice An External Position library contract for AliceV2 positions
contract AliceV2PositionLib is IAliceV2Position, AliceV2PositionLibBase1, AssetHelpers, IAliceReferenceIdReceiver {
using AddressArrayLib for address[];
using SafeERC20 for IERC20;
using Uint256ArrayLib for uint256[];
address public constant ALICEV2_NATIVE_ASSET_ADDRESS = address(0);
IAliceInstantOrderV2 public immutable ALICE_INSTANT_ORDER_V2;
IWETH public immutable WRAPPED_NATIVE_TOKEN;
error InvalidActionId();
error InvalidSender();
error OrderNotSettledOrCancelled();
error InvalidReferenceId();
constructor(address _aliceV2OrderManagerAddress, address _wrappedNativeAssetAddress) {
ALICE_INSTANT_ORDER_V2 = IAliceInstantOrderV2(_aliceV2OrderManagerAddress);
WRAPPED_NATIVE_TOKEN = IWETH(_wrappedNativeAssetAddress);
}
/// @notice Initializes the external position
/// @dev Nothing to initialize for this contract
function init(bytes memory) external override {}
/// @notice Receives and executes a call from the Vault
/// @param _actionData Encoded data to execute the action
function receiveCallFromVault(bytes memory _actionData) external override {
(uint256 actionId, bytes memory actionArgs) = abi.decode(_actionData, (uint256, bytes));
if (actionId == uint256(Actions.PlaceOrder)) {
__placeOrder(actionArgs);
} else if (actionId == uint256(Actions.Sweep)) {
__sweep(actionArgs);
} else if (actionId == uint256(Actions.RefundOrder)) {
__refundOrder(actionArgs);
} else if (actionId == uint256(Actions.PlaceOrderWithRefId)) {
__placeOrderWithRefId(actionArgs);
} else {
revert InvalidActionId();
}
}
/////////////////////////
// EXTERNAL FUNCTIONS //
////////////////////////
function notifySettle(address, uint256, bytes32 _referenceId) external override {
if (msg.sender != address(ALICE_INSTANT_ORDER_V2)) {
revert InvalidSender();
}
// Validate that the reference ID is pending and has been created by this external position
if (!isPendingReferenceId(_referenceId)) {
revert InvalidReferenceId();
}
uint256 orderId = uint256(_referenceId);
// Verify that order has actually been settled or cancelled.
// Prevents external parties from triggering a `notifySettle` through a malicious order.
if (!__isOrderSettledOrCancelled({_orderId: orderId})) {
revert OrderNotSettledOrCancelled();
}
// Find the stored order details
OrderDetails memory orderDetails = getOrderDetails({_orderId: orderId});
// Remove the order from storage
__removeOrder({_orderId: orderId});
// Remove the reference ID from storage
__removeReferenceId({_referenceId: _referenceId});
// Push the assets back to the vault. Sweeping both assets in case Alice offchain logic fails.
__retrieveAssetBalance({
_asset: IERC20(orderDetails.outgoingAssetAddress),
_receiver: IExternalPositionProxy(address(this)).getVaultProxy()
});
__retrieveAssetBalance({
_asset: IERC20(orderDetails.incomingAssetAddress),
_receiver: IExternalPositionProxy(address(this)).getVaultProxy()
});
}
function notifyCancel(bytes32 _referenceId) external override {
if (msg.sender != address(ALICE_INSTANT_ORDER_V2)) {
revert InvalidSender();
}
// Validate that the reference ID is pending and has been created by this external position
if (!isPendingReferenceId(_referenceId)) {
revert InvalidReferenceId();
}
uint256 orderId = uint256(_referenceId);
// Verify that order has actually been settled or cancelled.
// Prevents external parties from triggering a `notifySettle` through a malicious order.
if (!__isOrderSettledOrCancelled({_orderId: orderId})) {
revert OrderNotSettledOrCancelled();
}
// Find the stored order details
OrderDetails memory orderDetails = getOrderDetails({_orderId: orderId});
// Remove the order from storage
__removeOrder({_orderId: orderId});
// Remove the reference ID from storage
__removeReferenceId({_referenceId: _referenceId});
// Push the assets back to the vault. Sweeping both assets in case Alice offchain logic fails.
__retrieveAssetBalance({
_asset: IERC20(orderDetails.outgoingAssetAddress),
_receiver: IExternalPositionProxy(address(this)).getVaultProxy()
});
__retrieveAssetBalance({
_asset: IERC20(orderDetails.incomingAssetAddress),
_receiver: IExternalPositionProxy(address(this)).getVaultProxy()
});
}
////////////////////
// ACTION HELPERS //
////////////////////
/// @dev Helper to prepare order by adding to storage and handling asset approval/unwrapping
function __prepareOrder(IAliceV2Position.PlaceOrderActionArgs memory _placeOrderArgs)
private
returns (uint256 nativeAssetAmount)
{
address outgoingAssetAddress = _placeOrderArgs.tokenToSell;
address incomingAssetAddress = _placeOrderArgs.tokenToBuy;
__addOrder({
_orderDetails: OrderDetails({
outgoingAssetAddress: outgoingAssetAddress,
incomingAssetAddress: incomingAssetAddress,
outgoingAmount: _placeOrderArgs.quantityToSell
})
});
if (outgoingAssetAddress == ALICEV2_NATIVE_ASSET_ADDRESS) {
// If spendAsset is the native asset, unwrap WETH.
nativeAssetAmount = _placeOrderArgs.quantityToSell;
WRAPPED_NATIVE_TOKEN.withdraw(nativeAssetAmount);
} else {
// Approve the spend asset
IERC20(outgoingAssetAddress).safeApprove({
_spender: address(ALICE_INSTANT_ORDER_V2),
_value: _placeOrderArgs.quantityToSell
});
}
}
/// @dev Helper to place an order on the AliceV2 Order Manager
function __placeOrder(bytes memory _actionArgs) private {
IAliceV2Position.PlaceOrderActionArgs memory placeOrderArgs =
abi.decode(_actionArgs, (IAliceV2Position.PlaceOrderActionArgs));
uint256 nativeAssetAmount = __prepareOrder(placeOrderArgs);
// Place the order
ALICE_INSTANT_ORDER_V2.placeOrder{value: nativeAssetAmount}({
_tokenToSell: placeOrderArgs.tokenToSell,
_tokenToBuy: placeOrderArgs.tokenToBuy,
_quantityToSell: placeOrderArgs.quantityToSell,
_limitAmountToGet: placeOrderArgs.limitAmountToGet
});
}
/// @dev Helper to sweep balance from settled or cancelled orders and clear storage
function __sweep(bytes memory _actionsArgs) private {
IAliceV2Position.SweepActionArgs memory sweepArgs = abi.decode(_actionsArgs, (IAliceV2Position.SweepActionArgs));
for (uint256 i; i < sweepArgs.orderIds.length; i++) {
uint256 orderId = sweepArgs.orderIds[i];
if (!__isOrderSettledOrCancelled({_orderId: orderId})) {
revert OrderNotSettledOrCancelled();
}
OrderDetails memory orderDetails = getOrderDetails({_orderId: orderId});
// If a reference ID exists for this order, remove it
// This could theoretically happen if the callback methods fail for an order placed with reference ID
if (isPendingReferenceId(bytes32(orderId))) {
__removeReferenceId({_referenceId: bytes32(orderId)});
}
__removeOrder({_orderId: orderId});
// If the order is settled or cancelled, the EP could have received:
// The incomingAsset if the order has been settled
// The outgoingAsset if the order has been cancelled
__retrieveAssetBalance({_asset: IERC20(orderDetails.incomingAssetAddress), _receiver: msg.sender});
__retrieveAssetBalance({_asset: IERC20(orderDetails.outgoingAssetAddress), _receiver: msg.sender});
}
}
/// @dev Helper to refund an outstanding order
function __refundOrder(bytes memory _actionsArgs) private {
IAliceV2Position.RefundOrderActionArgs memory refundOrderArgs =
abi.decode(_actionsArgs, (IAliceV2Position.RefundOrderActionArgs));
// Remove the order from storage
__removeOrder({_orderId: refundOrderArgs.orderId});
// Refund the order
ALICE_INSTANT_ORDER_V2.refundOrder({
_orderId: refundOrderArgs.orderId,
_user: address(this),
_tokenToSell: refundOrderArgs.tokenToSell,
_tokenToBuy: refundOrderArgs.tokenToBuy,
_quantityToSell: refundOrderArgs.quantityToSell,
_limitAmountToGet: refundOrderArgs.limitAmountToGet,
_timestamp: refundOrderArgs.timestamp
});
// Return the refunded outgoing asset back to the vault using the existing helper
__retrieveAssetBalance({_asset: IERC20(refundOrderArgs.tokenToSell), _receiver: msg.sender});
}
/// @dev Helper to place an order with a reference ID
function __placeOrderWithRefId(bytes memory _actionArgs) private {
IAliceV2Position.PlaceOrderActionArgs memory placeOrderArgs =
abi.decode(_actionArgs, (IAliceV2Position.PlaceOrderActionArgs));
uint256 nativeAssetAmount = __prepareOrder(placeOrderArgs);
// Generate a unique reference ID for this external position
bytes32 referenceId = bytes32(ALICE_INSTANT_ORDER_V2.getMostRecentOrderId() + 1);
// Track the reference ID
__addReferenceId({_referenceId: referenceId});
// Place the order
ALICE_INSTANT_ORDER_V2.placeOrder{value: nativeAssetAmount}({
_tokenToSell: placeOrderArgs.tokenToSell,
_tokenToBuy: placeOrderArgs.tokenToBuy,
_quantityToSell: placeOrderArgs.quantityToSell,
_limitAmountToGet: placeOrderArgs.limitAmountToGet,
_receiver: address(this),
_referenceId: referenceId
});
}
/// @dev Helper to add the orderId to storage
function __addOrder(OrderDetails memory _orderDetails) private {
uint256 orderId = ALICE_INSTANT_ORDER_V2.getMostRecentOrderId() + 1;
orderIds.push(orderId);
orderIdToOrderDetails[orderId] = _orderDetails;
emit OrderIdAdded(orderId, _orderDetails);
}
/// @dev Helper to add a reference ID to storage
function __addReferenceId(bytes32 _referenceId) private {
referenceIdToIsPending[_referenceId] = true;
emit ReferenceIdAdded(_referenceId);
}
/// @dev Helper to check whether an order has settled or been cancelled
function __isOrderSettledOrCancelled(uint256 _orderId) private view returns (bool isSettledOrCancelled_) {
// When an order has been settled or cancelled, its orderHash getter will throw
try ALICE_INSTANT_ORDER_V2.getOrderHash({_orderId: _orderId}) {
return false;
} catch {
return true;
}
}
/// @dev Helper to remove the orderId from storage
function __removeOrder(uint256 _orderId) private {
orderIds.removeStorageItem(_orderId);
// Reset the mapping
delete orderIdToOrderDetails[_orderId];
emit OrderIdRemoved(_orderId);
}
/// @dev Helper to remove a reference ID from storage
function __removeReferenceId(bytes32 _referenceId) private {
delete referenceIdToIsPending[_referenceId];
emit ReferenceIdRemoved(_referenceId);
}
/// @dev Helper to send the balance of an AliceV2 order asset to the Vault
function __retrieveAssetBalance(IERC20 _asset, address _receiver) private {
uint256 balance =
address(_asset) == ALICEV2_NATIVE_ASSET_ADDRESS ? address(this).balance : _asset.balanceOf(address(this));
if (balance > 0) {
// Transfer the asset
if (address(_asset) == ALICEV2_NATIVE_ASSET_ADDRESS) {
Address.sendValue(payable(_receiver), balance);
} else {
_asset.safeTransfer(_receiver, balance);
}
}
}
////////////////////
// POSITION VALUE //
////////////////////
/// @notice Retrieves the debt assets (negative value) of the external position
/// @return assets_ Debt assets
/// @return amounts_ Debt asset amounts
function getDebtAssets() external view override returns (address[] memory assets_, uint256[] memory amounts_) {}
/// @notice Retrieves the managed assets (positive value) of the external position
/// @return assets_ Managed assets
/// @return amounts_ Managed asset amounts
/// @dev There are 2 ways that positive value can be contributed to this position
/// 1. Tokens held by the EP either as a result of order settlements or as a result of order cancellations
/// 2. Tokens held in pending (unfulfilled and uncancelled) orders
function getManagedAssets() external view override returns (address[] memory assets_, uint256[] memory amounts_) {
uint256[] memory orderIdsMem = getOrderIds();
address[] memory receivableAssets;
for (uint256 i; i < orderIdsMem.length; i++) {
OrderDetails memory orderDetails = getOrderDetails({_orderId: orderIdsMem[i]});
bool settledOrCancelled = __isOrderSettledOrCancelled({_orderId: orderIdsMem[i]});
// If the order is settled or cancelled, the EP will have received the incomingAsset or the outgoingAsset
// Incoming assets can be received through order settlements
// Outgoing assets can be received back through order cancellations
// We have no way of differentiating between the two, so we must add both to the expected assets
if (settledOrCancelled) {
receivableAssets = receivableAssets.addUniqueItem(orderDetails.outgoingAssetAddress);
receivableAssets = receivableAssets.addUniqueItem(orderDetails.incomingAssetAddress);
} else {
// If the order is not settled, value the position for its refundable value
assets_ = assets_.addItem(
orderDetails.outgoingAssetAddress == ALICEV2_NATIVE_ASSET_ADDRESS
? address(WRAPPED_NATIVE_TOKEN)
: orderDetails.outgoingAssetAddress
);
amounts_ = amounts_.addItem(orderDetails.outgoingAmount);
}
}
// Check the balance EP balance of each asset that could be received
for (uint256 i; i < receivableAssets.length; i++) {
address receivableAssetAddress = receivableAssets[i];
uint256 balance = receivableAssetAddress == ALICEV2_NATIVE_ASSET_ADDRESS
? address(this).balance
: IERC20(receivableAssetAddress).balanceOf(address(this));
if (balance == 0) {
continue;
}
assets_ = assets_.addItem(
receivableAssetAddress == ALICEV2_NATIVE_ASSET_ADDRESS
? address(WRAPPED_NATIVE_TOKEN)
: receivableAssetAddress
);
amounts_ = amounts_.addItem(balance);
}
return __aggregateAssetAmounts({_rawAssets: assets_, _rawAmounts: amounts_});
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Get the orderDetails of a specified orderId
/// @return orderDetails_ The orderDetails
function getOrderDetails(uint256 _orderId) public view override returns (OrderDetails memory orderDetails_) {
return orderIdToOrderDetails[_orderId];
}
/// @notice Get the pending orderIds of the external position
/// @return orderIds_ The orderIds
function getOrderIds() public view override returns (uint256[] memory orderIds_) {
return orderIds;
}
/// @notice Get whether a referenceId belongs to a pending order or not
/// @return isPending_ Whether the referenceId belongs to a pending order or not
function isPendingReferenceId(bytes32 _referenceId) public view override returns (bool isPending_) {
return referenceIdToIsPending[_referenceId];
}
}
"
},
"lib/openzeppelin-solc-0.8/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
"
},
"contracts/external-interfaces/IAliceInstantOrderV2.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity >=0.6.0 <0.9.0;
/// @title IAliceInstantOrderV2 Interface
/// @author Enzyme Foundation <security@enzyme.finance>
interface IAliceInstantOrderV2 {
function placeOrder(address _tokenToSell, address _tokenToBuy, uint256 _quantityToSell, uint256 _limitAmountToGet)
external
payable;
function placeOrder(
address _tokenToSell,
address _tokenToBuy,
uint256 _quantityToSell,
uint256 _limitAmountToGet,
address _receiver,
bytes32 _referenceId
) external payable;
function refundOrder(
uint256 _orderId,
address _user,
address _tokenToSell,
address _tokenToBuy,
uint256 _quantityToSell,
uint256 _limitAmountToGet,
uint256 _timestamp
) external;
function getOrderHash(uint256 _orderId) external view returns (bytes32 orderHash_);
function getMostRecentOrderId() external view returns (uint256 orderId_);
}
"
},
"contracts/external-interfaces/IAliceReferenceIdReceiver.sol": {
"content": "/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.9.0;
/// @title IAliceReferenceIdReceiver Interface
/// @author Enzyme Foundation <security@enzyme.finance>
interface IAliceReferenceIdReceiver {
function notifySettle(address _token, uint256 _amount, bytes32 _referenceId) external;
function notifyCancel(bytes32 _referenceId) external;
}
"
},
"contracts/external-interfaces/IERC20.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.9.0;
/// @title IERC20 Interface
/// @author Enzyme Foundation <security@enzyme.finance>
interface IERC20 {
// IERC20 - strict
function allowance(address _owner, address _spender) external view returns (uint256 allowance_);
function approve(address _spender, uint256 _value) external returns (bool approve_);
function balanceOf(address _account) external view returns (uint256 balanceOf_);
function totalSupply() external view returns (uint256 totalSupply_);
function transfer(address _to, uint256 _value) external returns (bool transfer_);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool transferFrom_);
// IERC20 - typical
function decimals() external view returns (uint8 decimals_);
function name() external view returns (string memory name_);
function symbol() external view returns (string memory symbol_);
}
"
},
"contracts/external-interfaces/IWETH.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity >=0.6.0 <0.9.0;
/// @title IWETH Interface
/// @author Enzyme Foundation <security@enzyme.finance>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
"
},
"contracts/persistent/external-positions/IExternalPositionProxy.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity >=0.6.0 <0.9.0;
/// @title IExternalPositionProxy interface
/// @author Enzyme Foundation <security@enzyme.finance>
/// @notice An interface for publicly accessible functions on the ExternalPositionProxy
interface IExternalPositionProxy {
function getExternalPositionType() external view returns (uint256 typeId_);
function getVaultProxy() external view returns (address vaultProxy_);
function receiveCallFromVault(bytes memory _data) external;
}
"
},
"contracts/utils/0.8.19/AddressArrayLib.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.8.19;
/// @title AddressArray Library
/// @author Enzyme Foundation <security@enzyme.finance>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) {
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
/// @dev Helper to verify if a storage array contains a particular value
function storageArrayContains(address[] storage _self, address _target) internal view returns (bool doesContain_) {
uint256 arrLength = _self.length;
for (uint256 i; i < arrLength; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) {
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) {
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
"
},
"contracts/utils/0.8.19/Uint256ArrayLib.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.8.19;
/// @title Uint256Array Library
/// @author Enzyme Foundation <security@enzyme.finance>
/// @notice A library to extend the uint256 array data type
library Uint256ArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(uint256[] storage _self, uint256 _itemToRemove) internal returns (bool removed_) {
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
/// @dev Helper to verify if a storage array contains a particular value
function storageArrayContains(uint256[] storage _self, uint256 _target) internal view returns (bool doesContain_) {
uint256 arrLength = _self.length;
for (uint256 i; i < arrLength; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(uint256[] memory _self, uint256 _itemToAdd) internal pure returns (uint256[] memory nextArray_) {
nextArray_ = new uint256[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(uint256[] memory _self, uint256 _itemToAdd)
internal
pure
returns (uint256[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(uint256[] memory _self, uint256 _target) internal pure returns (bool doesContain_) {
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(uint256[] memory _self, uint256[] memory _arrayToMerge)
internal
pure
returns (uint256[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new uint256[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(uint256[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(uint256[] memory _self, uint256[] memory _itemsToRemove)
internal
pure
returns (uint256[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new uint256[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
"
},
"contracts/utils/0.8.19/AssetHelpers.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.8.19;
import {IERC20} from "../../external-interfaces/IERC20.sol";
import {WrappedSafeERC20 as SafeERC20} from "../../utils/0.8.19/open-zeppelin/WrappedSafeERC20.sol";
/// @title AssetHelpers Contract
/// @author Enzyme Foundation <security@enzyme.finance>
/// @notice A util contract for common token actions
abstract contract AssetHelpers {
using SafeERC20 for IERC20;
/// @dev Helper to aggregate amounts of the same assets
function __aggregateAssetAmounts(address[] memory _rawAssets, uint256[] memory _rawAmounts)
internal
pure
returns (address[] memory aggregatedAssets_, uint256[] memory aggregatedAmounts_)
{
if (_rawAssets.length == 0) {
return (aggregatedAssets_, aggregatedAmounts_);
}
uint256 aggregatedAssetCount = 1;
for (uint256 i = 1; i < _rawAssets.length; i++) {
bool contains;
for (uint256 j; j < i; j++) {
if (_rawAssets[i] == _rawAssets[j]) {
contains = true;
break;
}
}
if (!contains) {
aggregatedAssetCount++;
}
}
aggregatedAssets_ = new address[](aggregatedAssetCount);
aggregatedAmounts_ = new uint256[](aggregatedAssetCount);
uint256 aggregatedAssetIndex;
for (uint256 i; i < _rawAssets.length; i++) {
bool contains;
for (uint256 j; j < aggregatedAssetIndex; j++) {
if (_rawAssets[i] == aggregatedAssets_[j]) {
contains = true;
aggregatedAmounts_[j] += _rawAmounts[i];
break;
}
}
if (!contains) {
aggregatedAssets_[aggregatedAssetIndex] = _rawAssets[i];
aggregatedAmounts_[aggregatedAssetIndex] = _rawAmounts[i];
aggregatedAssetIndex++;
}
}
return (aggregatedAssets_, aggregatedAmounts_);
}
/// @dev Helper to approve a target account with the max amount of an asset.
/// This is helpful for fully trusted contracts, such as adapters that
/// interact with external protocol like Uniswap, Compound, etc.
function __approveAssetMaxAsNeeded(address _asset, address _target, uint256 _neededAmount) internal {
uint256 allowance = IERC20(_asset).allowance(address(this), _target);
if (allowance < _neededAmount) {
if (allowance > 0) {
IERC20(_asset).safeApprove(_target, 0);
}
IERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to transfer full asset balance from the current contract to a target
function __pushFullAssetBalance(address _target, address _asset) internal returns (uint256 amountTransferred_) {
amountTransferred_ = IERC20(_asset).balanceOf(address(this));
if (amountTransferred_ > 0) {
IERC20(_asset).safeTransfer(_target, amountTransferred_);
}
return amountTransferred_;
}
/// @dev Helper to transfer full asset balances from the current contract to a target
function __pushFullAssetBalances(address _target, address[] memory _assets)
internal
returns (uint256[] memory amountsTransferred_)
{
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
IERC20 assetContract = IERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(address(this));
if (amountsTransferred_[i] > 0) {
assetContract.safeTransfer(_target, amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
}
"
},
"contracts/utils/0.8.19/open-zeppelin/WrappedSafeERC20.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.8.19;
import {IERC20 as OpenZeppelinIERC20} from "openzeppelin-solc-0.8/token/ERC20/IERC20.sol";
import {SafeERC20 as OpenZeppelinSafeERC20} from "openzeppelin-solc-0.8/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "../../../external-interfaces/IERC20.sol";
/// @title WrappedSafeERC20 Library
/// @author Enzyme Foundation <security@enzyme.finance>
/// @notice Wraps OpenZeppelin's SafeERC20 library to use the local IERC20 interface for inputs
library WrappedSafeERC20 {
function safeApprove(IERC20 _token, address _spender, uint256 _value) internal {
OpenZeppelinSafeERC20.safeApprove({token: __castToken(_token), spender: _spender, value: _value});
}
function safeDecreaseAllowance(IERC20 _token, address _spender, uint256 _value) internal {
OpenZeppelinSafeERC20.safeDecreaseAllowance({token: __castToken(_token), spender: _spender, value: _value});
}
function safeIncreaseAllowance(IERC20 _token, address _spender, uint256 _value) internal {
OpenZeppelinSafeERC20.safeIncreaseAllowance({token: __castToken(_token), spender: _spender, value: _value});
}
function safeTransfer(IERC20 _token, address _to, uint256 _value) internal {
OpenZeppelinSafeERC20.safeTransfer({token: __castToken(_token), to: _to, value: _value});
}
function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _value) internal {
OpenZeppelinSafeERC20.safeTransferFrom({token: __castToken(_token), from: _from, to: _to, value: _value});
}
function __castToken(IERC20 _token) private pure returns (OpenZeppelinIERC20 token_) {
return OpenZeppelinIERC20(address(_token));
}
}
"
},
"contracts/release/extensions/external-position-manager/external-positions/alice-v2/bases/AliceV2PositionLibBase1.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.8.19;
/// @title AliceV2PositionLibBase1 Contract
/// @author Enzyme Foundation <security@enzyme.finance>
/// @notice A persistent contract containing all required storage variables and
/// required functions for a AliceV2PositionLib implementation
/// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to
/// a numbered AliceV2PositionLibBaseXXX that inherits the previous base.
/// e.g., `AliceV2PositionLibBase2 is AliceV2PositionLibBase1`
abstract contract AliceV2PositionLibBase1 {
struct OrderDetails {
address outgoingAssetAddress;
address incomingAssetAddress;
uint256 outgoingAmount;
}
event OrderIdAdded(uint256 indexed orderId, OrderDetails orderDetails);
event OrderIdRemoved(uint256 indexed orderId);
event ReferenceIdAdded(bytes32 indexed referenceId);
event ReferenceIdRemoved(bytes32 indexed referenceId);
uint256[] internal orderIds;
mapping(uint256 orderId => OrderDetails) orderIdToOrderDetails;
mapping(bytes32 referenceId => bool isPending) internal referenceIdToIsPending;
}
"
},
"contracts/release/extensions/external-position-manager/external-positions/alice-v2/IAliceV2Position.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import {IExternalPosition} from "../../IExternalPosition.sol";
import {AliceV2PositionLibBase1} from "./bases/AliceV2PositionLibBase1.sol";
pragma solidity >=0.6.0 <0.9.0;
/// @title IAliceV2Position Interface
/// @author Enzyme Foundation <security@enzyme.finance>
interface IAliceV2Position is IExternalPosition {
enum Actions {
PlaceOrder,
RefundOrder,
Sweep,
PlaceOrderWithRefId
}
struct PlaceOrderActionArgs {
address tokenToSell;
address tokenToBuy;
uint256 quantityToSell;
uint256 limitAmountToGet;
}
struct SweepActionArgs {
uint256[] orderIds;
}
struct RefundOrderActionArgs {
uint256 orderId;
address tokenToSell;
address tokenToBuy;
uint256 quantityToSell;
uint256 limitAmountToGet;
uint256 timestamp;
}
function getOrderDetails(uint256 _orderId)
external
view
returns (AliceV2PositionLibBase1.OrderDetails memory orderDetails_);
function getOrderIds() external view returns (uint256[] memory orderIds_);
function isPendingReferenceId(bytes32 _referenceId) external view returns (bool isPending_);
}
"
},
"lib/openzeppelin-solc-0.8/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
"
},
"lib/openzeppelin-solc-0.8/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
"
},
"contracts/release/extensions/external-position-manager/IExternalPosition.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity >=0.6.0 <0.9.0;
import {IExternalPositionLibCore} from "../../../persistent/external-positions/IExternalPositionLibCore.sol";
/// @title IExternalPosition Contract
/// @author Enzyme Foundation <security@enzyme.finance>
interface IExternalPosition is IExternalPositionLibCore {
function getDebtAssets() external returns (address[] memory assets_, uint256[] memory amounts_);
function getManagedAssets() external returns (address[] memory assets_, uint256[] memory amounts_);
function init(bytes memory _data) external;
}
"
},
"lib/openzeppelin-solc-0.8/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
"
},
"contracts/persistent/external-positions/IExternalPositionLibCore.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Foundation <security@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity >=0.6.0 <0.9.0;
/// @title IExternalPositionLibCore interface
/// @author Enzyme Foundation <security@enzyme.finance>
/// @notice An interface for core required
Submitted on: 2025-10-15 11:28:55
Comments
Log in to comment.
No comments yet.