{ "language": "Solidity", "sources": { "contracts/protocols/convex/busdv2/Allocation.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {\n MetaPoolAllocationBaseV3\n} from \"contracts/protocols/convex/metapool/Imports.sol\";\n\nimport {ConvexBusdv2Constants} from \"./Constants.sol\";\n\ncontract ConvexBusdv2Allocation is\n MetaPoolAllocationBaseV3,\n ConvexBusdv2Constants\n{\n function balanceOf(address account, uint8 tokenIndex)\n public\n view\n override\n returns (uint256)\n {\n return\n super.getUnderlyerBalance(\n account,\n META_POOL,\n REWARD_CONTRACT,\n LP_TOKEN,\n uint256(tokenIndex)\n );\n }\n\n function _getTokenData()\n internal\n pure\n override\n returns (TokenData[] memory)\n {\n return _getBasePoolTokenData();\n }\n}\n" }, "contracts/protocols/convex/metapool/Imports.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {MetaPoolAllocationBaseV2} from \"./MetaPoolAllocationBaseV2.sol\";\nimport {MetaPoolAllocationBaseV3} from \"./MetaPoolAllocationBaseV3.sol\";\nimport {MetaPoolOldDepositorZap} from \"./MetaPoolOldDepositorZap.sol\";\nimport {MetaPoolDepositorZap} from \"./MetaPoolDepositorZap.sol\";\nimport {MetaPoolDepositorZapV2} from \"./MetaPoolDepositorZapV2.sol\";\n" }, "contracts/protocols/convex/busdv2/Constants.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity 0.6.11;\n\nimport {IERC20, INameIdentifier} from \"contracts/common/Imports.sol\";\nimport {\n IBaseRewardPool\n} from \"contracts/protocols/convex/common/interfaces/Imports.sol\";\nimport {IMetaPool} from \"contracts/protocols/curve/metapool/Imports.sol\";\n\nabstract contract ConvexBusdv2Constants is INameIdentifier {\n string public constant override NAME = \"convex-busdv2\";\n\n uint256 public constant PID = 34;\n\n // sometimes a metapool is its own LP token; otherwise,\n // you can obtain from `token` attribute\n IERC20 public constant LP_TOKEN =\n IERC20(0x4807862AA8b2bF68830e4C8dc86D0e9A998e085a);\n\n // metapool primary underlyer\n IERC20 public constant PRIMARY_UNDERLYER =\n IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53);\n\n IMetaPool public constant META_POOL =\n IMetaPool(0x4807862AA8b2bF68830e4C8dc86D0e9A998e085a);\n\n IBaseRewardPool public constant REWARD_CONTRACT =\n IBaseRewardPool(0xbD223812d360C9587921292D0644D18aDb6a2ad0);\n}\n" }, "contracts/protocols/convex/metapool/MetaPoolAllocationBaseV2.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\n\nimport {\n ILiquidityGauge,\n IStableSwap\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\nimport {IMetaPool} from \"contracts/protocols/curve/metapool/Imports.sol\";\nimport {\n IBaseRewardPool\n} from \"contracts/protocols/convex/common/interfaces/Imports.sol\";\n\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\nimport {\n Curve3poolUnderlyerConstants\n} from \"contracts/protocols/curve/3pool/Constants.sol\";\n\n/**\n * @title Periphery Contract for a Curve metapool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\nabstract contract MetaPoolAllocationBaseV2 is\n ImmutableAssetAllocation,\n Curve3poolUnderlyerConstants\n{\n using SafeMath for uint256;\n\n address public constant CURVE_3POOL_ADDRESS =\n 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;\n address public constant CURVE_3CRV_ADDRESS =\n 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @param metaPool the liquidity pool comprised of multiple underlyers\n * @param rewardContract the staking contract for the LP tokens\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n IMetaPool metaPool,\n IBaseRewardPool rewardContract,\n IERC20 lpToken,\n uint256 coin\n ) public view returns (uint256 balance) {\n require(address(metaPool) != address(0), \"INVALID_POOL\");\n require(\n address(rewardContract) != address(0),\n \"INVALID_REWARD_CONTRACT\"\n );\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n require(coin < 256, \"INVALID_COIN\");\n\n // since we swap out of primary underlyer, we effectively\n // hold zero of it\n if (coin == 0) {\n return 0;\n }\n // turn into 3Pool index\n coin -= 1;\n\n // metaPool values\n uint256 lpTokenSupply = lpToken.totalSupply();\n // do not include LP tokens held directly by account, as that\n // is included in the regular Curve allocation\n uint256 accountLpTokenBalance = rewardContract.balanceOf(account);\n\n uint256 totalSupplyFor3Crv = IERC20(CURVE_3CRV_ADDRESS).totalSupply();\n\n // metaPool's tracked primary underlyer and 3Crv balances\n // (this will differ from `balanceOf` due to admin fees)\n uint256 metaPoolPrimaryBalance = metaPool.balances(0);\n uint256 metaPool3CrvBalance = metaPool.balances(1);\n\n // calc account's share of 3Crv\n uint256 account3CrvBalance =\n accountLpTokenBalance.mul(metaPool3CrvBalance).div(lpTokenSupply);\n // calc account's share of primary underlyer\n uint256 accountPrimaryBalance =\n accountLpTokenBalance.mul(metaPoolPrimaryBalance).div(\n lpTokenSupply\n );\n // `metaPool.get_dy` can revert on dx = 0, so we skip the call in that case\n if (accountPrimaryBalance > 0) {\n // expected output of swapping primary underlyer amount for 3Crv tokens\n uint256 swap3CrvOutput =\n metaPool.get_dy(0, 1, accountPrimaryBalance);\n // total amount of 3Crv tokens account owns after swapping out of primary underlyer\n account3CrvBalance = account3CrvBalance.add(swap3CrvOutput);\n }\n\n // get account's share of 3Pool underlyer\n uint256 basePoolUnderlyerBalance =\n IStableSwap(CURVE_3POOL_ADDRESS).balances(coin);\n balance = account3CrvBalance.mul(basePoolUnderlyerBalance).div(\n totalSupplyFor3Crv\n );\n }\n\n function _getBasePoolTokenData(\n address primaryUnderlyer,\n string memory symbol,\n uint8 decimals\n ) internal pure returns (TokenData[] memory) {\n TokenData[] memory tokens = new TokenData[](4);\n tokens[0] = TokenData(primaryUnderlyer, symbol, decimals);\n tokens[1] = TokenData(DAI_ADDRESS, \"DAI\", 18);\n tokens[2] = TokenData(USDC_ADDRESS, \"USDC\", 6);\n tokens[3] = TokenData(USDT_ADDRESS, \"USDT\", 6);\n return tokens;\n }\n}\n" }, "contracts/protocols/convex/metapool/MetaPoolAllocationBaseV3.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\n\nimport {\n ILiquidityGauge,\n IStableSwap\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\nimport {IMetaPool} from \"contracts/protocols/curve/metapool/Imports.sol\";\nimport {\n IBaseRewardPool\n} from \"contracts/protocols/convex/common/interfaces/Imports.sol\";\n\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\nimport {\n Curve3poolUnderlyerConstants\n} from \"contracts/protocols/curve/3pool/Constants.sol\";\n\n/**\n * @title Periphery Contract for a Curve metapool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\nabstract contract MetaPoolAllocationBaseV3 is\n ImmutableAssetAllocation,\n Curve3poolUnderlyerConstants\n{\n using SafeMath for uint256;\n\n address public constant CURVE_3POOL_ADDRESS =\n 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;\n address public constant CURVE_3CRV_ADDRESS =\n 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @dev Primary coin for the metapool does not show in the decomposition.\n * The resulting amount form swapping for 3Crv is added to the 3Crv\n * balance, which is then decomposed.\n * @param metaPool the liquidity pool comprised of multiple underlyers\n * @param rewardContract the staking contract for the LP tokens\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n IMetaPool metaPool,\n IBaseRewardPool rewardContract,\n IERC20 lpToken,\n uint256 coin\n ) public view returns (uint256 balance) {\n require(address(metaPool) != address(0), \"INVALID_POOL\");\n require(\n address(rewardContract) != address(0),\n \"INVALID_REWARD_CONTRACT\"\n );\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n require(coin < 256, \"INVALID_COIN\");\n\n // metaPool values\n uint256 lpTokenSupply = lpToken.totalSupply();\n // do not include LP tokens held directly by account, as that\n // is included in the regular Curve allocation\n uint256 accountLpTokenBalance = rewardContract.balanceOf(account);\n\n uint256 totalSupplyFor3Crv = IERC20(CURVE_3CRV_ADDRESS).totalSupply();\n\n // metaPool's tracked primary underlyer and 3Crv balances\n // (this will differ from `balanceOf` due to admin fees)\n uint256 metaPoolPrimaryBalance = metaPool.balances(0);\n uint256 metaPool3CrvBalance = metaPool.balances(1);\n\n // calc account's share of 3Crv\n uint256 account3CrvBalance =\n accountLpTokenBalance.mul(metaPool3CrvBalance).div(lpTokenSupply);\n // calc account's share of primary underlyer\n uint256 accountPrimaryBalance =\n accountLpTokenBalance.mul(metaPoolPrimaryBalance).div(\n lpTokenSupply\n );\n // `metaPool.get_dy` can revert on dx = 0, so we skip the call in that case\n if (accountPrimaryBalance > 0) {\n // expected output of swapping primary underlyer amount for 3Crv tokens\n uint256 swap3CrvOutput =\n metaPool.get_dy(0, 1, accountPrimaryBalance);\n // total amount of 3Crv tokens account owns after swapping out of primary underlyer\n account3CrvBalance = account3CrvBalance.add(swap3CrvOutput);\n }\n\n // get account's share of 3Pool underlyer\n uint256 basePoolUnderlyerBalance =\n IStableSwap(CURVE_3POOL_ADDRESS).balances(coin);\n balance = account3CrvBalance.mul(basePoolUnderlyerBalance).div(\n totalSupplyFor3Crv\n );\n }\n\n function _getBasePoolTokenData()\n internal\n pure\n returns (TokenData[] memory)\n {\n TokenData[] memory tokens = new TokenData[](3);\n tokens[0] = TokenData(DAI_ADDRESS, \"DAI\", 18);\n tokens[1] = TokenData(USDC_ADDRESS, \"USDC\", 6);\n tokens[2] = TokenData(USDT_ADDRESS, \"USDT\", 6);\n return tokens;\n }\n}\n" }, "contracts/protocols/convex/metapool/MetaPoolOldDepositorZap.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IAssetAllocation} from \"contracts/common/Imports.sol\";\nimport {\n IOldDepositor,\n IMetaPool\n} from \"contracts/protocols/curve/metapool/Imports.sol\";\nimport {ConvexZapBase} from \"contracts/protocols/convex/common/Imports.sol\";\n\nabstract contract MetaPoolOldDepositorZap is ConvexZapBase {\n IOldDepositor internal immutable _DEPOSITOR;\n IMetaPool internal immutable _META_POOL;\n\n constructor(\n IOldDepositor depositor,\n IMetaPool metapool,\n address lpAddress,\n uint256 pid,\n uint256 denominator,\n uint256 slippage\n )\n public\n ConvexZapBase(\n address(depositor),\n lpAddress,\n pid,\n denominator,\n slippage,\n 4\n )\n {\n _DEPOSITOR = depositor;\n _META_POOL = metapool;\n }\n\n function _addLiquidity(uint256[] calldata amounts, uint256 minAmount)\n internal\n override\n {\n _DEPOSITOR.add_liquidity(\n [amounts[0], amounts[1], amounts[2], amounts[3]],\n minAmount\n );\n }\n\n function _removeLiquidity(\n uint256 lpBalance,\n uint8 index,\n uint256 minAmount\n ) internal override {\n IERC20(_LP_ADDRESS).safeApprove(address(_DEPOSITOR), 0);\n IERC20(_LP_ADDRESS).safeApprove(address(_DEPOSITOR), lpBalance);\n _DEPOSITOR.remove_liquidity_one_coin(lpBalance, index, minAmount);\n }\n\n function _getVirtualPrice() internal view override returns (uint256) {\n return _META_POOL.get_virtual_price();\n }\n\n function _getCoinAtIndex(uint256 i)\n internal\n view\n override\n returns (address)\n {\n if (i == 0) {\n return _DEPOSITOR.coins(0);\n } else {\n return _DEPOSITOR.base_coins(i.sub(1));\n }\n }\n}\n" }, "contracts/protocols/convex/metapool/MetaPoolDepositorZap.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IAssetAllocation} from \"contracts/common/Imports.sol\";\nimport {\n DepositorConstants,\n IMetaPool\n} from \"contracts/protocols/curve/metapool/Imports.sol\";\nimport {ConvexZapBase} from \"contracts/protocols/convex/common/Imports.sol\";\n\nabstract contract MetaPoolDepositorZap is ConvexZapBase, DepositorConstants {\n IMetaPool internal immutable _META_POOL;\n\n constructor(\n IMetaPool metapool,\n address lpAddress,\n uint256 pid,\n uint256 denominator,\n uint256 slippage\n )\n public\n ConvexZapBase(\n address(DEPOSITOR),\n lpAddress,\n pid,\n denominator,\n slippage,\n 4\n )\n {\n _META_POOL = metapool;\n }\n\n function _addLiquidity(uint256[] calldata amounts, uint256 minAmount)\n internal\n override\n {\n DEPOSITOR.add_liquidity(\n address(_META_POOL),\n [amounts[0], amounts[1], amounts[2], amounts[3]],\n minAmount\n );\n }\n\n function _removeLiquidity(\n uint256 lpBalance,\n uint8 index,\n uint256 minAmount\n ) internal override {\n IERC20(_LP_ADDRESS).safeApprove(address(DEPOSITOR), 0);\n IERC20(_LP_ADDRESS).safeApprove(address(DEPOSITOR), lpBalance);\n DEPOSITOR.remove_liquidity_one_coin(\n address(_META_POOL),\n lpBalance,\n index,\n minAmount\n );\n }\n\n function _getVirtualPrice() internal view override returns (uint256) {\n return _META_POOL.get_virtual_price();\n }\n\n function _getCoinAtIndex(uint256 i)\n internal\n view\n override\n returns (address)\n {\n if (i == 0) {\n return _META_POOL.coins(0);\n } else {\n return BASE_POOL.coins(i.sub(1));\n }\n }\n}\n" }, "contracts/protocols/convex/metapool/MetaPoolDepositorZapV2.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IAssetAllocation} from \"contracts/common/Imports.sol\";\nimport {\n DepositorConstants,\n IMetaPool\n} from \"contracts/protocols/curve/metapool/Imports.sol\";\nimport {ConvexZapBase} from \"contracts/protocols/convex/common/Imports.sol\";\n\nabstract contract MetaPoolDepositorZapV2 is ConvexZapBase, DepositorConstants {\n IMetaPool internal immutable _META_POOL;\n\n constructor(\n IMetaPool metapool,\n address lpAddress,\n uint256 pid,\n uint256 denominator,\n uint256 slippage\n )\n public\n ConvexZapBase(\n address(DEPOSITOR),\n lpAddress,\n pid,\n denominator,\n slippage,\n 4\n )\n {\n _META_POOL = metapool;\n }\n\n function _addLiquidity(uint256[] calldata amounts, uint256 minAmount)\n internal\n override\n {\n DEPOSITOR.add_liquidity(\n address(_META_POOL),\n [amounts[0], amounts[1], amounts[2], amounts[3]],\n minAmount\n );\n }\n\n function _removeLiquidity(\n uint256 lpBalance,\n uint8 index,\n uint256 minAmount\n ) internal override {\n require(index > 0, \"CANT_WITHDRAW_PRIMARY\");\n IERC20(_LP_ADDRESS).safeApprove(address(DEPOSITOR), 0);\n IERC20(_LP_ADDRESS).safeApprove(address(DEPOSITOR), lpBalance);\n DEPOSITOR.remove_liquidity_one_coin(\n address(_META_POOL),\n lpBalance,\n index,\n minAmount\n );\n }\n\n function _getVirtualPrice() internal view override returns (uint256) {\n return _META_POOL.get_virtual_price();\n }\n\n function _getCoinAtIndex(uint256 i)\n internal\n view\n override\n returns (address)\n {\n if (i == 0) {\n return _META_POOL.coins(0);\n } else {\n return BASE_POOL.coins(i.sub(1));\n }\n }\n}\n" }, "contracts/libraries/Imports.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {SignedSafeMath} from \"@openzeppelin/contracts/math/SignedSafeMath.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\nimport {EnumerableSet} from \"@openzeppelin/contracts/utils/EnumerableSet.sol\";\n\nimport {NamedAddressSet} from \"./NamedAddressSet.sol\";\n" }, "contracts/common/Imports.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\nimport {IDetailedERC20} from \"./IDetailedERC20.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {\n ReentrancyGuard\n} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\n\nimport {AccessControl} from \"./AccessControl.sol\";\nimport {INameIdentifier} from \"./INameIdentifier.sol\";\nimport {IAssetAllocation} from \"./IAssetAllocation.sol\";\nimport {IEmergencyExit} from \"./IEmergencyExit.sol\";\n" }, "contracts/protocols/curve/common/interfaces/Imports.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {CTokenInterface} from \"./CTokenInterface.sol\";\nimport {ITokenMinter} from \"./ITokenMinter.sol\";\nimport {IStableSwap, IStableSwap3} from \"./IStableSwap.sol\";\nimport {IStableSwap2} from \"./IStableSwap2.sol\";\nimport {IStableSwap4} from \"./IStableSwap4.sol\";\nimport {IOldStableSwap2} from \"./IOldStableSwap2.sol\";\nimport {IOldStableSwap3} from \"./IOldStableSwap3.sol\";\nimport {IOldStableSwap4} from \"./IOldStableSwap4.sol\";\nimport {ILiquidityGauge} from \"./ILiquidityGauge.sol\";\nimport {IStakingRewards} from \"./IStakingRewards.sol\";\nimport {IDepositZap} from \"./IDepositZap.sol\";\nimport {IDepositZap3} from \"./IDepositZap3.sol\";\n" }, "contracts/protocols/curve/metapool/Imports.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {IMetaPool} from \"./IMetaPool.sol\";\nimport {IOldDepositor} from \"./IOldDepositor.sol\";\nimport {IDepositor} from \"./IDepositor.sol\";\nimport {DepositorConstants} from \"./Constants.sol\";\nimport {MetaPoolAllocationBase} from \"./MetaPoolAllocationBase.sol\";\nimport {MetaPoolAllocationBaseV2} from \"./MetaPoolAllocationBaseV2.sol\";\nimport {MetaPoolAllocationBaseV3} from \"./MetaPoolAllocationBaseV3.sol\";\nimport {MetaPoolOldDepositorZap} from \"./MetaPoolOldDepositorZap.sol\";\nimport {MetaPoolDepositorZap} from \"./MetaPoolDepositorZap.sol\";\n" }, "contracts/protocols/convex/common/interfaces/Imports.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {IBaseRewardPool, IRewardPool} from \"./IBaseRewardPool.sol\";\nimport {IBooster} from \"./IBooster.sol\";\n" }, "contracts/tvl/Imports.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {IErc20Allocation} from \"./IErc20Allocation.sol\";\nimport {IChainlinkRegistry} from \"./IChainlinkRegistry.sol\";\nimport {IAssetAllocationRegistry} from \"./IAssetAllocationRegistry.sol\";\nimport {AssetAllocationBase} from \"./AssetAllocationBase.sol\";\nimport {ImmutableAssetAllocation} from \"./ImmutableAssetAllocation.sol\";\nimport {Erc20AllocationConstants} from \"./Erc20Allocation.sol\";\n" }, "contracts/protocols/curve/3pool/Constants.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {INameIdentifier} from \"contracts/common/Imports.sol\";\n\nabstract contract Curve3poolUnderlyerConstants {\n // underlyer addresses\n address public constant DAI_ADDRESS =\n 0x6B175474E89094C44Da98b954EedeAC495271d0F;\n address public constant USDC_ADDRESS =\n 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;\n address public constant USDT_ADDRESS =\n 0xdAC17F958D2ee523a2206206994597C13D831ec7;\n}\n\nabstract contract Curve3poolConstants is\n Curve3poolUnderlyerConstants,\n INameIdentifier\n{\n string public constant override NAME = \"curve-3pool\";\n\n address public constant STABLE_SWAP_ADDRESS =\n 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;\n address public constant LP_TOKEN_ADDRESS =\n 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;\n address public constant LIQUIDITY_GAUGE_ADDRESS =\n 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A;\n}\n" }, "@openzeppelin/contracts/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\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 // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size > 0;\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 function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, 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 /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "@openzeppelin/contracts/math/SafeMath.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.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, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n\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 *\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 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 *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b <= a, \"SafeMath: subtraction overflow\");\n return a - b;\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 *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0) return 0;\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting 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 *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b > 0, \"SafeMath: division by zero\");\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting 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 *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b > 0, \"SafeMath: modulo by zero\");\n return a % b;\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 * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {trySub}.\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n return a - b;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryDiv}.\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 *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting with custom message when dividing by zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryMod}.\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 *\n * - The divisor cannot be zero.\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/math/SignedSafeMath.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @title SignedSafeMath\n * @dev Signed math operations with safety checks that revert on error.\n */\nlibrary SignedSafeMath {\n int256 constant private _INT256_MIN = -2**255;\n\n /**\n * @dev Returns the multiplication of two signed integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(int256 a, int256 b) internal pure returns (int256) {\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 require(!(a == -1 && b == _INT256_MIN), \"SignedSafeMath: multiplication overflow\");\n\n int256 c = a * b;\n require(c / a == b, \"SignedSafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two signed 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 *\n * - The divisor cannot be zero.\n */\n function div(int256 a, int256 b) internal pure returns (int256) {\n require(b != 0, \"SignedSafeMath: division by zero\");\n require(!(b == -1 && a == _INT256_MIN), \"SignedSafeMath: division overflow\");\n\n int256 c = a / b;\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two signed integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a - b;\n require((b >= 0 && c <= a) || (b < 0 && c > a), \"SignedSafeMath: subtraction overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the addition of two signed integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a + b;\n require((b >= 0 && c >= a) || (b < 0 && c < a), \"SignedSafeMath: addition overflow\");\n\n return c;\n }\n}\n" }, "@openzeppelin/contracts/token/ERC20/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.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 IERC20;` 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 /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\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. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\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" }, "@openzeppelin/contracts/utils/EnumerableSet.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping (bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) { // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs\n // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.\n\n bytes32 lastvalue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastvalue;\n // Update the index for the moved value\n set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n require(set._values.length > index, \"EnumerableSet: index out of bounds\");\n return set._values[index];\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n}\n" }, "contracts/libraries/NamedAddressSet.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\nimport {EnumerableSet} from \"@openzeppelin/contracts/utils/EnumerableSet.sol\";\n\nimport {IAssetAllocation, INameIdentifier} from \"contracts/common/Imports.sol\";\nimport {IZap, ISwap} from \"contracts/lpaccount/Imports.sol\";\n\n/**\n * @notice Stores a set of addresses that can be looked up by name\n * @notice Addresses can be added or removed dynamically\n * @notice Useful for keeping track of unique deployed contracts\n * @dev Each address must be a contract with a `NAME` constant for lookup\n */\n// solhint-disable ordering\nlibrary NamedAddressSet {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n struct Set {\n EnumerableSet.AddressSet _namedAddresses;\n mapping(string => INameIdentifier) _nameLookup;\n }\n\n struct AssetAllocationSet {\n Set _inner;\n }\n\n struct ZapSet {\n Set _inner;\n }\n\n struct SwapSet {\n Set _inner;\n }\n\n function _add(Set storage set, INameIdentifier namedAddress) private {\n require(Address.isContract(address(namedAddress)), \"INVALID_ADDRESS\");\n require(\n !set._namedAddresses.contains(address(namedAddress)),\n \"DUPLICATE_ADDRESS\"\n );\n\n string memory name = namedAddress.NAME();\n require(bytes(name).length != 0, \"INVALID_NAME\");\n require(address(set._nameLookup[name]) == address(0), \"DUPLICATE_NAME\");\n\n set._namedAddresses.add(address(namedAddress));\n set._nameLookup[name] = namedAddress;\n }\n\n function _remove(Set storage set, string memory name) private {\n address namedAddress = address(set._nameLookup[name]);\n require(namedAddress != address(0), \"INVALID_NAME\");\n\n set._namedAddresses.remove(namedAddress);\n delete set._nameLookup[name];\n }\n\n function _contains(Set storage set, INameIdentifier namedAddress)\n private\n view\n returns (bool)\n {\n return set._namedAddresses.contains(address(namedAddress));\n }\n\n function _length(Set storage set) private view returns (uint256) {\n return set._namedAddresses.length();\n }\n\n function _at(Set storage set, uint256 index)\n private\n view\n returns (INameIdentifier)\n {\n return INameIdentifier(set._namedAddresses.at(index));\n }\n\n function _get(Set storage set, string memory name)\n private\n view\n returns (INameIdentifier)\n {\n return set._nameLookup[name];\n }\n\n function _names(Set storage set) private view returns (string[] memory) {\n uint256 length_ = set._namedAddresses.length();\n string[] memory names_ = new string[](length_);\n\n for (uint256 i = 0; i < length_; i++) {\n INameIdentifier namedAddress =\n INameIdentifier(set._namedAddresses.at(i));\n names_[i] = namedAddress.NAME();\n }\n\n return names_;\n }\n\n function add(\n AssetAllocationSet storage set,\n IAssetAllocation assetAllocation\n ) internal {\n _add(set._inner, assetAllocation);\n }\n\n function remove(AssetAllocationSet storage set, string memory name)\n internal\n {\n _remove(set._inner, name);\n }\n\n function contains(\n AssetAllocationSet storage set,\n IAssetAllocation assetAllocation\n ) internal view returns (bool) {\n return _contains(set._inner, assetAllocation);\n }\n\n function length(AssetAllocationSet storage set)\n internal\n view\n returns (uint256)\n {\n return _length(set._inner);\n }\n\n function at(AssetAllocationSet storage set, uint256 index)\n internal\n view\n returns (IAssetAllocation)\n {\n return IAssetAllocation(address(_at(set._inner, index)));\n }\n\n function get(AssetAllocationSet storage set, string memory name)\n internal\n view\n returns (IAssetAllocation)\n {\n return IAssetAllocation(address(_get(set._inner, name)));\n }\n\n function names(AssetAllocationSet storage set)\n internal\n view\n returns (string[] memory)\n {\n return _names(set._inner);\n }\n\n function add(ZapSet storage set, IZap zap) internal {\n _add(set._inner, zap);\n }\n\n function remove(ZapSet storage set, string memory name) internal {\n _remove(set._inner, name);\n }\n\n function contains(ZapSet storage set, IZap zap)\n internal\n view\n returns (bool)\n {\n return _contains(set._inner, zap);\n }\n\n function length(ZapSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n function at(ZapSet storage set, uint256 index)\n internal\n view\n returns (IZap)\n {\n return IZap(address(_at(set._inner, index)));\n }\n\n function get(ZapSet storage set, string memory name)\n internal\n view\n returns (IZap)\n {\n return IZap(address(_get(set._inner, name)));\n }\n\n function names(ZapSet storage set) internal view returns (string[] memory) {\n return _names(set._inner);\n }\n\n function add(SwapSet storage set, ISwap swap) internal {\n _add(set._inner, swap);\n }\n\n function remove(SwapSet storage set, string memory name) internal {\n _remove(set._inner, name);\n }\n\n function contains(SwapSet storage set, ISwap swap)\n internal\n view\n returns (bool)\n {\n return _contains(set._inner, swap);\n }\n\n function length(SwapSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n function at(SwapSet storage set, uint256 index)\n internal\n view\n returns (ISwap)\n {\n return ISwap(address(_at(set._inner, index)));\n }\n\n function get(SwapSet storage set, string memory name)\n internal\n view\n returns (ISwap)\n {\n return ISwap(address(_get(set._inner, name)));\n }\n\n function names(SwapSet storage set)\n internal\n view\n returns (string[] memory)\n {\n return _names(set._inner);\n }\n}\n// solhint-enable ordering\n" }, "@openzeppelin/contracts/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\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" }, "contracts/lpaccount/Imports.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {IZap} from \"./IZap.sol\";\nimport {ISwap} from \"./ISwap.sol\";\nimport {ILpAccount} from \"./ILpAccount.sol\";\nimport {ILpAccountV2} from \"./ILpAccountV2.sol\";\nimport {IZapRegistry} from \"./IZapRegistry.sol\";\nimport {ISwapRegistry} from \"./ISwapRegistry.sol\";\nimport {IStableSwap3Pool} from \"./IStableSwap3Pool.sol\";\nimport {IRewardFeeRegistry} from \"./IRewardFeeRegistry.sol\";\n" }, "contracts/common/IDetailedERC20.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IDetailedERC20 is IERC20 {\n function name() external view returns (string memory);\n\n function symbol() external view returns (string memory);\n\n function decimals() external view returns (uint8);\n}\n" }, "@openzeppelin/contracts/access/Ownable.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../utils/Context.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor () internal {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n}\n" }, "@openzeppelin/contracts/utils/ReentrancyGuard.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n constructor () internal {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and make it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n // On the first call to nonReentrant, _notEntered will be true\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n\n _;\n\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n}\n" }, "contracts/common/AccessControl.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.6.11;\n\nimport {\n AccessControl as OZAccessControl\n} from \"@openzeppelin/contracts/access/AccessControl.sol\";\n\n/**\n * @notice Extends OpenZeppelin AccessControl contract with modifiers\n * @dev This contract and AccessControlUpgradeSafe are essentially duplicates.\n */\ncontract AccessControl is OZAccessControl {\n /** @notice access control roles **/\n bytes32 public constant CONTRACT_ROLE = keccak256(\"CONTRACT_ROLE\");\n bytes32 public constant LP_ROLE = keccak256(\"LP_ROLE\");\n bytes32 public constant ADMIN_ROLE = keccak256(\"ADMIN_ROLE\");\n bytes32 public constant EMERGENCY_ROLE = keccak256(\"EMERGENCY_ROLE\");\n\n modifier onlyLpRole() {\n require(hasRole(LP_ROLE, _msgSender()), \"NOT_LP_ROLE\");\n _;\n }\n\n modifier onlyContractRole() {\n require(hasRole(CONTRACT_ROLE, _msgSender()), \"NOT_CONTRACT_ROLE\");\n _;\n }\n\n modifier onlyAdminRole() {\n require(hasRole(ADMIN_ROLE, _msgSender()), \"NOT_ADMIN_ROLE\");\n _;\n }\n\n modifier onlyEmergencyRole() {\n require(hasRole(EMERGENCY_ROLE, _msgSender()), \"NOT_EMERGENCY_ROLE\");\n _;\n }\n\n modifier onlyLpOrContractRole() {\n require(\n hasRole(LP_ROLE, _msgSender()) ||\n hasRole(CONTRACT_ROLE, _msgSender()),\n \"NOT_LP_OR_CONTRACT_ROLE\"\n );\n _;\n }\n\n modifier onlyAdminOrContractRole() {\n require(\n hasRole(ADMIN_ROLE, _msgSender()) ||\n hasRole(CONTRACT_ROLE, _msgSender()),\n \"NOT_ADMIN_OR_CONTRACT_ROLE\"\n );\n _;\n }\n}\n" }, "contracts/common/INameIdentifier.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\n/**\n * @notice Used by the `NamedAddressSet` library to store sets of contracts\n */\ninterface INameIdentifier {\n /// @notice Should be implemented as a constant value\n // solhint-disable-next-line func-name-mixedcase\n function NAME() external view returns (string memory);\n}\n" }, "contracts/common/IAssetAllocation.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {INameIdentifier} from \"./INameIdentifier.sol\";\n\n/**\n * @notice For use with the `TvlManager` to track the value locked in a protocol\n */\ninterface IAssetAllocation is INameIdentifier {\n struct TokenData {\n address token;\n string symbol;\n uint8 decimals;\n }\n\n /**\n * @notice Get data for the underlying tokens stored in the protocol\n * @return The array of `TokenData`\n */\n function tokens() external view returns (TokenData[] memory);\n\n /**\n * @notice Get the number of different tokens stored in the protocol\n * @return The number of tokens\n */\n function numberOfTokens() external view returns (uint256);\n\n /**\n * @notice Get an account's balance for a token stored in the protocol\n * @dev The token index should be ordered the same as the `tokens()` array\n * @param account The account to get the balance for\n * @param tokenIndex The index of the token to get the balance for\n * @return The account's balance\n */\n function balanceOf(address account, uint8 tokenIndex)\n external\n view\n returns (uint256);\n\n /**\n * @notice Get the symbol of a token stored in the protocol\n * @dev The token index should be ordered the same as the `tokens()` array\n * @param tokenIndex The index of the token\n * @return The symbol of the token\n */\n function symbolOf(uint8 tokenIndex) external view returns (string memory);\n\n /**\n * @notice Get the decimals of a token stored in the protocol\n * @dev The token index should be ordered the same as the `tokens()` array\n * @param tokenIndex The index of the token\n * @return The decimals of the token\n */\n function decimalsOf(uint8 tokenIndex) external view returns (uint8);\n}\n" }, "contracts/common/IEmergencyExit.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {IERC20} from \"./Imports.sol\";\n\n/**\n * @notice Used for contracts that need an emergency escape hatch\n * @notice Should only be used in an emergency to keep funds safu\n */\ninterface IEmergencyExit {\n /**\n * @param emergencySafe The address the tokens were escaped to\n * @param token The token escaped\n * @param balance The amount of tokens escaped\n */\n event EmergencyExit(address emergencySafe, IERC20 token, uint256 balance);\n\n /**\n * @notice Transfer all tokens to the emergency Safe\n * @dev Should only be callable by the emergency Safe\n * @dev Should only transfer tokens to the emergency Safe\n * @param token The token to transfer\n */\n function emergencyExit(address token) external;\n}\n" }, "@openzeppelin/contracts/utils/Context.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n" }, "@openzeppelin/contracts/access/AccessControl.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../utils/EnumerableSet.sol\";\nimport \"../utils/Address.sol\";\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context {\n using EnumerableSet for EnumerableSet.AddressSet;\n using Address for address;\n\n struct RoleData {\n EnumerableSet.AddressSet members;\n bytes32 adminRole;\n }\n\n mapping (bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view returns (bool) {\n return _roles[role].members.contains(account);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view returns (uint256) {\n return _roles[role].members.length();\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view returns (address) {\n return _roles[role].members.at(index);\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) public virtual {\n require(hasRole(_roles[role].adminRole, _msgSender()), \"AccessControl: sender must be an admin to grant\");\n\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) public virtual {\n require(hasRole(_roles[role].adminRole, _msgSender()), \"AccessControl: sender must be an admin to revoke\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) public virtual {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);\n _roles[role].adminRole = adminRole;\n }\n\n function _grantRole(bytes32 role, address account) private {\n if (_roles[role].members.add(account)) {\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n function _revokeRole(bytes32 role, address account) private {\n if (_roles[role].members.remove(account)) {\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n" }, "contracts/lpaccount/IZap.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {\n IAssetAllocation,\n INameIdentifier,\n IERC20\n} from \"contracts/common/Imports.sol\";\n\n/**\n * @notice Used to define how an LP Account farms an external protocol\n */\ninterface IZap is INameIdentifier {\n /**\n * @notice Deploy liquidity to a protocol (i.e. enter a farm)\n * @dev Implementation should add liquidity and stake LP tokens\n * @param amounts Amount of each token to deploy\n */\n function deployLiquidity(uint256[] calldata amounts) external;\n\n /**\n * @notice Unwind liquidity from a protocol (i.e exit a farm)\n * @dev Implementation should unstake LP tokens and remove liquidity\n * @dev If there is only one token to unwind, `index` should be 0\n * @param amount Amount of liquidity to unwind\n * @param index Which token should be unwound\n */\n function unwindLiquidity(uint256 amount, uint8 index) external;\n\n /**\n * @notice Claim accrued rewards from the protocol (i.e. harvest yield)\n */\n function claim() external;\n\n /**\n * @notice Retrieves the LP token balance\n */\n function getLpTokenBalance(address account) external view returns (uint256);\n\n /**\n * @notice Order of tokens for deploy `amounts` and unwind `index`\n * @dev Implementation should use human readable symbols\n * @dev Order should be the same for deploy and unwind\n * @return The array of symbols in order\n */\n function sortedSymbols() external view returns (string[] memory);\n\n /**\n * @notice Asset allocations to include in TVL\n * @dev Requires all allocations that track value deployed to the protocol\n * @return An array of the asset allocation names\n */\n function assetAllocations() external view returns (string[] memory);\n\n /**\n * @notice ERC20 asset allocations to include in TVL\n * @dev Should return addresses for all tokens that get deployed or unwound\n * @return The array of ERC20 token addresses\n */\n function erc20Allocations() external view returns (IERC20[] memory);\n}\n" }, "contracts/lpaccount/ISwap.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {\n IAssetAllocation,\n INameIdentifier,\n IERC20\n} from \"contracts/common/Imports.sol\";\n\n/**\n * @notice Used to define a token swap that can be performed by an LP Account\n */\ninterface ISwap is INameIdentifier {\n /**\n * @dev Implementation should perform a token swap\n * @param amount The amount of the input token to swap\n * @param minAmount The minimum amount of the output token to accept\n */\n function swap(uint256 amount, uint256 minAmount) external;\n\n /**\n * @notice ERC20 asset allocations to include in TVL\n * @dev Should return addresses for all tokens going in and out of the swap\n * @return The array of ERC20 token addresses\n */\n function erc20Allocations() external view returns (IERC20[] memory);\n}\n" }, "contracts/lpaccount/ILpAccount.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\n/**\n * @notice For contracts that provide liquidity to external protocols\n */\ninterface ILpAccount {\n /**\n * @notice Deploy liquidity with a registered `IZap`\n * @dev The order of token amounts should match `IZap.sortedSymbols`\n * @param name The name of the `IZap`\n * @param amounts The token amounts to deploy\n */\n function deployStrategy(string calldata name, uint256[] calldata amounts)\n external;\n\n /**\n * @notice Unwind liquidity with a registered `IZap`\n * @dev The index should match the order of `IZap.sortedSymbols`\n * @param name The name of the `IZap`\n * @param amount The amount of the token to unwind\n * @param index The index of the token to unwind into\n */\n function unwindStrategy(\n string calldata name,\n uint256 amount,\n uint8 index\n ) external;\n\n /**\n * @notice Return liquidity to a pool\n * @notice Typically used to refill a liquidity pool's reserve\n * @dev This should only be callable by the `MetaPoolToken`\n * @param pool The `IReservePool` to transfer to\n * @param amount The amount of the pool's underlyer token to transer\n */\n function transferToPool(address pool, uint256 amount) external;\n\n /**\n * @notice Swap tokens with a registered `ISwap`\n * @notice Used to compound reward tokens\n * @notice Used to rebalance underlyer tokens\n * @param name The name of the `IZap`\n * @param amount The amount of tokens to swap\n * @param minAmount The minimum amount of tokens to receive from the swap\n */\n function swap(\n string calldata name,\n uint256 amount,\n uint256 minAmount\n ) external;\n\n /**\n * @notice Claim reward tokens with a registered `IZap`\n * @param name The name of the `IZap`\n */\n function claim(string calldata name) external;\n}\n" }, "contracts/lpaccount/ILpAccountV2.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\n/**\n * @notice For contracts that provide liquidity to external protocols\n */\ninterface ILpAccountV2 {\n /**\n * @notice Deploy liquidity with a registered `IZap`\n * @dev The order of token amounts should match `IZap.sortedSymbols`\n * @param name The name of the `IZap`\n * @param amounts The token amounts to deploy\n */\n function deployStrategy(string calldata name, uint256[] calldata amounts)\n external;\n\n /**\n * @notice Unwind liquidity with a registered `IZap`\n * @dev The index should match the order of `IZap.sortedSymbols`\n * @param name The name of the `IZap`\n * @param amount The amount of the token to unwind\n * @param index The index of the token to unwind into\n */\n function unwindStrategy(\n string calldata name,\n uint256 amount,\n uint8 index\n ) external;\n\n /**\n * @notice Return liquidity to a pool\n * @notice Typically used to refill a liquidity pool's reserve\n * @dev This should only be callable by the `MetaPoolToken`\n * @param pool The `IReservePool` to transfer to\n * @param amount The amount of the pool's underlyer token to transer\n */\n function transferToPool(address pool, uint256 amount) external;\n\n /**\n * @notice Swap tokens with a registered `ISwap`\n * @notice Used to compound reward tokens\n * @notice Used to rebalance underlyer tokens\n * @param name The name of the `IZap`\n * @param amount The amount of tokens to swap\n * @param minAmount The minimum amount of tokens to receive from the swap\n */\n function swap(\n string calldata name,\n uint256 amount,\n uint256 minAmount\n ) external;\n\n /**\n * @notice Claim reward tokens with registered `IZap`s\n * @param names The names of the `IZap`s\n */\n function claim(string[] calldata names) external;\n}\n" }, "contracts/lpaccount/IZapRegistry.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {IZap} from \"./IZap.sol\";\n\n/**\n * @notice For managing a collection of `IZap` contracts\n */\ninterface IZapRegistry {\n /** @notice Log when a new `IZap` is registered */\n event ZapRegistered(IZap zap);\n\n /** @notice Log when an `IZap` is removed */\n event ZapRemoved(string name);\n\n /**\n * @notice Add a new `IZap` to the registry\n * @dev Should not allow duplicate swaps\n * @param zap The new `IZap`\n */\n function registerZap(IZap zap) external;\n\n /**\n * @notice Remove an `IZap` from the registry\n * @param name The name of the `IZap` (see `INameIdentifier`)\n */\n function removeZap(string calldata name) external;\n\n /**\n * @notice Get the names of all registered `IZap`\n * @return An array of `IZap` names\n */\n function zapNames() external view returns (string[] memory);\n}\n" }, "contracts/lpaccount/ISwapRegistry.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {ISwap} from \"./ISwap.sol\";\n\n/**\n * @notice For managing a collection of `ISwap` contracts\n */\ninterface ISwapRegistry {\n /** @notice Log when a new `ISwap` is registered */\n event SwapRegistered(ISwap swap);\n\n /** @notice Log when an `ISwap` is removed */\n event SwapRemoved(string name);\n\n /**\n * @notice Add a new `ISwap` to the registry\n * @dev Should not allow duplicate swaps\n * @param swap The new `ISwap`\n */\n function registerSwap(ISwap swap) external;\n\n /**\n * @notice Remove an `ISwap` from the registry\n * @param name The name of the `ISwap` (see `INameIdentifier`)\n */\n function removeSwap(string calldata name) external;\n\n /**\n * @notice Get the names of all registered `ISwap`\n * @return An array of `ISwap` names\n */\n function swapNames() external view returns (string[] memory);\n}\n" }, "contracts/lpaccount/IStableSwap3Pool.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\n/**\n * @notice the stablecoin pool contract\n */\ninterface IStableSwap3Pool {\n function exchange(\n int128 i,\n int128 j,\n uint256 dx,\n uint256 min_dy // solhint-disable-line func-param-name-mixedcase\n ) external;\n\n function coins(uint256 coin) external view returns (address);\n\n // solhint-disable-next-line func-name-mixedcase\n function get_dy(\n int128 i,\n int128 j,\n uint256 dx\n ) external view returns (uint256);\n}\n" }, "contracts/lpaccount/IRewardFeeRegistry.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\n/**\n * @notice For managing a collection of `IZap` contracts\n */\ninterface IRewardFeeRegistry {\n /** @notice Log when a reward fee is registered */\n event RewardFeeRegistered(address token, uint256 fee);\n\n /** @notice Log when reward fee is removed */\n event RewardFeeRemoved(address token);\n\n /**\n * @notice register a reward token and its fee\n * @param token address of reward token\n * @param fee percentage to charge fee in basis points\n */\n function registerRewardFee(address token, uint256 fee) external;\n\n /**\n * @notice register multiple reward tokens with fees\n * @param tokens addresss of reward tokens\n * @param fees percentage to charge fee in basis points\n */\n function registerMultipleRewardFees(\n address[] calldata tokens,\n uint256[] calldata fees\n ) external;\n\n /**\n * @notice deregister reward token\n * @param token address of reward token to deregister\n */\n function removeRewardFee(address token) external;\n\n /**\n * @notice deregister multiple reward tokens\n * @param tokens addresses of reward tokens to deregister\n */\n function removeMultipleRewardFees(address[] calldata tokens) external;\n}\n" }, "contracts/protocols/curve/common/interfaces/CTokenInterface.sol": { "content": "// SPDX-License-Identifier: BSD 3-Clause\n/*\n * https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol\n */\npragma solidity 0.6.11;\n\ninterface CTokenInterface {\n function symbol() external returns (string memory);\n\n function decimals() external returns (uint8);\n\n function totalSupply() external returns (uint256);\n\n function isCToken() external returns (bool);\n\n function transfer(address dst, uint256 amount) external returns (bool);\n\n function transferFrom(\n address src,\n address dst,\n uint256 amount\n ) external returns (bool);\n\n function approve(address spender, uint256 amount) external returns (bool);\n\n function totalBorrowsCurrent() external returns (uint256);\n\n function borrowBalanceCurrent(address account) external returns (uint256);\n\n function accrueInterest() external returns (uint256);\n\n function exchangeRateCurrent() external returns (uint256);\n\n function exchangeRateStored() external view returns (uint256);\n\n function getCash() external view returns (uint256);\n\n function borrowBalanceStored(address account)\n external\n view\n returns (uint256);\n\n function allowance(address owner, address spender)\n external\n view\n returns (uint256);\n\n function balanceOf(address owner) external view returns (uint256);\n\n function borrowRatePerBlock() external view returns (uint256);\n\n function supplyRatePerBlock() external view returns (uint256);\n\n function getAccountSnapshot(address account)\n external\n view\n returns (\n uint256,\n uint256,\n uint256,\n uint256\n );\n}\n" }, "contracts/protocols/curve/common/interfaces/ITokenMinter.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n/**\n * @notice the Curve token minter\n * @author Curve Finance\n * @dev translated from vyper\n * license MIT\n * version 0.2.4\n */\n\n// solhint-disable func-name-mixedcase, func-param-name-mixedcase\ninterface ITokenMinter {\n /**\n * @notice Mint everything which belongs to `msg.sender` and send to them\n * @param gauge_addr `LiquidityGauge` address to get mintable amount from\n */\n function mint(address gauge_addr) external;\n\n /**\n * @notice Mint everything which belongs to `msg.sender` across multiple gauges\n * @param gauge_addrs List of `LiquidityGauge` addresses\n */\n function mint_many(address[8] calldata gauge_addrs) external;\n\n /**\n * @notice Mint tokens for `_for`\n * @dev Only possible when `msg.sender` has been approved via `toggle_approve_mint`\n * @param gauge_addr `LiquidityGauge` address to get mintable amount from\n * @param _for Address to mint to\n */\n function mint_for(address gauge_addr, address _for) external;\n\n /**\n * @notice allow `minting_user` to mint for `msg.sender`\n * @param minting_user Address to toggle permission for\n */\n function toggle_approve_mint(address minting_user) external;\n}\n// solhint-enable\n" }, "contracts/protocols/curve/common/interfaces/IStableSwap.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\n/**\n * @notice the stablecoin pool contract\n */\ninterface IStableSwap {\n function balances(uint256 coin) external view returns (uint256);\n\n function coins(uint256 coin) external view returns (address);\n\n // solhint-disable-next-line\n function underlying_coins(uint256 coin) external view returns (address);\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount)\n external;\n\n // solhint-disable-next-line\n function add_liquidity(\n uint256[3] memory amounts,\n uint256 minMinAmount,\n bool useUnderlyer\n ) external;\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts)\n external;\n\n // solhint-disable-next-line\n function remove_liquidity_one_coin(\n uint256 tokenAmount,\n int128 tokenIndex,\n uint256 minAmount\n ) external;\n\n // solhint-disable-next-line\n function remove_liquidity_one_coin(\n uint256 tokenAmount,\n int128 tokenIndex,\n uint256 minAmount,\n bool useUnderlyer\n ) external;\n\n // solhint-disable-next-line\n function get_virtual_price() external view returns (uint256);\n}\n\n// solhint-disable-next-line no-empty-blocks\ninterface IStableSwap3 is IStableSwap {\n\n}\n" }, "contracts/protocols/curve/common/interfaces/IStableSwap2.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @notice the stablecoin pool contract\n */\ninterface IStableSwap2 {\n function balances(uint256 coin) external view returns (uint256);\n\n function coins(uint256 coin) external view returns (address);\n\n // solhint-disable-next-line\n function underlying_coins(uint256 coin) external view returns (address);\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount)\n external;\n\n // solhint-disable-next-line\n function add_liquidity(\n uint256[2] memory amounts,\n uint256 minMinAmount,\n bool useUnderlyer\n ) external;\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function remove_liquidity(uint256 _amount, uint256[2] memory min_amounts)\n external;\n\n // solhint-disable-next-line\n function remove_liquidity_one_coin(\n uint256 tokenAmount,\n int128 tokenIndex,\n uint256 minAmount\n ) external;\n\n // solhint-disable-next-line\n function remove_liquidity_one_coin(\n uint256 tokenAmount,\n int128 tokenIndex,\n uint256 minAmount,\n bool useUnderlyer\n ) external;\n\n // solhint-disable-next-line\n function get_virtual_price() external view returns (uint256);\n\n /**\n * @dev For newest curve pools like aave; older pools refer to a private `token` variable.\n */\n // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase\n}\n" }, "contracts/protocols/curve/common/interfaces/IStableSwap4.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @notice the stablecoin pool contract\n */\ninterface IStableSwap4 {\n function balances(uint256 coin) external view returns (uint256);\n\n function coins(uint256 coin) external view returns (address);\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount)\n external;\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function remove_liquidity(uint256 _amount, uint256[4] memory min_amounts)\n external;\n\n // solhint-disable-next-line\n function remove_liquidity_one_coin(\n uint256 tokenAmount,\n int128 tokenIndex,\n uint256 minAmount\n ) external;\n\n // solhint-disable-next-line\n function get_virtual_price() external view returns (uint256);\n\n /**\n * @dev For newest curve pools like aave; older pools refer to a private `token` variable.\n */\n // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase\n}\n" }, "contracts/protocols/curve/common/interfaces/IOldStableSwap2.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @notice the stablecoin pool contract\n */\ninterface IOldStableSwap2 {\n function balances(int128 coin) external view returns (uint256);\n\n function coins(int128 coin) external view returns (address);\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount)\n external;\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function remove_liquidity(uint256 _amount, uint256[2] memory min_amounts)\n external;\n\n /// @dev need this due to lack of `remove_liquidity_one_coin`\n function exchange(\n int128 i,\n int128 j,\n uint256 dx,\n uint256 min_dy // solhint-disable-line func-param-name-mixedcase\n ) external;\n\n // solhint-disable-next-line\n function get_virtual_price() external view returns (uint256);\n\n /**\n * @dev For newest curve pools like aave; older pools refer to a private `token` variable.\n */\n // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase\n}\n" }, "contracts/protocols/curve/common/interfaces/IOldStableSwap3.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @notice the stablecoin pool contract\n */\ninterface IOldStableSwap3 {\n function balances(int128 coin) external view returns (uint256);\n\n function coins(int128 coin) external view returns (address);\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount)\n external;\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts)\n external;\n\n /// @dev need this due to lack of `remove_liquidity_one_coin`\n function exchange(\n int128 i,\n int128 j,\n uint256 dx,\n uint256 min_dy // solhint-disable-line func-param-name-mixedcase\n ) external;\n\n // solhint-disable-next-line\n function get_virtual_price() external view returns (uint256);\n}\n" }, "contracts/protocols/curve/common/interfaces/IOldStableSwap4.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @notice the stablecoin pool contract\n */\ninterface IOldStableSwap4 {\n function balances(int128 coin) external view returns (uint256);\n\n function coins(int128 coin) external view returns (address);\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount)\n external;\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function remove_liquidity(uint256 _amount, uint256[4] memory min_amounts)\n external;\n\n /// @dev need this due to lack of `remove_liquidity_one_coin`\n function exchange(\n int128 i,\n int128 j,\n uint256 dx,\n uint256 min_dy // solhint-disable-line func-param-name-mixedcase\n ) external;\n\n // solhint-disable-next-line\n function get_virtual_price() external view returns (uint256);\n}\n" }, "contracts/protocols/curve/common/interfaces/ILiquidityGauge.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @notice the liquidity gauge, i.e. staking contract, for the stablecoin pool\n */\ninterface ILiquidityGauge {\n function deposit(uint256 _value) external;\n\n function deposit(uint256 _value, address _addr) external;\n\n function withdraw(uint256 _value) external;\n\n /**\n * @notice Claim available reward tokens for msg.sender\n */\n // solhint-disable-next-line func-name-mixedcase\n function claim_rewards() external;\n\n /**\n * @notice Get the number of claimable reward tokens for a user\n * @dev This function should be manually changed to \"view\" in the ABI\n * Calling it via a transaction will claim available reward tokens\n * @param _addr Account to get reward amount for\n * @param _token Token to get reward amount for\n * @return uint256 Claimable reward token amount\n */\n // solhint-disable-next-line func-name-mixedcase\n function claimable_reward(address _addr, address _token)\n external\n returns (uint256);\n\n function balanceOf(address account) external view returns (uint256);\n}\n" }, "contracts/protocols/curve/common/interfaces/IStakingRewards.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n/*\n * Synthetix: StakingRewards.sol\n *\n * Docs: https://docs.synthetix.io/\n *\n *\n * MIT License\n * ===========\n *\n * Copyright (c) 2020 Synthetix\n *\n */\n\ninterface IStakingRewards {\n // Mutative\n function stake(uint256 amount) external;\n\n function withdraw(uint256 amount) external;\n\n function getReward() external;\n\n function exit() external;\n\n // Views\n function lastTimeRewardApplicable() external view returns (uint256);\n\n function rewardPerToken() external view returns (uint256);\n\n function earned(address account) external view returns (uint256);\n\n function getRewardForDuration() external view returns (uint256);\n\n function totalSupply() external view returns (uint256);\n\n function balanceOf(address account) external view returns (uint256);\n}\n" }, "contracts/protocols/curve/common/interfaces/IDepositZap.sol": { "content": "// SPDX-License-Identifier: BUSDL-2.1\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @notice deposit contract used for pools such as Compound and USDT\n */\ninterface IDepositZap {\n // solhint-disable-next-line\n function underlying_coins(int128 coin) external view returns (address);\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount)\n external;\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function remove_liquidity_one_coin(\n uint256 _amount,\n int128 i,\n uint256 minAmount\n ) external;\n\n function curve() external view returns (address);\n}\n" }, "contracts/protocols/curve/common/interfaces/IDepositZap3.sol": { "content": "// SPDX-License-Identifier: BUSDL-2.1\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @notice deposit contract used for pools such as Compound and USDT\n */\ninterface IDepositZap3 {\n // solhint-disable-next-line\n function underlying_coins(int128 coin) external view returns (address);\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount)\n external;\n\n /**\n * @dev the number of coins is hard-coded in curve contracts\n */\n // solhint-disable-next-line\n function remove_liquidity_one_coin(\n uint256 _amount,\n int128 i,\n uint256 minAmount\n ) external;\n\n function curve() external view returns (address);\n}\n" }, "contracts/protocols/curve/metapool/IMetaPool.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @notice the Curve metapool contract\n * @dev A metapool is sometimes its own LP token\n */\n/* solhint-disable func-name-mixedcase */\n/* solhint-disable func-param-name-mixedcase */\ninterface IMetaPool is IERC20 {\n /// @dev the number of coins is hard-coded in curve contracts\n function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount)\n external;\n\n /// @dev the number of coins is hard-coded in curve contracts\n function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts)\n external;\n\n function remove_liquidity_one_coin(\n uint256 tokenAmount,\n int128 tokenIndex,\n uint256 minAmount\n ) external;\n\n /// @dev 1st coin is the protocol token, 2nd is the Curve base pool\n function balances(uint256 coin) external view returns (uint256);\n\n /// @dev 1st coin is the protocol token, 2nd is the Curve base pool\n function coins(uint256 coin) external view returns (address);\n\n function get_virtual_price() external view returns (uint256);\n\n function get_dy(\n int128 i,\n int128 j,\n uint256 dx\n ) external view returns (uint256);\n}\n/* solhint-enable */\n" }, "contracts/protocols/curve/metapool/IOldDepositor.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\ninterface IOldDepositor {\n // solhint-disable\n function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount)\n external\n returns (uint256);\n\n function remove_liquidity_one_coin(\n uint256 _token_amount,\n int128 i,\n uint256 _min_amount\n ) external returns (uint256);\n\n function coins(uint256 i) external view returns (address);\n\n function base_coins(uint256 i) external view returns (address);\n // solhint-enable\n}\n" }, "contracts/protocols/curve/metapool/IDepositor.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\ninterface IDepositor {\n // solhint-disable\n function add_liquidity(\n address _pool,\n uint256[4] calldata _deposit_amounts,\n uint256 _min_mint_amount\n ) external returns (uint256);\n\n // solhint-enable\n\n // solhint-disable\n function remove_liquidity_one_coin(\n address _pool,\n uint256 _burn_amount,\n int128 i,\n uint256 _min_amounts\n ) external returns (uint256);\n // solhint-enable\n}\n" }, "contracts/protocols/curve/metapool/Constants.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {\n IStableSwap\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\nimport {IDepositor} from \"./IDepositor.sol\";\n\nabstract contract DepositorConstants {\n IStableSwap public constant BASE_POOL =\n IStableSwap(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);\n\n // A depositor \"zap\" contract for metapools\n IDepositor public constant DEPOSITOR =\n IDepositor(0xA79828DF1850E8a3A3064576f380D90aECDD3359);\n}\n" }, "contracts/protocols/curve/metapool/MetaPoolAllocationBase.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\n\nimport {\n ILiquidityGauge\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\n\nimport {IMetaPool} from \"./IMetaPool.sol\";\n\nimport {\n Curve3poolAllocation\n} from \"contracts/protocols/curve/3pool/Allocation.sol\";\n\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\nimport {\n Curve3poolUnderlyerConstants\n} from \"contracts/protocols/curve/3pool/Constants.sol\";\n\n/**\n * @title Periphery Contract for a Curve metapool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\nabstract contract MetaPoolAllocationBase is\n ImmutableAssetAllocation,\n Curve3poolUnderlyerConstants\n{\n using SafeMath for uint256;\n\n /// @dev all existing Curve metapools are paired with 3pool\n Curve3poolAllocation public immutable curve3poolAllocation;\n\n constructor(address curve3poolAllocation_) public {\n curve3poolAllocation = Curve3poolAllocation(curve3poolAllocation_);\n }\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @param metaPool the liquidity pool comprised of multiple underlyers\n * @param gauge the staking contract for the LP tokens\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n IMetaPool metaPool,\n ILiquidityGauge gauge,\n IERC20 lpToken,\n uint256 coin\n ) public view returns (uint256 balance) {\n require(address(metaPool) != address(0), \"INVALID_POOL\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n uint256 poolBalance = getPoolBalance(metaPool, coin);\n (uint256 lpTokenBalance, uint256 lpTokenSupply) =\n getLpTokenShare(account, metaPool, gauge, lpToken);\n\n balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);\n }\n\n function getPoolBalance(IMetaPool metaPool, uint256 coin)\n public\n view\n returns (uint256)\n {\n require(address(metaPool) != address(0), \"INVALID_POOL\");\n require(coin < 256, \"INVALID_COIN\");\n if (coin == 0) {\n return metaPool.balances(0);\n }\n coin -= 1;\n uint256 balance =\n curve3poolAllocation.balanceOf(address(metaPool), uint8(coin));\n // renormalize using the pool's tracked 3Crv balance\n IERC20 baseLpToken = IERC20(metaPool.coins(1));\n uint256 adjustedBalance =\n balance.mul(metaPool.balances(1)).div(\n baseLpToken.balanceOf(address(metaPool))\n );\n return adjustedBalance;\n }\n\n function getLpTokenShare(\n address account,\n IMetaPool metaPool,\n ILiquidityGauge gauge,\n IERC20 lpToken\n ) public view returns (uint256 balance, uint256 totalSupply) {\n require(address(metaPool) != address(0), \"INVALID_POOL\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n totalSupply = lpToken.totalSupply();\n balance = lpToken.balanceOf(account);\n balance = balance.add(gauge.balanceOf(account));\n }\n\n function _getBasePoolTokenData(\n address primaryUnderlyer,\n string memory symbol,\n uint8 decimals\n ) internal pure returns (TokenData[] memory) {\n TokenData[] memory tokens = new TokenData[](4);\n tokens[0] = TokenData(primaryUnderlyer, symbol, decimals);\n tokens[1] = TokenData(DAI_ADDRESS, \"DAI\", 18);\n tokens[2] = TokenData(USDC_ADDRESS, \"USDC\", 6);\n tokens[3] = TokenData(USDT_ADDRESS, \"USDT\", 6);\n return tokens;\n }\n}\n" }, "contracts/protocols/curve/metapool/MetaPoolAllocationBaseV2.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\n\nimport {\n ILiquidityGauge,\n IStableSwap\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\n\nimport {IMetaPool} from \"./IMetaPool.sol\";\n\nimport {\n Curve3poolAllocation\n} from \"contracts/protocols/curve/3pool/Allocation.sol\";\n\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\nimport {\n Curve3poolUnderlyerConstants\n} from \"contracts/protocols/curve/3pool/Constants.sol\";\n\n/**\n * @title Periphery Contract for a Curve metapool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\nabstract contract MetaPoolAllocationBaseV2 is\n ImmutableAssetAllocation,\n Curve3poolUnderlyerConstants\n{\n using SafeMath for uint256;\n\n address public constant CURVE_3POOL_ADDRESS =\n 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;\n address public constant CURVE_3CRV_ADDRESS =\n 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @param metaPool the liquidity pool comprised of multiple underlyers\n * @param gauge the staking contract for the LP tokens\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n IMetaPool metaPool,\n ILiquidityGauge gauge,\n IERC20 lpToken,\n uint256 coin\n ) public view returns (uint256 balance) {\n require(address(metaPool) != address(0), \"INVALID_POOL\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n require(coin < 256, \"INVALID_COIN\");\n\n // since we swap out of primary underlyer, we effectively\n // hold zero of it\n if (coin == 0) {\n return 0;\n }\n // turn into 3Pool index\n coin -= 1;\n\n // metaPool values\n uint256 lpTokenSupply = lpToken.totalSupply();\n uint256 accountLpTokenBalance = lpToken.balanceOf(account);\n accountLpTokenBalance = accountLpTokenBalance.add(\n gauge.balanceOf(account)\n );\n\n uint256 totalSupplyFor3Crv = IERC20(CURVE_3CRV_ADDRESS).totalSupply();\n\n // metaPool's tracked primary underlyer and 3Crv balances\n // (this will differ from `balanceOf` due to admin fees)\n uint256 metaPoolPrimaryBalance = metaPool.balances(0);\n uint256 metaPool3CrvBalance = metaPool.balances(1);\n\n // calc account's share of 3Crv\n uint256 account3CrvBalance =\n accountLpTokenBalance.mul(metaPool3CrvBalance).div(lpTokenSupply);\n // calc account's share of primary underlyer\n uint256 accountPrimaryBalance =\n accountLpTokenBalance.mul(metaPoolPrimaryBalance).div(\n lpTokenSupply\n );\n // `metaPool.get_dy` can revert on dx = 0, so we skip the call in that case\n if (accountPrimaryBalance > 0) {\n // expected output of swapping primary underlyer amount for 3Crv tokens\n uint256 swap3CrvOutput =\n metaPool.get_dy(0, 1, accountPrimaryBalance);\n // total amount of 3Crv tokens account owns after swapping out of primary underlyer\n account3CrvBalance = account3CrvBalance.add(swap3CrvOutput);\n }\n\n // get account's share of 3Pool underlyer\n uint256 basePoolUnderlyerBalance =\n IStableSwap(CURVE_3POOL_ADDRESS).balances(coin);\n balance = account3CrvBalance.mul(basePoolUnderlyerBalance).div(\n totalSupplyFor3Crv\n );\n }\n\n function _getBasePoolTokenData(\n address primaryUnderlyer,\n string memory symbol,\n uint8 decimals\n ) internal pure returns (TokenData[] memory) {\n TokenData[] memory tokens = new TokenData[](4);\n tokens[0] = TokenData(primaryUnderlyer, symbol, decimals);\n tokens[1] = TokenData(DAI_ADDRESS, \"DAI\", 18);\n tokens[2] = TokenData(USDC_ADDRESS, \"USDC\", 6);\n tokens[3] = TokenData(USDT_ADDRESS, \"USDT\", 6);\n return tokens;\n }\n}\n" }, "contracts/protocols/curve/metapool/MetaPoolAllocationBaseV3.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.6.11;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\n\nimport {\n ILiquidityGauge,\n IStableSwap\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\n\nimport {IMetaPool} from \"./IMetaPool.sol\";\n\nimport {\n Curve3poolAllocation\n} from \"contracts/protocols/curve/3pool/Allocation.sol\";\n\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\nimport {\n Curve3poolUnderlyerConstants\n} from \"contracts/protocols/curve/3pool/Constants.sol\";\n\n/**\n * @title Periphery Contract for a Curve metapool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\nabstract contract MetaPoolAllocationBaseV3 is\n ImmutableAssetAllocation,\n Curve3poolUnderlyerConstants\n{\n using SafeMath for uint256;\n\n address public constant CURVE_3POOL_ADDRESS =\n 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;\n address public constant CURVE_3CRV_ADDRESS =\n 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @dev Primary coin for the metapool does not show in the decomposition.\n * The resulting amount form swapping for 3Crv is added to the 3Crv\n * balance, which is then decomposed.\n * @param metaPool the liquidity pool comprised of multiple underlyers\n * @param gauge the staking contract for the LP tokens\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n IMetaPool metaPool,\n ILiquidityGauge gauge,\n IERC20 lpToken,\n uint256 coin\n ) public view returns (uint256 balance) {\n require(address(metaPool) != address(0), \"INVALID_POOL\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n require(coin < 256, \"INVALID_COIN\");\n\n // metaPool values\n uint256 lpTokenSupply = lpToken.totalSupply();\n uint256 accountLpTokenBalance = lpToken.balanceOf(account);\n accountLpTokenBalance = accountLpTokenBalance.add(\n gauge.balanceOf(account)\n );\n\n uint256 totalSupplyFor3Crv = IERC20(CURVE_3CRV_ADDRESS).totalSupply();\n\n // metaPool's tracked primary underlyer and 3Crv balances\n // (this will differ from `balanceOf` due to admin fees)\n uint256 metaPoolPrimaryBalance = metaPool.balances(0);\n uint256 metaPool3CrvBalance = metaPool.balances(1);\n\n // calc account's share of 3Crv\n uint256 account3CrvBalance =\n accountLpTokenBalance.mul(metaPool3CrvBalance).div(lpTokenSupply);\n // calc account's share of primary underlyer\n uint256 accountPrimaryBalance =\n accountLpTokenBalance.mul(metaPoolPrimaryBalance).div(\n lpTokenSupply\n );\n // `metaPool.get_dy` can revert on dx = 0, so we skip the call in that case\n if (accountPrimaryBalance > 0) {\n // expected output of swapping primary underlyer amount for 3Crv tokens\n uint256 swap3CrvOutput =\n metaPool.get_dy(0, 1, accountPrimaryBalance);\n // total amount of 3Crv tokens account owns after swapping out of primary underlyer\n account3CrvBalance = account3CrvBalance.add(swap3CrvOutput);\n }\n\n // get account's share of 3Pool underlyer\n uint256 basePoolUnderlyerBalance =\n IStableSwap(CURVE_3POOL_ADDRESS).balances(coin);\n balance = account3CrvBalance.mul(basePoolUnderlyerBalance).div(\n totalSupplyFor3Crv\n );\n }\n\n function _getBasePoolTokenData()\n internal\n pure\n returns (TokenData[] memory)\n {\n TokenData[] memory tokens = new TokenData[](3);\n tokens[0] = TokenData(DAI_ADDRESS, \"DAI\", 18);\n tokens[1] = TokenData(USDC_ADDRESS, \"USDC\", 6);\n tokens[2] = TokenData(USDT_ADDRESS, \"USDT\", 6);\n return tokens;\n }\n}\n" }, "contracts/protocols/curve/metapool/MetaPoolOldDepositorZap.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IAssetAllocation} from \"contracts/common/Imports.sol\";\nimport {IMetaPool} from \"./IMetaPool.sol\";\nimport {IOldDepositor} from \"./IOldDepositor.sol\";\nimport {CurveGaugeZapBase} from \"contracts/protocols/curve/common/Imports.sol\";\n\nabstract contract MetaPoolOldDepositorZap is CurveGaugeZapBase {\n IOldDepositor internal immutable _DEPOSITOR;\n IMetaPool internal immutable _META_POOL;\n\n constructor(\n IOldDepositor depositor,\n IMetaPool metapool,\n address lpAddress,\n address gaugeAddress,\n uint256 denominator,\n uint256 slippage\n )\n public\n CurveGaugeZapBase(\n address(depositor),\n lpAddress,\n gaugeAddress,\n denominator,\n slippage,\n 4\n )\n {\n _DEPOSITOR = depositor;\n _META_POOL = metapool;\n }\n\n function _addLiquidity(uint256[] calldata amounts, uint256 minAmount)\n internal\n override\n {\n _DEPOSITOR.add_liquidity(\n [amounts[0], amounts[1], amounts[2], amounts[3]],\n minAmount\n );\n }\n\n function _removeLiquidity(\n uint256 lpBalance,\n uint8 index,\n uint256 minAmount\n ) internal override {\n IERC20(LP_ADDRESS).safeApprove(address(_DEPOSITOR), 0);\n IERC20(LP_ADDRESS).safeApprove(address(_DEPOSITOR), lpBalance);\n _DEPOSITOR.remove_liquidity_one_coin(lpBalance, index, minAmount);\n }\n\n function _getVirtualPrice() internal view override returns (uint256) {\n return _META_POOL.get_virtual_price();\n }\n\n function _getCoinAtIndex(uint256 i)\n internal\n view\n override\n returns (address)\n {\n if (i == 0) {\n return _DEPOSITOR.coins(0);\n } else {\n return _DEPOSITOR.base_coins(i.sub(1));\n }\n }\n}\n" }, "contracts/protocols/curve/metapool/MetaPoolDepositorZap.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IAssetAllocation} from \"contracts/common/Imports.sol\";\nimport {IMetaPool} from \"./IMetaPool.sol\";\nimport {DepositorConstants} from \"./Constants.sol\";\nimport {CurveGaugeZapBase} from \"contracts/protocols/curve/common/Imports.sol\";\n\nabstract contract MetaPoolDepositorZap is\n CurveGaugeZapBase,\n DepositorConstants\n{\n IMetaPool internal immutable _META_POOL;\n\n constructor(\n IMetaPool metapool,\n address lpAddress,\n address gaugeAddress,\n uint256 denominator,\n uint256 slippage\n )\n public\n CurveGaugeZapBase(\n address(DEPOSITOR),\n lpAddress,\n gaugeAddress,\n denominator,\n slippage,\n 4\n )\n {\n _META_POOL = metapool;\n }\n\n function _addLiquidity(uint256[] calldata amounts, uint256 minAmount)\n internal\n override\n {\n DEPOSITOR.add_liquidity(\n address(_META_POOL),\n [amounts[0], amounts[1], amounts[2], amounts[3]],\n minAmount\n );\n }\n\n function _removeLiquidity(\n uint256 lpBalance,\n uint8 index,\n uint256 minAmount\n ) internal override {\n IERC20(LP_ADDRESS).safeApprove(address(DEPOSITOR), 0);\n IERC20(LP_ADDRESS).safeApprove(address(DEPOSITOR), lpBalance);\n DEPOSITOR.remove_liquidity_one_coin(\n address(_META_POOL),\n lpBalance,\n index,\n minAmount\n );\n }\n\n function _getVirtualPrice() internal view override returns (uint256) {\n return _META_POOL.get_virtual_price();\n }\n\n function _getCoinAtIndex(uint256 i)\n internal\n view\n override\n returns (address)\n {\n if (i == 0) {\n return _META_POOL.coins(0);\n } else {\n return BASE_POOL.coins(i.sub(1));\n }\n }\n}\n" }, "contracts/protocols/curve/3pool/Allocation.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {IERC20} from \"contracts/common/Imports.sol\";\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\n\nimport {\n IStableSwap,\n ILiquidityGauge\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\n\nimport {\n CurveAllocationBase\n} from \"contracts/protocols/curve/common/Imports.sol\";\n\nimport {Curve3poolConstants} from \"./Constants.sol\";\n\ncontract Curve3poolAllocation is\n CurveAllocationBase,\n ImmutableAssetAllocation,\n Curve3poolConstants\n{\n function balanceOf(address account, uint8 tokenIndex)\n public\n view\n override\n returns (uint256)\n {\n return\n super.getUnderlyerBalance(\n account,\n IStableSwap(STABLE_SWAP_ADDRESS),\n ILiquidityGauge(LIQUIDITY_GAUGE_ADDRESS),\n IERC20(LP_TOKEN_ADDRESS),\n uint256(tokenIndex)\n );\n }\n\n function _getTokenData()\n internal\n pure\n override\n returns (TokenData[] memory)\n {\n TokenData[] memory tokens = new TokenData[](3);\n tokens[0] = TokenData(DAI_ADDRESS, \"DAI\", 18);\n tokens[1] = TokenData(USDC_ADDRESS, \"USDC\", 6);\n tokens[2] = TokenData(USDT_ADDRESS, \"USDT\", 6);\n return tokens;\n }\n}\n" }, "contracts/protocols/curve/common/Imports.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {CurveAllocationBase, CurveAllocationBase3} from \"./CurveAllocationBase.sol\";\nimport {CurveAllocationBase2} from \"./CurveAllocationBase2.sol\";\nimport {CurveAllocationBase4} from \"./CurveAllocationBase4.sol\";\nimport {CurveGaugeZapBase} from \"./CurveGaugeZapBase.sol\";\nimport {CurveZapBase} from \"./CurveZapBase.sol\";\nimport {OldCurveAllocationBase2} from \"./OldCurveAllocationBase2.sol\";\nimport {OldCurveAllocationBase3} from \"./OldCurveAllocationBase3.sol\";\nimport {OldCurveAllocationBase4} from \"./OldCurveAllocationBase4.sol\";\nimport {TestCurveZap} from \"./TestCurveZap.sol\";\n" }, "contracts/tvl/IErc20Allocation.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {IERC20, IDetailedERC20} from \"contracts/common/Imports.sol\";\n\n/**\n * @notice An asset allocation for tokens not stored in a protocol\n * @dev `IZap`s and `ISwap`s register these separate from other allocations\n * @dev Unlike other asset allocations, new tokens can be added or removed\n * @dev Registration can override `symbol` and `decimals` manually because\n * they are optional in the ERC20 standard.\n */\ninterface IErc20Allocation {\n /** @notice Log when an ERC20 allocation is registered */\n event Erc20TokenRegistered(IERC20 token, string symbol, uint8 decimals);\n\n /** @notice Log when an ERC20 allocation is removed */\n event Erc20TokenRemoved(IERC20 token);\n\n /**\n * @notice Add a new ERC20 token to the asset allocation\n * @dev Should not allow duplicate tokens\n * @param token The new token\n */\n function registerErc20Token(IDetailedERC20 token) external;\n\n /**\n * @notice Add a new ERC20 token to the asset allocation\n * @dev Should not allow duplicate tokens\n * @param token The new token\n * @param symbol Override the token symbol\n */\n function registerErc20Token(IDetailedERC20 token, string calldata symbol)\n external;\n\n /**\n * @notice Add a new ERC20 token to the asset allocation\n * @dev Should not allow duplicate tokens\n * @param token The new token\n * @param symbol Override the token symbol\n * @param decimals Override the token decimals\n */\n function registerErc20Token(\n IERC20 token,\n string calldata symbol,\n uint8 decimals\n ) external;\n\n /**\n * @notice Remove an ERC20 token from the asset allocation\n * @param token The token to remove\n */\n function removeErc20Token(IERC20 token) external;\n\n /**\n * @notice Check if an ERC20 token is registered\n * @param token The token to check\n * @return `true` if the token is registered, `false` otherwise\n */\n function isErc20TokenRegistered(IERC20 token) external view returns (bool);\n\n /**\n * @notice Check if multiple ERC20 tokens are ALL registered\n * @param tokens An array of tokens to check\n * @return `true` if every token is registered, `false` otherwise\n */\n function isErc20TokenRegistered(IERC20[] calldata tokens)\n external\n view\n returns (bool);\n}\n" }, "contracts/tvl/IChainlinkRegistry.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\n/**\n * @notice Interface used by Chainlink to aggregate allocations and compute TVL\n */\ninterface IChainlinkRegistry {\n /**\n * @notice Get all IDs from registered asset allocations\n * @notice Each ID is a unique asset allocation and token index pair\n * @dev Should contain no duplicate IDs\n * @return list of all IDs\n */\n function getAssetAllocationIds() external view returns (bytes32[] memory);\n\n /**\n * @notice Get the LP Account's balance for an asset allocation ID\n * @param allocationId The ID to fetch the balance for\n * @return The balance for the LP Account\n */\n function balanceOf(bytes32 allocationId) external view returns (uint256);\n\n /**\n * @notice Get the symbol for an allocation ID's underlying token\n * @param allocationId The ID to fetch the symbol for\n * @return The underlying token symbol\n */\n function symbolOf(bytes32 allocationId)\n external\n view\n returns (string memory);\n\n /**\n * @notice Get the decimals for an allocation ID's underlying token\n * @param allocationId The ID to fetch the decimals for\n * @return The underlying token decimals\n */\n function decimalsOf(bytes32 allocationId) external view returns (uint256);\n}\n" }, "contracts/tvl/IAssetAllocationRegistry.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {IAssetAllocation} from \"contracts/common/Imports.sol\";\n\n/**\n * @notice For managing a collection of `IAssetAllocation` contracts\n */\ninterface IAssetAllocationRegistry {\n /** @notice Log when an asset allocation is registered */\n event AssetAllocationRegistered(IAssetAllocation assetAllocation);\n\n /** @notice Log when an asset allocation is removed */\n event AssetAllocationRemoved(string name);\n\n /**\n * @notice Add a new asset allocation to the registry\n * @dev Should not allow duplicate asset allocations\n * @param assetAllocation The new asset allocation\n */\n function registerAssetAllocation(IAssetAllocation assetAllocation) external;\n\n /**\n * @notice Remove an asset allocation from the registry\n * @param name The name of the asset allocation (see `INameIdentifier`)\n */\n function removeAssetAllocation(string memory name) external;\n\n /**\n * @notice Check if multiple asset allocations are ALL registered\n * @param allocationNames An array of asset allocation names\n * @return `true` if every allocation is registered, otherwise `false`\n */\n function isAssetAllocationRegistered(string[] calldata allocationNames)\n external\n view\n returns (bool);\n\n /**\n * @notice Get the registered asset allocation with a given name\n * @param name The asset allocation name\n * @return The asset allocation\n */\n function getAssetAllocation(string calldata name)\n external\n view\n returns (IAssetAllocation);\n}\n" }, "contracts/tvl/AssetAllocationBase.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {IAssetAllocation} from \"contracts/common/Imports.sol\";\n\nabstract contract AssetAllocationBase is IAssetAllocation {\n function numberOfTokens() external view override returns (uint256) {\n return tokens().length;\n }\n\n function symbolOf(uint8 tokenIndex)\n public\n view\n override\n returns (string memory)\n {\n return tokens()[tokenIndex].symbol;\n }\n\n function decimalsOf(uint8 tokenIndex) public view override returns (uint8) {\n return tokens()[tokenIndex].decimals;\n }\n\n function addressOf(uint8 tokenIndex) public view returns (address) {\n return tokens()[tokenIndex].token;\n }\n\n function tokens() public view virtual override returns (TokenData[] memory);\n}\n" }, "contracts/tvl/ImmutableAssetAllocation.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {Address} from \"contracts/libraries/Imports.sol\";\nimport {AssetAllocationBase} from \"./AssetAllocationBase.sol\";\n\n/**\n * @notice Asset allocation with underlying tokens that cannot be added/removed\n */\nabstract contract ImmutableAssetAllocation is AssetAllocationBase {\n using Address for address;\n\n constructor() public {\n _validateTokens(_getTokenData());\n }\n\n function tokens() public view override returns (TokenData[] memory) {\n TokenData[] memory tokens_ = _getTokenData();\n return tokens_;\n }\n\n /**\n * @notice Verifies that a `TokenData` array works with the `TvlManager`\n * @dev Reverts when there is invalid `TokenData`\n * @param tokens_ The array of `TokenData`\n */\n function _validateTokens(TokenData[] memory tokens_) internal view virtual {\n // length restriction due to encoding logic for allocation IDs\n require(tokens_.length < type(uint8).max, \"TOO_MANY_TOKENS\");\n for (uint256 i = 0; i < tokens_.length; i++) {\n address token = tokens_[i].token;\n _validateTokenAddress(token);\n string memory symbol = tokens_[i].symbol;\n require(bytes(symbol).length != 0, \"INVALID_SYMBOL\");\n }\n // TODO: check for duplicate tokens\n }\n\n /**\n * @notice Verify that a token is a contract\n * @param token The token to verify\n */\n function _validateTokenAddress(address token) internal view virtual {\n require(token.isContract(), \"INVALID_ADDRESS\");\n }\n\n /**\n * @notice Get the immutable array of underlying `TokenData`\n * @dev Should be implemented in child contracts with a hardcoded array\n * @return The array of `TokenData`\n */\n function _getTokenData() internal pure virtual returns (TokenData[] memory);\n}\n" }, "contracts/tvl/Erc20Allocation.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {\n IERC20,\n IDetailedERC20,\n AccessControl,\n INameIdentifier,\n ReentrancyGuard\n} from \"contracts/common/Imports.sol\";\nimport {Address, EnumerableSet} from \"contracts/libraries/Imports.sol\";\nimport {IAddressRegistryV2} from \"contracts/registry/Imports.sol\";\nimport {ILockingOracle} from \"contracts/oracle/Imports.sol\";\n\nimport {IErc20Allocation} from \"./IErc20Allocation.sol\";\nimport {AssetAllocationBase} from \"./AssetAllocationBase.sol\";\n\nabstract contract Erc20AllocationConstants is INameIdentifier {\n string public constant override NAME = \"erc20Allocation\";\n}\n\ncontract Erc20Allocation is\n IErc20Allocation,\n AssetAllocationBase,\n Erc20AllocationConstants,\n AccessControl,\n ReentrancyGuard\n{\n using Address for address;\n using EnumerableSet for EnumerableSet.AddressSet;\n\n IAddressRegistryV2 public addressRegistry;\n\n EnumerableSet.AddressSet private _tokenAddresses;\n mapping(address => TokenData) private _tokenToData;\n\n /** @notice Log when the address registry is changed */\n event AddressRegistryChanged(address);\n\n constructor(address addressRegistry_) public {\n _setAddressRegistry(addressRegistry_);\n _setupRole(DEFAULT_ADMIN_ROLE, addressRegistry.emergencySafeAddress());\n _setupRole(EMERGENCY_ROLE, addressRegistry.emergencySafeAddress());\n _setupRole(ADMIN_ROLE, addressRegistry.adminSafeAddress());\n _setupRole(CONTRACT_ROLE, addressRegistry.mAptAddress());\n }\n\n /**\n * @notice Set the new address registry\n * @param addressRegistry_ The new address registry\n */\n function emergencySetAddressRegistry(address addressRegistry_)\n external\n nonReentrant\n onlyEmergencyRole\n {\n _setAddressRegistry(addressRegistry_);\n }\n\n function registerErc20Token(IDetailedERC20 token)\n external\n override\n nonReentrant\n onlyAdminOrContractRole\n {\n string memory symbol = token.symbol();\n uint8 decimals = token.decimals();\n _registerErc20Token(token, symbol, decimals);\n }\n\n function registerErc20Token(IDetailedERC20 token, string calldata symbol)\n external\n override\n nonReentrant\n onlyAdminRole\n {\n uint8 decimals = token.decimals();\n _registerErc20Token(token, symbol, decimals);\n }\n\n function registerErc20Token(\n IERC20 token,\n string calldata symbol,\n uint8 decimals\n ) external override nonReentrant onlyAdminRole {\n _registerErc20Token(token, symbol, decimals);\n }\n\n function removeErc20Token(IERC20 token)\n external\n override\n nonReentrant\n onlyAdminRole\n {\n _tokenAddresses.remove(address(token));\n delete _tokenToData[address(token)];\n\n _lockOracleAdapter();\n\n emit Erc20TokenRemoved(token);\n }\n\n function isErc20TokenRegistered(IERC20 token)\n external\n view\n override\n returns (bool)\n {\n return _tokenAddresses.contains(address(token));\n }\n\n function isErc20TokenRegistered(IERC20[] calldata tokens)\n external\n view\n override\n returns (bool)\n {\n uint256 length = tokens.length;\n for (uint256 i = 0; i < length; i++) {\n if (!_tokenAddresses.contains(address(tokens[i]))) {\n return false;\n }\n }\n\n return true;\n }\n\n function balanceOf(address account, uint8 tokenIndex)\n external\n view\n override\n returns (uint256)\n {\n address token = addressOf(tokenIndex);\n return IERC20(token).balanceOf(account);\n }\n\n function tokens() public view override returns (TokenData[] memory) {\n TokenData[] memory _tokens = new TokenData[](_tokenAddresses.length());\n for (uint256 i = 0; i < _tokens.length; i++) {\n address tokenAddress = _tokenAddresses.at(i);\n _tokens[i] = _tokenToData[tokenAddress];\n }\n return _tokens;\n }\n\n function _setAddressRegistry(address addressRegistry_) internal {\n require(addressRegistry_.isContract(), \"INVALID_ADDRESS\");\n addressRegistry = IAddressRegistryV2(addressRegistry_);\n emit AddressRegistryChanged(addressRegistry_);\n }\n\n function _registerErc20Token(\n IERC20 token,\n string memory symbol,\n uint8 decimals\n ) internal {\n require(address(token).isContract(), \"INVALID_ADDRESS\");\n require(bytes(symbol).length != 0, \"INVALID_SYMBOL\");\n _tokenAddresses.add(address(token));\n _tokenToData[address(token)] = TokenData(\n address(token),\n symbol,\n decimals\n );\n\n _lockOracleAdapter();\n\n emit Erc20TokenRegistered(token, symbol, decimals);\n }\n\n /**\n * @notice Lock the `OracleAdapter` for the default period of time\n * @dev Locking protects against front-running while Chainlink updates\n */\n function _lockOracleAdapter() internal {\n ILockingOracle oracleAdapter =\n ILockingOracle(addressRegistry.oracleAdapterAddress());\n oracleAdapter.lock();\n }\n}\n" }, "contracts/registry/Imports.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {IAddressRegistryV2} from \"./IAddressRegistryV2.sol\";\n" }, "contracts/oracle/Imports.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {AggregatorV3Interface, FluxAggregator} from \"./FluxAggregator.sol\";\nimport {IOracleAdapter} from \"./IOracleAdapter.sol\";\nimport {IOverrideOracle} from \"./IOverrideOracle.sol\";\nimport {ILockingOracle} from \"./ILockingOracle.sol\";\n" }, "contracts/registry/IAddressRegistryV2.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\n/**\n * @notice The address registry has two important purposes, one which\n * is fairly concrete and another abstract.\n *\n * 1. The registry enables components of the APY.Finance system\n * and external systems to retrieve core addresses reliably\n * even when the functionality may move to a different\n * address.\n *\n * 2. The registry also makes explicit which contracts serve\n * as primary entrypoints for interacting with different\n * components. Not every contract is registered here, only\n * the ones properly deserving of an identifier. This helps\n * define explicit boundaries between groups of contracts,\n * each of which is logically cohesive.\n */\ninterface IAddressRegistryV2 {\n /**\n * @notice Log when a new address is registered\n * @param id The ID of the new address\n * @param _address The new address\n */\n event AddressRegistered(bytes32 id, address _address);\n\n /**\n * @notice Log when an address is removed from the registry\n * @param id The ID of the address\n * @param _address The address\n */\n event AddressDeleted(bytes32 id, address _address);\n\n /**\n * @notice Register address with identifier\n * @dev Using an existing ID will replace the old address with new\n * @dev Currently there is no way to remove an ID, as attempting to\n * register the zero address will revert.\n */\n function registerAddress(bytes32 id, address address_) external;\n\n /**\n * @notice Registers multiple address at once\n * @dev Convenient method to register multiple addresses at once.\n * @param ids Ids to register addresses under\n * @param addresses Addresses to register\n */\n function registerMultipleAddresses(\n bytes32[] calldata ids,\n address[] calldata addresses\n ) external;\n\n /**\n * @notice Removes a registered id and it's associated address\n * @dev Delete the address corresponding to the identifier Time-complexity is O(n) where n is the length of `_idList`.\n * @param id ID to remove along with it's associated address\n */\n function deleteAddress(bytes32 id) external;\n\n /**\n * @notice Returns the list of all registered identifiers.\n * @return List of identifiers\n */\n function getIds() external view returns (bytes32[] memory);\n\n /**\n * @notice Returns the list of all registered identifiers\n * @param id Component identifier\n * @return The current address represented by an identifier\n */\n function getAddress(bytes32 id) external view returns (address);\n\n /**\n * @notice Returns the TVL Manager Address\n * @dev Not just a helper function, this makes explicit a key ID for the system\n * @return TVL Manager Address\n */\n function tvlManagerAddress() external view returns (address);\n\n /**\n * @notice Returns the Chainlink Registry Address\n * @dev Not just a helper function, this makes explicit a key ID for the system\n * @return Chainlink Registry Address\n */\n function chainlinkRegistryAddress() external view returns (address);\n\n /**\n * @notice Returns the DAI Pool Address\n * @dev Not just a helper function, this makes explicit a key ID for the system\n * @return DAI Pool Address\n */\n function daiPoolAddress() external view returns (address);\n\n /**\n * @notice Returns the USDC Pool Address\n * @dev Not just a helper function, this makes explicit a key ID for the system\n * @return USDC Pool Address\n */\n function usdcPoolAddress() external view returns (address);\n\n /**\n * @notice Returns the USDT Pool Address\n * @dev Not just a helper function, this makes explicit a key ID for the system\n * @return USDT Pool Address\n */\n function usdtPoolAddress() external view returns (address);\n\n /**\n * @notice Returns the MAPT Pool Address\n * @dev Not just a helper function, this makes explicit a key ID for the system\n * @return MAPT Pool Address\n */\n function mAptAddress() external view returns (address);\n\n /**\n * @notice Returns the LP Account Address\n * @dev Not just a helper function, this makes explicit a key ID for the system\n * @return LP Account Address\n */\n function lpAccountAddress() external view returns (address);\n\n /**\n * @notice Returns the LP Safe Address\n * @dev Not just a helper function, this makes explicit a key ID for the system\n * @return LP Safe Address\n */\n function lpSafeAddress() external view returns (address);\n\n /**\n * @notice Returns the Admin Safe Address\n * @dev Not just a helper function, this makes explicit a key ID for the system\n * @return Admin Safe Address\n */\n function adminSafeAddress() external view returns (address);\n\n /**\n * @notice Returns the Emergency Safe Address\n * @dev Not just a helper function, this makes explicit a key ID for the system\n * @return Emergency Safe Address\n */\n function emergencySafeAddress() external view returns (address);\n\n /**\n * @notice Returns the Oracle Adapter Address\n * @dev Not just a helper function, this makes explicit a key ID for the system\n * @return Oracle Adapter Address\n */\n function oracleAdapterAddress() external view returns (address);\n\n /**\n * @notice Returns the ERC20 Allocation Address\n * @dev Not just a helper function, this makes explicit a key ID for the system\n * @return ERC20 Allocation Address\n */\n function erc20AllocationAddress() external view returns (address);\n}\n" }, "contracts/oracle/FluxAggregator.sol": { "content": "/**\nSPDX-License-Identifier: UNLICENSED\n----------------------------------\n---- APY.Finance comments --------\n----------------------------------\n\nDue to pragma being fixed at 0.6.6, we had to copy over this contract\nand fix the imports.\n\noriginal path: @chainlink/contracts/src/v0.6/FluxAggregator.sol\nnpm package version: 0.0.9\n */\npragma solidity 0.6.11;\n\nimport \"@chainlink/contracts/src/v0.6/Median.sol\";\nimport \"@chainlink/contracts/src/v0.6/Owned.sol\";\nimport \"@chainlink/contracts/src/v0.6/SafeMath128.sol\";\nimport \"@chainlink/contracts/src/v0.6/SafeMath32.sol\";\nimport \"@chainlink/contracts/src/v0.6/SafeMath64.sol\";\nimport \"@chainlink/contracts/src/v0.6/interfaces/AggregatorV2V3Interface.sol\";\nimport \"@chainlink/contracts/src/v0.6/interfaces/AggregatorValidatorInterface.sol\";\nimport \"@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol\";\nimport \"@chainlink/contracts/src/v0.6/vendor/SafeMath.sol\";\n\n/* solhint-disable */\n/**\n * @title The Prepaid Aggregator contract\n * @notice Handles aggregating data pushed in from off-chain, and unlocks\n * payment for oracles as they report. Oracles' submissions are gathered in\n * rounds, with each round aggregating the submissions for each oracle into a\n * single answer. The latest aggregated answer is exposed as well as historical\n * answers and their updated at timestamp.\n */\ncontract FluxAggregator is AggregatorV2V3Interface, Owned {\n using SafeMath for uint256;\n using SafeMath128 for uint128;\n using SafeMath64 for uint64;\n using SafeMath32 for uint32;\n\n struct Round {\n int256 answer;\n uint64 startedAt;\n uint64 updatedAt;\n uint32 answeredInRound;\n }\n\n struct RoundDetails {\n int256[] submissions;\n uint32 maxSubmissions;\n uint32 minSubmissions;\n uint32 timeout;\n uint128 paymentAmount;\n }\n\n struct OracleStatus {\n uint128 withdrawable;\n uint32 startingRound;\n uint32 endingRound;\n uint32 lastReportedRound;\n uint32 lastStartedRound;\n int256 latestSubmission;\n uint16 index;\n address admin;\n address pendingAdmin;\n }\n\n struct Requester {\n bool authorized;\n uint32 delay;\n uint32 lastStartedRound;\n }\n\n struct Funds {\n uint128 available;\n uint128 allocated;\n }\n\n LinkTokenInterface public linkToken;\n AggregatorValidatorInterface public validator;\n\n // Round related params\n uint128 public paymentAmount;\n uint32 public maxSubmissionCount;\n uint32 public minSubmissionCount;\n uint32 public restartDelay;\n uint32 public timeout;\n uint8 public override decimals;\n string public override description;\n\n int256 public immutable minSubmissionValue;\n int256 public immutable maxSubmissionValue;\n\n uint256 public constant override version = 3;\n\n /**\n * @notice To ensure owner isn't withdrawing required funds as oracles are\n * submitting updates, we enforce that the contract maintains a minimum\n * reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to\n * oracles. (Of course, this doesn't prevent the contract from running out of\n * funds without the owner's intervention.)\n */\n uint256 private constant RESERVE_ROUNDS = 2;\n uint256 private constant MAX_ORACLE_COUNT = 77;\n uint32 private constant ROUND_MAX = 2**32 - 1;\n uint256 private constant VALIDATOR_GAS_LIMIT = 100000;\n // An error specific to the Aggregator V3 Interface, to prevent possible\n // confusion around accidentally reading unset values as reported values.\n string private constant V3_NO_DATA_ERROR = \"No data present\";\n\n uint32 private reportingRoundId;\n uint32 internal latestRoundId;\n mapping(address => OracleStatus) private oracles;\n mapping(uint32 => Round) internal rounds;\n mapping(uint32 => RoundDetails) internal details;\n mapping(address => Requester) internal requesters;\n address[] private oracleAddresses;\n Funds private recordedFunds;\n\n event AvailableFundsUpdated(uint256 indexed amount);\n event RoundDetailsUpdated(\n uint128 indexed paymentAmount,\n uint32 indexed minSubmissionCount,\n uint32 indexed maxSubmissionCount,\n uint32 restartDelay,\n uint32 timeout // measured in seconds\n );\n event OraclePermissionsUpdated(\n address indexed oracle,\n bool indexed whitelisted\n );\n event OracleAdminUpdated(address indexed oracle, address indexed newAdmin);\n event OracleAdminUpdateRequested(\n address indexed oracle,\n address admin,\n address newAdmin\n );\n event SubmissionReceived(\n int256 indexed submission,\n uint32 indexed round,\n address indexed oracle\n );\n event RequesterPermissionsSet(\n address indexed requester,\n bool authorized,\n uint32 delay\n );\n event ValidatorUpdated(address indexed previous, address indexed current);\n\n /**\n * @notice set up the aggregator with initial configuration\n * @param _link The address of the LINK token\n * @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK)\n * @param _timeout is the number of seconds after the previous round that are\n * allowed to lapse before allowing an oracle to skip an unfinished round\n * @param _validator is an optional contract address for validating\n * external validation of answers\n * @param _minSubmissionValue is an immutable check for a lower bound of what\n * submission values are accepted from an oracle\n * @param _maxSubmissionValue is an immutable check for an upper bound of what\n * submission values are accepted from an oracle\n * @param _decimals represents the number of decimals to offset the answer by\n * @param _description a short description of what is being reported\n */\n constructor(\n address _link,\n uint128 _paymentAmount,\n uint32 _timeout,\n address _validator,\n int256 _minSubmissionValue,\n int256 _maxSubmissionValue,\n uint8 _decimals,\n string memory _description\n ) public {\n linkToken = LinkTokenInterface(_link);\n updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout);\n setValidator(_validator);\n minSubmissionValue = _minSubmissionValue;\n maxSubmissionValue = _maxSubmissionValue;\n decimals = _decimals;\n description = _description;\n rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout)));\n }\n\n /**\n * @notice called by oracles when they have witnessed a need to update\n * @param _roundId is the ID of the round this submission pertains to\n * @param _submission is the updated data that the oracle is submitting\n */\n function submit(uint256 _roundId, int256 _submission) external {\n bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));\n require(\n _submission >= minSubmissionValue,\n \"value below minSubmissionValue\"\n );\n require(\n _submission <= maxSubmissionValue,\n \"value above maxSubmissionValue\"\n );\n require(error.length == 0, string(error));\n\n oracleInitializeNewRound(uint32(_roundId));\n recordSubmission(_submission, uint32(_roundId));\n (bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));\n payOracle(uint32(_roundId));\n deleteRoundDetails(uint32(_roundId));\n if (updated) {\n validateAnswer(uint32(_roundId), newAnswer);\n }\n }\n\n /**\n * @notice called by the owner to remove and add new oracles as well as\n * update the round related parameters that pertain to total oracle count\n * @param _removed is the list of addresses for the new Oracles being removed\n * @param _added is the list of addresses for the new Oracles being added\n * @param _addedAdmins is the admin addresses for the new respective _added\n * list. Only this address is allowed to access the respective oracle's funds\n * @param _minSubmissions is the new minimum submission count for each round\n * @param _maxSubmissions is the new maximum submission count for each round\n * @param _restartDelay is the number of rounds an Oracle has to wait before\n * they can initiate a round\n */\n function changeOracles(\n address[] calldata _removed,\n address[] calldata _added,\n address[] calldata _addedAdmins,\n uint32 _minSubmissions,\n uint32 _maxSubmissions,\n uint32 _restartDelay\n ) external onlyOwner() {\n for (uint256 i = 0; i < _removed.length; i++) {\n removeOracle(_removed[i]);\n }\n\n require(\n _added.length == _addedAdmins.length,\n \"need same oracle and admin count\"\n );\n require(\n uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT,\n \"max oracles allowed\"\n );\n\n for (uint256 i = 0; i < _added.length; i++) {\n addOracle(_added[i], _addedAdmins[i]);\n }\n\n updateFutureRounds(\n paymentAmount,\n _minSubmissions,\n _maxSubmissions,\n _restartDelay,\n timeout\n );\n }\n\n /**\n * @notice update the round and payment related parameters for subsequent\n * rounds\n * @param _paymentAmount is the payment amount for subsequent rounds\n * @param _minSubmissions is the new minimum submission count for each round\n * @param _maxSubmissions is the new maximum submission count for each round\n * @param _restartDelay is the number of rounds an Oracle has to wait before\n * they can initiate a round\n */\n function updateFutureRounds(\n uint128 _paymentAmount,\n uint32 _minSubmissions,\n uint32 _maxSubmissions,\n uint32 _restartDelay,\n uint32 _timeout\n ) public onlyOwner() {\n uint32 oracleNum = oracleCount(); // Save on storage reads\n require(\n _maxSubmissions >= _minSubmissions,\n \"max must equal/exceed min\"\n );\n require(oracleNum >= _maxSubmissions, \"max cannot exceed total\");\n require(\n oracleNum == 0 || oracleNum > _restartDelay,\n \"delay cannot exceed total\"\n );\n require(\n recordedFunds.available >= requiredReserve(_paymentAmount),\n \"insufficient funds for payment\"\n );\n if (oracleCount() > 0) {\n require(_minSubmissions > 0, \"min must be greater than 0\");\n }\n\n paymentAmount = _paymentAmount;\n minSubmissionCount = _minSubmissions;\n maxSubmissionCount = _maxSubmissions;\n restartDelay = _restartDelay;\n timeout = _timeout;\n\n emit RoundDetailsUpdated(\n paymentAmount,\n _minSubmissions,\n _maxSubmissions,\n _restartDelay,\n _timeout\n );\n }\n\n /**\n * @notice the amount of payment yet to be withdrawn by oracles\n */\n function allocatedFunds() external view returns (uint128) {\n return recordedFunds.allocated;\n }\n\n /**\n * @notice the amount of future funding available to oracles\n */\n function availableFunds() external view returns (uint128) {\n return recordedFunds.available;\n }\n\n /**\n * @notice recalculate the amount of LINK available for payouts\n */\n function updateAvailableFunds() public {\n Funds memory funds = recordedFunds;\n\n uint256 nowAvailable =\n linkToken.balanceOf(address(this)).sub(funds.allocated);\n\n if (funds.available != nowAvailable) {\n recordedFunds.available = uint128(nowAvailable);\n emit AvailableFundsUpdated(nowAvailable);\n }\n }\n\n /**\n * @notice returns the number of oracles\n */\n function oracleCount() public view returns (uint8) {\n return uint8(oracleAddresses.length);\n }\n\n /**\n * @notice returns an array of addresses containing the oracles on contract\n */\n function getOracles() external view returns (address[] memory) {\n return oracleAddresses;\n }\n\n /**\n * @notice get the most recently reported answer\n *\n * @dev #[deprecated] Use latestRoundData instead. This does not error if no\n * answer has been reached, it will simply return 0. Either wait to point to\n * an already answered Aggregator or use the recommended latestRoundData\n * instead which includes better verification information.\n */\n function latestAnswer() public view virtual override returns (int256) {\n return rounds[latestRoundId].answer;\n }\n\n /**\n * @notice get the most recent updated at timestamp\n *\n * @dev #[deprecated] Use latestRoundData instead. This does not error if no\n * answer has been reached, it will simply return 0. Either wait to point to\n * an already answered Aggregator or use the recommended latestRoundData\n * instead which includes better verification information.\n */\n function latestTimestamp() public view virtual override returns (uint256) {\n return rounds[latestRoundId].updatedAt;\n }\n\n /**\n * @notice get the ID of the last updated round\n *\n * @dev #[deprecated] Use latestRoundData instead. This does not error if no\n * answer has been reached, it will simply return 0. Either wait to point to\n * an already answered Aggregator or use the recommended latestRoundData\n * instead which includes better verification information.\n */\n function latestRound() public view virtual override returns (uint256) {\n return latestRoundId;\n }\n\n /**\n * @notice get past rounds answers\n * @param _roundId the round number to retrieve the answer for\n *\n * @dev #[deprecated] Use getRoundData instead. This does not error if no\n * answer has been reached, it will simply return 0. Either wait to point to\n * an already answered Aggregator or use the recommended getRoundData\n * instead which includes better verification information.\n */\n function getAnswer(uint256 _roundId)\n public\n view\n virtual\n override\n returns (int256)\n {\n if (validRoundId(_roundId)) {\n return rounds[uint32(_roundId)].answer;\n }\n return 0;\n }\n\n /**\n * @notice get timestamp when an answer was last updated\n * @param _roundId the round number to retrieve the updated timestamp for\n *\n * @dev #[deprecated] Use getRoundData instead. This does not error if no\n * answer has been reached, it will simply return 0. Either wait to point to\n * an already answered Aggregator or use the recommended getRoundData\n * instead which includes better verification information.\n */\n function getTimestamp(uint256 _roundId)\n public\n view\n virtual\n override\n returns (uint256)\n {\n if (validRoundId(_roundId)) {\n return rounds[uint32(_roundId)].updatedAt;\n }\n return 0;\n }\n\n /**\n * @notice get data about a round. Consumers are encouraged to check\n * that they're receiving fresh data by inspecting the updatedAt and\n * answeredInRound return values.\n * @param _roundId the round ID to retrieve the round data for\n * @return roundId is the round ID for which data was retrieved\n * @return answer is the answer for the given round\n * @return startedAt is the timestamp when the round was started. This is 0\n * if the round hasn't been started yet.\n * @return updatedAt is the timestamp when the round last was updated (i.e.\n * answer was last computed)\n * @return answeredInRound is the round ID of the round in which the answer\n * was computed. answeredInRound may be smaller than roundId when the round\n * timed out. answeredInRound is equal to roundId when the round didn't time out\n * and was completed regularly.\n * @dev Note that for in-progress rounds (i.e. rounds that haven't yet received\n * maxSubmissions) answer and updatedAt may change between queries.\n */\n function getRoundData(uint80 _roundId)\n public\n view\n virtual\n override\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n )\n {\n Round memory r = rounds[uint32(_roundId)];\n\n require(\n r.answeredInRound > 0 && validRoundId(_roundId),\n V3_NO_DATA_ERROR\n );\n\n return (\n _roundId,\n r.answer,\n r.startedAt,\n r.updatedAt,\n r.answeredInRound\n );\n }\n\n /**\n * @notice get data about the latest round. Consumers are encouraged to check\n * that they're receiving fresh data by inspecting the updatedAt and\n * answeredInRound return values. Consumers are encouraged to\n * use this more fully featured method over the \"legacy\" latestRound/\n * latestAnswer/latestTimestamp functions. Consumers are encouraged to check\n * that they're receiving fresh data by inspecting the updatedAt and\n * answeredInRound return values.\n * @return roundId is the round ID for which data was retrieved\n * @return answer is the answer for the given round\n * @return startedAt is the timestamp when the round was started. This is 0\n * if the round hasn't been started yet.\n * @return updatedAt is the timestamp when the round last was updated (i.e.\n * answer was last computed)\n * @return answeredInRound is the round ID of the round in which the answer\n * was computed. answeredInRound may be smaller than roundId when the round\n * timed out. answeredInRound is equal to roundId when the round didn't time\n * out and was completed regularly.\n * @dev Note that for in-progress rounds (i.e. rounds that haven't yet\n * received maxSubmissions) answer and updatedAt may change between queries.\n */\n function latestRoundData()\n public\n view\n virtual\n override\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n )\n {\n return getRoundData(latestRoundId);\n }\n\n /**\n * @notice query the available amount of LINK for an oracle to withdraw\n */\n function withdrawablePayment(address _oracle)\n external\n view\n returns (uint256)\n {\n return oracles[_oracle].withdrawable;\n }\n\n /**\n * @notice transfers the oracle's LINK to another address. Can only be called\n * by the oracle's admin.\n * @param _oracle is the oracle whose LINK is transferred\n * @param _recipient is the address to send the LINK to\n * @param _amount is the amount of LINK to send\n */\n function withdrawPayment(\n address _oracle,\n address _recipient,\n uint256 _amount\n ) external {\n require(oracles[_oracle].admin == msg.sender, \"only callable by admin\");\n\n // Safe to downcast _amount because the total amount of LINK is less than 2^128.\n uint128 amount = uint128(_amount);\n uint128 available = oracles[_oracle].withdrawable;\n require(available >= amount, \"insufficient withdrawable funds\");\n\n oracles[_oracle].withdrawable = available.sub(amount);\n recordedFunds.allocated = recordedFunds.allocated.sub(amount);\n\n assert(linkToken.transfer(_recipient, uint256(amount)));\n }\n\n /**\n * @notice transfers the owner's LINK to another address\n * @param _recipient is the address to send the LINK to\n * @param _amount is the amount of LINK to send\n */\n function withdrawFunds(address _recipient, uint256 _amount)\n external\n onlyOwner()\n {\n uint256 available = uint256(recordedFunds.available);\n require(\n available.sub(requiredReserve(paymentAmount)) >= _amount,\n \"insufficient reserve funds\"\n );\n require(\n linkToken.transfer(_recipient, _amount),\n \"token transfer failed\"\n );\n updateAvailableFunds();\n }\n\n /**\n * @notice get the admin address of an oracle\n * @param _oracle is the address of the oracle whose admin is being queried\n */\n function getAdmin(address _oracle) external view returns (address) {\n return oracles[_oracle].admin;\n }\n\n /**\n * @notice transfer the admin address for an oracle\n * @param _oracle is the address of the oracle whose admin is being transferred\n * @param _newAdmin is the new admin address\n */\n function transferAdmin(address _oracle, address _newAdmin) external {\n require(oracles[_oracle].admin == msg.sender, \"only callable by admin\");\n oracles[_oracle].pendingAdmin = _newAdmin;\n\n emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin);\n }\n\n /**\n * @notice accept the admin address transfer for an oracle\n * @param _oracle is the address of the oracle whose admin is being transferred\n */\n function acceptAdmin(address _oracle) external {\n require(\n oracles[_oracle].pendingAdmin == msg.sender,\n \"only callable by pending admin\"\n );\n oracles[_oracle].pendingAdmin = address(0);\n oracles[_oracle].admin = msg.sender;\n\n emit OracleAdminUpdated(_oracle, msg.sender);\n }\n\n /**\n * @notice allows non-oracles to request a new round\n */\n function requestNewRound() external returns (uint80) {\n require(requesters[msg.sender].authorized, \"not authorized requester\");\n\n uint32 current = reportingRoundId;\n require(\n rounds[current].updatedAt > 0 || timedOut(current),\n \"prev round must be supersedable\"\n );\n\n uint32 newRoundId = current.add(1);\n requesterInitializeNewRound(newRoundId);\n return newRoundId;\n }\n\n /**\n * @notice allows the owner to specify new non-oracles to start new rounds\n * @param _requester is the address to set permissions for\n * @param _authorized is a boolean specifying whether they can start new rounds or not\n * @param _delay is the number of rounds the requester must wait before starting another round\n */\n function setRequesterPermissions(\n address _requester,\n bool _authorized,\n uint32 _delay\n ) external onlyOwner() {\n if (requesters[_requester].authorized == _authorized) return;\n\n if (_authorized) {\n requesters[_requester].authorized = _authorized;\n requesters[_requester].delay = _delay;\n } else {\n delete requesters[_requester];\n }\n\n emit RequesterPermissionsSet(_requester, _authorized, _delay);\n }\n\n /**\n * @notice called through LINK's transferAndCall to update available funds\n * in the same transaction as the funds were transferred to the aggregator\n * @param _data is mostly ignored. It is checked for length, to be sure\n * nothing strange is passed in.\n */\n function onTokenTransfer(\n address,\n uint256,\n bytes calldata _data\n ) external {\n require(_data.length == 0, \"transfer doesn't accept calldata\");\n updateAvailableFunds();\n }\n\n /**\n * @notice a method to provide all current info oracles need. Intended only\n * only to be callable by oracles. Not for use by contracts to read state.\n * @param _oracle the address to look up information for.\n */\n function oracleRoundState(address _oracle, uint32 _queriedRoundId)\n external\n view\n returns (\n bool _eligibleToSubmit,\n uint32 _roundId,\n int256 _latestSubmission,\n uint64 _startedAt,\n uint64 _timeout,\n uint128 _availableFunds,\n uint8 _oracleCount,\n uint128 _paymentAmount\n )\n {\n require(msg.sender == tx.origin, \"off-chain reading only\");\n\n if (_queriedRoundId > 0) {\n Round storage round = rounds[_queriedRoundId];\n RoundDetails storage details = details[_queriedRoundId];\n return (\n eligibleForSpecificRound(_oracle, _queriedRoundId),\n _queriedRoundId,\n oracles[_oracle].latestSubmission,\n round.startedAt,\n details.timeout,\n recordedFunds.available,\n oracleCount(),\n (round.startedAt > 0 ? details.paymentAmount : paymentAmount)\n );\n } else {\n return oracleRoundStateSuggestRound(_oracle);\n }\n }\n\n /**\n * @notice method to update the address which does external data validation.\n * @param _newValidator designates the address of the new validation contract.\n */\n function setValidator(address _newValidator) public onlyOwner() {\n address previous = address(validator);\n\n if (previous != _newValidator) {\n validator = AggregatorValidatorInterface(_newValidator);\n\n emit ValidatorUpdated(previous, _newValidator);\n }\n }\n\n /**\n * Private\n */\n\n function initializeNewRound(uint32 _roundId) private {\n updateTimedOutRoundInfo(_roundId.sub(1));\n\n reportingRoundId = _roundId;\n RoundDetails memory nextDetails =\n RoundDetails(\n new int256[](0),\n maxSubmissionCount,\n minSubmissionCount,\n timeout,\n paymentAmount\n );\n details[_roundId] = nextDetails;\n rounds[_roundId].startedAt = uint64(block.timestamp);\n\n emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);\n }\n\n function oracleInitializeNewRound(uint32 _roundId) private {\n if (!newRound(_roundId)) return;\n uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads\n if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;\n\n initializeNewRound(_roundId);\n\n oracles[msg.sender].lastStartedRound = _roundId;\n }\n\n function requesterInitializeNewRound(uint32 _roundId) private {\n if (!newRound(_roundId)) return;\n uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads\n require(\n _roundId > lastStarted + requesters[msg.sender].delay ||\n lastStarted == 0,\n \"must delay requests\"\n );\n\n initializeNewRound(_roundId);\n\n requesters[msg.sender].lastStartedRound = _roundId;\n }\n\n function updateTimedOutRoundInfo(uint32 _roundId) private {\n if (!timedOut(_roundId)) return;\n\n uint32 prevId = _roundId.sub(1);\n rounds[_roundId].answer = rounds[prevId].answer;\n rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;\n rounds[_roundId].updatedAt = uint64(block.timestamp);\n\n delete details[_roundId];\n }\n\n function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId)\n private\n view\n returns (bool _eligible)\n {\n if (rounds[_queriedRoundId].startedAt > 0) {\n return\n acceptingSubmissions(_queriedRoundId) &&\n validateOracleRound(_oracle, _queriedRoundId).length == 0;\n } else {\n return\n delayed(_oracle, _queriedRoundId) &&\n validateOracleRound(_oracle, _queriedRoundId).length == 0;\n }\n }\n\n function oracleRoundStateSuggestRound(address _oracle)\n private\n view\n returns (\n bool _eligibleToSubmit,\n uint32 _roundId,\n int256 _latestSubmission,\n uint64 _startedAt,\n uint64 _timeout,\n uint128 _availableFunds,\n uint8 _oracleCount,\n uint128 _paymentAmount\n )\n {\n Round storage round = rounds[0];\n OracleStatus storage oracle = oracles[_oracle];\n\n bool shouldSupersede =\n oracle.lastReportedRound == reportingRoundId ||\n !acceptingSubmissions(reportingRoundId);\n // Instead of nudging oracles to submit to the next round, the inclusion of\n // the shouldSupersede bool in the if condition pushes them towards\n // submitting in a currently open round.\n if (supersedable(reportingRoundId) && shouldSupersede) {\n _roundId = reportingRoundId.add(1);\n round = rounds[_roundId];\n\n _paymentAmount = paymentAmount;\n _eligibleToSubmit = delayed(_oracle, _roundId);\n } else {\n _roundId = reportingRoundId;\n round = rounds[_roundId];\n\n _paymentAmount = details[_roundId].paymentAmount;\n _eligibleToSubmit = acceptingSubmissions(_roundId);\n }\n\n if (validateOracleRound(_oracle, _roundId).length != 0) {\n _eligibleToSubmit = false;\n }\n\n return (\n _eligibleToSubmit,\n _roundId,\n oracle.latestSubmission,\n round.startedAt,\n details[_roundId].timeout,\n recordedFunds.available,\n oracleCount(),\n _paymentAmount\n );\n }\n\n function updateRoundAnswer(uint32 _roundId)\n internal\n returns (bool, int256)\n {\n if (\n details[_roundId].submissions.length <\n details[_roundId].minSubmissions\n ) {\n return (false, 0);\n }\n\n int256 newAnswer =\n Median.calculateInplace(details[_roundId].submissions);\n rounds[_roundId].answer = newAnswer;\n rounds[_roundId].updatedAt = uint64(block.timestamp);\n rounds[_roundId].answeredInRound = _roundId;\n latestRoundId = _roundId;\n\n emit AnswerUpdated(newAnswer, _roundId, now);\n\n return (true, newAnswer);\n }\n\n function validateAnswer(uint32 _roundId, int256 _newAnswer) private {\n AggregatorValidatorInterface av = validator; // cache storage reads\n if (address(av) == address(0)) return;\n\n uint32 prevRound = _roundId.sub(1);\n uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;\n int256 prevRoundAnswer = rounds[prevRound].answer;\n // We do not want the validator to ever prevent reporting, so we limit its\n // gas usage and catch any errors that may arise.\n try\n av.validate{gas: VALIDATOR_GAS_LIMIT}(\n prevAnswerRoundId,\n prevRoundAnswer,\n _roundId,\n _newAnswer\n )\n {} catch {}\n }\n\n function payOracle(uint32 _roundId) private {\n uint128 payment = details[_roundId].paymentAmount;\n Funds memory funds = recordedFunds;\n funds.available = funds.available.sub(payment);\n funds.allocated = funds.allocated.add(payment);\n recordedFunds = funds;\n oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(\n payment\n );\n\n emit AvailableFundsUpdated(funds.available);\n }\n\n function recordSubmission(int256 _submission, uint32 _roundId) private {\n require(\n acceptingSubmissions(_roundId),\n \"round not accepting submissions\"\n );\n\n details[_roundId].submissions.push(_submission);\n oracles[msg.sender].lastReportedRound = _roundId;\n oracles[msg.sender].latestSubmission = _submission;\n\n emit SubmissionReceived(_submission, _roundId, msg.sender);\n }\n\n function deleteRoundDetails(uint32 _roundId) private {\n if (\n details[_roundId].submissions.length <\n details[_roundId].maxSubmissions\n ) return;\n\n delete details[_roundId];\n }\n\n function timedOut(uint32 _roundId) private view returns (bool) {\n uint64 startedAt = rounds[_roundId].startedAt;\n uint32 roundTimeout = details[_roundId].timeout;\n return\n startedAt > 0 &&\n roundTimeout > 0 &&\n startedAt.add(roundTimeout) < block.timestamp;\n }\n\n function getStartingRound(address _oracle) private view returns (uint32) {\n uint32 currentRound = reportingRoundId;\n if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {\n return currentRound;\n }\n return currentRound.add(1);\n }\n\n function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId)\n private\n view\n returns (bool)\n {\n return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0;\n }\n\n function requiredReserve(uint256 payment) private view returns (uint256) {\n return payment.mul(oracleCount()).mul(RESERVE_ROUNDS);\n }\n\n function addOracle(address _oracle, address _admin) private {\n require(!oracleEnabled(_oracle), \"oracle already enabled\");\n\n require(_admin != address(0), \"cannot set admin to 0\");\n require(\n oracles[_oracle].admin == address(0) ||\n oracles[_oracle].admin == _admin,\n \"owner cannot overwrite admin\"\n );\n\n oracles[_oracle].startingRound = getStartingRound(_oracle);\n oracles[_oracle].endingRound = ROUND_MAX;\n oracles[_oracle].index = uint16(oracleAddresses.length);\n oracleAddresses.push(_oracle);\n oracles[_oracle].admin = _admin;\n\n emit OraclePermissionsUpdated(_oracle, true);\n emit OracleAdminUpdated(_oracle, _admin);\n }\n\n function removeOracle(address _oracle) private {\n require(oracleEnabled(_oracle), \"oracle not enabled\");\n\n oracles[_oracle].endingRound = reportingRoundId.add(1);\n address tail = oracleAddresses[uint256(oracleCount()).sub(1)];\n uint16 index = oracles[_oracle].index;\n oracles[tail].index = index;\n delete oracles[_oracle].index;\n oracleAddresses[index] = tail;\n oracleAddresses.pop();\n\n emit OraclePermissionsUpdated(_oracle, false);\n }\n\n function validateOracleRound(address _oracle, uint32 _roundId)\n private\n view\n returns (bytes memory)\n {\n // cache storage reads\n uint32 startingRound = oracles[_oracle].startingRound;\n uint32 rrId = reportingRoundId;\n\n if (startingRound == 0) return \"not enabled oracle\";\n if (startingRound > _roundId) return \"not yet enabled oracle\";\n if (oracles[_oracle].endingRound < _roundId)\n return \"no longer allowed oracle\";\n if (oracles[_oracle].lastReportedRound >= _roundId)\n return \"cannot report on previous rounds\";\n if (\n _roundId != rrId &&\n _roundId != rrId.add(1) &&\n !previousAndCurrentUnanswered(_roundId, rrId)\n ) return \"invalid round to report\";\n if (_roundId != 1 && !supersedable(_roundId.sub(1)))\n return \"previous round not supersedable\";\n }\n\n function supersedable(uint32 _roundId) private view returns (bool) {\n return rounds[_roundId].updatedAt > 0 || timedOut(_roundId);\n }\n\n function oracleEnabled(address _oracle) private view returns (bool) {\n return oracles[_oracle].endingRound == ROUND_MAX;\n }\n\n function acceptingSubmissions(uint32 _roundId) private view returns (bool) {\n return details[_roundId].maxSubmissions != 0;\n }\n\n function delayed(address _oracle, uint32 _roundId)\n private\n view\n returns (bool)\n {\n uint256 lastStarted = oracles[_oracle].lastStartedRound;\n return _roundId > lastStarted + restartDelay || lastStarted == 0;\n }\n\n function newRound(uint32 _roundId) private view returns (bool) {\n return _roundId == reportingRoundId.add(1);\n }\n\n function validRoundId(uint256 _roundId) private view returns (bool) {\n return _roundId <= ROUND_MAX;\n }\n}\n" }, "contracts/oracle/IOracleAdapter.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\n/**\n * @notice Interface for securely interacting with Chainlink aggregators\n */\ninterface IOracleAdapter {\n struct Value {\n uint256 value;\n uint256 periodEnd;\n }\n\n /// @notice Event fired when asset's pricing source (aggregator) is updated\n event AssetSourceUpdated(address indexed asset, address indexed source);\n\n /// @notice Event fired when the TVL aggregator address is updated\n event TvlSourceUpdated(address indexed source);\n\n /**\n * @notice Set the TVL source (aggregator)\n * @param source The new TVL source (aggregator)\n */\n function emergencySetTvlSource(address source) external;\n\n /**\n * @notice Set an asset's price source (aggregator)\n * @param asset The asset to change the source of\n * @param source The new source (aggregator)\n */\n function emergencySetAssetSource(address asset, address source) external;\n\n /**\n * @notice Set multiple assets' pricing sources\n * @param assets An array of assets (tokens)\n * @param sources An array of price sources (aggregators)\n */\n function emergencySetAssetSources(\n address[] memory assets,\n address[] memory sources\n ) external;\n\n /**\n * @notice Retrieve the asset's price from its pricing source\n * @param asset The asset address\n * @return The price of the asset\n */\n function getAssetPrice(address asset) external view returns (uint256);\n\n /**\n * @notice Retrieve the deployed TVL from the TVL aggregator\n * @return The TVL\n */\n function getTvl() external view returns (uint256);\n}\n" }, "contracts/oracle/IOverrideOracle.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {IOracleAdapter} from \"./IOracleAdapter.sol\";\n\ninterface IOverrideOracle is IOracleAdapter {\n /**\n * @notice Event fired when asset value is set manually\n * @param asset The asset that is being overridden\n * @param value The new value used for the override\n * @param period The number of blocks the override will be active for\n * @param periodEnd The block on which the override ends\n */\n event AssetValueSet(\n address asset,\n uint256 value,\n uint256 period,\n uint256 periodEnd\n );\n\n /**\n * @notice Event fired when manually submitted asset value is\n * invalidated, allowing usual Chainlink pricing.\n */\n event AssetValueUnset(address asset);\n\n /**\n * @notice Event fired when deployed TVL is set manually\n * @param value The new value used for the override\n * @param period The number of blocks the override will be active for\n * @param periodEnd The block on which the override ends\n */\n event TvlSet(uint256 value, uint256 period, uint256 periodEnd);\n\n /**\n * @notice Event fired when manually submitted TVL is\n * invalidated, allowing usual Chainlink pricing.\n */\n event TvlUnset();\n\n /**\n * @notice Manually override the asset pricing source with a value\n * @param asset The asset that is being overriden\n * @param value asset value to return instead of from Chainlink\n * @param period length of time, in number of blocks, to use manual override\n */\n function emergencySetAssetValue(\n address asset,\n uint256 value,\n uint256 period\n ) external;\n\n /**\n * @notice Revoke manually set value, allowing usual Chainlink pricing\n * @param asset address of asset to price\n */\n function emergencyUnsetAssetValue(address asset) external;\n\n /**\n * @notice Manually override the TVL source with a value\n * @param value TVL to return instead of from Chainlink\n * @param period length of time, in number of blocks, to use manual override\n */\n function emergencySetTvl(uint256 value, uint256 period) external;\n\n /// @notice Revoke manually set value, allowing usual Chainlink pricing\n function emergencyUnsetTvl() external;\n\n /// @notice Check if TVL has active manual override\n function hasTvlOverride() external view returns (bool);\n\n /**\n * @notice Check if asset has active manual override\n * @param asset address of the asset\n * @return `true` if manual override is active\n */\n function hasAssetOverride(address asset) external view returns (bool);\n}\n" }, "contracts/oracle/ILockingOracle.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {IOracleAdapter} from \"./IOracleAdapter.sol\";\n\n/**\n * @notice For an `IOracleAdapter` that can be locked and unlocked\n */\ninterface ILockingOracle is IOracleAdapter {\n /// @notice Event fired when using the default lock\n event DefaultLocked(address locker, uint256 defaultPeriod, uint256 lockEnd);\n\n /// @notice Event fired when using a specified lock period\n event Locked(address locker, uint256 activePeriod, uint256 lockEnd);\n\n /// @notice Event fired when changing the default locking period\n event DefaultLockPeriodChanged(uint256 newPeriod);\n\n /// @notice Event fired when unlocking the adapter\n event Unlocked();\n\n /// @notice Event fired when updating the threshold for stale data\n event ChainlinkStalePeriodUpdated(uint256 period);\n\n /// @notice Block price/value retrieval for the default locking duration\n function lock() external;\n\n /**\n * @notice Block price/value retrieval for the specified duration.\n * @param period number of blocks to block retrieving values\n */\n function lockFor(uint256 period) external;\n\n /**\n * @notice Unblock price/value retrieval. Should only be callable\n * by the Emergency Safe.\n */\n function emergencyUnlock() external;\n\n /**\n * @notice Set the length of time before values can be retrieved.\n * @param newPeriod number of blocks before values can be retrieved\n */\n function setDefaultLockPeriod(uint256 newPeriod) external;\n\n /**\n * @notice Set the length of time before an agg value is considered stale.\n * @param chainlinkStalePeriod_ the length of time in seconds\n */\n function setChainlinkStalePeriod(uint256 chainlinkStalePeriod_) external;\n\n /**\n * @notice Get the length of time, in number of blocks, before values\n * can be retrieved.\n */\n function defaultLockPeriod() external returns (uint256 period);\n\n /// @notice Check if the adapter is blocked from retrieving values.\n function isLocked() external view returns (bool);\n}\n" }, "@chainlink/contracts/src/v0.6/Median.sol": { "content": "pragma solidity ^0.6.0;\n\nimport \"./vendor/SafeMath.sol\";\nimport \"./SignedSafeMath.sol\";\n\nlibrary Median {\n using SignedSafeMath for int256;\n\n int256 constant INT_MAX = 2**255-1;\n\n /**\n * @notice Returns the sorted middle, or the average of the two middle indexed items if the\n * array has an even number of elements.\n * @dev The list passed as an argument isn't modified.\n * @dev This algorithm has expected runtime O(n), but for adversarially chosen inputs\n * the runtime is O(n^2).\n * @param list The list of elements to compare\n */\n function calculate(int256[] memory list)\n internal\n pure\n returns (int256)\n {\n return calculateInplace(copy(list));\n }\n\n /**\n * @notice See documentation for function calculate.\n * @dev The list passed as an argument may be permuted.\n */\n function calculateInplace(int256[] memory list)\n internal\n pure\n returns (int256)\n {\n require(0 < list.length, \"list must not be empty\");\n uint256 len = list.length;\n uint256 middleIndex = len / 2;\n if (len % 2 == 0) {\n int256 median1;\n int256 median2;\n (median1, median2) = quickselectTwo(list, 0, len - 1, middleIndex - 1, middleIndex);\n return SignedSafeMath.avg(median1, median2);\n } else {\n return quickselect(list, 0, len - 1, middleIndex);\n }\n }\n\n /**\n * @notice Maximum length of list that shortSelectTwo can handle\n */\n uint256 constant SHORTSELECTTWO_MAX_LENGTH = 7;\n\n /**\n * @notice Select the k1-th and k2-th element from list of length at most 7\n * @dev Uses an optimal sorting network\n */\n function shortSelectTwo(\n int256[] memory list,\n uint256 lo,\n uint256 hi,\n uint256 k1,\n uint256 k2\n )\n private\n pure\n returns (int256 k1th, int256 k2th)\n {\n // Uses an optimal sorting network (https://en.wikipedia.org/wiki/Sorting_network)\n // for lists of length 7. Network layout is taken from\n // http://jgamble.ripco.net/cgi-bin/nw.cgi?inputs=7&algorithm=hibbard&output=svg\n\n uint256 len = hi + 1 - lo;\n int256 x0 = list[lo + 0];\n int256 x1 = 1 < len ? list[lo + 1] : INT_MAX;\n int256 x2 = 2 < len ? list[lo + 2] : INT_MAX;\n int256 x3 = 3 < len ? list[lo + 3] : INT_MAX;\n int256 x4 = 4 < len ? list[lo + 4] : INT_MAX;\n int256 x5 = 5 < len ? list[lo + 5] : INT_MAX;\n int256 x6 = 6 < len ? list[lo + 6] : INT_MAX;\n\n if (x0 > x1) {(x0, x1) = (x1, x0);}\n if (x2 > x3) {(x2, x3) = (x3, x2);}\n if (x4 > x5) {(x4, x5) = (x5, x4);}\n if (x0 > x2) {(x0, x2) = (x2, x0);}\n if (x1 > x3) {(x1, x3) = (x3, x1);}\n if (x4 > x6) {(x4, x6) = (x6, x4);}\n if (x1 > x2) {(x1, x2) = (x2, x1);}\n if (x5 > x6) {(x5, x6) = (x6, x5);}\n if (x0 > x4) {(x0, x4) = (x4, x0);}\n if (x1 > x5) {(x1, x5) = (x5, x1);}\n if (x2 > x6) {(x2, x6) = (x6, x2);}\n if (x1 > x4) {(x1, x4) = (x4, x1);}\n if (x3 > x6) {(x3, x6) = (x6, x3);}\n if (x2 > x4) {(x2, x4) = (x4, x2);}\n if (x3 > x5) {(x3, x5) = (x5, x3);}\n if (x3 > x4) {(x3, x4) = (x4, x3);}\n\n uint256 index1 = k1 - lo;\n if (index1 == 0) {k1th = x0;}\n else if (index1 == 1) {k1th = x1;}\n else if (index1 == 2) {k1th = x2;}\n else if (index1 == 3) {k1th = x3;}\n else if (index1 == 4) {k1th = x4;}\n else if (index1 == 5) {k1th = x5;}\n else if (index1 == 6) {k1th = x6;}\n else {revert(\"k1 out of bounds\");}\n\n uint256 index2 = k2 - lo;\n if (k1 == k2) {return (k1th, k1th);}\n else if (index2 == 0) {return (k1th, x0);}\n else if (index2 == 1) {return (k1th, x1);}\n else if (index2 == 2) {return (k1th, x2);}\n else if (index2 == 3) {return (k1th, x3);}\n else if (index2 == 4) {return (k1th, x4);}\n else if (index2 == 5) {return (k1th, x5);}\n else if (index2 == 6) {return (k1th, x6);}\n else {revert(\"k2 out of bounds\");}\n }\n\n /**\n * @notice Selects the k-th ranked element from list, looking only at indices between lo and hi\n * (inclusive). Modifies list in-place.\n */\n function quickselect(int256[] memory list, uint256 lo, uint256 hi, uint256 k)\n private\n pure\n returns (int256 kth)\n {\n require(lo <= k);\n require(k <= hi);\n while (lo < hi) {\n if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) {\n int256 ignore;\n (kth, ignore) = shortSelectTwo(list, lo, hi, k, k);\n return kth;\n }\n uint256 pivotIndex = partition(list, lo, hi);\n if (k <= pivotIndex) {\n // since pivotIndex < (original hi passed to partition),\n // termination is guaranteed in this case\n hi = pivotIndex;\n } else {\n // since (original lo passed to partition) <= pivotIndex,\n // termination is guaranteed in this case\n lo = pivotIndex + 1;\n }\n }\n return list[lo];\n }\n\n /**\n * @notice Selects the k1-th and k2-th ranked elements from list, looking only at indices between\n * lo and hi (inclusive). Modifies list in-place.\n */\n function quickselectTwo(\n int256[] memory list,\n uint256 lo,\n uint256 hi,\n uint256 k1,\n uint256 k2\n )\n internal // for testing\n pure\n returns (int256 k1th, int256 k2th)\n {\n require(k1 < k2);\n require(lo <= k1 && k1 <= hi);\n require(lo <= k2 && k2 <= hi);\n\n while (true) {\n if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) {\n return shortSelectTwo(list, lo, hi, k1, k2);\n }\n uint256 pivotIdx = partition(list, lo, hi);\n if (k2 <= pivotIdx) {\n hi = pivotIdx;\n } else if (pivotIdx < k1) {\n lo = pivotIdx + 1;\n } else {\n assert(k1 <= pivotIdx && pivotIdx < k2);\n k1th = quickselect(list, lo, pivotIdx, k1);\n k2th = quickselect(list, pivotIdx + 1, hi, k2);\n return (k1th, k2th);\n }\n }\n }\n\n /**\n * @notice Partitions list in-place using Hoare's partitioning scheme.\n * Only elements of list between indices lo and hi (inclusive) will be modified.\n * Returns an index i, such that:\n * - lo <= i < hi\n * - forall j in [lo, i]. list[j] <= list[i]\n * - forall j in [i, hi]. list[i] <= list[j]\n */\n function partition(int256[] memory list, uint256 lo, uint256 hi)\n private\n pure\n returns (uint256)\n {\n // We don't care about overflow of the addition, because it would require a list\n // larger than any feasible computer's memory.\n int256 pivot = list[(lo + hi) / 2];\n lo -= 1; // this can underflow. that's intentional.\n hi += 1;\n while (true) {\n do {\n lo += 1;\n } while (list[lo] < pivot);\n do {\n hi -= 1;\n } while (list[hi] > pivot);\n if (lo < hi) {\n (list[lo], list[hi]) = (list[hi], list[lo]);\n } else {\n // Let orig_lo and orig_hi be the original values of lo and hi passed to partition.\n // Then, hi < orig_hi, because hi decreases *strictly* monotonically\n // in each loop iteration and\n // - either list[orig_hi] > pivot, in which case the first loop iteration\n // will achieve hi < orig_hi;\n // - or list[orig_hi] <= pivot, in which case at least two loop iterations are\n // needed:\n // - lo will have to stop at least once in the interval\n // [orig_lo, (orig_lo + orig_hi)/2]\n // - (orig_lo + orig_hi)/2 < orig_hi\n return hi;\n }\n }\n }\n\n /**\n * @notice Makes an in-memory copy of the array passed in\n * @param list Reference to the array to be copied\n */\n function copy(int256[] memory list)\n private\n pure\n returns(int256[] memory)\n {\n int256[] memory list2 = new int256[](list.length);\n for (uint256 i = 0; i < list.length; i++) {\n list2[i] = list[i];\n }\n return list2;\n }\n}\n" }, "@chainlink/contracts/src/v0.6/Owned.sol": { "content": "pragma solidity ^0.6.0;\n\n/**\n * @title The Owned contract\n * @notice A contract with helpers for basic contract ownership.\n */\ncontract Owned {\n\n address payable public owner;\n address private pendingOwner;\n\n event OwnershipTransferRequested(\n address indexed from,\n address indexed to\n );\n event OwnershipTransferred(\n address indexed from,\n address indexed to\n );\n\n constructor() public {\n owner = msg.sender;\n }\n\n /**\n * @dev Allows an owner to begin transferring ownership to a new address,\n * pending.\n */\n function transferOwnership(address _to)\n external\n onlyOwner()\n {\n pendingOwner = _to;\n\n emit OwnershipTransferRequested(owner, _to);\n }\n\n /**\n * @dev Allows an ownership transfer to be completed by the recipient.\n */\n function acceptOwnership()\n external\n {\n require(msg.sender == pendingOwner, \"Must be proposed owner\");\n\n address oldOwner = owner;\n owner = msg.sender;\n pendingOwner = address(0);\n\n emit OwnershipTransferred(oldOwner, msg.sender);\n }\n\n /**\n * @dev Reverts if called by anyone other than the contract owner.\n */\n modifier onlyOwner() {\n require(msg.sender == owner, \"Only callable by owner\");\n _;\n }\n\n}\n" }, "@chainlink/contracts/src/v0.6/SafeMath128.sol": { "content": "pragma solidity ^0.6.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 *\n * This library is a version of Open Zeppelin's SafeMath, modified to support\n * unsigned 128 bit integers.\n */\nlibrary SafeMath128 {\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(uint128 a, uint128 b) internal pure returns (uint128) {\n uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {\n require(b <= a, \"SafeMath: subtraction overflow\");\n uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {\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-solidity/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, \"SafeMath: division by zero\");\n uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {\n require(b != 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n}\n" }, "@chainlink/contracts/src/v0.6/SafeMath32.sol": { "content": "pragma solidity ^0.6.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 *\n * This library is a version of Open Zeppelin's SafeMath, modified to support\n * unsigned 32 bit integers.\n */\nlibrary SafeMath32 {\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(uint32 a, uint32 b) internal pure returns (uint32) {\n uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {\n require(b <= a, \"SafeMath: subtraction overflow\");\n uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {\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-solidity/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, \"SafeMath: division by zero\");\n uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {\n require(b != 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n}\n" }, "@chainlink/contracts/src/v0.6/SafeMath64.sol": { "content": "pragma solidity ^0.6.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 *\n * This library is a version of Open Zeppelin's SafeMath, modified to support\n * unsigned 64 bit integers.\n */\nlibrary SafeMath64 {\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(uint64 a, uint64 b) internal pure returns (uint64) {\n uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {\n require(b <= a, \"SafeMath: subtraction overflow\");\n uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {\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-solidity/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, \"SafeMath: division by zero\");\n uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {\n require(b != 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n}\n" }, "@chainlink/contracts/src/v0.6/interfaces/AggregatorV2V3Interface.sol": { "content": "pragma solidity >=0.6.0;\n\nimport \"./AggregatorInterface.sol\";\nimport \"./AggregatorV3Interface.sol\";\n\ninterface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface\n{\n}\n" }, "@chainlink/contracts/src/v0.6/interfaces/AggregatorValidatorInterface.sol": { "content": "pragma solidity ^0.6.0;\n\ninterface AggregatorValidatorInterface {\n function validate(\n uint256 previousRoundId,\n int256 previousAnswer,\n uint256 currentRoundId,\n int256 currentAnswer\n ) external returns (bool);\n}\n" }, "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol": { "content": "pragma solidity ^0.6.0;\n\ninterface LinkTokenInterface {\n function allowance(address owner, address spender) external view returns (uint256 remaining);\n function approve(address spender, uint256 value) external returns (bool success);\n function balanceOf(address owner) external view returns (uint256 balance);\n function decimals() external view returns (uint8 decimalPlaces);\n function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);\n function increaseApproval(address spender, uint256 subtractedValue) external;\n function name() external view returns (string memory tokenName);\n function symbol() external view returns (string memory tokenSymbol);\n function totalSupply() external view returns (uint256 totalTokensIssued);\n function transfer(address to, uint256 value) external returns (bool success);\n function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);\n function transferFrom(address from, address to, uint256 value) external returns (bool success);\n}\n" }, "@chainlink/contracts/src/v0.6/vendor/SafeMath.sol": { "content": "pragma solidity ^0.6.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 require(b <= a, \"SafeMath: subtraction overflow\");\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-solidity/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 // Solidity only automatically asserts when dividing by 0\n require(b > 0, \"SafeMath: division by zero\");\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 require(b != 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n}\n" }, "@chainlink/contracts/src/v0.6/SignedSafeMath.sol": { "content": "pragma solidity ^0.6.0;\n\nlibrary SignedSafeMath {\n int256 constant private _INT256_MIN = -2**255;\n\n /**\n * @dev Multiplies two signed integers, reverts on overflow.\n */\n function mul(int256 a, int256 b) internal pure returns (int256) {\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 require(!(a == -1 && b == _INT256_MIN), \"SignedSafeMath: multiplication overflow\");\n\n int256 c = a * b;\n require(c / a == b, \"SignedSafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.\n */\n function div(int256 a, int256 b) internal pure returns (int256) {\n require(b != 0, \"SignedSafeMath: division by zero\");\n require(!(b == -1 && a == _INT256_MIN), \"SignedSafeMath: division overflow\");\n\n int256 c = a / b;\n\n return c;\n }\n\n /**\n * @dev Subtracts two signed integers, reverts on overflow.\n */\n function sub(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a - b;\n require((b >= 0 && c <= a) || (b < 0 && c > a), \"SignedSafeMath: subtraction overflow\");\n\n return c;\n }\n\n /**\n * @dev Adds two signed integers, reverts on overflow.\n */\n function add(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a + b;\n require((b >= 0 && c >= a) || (b < 0 && c < a), \"SignedSafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @notice Computes average of two signed integers, ensuring that the computation\n * doesn't overflow.\n * @dev If the result is not an integer, it is rounded towards zero. For example,\n * avg(-3, -4) = -3\n */\n function avg(int256 _a, int256 _b)\n internal\n pure\n returns (int256)\n {\n if ((_a < 0 && _b > 0) || (_a > 0 && _b < 0)) {\n return add(_a, _b) / 2;\n }\n int256 remainder = (_a % 2 + _b % 2) / 2;\n return add(add(_a / 2, _b / 2), remainder);\n }\n}\n" }, "@chainlink/contracts/src/v0.6/interfaces/AggregatorInterface.sol": { "content": "pragma solidity >=0.6.0;\n\ninterface AggregatorInterface {\n function latestAnswer() external view returns (int256);\n function latestTimestamp() external view returns (uint256);\n function latestRound() external view returns (uint256);\n function getAnswer(uint256 roundId) external view returns (int256);\n function getTimestamp(uint256 roundId) external view returns (uint256);\n\n event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);\n event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);\n}\n" }, "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol": { "content": "pragma solidity >=0.6.0;\n\ninterface AggregatorV3Interface {\n\n function decimals() external view returns (uint8);\n function description() external view returns (string memory);\n function version() external view returns (uint256);\n\n // getRoundData and latestRoundData should both raise \"No data present\"\n // if they do not have data to report, instead of returning unset values\n // which could be misinterpreted as actual reported values.\n function getRoundData(uint80 _roundId)\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n function latestRoundData()\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n\n}\n" }, "contracts/protocols/curve/common/CurveAllocationBase.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\n\nimport {\n IStableSwap,\n ILiquidityGauge\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\n\n/**\n * @title Periphery Contract for the Curve 3pool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\ncontract CurveAllocationBase {\n using SafeMath for uint256;\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @param stableSwap the liquidity pool comprised of multiple underlyers\n * @param gauge the staking contract for the LP tokens\n * @param lpToken the LP token representing the share of the pool\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n IStableSwap stableSwap,\n ILiquidityGauge gauge,\n IERC20 lpToken,\n uint256 coin\n ) public view returns (uint256 balance) {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n uint256 poolBalance = getPoolBalance(stableSwap, coin);\n (uint256 lpTokenBalance, uint256 lpTokenSupply) =\n getLpTokenShare(account, stableSwap, gauge, lpToken);\n\n balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);\n }\n\n function getPoolBalance(IStableSwap stableSwap, uint256 coin)\n public\n view\n returns (uint256)\n {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n return stableSwap.balances(coin);\n }\n\n function getLpTokenShare(\n address account,\n IStableSwap stableSwap,\n ILiquidityGauge gauge,\n IERC20 lpToken\n ) public view returns (uint256 balance, uint256 totalSupply) {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n totalSupply = lpToken.totalSupply();\n balance = lpToken.balanceOf(account);\n balance = balance.add(gauge.balanceOf(account));\n }\n}\n\n// solhint-disable-next-line no-empty-blocks\ncontract CurveAllocationBase3 is CurveAllocationBase {\n\n}\n" }, "contracts/protocols/curve/common/CurveAllocationBase2.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\n\nimport {\n IStableSwap2,\n ILiquidityGauge\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\n\n/**\n * @title Periphery Contract for the Curve 3pool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\ncontract CurveAllocationBase2 {\n using SafeMath for uint256;\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @param stableSwap the liquidity pool comprised of multiple underlyers\n * @param gauge the staking contract for the LP tokens\n * @param lpToken the LP token representing the share of the pool\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n IStableSwap2 stableSwap,\n ILiquidityGauge gauge,\n IERC20 lpToken,\n uint256 coin\n ) public view returns (uint256 balance) {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n uint256 poolBalance = getPoolBalance(stableSwap, coin);\n (uint256 lpTokenBalance, uint256 lpTokenSupply) =\n getLpTokenShare(account, stableSwap, gauge, lpToken);\n\n balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);\n }\n\n function getPoolBalance(IStableSwap2 stableSwap, uint256 coin)\n public\n view\n returns (uint256)\n {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n return stableSwap.balances(coin);\n }\n\n function getLpTokenShare(\n address account,\n IStableSwap2 stableSwap,\n ILiquidityGauge gauge,\n IERC20 lpToken\n ) public view returns (uint256 balance, uint256 totalSupply) {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n totalSupply = lpToken.totalSupply();\n balance = lpToken.balanceOf(account);\n balance = balance.add(gauge.balanceOf(account));\n }\n}\n" }, "contracts/protocols/curve/common/CurveAllocationBase4.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\n\nimport {\n IStableSwap4,\n ILiquidityGauge\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\n\n/**\n * @title Periphery Contract for the Curve 3pool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\ncontract CurveAllocationBase4 {\n using SafeMath for uint256;\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @param stableSwap the liquidity pool comprised of multiple underlyers\n * @param gauge the staking contract for the LP tokens\n * @param lpToken the LP token representing the share of the pool\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n IStableSwap4 stableSwap,\n ILiquidityGauge gauge,\n IERC20 lpToken,\n uint256 coin\n ) public view returns (uint256 balance) {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n uint256 poolBalance = getPoolBalance(stableSwap, coin);\n (uint256 lpTokenBalance, uint256 lpTokenSupply) =\n getLpTokenShare(account, stableSwap, gauge, lpToken);\n\n balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);\n }\n\n function getPoolBalance(IStableSwap4 stableSwap, uint256 coin)\n public\n view\n returns (uint256)\n {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n return stableSwap.balances(coin);\n }\n\n function getLpTokenShare(\n address account,\n IStableSwap4 stableSwap,\n ILiquidityGauge gauge,\n IERC20 lpToken\n ) public view returns (uint256 balance, uint256 totalSupply) {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n totalSupply = lpToken.totalSupply();\n balance = lpToken.balanceOf(account);\n balance = balance.add(gauge.balanceOf(account));\n }\n}\n" }, "contracts/protocols/curve/common/CurveGaugeZapBase.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {IZap} from \"contracts/lpaccount/Imports.sol\";\nimport {\n IAssetAllocation,\n IERC20,\n IDetailedERC20\n} from \"contracts/common/Imports.sol\";\nimport {SafeERC20} from \"contracts/libraries/Imports.sol\";\nimport {\n ILiquidityGauge,\n ITokenMinter\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\nimport {CurveZapBase} from \"contracts/protocols/curve/common/CurveZapBase.sol\";\n\nabstract contract CurveGaugeZapBase is IZap, CurveZapBase {\n using SafeERC20 for IERC20;\n\n address internal constant MINTER_ADDRESS =\n 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;\n\n address internal immutable LP_ADDRESS;\n address internal immutable GAUGE_ADDRESS;\n\n constructor(\n address swapAddress,\n address lpAddress,\n address gaugeAddress,\n uint256 denominator,\n uint256 slippage,\n uint256 nCoins\n )\n public\n CurveZapBase(swapAddress, denominator, slippage, nCoins)\n // solhint-disable-next-line no-empty-blocks\n {\n LP_ADDRESS = lpAddress;\n GAUGE_ADDRESS = gaugeAddress;\n }\n\n function getLpTokenBalance(address account)\n external\n view\n override\n returns (uint256)\n {\n return ILiquidityGauge(GAUGE_ADDRESS).balanceOf(account);\n }\n\n function _depositToGauge() internal override {\n ILiquidityGauge liquidityGauge = ILiquidityGauge(GAUGE_ADDRESS);\n uint256 lpBalance = IERC20(LP_ADDRESS).balanceOf(address(this));\n IERC20(LP_ADDRESS).safeApprove(GAUGE_ADDRESS, 0);\n IERC20(LP_ADDRESS).safeApprove(GAUGE_ADDRESS, lpBalance);\n liquidityGauge.deposit(lpBalance);\n }\n\n function _withdrawFromGauge(uint256 amount)\n internal\n override\n returns (uint256)\n {\n ILiquidityGauge liquidityGauge = ILiquidityGauge(GAUGE_ADDRESS);\n liquidityGauge.withdraw(amount);\n //lpBalance\n return IERC20(LP_ADDRESS).balanceOf(address(this));\n }\n\n function _claim() internal override {\n // claim CRV\n ITokenMinter(MINTER_ADDRESS).mint(GAUGE_ADDRESS);\n\n // claim protocol-specific rewards\n _claimRewards();\n }\n\n // solhint-disable-next-line no-empty-blocks\n function _claimRewards() internal virtual {}\n}\n" }, "contracts/protocols/curve/common/CurveZapBase.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath, SafeERC20} from \"contracts/libraries/Imports.sol\";\nimport {IZap} from \"contracts/lpaccount/Imports.sol\";\nimport {\n IAssetAllocation,\n IDetailedERC20,\n IERC20\n} from \"contracts/common/Imports.sol\";\nimport {\n Curve3poolUnderlyerConstants\n} from \"contracts/protocols/curve/3pool/Constants.sol\";\n\nabstract contract CurveZapBase is Curve3poolUnderlyerConstants, IZap {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n address internal constant CRV_ADDRESS =\n 0xD533a949740bb3306d119CC777fa900bA034cd52;\n\n address internal immutable SWAP_ADDRESS;\n uint256 internal immutable DENOMINATOR;\n uint256 internal immutable SLIPPAGE;\n uint256 internal immutable N_COINS;\n\n constructor(\n address swapAddress,\n uint256 denominator,\n uint256 slippage,\n uint256 nCoins\n ) public {\n SWAP_ADDRESS = swapAddress;\n DENOMINATOR = denominator;\n SLIPPAGE = slippage;\n N_COINS = nCoins;\n }\n\n /// @param amounts array of underlyer amounts\n function deployLiquidity(uint256[] calldata amounts) external override {\n require(amounts.length == N_COINS, \"INVALID_AMOUNTS\");\n\n uint256 totalNormalizedDeposit = 0;\n for (uint256 i = 0; i < amounts.length; i++) {\n if (amounts[i] == 0) continue;\n\n uint256 deposit = amounts[i];\n address underlyerAddress = _getCoinAtIndex(i);\n uint8 decimals = IDetailedERC20(underlyerAddress).decimals();\n\n uint256 normalizedDeposit =\n deposit.mul(10**uint256(18)).div(10**uint256(decimals));\n totalNormalizedDeposit = totalNormalizedDeposit.add(\n normalizedDeposit\n );\n\n IERC20(underlyerAddress).safeApprove(SWAP_ADDRESS, 0);\n IERC20(underlyerAddress).safeApprove(SWAP_ADDRESS, amounts[i]);\n }\n\n uint256 minAmount =\n _calcMinAmount(totalNormalizedDeposit, _getVirtualPrice());\n _addLiquidity(amounts, minAmount);\n _depositToGauge();\n }\n\n /**\n * @param amount LP token amount\n * @param index underlyer index\n */\n function unwindLiquidity(uint256 amount, uint8 index) external override {\n require(index < N_COINS, \"INVALID_INDEX\");\n uint256 lpBalance = _withdrawFromGauge(amount);\n address underlyerAddress = _getCoinAtIndex(index);\n uint8 decimals = IDetailedERC20(underlyerAddress).decimals();\n uint256 minAmount =\n _calcMinAmountUnderlyer(lpBalance, _getVirtualPrice(), decimals);\n _removeLiquidity(lpBalance, index, minAmount);\n }\n\n function claim() external override {\n _claim();\n }\n\n function sortedSymbols() public view override returns (string[] memory) {\n // N_COINS is not available as a public function\n // so we have to hardcode the number here\n string[] memory symbols = new string[](N_COINS);\n for (uint256 i = 0; i < symbols.length; i++) {\n address underlyerAddress = _getCoinAtIndex(i);\n symbols[i] = IDetailedERC20(underlyerAddress).symbol();\n }\n return symbols;\n }\n\n function _getVirtualPrice() internal view virtual returns (uint256);\n\n function _getCoinAtIndex(uint256 i) internal view virtual returns (address);\n\n function _addLiquidity(uint256[] calldata amounts_, uint256 minAmount)\n internal\n virtual;\n\n function _removeLiquidity(\n uint256 lpBalance,\n uint8 index,\n uint256 minAmount\n ) internal virtual;\n\n function _depositToGauge() internal virtual;\n\n function _withdrawFromGauge(uint256 amount)\n internal\n virtual\n returns (uint256);\n\n function _claim() internal virtual;\n\n /**\n * @dev normalizedDepositAmount the amount in same units as virtual price (18 decimals)\n * @dev virtualPrice the \"price\", in 18 decimals, per big token unit of the LP token\n * @return required minimum amount of LP token (in token wei)\n */\n function _calcMinAmount(\n uint256 normalizedDepositAmount,\n uint256 virtualPrice\n ) internal view returns (uint256) {\n uint256 idealLpTokenAmount =\n normalizedDepositAmount.mul(1e18).div(virtualPrice);\n // allow some slippage/MEV\n return\n idealLpTokenAmount.mul(DENOMINATOR.sub(SLIPPAGE)).div(DENOMINATOR);\n }\n\n /**\n * @param lpTokenAmount the amount in the same units as Curve LP token (18 decimals)\n * @param virtualPrice the \"price\", in 18 decimals, per big token unit of the LP token\n * @param decimals the number of decimals for underlyer token\n * @return required minimum amount of underlyer (in token wei)\n */\n function _calcMinAmountUnderlyer(\n uint256 lpTokenAmount,\n uint256 virtualPrice,\n uint8 decimals\n ) internal view returns (uint256) {\n // TODO: grab LP Token decimals explicitly?\n uint256 normalizedUnderlyerAmount =\n lpTokenAmount.mul(virtualPrice).div(1e18);\n uint256 underlyerAmount =\n normalizedUnderlyerAmount.mul(10**uint256(decimals)).div(\n 10**uint256(18)\n );\n\n // allow some slippage/MEV\n return underlyerAmount.mul(DENOMINATOR.sub(SLIPPAGE)).div(DENOMINATOR);\n }\n\n function _createErc20AllocationArray(uint256 extraAllocations)\n internal\n pure\n returns (IERC20[] memory)\n {\n IERC20[] memory allocations = new IERC20[](extraAllocations.add(4));\n allocations[0] = IERC20(CRV_ADDRESS);\n allocations[1] = IERC20(DAI_ADDRESS);\n allocations[2] = IERC20(USDC_ADDRESS);\n allocations[3] = IERC20(USDT_ADDRESS);\n return allocations;\n }\n}\n" }, "contracts/protocols/curve/common/OldCurveAllocationBase2.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\n\nimport {\n IOldStableSwap2,\n ILiquidityGauge\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\n\n/**\n * @title Periphery Contract for the Curve 3pool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\ncontract OldCurveAllocationBase2 {\n using SafeMath for uint256;\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @param stableSwap the liquidity pool comprised of multiple underlyers\n * @param gauge the staking contract for the LP tokens\n * @param lpToken the LP token representing the share of the pool\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n IOldStableSwap2 stableSwap,\n ILiquidityGauge gauge,\n IERC20 lpToken,\n int128 coin\n ) public view returns (uint256 balance) {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n uint256 poolBalance = getPoolBalance(stableSwap, coin);\n (uint256 lpTokenBalance, uint256 lpTokenSupply) =\n getLpTokenShare(account, stableSwap, gauge, lpToken);\n\n balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);\n }\n\n function getPoolBalance(IOldStableSwap2 stableSwap, int128 coin)\n public\n view\n returns (uint256)\n {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n return stableSwap.balances(coin);\n }\n\n function getLpTokenShare(\n address account,\n IOldStableSwap2 stableSwap,\n ILiquidityGauge gauge,\n IERC20 lpToken\n ) public view returns (uint256 balance, uint256 totalSupply) {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n totalSupply = lpToken.totalSupply();\n balance = lpToken.balanceOf(account);\n balance = balance.add(gauge.balanceOf(account));\n }\n}\n" }, "contracts/protocols/curve/common/OldCurveAllocationBase3.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\n\nimport {IOldStableSwap3, ILiquidityGauge} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\n\n/**\n * @title Periphery Contract for the Curve 3pool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\ncontract OldCurveAllocationBase3 {\n using SafeMath for uint256;\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @param stableSwap the liquidity pool comprised of multiple underlyers\n * @param gauge the staking contract for the LP tokens\n * @param lpToken the LP token representing the share of the pool\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n IOldStableSwap3 stableSwap,\n ILiquidityGauge gauge,\n IERC20 lpToken,\n int128 coin\n ) public view returns (uint256 balance) {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n uint256 poolBalance = getPoolBalance(stableSwap, coin);\n (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(\n account,\n stableSwap,\n gauge,\n lpToken\n );\n\n balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);\n }\n\n function getPoolBalance(IOldStableSwap3 stableSwap, int128 coin)\n public\n view\n returns (uint256)\n {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n return stableSwap.balances(coin);\n }\n\n function getLpTokenShare(\n address account,\n IOldStableSwap3 stableSwap,\n ILiquidityGauge gauge,\n IERC20 lpToken\n ) public view returns (uint256 balance, uint256 totalSupply) {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n totalSupply = lpToken.totalSupply();\n balance = lpToken.balanceOf(account);\n balance = balance.add(gauge.balanceOf(account));\n }\n}\n" }, "contracts/protocols/curve/common/OldCurveAllocationBase4.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\n\nimport {\n IOldStableSwap4,\n ILiquidityGauge\n} from \"contracts/protocols/curve/common/interfaces/Imports.sol\";\n\n/**\n * @title Periphery Contract for the Curve 3pool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\ncontract OldCurveAllocationBase4 {\n using SafeMath for uint256;\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @param stableSwap the liquidity pool comprised of multiple underlyers\n * @param gauge the staking contract for the LP tokens\n * @param lpToken the LP token representing the share of the pool\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n IOldStableSwap4 stableSwap,\n ILiquidityGauge gauge,\n IERC20 lpToken,\n int128 coin\n ) public view returns (uint256 balance) {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n uint256 poolBalance = getPoolBalance(stableSwap, coin);\n (uint256 lpTokenBalance, uint256 lpTokenSupply) =\n getLpTokenShare(account, stableSwap, gauge, lpToken);\n\n balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);\n }\n\n function getPoolBalance(IOldStableSwap4 stableSwap, int128 coin)\n public\n view\n returns (uint256)\n {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n return stableSwap.balances(coin);\n }\n\n function getLpTokenShare(\n address account,\n IOldStableSwap4 stableSwap,\n ILiquidityGauge gauge,\n IERC20 lpToken\n ) public view returns (uint256 balance, uint256 totalSupply) {\n require(address(stableSwap) != address(0), \"INVALID_STABLESWAP\");\n require(address(gauge) != address(0), \"INVALID_GAUGE\");\n require(address(lpToken) != address(0), \"INVALID_LP_TOKEN\");\n\n totalSupply = lpToken.totalSupply();\n balance = lpToken.balanceOf(account);\n balance = balance.add(gauge.balanceOf(account));\n }\n}\n" }, "contracts/protocols/curve/common/TestCurveZap.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IAssetAllocation} from \"contracts/common/Imports.sol\";\nimport {\n CurveGaugeZapBase\n} from \"contracts/protocols/curve/common/CurveGaugeZapBase.sol\";\n\ncontract TestCurveZap is CurveGaugeZapBase {\n string public constant override NAME = \"TestCurveZap\";\n\n address[] private _underlyers;\n\n constructor(\n address swapAddress,\n address lpTokenAddress,\n address liquidityGaugeAddress,\n uint256 denominator,\n uint256 slippage,\n uint256 numOfCoins\n )\n public\n CurveGaugeZapBase(\n swapAddress,\n lpTokenAddress,\n liquidityGaugeAddress,\n denominator,\n slippage,\n numOfCoins\n ) // solhint-disable-next-line no-empty-blocks\n {}\n\n function setUnderlyers(address[] calldata underlyers) external {\n _underlyers = underlyers;\n }\n\n function getSwapAddress() external view returns (address) {\n return SWAP_ADDRESS;\n }\n\n function getLpTokenAddress() external view returns (address) {\n return address(LP_ADDRESS);\n }\n\n function getGaugeAddress() external view returns (address) {\n return GAUGE_ADDRESS;\n }\n\n function getDenominator() external view returns (uint256) {\n return DENOMINATOR;\n }\n\n function getSlippage() external view returns (uint256) {\n return SLIPPAGE;\n }\n\n function getNumberOfCoins() external view returns (uint256) {\n return N_COINS;\n }\n\n function calcMinAmount(uint256 totalAmount, uint256 virtualPrice)\n external\n view\n returns (uint256)\n {\n return _calcMinAmount(totalAmount, virtualPrice);\n }\n\n function calcMinAmountUnderlyer(\n uint256 totalAmount,\n uint256 virtualPrice,\n uint8 decimals\n ) external view returns (uint256) {\n return _calcMinAmountUnderlyer(totalAmount, virtualPrice, decimals);\n }\n\n function assetAllocations() public view override returns (string[] memory) {\n string[] memory allocationNames = new string[](1);\n return allocationNames;\n }\n\n function erc20Allocations() public view override returns (IERC20[] memory) {\n IERC20[] memory allocations = new IERC20[](0);\n return allocations;\n }\n\n function _getVirtualPrice() internal view override returns (uint256) {\n return 1;\n }\n\n function _getCoinAtIndex(uint256 i)\n internal\n view\n override\n returns (address)\n {\n return _underlyers[i];\n }\n\n function _addLiquidity(uint256[] calldata amounts, uint256 minAmount)\n internal\n override\n // solhint-disable-next-line no-empty-blocks\n {\n\n }\n\n function _removeLiquidity(\n uint256 lpBalance,\n uint8 index,\n uint256 minAmount // solhint-disable-next-line no-empty-blocks\n ) internal override {}\n}\n" }, "contracts/protocols/convex/common/interfaces/IBaseRewardPool.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IRewardPool {\n /// @notice withdraw to a convex tokenized deposit\n function withdraw(uint256 _amount, bool _claim) external returns (bool);\n\n /// @notice claim rewards\n function getReward() external returns (bool);\n\n /// @notice stake a convex tokenized deposit\n function stake(uint256 _amount) external returns (bool);\n\n /// @notice Return how much rewards an address will receive if they claim their rewards now.\n function earned(address account) external view returns (uint256);\n\n /// @notice get balance of an address\n function balanceOf(address _account) external view returns (uint256);\n\n /// @notice get reward period end time\n /// @dev since this is based on the unipool contract, `notifyRewardAmount`\n /// must be called in order for a new period to begin.\n function periodFinish() external view returns (uint256);\n}\n\ninterface IBaseRewardPool is IRewardPool {\n /// @notice withdraw directly to curve LP token\n function withdrawAndUnwrap(uint256 _amount, bool _claim)\n external\n returns (bool);\n\n /// @notice Return the number of extra rewards.\n function extraRewardsLength() external view returns (uint256);\n\n /** @notice array of child reward contracts\n * You can query the number of extra rewards via baseRewardPool.extraRewardsLength().\n * This array holds a list of VirtualBalanceRewardPool contracts which are similar in\n * nature to the base reward contract but without actual control of staked tokens.\n *\n * This means that if a pool has CRV rewards as well as SNX rewards, the pool's main\n * reward contract (BaseRewardPool) will distribute the CRV and the child contract\n * (VirtualBalanceRewardPool) will distribute the SNX.\n */\n function extraRewards(uint256 index) external view returns (address);\n}\n" }, "contracts/protocols/convex/common/interfaces/IBooster.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\ninterface IBooster {\n struct PoolInfo {\n address lptoken;\n address token;\n address gauge;\n address crvRewards;\n address stash;\n bool shutdown;\n }\n\n /**\n * @notice deposit into convex, receive a tokenized deposit.\n * Parameter to stake immediately.\n */\n function deposit(\n uint256 _pid,\n uint256 _amount,\n bool _stake\n ) external returns (bool);\n\n /// @notice burn a tokenized deposit to receive curve lp tokens back\n function withdraw(uint256 _pid, uint256 _amount) external returns (bool);\n\n function poolInfo(uint256 index) external view returns (PoolInfo memory);\n}\n" }, "contracts/protocols/convex/common/Imports.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\n\nimport {ConvexZapBase} from \"./ConvexZapBase.sol\";\nimport {ConvexAllocationBase} from \"./ConvexAllocationBase.sol\";\nimport {OldConvexAllocationBase} from \"./OldConvexAllocationBase.sol\";\n" }, "contracts/protocols/convex/common/ConvexZapBase.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {IZap} from \"contracts/lpaccount/Imports.sol\";\nimport {\n IAssetAllocation,\n IERC20,\n IDetailedERC20\n} from \"contracts/common/Imports.sol\";\nimport {SafeERC20} from \"contracts/libraries/Imports.sol\";\nimport {\n IBooster,\n IBaseRewardPool\n} from \"contracts/protocols/convex/common/interfaces/Imports.sol\";\nimport {CurveZapBase} from \"contracts/protocols/curve/common/CurveZapBase.sol\";\n\nabstract contract ConvexZapBase is IZap, CurveZapBase {\n using SafeERC20 for IERC20;\n\n address internal constant CVX_ADDRESS =\n 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;\n\n address internal constant BOOSTER_ADDRESS =\n 0xF403C135812408BFbE8713b5A23a04b3D48AAE31;\n\n address internal immutable _LP_ADDRESS;\n uint256 internal immutable _PID;\n\n constructor(\n address swapAddress,\n address lpAddress,\n uint256 pid,\n uint256 denominator,\n uint256 slippage,\n uint256 nCoins\n ) public CurveZapBase(swapAddress, denominator, slippage, nCoins) {\n _LP_ADDRESS = lpAddress;\n _PID = pid;\n }\n\n function getLpTokenBalance(address account)\n external\n view\n override\n returns (uint256 lpBalance)\n {\n IBaseRewardPool rewardContract = _getRewardContract();\n // Convex's staking token is issued 1:1 for deposited LP tokens\n lpBalance = rewardContract.balanceOf(account);\n }\n\n /// @dev deposit LP tokens in Convex's Booster contract\n function _depositToGauge() internal override {\n IBooster booster = IBooster(BOOSTER_ADDRESS);\n uint256 lpBalance = IERC20(_LP_ADDRESS).balanceOf(address(this));\n IERC20(_LP_ADDRESS).safeApprove(BOOSTER_ADDRESS, 0);\n IERC20(_LP_ADDRESS).safeApprove(BOOSTER_ADDRESS, lpBalance);\n // deposit and mint staking tokens 1:1; bool is to stake\n booster.deposit(_PID, lpBalance, true);\n }\n\n function _withdrawFromGauge(uint256 amount)\n internal\n override\n returns (uint256 lpBalance)\n {\n IBaseRewardPool rewardContract = _getRewardContract();\n // withdraw staked tokens and unwrap to LP tokens;\n // bool is for claiming rewards at the same time\n rewardContract.withdrawAndUnwrap(amount, false);\n lpBalance = IERC20(_LP_ADDRESS).balanceOf(address(this));\n }\n\n function _claim() internal override {\n // this will claim CRV and extra rewards\n IBaseRewardPool rewardContract = _getRewardContract();\n rewardContract.getReward();\n }\n\n function _getRewardContract() internal view returns (IBaseRewardPool) {\n IBooster booster = IBooster(BOOSTER_ADDRESS);\n IBooster.PoolInfo memory poolInfo = booster.poolInfo(_PID);\n return IBaseRewardPool(poolInfo.crvRewards);\n }\n}\n" }, "contracts/protocols/convex/common/ConvexAllocationBase.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\nimport {IRewardPool} from \"./interfaces/IBaseRewardPool.sol\";\n\ninterface ICurvePool {\n function balances(uint256 coin) external view returns (uint256);\n}\n\n/**\n * @title Periphery Contract for the Curve 3pool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\ncontract ConvexAllocationBase {\n using SafeMath for uint256;\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @param stableSwap the liquidity pool comprised of multiple underlyers\n * @param rewardContract the staking contract for the LP tokens\n * @param lpToken the LP token representing the share of the pool\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n address stableSwap,\n address rewardContract,\n address lpToken,\n uint256 coin\n ) public view returns (uint256 balance) {\n require(stableSwap != address(0), \"INVALID_STABLESWAP\");\n require(rewardContract != address(0), \"INVALID_GAUGE\");\n require(lpToken != address(0), \"INVALID_LP_TOKEN\");\n\n uint256 poolBalance = getPoolBalance(stableSwap, coin);\n (uint256 lpTokenBalance, uint256 lpTokenSupply) =\n getLpTokenShare(account, rewardContract, lpToken);\n\n balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);\n }\n\n function getPoolBalance(address stableSwap, uint256 coin)\n public\n view\n returns (uint256)\n {\n require(stableSwap != address(0), \"INVALID_STABLESWAP\");\n return ICurvePool(stableSwap).balances(coin);\n }\n\n function getLpTokenShare(\n address account,\n address rewardContract,\n address lpToken\n ) public view returns (uint256 balance, uint256 totalSupply) {\n require(rewardContract != address(0), \"INVALID_GAUGE\");\n require(lpToken != address(0), \"INVALID_LP_TOKEN\");\n\n totalSupply = IERC20(lpToken).totalSupply();\n // Need to be careful to not include the balance of `account`,\n // since that is included in the Curve allocation.\n balance = IRewardPool(rewardContract).balanceOf(account);\n }\n}\n" }, "contracts/protocols/convex/common/OldConvexAllocationBase.sol": { "content": "// SPDX-License-Identifier: BUSDL-1.1\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport {SafeMath} from \"contracts/libraries/Imports.sol\";\nimport {IERC20} from \"contracts/common/Imports.sol\";\nimport {ImmutableAssetAllocation} from \"contracts/tvl/Imports.sol\";\nimport {IRewardPool} from \"./interfaces/IBaseRewardPool.sol\";\n\ninterface ICurvePool {\n function balances(int128 coin) external view returns (uint256);\n}\n\n/**\n * @title Periphery Contract for the Curve 3pool\n * @author APY.Finance\n * @notice This contract enables the APY.Finance system to retrieve the balance\n * of an underlyer of a Curve LP token. The balance is used as part\n * of the Chainlink computation of the deployed TVL. The primary\n * `getUnderlyerBalance` function is invoked indirectly when a\n * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.\n */\ncontract OldConvexAllocationBase {\n using SafeMath for uint256;\n\n /**\n * @notice Returns the balance of an underlying token represented by\n * an account's LP token balance.\n * @param stableSwap the liquidity pool comprised of multiple underlyers\n * @param rewardContract the staking contract for the LP tokens\n * @param lpToken the LP token representing the share of the pool\n * @param coin the index indicating which underlyer\n * @return balance\n */\n function getUnderlyerBalance(\n address account,\n address stableSwap,\n address rewardContract,\n address lpToken,\n uint256 coin\n ) public view returns (uint256 balance) {\n require(stableSwap != address(0), \"INVALID_STABLESWAP\");\n require(rewardContract != address(0), \"INVALID_GAUGE\");\n require(lpToken != address(0), \"INVALID_LP_TOKEN\");\n\n uint256 poolBalance = getPoolBalance(stableSwap, coin);\n (uint256 lpTokenBalance, uint256 lpTokenSupply) =\n getLpTokenShare(account, rewardContract, lpToken);\n\n balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);\n }\n\n function getPoolBalance(address stableSwap, uint256 coin)\n public\n view\n returns (uint256)\n {\n require(stableSwap != address(0), \"INVALID_STABLESWAP\");\n return ICurvePool(stableSwap).balances(int128(coin));\n }\n\n function getLpTokenShare(\n address account,\n address rewardContract,\n address lpToken\n ) public view returns (uint256 balance, uint256 totalSupply) {\n require(rewardContract != address(0), \"INVALID_GAUGE\");\n require(lpToken != address(0), \"INVALID_LP_TOKEN\");\n\n totalSupply = IERC20(lpToken).totalSupply();\n // Need to be careful to not include the balance of `account`,\n // since that is included in the Curve allocation.\n balance = IRewardPool(rewardContract).balanceOf(account);\n }\n}\n" } }, "settings": { "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} } }