// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import "../interfaces/IAavePool.sol"; import "../interfaces/IERC20.sol"; /** * @title AaveSupplyBorrow * @notice Example contract for supplying collateral and borrowing on Aave v3 */ contract AaveSupplyBorrow { IAavePool public immutable pool; constructor(address pool_) { pool = IAavePool(pool_); } /** * @notice Supply collateral, enable as collateral, and borrow * @param asset The collateral asset to supply * @param amount The amount of collateral to supply * @param debtAsset The asset to borrow * @param borrowAmount The amount to borrow */ function supplyAndBorrow( address asset, uint256 amount, address debtAsset, uint256 borrowAmount ) external { // Step 1: Transfer collateral from user IERC20(asset).transferFrom(msg.sender, address(this), amount); // Step 2: Approve pool to take collateral IERC20(asset).approve(address(pool), amount); // Step 3: Supply collateral pool.supply(asset, amount, address(this), 0); // Step 4: Enable as collateral pool.setUserUseReserveAsCollateral(asset, true); // Step 5: Borrow (variable rate = 2, stable rate is deprecated) pool.borrow(debtAsset, borrowAmount, 2, 0, address(this)); // Step 6: Transfer borrowed tokens to user IERC20(debtAsset).transfer(msg.sender, borrowAmount); } /** * @notice Repay debt and withdraw collateral * @param debtAsset The debt asset to repay * @param repayAmount The amount to repay * @param collateralAsset The collateral asset to withdraw * @param withdrawAmount The amount to withdraw */ function repayAndWithdraw( address debtAsset, uint256 repayAmount, address collateralAsset, uint256 withdrawAmount ) external { // Step 1: Transfer repayment tokens from user IERC20(debtAsset).transferFrom(msg.sender, address(this), repayAmount); // Step 2: Approve pool to take repayment IERC20(debtAsset).approve(address(pool), repayAmount); // Step 3: Repay debt (variable rate = 2) pool.repay(debtAsset, repayAmount, 2, address(this)); // Step 4: Withdraw collateral pool.withdraw(collateralAsset, withdrawAmount, address(this)); // Step 5: Transfer collateral to user IERC20(collateralAsset).transfer(msg.sender, withdrawAmount); } }