|
{
|
|
"language": "Solidity",
|
|
"sources": {
|
|
"contracts/strategies/aura/AuraStrategyMainnet_stETHBbaUSD.sol": {
|
|
"content": "//SPDX-License-Identifier: Unlicense\npragma solidity 0.5.16;\npragma experimental ABIEncoderV2;\n\nimport \"./base/AuraStrategyBatchSwapJoinPoolUL.sol\";\n\ncontract AuraStrategyMainnet_stETHBbaUSD is AuraStrategyBatchSwapJoinPoolUL {\n\n //Differentiator for the bytecode\n address public bbaUSD_unused;\n\n constructor() public {}\n\n // Swap all reward tokens into WETH\n // Swap WETH into bbaUSD\n // Deposit bbaUSD for 50wstETH-50bb-a-USD\n // Deposit 50wstETH-50bb-a-USD into Aura\n\n function initializeStrategy(\n address _storage, // Harvest: Storage\n address _vault // Harvest: Vault\n ) public initializer {\n address underlying = address(0x25Accb7943Fd73Dda5E23bA6329085a3C24bfb6a); // Balancer: Balancer 50wstETH-50bb-a-USD Pool\n address rewardPool = address(0x8c9E4a04aDb0D543B33cAb644135BFcA523c40C8); // Aura: Balancer 50wstETH-50bb-a-USD Aura Deposit Vault\n bytes32 wETH_USDC = bytes32(0x96646936b91d6b9d7d0c47c496afbf3d6ec7b6f8000200000000000000000019);\n bytes32 USDC_bbaUSDC = bytes32(0x82698aecc9e28e9bb27608bd52cf57f704bd1b83000000000000000000000336);\n bytes32 bbaUSDC_bbaUSD = bytes32(0xa13a9247ea42d743238089903570127dda72fe4400000000000000000000035d);\n address usdc = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);\n address bbaUSDC = address(0x82698aeCc9E28e9Bb27608Bd52cF57f704BD1B83);\n address bbaUSD = address(0xA13a9247ea42D743238089903570127DdA72fE44);\n address wstEth = address(0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0);\n\n poolAssets = [wstEth, bbaUSD];\n // WETH -> USDC -> bb-a-USDC -> bb-a-USD\n swapAssets = [weth, usdc, bbaUSDC, bbaUSD];\n swapPoolIds = [wETH_USDC, USDC_bbaUSDC, bbaUSDC_bbaUSD];\n\n rewardTokens = [bal, aura];\n storedLiquidationPaths[bal][weth] = [bal, weth];\n storedLiquidationDexes[bal][weth] = [balancerDex];\n storedLiquidationPaths[aura][weth] = [aura, weth];\n storedLiquidationDexes[aura][weth] = [balancerDex];\n AuraStrategyBatchSwapJoinPoolUL.initializeBaseStrategy(\n _storage,\n underlying,\n _vault,\n rewardPool,\n 9, // Aura: PoolId\n 0x25accb7943fd73dda5e23ba6329085a3c24bfb6a000200000000000000000387, // Balancer: PoolId\n bbaUSD, //Balancer: Deposit Token\n 1,\n 500\n );\n }\n}\n"
|
|
},
|
|
"contracts/strategies/aura/base/AuraStrategyBatchSwapJoinPoolUL.sol": {
|
|
"content": "//SPDX-License-Identifier: Unlicense\npragma solidity 0.5.16;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts/math/Math.sol\";\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\nimport \"../../../base/upgradability/BaseUpgradeableStrategyUL.sol\";\nimport \"../interface/IAuraBooster.sol\";\nimport \"../interface/IAuraBaseRewardPool.sol\";\nimport \"../../../base/interface/IStrategy.sol\";\nimport \"../../../base/interface/IVault.sol\";\nimport \"../../../base/interface/balancer/IBVault.sol\";\n\ncontract AuraStrategyBatchSwapJoinPoolUL is\n IStrategy,\n BaseUpgradeableStrategyUL\n{\n\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n address public constant booster = address(0xA57b8d98dAE62B26Ec3bcC4a365338157060B234);\n address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);\n address public constant multiSigAddr = address(0xF49440C1F012d041802b25A73e5B0B9166a75c02);\n address public constant bVault = address(0xBA12222222228d8Ba445958a75a0704d566BF2C8);\n address public constant bal = address(0xba100000625a3754423978a60c9317c58a424e3D);\n address public constant aura = address(0xC0c293ce456fF0ED870ADd98a0828Dd4d2903DBF);\n bytes32 public constant balancerDex = bytes32(0x9e73ce1e99df7d45bc513893badf42bc38069f1564ee511b0c8988f72f127b13);\n\n // additional storage slots (on top of BaseUpgradeableStrategy ones) are defined here\n bytes32 internal constant _AURA_POOLID_SLOT = 0xbc10a276e435b4e9a9e92986f93a224a34b50c1898d7551c38ef30a08efadec4;\n bytes32 internal constant _BALANCER_POOLID_SLOT = 0xbf3f653715dd45c84a3367d2975f271307cb967d6ce603dc4f0def2ad909ca64;\n bytes32 internal constant _DEPOSIT_TOKEN_SLOT = 0x219270253dbc530471c88a9e7c321b36afda219583431e7b6c386d2d46e70c86;\n bytes32 internal constant _DEPOSIT_ARRAY_INDEX_SLOT = 0xf5304231d5b8db321cd2f83be554278488120895d3326b9a012d540d75622ba3;\n bytes32 internal constant _HODL_RATIO_SLOT = 0xb487e573671f10704ed229d25cf38dda6d287a35872859d096c0395110a0adb1;\n bytes32 internal constant _HODL_VAULT_SLOT = 0xc26d330f887c749cb38ae7c37873ff08ac4bba7aec9113c82d48a0cf6cc145f2;\n bytes32 internal constant _NTOKENS_SLOT = 0xbb60b35bae256d3c1378ff05e8d7bee588cd800739c720a107471dfa218f74c1;\n\n uint256 public constant hodlRatioBase = 10000;\n address[] public poolAssets;\n address[] public swapAssets;\n address[] public rewardTokens;\n bytes32[] public swapPoolIds;\n\n constructor() public BaseUpgradeableStrategyUL() {\n assert(_AURA_POOLID_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.auraPoolId\")) - 1));\n assert(_BALANCER_POOLID_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.balancerPoolId\")) - 1));\n assert(_DEPOSIT_TOKEN_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.depositToken\")) - 1));\n assert(_DEPOSIT_ARRAY_INDEX_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.depositArrayIndex\")) - 1));\n assert(_HODL_RATIO_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.hodlRatio\")) - 1));\n assert(_HODL_VAULT_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.hodlVault\")) - 1));\n assert(_NTOKENS_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.nTokens\")) - 1));\n }\n\n function initializeBaseStrategy(\n address _storage,\n address _underlying,\n address _vault,\n address _rewardPool,\n uint256 _auraPoolID,\n bytes32 _balancerPoolID,\n address _depositToken,\n uint256 _depositArrayPosition,\n uint256 _hodlRatio\n ) public initializer {\n\n // calculate profit sharing fee depending on hodlRatio\n uint256 profitSharingNumerator = 150;\n if (_hodlRatio >= 1500) {\n profitSharingNumerator = 0;\n }\n else if (_hodlRatio > 0) {\n // (profitSharingNumerator - hodlRatio/10) * hodlRatioBase / (hodlRatioBase - hodlRatio)\n // e.g. with default values: (300 - 1000 / 10) * 10000 / (10000 - 1000)\n // = (300 - 100) * 10000 / 9000 = 222\n profitSharingNumerator = profitSharingNumerator.sub(_hodlRatio.div(10)) // subtract hodl ratio from profit sharing numerator\n .mul(hodlRatioBase) // multiply with hodlRatioBase\n .div(hodlRatioBase.sub(_hodlRatio)); // divide by hodlRatioBase minus hodlRatio\n }\n\n BaseUpgradeableStrategyUL.initialize(\n _storage,\n _underlying,\n _vault,\n _rewardPool,\n weth,\n profitSharingNumerator, // profit sharing numerator\n 1000, // profit sharing denominator\n true, // sell\n 0, // sell floor\n 12 hours, // implementation change delay\n address(0x7882172921E99d590E097cD600554339fBDBc480) //UL Registry\n );\n\n address _lpt;\n (_lpt,,,,,) = IAuraBooster(booster).poolInfo(_auraPoolID);\n require(_lpt == underlying(), \"Pool Info does not match underlying\");\n _setNTokens(poolAssets.length);\n _setDepositArrayIndex(_depositArrayPosition);\n _setAuraPoolId(_auraPoolID);\n _setBalancerPoolId(_balancerPoolID);\n _setDepositToken(_depositToken);\n setUint256(_HODL_RATIO_SLOT, _hodlRatio);\n setAddress(_HODL_VAULT_SLOT, multiSigAddr);\n }\n\n //\n // Set Strategy Metadata Functions\n //\n\n function setHodlRatio(uint256 _value)\n public\n onlyGovernance\n {\n uint256 profitSharingNumerator = 150;\n if (_value >= 1500) {\n profitSharingNumerator = 0;\n }\n else if (_value > 0){\n // (profitSharingNumerator - hodlRatio/10) * hodlRatioBase / (hodlRatioBase - hodlRatio)\n // e.g. with default values: (300 - 1000 / 10) * 10000 / (10000 - 1000)\n // = (300 - 100) * 10000 / 9000 = 222\n profitSharingNumerator = profitSharingNumerator.sub(_value.div(10)) // subtract hodl ratio from profit sharing numerator\n .mul(hodlRatioBase) // multiply with hodlRatioBase\n .div(hodlRatioBase.sub(_value)); // divide by hodlRatioBase minus hodlRatio\n }\n _setProfitSharingNumerator(profitSharingNumerator);\n setUint256(_HODL_RATIO_SLOT, _value);\n }\n\n function setHodlVault(address _address)\n public\n onlyGovernance\n {\n setAddress(_HODL_VAULT_SLOT, _address);\n }\n\n /** Resumes the ability to invest into the underlying reward pools\n */\n function continueInvesting()\n public\n onlyGovernance\n {\n _setPausedInvesting(false);\n }\n\n /** Can completely disable claiming UNI rewards and selling. Good for emergency withdraw in the\n * simplest possible way.\n */\n function setSell(bool s)\n public\n onlyGovernance\n {\n _setSell(s);\n }\n\n /** Sets the minimum amount of CRV needed to trigger a sale.\n */\n function setSellFloor(uint256 floor)\n public\n onlyGovernance\n {\n _setSellFloor(floor);\n }\n\n /** Aura deposit pool ID\n */\n function _setAuraPoolId(uint256 _value)\n internal\n {\n setUint256(_AURA_POOLID_SLOT, _value);\n }\n\n /** Balancer deposit pool ID\n */\n function _setBalancerPoolId(bytes32 _value)\n internal\n {\n setBytes32(_BALANCER_POOLID_SLOT, _value);\n }\n\n function _setNTokens(uint256 _value) internal {\n setUint256(_NTOKENS_SLOT, _value);\n }\n\n function _setDepositToken(address _address)\n internal\n {\n setAddress(_DEPOSIT_TOKEN_SLOT, _address);\n }\n\n function _setDepositArrayIndex(uint256 _value)\n internal\n {\n require(_value <= nTokens(), \"Invalid index\");\n setUint256(_DEPOSIT_ARRAY_INDEX_SLOT, _value);\n }\n\n //\n // Get Strategy Metadata Functions\n //\n\n function hodlRatio()\n public\n view\n returns (uint256)\n {\n return getUint256(_HODL_RATIO_SLOT);\n }\n\n function hodlVault()\n public\n view\n returns (address)\n {\n return getAddress(_HODL_VAULT_SLOT);\n }\n\n function depositArbCheck()\n public\n view\n returns(bool)\n {\n return true;\n }\n\n function auraPoolId()\n public\n view\n returns (uint256)\n {\n return getUint256(_AURA_POOLID_SLOT);\n }\n\n function balancerPoolId()\n public\n view\n returns (bytes32)\n {\n return getBytes32(_BALANCER_POOLID_SLOT);\n }\n\n function nTokens()\n public\n view\n returns (uint256)\n {\n return getUint256(_NTOKENS_SLOT);\n }\n\n function depositToken()\n public\n view\n returns (address)\n {\n return getAddress(_DEPOSIT_TOKEN_SLOT);\n }\n\n function depositArrayIndex()\n public\n view\n returns (uint256)\n {\n return getUint256(_DEPOSIT_ARRAY_INDEX_SLOT);\n }\n\n //\n // Get Strategy Information Functions\n //\n\n /** Note that we currently do not have a mechanism here to include the\n * amount of reward that is accrued.\n */\n function investedUnderlyingBalance()\n external\n view\n returns (uint256)\n {\n return _rewardPoolBalance()\n .add(IERC20(underlying()).balanceOf(address(this)));\n }\n\n //\n // Strategy Operation Functions - Reinvest\n //\n\n /** Get the reward, sell it in exchange for underlying, invest what you got.\n * It's not much, but it's honest work.\n *\n * Note that although `onlyNotPausedInvesting` is not added here,\n * calling `_investAllUnderlying()` affectively blocks the usage of `doHardWork`\n * when the investing is being paused by governance.\n */\n function doHardWork()\n external\n onlyNotPausedInvesting\n restricted\n {\n IAuraBaseRewardPool(rewardPool()).getReward();\n _liquidateReward();\n _investAllUnderlying();\n }\n\n // We assume that all the tradings can be done on Sushiswap\n function _liquidateReward()\n internal\n {\n // Profits can be disabled for possible simplified and rapoolId exit\n if (!sell()) {\n emit ProfitsNotCollected(sell(), false);\n return;\n }\n\n address universalRewardToken = rewardToken();\n address universalDepositToken = depositToken();\n address universalLiquidator = universalLiquidator();\n // For reward tokens that can be swapped in a Single Swap\n for(uint256 i = 0; i < rewardTokens.length; i++){\n address token = rewardTokens[i];\n uint256 rewardBalance = IERC20(token).balanceOf(address(this));\n\n // if the token is the rewardToken then there won't be a path defined because liquidation is not necessary,\n // but we still have to make sure that the toHodl part is executed.\n if (rewardBalance == 0 ||\n (storedLiquidationDexes[token][universalRewardToken].length < 1) &&\n token != universalRewardToken) {\n continue;\n }\n\n uint256 toHodl = rewardBalance.mul(hodlRatio()).div(hodlRatioBase);\n if (toHodl > 0) {\n IERC20(token).safeTransfer(hodlVault(), toHodl);\n rewardBalance = rewardBalance.sub(toHodl);\n if (rewardBalance == 0) {\n continue;\n }\n }\n\n if(token == universalRewardToken) {\n // one of the reward tokens is the same as the token that we liquidate to ->\n // no liquidation necessary\n continue;\n }\n IERC20(token).safeApprove(universalLiquidator, 0);\n IERC20(token).safeApprove(universalLiquidator, rewardBalance);\n // we can accept 1 as the minimum because this will be called only by a trusted worker\n ILiquidator(universalLiquidator).swapTokenOnMultipleDEXes(\n rewardBalance,\n 1,\n address(this), // target\n storedLiquidationDexes[token][universalRewardToken],\n storedLiquidationPaths[token][universalRewardToken]\n );\n }\n\n uint256 rewardBalance = IERC20(universalRewardToken).balanceOf(address(this));\n notifyProfitInRewardToken(rewardBalance);\n uint256 remainingRewardBalance = IERC20(universalRewardToken).balanceOf(address(this));\n\n if (remainingRewardBalance == 0) {\n return;\n }\n\n // Swap Universal Reward Token(WETH) into Universal Deposit Token(bbaUSD)\n if(universalDepositToken != universalRewardToken) {\n address payable recipient = address(uint160(address(this)));\n uint256 batchSwapTokens = swapAssets.length;\n uint256 tokenBalance = IERC20(universalRewardToken).balanceOf(address(this));\n\n IERC20(universalRewardToken).safeApprove(bVault, 0);\n IERC20(universalRewardToken).safeApprove(bVault, tokenBalance);\n\n IBVault.BatchSwapStep[] memory swaps = new IBVault.BatchSwapStep[](batchSwapTokens.sub(1));\n swaps[0].amount = tokenBalance;\n for (uint256 i = 0; i < batchSwapTokens.sub(1); i++) {\n swaps[i].poolId = swapPoolIds[i];\n swaps[i].assetInIndex = i;\n swaps[i].assetOutIndex = i.add(1);\n }\n\n IAsset[] memory assets = new IAsset[](batchSwapTokens);\n for (uint256 i = 0; i < batchSwapTokens; i++) {\n assets[i] = IAsset(swapAssets[i]);\n }\n\n IBVault.FundManagement memory funds;\n funds.sender = address(this);\n funds.recipient = recipient;\n\n int256[] memory limits = new int256[](batchSwapTokens);\n limits[0] = int256(tokenBalance);\n\n IBVault(bVault).batchSwap(\n IBVault.SwapKind.GIVEN_IN,\n swaps,\n assets,\n funds,\n limits,\n 999999999999999999\n );\n }\n\n uint256 tokenBalance = IERC20(universalDepositToken).balanceOf(address(this));\n if (tokenBalance > 0) {\n depositLP();\n }\n }\n\n function depositLP()\n internal\n {\n address universalDepositToken = depositToken();\n uint256 depositTokensAmount = nTokens();\n uint256 tokenBalance = IERC20(universalDepositToken).balanceOf(address(this));\n\n if (IERC20(universalDepositToken).allowance(address(this), bVault) < tokenBalance) {\n IERC20(universalDepositToken).safeApprove(bVault, 0);\n IERC20(universalDepositToken).safeApprove(bVault, tokenBalance);\n }\n\n // we can accept 0 as minimum, this will be called only by trusted roles\n IAsset[] memory assets = new IAsset[](depositTokensAmount);\n for (uint256 i = 0; i < depositTokensAmount; i++) {\n assets[i] = IAsset(poolAssets[i]);\n }\n\n IBVault.JoinKind joinKind = IBVault.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT;\n uint256[] memory amountsIn = new uint256[](depositTokensAmount);\n amountsIn[depositArrayIndex()] = tokenBalance;\n uint256 minAmountOut = 1;\n\n bytes memory userData = abi.encode(joinKind, amountsIn, minAmountOut);\n\n IBVault.JoinPoolRequest memory request;\n request.assets = assets;\n request.maxAmountsIn = amountsIn;\n request.userData = userData;\n request.fromInternalBalance = false;\n\n IBVault(bVault).joinPool(\n balancerPoolId(),\n address(this),\n address(this),\n request\n );\n }\n\n /** Stakes everything the strategy holds into the reward pool\n */\n function _investAllUnderlying()\n internal\n onlyNotPausedInvesting\n {\n // this check is needed, because most of the SNX reward pools will revert if\n // you try to stake(0).\n if(IERC20(underlying()).balanceOf(address(this)) > 0) {\n _enterRewardPool();\n }\n }\n\n function _enterRewardPool()\n internal\n {\n address lpToken = underlying();\n uint256 entireBalance = IERC20(lpToken).balanceOf(address(this));\n IERC20(lpToken).safeApprove(booster, 0);\n IERC20(lpToken).safeApprove(booster, entireBalance);\n IAuraBooster(booster).depositAll(auraPoolId(), true); //deposit and stake\n }\n\n function addRewardToken(\n address _token,\n address[] memory _path2Reward,\n bytes32[] memory _dexOption\n )\n public\n onlyGovernance\n {\n address universalRewardToken = rewardToken();\n require(_path2Reward[_path2Reward.length-1] == universalRewardToken, \"Path should end with universal reward token\");\n require(_path2Reward[0] == _token, \"Path should start with new reward token\");\n require(_dexOption.length == _path2Reward.length-1, \"Inconsistent length for path/dexes\");\n rewardTokens.push(_token);\n storedLiquidationPaths[_token][universalRewardToken] = _path2Reward;\n storedLiquidationDexes[_token][universalRewardToken] = _dexOption;\n }\n\n //\n // Strategy Operation Functions - Exit\n //\n\n /** Withdraws all the asset to the vault\n */\n function withdrawAllToVault()\n public\n restricted\n {\n address lpToken = underlying();\n if (address(rewardPool()) != address(0)) {\n exitRewardPool();\n }\n _liquidateReward();\n IERC20(lpToken).safeTransfer(vault(), IERC20(lpToken).balanceOf(address(this)));\n }\n\n /** Withdraws all the asset to the vault\n */\n function withdrawToVault(uint256 amount)\n public\n restricted\n {\n address lpToken = underlying();\n // Typically there wouldn't be any amount here\n // however, it is possible because of the emergencyExit\n uint256 entireBalance = IERC20(lpToken).balanceOf(address(this));\n\n if(amount > entireBalance){\n // While we have the check above, we still using SafeMath below\n // for the peace of mind (in case something gets changed in between)\n uint256 needToWithdraw = amount.sub(entireBalance);\n uint256 toWithdraw = Math.min(_rewardPoolBalance(), needToWithdraw);\n partialWithdrawalRewardPool(toWithdraw);\n }\n IERC20(lpToken).safeTransfer(vault(), amount);\n }\n\n function partialWithdrawalRewardPool(uint256 amount)\n internal\n {\n IAuraBaseRewardPool(rewardPool()).withdrawAndUnwrap(amount, false); //don't claim rewards at this point\n }\n\n /** In case there are some issues discovered about the pool or underlying asset\n * Governance can exit the pool properly\n * The function is only used for emergency to exit the pool\n */\n function emergencyExit()\n public\n onlyGovernance\n {\n _emergencyExitRewardPool();\n _setPausedInvesting(true);\n }\n\n function _emergencyExitRewardPool()\n internal\n {\n uint256 stakedBalance = _rewardPoolBalance();\n if (stakedBalance != 0) {\n IAuraBaseRewardPool(rewardPool()).withdrawAllAndUnwrap(false); //don't claim rewards\n }\n }\n\n function exitRewardPool()\n internal\n {\n uint256 stakedBalance = _rewardPoolBalance();\n if (stakedBalance != 0) {\n IAuraBaseRewardPool(rewardPool()).withdrawAllAndUnwrap(true);\n }\n }\n\n function _rewardPoolBalance()\n internal\n view\n returns (uint256 balance)\n {\n balance = IAuraBaseRewardPool(rewardPool()).balanceOf(address(this));\n }\n\n //\n // Strategy Operation Functions - Miscellaneous\n //\n\n /** Governance or Controller can claim coins that are somehow transferred into the contract\n * Note that they cannot come in take away coins that are used and defined in the strategy itself\n */\n function salvage(\n address recipient,\n address token,\n uint256 amount\n )\n external\n onlyControllerOrGovernance\n {\n // To make sure that governance cannot come in and take away the coins\n require(!unsalvagableTokens(token), \"token is defined as not salvagable\");\n IERC20(token).safeTransfer(recipient, amount);\n }\n\n function unsalvagableTokens(address token)\n public\n view\n returns (bool)\n {\n return (token == rewardToken() || token == underlying());\n }\n\n function finalizeUpgrade()\n external\n onlyGovernance\n {\n _finalizeUpgrade();\n setHodlVault(multiSigAddr);\n setHodlRatio(1000); // 10%\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/math/Math.sol": {
|
|
"content": "pragma solidity ^0.5.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow, so we distribute\n return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/math/SafeMath.sol": {
|
|
"content": "pragma solidity ^0.5.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n *\n * _Available since v2.4.0._\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n *\n * _Available since v2.4.0._\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n *\n * _Available since v2.4.0._\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol": {
|
|
"content": "pragma solidity ^0.5.0;\n\nimport \"./IERC20.sol\";\n\n/**\n * @dev Optional functions from the ERC20 standard.\n */\ncontract ERC20Detailed is IERC20 {\n string private _name;\n string private _symbol;\n uint8 private _decimals;\n\n /**\n * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of\n * these values are immutable: they can only be set once during\n * construction.\n */\n constructor (string memory name, string memory symbol, uint8 decimals) public {\n _name = name;\n _symbol = symbol;\n _decimals = decimals;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5,05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view returns (uint8) {\n return _decimals;\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/token/ERC20/SafeERC20.sol": {
|
|
"content": "pragma solidity ^0.5.0;\n\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using SafeMath for uint256;\n using Address for address;\n\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n // solhint-disable-next-line max-line-length\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).add(value);\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves.\n\n // A Solidity high level call has three parts:\n // 1. The target address is checked to verify it contains contract code\n // 2. The call itself is made, and success asserted\n // 3. The return value is decoded, which in turn checks the size of the returned data.\n // solhint-disable-next-line max-line-length\n require(address(token).isContract(), \"SafeERC20: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = address(token).call(data);\n require(success, \"SafeERC20: low-level call failed\");\n\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n"
|
|
},
|
|
"contracts/base/upgradability/BaseUpgradeableStrategyUL.sol": {
|
|
"content": "pragma solidity 0.5.16;\n\nimport \"@openzeppelin/upgrades/contracts/Initializable.sol\";\nimport \"./BaseUpgradeableStrategyStorage.sol\";\nimport \"../inheritance/ControllableInit.sol\";\nimport \"../interface/IController.sol\";\nimport \"../interface/IFeeRewardForwarderV6.sol\";\nimport \"../interface/ILiquidator.sol\";\nimport \"../interface/ILiquidatorRegistry.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\n\ncontract BaseUpgradeableStrategyUL is Initializable, ControllableInit, BaseUpgradeableStrategyStorage {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n bytes32 internal constant _UL_REGISTRY_SLOT = 0x7a4b558e8ed4a66729f4a918db093413f0f1ae77c0de7c88bea8b99e084b2a17;\n bytes32 internal constant _UL_SLOT = 0xebfe408f65547b28326a79acf512c0f9a2bf4211ece39254d7c3ec96dd3dd242;\n\n mapping(address => mapping(address => address[])) public storedLiquidationPaths;\n mapping(address => mapping(address => bytes32[])) public storedLiquidationDexes;\n\n event ProfitsNotCollected(bool sell, bool floor);\n event ProfitLogInReward(uint256 profitAmount, uint256 feeAmount, uint256 timestamp);\n event ProfitAndBuybackLog(uint256 profitAmount, uint256 feeAmount, uint256 timestamp);\n\n modifier restricted() {\n require(msg.sender == vault() || msg.sender == controller()\n || msg.sender == governance(),\n \"The sender has to be the controller, governance, or vault\");\n _;\n }\n\n // This is only used in `investAllUnderlying()`\n // The user can still freely withdraw from the strategy\n modifier onlyNotPausedInvesting() {\n require(!pausedInvesting(), \"Action blocked as the strategy is in emergency state\");\n _;\n }\n\n constructor() public BaseUpgradeableStrategyStorage() {\n assert(_UL_REGISTRY_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.ULRegistry\")) - 1));\n assert(_UL_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.UL\")) - 1));\n }\n\n function initialize(\n address _storage,\n address _underlying,\n address _vault,\n address _rewardPool,\n address _rewardToken,\n uint256 _profitSharingNumerator,\n uint256 _profitSharingDenominator,\n bool _sell,\n uint256 _sellFloor,\n uint256 _implementationChangeDelay,\n address _universalLiquidatorRegistry\n ) public initializer {\n ControllableInit.initialize(\n _storage\n );\n _setUnderlying(_underlying);\n _setVault(_vault);\n _setRewardPool(_rewardPool);\n _setRewardToken(_rewardToken);\n _setProfitSharingNumerator(_profitSharingNumerator);\n _setProfitSharingDenominator(_profitSharingDenominator);\n\n _setSell(_sell);\n _setSellFloor(_sellFloor);\n _setNextImplementationDelay(_implementationChangeDelay);\n _setPausedInvesting(false);\n _setUniversalLiquidatorRegistry(_universalLiquidatorRegistry);\n _setUniversalLiquidator(ILiquidatorRegistry(universalLiquidatorRegistry()).universalLiquidator());\n }\n\n /**\n * Schedules an upgrade for this vault's proxy.\n */\n function scheduleUpgrade(address impl) public onlyGovernance {\n _setNextImplementation(impl);\n _setNextImplementationTimestamp(block.timestamp.add(nextImplementationDelay()));\n }\n\n function _finalizeUpgrade() internal {\n _setNextImplementation(address(0));\n _setNextImplementationTimestamp(0);\n }\n\n function shouldUpgrade() external view returns (bool, address) {\n return (\n nextImplementationTimestamp() != 0\n && block.timestamp > nextImplementationTimestamp()\n && nextImplementation() != address(0),\n nextImplementation()\n );\n }\n\n // reward notification\n\n function notifyProfitInRewardToken(uint256 _rewardBalance) internal {\n if( _rewardBalance > 0 ){\n uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator()).div(profitSharingDenominator());\n emit ProfitLogInReward(_rewardBalance, feeAmount, block.timestamp);\n IERC20(rewardToken()).safeApprove(controller(), 0);\n IERC20(rewardToken()).safeApprove(controller(), feeAmount);\n\n IController(controller()).notifyFee(\n rewardToken(),\n feeAmount\n );\n } else {\n emit ProfitLogInReward(0, 0, block.timestamp);\n }\n }\n\n function notifyProfitAndBuybackInRewardToken(uint256 _rewardBalance, address pool, uint256 _buybackRatio) internal {\n if( _rewardBalance > 0 ){\n uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator()).div(profitSharingDenominator());\n uint256 buybackAmount = _rewardBalance.sub(feeAmount).mul(_buybackRatio).div(10000);\n\n address forwarder = IController(controller()).feeRewardForwarder();\n emit ProfitAndBuybackLog(_rewardBalance, feeAmount, block.timestamp);\n\n IERC20(rewardToken()).safeApprove(forwarder, 0);\n IERC20(rewardToken()).safeApprove(forwarder, _rewardBalance);\n\n IFeeRewardForwarderV6(forwarder).notifyFeeAndBuybackAmounts(\n rewardToken(),\n feeAmount,\n pool,\n buybackAmount\n );\n } else {\n emit ProfitAndBuybackLog(0, 0, block.timestamp);\n }\n }\n\n function _setUniversalLiquidatorRegistry(address _address) internal {\n setAddress(_UL_REGISTRY_SLOT, _address);\n }\n\n function universalLiquidatorRegistry() public view returns (address) {\n return getAddress(_UL_REGISTRY_SLOT);\n }\n\n function _setUniversalLiquidator(address _address) internal {\n setAddress(_UL_SLOT, _address);\n }\n\n function universalLiquidator() public view returns (address) {\n return getAddress(_UL_SLOT);\n }\n\n function configureLiquidation(address[] memory path, bytes32[] memory dexes) public onlyGovernance {\n address fromToken = path[0];\n address toToken = path[path.length - 1];\n\n require(dexes.length == path.length - 1, \"lengths do not match\");\n\n storedLiquidationPaths[fromToken][toToken] = path;\n storedLiquidationDexes[fromToken][toToken] = dexes;\n }\n}\n"
|
|
},
|
|
"contracts/strategies/aura/interface/IAuraBooster.sol": {
|
|
"content": "pragma solidity 0.5.16;\n\ninterface IAuraBooster {\n \n function deposit(uint256 _pid, uint256 _amount, bool _stake) external;\n\n function depositAll(uint256 _pid, bool _stake) external;\n\n function withdraw(uint256 _pid, uint256 _amount) external;\n\n function withdrawAll(uint256 _pid) external;\n\n function poolInfo(uint256 _pid) external view returns (address lpToken, address, address, address, address, bool);\n\n function earmarkRewards(uint256 _pid) external;\n}"
|
|
},
|
|
"contracts/strategies/aura/interface/IAuraBaseRewardPool.sol": {
|
|
"content": "pragma solidity 0.5.16;\n\ninterface IAuraBaseRewardPool {\n\n function balanceOf(address account) external view returns(uint256 amount);\n\n function pid() external view returns (uint256 _pid);\n\n function stakingToken() external view returns (address _stakingToken);\n\n function getReward() external;\n\n function stake(uint256 _amount) external;\n\n function stakeAll() external;\n\n function withdraw(uint256 amount, bool claim) external;\n\n function withdrawAll(bool claim) external;\n\n function withdrawAndUnwrap(uint256 amount, bool claim) external;\n\n function withdrawAllAndUnwrap(bool claim) external;\n}"
|
|
},
|
|
"contracts/base/interface/IStrategy.sol": {
|
|
"content": "pragma solidity 0.5.16;\n\ninterface IStrategy {\n \n function unsalvagableTokens(address tokens) external view returns (bool);\n \n function governance() external view returns (address);\n function controller() external view returns (address);\n function underlying() external view returns (address);\n function vault() external view returns (address);\n\n function withdrawAllToVault() external;\n function withdrawToVault(uint256 amount) external;\n\n function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch()\n\n // should only be called by controller\n function salvage(address recipient, address token, uint256 amount) external;\n\n function doHardWork() external;\n function depositArbCheck() external view returns(bool);\n}\n"
|
|
},
|
|
"contracts/base/interface/IVault.sol": {
|
|
"content": "pragma solidity 0.5.16;\n\ninterface IVault {\n\n function initializeVault(\n address _storage,\n address _underlying,\n uint256 _toInvestNumerator,\n uint256 _toInvestDenominator\n ) external ;\n\n function balanceOf(address) external view returns (uint256);\n\n function underlyingBalanceInVault() external view returns (uint256);\n function underlyingBalanceWithInvestment() external view returns (uint256);\n\n // function store() external view returns (address);\n function governance() external view returns (address);\n function controller() external view returns (address);\n function underlying() external view returns (address);\n function strategy() external view returns (address);\n\n function setStrategy(address _strategy) external;\n function announceStrategyUpdate(address _strategy) external;\n function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external;\n\n function deposit(uint256 amountWei) external;\n function depositFor(uint256 amountWei, address holder) external;\n\n function withdrawAll() external;\n function withdraw(uint256 numberOfShares) external;\n function getPricePerFullShare() external view returns (uint256);\n\n function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256);\n\n // hard work should be callable only by the controller (by the hard worker) or by governance\n function doHardWork() external;\n}\n"
|
|
},
|
|
"contracts/base/interface/balancer/IBVault.sol": {
|
|
"content": "//SPDX-License-Identifier: Unlicense\npragma solidity 0.5.16;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"./IAsset.sol\";\n\ninterface IBVault {\n // Internal Balance\n //\n // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later\n // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination\n // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced\n // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.\n //\n // Internal Balance management features batching, which means a single contract call can be used to perform multiple\n // operations of different kinds, with different senders and recipients, at once.\n\n /**\n * @dev Returns `user`'s Internal Balance for a set of tokens.\n */\n function getInternalBalance(address user, IERC20[] calldata tokens) external view returns (uint256[] memory);\n\n /**\n * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)\n * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as\n * it lets integrators reuse a user's Vault allowance.\n *\n * For each operation, if the caller is not `sender`, it must be an authorized relayer for them.\n */\n function manageUserBalance(UserBalanceOp[] calldata ops) external payable;\n\n /**\n * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received\n without manual WETH wrapping or unwrapping.\n */\n struct UserBalanceOp {\n UserBalanceOpKind kind;\n IAsset asset;\n uint256 amount;\n address sender;\n address payable recipient;\n }\n\n // There are four possible operations in `manageUserBalance`:\n //\n // - DEPOSIT_INTERNAL\n // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding\n // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.\n //\n // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped\n // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is\n // relevant for relayers).\n //\n // Emits an `InternalBalanceChanged` event.\n //\n //\n // - WITHDRAW_INTERNAL\n // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.\n //\n // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send\n // it to the recipient as ETH.\n //\n // Emits an `InternalBalanceChanged` event.\n //\n //\n // - TRANSFER_INTERNAL\n // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.\n //\n // Reverts if the ETH sentinel value is passed.\n //\n // Emits an `InternalBalanceChanged` event.\n //\n //\n // - TRANSFER_EXTERNAL\n // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by\n // relayers, as it lets them reuse a user's Vault allowance.\n //\n // Reverts if the ETH sentinel value is passed.\n //\n // Emits an `ExternalBalanceTransfer` event.\n\n enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }\n\n /**\n * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through\n * interacting with Pools using Internal Balance.\n *\n * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH\n * address.\n */\n event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);\n\n /**\n * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.\n */\n event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);\n\n // Pools\n //\n // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced\n // functionality:\n //\n // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the\n // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),\n // which increase with the number of registered tokens.\n //\n // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the\n // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted\n // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are\n // independent of the number of registered tokens.\n //\n // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like\n // minimal swap info Pools, these are called via IMinimalSwapInfoPool.\n\n enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }\n\n /**\n * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which\n * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be\n * changed.\n *\n * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,\n * depending on the chosen specialization setting. This contract is known as the Pool's contract.\n *\n * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,\n * multiple Pools may share the same contract.\n *\n * Emits a `PoolRegistered` event.\n */\n function registerPool(PoolSpecialization specialization) external returns (bytes32);\n\n /**\n * @dev Emitted when a Pool is registered by calling `registerPool`.\n */\n event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);\n\n /**\n * @dev Returns a Pool's contract address and specialization setting.\n */\n function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);\n\n /**\n * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.\n *\n * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,\n * exit by receiving registered tokens, and can only swap registered tokens.\n *\n * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length\n * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in\n * ascending order.\n *\n * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset\n * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,\n * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore\n * expected to be highly secured smart contracts with sound design principles, and the decision to register an\n * Asset Manager should not be made lightly.\n *\n * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset\n * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a\n * different Asset Manager.\n *\n * Emits a `TokensRegistered` event.\n */\n function registerTokens(\n bytes32 poolId,\n IERC20[] calldata tokens,\n address[] calldata assetManagers\n ) external;\n\n /**\n * @dev Emitted when a Pool registers tokens by calling `registerTokens`.\n */\n event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);\n\n /**\n * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.\n *\n * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total\n * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens\n * must be deregistered in the same `deregisterTokens` call.\n *\n * A deregistered token can be re-registered later on, possibly with a different Asset Manager.\n *\n * Emits a `TokensDeregistered` event.\n */\n function deregisterTokens(bytes32 poolId, IERC20[] calldata tokens) external;\n\n /**\n * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.\n */\n event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);\n\n /**\n * @dev Returns detailed information for a Pool's registered token.\n *\n * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens\n * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`\n * equals the sum of `cash` and `managed`.\n *\n * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,\n * `managed` or `total` balance to be greater than 2^112 - 1.\n *\n * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a\n * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for\n * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a\n * change for this purpose, and will update `lastChangeBlock`.\n *\n * `assetManager` is the Pool's token Asset Manager.\n */\n function getPoolTokenInfo(bytes32 poolId, IERC20 token)\n external\n view\n returns (\n uint256 cash,\n uint256 managed,\n uint256 lastChangeBlock,\n address assetManager\n );\n\n /**\n * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of\n * the tokens' `balances` changed.\n *\n * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all\n * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.\n *\n * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same\n * order as passed to `registerTokens`.\n *\n * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are\n * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`\n * instead.\n */\n function getPoolTokens(bytes32 poolId)\n external\n view\n returns (\n IERC20[] memory tokens,\n uint256[] memory balances,\n uint256 lastChangeBlock\n );\n\n /**\n * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will\n * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized\n * Pool shares.\n *\n * If the caller is not `sender`, it must be an authorized relayer for them.\n *\n * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount\n * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces\n * these maximums.\n *\n * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable\n * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the\n * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent\n * back to the caller (not the sender, which is important for relayers).\n *\n * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when\n * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be\n * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final\n * `assets` array might not be sorted. Pools with no registered tokens cannot be joined.\n *\n * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only\n * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be\n * withdrawn from Internal Balance: attempting to do so will trigger a revert.\n *\n * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement\n * their own custom logic. This typically requires additional information from the user (such as the expected number\n * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed\n * directly to the Pool's contract, as is `recipient`.\n *\n * Emits a `PoolBalanceChanged` event.\n */\n function joinPool(\n bytes32 poolId,\n address sender,\n address recipient,\n JoinPoolRequest calldata request\n ) external payable;\n\n enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT }\n enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT }\n\n struct JoinPoolRequest {\n IAsset[] assets;\n uint256[] maxAmountsIn;\n bytes userData;\n bool fromInternalBalance;\n }\n\n /**\n * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will\n * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized\n * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see\n * `getPoolTokenInfo`).\n *\n * If the caller is not `sender`, it must be an authorized relayer for them.\n *\n * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum\n * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:\n * it just enforces these minimums.\n *\n * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To\n * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead\n * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.\n *\n * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when\n * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must\n * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the\n * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.\n *\n * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,\n * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to\n * do so will trigger a revert.\n *\n * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the\n * `tokens` array. This array must match the Pool's registered tokens.\n *\n * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement\n * their own custom logic. This typically requires additional information from the user (such as the expected number\n * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and\n * passed directly to the Pool's contract.\n *\n * Emits a `PoolBalanceChanged` event.\n */\n function exitPool(\n bytes32 poolId,\n address sender,\n address payable recipient,\n ExitPoolRequest calldata request\n ) external;\n\n struct ExitPoolRequest {\n IAsset[] assets;\n uint256[] minAmountsOut;\n bytes userData;\n bool toInternalBalance;\n }\n\n /**\n * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.\n */\n event PoolBalanceChanged(\n bytes32 indexed poolId,\n address indexed liquidityProvider,\n IERC20[] tokens,\n int256[] deltas,\n uint256[] protocolFeeAmounts\n );\n\n enum PoolBalanceChangeKind { JOIN, EXIT }\n\n // Swaps\n //\n // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,\n // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be\n // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.\n //\n // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.\n // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),\n // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').\n // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together\n // individual swaps.\n //\n // There are two swap kinds:\n // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the\n // `onSwap` hook) the amount of tokens out (to send to the recipient).\n // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines\n // (via the `onSwap` hook) the amount of tokens in (to receive from the sender).\n //\n // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with\n // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated\n // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended\n // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at\n // the final intended token.\n //\n // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal\n // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes\n // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost\n // much less gas than they would otherwise.\n //\n // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple\n // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only\n // updating the Pool's internal accounting).\n //\n // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token\n // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the\n // minimum amount of tokens to receive (by passing a negative value) is specified.\n //\n // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after\n // this point in time (e.g. if the transaction failed to be included in a block promptly).\n //\n // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do\n // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be\n // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the\n // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).\n //\n // Finally, Internal Balance can be used when either sending or receiving tokens.\n\n enum SwapKind { GIVEN_IN, GIVEN_OUT }\n\n /**\n * @dev Performs a swap with a single Pool.\n *\n * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens\n * taken from the Pool, which must be greater than or equal to `limit`.\n *\n * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens\n * sent to the Pool, which must be less than or equal to `limit`.\n *\n * Internal Balance usage and the recipient are determined by the `funds` struct.\n *\n * Emits a `Swap` event.\n */\n function swap(\n SingleSwap calldata singleSwap,\n FundManagement calldata funds,\n uint256 limit,\n uint256 deadline\n ) external payable returns (uint256);\n\n /**\n * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on\n * the `kind` value.\n *\n * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).\n * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.\n *\n * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be\n * used to extend swap behavior.\n */\n struct SingleSwap {\n bytes32 poolId;\n SwapKind kind;\n IAsset assetIn;\n IAsset assetOut;\n uint256 amount;\n bytes userData;\n }\n\n /**\n * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either\n * the amount of tokens sent to or received from the Pool, depending on the `kind` value.\n *\n * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the\n * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at\n * the same index in the `assets` array.\n *\n * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a\n * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or\n * `amountOut` depending on the swap kind.\n *\n * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out\n * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal\n * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.\n *\n * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,\n * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and\n * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to\n * or unwrapped from WETH by the Vault.\n *\n * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies\n * the minimum or maximum amount of each token the vault is allowed to transfer.\n *\n * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the\n * equivalent `swap` call.\n *\n * Emits `Swap` events.\n */\n function batchSwap(\n SwapKind kind,\n BatchSwapStep[] calldata swaps,\n IAsset[] calldata assets,\n FundManagement calldata funds,\n int256[] calldata limits,\n uint256 deadline\n ) external payable returns (int256[] memory);\n\n /**\n * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the\n * `assets` array passed to that function, and ETH assets are converted to WETH.\n *\n * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out\n * from the previous swap, depending on the swap kind.\n *\n * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be\n * used to extend swap behavior.\n */\n struct BatchSwapStep {\n bytes32 poolId;\n uint256 assetInIndex;\n uint256 assetOutIndex;\n uint256 amount;\n bytes userData;\n }\n\n /**\n * @dev Emitted for each individual swap performed by `swap` or `batchSwap`.\n */\n event Swap(\n bytes32 indexed poolId,\n IERC20 indexed tokenIn,\n IERC20 indexed tokenOut,\n uint256 amountIn,\n uint256 amountOut\n );\n\n /**\n * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the\n * `recipient` account.\n *\n * If the caller is not `sender`, it must be an authorized relayer for them.\n *\n * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20\n * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`\n * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of\n * `joinPool`.\n *\n * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of\n * transferred. This matches the behavior of `exitPool`.\n *\n * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a\n * revert.\n */\n struct FundManagement {\n address sender;\n bool fromInternalBalance;\n address payable recipient;\n bool toInternalBalance;\n }\n\n /**\n * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be\n * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.\n *\n * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)\n * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it\n * receives are the same that an equivalent `batchSwap` call would receive.\n *\n * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.\n * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,\n * approve them for the Vault, or even know a user's address.\n *\n * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute\n * eth_call instead of eth_sendTransaction.\n */\n function queryBatchSwap(\n SwapKind kind,\n BatchSwapStep[] calldata swaps,\n IAsset[] calldata assets,\n FundManagement calldata funds\n ) external returns (int256[] memory assetDeltas);\n}"
|
|
},
|
|
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
|
|
"content": "pragma solidity ^0.5.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP. Does not include\n * the optional functions; to access them see {ERC20Detailed}.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/utils/Address.sol": {
|
|
"content": "pragma solidity ^0.5.5;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following \n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\n // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\n // for accounts without code, i.e. `keccak256('')`\n bytes32 codehash;\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n // solhint-disable-next-line no-inline-assembly\n assembly { codehash := extcodehash(account) }\n return (codehash != accountHash && codehash != 0x0);\n }\n\n /**\n * @dev Converts an `address` into `address payable`. Note that this is\n * simply a type cast: the actual underlying value is not changed.\n *\n * _Available since v2.4.0._\n */\n function toPayable(address account) internal pure returns (address payable) {\n return address(uint160(account));\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n *\n * _Available since v2.4.0._\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-call-value\n (bool success, ) = recipient.call.value(amount)(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n}\n"
|
|
},
|
|
"@openzeppelin/upgrades/contracts/Initializable.sol": {
|
|
"content": "pragma solidity >=0.4.24 <0.7.0;\n\n\n/**\n * @title Initializable\n *\n * @dev Helper contract to support initializer functions. To use it, replace\n * the constructor with a function that has the `initializer` modifier.\n * WARNING: Unlike constructors, initializer functions must be manually\n * invoked. This applies both to deploying an Initializable contract, as well\n * as extending an Initializable contract via inheritance.\n * WARNING: When used with inheritance, manual care must be taken to not invoke\n * a parent initializer twice, or ensure that all initializers are idempotent,\n * because this is not dealt with automatically as with constructors.\n */\ncontract Initializable {\n\n /**\n * @dev Indicates that the contract has been initialized.\n */\n bool private initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private initializing;\n\n /**\n * @dev Modifier to use in the initializer function of a contract.\n */\n modifier initializer() {\n require(initializing || isConstructor() || !initialized, \"Contract instance has already been initialized\");\n\n bool isTopLevelCall = !initializing;\n if (isTopLevelCall) {\n initializing = true;\n initialized = true;\n }\n\n _;\n\n if (isTopLevelCall) {\n initializing = false;\n }\n }\n\n /// @dev Returns true if and only if the function is running in the constructor\n function isConstructor() private view returns (bool) {\n // extcodesize checks the size of the code stored in an address, and\n // address returns the current address. Since the code is still not\n // deployed when running a constructor, any checks on its code size will\n // yield zero, making it an effective way to detect if a contract is\n // under construction or not.\n address self = address(this);\n uint256 cs;\n assembly { cs := extcodesize(self) }\n return cs == 0;\n }\n\n // Reserved storage space to allow for layout changes in the future.\n uint256[50] private ______gap;\n}\n"
|
|
},
|
|
"contracts/base/upgradability/BaseUpgradeableStrategyStorage.sol": {
|
|
"content": "pragma solidity 0.5.16;\n\nimport \"@openzeppelin/upgrades/contracts/Initializable.sol\";\n\ncontract BaseUpgradeableStrategyStorage {\n\n bytes32 internal constant _UNDERLYING_SLOT = 0xa1709211eeccf8f4ad5b6700d52a1a9525b5f5ae1e9e5f9e5a0c2fc23c86e530;\n bytes32 internal constant _VAULT_SLOT = 0xefd7c7d9ef1040fc87e7ad11fe15f86e1d11e1df03c6d7c87f7e1f4041f08d41;\n\n bytes32 internal constant _REWARD_TOKEN_SLOT = 0xdae0aafd977983cb1e78d8f638900ff361dc3c48c43118ca1dd77d1af3f47bbf;\n bytes32 internal constant _REWARD_POOL_SLOT = 0x3d9bb16e77837e25cada0cf894835418b38e8e18fbec6cfd192eb344bebfa6b8;\n bytes32 internal constant _SELL_FLOOR_SLOT = 0xc403216a7704d160f6a3b5c3b149a1226a6080f0a5dd27b27d9ba9c022fa0afc;\n bytes32 internal constant _SELL_SLOT = 0x656de32df98753b07482576beb0d00a6b949ebf84c066c765f54f26725221bb6;\n bytes32 internal constant _PAUSED_INVESTING_SLOT = 0xa07a20a2d463a602c2b891eb35f244624d9068572811f63d0e094072fb54591a;\n\n bytes32 internal constant _PROFIT_SHARING_NUMERATOR_SLOT = 0xe3ee74fb7893020b457d8071ed1ef76ace2bf4903abd7b24d3ce312e9c72c029;\n bytes32 internal constant _PROFIT_SHARING_DENOMINATOR_SLOT = 0x0286fd414602b432a8c80a0125e9a25de9bba96da9d5068c832ff73f09208a3b;\n\n bytes32 internal constant _NEXT_IMPLEMENTATION_SLOT = 0x29f7fcd4fe2517c1963807a1ec27b0e45e67c60a874d5eeac7a0b1ab1bb84447;\n bytes32 internal constant _NEXT_IMPLEMENTATION_TIMESTAMP_SLOT = 0x414c5263b05428f1be1bfa98e25407cc78dd031d0d3cd2a2e3d63b488804f22e;\n bytes32 internal constant _NEXT_IMPLEMENTATION_DELAY_SLOT = 0x82b330ca72bcd6db11a26f10ce47ebcfe574a9c646bccbc6f1cd4478eae16b31;\n\n bytes32 internal constant _REWARD_CLAIMABLE_SLOT = 0xbc7c0d42a71b75c3129b337a259c346200f901408f273707402da4b51db3b8e7;\n bytes32 internal constant _MULTISIG_SLOT = 0x3e9de78b54c338efbc04e3a091b87dc7efb5d7024738302c548fc59fba1c34e6;\n\n constructor() public {\n assert(_UNDERLYING_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.underlying\")) - 1));\n assert(_VAULT_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.vault\")) - 1));\n assert(_REWARD_TOKEN_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.rewardToken\")) - 1));\n assert(_REWARD_POOL_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.rewardPool\")) - 1));\n assert(_SELL_FLOOR_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.sellFloor\")) - 1));\n assert(_SELL_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.sell\")) - 1));\n assert(_PAUSED_INVESTING_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.pausedInvesting\")) - 1));\n\n assert(_PROFIT_SHARING_NUMERATOR_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.profitSharingNumerator\")) - 1));\n assert(_PROFIT_SHARING_DENOMINATOR_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.profitSharingDenominator\")) - 1));\n\n assert(_NEXT_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.nextImplementation\")) - 1));\n assert(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.nextImplementationTimestamp\")) - 1));\n assert(_NEXT_IMPLEMENTATION_DELAY_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.nextImplementationDelay\")) - 1));\n\n assert(_REWARD_CLAIMABLE_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.rewardClaimable\")) - 1));\n assert(_MULTISIG_SLOT == bytes32(uint256(keccak256(\"eip1967.strategyStorage.multiSig\")) - 1));\n }\n\n function _setUnderlying(address _address) internal {\n setAddress(_UNDERLYING_SLOT, _address);\n }\n\n function underlying() public view returns (address) {\n return getAddress(_UNDERLYING_SLOT);\n }\n\n function _setRewardPool(address _address) internal {\n setAddress(_REWARD_POOL_SLOT, _address);\n }\n\n function rewardPool() public view returns (address) {\n return getAddress(_REWARD_POOL_SLOT);\n }\n\n function _setRewardToken(address _address) internal {\n setAddress(_REWARD_TOKEN_SLOT, _address);\n }\n\n function rewardToken() public view returns (address) {\n return getAddress(_REWARD_TOKEN_SLOT);\n }\n\n function _setVault(address _address) internal {\n setAddress(_VAULT_SLOT, _address);\n }\n\n function vault() public view returns (address) {\n return getAddress(_VAULT_SLOT);\n }\n\n // a flag for disabling selling for simplified emergency exit\n function _setSell(bool _value) internal {\n setBoolean(_SELL_SLOT, _value);\n }\n\n function sell() public view returns (bool) {\n return getBoolean(_SELL_SLOT);\n }\n\n function _setPausedInvesting(bool _value) internal {\n setBoolean(_PAUSED_INVESTING_SLOT, _value);\n }\n\n function pausedInvesting() public view returns (bool) {\n return getBoolean(_PAUSED_INVESTING_SLOT);\n }\n\n function _setSellFloor(uint256 _value) internal {\n setUint256(_SELL_FLOOR_SLOT, _value);\n }\n\n function sellFloor() public view returns (uint256) {\n return getUint256(_SELL_FLOOR_SLOT);\n }\n\n function _setProfitSharingNumerator(uint256 _value) internal {\n setUint256(_PROFIT_SHARING_NUMERATOR_SLOT, _value);\n }\n\n function profitSharingNumerator() public view returns (uint256) {\n return getUint256(_PROFIT_SHARING_NUMERATOR_SLOT);\n }\n\n function _setProfitSharingDenominator(uint256 _value) internal {\n setUint256(_PROFIT_SHARING_DENOMINATOR_SLOT, _value);\n }\n\n function profitSharingDenominator() public view returns (uint256) {\n return getUint256(_PROFIT_SHARING_DENOMINATOR_SLOT);\n }\n\n function allowedRewardClaimable() public view returns (bool) {\n return getBoolean(_REWARD_CLAIMABLE_SLOT);\n }\n\n function _setRewardClaimable(bool _value) internal {\n setBoolean(_REWARD_CLAIMABLE_SLOT, _value);\n }\n\n function multiSig() public view returns(address) {\n return getAddress(_MULTISIG_SLOT);\n }\n\n function _setMultiSig(address _address) internal {\n setAddress(_MULTISIG_SLOT, _address);\n }\n\n // upgradeability\n\n function _setNextImplementation(address _address) internal {\n setAddress(_NEXT_IMPLEMENTATION_SLOT, _address);\n }\n\n function nextImplementation() public view returns (address) {\n return getAddress(_NEXT_IMPLEMENTATION_SLOT);\n }\n\n function _setNextImplementationTimestamp(uint256 _value) internal {\n setUint256(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT, _value);\n }\n\n function nextImplementationTimestamp() public view returns (uint256) {\n return getUint256(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT);\n }\n\n function _setNextImplementationDelay(uint256 _value) internal {\n setUint256(_NEXT_IMPLEMENTATION_DELAY_SLOT, _value);\n }\n\n function nextImplementationDelay() public view returns (uint256) {\n return getUint256(_NEXT_IMPLEMENTATION_DELAY_SLOT);\n }\n\n function setBoolean(bytes32 slot, bool _value) internal {\n setUint256(slot, _value ? 1 : 0);\n }\n\n function setAddress(bytes32 slot, address _address) internal {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n sstore(slot, _address)\n }\n }\n\n function setUint256(bytes32 slot, uint256 _value) internal {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n sstore(slot, _value)\n }\n }\n\n function setBytes32(bytes32 slot, bytes32 _value) internal {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n sstore(slot, _value)\n }\n }\n\n function getBoolean(bytes32 slot) internal view returns (bool) {\n return (getUint256(slot) == 1);\n }\n\n function getAddress(bytes32 slot) internal view returns (address str) {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n str := sload(slot)\n }\n }\n\n function getUint256(bytes32 slot) internal view returns (uint256 str) {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n str := sload(slot)\n }\n }\n\n function getBytes32(bytes32 slot) internal view returns (bytes32 str) {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n str := sload(slot)\n }\n }\n}\n"
|
|
},
|
|
"contracts/base/inheritance/ControllableInit.sol": {
|
|
"content": "pragma solidity 0.5.16;\n\nimport \"./GovernableInit.sol\";\n\n// A clone of Governable supporting the Initializable interface and pattern\ncontract ControllableInit is GovernableInit {\n\n constructor() public {\n }\n\n function initialize(address _storage) public initializer {\n GovernableInit.initialize(_storage);\n }\n\n modifier onlyController() {\n require(Storage(_storage()).isController(msg.sender), \"Not a controller\");\n _;\n }\n\n modifier onlyControllerOrGovernance(){\n require((Storage(_storage()).isController(msg.sender) || Storage(_storage()).isGovernance(msg.sender)),\n \"The caller must be controller or governance\");\n _;\n }\n\n function controller() public view returns (address) {\n return Storage(_storage()).controller();\n }\n}\n"
|
|
},
|
|
"contracts/base/interface/IController.sol": {
|
|
"content": "pragma solidity 0.5.16;\n\ninterface IController {\n\n event SharePriceChangeLog(\n address indexed vault,\n address indexed strategy,\n uint256 oldSharePrice,\n uint256 newSharePrice,\n uint256 timestamp\n );\n\n // [Grey list]\n // An EOA can safely interact with the system no matter what.\n // If you're using Metamask, you're using an EOA.\n // Only smart contracts may be affected by this grey list.\n //\n // This contract will not be able to ban any EOA from the system\n // even if an EOA is being added to the greyList, he/she will still be able\n // to interact with the whole system as if nothing happened.\n // Only smart contracts will be affected by being added to the greyList.\n // This grey list is only used in Vault.sol, see the code there for reference\n function greyList(address _target) external view returns(bool);\n\n function addVaultAndStrategy(address _vault, address _strategy) external;\n function doHardWork(address _vault) external;\n\n function salvage(address _token, uint256 amount) external;\n function salvageStrategy(address _strategy, address _token, uint256 amount) external;\n\n function notifyFee(address _underlying, uint256 fee) external;\n function profitSharingNumerator() external view returns (uint256);\n function profitSharingDenominator() external view returns (uint256);\n\n function feeRewardForwarder() external view returns(address);\n function setFeeRewardForwarder(address _value) external;\n\n function addHardWorker(address _worker) external;\n function addToWhitelist(address _target) external;\n}\n"
|
|
},
|
|
"contracts/base/interface/IFeeRewardForwarderV6.sol": {
|
|
"content": "pragma solidity 0.5.16;\n\ninterface IFeeRewardForwarderV6 {\n function poolNotifyFixedTarget(address _token, uint256 _amount) external;\n\n function notifyFeeAndBuybackAmounts(uint256 _feeAmount, address _pool, uint256 _buybackAmount) external;\n function notifyFeeAndBuybackAmounts(address _token, uint256 _feeAmount, address _pool, uint256 _buybackAmount) external;\n function profitSharingPool() external view returns (address);\n function configureLiquidation(address[] calldata _path, bytes32[] calldata _dexes) external;\n}\n"
|
|
},
|
|
"contracts/base/interface/ILiquidator.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.5.16;\n\ninterface ILiquidator {\n event Swap(\n address indexed buyToken,\n address indexed sellToken,\n address indexed target,\n address initiator,\n uint256 amountIn,\n uint256 slippage,\n uint256 total\n );\n\n function swapTokenOnMultipleDEXes(\n uint256 amountIn,\n uint256 amountOutMin,\n address target,\n bytes32[] calldata dexes,\n address[] calldata path\n ) external;\n\n function swapTokenOnDEX(\n uint256 amountIn,\n uint256 amountOutMin,\n address target,\n bytes32 dexName,\n address[] calldata path\n ) external;\n\n function getAllDexes() external view returns (bytes32[] memory);\n}\n"
|
|
},
|
|
"contracts/base/interface/ILiquidatorRegistry.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.5.16;\n\ninterface ILiquidatorRegistry {\n\n function universalLiquidator() external view returns(address);\n\n function setUniversalLiquidator(address _ul) external;\n\n function getPath(\n bytes32 dex,\n address inputToken,\n address outputToken\n ) external view returns(address[] memory);\n\n function setPath(\n bytes32 dex,\n address inputToken,\n address outputToken,\n address[] calldata path\n ) external;\n}\n"
|
|
},
|
|
"contracts/base/inheritance/GovernableInit.sol": {
|
|
"content": "pragma solidity 0.5.16;\n\nimport \"@openzeppelin/upgrades/contracts/Initializable.sol\";\nimport \"./Storage.sol\";\n\n// A clone of Governable supporting the Initializable interface and pattern\ncontract GovernableInit is Initializable {\n\n bytes32 internal constant _STORAGE_SLOT = 0xa7ec62784904ff31cbcc32d09932a58e7f1e4476e1d041995b37c917990b16dc;\n\n modifier onlyGovernance() {\n require(Storage(_storage()).isGovernance(msg.sender), \"Not governance\");\n _;\n }\n\n constructor() public {\n assert(_STORAGE_SLOT == bytes32(uint256(keccak256(\"eip1967.governableInit.storage\")) - 1));\n }\n\n function initialize(address _store) public initializer {\n _setStorage(_store);\n }\n\n function _setStorage(address newStorage) private {\n bytes32 slot = _STORAGE_SLOT;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n sstore(slot, newStorage)\n }\n }\n\n function setStorage(address _store) public onlyGovernance {\n require(_store != address(0), \"new storage shouldn't be empty\");\n _setStorage(_store);\n }\n\n function _storage() internal view returns (address str) {\n bytes32 slot = _STORAGE_SLOT;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n str := sload(slot)\n }\n }\n\n function governance() public view returns (address) {\n return Storage(_storage()).governance();\n }\n}\n"
|
|
},
|
|
"contracts/base/inheritance/Storage.sol": {
|
|
"content": "pragma solidity 0.5.16;\n\ncontract Storage {\n\n address public governance;\n address public controller;\n\n constructor() public {\n governance = msg.sender;\n }\n\n modifier onlyGovernance() {\n require(isGovernance(msg.sender), \"Not governance\");\n _;\n }\n\n function setGovernance(address _governance) public onlyGovernance {\n require(_governance != address(0), \"new governance shouldn't be empty\");\n governance = _governance;\n }\n\n function setController(address _controller) public onlyGovernance {\n require(_controller != address(0), \"new controller shouldn't be empty\");\n controller = _controller;\n }\n\n function isGovernance(address account) public view returns (bool) {\n return account == governance;\n }\n\n function isController(address account) public view returns (bool) {\n return account == controller;\n }\n}\n"
|
|
},
|
|
"contracts/base/interface/balancer/IAsset.sol": {
|
|
"content": "pragma solidity 0.5.16;\n\ninterface IAsset {\n // solhint-disable-previous-line no-empty-blocks\n}"
|
|
}
|
|
},
|
|
"settings": {
|
|
"optimizer": {
|
|
"enabled": true,
|
|
"runs": 200
|
|
},
|
|
"outputSelection": {
|
|
"*": {
|
|
"*": [
|
|
"evm.bytecode",
|
|
"evm.deployedBytecode",
|
|
"devdoc",
|
|
"userdoc",
|
|
"metadata",
|
|
"abi"
|
|
]
|
|
}
|
|
},
|
|
"libraries": {}
|
|
}
|
|
} |