文件 1 的 17:Address.sol
pragma solidity ^0.8.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
文件 2 的 17:CompoundStrategy.sol
pragma solidity 0.8.3;
import "../Strategy.sol";
import "../../interfaces/compound/ICompound.sol";
abstract contract CompoundStrategy is Strategy {
using SafeERC20 for IERC20;
CToken internal cToken;
address internal constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
Comptroller internal constant COMPTROLLER = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
constructor(
address _pool,
address _swapManager,
address _receiptToken
) Strategy(_pool, _swapManager, _receiptToken) {
require(_receiptToken != address(0), "cToken-address-is-zero");
cToken = CToken(_receiptToken);
swapSlippage = 10000;
}
function totalValue() public view virtual override returns (uint256 _totalValue) {
_totalValue = _calculateTotalValue(COMPTROLLER.compAccrued(address(this)));
}
function totalValueCurrent() external virtual override returns (uint256 _totalValue) {
_claimComp();
_totalValue = _calculateTotalValue(IERC20(COMP).balanceOf(address(this)));
}
function _calculateTotalValue(uint256 _compAccrued) internal view returns (uint256 _totalValue) {
if (_compAccrued != 0) {
(, _totalValue) = swapManager.bestPathFixedInput(COMP, address(collateralToken), _compAccrued, 0);
}
_totalValue += _convertToCollateral(cToken.balanceOf(address(this)));
}
function isReservedToken(address _token) public view virtual override returns (bool) {
return _token == address(cToken) || _token == COMP;
}
function _approveToken(uint256 _amount) internal virtual override {
collateralToken.safeApprove(pool, _amount);
collateralToken.safeApprove(address(cToken), _amount);
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
IERC20(COMP).safeApprove(address(swapManager.ROUTERS(i)), _amount);
}
}
function _beforeMigration(address _newStrategy) internal virtual override {
_claimComp();
IERC20(COMP).safeTransfer(_newStrategy, IERC20(COMP).balanceOf(address(this)));
}
function _claimComp() internal {
address[] memory _markets = new address[](1);
_markets[0] = address(cToken);
COMPTROLLER.claimComp(address(this), _markets);
}
function _claimRewardsAndConvertTo(address _toToken) internal virtual override {
_claimComp();
uint256 _compAmount = IERC20(COMP).balanceOf(address(this));
if (_compAmount != 0) {
uint256 minAmtOut =
(swapSlippage != 10000)
? _calcAmtOutAfterSlippage(
_getOracleRate(_simpleOraclePath(COMP, _toToken), _compAmount),
swapSlippage
)
: 1;
_safeSwap(COMP, _toToken, _compAmount, minAmtOut);
}
}
function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) {
if (_excessDebt != 0) {
_payback = _safeWithdraw(_excessDebt);
}
}
function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) {
_claimRewardsAndConvertTo(address(collateralToken));
uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this)));
if (_collateralBalance > _totalDebt) {
_withdrawHere(_collateralBalance - _totalDebt);
}
return collateralToken.balanceOf(address(this));
}
function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) {
uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this)));
if (_collateralBalance < _totalDebt) {
_loss = _totalDebt - _collateralBalance;
}
}
function _reinvest() internal virtual override {
uint256 _collateralBalance = collateralToken.balanceOf(address(this));
if (_collateralBalance != 0) {
require(cToken.mint(_collateralBalance) == 0, "deposit-to-compound-failed");
}
}
function _withdraw(uint256 _amount) internal override {
_safeWithdraw(_amount);
collateralToken.safeTransfer(pool, collateralToken.balanceOf(address(this)));
}
function _safeWithdraw(uint256 _amount) internal returns (uint256) {
uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this)));
uint256 _availableLiquidity = cToken.getCash();
uint256 _withdrawAmount = _amount < _availableLiquidity ? _amount : _availableLiquidity;
return _withdrawHere(_withdrawAmount < _collateralBalance ? _withdrawAmount : _collateralBalance);
}
function _withdrawHere(uint256 _amount) internal returns (uint256) {
if (_amount != 0) {
require(cToken.redeemUnderlying(_amount) == 0, "withdraw-from-compound-failed");
_afterRedeem();
}
return _amount;
}
function _setupOracles() internal virtual override {
swapManager.createOrUpdateOracle(COMP, WETH, oraclePeriod, oracleRouterIdx);
if (address(collateralToken) != WETH) {
swapManager.createOrUpdateOracle(WETH, address(collateralToken), oraclePeriod, oracleRouterIdx);
}
}
function _afterRedeem() internal virtual {}
function _convertToCollateral(uint256 _cTokenAmount) internal view returns (uint256) {
return (_cTokenAmount * cToken.exchangeRateStored()) / 1e18;
}
}
文件 3 的 17:Context.sol
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this;
return msg.data;
}
}
文件 4 的 17:IAddressList.sol
pragma solidity 0.8.3;
interface IAddressList {
function add(address a) external returns (bool);
function remove(address a) external returns (bool);
function get(address a) external view returns (uint256);
function contains(address a) external view returns (bool);
function length() external view returns (uint256);
function grantRole(bytes32 role, address account) external;
}
文件 5 的 17:IAddressListFactory.sol
pragma solidity 0.8.3;
interface IAddressListFactory {
function ours(address a) external view returns (bool);
function listCount() external view returns (uint256);
function listAt(uint256 idx) external view returns (address);
function createList() external returns (address listaddr);
}
文件 6 的 17:ICompound.sol
pragma solidity 0.8.3;
interface CToken {
function accrueInterest() external returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrow(uint256 borrowAmount) external returns (uint256);
function mint() external payable;
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function repayBorrow() external payable;
function repayBorrow(uint256 repayAmount) external returns (uint256);
function transfer(address user, uint256 amount) external returns (bool);
function getCash() external view returns (uint256);
function transferFrom(
address owner,
address user,
uint256 amount
) external returns (bool);
function underlying() external view returns (address);
}
interface Comptroller {
function claimComp(address holder, address[] memory) external;
function enterMarkets(address[] memory cTokens) external returns (uint256[] memory);
function exitMarket(address cToken) external returns (uint256);
function compAccrued(address holder) external view returns (uint256);
function getAccountLiquidity(address account)
external
view
returns (
uint256,
uint256,
uint256
);
function markets(address market)
external
view
returns (
bool isListed,
uint256 collateralFactorMantissa,
bool isCompted
);
}
文件 7 的 17:IComptroller.sol
pragma solidity 0.8.3;
interface IComptroller {
function cTokensByUnderlying(address) external view returns (address cToken);
}
文件 8 的 17:IERC20.sol
pragma solidity ^0.8.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
文件 9 的 17:IFusePoolDirectory.sol
pragma solidity 0.8.3;
interface IFusePoolDirectory {
function pools(uint256)
external
view
returns (
string memory name,
address creator,
address comptroller,
uint256 blockPosted,
uint256 timestampPosted
);
}
文件 10 的 17:IStrategy.sol
pragma solidity 0.8.3;
interface IStrategy {
function rebalance() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function feeCollector() external view returns (address);
function isReservedToken(address _token) external view returns (bool);
function migrate(address _newStrategy) external;
function token() external view returns (address);
function totalValue() external view returns (uint256);
function totalValueCurrent() external returns (uint256);
function pool() external view returns (address);
}
文件 11 的 17:ISwapManager.sol
pragma solidity 0.8.3;
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
interface ISwapManager {
event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period);
function N_DEX() external view returns (uint256);
function ROUTERS(uint256 i) external view returns (IUniswapV2Router02);
function bestOutputFixedInput(
address _from,
address _to,
uint256 _amountIn
)
external
view
returns (
address[] memory path,
uint256 amountOut,
uint256 rIdx
);
function bestPathFixedInput(
address _from,
address _to,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function bestInputFixedOutput(
address _from,
address _to,
uint256 _amountOut
)
external
view
returns (
address[] memory path,
uint256 amountIn,
uint256 rIdx
);
function bestPathFixedOutput(
address _from,
address _to,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function safeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function safeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function comparePathsFixedInput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function comparePathsFixedOutput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function ours(address a) external view returns (bool);
function oracleCount() external view returns (uint256);
function oracleAt(uint256 idx) external view returns (address);
function getOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external view returns (address);
function createOrUpdateOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external returns (address oracleAddr);
function consultForFree(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
) external view returns (uint256 amountOut, uint256 lastUpdatedAt);
function consult(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
)
external
returns (
uint256 amountOut,
uint256 lastUpdatedAt,
bool updated
);
function updateOracles() external returns (uint256 updated, uint256 expected);
function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected);
}
文件 12 的 17:IUniswapV2Router01.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
文件 13 的 17:IUniswapV2Router02.sol
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
文件 14 的 17:IVesperPool.sol
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../bloq/IAddressList.sol";
interface IVesperPool is IERC20 {
function deposit() external payable;
function deposit(uint256 _share) external;
function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool);
function excessDebt(address _strategy) external view returns (uint256);
function permit(
address,
address,
uint256,
uint256,
uint8,
bytes32,
bytes32
) external;
function poolRewards() external returns (address);
function reportEarning(
uint256 _profit,
uint256 _loss,
uint256 _payback
) external;
function reportLoss(uint256 _loss) external;
function resetApproval() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function withdrawETH(uint256 _amount) external;
function whitelistedWithdraw(uint256 _amount) external;
function governor() external view returns (address);
function keepers() external view returns (IAddressList);
function maintainers() external view returns (IAddressList);
function feeCollector() external view returns (address);
function pricePerShare() external view returns (uint256);
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
);
function stopEverything() external view returns (bool);
function token() external view returns (IERC20);
function tokensHere() external view returns (uint256);
function totalDebtOf(address _strategy) external view returns (uint256);
function totalValue() external view returns (uint256);
function withdrawFee() external view returns (uint256);
}
文件 15 的 17:RariFuseStrategy.sol
pragma solidity 0.8.3;
import "../compound/CompoundStrategy.sol";
import "../../interfaces/rari-fuse/IComptroller.sol";
import "../../interfaces/rari-fuse/IFusePoolDirectory.sol";
contract RariFuseStrategy is CompoundStrategy {
using SafeERC20 for IERC20;
string public constant NAME = "RariFuse-Strategy";
string public constant VERSION = "3.0.13";
uint256 public fusePoolId;
address private constant FUSE_POOL_DIRECTORY = 0x835482FE0532f169024d5E9410199369aAD5C77E;
event FusePoolChanged(uint256 indexed newFusePoolId, address indexed oldCToken, address indexed newCToken);
constructor(
address _pool,
address _swapManager,
uint256 _fusePoolId
) CompoundStrategy(_pool, _swapManager, _cTokenByUnderlying(_fusePoolId, address(IVesperPool(_pool).token()))) {
fusePoolId = _fusePoolId;
}
function totalValue() public view override returns (uint256 _totalValue) {
_totalValue = _convertToCollateral(cToken.balanceOf(address(this)));
}
function migrateFusePool(uint256 _newPoolId) external virtual onlyGovernor {
address _newCToken = _cTokenByUnderlying(_newPoolId, address(collateralToken));
require(address(cToken) != _newCToken, "same-fuse-pool");
require(cToken.redeem(cToken.balanceOf(address(this))) == 0, "withdraw-from-fuse-pool-failed");
uint256 _collateralBalance = collateralToken.balanceOf(address(this));
collateralToken.safeApprove(_newCToken, _collateralBalance);
require(CToken(_newCToken).mint(_collateralBalance) == 0, "deposit-to-fuse-pool-failed");
emit FusePoolChanged(_newPoolId, address(cToken), _newCToken);
cToken = CToken(_newCToken);
receiptToken = _newCToken;
fusePoolId = _newPoolId;
}
function isReservedToken(address _token) public view override returns (bool) {
return _token == address(cToken);
}
function _cTokenByUnderlying(uint256 _poolId, address _collateralToken) internal view returns (address) {
(, , address _comptroller, , ) = IFusePoolDirectory(FUSE_POOL_DIRECTORY).pools(_poolId);
require(_comptroller != address(0), "rari-fuse-invalid-comptroller");
if (_collateralToken == WETH) {
_collateralToken = address(0x0);
}
address _cToken = IComptroller(_comptroller).cTokensByUnderlying(_collateralToken);
require(_cToken != address(0), "rari-fuse-invalid-ctoken");
return _cToken;
}
function _beforeMigration(address _newStrategy) internal override {}
function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) {
uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this)));
if (_collateralBalance > _totalDebt) {
_withdrawHere(_collateralBalance - _totalDebt);
}
return collateralToken.balanceOf(address(this));
}
}
文件 16 的 17:SafeERC20.sol
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
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));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
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 _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
文件 17 的 17:Strategy.sol
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "../interfaces/bloq/ISwapManager.sol";
import "../interfaces/bloq/IAddressList.sol";
import "../interfaces/bloq/IAddressListFactory.sol";
import "../interfaces/vesper/IStrategy.sol";
import "../interfaces/vesper/IVesperPool.sol";
abstract contract Strategy is IStrategy, Context {
using SafeERC20 for IERC20;
IERC20 public immutable collateralToken;
address public receiptToken;
address public immutable override pool;
IAddressList public keepers;
address public override feeCollector;
ISwapManager public swapManager;
uint256 public oraclePeriod = 3600;
uint256 public oracleRouterIdx = 0;
uint256 public swapSlippage = 10000;
address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 internal constant MAX_UINT_VALUE = type(uint256).max;
event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector);
event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager);
event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage);
event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx);
constructor(
address _pool,
address _swapManager,
address _receiptToken
) {
require(_pool != address(0), "pool-address-is-zero");
require(_swapManager != address(0), "sm-address-is-zero");
swapManager = ISwapManager(_swapManager);
pool = _pool;
collateralToken = IVesperPool(_pool).token();
receiptToken = _receiptToken;
}
modifier onlyGovernor {
require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor");
_;
}
modifier onlyKeeper() {
require(keepers.contains(_msgSender()), "caller-is-not-a-keeper");
_;
}
modifier onlyPool() {
require(_msgSender() == pool, "caller-is-not-vesper-pool");
_;
}
function addKeeper(address _keeperAddress) external onlyGovernor {
require(keepers.add(_keeperAddress), "add-keeper-failed");
}
function init(address _addressListFactory) external onlyGovernor {
require(address(keepers) == address(0), "keeper-list-already-created");
IAddressListFactory _factory = IAddressListFactory(_addressListFactory);
keepers = IAddressList(_factory.createList());
require(keepers.add(_msgSender()), "add-keeper-failed");
}
function migrate(address _newStrategy) external virtual override onlyPool {
require(_newStrategy != address(0), "new-strategy-address-is-zero");
require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy");
_beforeMigration(_newStrategy);
IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this)));
collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this)));
}
function removeKeeper(address _keeperAddress) external onlyGovernor {
require(keepers.remove(_keeperAddress), "remove-keeper-failed");
}
function updateFeeCollector(address _feeCollector) external onlyGovernor {
require(_feeCollector != address(0), "fee-collector-address-is-zero");
require(_feeCollector != feeCollector, "fee-collector-is-same");
emit UpdatedFeeCollector(feeCollector, _feeCollector);
feeCollector = _feeCollector;
}
function updateSwapManager(address _swapManager) external onlyGovernor {
require(_swapManager != address(0), "sm-address-is-zero");
require(_swapManager != address(swapManager), "sm-is-same");
emit UpdatedSwapManager(address(swapManager), _swapManager);
swapManager = ISwapManager(_swapManager);
}
function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor {
require(_newSwapSlippage <= 10000, "invalid-slippage-value");
emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage);
swapSlippage = _newSwapSlippage;
}
function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor {
require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index");
if (_newPeriod == 0) _newPeriod = oraclePeriod;
require(_newPeriod > 59, "invalid-oracle-period");
emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx);
oraclePeriod = _newPeriod;
oracleRouterIdx = _newRouterIdx;
}
function approveToken() external onlyKeeper {
_approveToken(0);
_approveToken(MAX_UINT_VALUE);
}
function setupOracles() external onlyKeeper {
_setupOracles();
}
function withdraw(uint256 _amount) external override onlyPool {
_withdraw(_amount);
}
function rebalance() external virtual override onlyKeeper {
(uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport();
IVesperPool(pool).reportEarning(_profit, _loss, _payback);
_reinvest();
}
function sweepERC20(address _fromToken) external override onlyKeeper {
require(feeCollector != address(0), "fee-collector-not-set");
require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral");
require(!isReservedToken(_fromToken), "not-allowed-to-sweep");
if (_fromToken == ETH) {
Address.sendValue(payable(feeCollector), address(this).balance);
} else {
uint256 _amount = IERC20(_fromToken).balanceOf(address(this));
IERC20(_fromToken).safeTransfer(feeCollector, _amount);
}
}
function token() external view override returns (address) {
return receiptToken;
}
function convertFrom18(uint256 amount) public pure virtual returns (uint256) {
return amount;
}
function totalValue() public view virtual override returns (uint256 _value);
function totalValueCurrent() external virtual override returns (uint256) {
return totalValue();
}
function isReservedToken(address _token) public view virtual override returns (bool);
function _beforeMigration(address _newStrategy) internal virtual;
function _generateReport()
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _payback
)
{
uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this));
uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this));
_profit = _realizeProfit(_totalDebt);
_loss = _realizeLoss(_totalDebt);
_payback = _liquidate(_excessDebt);
}
function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) {
return (_amount * (10000 - _slippage)) / (10000);
}
function _simpleOraclePath(address _from, address _to) internal pure returns (address[] memory path) {
if (_from == WETH || _to == WETH) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = WETH;
path[2] = _to;
}
}
function _consultOracle(
address _from,
address _to,
uint256 _amt
) internal returns (uint256, bool) {
(uint256 rate, uint256 lastUpdate, ) = swapManager.consult(_from, _to, _amt, oraclePeriod, oracleRouterIdx);
if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true);
return (0, false);
}
function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) {
require(path.length > 1, "invalid-oracle-path");
amountOut = _amountIn;
bool isValid;
for (uint256 i = 0; i < path.length - 1; i++) {
(amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut);
require(isValid, "invalid-oracle-rate");
}
}
function _safeSwap(
address _from,
address _to,
uint256 _amountIn,
uint256 _minAmountOut
) internal {
(address[] memory path, uint256 amountOut, uint256 rIdx) =
swapManager.bestOutputFixedInput(_from, _to, _amountIn);
if (_minAmountOut == 0) _minAmountOut = 1;
if (amountOut != 0) {
swapManager.ROUTERS(rIdx).swapExactTokensForTokens(
_amountIn,
_minAmountOut,
path,
address(this),
block.timestamp
);
}
}
function _claimRewardsAndConvertTo(address _toToken) internal virtual {}
function _setupOracles() internal virtual {}
function _withdraw(uint256 _amount) internal virtual;
function _approveToken(uint256 _amount) internal virtual;
function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback);
function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit);
function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss);
function _reinvest() internal virtual;
}
{
"compilationTarget": {
"contracts/strategies/rari-fuse/RariFuseStrategy.sol": "RariFuseStrategy"
},
"evmVersion": "istanbul",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"_pool","type":"address"},{"internalType":"address","name":"_swapManager","type":"address"},{"internalType":"uint256","name":"_fusePoolId","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"newFusePoolId","type":"uint256"},{"indexed":true,"internalType":"address","name":"oldCToken","type":"address"},{"indexed":true,"internalType":"address","name":"newCToken","type":"address"}],"name":"FusePoolChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousFeeCollector","type":"address"},{"indexed":true,"internalType":"address","name":"newFeeCollector","type":"address"}],"name":"UpdatedFeeCollector","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldPeriod","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newPeriod","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"oldRouterIdx","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newRouterIdx","type":"uint256"}],"name":"UpdatedOracleConfig","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousSwapManager","type":"address"},{"indexed":true,"internalType":"address","name":"newSwapManager","type":"address"}],"name":"UpdatedSwapManager","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldSwapSlippage","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newSwapSlippage","type":"uint256"}],"name":"UpdatedSwapSlippage","type":"event"},{"inputs":[],"name":"NAME","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_keeperAddress","type":"address"}],"name":"addKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"approveToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"collateralToken","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"convertFrom18","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"feeCollector","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fusePoolId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_addressListFactory","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"isReservedToken","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"keepers","outputs":[{"internalType":"contract IAddressList","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_newStrategy","type":"address"}],"name":"migrate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newPoolId","type":"uint256"}],"name":"migrateFusePool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"oraclePeriod","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oracleRouterIdx","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pool","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rebalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"receiptToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_keeperAddress","type":"address"}],"name":"removeKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"setupOracles","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"swapManager","outputs":[{"internalType":"contract ISwapManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"swapSlippage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_fromToken","type":"address"}],"name":"sweepERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"token","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalValue","outputs":[{"internalType":"uint256","name":"_totalValue","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalValueCurrent","outputs":[{"internalType":"uint256","name":"_totalValue","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_feeCollector","type":"address"}],"name":"updateFeeCollector","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newPeriod","type":"uint256"},{"internalType":"uint256","name":"_newRouterIdx","type":"uint256"}],"name":"updateOracleConfig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_swapManager","type":"address"}],"name":"updateSwapManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newSwapSlippage","type":"uint256"}],"name":"updateSwapSlippage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}]