// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {BaseYieldAdapter, IMeldFarming} from "../yield-adapters/BaseYieldAdapter.sol";
import {IPool} from "../interfaces/yield-adapters/aave-v3/IPool.sol";
import {IPoolDataProvider} from "../interfaces/yield-adapters/aave-v3/IPoolDataProvider.sol";
import {
IPoolAddressesProvider
} from "../interfaces/yield-adapters/aave-v3/IPoolAddressesProvider.sol";
import {Errors} from "../libraries/Errors.sol";
/**
* @title Aave v3 Yield Adapter
* @notice Contract to interact with the Aave v3 protocol
* @author MELD team
*/
contract AaveV3YieldAdapter is BaseYieldAdapter {
using SafeERC20 for IERC20;
IPool public pool;
IPoolDataProvider public dataProvider;
mapping(address asset => uint256 deposit) public depositTracking;
mapping(address asset => IERC20 aToken) public aTokens;
/**
* @notice Emitted when the adapter is deployed and the Aave addresses are set
* @param executedBy Address that executed the function
* @param pool Aave Pool
* @param dataProvider Aave Data Provider
*/
event AaveAddressesSet(
address indexed executedBy,
address indexed pool,
address indexed dataProvider
);
/**
* @notice Emitted when an asset is configured for the adapter
* @param executedBy Address that executed the function
* @param asset Asset configured
* @param aToken Aave Token corresponding to the asset
*/
event AaveAssetConfigured(
address indexed executedBy,
address indexed asset,
address indexed aToken
);
/**
* @notice Constructor
* @param _meldFarmingManager MELD Farming Manager
* @param _aaveAddressesProvider Aave Addresses Provider
*/
constructor(
address _meldFarmingManager,
address _aaveAddressesProvider
) BaseYieldAdapter(_meldFarmingManager) {
IPoolAddressesProvider provider = IPoolAddressesProvider(_aaveAddressesProvider);
pool = IPool(provider.getPool());
dataProvider = IPoolDataProvider(provider.getPoolDataProvider());
emit AaveAddressesSet(msg.sender, address(pool), address(dataProvider));
}
/**
* @inheritdoc IMeldFarming
*/
function deposit(
address _asset,
uint256 _amount,
bytes calldata
) external override onlyMeldFarmingManager {
IERC20(_asset).safeTransferFrom(meldFarmingManager, address(this), _amount);
pool.supply(_asset, _amount, address(this), 0);
depositTracking[_asset] += _amount;
_verifyStatus(_asset);
emit Deposited(_asset, _amount);
}
/**
* @inheritdoc IMeldFarming
*/
function withdraw(
address _asset,
uint256 _amount,
bytes calldata
) external override onlyMeldFarmingManager returns (uint256) {
uint256 amount = _amount;
if (_amount == type(uint256).max) {
amount = getAvailableLiquidity(_asset);
}
depositTracking[_asset] -= amount;
uint256 actualAmount = _withdrawAndSendToFarmingManager(_asset, amount);
require(actualAmount == amount, Errors.AAVE_ADAPTER_INVALID_WITHDRAWN_AMOUNT);
emit Withdrawn(_asset, amount);
return actualAmount;
}
/**
* @inheritdoc IMeldFarming
*/
function claimRewards(
address _asset,
bytes calldata,
bool _withdrawOnlyAvailable
) external override onlyMeldFarmingManager returns (uint256) {
uint256 amount = getRewardsAmount(_asset);
if (_withdrawOnlyAvailable) {
amount = _getAmountOrAvailable(_asset, amount);
}
if (amount == 0) {
return 0;
}
uint256 actualAmount = _withdrawAndSendToFarmingManager(_asset, amount);
require(actualAmount == amount, Errors.AAVE_ADAPTER_INVALID_WITHDRAWN_AMOUNT);
return amount;
}
/**
* @notice Configures the aToken address for the `_asset`
* @dev This function needs to be called before start using the adapter for that asset
* @param _asset Asset to configure
*/
function configAsset(address _asset) external {
(address aTokenAddress, , ) = dataProvider.getReserveTokensAddresses(_asset);
aTokens[_asset] = IERC20(aTokenAddress);
_safeApproveAll(IERC20(_asset), address(pool));
emit AaveAssetConfigured(msg.sender, _asset, aTokenAddress);
}
/**
* @inheritdoc IMeldFarming
* @dev It will return the minimum between the deposit amount and the pool balance (balance of _asset in the aToken contract)
* @dev It also confirms that the aToken balance is consistent with the deposit amount
*/
function getAvailableLiquidity(address _asset) public view override returns (uint256) {
uint256 depositAmount = depositTracking[_asset];
return _getAmountOrAvailable(_asset, depositAmount);
}
/**
* @inheritdoc IMeldFarming
*/
function getRewardsAmount(address _asset) public view override returns (uint256) {
IERC20 aToken = aTokens[_asset];
return aToken.balanceOf(address(this)) - depositTracking[_asset];
}
/**
* @notice Withdraws the `_amount` of `_asset` from the aave pool and sends it to the MELD Farming Manager
* @param _asset Asset to withdraw
* @param _amount Amount to withdraw
* @return actualAmount Actual amount withdrawn
*/
function _withdrawAndSendToFarmingManager(
address _asset,
uint256 _amount
) private returns (uint256 actualAmount) {
actualAmount = pool.withdraw(_asset, _amount, meldFarmingManager);
_verifyStatus(_asset);
}
/**
* @notice Private function to safe approve all the tokens to the spender
* @param _token Token to approve
* @param _spender Spender to approve
*/
function _safeApproveAll(IERC20 _token, address _spender) private {
uint256 allowance = _token.allowance(address(this), _spender);
uint256 increaseAllowance = type(uint256).max - allowance;
if (increaseAllowance > 0) {
_token.safeIncreaseAllowance(_spender, increaseAllowance);
}
}
/**
* @notice Verifies the status of the aToken balance
* @dev It will revert if the aToken balance is less than the deposit amount
* @param _asset Asset to check
*/
function _verifyStatus(address _asset) private view {
uint256 aTokenBalance = aTokens[_asset].balanceOf(address(this));
require(
aTokenBalance >= depositTracking[_asset],
Errors.AAVE_ADAPTER_INCONSISTENT_ATOKEN_BALANCE
);
}
/**
* @notice Checks if there's enough balance in the Aave protocol to withdraw `_amount`
* @param _asset Address of the token
* @param _amount Amount to check against available liquidity
*/
function _getAmountOrAvailable(address _asset, uint256 _amount) private view returns (uint256) {
uint256 poolBalance = IERC20(_asset).balanceOf(address(aTokens[_asset]));
return _amount <= poolBalance ? _amount : poolBalance;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {
IERC1155Receiver,
IERC165
} from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import {IMeldFarming} from "../interfaces/IMeldFarming.sol";
import {IMeldFarmingManager} from "../interfaces/IMeldFarmingManager.sol";
import {IMeldBridgeReceiver} from "../interfaces/IMeldBridgeReceiver.sol";
import {Errors} from "../libraries/Errors.sol";
import {RescueTokens} from "../RescueTokens.sol";
/**
* @title Base Yield Adapter
* @notice Abstract base contract for the yield adapters
* @dev Implements the IMeldFarming interface and adds the onlyMeldFarmingManager modifier
* @author MELD team
*/
abstract contract BaseYieldAdapter is
RescueTokens,
IERC721Receiver,
IERC1155Receiver,
IMeldFarming
{
address public override meldFarmingManager;
/**
* @notice Emitted when the Meld Farming Manager is set
* @param executedBy Address that executed the function
* @param meldFarmingManager Address of the Meld Farming Manager
*/
event MeldFarmingManagerSet(address indexed executedBy, address indexed meldFarmingManager);
/**
* @notice Modifier to check that the caller is the default admin
*/
modifier onlyDefaultAdmin() {
IMeldBridgeReceiver(IMeldFarmingManager(meldFarmingManager).bridge()).checkRole(
0x00,
msg.sender
);
_;
}
/**
* @notice Modifier to check that the caller is the Meld Farming Manager
*/
modifier onlyMeldFarmingManager() {
require(msg.sender == meldFarmingManager, Errors.BYA_ONLY_FARMING_MANAGER_ALLOWED);
_;
}
/**
* @notice Constructor of the Base Yield Adapter
* @param _meldFarmingManager Address of the Meld Farming Manager
*/
constructor(address _meldFarmingManager) {
meldFarmingManager = _meldFarmingManager;
emit MeldFarmingManagerSet(msg.sender, _meldFarmingManager);
}
/**
* @notice Rescue ERC20 tokens stuck in this contract
* @dev Only the default admin can call this function
* @param _token The address of the ERC20 token
* @param _to The address to send the ERC20 tokens to
*/
function rescueERC20(address _token, address _to) external virtual onlyDefaultAdmin {
_rescueERC20(_token, _to);
}
/**
* @notice Rescue ERC721 tokens stuck in this contract
* @dev Only the default admin can call this function
* @param _token The address of the ERC721 token
* @param _to The address to send the ERC721 tokens to
* @param _tokenId The ID of the ERC721 token
*/
function rescueERC721(
address _token,
address _to,
uint256 _tokenId
) external virtual onlyDefaultAdmin {
_rescueERC721(_token, _to, _tokenId);
}
/**
* @notice Rescue ERC1155 tokens stuck in this contract
* @dev Only the default admin can call this function
* @param _token The address of the ERC1155 token
* @param _to The address to send the ERC1155 tokens to
* @param _tokenId The ID of the ERC1155 token
*/
function rescueERC1155(
address _token,
address _to,
uint256 _tokenId
) external virtual onlyDefaultAdmin {
_rescueERC1155(_token, _to, _tokenId);
}
/**
* @inheritdoc IERC721Receiver
*/
function onERC721Received(
address,
address,
uint256,
bytes calldata
) public pure override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @inheritdoc IERC1155Receiver
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) public pure override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @inheritdoc IERC1155Receiver
*/
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) public pure override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
/**
* @inheritdoc IERC165
* @dev Also supports the IMeldFarming interface. Needed to be added to the MeldFarmingManager
*/
function supportsInterface(bytes4 _interfaceId) public pure override returns (bool) {
return
_interfaceId == type(IMeldFarming).interfaceId ||
_interfaceId == type(IERC1155Receiver).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/**
* @title Errors library
* @notice Defines the error messages emitted by the different contracts of the Meld Bridge
* @dev Error messages prefix glossary:
* - MBP: Meld Bridge Panoptic
* - MBR: Meld Bridge Receiver
* - MFM: Meld Farming Manager
* - BYA: Base Yield Adapter
* @author MELD team
*/
library Errors {
string public constant INVALID_ARRAY_LENGTH = "Invalid array length";
string public constant TOKEN_NOT_SUPPORTED = "Token is not supported";
string public constant REQUEST_ALREADY_PROCESSED = "Request already processed";
string public constant INVALID_ADDRESS = "Invalid address";
string public constant INVALID_AMOUNT = "Invalid amount";
string public constant MBP_REQUEST_NOT_PROCESSED = "MeldBridgePanoptic: Request not processed";
string public constant MBP_NETWORK_NOT_SUPPORTED =
"MeldBridgePanoptic: Network is not supported for this token";
string public constant MBP_INSUFFICIENT_FEE = "MeldBridgePanoptic: Insufficient fee";
string public constant MBP_TRANSFERRING_FEE_FAILED =
"MeldBridgePanoptic: Transferring fee failed";
string public constant MBP_SIGNATURE_EXPIRED = "MeldBridgePanoptic: Signature is expired";
string public constant MBR_ONLY_WETH_ALLOWED =
"MeldBridgeReceiver: Only WETH can deposit ETH directly to the contract";
string public constant MBR_NATIVE_NOT_SUPPORTED =
"MeldBridgeReceiver: Native Token is not supported";
string public constant MBR_NATIVE_WRAPPING_FAILED =
"MeldBridgeReceiver: Native wrapping failed";
string public constant MBR_NATIVE_TOKEN_NOT_WETH =
"MeldBridgeReceiver: Native token withdraw is not WETH";
string public constant MFM_ONLY_BRIDGE_ALLOWED =
"MeldFarmingManager: Only bridge can call this function";
string public constant MFM_ADAPTER_ALREADY_EXISTS =
"MeldFarmingManager: Adapter already exists";
string public constant MFM_ADAPTER_ADDRESS_ALREADY_EXISTS =
"MeldFarmingManager: Adapter address already exists";
string public constant MFM_ADAPTER_DOES_NOT_EXIST =
"MeldFarmingManager: Adapter does not exist";
string public constant MFM_ADAPTER_DISABLED = "MeldFarmingManager: Adapter is disabled";
string public constant MFM_AMOUNT_MISMATCH = "MeldFarmingManager: Amount mismatch";
string public constant MFM_NOT_ENOUGH_FUNDS = "MeldFarmingManager: Not enough funds";
string public constant MFM_INVALID_ADAPTER_ID = "MeldFarmingManager: Invalid adapter ID";
string public constant MFM_NO_ADAPTERS_CONFIGURED =
"MeldFarmingManager: No adapters configured";
string public constant MFM_INVALID_ADAPTER_MFM =
"MeldFarmingManager: Invalid adapter MeldFarmingManager address";
string public constant MFM_ADAPTER_IS_NOT_MELD_FARMING =
"MeldFarmingManager: Adapter does not implement IMeldFarming";
string public constant RT_NO_TOKENS_TO_RESCUE = "RescueTokens: No tokens to rescue";
string public constant RT_RESCUER_NOT_OWNER =
"RescueTokens: Contract is not the owner of the token";
string public constant BYA_ONLY_FARMING_MANAGER_ALLOWED =
"BaseYieldAdapter: Only MeldFarmingManager can call this function";
string public constant AAVE_ADAPTER_INCONSISTENT_ATOKEN_BALANCE =
"AaveAdapter: Inconsistent aToken balance";
string public constant AAVE_ADAPTER_INVALID_WITHDRAWN_AMOUNT =
"AaveAdapter: Invalid withdrawn amount";
string public constant GOGOPOOL_ONLY_WAVAX_ALLOWED = "GoGoPoolAdapter: Only WAVAX is allowed";
string public constant GOGOPOOL_AVAX_RECEIVED_OUTSIDE_WINDOW =
"GoGoPoolAdapter: AVAX received outside window";
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] calldata accounts,
uint256[] calldata ids
) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== 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
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/**
* @title Meld Bridge Base interface
* @notice Interface for the Meld Bridge Base contract, to set supported tokens and check roles
* @author MELD team
*/
interface IMeldBridgeBase {
/**
* @notice Emitted when a token is supported or unsupported
* @param executedBy Address that executed the event
* @param token Address of the token
* @param supported True if the token is supported, false if unsupported
*/
event SupportedTokenSet(address indexed executedBy, address indexed token, bool supported);
/**
* @notice Set the supported status of a token
* @param _token Address of the token
* @param _supported True if the token is supported, false if unsupported
*/
function setSupportedToken(address _token, bool _supported) external;
/**
* @notice Check if an account has a role. Reverts if the account does not have the role
* @param _role Role to check
* @param _account Account to check
*/
function checkRole(bytes32 _role, address _account) external view;
/**
* @notice Role for configuration
* @return Role
*/
function CONFIGURATION_ROLE() external view returns (bytes32); // solhint-disable-line func-name-mixedcase
/**
* @notice Role for execution of requests
* @return Role
*/
function EXECUTION_ROLE() external view returns (bytes32); // solhint-disable-line func-name-mixedcase
/**
* @notice Check if a token is supported
* @param _token Address of the token
* @return True if the token is supported
*/
function supportedTokens(address _token) external view returns (bool);
/**
* @notice Check if a request has been processed
* @param _requestId ID of the request
* @return True if the request has been processed
*/
function processedRequests(bytes32 _requestId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IMeldBridgeBase} from "./IMeldBridgeBase.sol";
/**
* @title Meld Bridge Receiver interface
* @notice Interface for interacting with the Meld Bridge Receiver contract
* @author MELD team
*/
interface IMeldBridgeReceiver is IMeldBridgeBase {
/**
* @notice Event emitted when a user requests to bridge tokens
* @param user Address of the user
* @param token Address of the token
* @param amount Amount of tokens to bridge
*/
event BridgeRequested(address indexed user, address indexed token, uint256 amount);
/**
* @notice Event emitted when the wETH address is set
* @param executedBy Address that executed the action
* @param wETH Address of the wETH contract
*/
event WETHAddressSet(address indexed executedBy, address indexed wETH);
/**
* @notice Event emitted when the Meld Farming Manager is deployed
* @param executedBy Address that executed the action
* @param meldFarmingManagerAddress Address of the Meld Farming Manager
*/
event MeldFarmingManagerDeployed(
address indexed executedBy,
address indexed meldFarmingManagerAddress
);
/**
* @notice Event emitted when a user requests to bridge ERC721 tokens
* @param user Address of the user
* @param token Address of the token
* @param tokenId Token ID to bridge
*/
event BridgeERC721Requested(address indexed user, address indexed token, uint256 tokenId);
/**
* @notice Event emitted when a user requests to bridge ERC1155 tokens
* @param user Address of the user
* @param token Address of the token
* @param tokenId Token ID to bridge
* @param amount Amount of tokens to bridge
*/
event BridgeERC1155Requested(
address indexed user,
address indexed token,
uint256 tokenId,
uint256 amount
);
/**
* @notice Event emitted when ERC20 tokens are withdrawn to a user
* @param token Address of the token
* @param to Address of the user
* @param amount Amount of tokens withdrawn
* @param requestID ID of the request
*/
event WithdrawnToUser(
address indexed token,
address indexed to,
uint256 amount,
bytes32 indexed requestID
);
/**
* @notice Event emitted when ERC721 tokens are withdrawn to a user
* @param token Address of the token
* @param to Address of the user
* @param tokenId Token ID withdrawn
* @param requestID ID of the request
*/
event WithdrawnERC721ToUser(
address indexed token,
address indexed to,
uint256 tokenId,
bytes32 indexed requestID
);
/**
* @notice Event emitted when ERC1155 tokens are withdrawn to a user
* @param token Address of the token
* @param to Address of the user
* @param tokenId Token ID withdrawn
* @param amount Amount of tokens withdrawn
* @param requestID ID of the request
*/
event WithdrawnERC1155ToUser(
address indexed token,
address indexed to,
uint256 tokenId,
uint256 amount,
bytes32 indexed requestID
);
/**
* @notice Function called to bridge ERC20 tokens
* @param _token Address of the token
* @param _amount Amount of tokens to bridge
*/
function bridge(address _token, uint256 _amount) external;
/**
* @notice Function called to bridge native tokens
* @dev This function is payable so the amount of tokens to bridge is the value sent with the transaction
*/
function bridgeNative() external payable;
/**
* @notice Function called to bridge ERC721 tokens
* @param _token Address of the token
* @param _tokenId Token ID to bridge
*/
function bridgeERC721(address _token, uint256 _tokenId) external;
/**
* @notice Function called to bridge ERC1155 tokens
* @param _token Address of the token
* @param _tokenId Token ID to bridge
* @param _amount Amount of tokens to bridge
*/
function bridgeERC1155(address _token, uint256 _tokenId, uint256 _amount) external;
/**
* @notice Function called to withdraw tokens to a user
* @param _token Address of the token
* @param _to Address of the user
* @param _amount Amount of tokens to withdraw
* @param _requestID ID of the request
* @param _extra Additional data
*/
function withdrawToUser(
address _token,
address _to,
uint256 _amount,
bytes32 _requestID,
bytes calldata _extra
) external;
/**
* @notice Function called to withdraw ERC721 tokens to a user
* @param _token Address of the token
* @param _to Address of the user
* @param _tokenId Token ID to withdraw
* @param _requestID ID of the request
*/
function withdrawERC721ToUser(
address _token,
address _to,
uint256 _tokenId,
bytes32 _requestID
) external;
/**
* @notice Function called to withdraw ERC1155 tokens to a user
* @param _token Address of the token
* @param _to Address of the user
* @param _tokenId Token ID to withdraw
* @param _amount Amount of tokens to withdraw
* @param _requestID ID of the request
*/
function withdrawERC1155ToUser(
address _token,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes32 _requestID
) external;
/**
* @notice Function called to withdraw tokens to multiple users
* @param _token Address of the token
* @param _to Addresses of the users
* @param _amount Amounts of tokens to withdraw
* @param _requestID IDs of the requests
* @param _extra Additional data
*/
function withdrawToUsers(
address _token,
address[] calldata _to,
uint256[] calldata _amount,
bytes32[] calldata _requestID,
bytes[] calldata _extra
) external;
/**
* @notice Function called to withdraw ERC721 tokens to multiple users
* @param _token Address of the token
* @param _to Addresses of the users
* @param _tokenId Token IDs to withdraw
* @param _requestID IDs of the requests
*/
function withdrawERC721ToUsers(
address _token,
address[] calldata _to,
uint256[] calldata _tokenId,
bytes32[] calldata _requestID
) external;
/**
* @notice Function called to withdraw ERC1155 tokens to multiple users
* @param _token Address of the token
* @param _to Addresses of the users
* @param _tokenId Token IDs to withdraw
* @param _amount Amounts of tokens to withdraw
* @param _requestID IDs of the requests
*/
function withdrawERC1155ToUsers(
address _token,
address[] calldata _to,
uint256[] calldata _tokenId,
uint256[] calldata _amount,
bytes32[] calldata _requestID
) external;
/**
* @notice Returns the bytes32 identifier for the REBALANCER_ROLE
*/
function REBALANCER_ROLE() external view returns (bytes32); // solhint-disable-line func-name-mixedcase
/**
* @notice Returns the address of the wETH contract
*/
function wETHAddress() external view returns (address payable);
/**
* @notice Returns the address of the Meld Farming Manager
*/
function getFarmingManagerAddress() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @title Meld Farming interface
* @notice Interface for the Meld Farming Manager contract as well as the adapters
* @author MELD team
*/
interface IMeldFarming is IERC165 {
/**
* @notice Emitted when an asset is deposited
* @param asset Address of the asset
* @param amount Amount deposited
*/
event Deposited(address indexed asset, uint256 amount);
/**
* @notice Emitted when an asset is withdrawn
* @param asset Address of the asset
* @param amount Amount withdrawn
*/
event Withdrawn(address indexed asset, uint256 amount);
/**
* @notice Deposits funds into the Meld Farming Manager or the adapter
* @param _asset Address of the asset to deposit
* @param _amount Amount to deposit
* @param _extra Extra data for the deposit
*/
function deposit(address _asset, uint256 _amount, bytes calldata _extra) external;
/**
* @notice Withdraws funds from the Meld Farming Manager or the adapter
* @param _asset Address of the asset to withdraw
* @param _amount Amount to withdraw
* @param _extra Extra data for the withdraw
* @return Amount withdrawn
*/
function withdraw(
address _asset,
uint256 _amount,
bytes calldata _extra
) external returns (uint256);
/**
* @notice Claims rewards from the adapter
* @param _asset Address of the asset to claim
* @param _extra Extra data for the claim
* @param _withdrawOnlyAvailable If true, only claims the rewards up to the available liquidity. If false and there's not enough liquidity, it reverts
* @return Amount claimed
*/
function claimRewards(
address _asset,
bytes calldata _extra,
bool _withdrawOnlyAvailable
) external returns (uint256);
/**
* @notice Returns the total available liquidity for a given asset
* @param _asset Address of the asset
* @return Available liquidity
*/
function getAvailableLiquidity(address _asset) external view returns (uint256);
/**
* @notice Returns the amount of rewards available for the `_asset`
* @param _asset Address of the asset
* @return Amount of rewards available
*/
function getRewardsAmount(address _asset) external view returns (uint256);
/**
* @notice Returns the address of the Meld Farming Manager
* @return Address of the Meld Farming Manager
*/
function meldFarmingManager() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IMeldFarming} from "./IMeldFarming.sol";
import {IMeldBridgeReceiver} from "./IMeldBridgeReceiver.sol";
/**
* @title Meld Farming Manager interface
* @notice Interface for the Meld Farming Manager contract
* @dev This interface also includes the IMeldFarming interface
* @author MELD team
*/
interface IMeldFarmingManager is IMeldFarming {
struct AdapterConfig {
string adapterIdStr;
bool enabled;
bool locked;
bool exists;
}
struct YieldAssetAdapter {
uint256 yieldDeposit;
uint256 index;
uint256 lastTimestampRewardsClaimed;
bool exists;
}
struct YieldAssetConfig {
uint256 liquidDeposit;
mapping(uint256 index => address adapterAddress) adapterIndex;
mapping(address adapterAddress => YieldAssetAdapter) adapters;
uint256 numAdapters;
}
struct RebalancingInfo {
address asset;
address adapterAddress;
uint256 amount;
RebalanceAction action;
bytes extra;
}
enum RebalanceAction {
NONE,
DEPOSIT,
WITHDRAW,
REQUEST_WITHDRAW
}
/**
* @notice Emitted when the Meld Bridge Receiver contract is set
* @param bridge Address of the Meld Bridge Receiver contract
*/
event BridgeSet(address indexed executedBy, address bridge);
/**
* @notice Emitted when the treasury address is updated
* @param executedBy Address that executed the function
* @param oldTreasury Address of the old treasury
* @param newTreasury Address of the new treasury
*/
event TreasuryUpdated(
address indexed executedBy,
address indexed oldTreasury,
address indexed newTreasury
);
/**
* @notice Emitted when a new adapter is added
* @param executedBy Address that executed the function
* @param adapterIdStr String ID of the adapter
* @param adapterAddress Address of the adapter
* @param locked Boolean indicating if the adapter is locked
*/
event AdapterAdded(
address executedBy,
string indexed adapterIdStr,
address indexed adapterAddress,
bool locked
);
/**
* @notice Emitted when an adapter is enabled or disabled
* @param executedBy Address that executed the function
* @param adapterAddress Address of the adapter
* @param enabled Boolean indicating if the adapter is enabled
*/
event AdapterEnabled(address indexed executedBy, address indexed adapterAddress, bool enabled);
/**
* @notice Emitted when an asset is configured with adapters
* @param executedBy Address that executed the function
* @param asset Address of the asset
* @param adapterAddresses Array of adapter addresses
*/
event AssetConfigSet(
address indexed executedBy,
address indexed asset,
address[] adapterAddresses
);
/**
* @notice Emitted when rewards are claimed
* @param executedBy Address that executed the function
* @param asset Address of the asset
* @param adapterAddress Address of the adapter
* @param amount Amount claimed
*/
event RewardsClaimed(
address indexed executedBy,
address indexed asset,
address indexed adapterAddress,
uint256 amount
);
/**
* @notice Emitted when a rebalance is executed
* @param executedBy Address that executed the function
* @param asset Address of the asset
* @param adapterAddress Address of the adapter
* @param amount Amount rebalanced
* @param action Rebalance action. 0: None, 1: Deposit, 2: Withdraw, 3: Request Withdraw
*/
event Rebalanced(
address executedBy,
address indexed asset,
address indexed adapterAddress,
uint256 amount,
RebalanceAction indexed action
);
/**
* @notice Adds a new adapter to the Meld Farming Manager
* @param _adapterId String ID of the adapter
* @param _adapterAddress Address of the adapter
* @param _locked Boolean indicating if the adapter is locked
*/
function addAdapter(string memory _adapterId, address _adapterAddress, bool _locked) external;
/**
* @notice Enables or disables an adapter
* @param _adapterAddress Address of the adapter
* @param _enabled Boolean indicating if the adapter is enabled
*/
function setAdapterEnabled(address _adapterAddress, bool _enabled) external;
/**
* @notice Configures an asset with adapters
* @dev The list of adapters will be the new one, so any previous configuration will be overwritten
* @dev To remove all adapters, pass an empty array
* @dev It is needed to call this function even if no adapters will be used for the asset
* @param _asset Address of the asset
* @param _adaptersAddresses Array of adapter addresses
*/
function configAsset(address _asset, address[] memory _adaptersAddresses) external;
/**
* @notice Sets the treasury address that will receive the rewards
* @param _treasury Address of the treasury
*/
function setTreasury(address _treasury) external;
/**
* @notice Moves funds between the adapters and the Meld Farming Manager
* @param _rebalanceInfo Array of RebalancingInfo, indicating the asset, adapter, amount and action
*/
function rebalance(RebalancingInfo[] calldata _rebalanceInfo) external;
/**
* @notice Returns the adapter address for a given index
* @param _index Index of the adapter
* @return Adapter address
*/
function adapterAddresses(uint256 _index) external view returns (address);
/**
* @notice Returns the number of adapters
* @return Number of adapters
*/
function numAdapters() external view returns (uint256);
/**
* @notice Returns the Meld Bridge Receiver contract address
* @return Meld Bridge Receiver contract address
*/
function bridge() external view returns (IMeldBridgeReceiver);
/**
* @notice Returns the treasury address
* @return Treasury address
*/
function treasury() external view returns (address);
/**
* @notice Returns the adapter configuration for a given ID
* @param _adapterAddress Address of the adapter
* @return Adapter configuration
*/
function getAdapter(address _adapterAddress) external view returns (AdapterConfig memory);
/**
* @notice Returns the adapter configuration for all adapters
* @return Array of every Adapter configuration
*/
function getAllAdapters() external view returns (AdapterConfig[] memory);
/**
* @notice Returns the asset configuration for a given asset
* @param _asset Address of the asset
* @return assetAdapterIds Array of the adapter IDs for each adapter
* @return assetAdapterAddressess Array of the adapter addresses for each adapter
* @return yieldDeposit Array of the yield deposit for each adapter
* @return lastTimestampRewardsClaimed Array of the last timestamp rewards claimed for each adapter
* @return liquidDeposit Liquid deposit for the asset
* @return totalDeposit Total deposit for the asset
* @return totalAvailableLiquidity Total available liquidity for the asset
*/
function getYieldAssetConfig(
address _asset
)
external
view
returns (
string[] memory assetAdapterIds,
address[] memory assetAdapterAddressess,
uint256[] memory yieldDeposit,
uint256[] memory lastTimestampRewardsClaimed,
uint256 liquidDeposit,
uint256 totalDeposit,
uint256 totalAvailableLiquidity
);
/**
* @notice Returns the total deposit for a given asset
* @param _asset Address of the asset
* @return Total deposit
*/
function getTotalDeposit(address _asset) external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
/**
* @title IPool
* @author Aave
* @notice Defines the basic interface for an Aave Pool.
* @dev --- This is a minimal interface to be used by the Meld Yield Adapter ---
*/
interface IPool {
/**
* @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User supplies 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to supply
* @param amount The amount to be supplied
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
*/
function supply(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to The address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
*/
function withdraw(address asset, uint256 amount, address to) external returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
/**
* @title IPoolAddressesProvider
* @author Aave
* @notice Defines the basic interface for a Pool Addresses Provider.
* @dev --- This is a minimal interface to be used by the Meld Yield Adapter ---
*/
interface IPoolAddressesProvider {
/**
* @notice Returns the address of the Pool proxy.
* @return The Pool proxy address
*/
function getPool() external view returns (address);
/**
* @notice Returns the address of the data provider.
* @return The address of the DataProvider
*/
function getPoolDataProvider() external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
/**
* @title IPoolDataProvider
* @author Aave
* @notice Defines the basic interface of a PoolDataProvider
* @dev --- This is a minimal interface to be used by the Meld Yield Adapter ---
*/
interface IPoolDataProvider {
/**
* @notice Returns the token addresses of the reserve
* @param asset The address of the underlying asset of the reserve
* @return aTokenAddress The AToken address of the reserve
* @return stableDebtTokenAddress The StableDebtToken address of the reserve
* @return variableDebtTokenAddress The VariableDebtToken address of the reserve
*/
function getReserveTokensAddresses(
address asset
)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {Errors} from "./libraries/Errors.sol";
/**
* @title RescueTokens
* @notice A contract that can rescue ERC20, ERC721, and ERC1155 tokens stuck in it
* @dev This contract is abstract and must be inherited by another contract
* @author MELD team
*/
abstract contract RescueTokens {
using SafeERC20 for IERC20;
/**
* @notice Rescue ERC20 tokens stuck in this contract
* @param _token The address of the ERC20 token
* @param _to The address to send the ERC20 tokens to
*/
function _rescueERC20(address _token, address _to) internal virtual {
uint256 balance = IERC20(_token).balanceOf(address(this));
require(balance > 0, Errors.RT_NO_TOKENS_TO_RESCUE);
IERC20(_token).safeTransfer(_to, balance);
}
/**
* @notice Rescue ERC721 tokens stuck in this contract
* @param _token The address of the ERC721 token
* @param _to The address to send the ERC721 tokens to
* @param _tokenId The ID of the ERC721 token
*/
function _rescueERC721(address _token, address _to, uint256 _tokenId) internal virtual {
require(IERC721(_token).ownerOf(_tokenId) == address(this), Errors.RT_RESCUER_NOT_OWNER);
IERC721(_token).safeTransferFrom(address(this), _to, _tokenId);
}
/**
* @notice Rescue ERC1155 tokens stuck in this contract
* @param _token The address of the ERC1155 token
* @param _to The address to send the ERC1155 tokens to
* @param _tokenId The ID of the ERC1155 token
*/
function _rescueERC1155(address _token, address _to, uint256 _tokenId) internal virtual {
uint256 balance = IERC1155(_token).balanceOf(address(this), _tokenId);
require(balance > 0, Errors.RT_NO_TOKENS_TO_RESCUE);
IERC1155(_token).safeTransferFrom(address(this), _to, _tokenId, balance, "");
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
{
"compilationTarget": {
"contracts/yield-adapters/AaveV3YieldAdapter.sol": "AaveV3YieldAdapter"
},
"evmVersion": "shanghai",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"_meldFarmingManager","type":"address"},{"internalType":"address","name":"_aaveAddressesProvider","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"executedBy","type":"address"},{"indexed":true,"internalType":"address","name":"pool","type":"address"},{"indexed":true,"internalType":"address","name":"dataProvider","type":"address"}],"name":"AaveAddressesSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"executedBy","type":"address"},{"indexed":true,"internalType":"address","name":"asset","type":"address"},{"indexed":true,"internalType":"address","name":"aToken","type":"address"}],"name":"AaveAssetConfigured","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"asset","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Deposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"executedBy","type":"address"},{"indexed":true,"internalType":"address","name":"meldFarmingManager","type":"address"}],"name":"MeldFarmingManagerSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"asset","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdrawn","type":"event"},{"inputs":[{"internalType":"address","name":"asset","type":"address"}],"name":"aTokens","outputs":[{"internalType":"contract IERC20","name":"aToken","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_asset","type":"address"},{"internalType":"bytes","name":"","type":"bytes"},{"internalType":"bool","name":"_withdrawOnlyAvailable","type":"bool"}],"name":"claimRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_asset","type":"address"}],"name":"configAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"dataProvider","outputs":[{"internalType":"contract IPoolDataProvider","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_asset","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"}],"name":"depositTracking","outputs":[{"internalType":"uint256","name":"deposit","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_asset","type":"address"}],"name":"getAvailableLiquidity","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_asset","type":"address"}],"name":"getRewardsAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"meldFarmingManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"pool","outputs":[{"internalType":"contract IPool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"rescueERC1155","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_to","type":"address"}],"name":"rescueERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"rescueERC721","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"_interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"_asset","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]