File size: 69,091 Bytes
f998fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
{
  "language": "Solidity",
  "sources": {
    "contracts/deploy/Actions.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.6.12;\n\npragma experimental ABIEncoderV2;\nimport {RightsManager} from \"../libraries/RightsManager.sol\";\nimport {SmartPoolManager} from \"../libraries/SmartPoolManager.sol\";\n\nimport \"../libraries/SafeERC20.sol\";\n\nabstract contract DesynOwnable {\n    function setController(address controller) external virtual;\n    function setManagersInfo(address[] memory _owners, uint[] memory _ownerPercentage) external virtual;\n}\n\nabstract contract AbstractPool is IERC20, DesynOwnable {\n    function setSwapFee(uint swapFee) external virtual;\n\n    function setPublicSwap(bool public_) external virtual;\n\n    function joinPool(\n        uint poolAmountOut,\n        uint[] calldata maxAmountsIn,\n        address kol\n    ) external virtual;\n\n    function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external virtual;\n}\n\nabstract contract LiquidityPoolActions is AbstractPool {\n    function finalize() external virtual;\n\n    function bind(\n        address token,\n        uint balance,\n        uint denorm\n    ) external virtual;\n\n    function rebind(\n        address token,\n        uint balance,\n        uint denorm\n    ) external virtual;\n\n    function unbind(address token) external virtual;\n\n    function isBound(address t) external view virtual returns (bool);\n\n    function getCurrentTokens() external view virtual returns (address[] memory);\n\n    function getFinalTokens() external view virtual returns (address[] memory);\n\n    function getBalance(address token) external view virtual returns (uint);\n}\n\nabstract contract FactoryActions {\n    function newLiquidityPool() external virtual returns (LiquidityPoolActions);\n}\n\nabstract contract IConfigurableRightsPool is AbstractPool {\n    enum Etypes {\n        OPENED,\n        CLOSED\n    }\n    enum Period {\n        HALF,\n        ONE,\n        TWO\n    }\n\n    struct PoolTokenRange {\n        uint bspFloor;\n        uint bspCap;\n    }\n\n    struct PoolParams {\n        string poolTokenSymbol;\n        string poolTokenName;\n        address[] constituentTokens;\n        uint[] tokenBalances;\n        uint[] tokenWeights;\n        uint swapFee;\n        uint managerFee;\n        uint redeemFee;\n        uint issueFee;\n        uint perfermanceFee;\n        Etypes etype;\n    }\n\n    struct CrpParams {\n        uint initialSupply;\n        uint collectPeriod;\n        Period period;\n    }\n\n    function createPool(\n        uint initialSupply,\n        uint collectPeriod,\n        Period period,\n        PoolTokenRange memory tokenRange\n    ) external virtual;\n\n    function createPool(uint initialSupply) external virtual;\n\n    function setCap(uint newCap) external virtual;\n\n    function rebalance(\n        address tokenA,\n        address tokenB,\n        uint deltaWeight,\n        uint minAmountOut\n    ) external virtual;\n\n    function commitAddToken(\n        address token,\n        uint balance,\n        uint denormalizedWeight\n    ) external virtual;\n\n    function applyAddToken() external virtual;\n\n    function whitelistLiquidityProvider(address provider) external virtual;\n\n    function removeWhitelistedLiquidityProvider(address provider) external virtual;\n\n    function bPool() external view virtual returns (LiquidityPoolActions);\n\n    function addTokenToWhitelist(uint[] memory sort, address[] memory token) external virtual;\n    function claimManagerFee() external virtual;\n\n    function etype() external virtual returns(SmartPoolManager.Etypes);\n\n    function vaultAddress() external virtual view returns(address);\n}\n\nabstract contract ICRPFactory {\n    function newCrp(\n        address factoryAddress,\n        IConfigurableRightsPool.PoolParams calldata params,\n        RightsManager.Rights calldata rights,\n        SmartPoolManager.KolPoolParams calldata kolPoolParams,\n        address[] memory owners,\n        uint[] memory ownerPercentage\n    ) external virtual returns (IConfigurableRightsPool);\n}\n\nabstract contract IVault {\n    function userVault() external virtual returns(address);\n}\n\nabstract contract IUserVault {\n    function kolClaim(address pool) external virtual;\n\n    function managerClaim(address pool) external virtual;\n\n    function getManagerClaimBool(address pool) external view virtual returns(bool);\n}\n\n/********************************** WARNING **********************************/\n//                                                                           //\n// This contract is only meant to be used in conjunction with ds-proxy.      //\n// Calling this contract directly will lead to loss of funds.                //\n//                                                                           //\n/********************************** WARNING **********************************/\n\ncontract Actions {\n    using SafeERC20 for IERC20;\n    // --- Pool Creation ---\n\n    function create(\n        FactoryActions factory,\n        address[] calldata tokens,\n        uint[] calldata balances,\n        uint[] calldata weights,\n        uint swapFee,\n        bool finalize\n    ) external returns (LiquidityPoolActions pool) {\n        require(tokens.length == balances.length, \"ERR_LENGTH_MISMATCH\");\n        require(tokens.length == weights.length, \"ERR_LENGTH_MISMATCH\");\n\n        pool = factory.newLiquidityPool();\n        pool.setSwapFee(swapFee);\n\n        for (uint i = 0; i < tokens.length; i++) {\n            IERC20 token = IERC20(tokens[i]);\n            token.safeTransferFrom(msg.sender, address(this), balances[i]);\n            _safeApprove(token, address(pool), balances[i]);\n            pool.bind(tokens[i], balances[i], weights[i]);\n        }\n\n        if (finalize) {\n            pool.finalize();\n            require(pool.transfer(msg.sender, pool.balanceOf(address(this))), \"ERR_TRANSFER_FAILED\");\n        } else {\n            pool.setPublicSwap(true);\n        }\n    }\n\n    function createSmartPool(\n        ICRPFactory factory,\n        FactoryActions coreFactory,\n        IConfigurableRightsPool.PoolParams calldata poolParams,\n        IConfigurableRightsPool.CrpParams calldata crpParams,\n        RightsManager.Rights calldata rights,\n        SmartPoolManager.KolPoolParams calldata kolPoolParams,\n        address[] memory owners,\n        uint[] memory ownerPercentage,\n        IConfigurableRightsPool.PoolTokenRange memory tokenRange\n    ) external returns (IConfigurableRightsPool crp) {\n        require(poolParams.constituentTokens.length == poolParams.tokenBalances.length, \"ERR_LENGTH_MISMATCH\");\n        require(poolParams.constituentTokens.length == poolParams.tokenWeights.length, \"ERR_LENGTH_MISMATCH\");\n\n        crp = factory.newCrp(address(coreFactory), poolParams, rights, kolPoolParams, owners, ownerPercentage);\n        for (uint i = 0; i < poolParams.constituentTokens.length; i++) {\n            IERC20 token = IERC20(poolParams.constituentTokens[i]);\n            token.safeTransferFrom(msg.sender, address(this), poolParams.tokenBalances[i]);\n            _safeApprove(token, address(crp), poolParams.tokenBalances[i]);\n        }\n\n        crp.createPool(crpParams.initialSupply, crpParams.collectPeriod, crpParams.period, tokenRange);\n        require(crp.transfer(msg.sender, crpParams.initialSupply), \"ERR_TRANSFER_FAILED\");\n        // DSProxy instance keeps pool ownership to enable management\n    }\n\n    // --- Joins ---\n\n    function joinPool(\n        LiquidityPoolActions pool,\n        uint poolAmountOut,\n        uint[] calldata maxAmountsIn\n    ) external {\n        address[] memory tokens = pool.getFinalTokens();\n        _join(pool, tokens, poolAmountOut, maxAmountsIn, msg.sender);\n    }\n\n    function joinSmartPool(\n        IConfigurableRightsPool pool,\n        uint poolAmountOut,\n        uint[] calldata maxAmountsIn,\n        address kol\n    ) external {\n        address[] memory tokens = pool.bPool().getCurrentTokens();\n        _join(pool, tokens, poolAmountOut, maxAmountsIn, kol);\n    }\n\n    function exitPool(\n        IConfigurableRightsPool pool,\n        uint poolAmountIn,\n        uint[] memory minAmountsOut\n    ) external {\n        address[] memory tokens = pool.bPool().getCurrentTokens();\n        _exit(pool, poolAmountIn, minAmountsOut, tokens);\n    }\n\n    // --- Pool management (common) ---\n\n    function setPublicSwap(AbstractPool pool, bool publicSwap) external {\n        pool.setPublicSwap(publicSwap);\n    }\n\n    function setSwapFee(AbstractPool pool, uint newFee) external {\n        pool.setSwapFee(newFee);\n    }\n\n    function setController(AbstractPool pool, address newController) external {\n        _beforeOwnerChange(address(pool));\n        pool.setController(newController);\n    }\n\n    function setManagersInfo(AbstractPool pool ,address[] memory _owners, uint[] memory _ownerPercentage) public {\n        _beforeOwnerChange(address(pool));\n        pool.setManagersInfo(_owners, _ownerPercentage);\n    }\n\n    function _beforeOwnerChange(address pool) internal {\n        claimManagementFee(IConfigurableRightsPool(pool));\n        _claimManagersReward(pool);\n    }\n\n    // --- Private pool management ---\n\n    function setTokens(\n        LiquidityPoolActions pool,\n        address[] calldata tokens,\n        uint[] calldata balances,\n        uint[] calldata denorms\n    ) external {\n        require(tokens.length == balances.length, \"ERR_LENGTH_MISMATCH\");\n        require(tokens.length == denorms.length, \"ERR_LENGTH_MISMATCH\");\n\n        for (uint i = 0; i < tokens.length; i++) {\n            IERC20 token = IERC20(tokens[i]);\n            if (pool.isBound(tokens[i])) {\n                if (balances[i] > pool.getBalance(tokens[i])) {\n                    token.safeTransferFrom(msg.sender, address(this), balances[i] - pool.getBalance(tokens[i]));\n                    _safeApprove(token, address(pool), balances[i] - pool.getBalance(tokens[i]));\n                }\n                if (balances[i] > 10**6) {\n                    pool.rebind(tokens[i], balances[i], denorms[i]);\n                } else {\n                    pool.unbind(tokens[i]);\n                }\n            } else {\n                token.safeTransferFrom(msg.sender, address(this), balances[i]);\n                _safeApprove(token, address(pool), balances[i]);\n                pool.bind(tokens[i], balances[i], denorms[i]);\n            }\n\n            if (token.balanceOf(address(this)) > 0) {\n                token.safeTransfer(msg.sender, token.balanceOf(address(this)));\n            }\n        }\n    }\n\n    function finalize(LiquidityPoolActions pool) external {\n        pool.finalize();\n        require(pool.transfer(msg.sender, pool.balanceOf(address(this))), \"ERR_TRANSFER_FAILED\");\n    }\n\n    // --- Smart pool management ---\n\n    function rebalance(\n        IConfigurableRightsPool crp,\n        address tokenA,\n        address tokenB,\n        uint deltaWeight,\n        uint minAmountOut\n    ) external {\n        crp.rebalance(tokenA, tokenB, deltaWeight, minAmountOut);\n    }\n\n    function setCap(IConfigurableRightsPool crp, uint newCap) external {\n        crp.setCap(newCap);\n    }\n\n    function whitelistLiquidityProvider(IConfigurableRightsPool crp, address provider) external {\n        crp.whitelistLiquidityProvider(provider);\n    }\n\n    function removeWhitelistedLiquidityProvider(IConfigurableRightsPool crp, address provider) external {\n        crp.removeWhitelistedLiquidityProvider(provider);\n    }\n\n    function addTokenToWhitelist(IConfigurableRightsPool crp, uint[] memory sort, address[] memory token) public {\n        crp.addTokenToWhitelist(sort, token);\n    }\n\n    function claimManagementFee(IConfigurableRightsPool crp) public {\n         crp.claimManagerFee();\n    }\n    // --- Internals ---\n\n    function _safeApprove(\n        IERC20 token,\n        address spender,\n        uint amount\n    ) internal {\n        if (token.allowance(address(this), spender) > 0) {\n            token.approve(spender, 0);\n        }\n        token.approve(spender, amount);\n    }\n\n    function _join(\n        AbstractPool pool,\n        address[] memory tokens,\n        uint poolAmountOut,\n        uint[] memory maxAmountsIn,\n        address kol\n    ) internal {\n        require(maxAmountsIn.length == tokens.length, \"ERR_LENGTH_MISMATCH\");\n\n        for (uint i = 0; i < tokens.length; i++) {\n            IERC20 token = IERC20(tokens[i]);\n            token.safeTransferFrom(msg.sender, address(this), maxAmountsIn[i]);\n            _safeApprove(token, address(pool), maxAmountsIn[i]);\n        }\n        pool.joinPool(poolAmountOut, maxAmountsIn, kol);\n        for (uint i = 0; i < tokens.length; i++) {\n            IERC20 token = IERC20(tokens[i]);\n            if (token.balanceOf(address(this)) > 0) {\n                token.safeTransfer(msg.sender, token.balanceOf(address(this)));\n            }\n        }\n        require(pool.transfer(msg.sender, pool.balanceOf(address(this))), \"ERR_TRANSFER_FAILED\");\n    }\n\n    function _exit(\n        AbstractPool pool,\n        uint poolAmountIn,\n        uint[] memory minAmountsOut,\n        address[] memory tokens\n    ) internal {\n        uint bal = pool.balanceOf(msg.sender);\n        require(pool.transferFrom(msg.sender, address(this), bal), \"ERR_TRANSFER_FAILED\");\n        _safeApprove(pool, address(pool), bal);\n\n        pool.exitPool(poolAmountIn, minAmountsOut);\n\n        for (uint i = 0; i < tokens.length; i++) {\n            IERC20 token = IERC20(tokens[i]);\n            if (token.balanceOf(address(this)) > 0) {\n                token.safeTransfer(msg.sender, token.balanceOf(address(this)));\n            }\n        }\n\n        require(pool.transfer(msg.sender, pool.balanceOf(address(this))), \"ERR_TRANSFER_FAILED\");\n    }\n\n    function claimKolReward(address pool) public {\n        address uservault = _getUserVault(pool);\n        IUserVault(uservault).kolClaim(pool);\n    }\n\n    function claimManagersReward(address vault_,address pool) external {\n        IUserVault(vault_).managerClaim(pool);\n    }\n\n    function _claimManagersReward(address pool) internal {\n        address vault = _getVault(pool);\n        address uservault = _getUserVault(pool);\n\n        bool vaultCanClaim = IUserVault(vault).getManagerClaimBool(pool);\n        bool uservaultCanClaim = IUserVault(uservault).getManagerClaimBool(pool);\n        SmartPoolManager.Etypes type_ = IConfigurableRightsPool(pool).etype();\n\n        if(type_ == SmartPoolManager.Etypes.OPENED && vaultCanClaim) IUserVault(vault).managerClaim(pool);\n        if(type_ == SmartPoolManager.Etypes.CLOSED && uservaultCanClaim) IUserVault(uservault).managerClaim(pool);\n    }\n\n    function _getVault(address pool) internal view  returns(address){\n        return IConfigurableRightsPool(pool).vaultAddress();\n    }\n    function _getUserVault(address pool) internal  returns(address){\n        address vault = _getVault(pool);\n        return IVault(vault).userVault();\n    }\n}\n"
    },
    "contracts/libraries/RightsManager.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.6.12;\n\n// Needed to handle structures externally\npragma experimental ABIEncoderV2;\n\n/**\n * @author Desyn Labs\n * @title Manage Configurable Rights for the smart pool\n *      canPauseSwapping - can setPublicSwap back to false after turning it on\n *                         by default, it is off on initialization and can only be turned on\n *      canChangeSwapFee - can setSwapFee after initialization (by default, it is fixed at create time)\n *      canChangeWeights - can bind new token weights (allowed by default in base pool)\n *      canAddRemoveTokens - can bind/unbind tokens (allowed by default in base pool)\n *      canWhitelistLPs - can limit liquidity providers to a given set of addresses\n *      canChangeCap - can change the BSP cap (max # of pool tokens)\n *      canChangeFloor - can change the BSP floor for Closure ETF (min # of pool tokens)\n */\nlibrary RightsManager {\n    // Type declarations\n\n    enum Permissions {\n        PAUSE_SWAPPING,\n        CHANGE_SWAP_FEE,\n        CHANGE_WEIGHTS,\n        ADD_REMOVE_TOKENS,\n        WHITELIST_LPS,\n        TOKEN_WHITELISTS\n        // CHANGE_CAP,\n        // CHANGE_FLOOR\n    }\n\n    struct Rights {\n        bool canPauseSwapping;\n        bool canChangeSwapFee;\n        bool canChangeWeights;\n        bool canAddRemoveTokens;\n        bool canWhitelistLPs;\n        bool canTokenWhiteLists;\n        // bool canChangeCap;\n        // bool canChangeFloor;\n    }\n\n    // State variables (can only be constants in a library)\n    bool public constant DEFAULT_CAN_PAUSE_SWAPPING = false;\n    bool public constant DEFAULT_CAN_CHANGE_SWAP_FEE = true;\n    bool public constant DEFAULT_CAN_CHANGE_WEIGHTS = true;\n    bool public constant DEFAULT_CAN_ADD_REMOVE_TOKENS = false;\n    bool public constant DEFAULT_CAN_WHITELIST_LPS = false;\n    bool public constant DEFAULT_CAN_TOKEN_WHITELISTS = false;\n\n    // bool public constant DEFAULT_CAN_CHANGE_CAP = false;\n    // bool public constant DEFAULT_CAN_CHANGE_FLOOR = false;\n\n    // Functions\n\n    /**\n     * @notice create a struct from an array (or return defaults)\n     * @dev If you pass an empty array, it will construct it using the defaults\n     * @param a - array input\n     * @return Rights struct\n     */\n    function constructRights(bool[] calldata a) external pure returns (Rights memory) {\n        if (a.length < 6) {\n            return\n                Rights(\n                    DEFAULT_CAN_PAUSE_SWAPPING,\n                    DEFAULT_CAN_CHANGE_SWAP_FEE,\n                    DEFAULT_CAN_CHANGE_WEIGHTS,\n                    DEFAULT_CAN_ADD_REMOVE_TOKENS,\n                    DEFAULT_CAN_WHITELIST_LPS,\n                    DEFAULT_CAN_TOKEN_WHITELISTS\n                    // DEFAULT_CAN_CHANGE_CAP,\n                    // DEFAULT_CAN_CHANGE_FLOOR\n                );\n        } else {\n            // return Rights(a[0], a[1], a[2], a[3], a[4], a[5], a[6]);\n            return Rights(a[0], a[1], a[2], a[3], a[4], a[5]);\n        }\n    }\n\n    /**\n     * @notice Convert rights struct to an array (e.g., for events, GUI)\n     * @dev avoids multiple calls to hasPermission\n     * @param rights - the rights struct to convert\n     * @return boolean array containing the rights settings\n     */\n    function convertRights(Rights calldata rights) external pure returns (bool[] memory) {\n        bool[] memory result = new bool[](6);\n\n        result[0] = rights.canPauseSwapping;\n        result[1] = rights.canChangeSwapFee;\n        result[2] = rights.canChangeWeights;\n        result[3] = rights.canAddRemoveTokens;\n        result[4] = rights.canWhitelistLPs;\n        result[5] = rights.canTokenWhiteLists;\n        // result[5] = rights.canChangeCap;\n        // result[6] = rights.canChangeFloor;\n\n        return result;\n    }\n\n    // Though it is actually simple, the number of branches triggers code-complexity\n    /* solhint-disable code-complexity */\n\n    /**\n     * @notice Externally check permissions using the Enum\n     * @param self - Rights struct containing the permissions\n     * @param permission - The permission to check\n     * @return Boolean true if it has the permission\n     */\n    function hasPermission(Rights calldata self, Permissions permission) external pure returns (bool) {\n        if (Permissions.PAUSE_SWAPPING == permission) {\n            return self.canPauseSwapping;\n        } else if (Permissions.CHANGE_SWAP_FEE == permission) {\n            return self.canChangeSwapFee;\n        } else if (Permissions.CHANGE_WEIGHTS == permission) {\n            return self.canChangeWeights;\n        } else if (Permissions.ADD_REMOVE_TOKENS == permission) {\n            return self.canAddRemoveTokens;\n        } else if (Permissions.WHITELIST_LPS == permission) {\n            return self.canWhitelistLPs;\n        } else if (Permissions.TOKEN_WHITELISTS == permission) {\n            return self.canTokenWhiteLists;\n        }\n        // else if (Permissions.CHANGE_CAP == permission) {\n        //     return self.canChangeCap;\n        // } else if (Permissions.CHANGE_FLOOR == permission) {\n        //     return self.canChangeFloor;\n        // }\n    }\n\n    /* solhint-enable code-complexity */\n}\n"
    },
    "contracts/libraries/SmartPoolManager.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.6.12;\n\n// Needed to pass in structs\npragma experimental ABIEncoderV2;\n\n// Imports\n\nimport \"../interfaces/IERC20.sol\";\nimport \"../interfaces/IConfigurableRightsPool.sol\";\nimport \"../interfaces/IBFactory.sol\"; // unused\nimport \"./DesynSafeMath.sol\";\nimport \"./SafeMath.sol\";\n// import \"./SafeApprove.sol\";\nimport \"../libraries/SafeERC20.sol\";\n\n/**\n * @author Desyn Labs\n * @title Factor out the weight updates\n */\nlibrary SmartPoolManager {\n    // using SafeApprove for IERC20;\n    using DesynSafeMath for uint;\n    using SafeMath for uint;\n    using SafeERC20 for IERC20;\n\n    //kol pool params\n    struct levelParams {\n        uint level;\n        uint ratio;\n    }\n\n    struct feeParams {\n        levelParams firstLevel;\n        levelParams secondLevel;\n        levelParams thirdLevel;\n        levelParams fourLevel;\n    }\n    \n    struct KolPoolParams {\n        feeParams managerFee;\n        feeParams issueFee;\n        feeParams redeemFee;\n        feeParams perfermanceFee;\n    }\n\n    // Type declarations\n    enum Etypes {\n        OPENED,\n        CLOSED\n    }\n\n    enum Period {\n        HALF,\n        ONE,\n        TWO\n    }\n\n    // updateWeight and pokeWeights are unavoidably long\n    /* solhint-disable function-max-lines */\n    struct Status {\n        uint collectPeriod;\n        uint collectEndTime;\n        uint closurePeriod;\n        uint closureEndTime;\n        uint upperCap;\n        uint floorCap;\n        uint managerFee;\n        uint redeemFee;\n        uint issueFee;\n        uint perfermanceFee;\n        uint startClaimFeeTime;\n    }\n\n    struct PoolParams {\n        // Desyn Pool Token (representing shares of the pool)\n        string poolTokenSymbol;\n        string poolTokenName;\n        // Tokens inside the Pool\n        address[] constituentTokens;\n        uint[] tokenBalances;\n        uint[] tokenWeights;\n        uint swapFee;\n        uint managerFee;\n        uint redeemFee;\n        uint issueFee;\n        uint perfermanceFee;\n        Etypes etype;\n    }\n\n    struct PoolTokenRange {\n        uint bspFloor;\n        uint bspCap;\n    }\n\n    struct Fund {\n        uint etfAmount;\n        uint fundAmount;\n    }\n\n    function initRequire(\n        uint swapFee,\n        uint managerFee,\n        uint issueFee,\n        uint redeemFee,\n        uint perfermanceFee,\n        uint tokenBalancesLength,\n        uint tokenWeightsLength,\n        uint constituentTokensLength,\n        bool initBool\n    ) external pure {\n        // We don't have a pool yet; check now or it will fail later (in order of likelihood to fail)\n        // (and be unrecoverable if they don't have permission set to change it)\n        // Most likely to fail, so check first\n        require(!initBool, \"Init fail\");\n        require(swapFee >= DesynConstants.MIN_FEE, \"ERR_INVALID_SWAP_FEE\");\n        require(swapFee <= DesynConstants.MAX_FEE, \"ERR_INVALID_SWAP_FEE\");\n        require(managerFee >= DesynConstants.MANAGER_MIN_FEE, \"ERR_INVALID_MANAGER_FEE\");\n        require(managerFee <= DesynConstants.MANAGER_MAX_FEE, \"ERR_INVALID_MANAGER_FEE\");\n        require(issueFee >= DesynConstants.ISSUE_MIN_FEE, \"ERR_INVALID_ISSUE_MIN_FEE\");\n        require(issueFee <= DesynConstants.ISSUE_MAX_FEE, \"ERR_INVALID_ISSUE_MAX_FEE\");\n        require(redeemFee >= DesynConstants.REDEEM_MIN_FEE, \"ERR_INVALID_REDEEM_MIN_FEE\");\n        require(redeemFee <= DesynConstants.REDEEM_MAX_FEE, \"ERR_INVALID_REDEEM_MAX_FEE\");\n        require(perfermanceFee >= DesynConstants.PERFERMANCE_MIN_FEE, \"ERR_INVALID_PERFERMANCE_MIN_FEE\");\n        require(perfermanceFee <= DesynConstants.PERFERMANCE_MAX_FEE, \"ERR_INVALID_PERFERMANCE_MAX_FEE\");\n\n        // Arrays must be parallel\n        require(tokenBalancesLength == constituentTokensLength, \"ERR_START_BALANCES_MISMATCH\");\n        require(tokenWeightsLength == constituentTokensLength, \"ERR_START_WEIGHTS_MISMATCH\");\n        // Cannot have too many or too few - technically redundant, since BPool.bind() would fail later\n        // But if we don't check now, we could have a useless contract with no way to create a pool\n\n        require(constituentTokensLength >= DesynConstants.MIN_ASSET_LIMIT, \"ERR_TOO_FEW_TOKENS\");\n        require(constituentTokensLength <= DesynConstants.MAX_ASSET_LIMIT, \"ERR_TOO_MANY_TOKENS\");\n        // There are further possible checks (e.g., if they use the same token twice), but\n        // we can let bind() catch things like that (i.e., not things that might reasonably work)\n    }\n\n    /**\n     * @notice Update the weight of an existing token\n     * @dev Refactored to library to make CRPFactory deployable\n     * @param self - ConfigurableRightsPool instance calling the library\n     * @param bPool - Core BPool the CRP is wrapping\n     * @param tokenA - token to sell\n     * @param tokenB - token to buy\n     */\n    function rebalance(\n        IConfigurableRightsPool self,\n        IBPool bPool,\n        address tokenA,\n        address tokenB,\n        uint deltaWeight,\n        uint minAmountOut\n    ) external {\n        uint currentWeightA = bPool.getDenormalizedWeight(tokenA);\n        uint currentBalanceA = bPool.getBalance(tokenA);\n        // uint currentWeightB = bPool.getDenormalizedWeight(tokenB);\n\n        require(deltaWeight <= currentWeightA, \"ERR_DELTA_WEIGHT_TOO_BIG\");\n\n        // deltaBalance = currentBalance * (deltaWeight / currentWeight)\n        uint deltaBalanceA = DesynSafeMath.bmul(currentBalanceA, DesynSafeMath.bdiv(deltaWeight, currentWeightA));\n\n        // uint currentBalanceB = bPool.getBalance(tokenB);\n\n        // uint deltaWeight = DesynSafeMath.bsub(newWeight, currentWeightA);\n\n        // uint newWeightB = DesynSafeMath.bsub(currentWeightB, deltaWeight);\n        // require(newWeightB >= 0, \"ERR_INCORRECT_WEIGHT_B\");\n        bool soldout;\n        if (deltaWeight == currentWeightA) {\n            // reduct token A\n            bPool.unbindPure(tokenA);\n            soldout = true;\n        }\n\n        // Now with the tokens this contract can bind them to the pool it controls\n        bPool.rebindSmart(tokenA, tokenB, deltaWeight, deltaBalanceA, soldout, minAmountOut);\n    }\n\n    /**\n     * @notice Non ERC20-conforming tokens are problematic; don't allow them in pools\n     * @dev Will revert if invalid\n     * @param token - The prospective token to verify\n     */\n    function verifyTokenCompliance(address token) external {\n        verifyTokenComplianceInternal(token);\n    }\n\n    /**\n     * @notice Non ERC20-conforming tokens are problematic; don't allow them in pools\n     * @dev Will revert if invalid - overloaded to save space in the main contract\n     * @param tokens - The prospective tokens to verify\n     */\n    function verifyTokenCompliance(address[] calldata tokens) external {\n        for (uint i = 0; i < tokens.length; i++) {\n            verifyTokenComplianceInternal(tokens[i]);\n        }\n    }\n\n    function createPoolInternalHandle(IBPool bPool, uint initialSupply) external view {\n        require(initialSupply >= DesynConstants.MIN_POOL_SUPPLY, \"ERR_INIT_SUPPLY_MIN\");\n        require(initialSupply <= DesynConstants.MAX_POOL_SUPPLY, \"ERR_INIT_SUPPLY_MAX\");\n        require(bPool.EXIT_FEE() == 0, \"ERR_NONZERO_EXIT_FEE\");\n        // EXIT_FEE must always be zero, or ConfigurableRightsPool._pushUnderlying will fail\n        require(DesynConstants.EXIT_FEE == 0, \"ERR_NONZERO_EXIT_FEE\");\n    }\n\n    function createPoolHandle(\n        uint collectPeriod,\n        uint upperCap,\n        uint initialSupply\n    ) external pure {\n        require(collectPeriod <= DesynConstants.MAX_COLLECT_PERIOD, \"ERR_EXCEEDS_FUND_RAISING_PERIOD\");\n        require(upperCap >= initialSupply, \"ERR_CAP_BIGGER_THAN_INITSUPPLY\");\n    }\n\n    function exitPoolHandle(\n        uint _endEtfAmount,\n        uint _endFundAmount,\n        uint _beginEtfAmount,\n        uint _beginFundAmount,\n        uint poolAmountIn,\n        uint totalEnd\n    )\n        external\n        pure\n        returns (\n            uint endEtfAmount,\n            uint endFundAmount,\n            uint profitRate\n        )\n    {\n        endEtfAmount = DesynSafeMath.badd(_endEtfAmount, poolAmountIn);\n        endFundAmount = DesynSafeMath.badd(_endFundAmount, totalEnd);\n        uint amount1 = DesynSafeMath.bdiv(endFundAmount, endEtfAmount);\n        uint amount2 = DesynSafeMath.bdiv(_beginFundAmount, _beginEtfAmount);\n        if (amount1 > amount2) {\n            profitRate = DesynSafeMath.bdiv(\n                DesynSafeMath.bmul(DesynSafeMath.bsub(DesynSafeMath.bdiv(endFundAmount, endEtfAmount), DesynSafeMath.bdiv(_beginFundAmount, _beginEtfAmount)), poolAmountIn),\n                totalEnd\n            );\n        }\n    }\n\n    function exitPoolHandleA(\n        IConfigurableRightsPool self,\n        IBPool bPool,\n        address poolToken,\n        uint _tokenAmountOut,\n        uint redeemFee,\n        uint profitRate,\n        uint perfermanceFee\n    )\n        external\n        returns (\n            uint redeemAndPerformanceFeeReceived,\n            uint finalAmountOut,\n            uint redeemFeeReceived\n        )\n    {\n        // redeem fee\n        redeemFeeReceived = DesynSafeMath.bmul(_tokenAmountOut, redeemFee);\n\n        // performance fee\n        uint performanceFeeReceived = DesynSafeMath.bmul(DesynSafeMath.bmul(_tokenAmountOut, profitRate), perfermanceFee);\n        \n        // redeem fee and performance fee\n        redeemAndPerformanceFeeReceived = DesynSafeMath.badd(performanceFeeReceived, redeemFeeReceived);\n\n        // final amount the user got\n        finalAmountOut = DesynSafeMath.bsub(_tokenAmountOut, redeemAndPerformanceFeeReceived);\n\n        _pushUnderlying(bPool, poolToken, msg.sender, finalAmountOut);\n\n        if (redeemFee != 0 || (profitRate > 0 && perfermanceFee != 0)) {\n            _pushUnderlying(bPool, poolToken, address(this), redeemAndPerformanceFeeReceived);\n            IERC20(poolToken).safeApprove(self.vaultAddress(), 0);\n            IERC20(poolToken).safeApprove(self.vaultAddress(), redeemAndPerformanceFeeReceived);\n        }\n    }\n\n    function exitPoolHandleB(\n        IConfigurableRightsPool self,\n        bool bools,\n        bool isCompletedCollect,\n        uint closureEndTime,\n        uint collectEndTime,\n        uint _etfAmount,\n        uint _fundAmount,\n        uint poolAmountIn\n    ) external view returns (uint etfAmount, uint fundAmount, uint actualPoolAmountIn) {\n        actualPoolAmountIn = poolAmountIn;\n        if (bools) {\n            bool isCloseEtfCollectEndWithFailure = isCompletedCollect == false && block.timestamp >= collectEndTime;\n            bool isCloseEtfClosureEnd = block.timestamp >= closureEndTime;\n            require(isCloseEtfCollectEndWithFailure || isCloseEtfClosureEnd, \"ERR_CLOSURE_TIME_NOT_ARRIVED!\");\n\n            actualPoolAmountIn = self.balanceOf(msg.sender);\n        }\n        fundAmount = _fundAmount;\n        etfAmount = _etfAmount;\n    }\n\n    function joinPoolHandle(\n        bool canWhitelistLPs,\n        bool isList,\n        bool bools,\n        uint collectEndTime\n    ) external view {\n        require(!canWhitelistLPs || isList, \"ERR_NOT_ON_WHITELIST\");\n\n        if (bools) {\n            require(block.timestamp <= collectEndTime, \"ERR_COLLECT_PERIOD_FINISHED!\");\n        }\n    }\n\n    function rebalanceHandle(\n        IBPool bPool,\n        bool isCompletedCollect,\n        bool bools,\n        uint collectEndTime,\n        uint closureEndTime,\n        bool canChangeWeights,\n        address tokenA,\n        address tokenB\n    ) external {\n        require(bPool.isBound(tokenA), \"ERR_TOKEN_NOT_BOUND\");\n        if (bools) {\n            require(isCompletedCollect, \"ERROR_COLLECTION_FAILED\");\n            require(block.timestamp > collectEndTime && block.timestamp < closureEndTime, \"ERR_NOT_REBALANCE_PERIOD\");\n        }\n\n        if (!bPool.isBound(tokenB)) {\n            IERC20(tokenB).safeApprove(address(bPool), 0);\n            IERC20(tokenB).safeApprove(address(bPool), DesynConstants.MAX_UINT);\n        }\n\n        require(canChangeWeights, \"ERR_NOT_CONFIGURABLE_WEIGHTS\");\n        require(tokenA != tokenB, \"ERR_TOKENS_SAME\");\n    }\n\n    /**\n     * @notice Join a pool\n     * @param self - ConfigurableRightsPool instance calling the library\n     * @param bPool - Core BPool the CRP is wrapping\n     * @param poolAmountOut - number of pool tokens to receive\n     * @param maxAmountsIn - Max amount of asset tokens to spend\n     * @return actualAmountsIn - calculated values of the tokens to pull in\n     */\n    function joinPool(\n        IConfigurableRightsPool self,\n        IBPool bPool,\n        uint poolAmountOut,\n        uint[] calldata maxAmountsIn,\n        uint issueFee\n    ) external view returns (uint[] memory actualAmountsIn) {\n        address[] memory tokens = bPool.getCurrentTokens();\n\n        require(maxAmountsIn.length == tokens.length, \"ERR_AMOUNTS_MISMATCH\");\n\n        uint poolTotal = self.totalSupply();\n        // Subtract  1 to ensure any rounding errors favor the pool\n        uint ratio = DesynSafeMath.bdiv(poolAmountOut, DesynSafeMath.bsub(poolTotal, 1));\n\n        require(ratio != 0, \"ERR_MATH_APPROX\");\n\n        // We know the length of the array; initialize it, and fill it below\n        // Cannot do \"push\" in memory\n        actualAmountsIn = new uint[](tokens.length);\n\n        // This loop contains external calls\n        // External calls are to math libraries or the underlying pool, so low risk\n        uint issueFeeRate = issueFee.bmul(1000);\n        for (uint i = 0; i < tokens.length; i++) {\n            address t = tokens[i];\n            uint bal = bPool.getBalance(t);\n            // Add 1 to ensure any rounding errors favor the pool\n            uint base = bal.badd(1).bmul(poolAmountOut * uint(1000));\n            uint tokenAmountIn = base.bdiv(poolTotal.bsub(1) * (uint(1000).bsub(issueFeeRate)));\n\n            require(tokenAmountIn != 0, \"ERR_MATH_APPROX\");\n            require(tokenAmountIn <= maxAmountsIn[i], \"ERR_LIMIT_IN\");\n\n            actualAmountsIn[i] = tokenAmountIn;\n        }\n    }\n\n    /**\n     * @notice Exit a pool - redeem pool tokens for underlying assets\n     * @param self - ConfigurableRightsPool instance calling the library\n     * @param bPool - Core BPool the CRP is wrapping\n     * @param poolAmountIn - amount of pool tokens to redeem\n     * @param minAmountsOut - minimum amount of asset tokens to receive\n     * @return actualAmountsOut - calculated amounts of each token to pull\n     */\n    function exitPool(\n        IConfigurableRightsPool self,\n        IBPool bPool,\n        uint poolAmountIn,\n        uint[] calldata minAmountsOut\n    ) external view returns (uint[] memory actualAmountsOut) {\n        address[] memory tokens = bPool.getCurrentTokens();\n\n        require(minAmountsOut.length == tokens.length, \"ERR_AMOUNTS_MISMATCH\");\n\n        uint poolTotal = self.totalSupply();\n\n        uint ratio = DesynSafeMath.bdiv(poolAmountIn, DesynSafeMath.badd(poolTotal, 1));\n\n        require(ratio != 0, \"ERR_MATH_APPROX\");\n\n        actualAmountsOut = new uint[](tokens.length);\n\n        // This loop contains external calls\n        // External calls are to math libraries or the underlying pool, so low risk\n        for (uint i = 0; i < tokens.length; i++) {\n            address t = tokens[i];\n            uint bal = bPool.getBalance(t);\n            // Subtract 1 to ensure any rounding errors favor the pool\n            uint tokenAmountOut = DesynSafeMath.bmul(ratio, DesynSafeMath.bsub(bal, 1));\n\n            require(tokenAmountOut != 0, \"ERR_MATH_APPROX\");\n            require(tokenAmountOut >= minAmountsOut[i], \"ERR_LIMIT_OUT\");\n\n            actualAmountsOut[i] = tokenAmountOut;\n        }\n    }\n\n    // Internal functions\n    // Check for zero transfer, and make sure it returns true to returnValue\n    function verifyTokenComplianceInternal(address token) internal {\n        IERC20(token).safeTransfer(msg.sender, 0);\n    }\n\n    function handleTransferInTokens(\n        IConfigurableRightsPool self,\n        IBPool bPool,\n        address poolToken,\n        uint actualAmountIn,\n        uint _actualIssueFee\n    ) external returns (uint issueFeeReceived) {\n        issueFeeReceived = DesynSafeMath.bmul(actualAmountIn, _actualIssueFee);\n        uint amount = DesynSafeMath.bsub(actualAmountIn, issueFeeReceived);\n\n        _pullUnderlying(bPool, poolToken, msg.sender, amount);\n\n        if (_actualIssueFee != 0) {\n            IERC20(poolToken).safeTransferFrom(msg.sender, address(this), issueFeeReceived);\n            IERC20(poolToken).safeApprove(self.vaultAddress(), 0);\n            IERC20(poolToken).safeApprove(self.vaultAddress(), issueFeeReceived);\n        }\n    }\n\n    function handleClaim(\n        IConfigurableRightsPool self,\n        IBPool bPool,\n        address[] calldata poolTokens,\n        uint managerFee,\n        uint timeElapsed,\n        uint claimPeriod\n    ) external returns (uint[] memory) {\n        uint[] memory tokensAmount = new uint[](poolTokens.length);\n        \n        for (uint i = 0; i < poolTokens.length; i++) {\n            address t = poolTokens[i];\n            uint tokenBalance = bPool.getBalance(t);\n            uint tokenAmountOut = tokenBalance.bmul(managerFee).mul(timeElapsed).div(claimPeriod).div(12);    \n            _pushUnderlying(bPool, t, address(this), tokenAmountOut);\n            IERC20(t).safeApprove(self.vaultAddress(), 0);\n            IERC20(t).safeApprove(self.vaultAddress(), tokenAmountOut);\n            tokensAmount[i] = tokenAmountOut;\n        }\n        \n        return tokensAmount;\n    }\n\n    function handleCollectionCompleted(\n        IConfigurableRightsPool self,\n        IBPool bPool,\n        address[] calldata poolTokens,\n        uint issueFee\n    ) external {\n        if (issueFee != 0) {\n            uint[] memory tokensAmount = new uint[](poolTokens.length);\n\n            for (uint i = 0; i < poolTokens.length; i++) {\n                address t = poolTokens[i];\n                uint currentAmount = bPool.getBalance(t);\n                uint currentAmountFee = DesynSafeMath.bmul(currentAmount, issueFee);\n\n                _pushUnderlying(bPool, t, address(this), currentAmountFee);\n                tokensAmount[i] = currentAmountFee;\n                IERC20(t).safeApprove(self.vaultAddress(), 0);\n                IERC20(t).safeApprove(self.vaultAddress(), currentAmountFee);\n            }\n\n            IVault(self.vaultAddress()).depositIssueRedeemPToken(poolTokens, tokensAmount, tokensAmount, false);\n        }\n    }\n\n    function WhitelistHandle(\n        bool bool1,\n        bool bool2,\n        address adr\n    ) external pure {\n        require(bool1, \"ERR_CANNOT_WHITELIST_LPS\");\n        require(bool2, \"ERR_LP_NOT_WHITELISTED\");\n        require(adr != address(0), \"ERR_INVALID_ADDRESS\");\n    }\n\n    function _pullUnderlying(\n        IBPool bPool,\n        address erc20,\n        address from,\n        uint amount\n    ) internal {\n        uint tokenBalance = bPool.getBalance(erc20);\n        uint tokenWeight = bPool.getDenormalizedWeight(erc20);\n\n        IERC20(erc20).safeTransferFrom(from, address(this), amount);\n        bPool.rebind(erc20, DesynSafeMath.badd(tokenBalance, amount), tokenWeight);\n    }\n\n    function _pushUnderlying(\n        IBPool bPool,\n        address erc20,\n        address to,\n        uint amount\n    ) internal {\n        uint tokenBalance = bPool.getBalance(erc20);\n        uint tokenWeight = bPool.getDenormalizedWeight(erc20);\n        bPool.rebind(erc20, DesynSafeMath.bsub(tokenBalance, amount), tokenWeight);\n        IERC20(erc20).safeTransfer(to, amount);\n    }\n}\n"
    },
    "contracts/libraries/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport {IERC20} from \"../interfaces/IERC20.sol\";\nimport {SafeMath} from \"./SafeMath.sol\";\nimport {Address} from \"./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 uint;\n    using Address for address;\n\n    function safeTransfer(\n        IERC20 token,\n        address to,\n        uint value\n    ) internal {\n        callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(\n        IERC20 token,\n        address from,\n        address to,\n        uint value\n    ) internal {\n        callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    function safeApprove(\n        IERC20 token,\n        address spender,\n        uint value\n    ) internal {\n        require((value == 0) || (token.allowance(address(this), spender) == 0), \"SafeERC20: approve from non-zero to non-zero allowance\");\n        callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    function callOptionalReturn(IERC20 token, bytes memory data) private {\n        require(address(token).isContract(), \"SafeERC20: call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = address(token).call(data);\n        require(success, \"SafeERC20: low-level call failed\");\n\n        if (returndata.length > 0) {\n            // Return data is optional\n            // solhint-disable-next-line max-line-length\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}\n"
    },
    "contracts/libraries/SafeMath.sol": {
      "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\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(uint a, uint b) internal pure returns (uint) {\n        uint 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(uint a, uint b) internal pure returns (uint) {\n        return sub(a, b, \"SafeMath: subtraction overflow\");\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     * - Subtraction cannot overflow.\n     */\n    function sub(\n        uint a,\n        uint b,\n        string memory errorMessage\n    ) internal pure returns (uint) {\n        require(b <= a, errorMessage);\n        uint 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(uint a, uint b) internal pure returns (uint) {\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        uint 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(uint a, uint b) internal pure returns (uint) {\n        return div(a, b, \"SafeMath: division by zero\");\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function div(\n        uint a,\n        uint b,\n        string memory errorMessage\n    ) internal pure returns (uint) {\n        // Solidity only automatically asserts when dividing by 0\n        require(b > 0, errorMessage);\n        uint 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(uint a, uint b) internal pure returns (uint) {\n        return mod(a, b, \"SafeMath: modulo by zero\");\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * Reverts with custom message when dividing by zero.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function mod(\n        uint a,\n        uint b,\n        string memory errorMessage\n    ) internal pure returns (uint) {\n        require(b != 0, errorMessage);\n        return a % b;\n    }\n}\n"
    },
    "contracts/interfaces/IBFactory.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\nimport \"../libraries/SmartPoolManager.sol\";\n\ninterface IBPool {\n    function rebind(\n        address token,\n        uint balance,\n        uint denorm\n    ) external;\n\n    function rebindSmart(\n        address tokenA,\n        address tokenB,\n        uint deltaWeight,\n        uint deltaBalance,\n        bool isSoldout,\n        uint minAmountOut\n    ) external;\n\n    function execute(\n        address _target,\n        uint _value,\n        bytes calldata _data\n    ) external returns (bytes memory _returnValue);\n\n    function bind(\n        address token,\n        uint balance,\n        uint denorm\n    ) external;\n\n    function unbind(address token) external;\n\n    function unbindPure(address token) external;\n\n    function isBound(address token) external view returns (bool);\n\n    function getBalance(address token) external view returns (uint);\n\n    function totalSupply() external view returns (uint);\n\n    function getSwapFee() external view returns (uint);\n\n    function isPublicSwap() external view returns (bool);\n\n    function getDenormalizedWeight(address token) external view returns (uint);\n\n    function getTotalDenormalizedWeight() external view returns (uint);\n\n    function EXIT_FEE() external view returns (uint);\n\n    function getCurrentTokens() external view returns (address[] memory tokens);\n\n    function setController(address owner) external;\n}\n\ninterface IBFactory {\n    function newLiquidityPool() external returns (IBPool);\n\n    function setBLabs(address b) external;\n\n    function collect(IBPool pool) external;\n\n    function isBPool(address b) external view returns (bool);\n\n    function getBLabs() external view returns (address);\n\n    function getSwapRouter() external view returns (address);\n\n    function getVault() external view returns (address);\n\n    function getUserVault() external view returns (address);\n\n    function getVaultAddress() external view returns (address);\n\n    function getOracleAddress() external view returns (address);\n\n    function getManagerOwner() external view returns (address);\n\n    function isTokenWhitelistedForVerify(uint sort, address token) external view returns (bool);\n\n    function isTokenWhitelistedForVerify(address token) external view returns (bool);\n\n    function getModuleStatus(address etf, address module) external view returns (bool);\n\n    function isPaused() external view returns (bool);\n}\n\ninterface IVault {\n    function depositManagerToken(address[] calldata poolTokens, uint[] calldata tokensAmount) external;\n\n    function depositIssueRedeemPToken(\n        address[] calldata poolTokens,\n        uint[] calldata tokensAmount,\n        uint[] calldata tokensAmountP,\n        bool isPerfermance\n    ) external;\n\n    function managerClaim(address pool) external;\n\n    function getManagerClaimBool(address pool) external view returns (bool);\n}\n\ninterface IUserVault {\n    function recordTokenInfo(\n        address kol,\n        address user,\n        address[] calldata poolTokens,\n        uint[] calldata tokensAmount\n    ) external;\n}\n\ninterface Oracles {\n    function getPrice(address tokenAddress) external returns (uint price);\n\n    function getAllPrice(address[] calldata poolTokens, uint[] calldata tokensAmount) external returns (uint);\n}"
    },
    "contracts/interfaces/IERC20.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.6.12;\n\n// Interface declarations\n\n/* solhint-disable func-order */\n\ninterface IERC20 {\n    // Emitted when the allowance of a spender for an owner is set by a call to approve.\n    // Value is the new allowance\n    event Approval(address indexed owner, address indexed spender, uint value);\n\n    // Emitted when value tokens are moved from one account (from) to another (to).\n    // Note that value may be zero\n    event Transfer(address indexed from, address indexed to, uint value);\n\n    // Returns the amount of tokens in existence\n    function totalSupply() external view returns (uint);\n\n    // Returns the amount of tokens owned by account\n    function balanceOf(address account) external view returns (uint);\n\n    // Returns the decimals of tokens\n    function decimals() external view returns (uint8);\n\n    function symbol() external view returns (string memory);\n\n    // Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner\n    // through transferFrom. This is zero by default\n    // This value changes when approve or transferFrom are called\n    function allowance(address owner, address spender) external view returns (uint);\n\n    // Sets amount as the allowance of spender over the caller’s tokens\n    // Returns a boolean value indicating whether the operation succeeded\n    // Emits an Approval event.\n    function approve(address spender, uint amount) external returns (bool);\n\n    // Moves amount tokens from the caller’s account to recipient\n    // Returns a boolean value indicating whether the operation succeeded\n    // Emits a Transfer event.\n    function transfer(address recipient, uint amount) external returns (bool);\n\n    // Moves amount tokens from sender to recipient using the allowance mechanism\n    // Amount is then deducted from the caller’s allowance\n    // Returns a boolean value indicating whether the operation succeeded\n    // Emits a Transfer event\n    function transferFrom(\n        address sender,\n        address recipient,\n        uint amount\n    ) external returns (bool);\n}\n"
    },
    "contracts/libraries/DesynSafeMath.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.6.12;\n\n// Imports\n\nimport \"./DesynConstants.sol\";\n\n/**\n * @author Desyn Labs\n * @title SafeMath - wrap Solidity operators to prevent underflow/overflow\n * @dev badd and bsub are basically identical to OpenZeppelin SafeMath; mul/div have extra checks\n */\nlibrary DesynSafeMath {\n    /**\n     * @notice Safe addition\n     * @param a - first operand\n     * @param b - second operand\n     * @dev if we are adding b to a, the resulting sum must be greater than a\n     * @return - sum of operands; throws if overflow\n     */\n    function badd(uint a, uint b) internal pure returns (uint) {\n        uint c = a + b;\n        require(c >= a, \"ERR_ADD_OVERFLOW\");\n        return c;\n    }\n\n    /**\n     * @notice Safe unsigned subtraction\n     * @param a - first operand\n     * @param b - second operand\n     * @dev Do a signed subtraction, and check that it produces a positive value\n     *      (i.e., a - b is valid if b <= a)\n     * @return - a - b; throws if underflow\n     */\n    function bsub(uint a, uint b) internal pure returns (uint) {\n        (uint c, bool negativeResult) = bsubSign(a, b);\n        require(!negativeResult, \"ERR_SUB_UNDERFLOW\");\n        return c;\n    }\n\n    /**\n     * @notice Safe signed subtraction\n     * @param a - first operand\n     * @param b - second operand\n     * @dev Do a signed subtraction\n     * @return - difference between a and b, and a flag indicating a negative result\n     *           (i.e., a - b if a is greater than or equal to b; otherwise b - a)\n     */\n    function bsubSign(uint a, uint b) internal pure returns (uint, bool) {\n        if (b <= a) {\n            return (a - b, false);\n        } else {\n            return (b - a, true);\n        }\n    }\n\n    /**\n     * @notice Safe multiplication\n     * @param a - first operand\n     * @param b - second operand\n     * @dev Multiply safely (and efficiently), rounding down\n     * @return - product of operands; throws if overflow or rounding error\n     */\n    function bmul(uint a, uint b) internal pure returns (uint) {\n        // Gas optimization (see github.com/OpenZeppelin/openzeppelin-contracts/pull/522)\n        if (a == 0) {\n            return 0;\n        }\n\n        // Standard overflow check: a/a*b=b\n        uint c0 = a * b;\n        require(c0 / a == b, \"ERR_MUL_OVERFLOW\");\n\n        // Round to 0 if x*y < BONE/2?\n        uint c1 = c0 + (DesynConstants.BONE / 2);\n        require(c1 >= c0, \"ERR_MUL_OVERFLOW\");\n        uint c2 = c1 / DesynConstants.BONE;\n        return c2;\n    }\n\n    /**\n     * @notice Safe division\n     * @param dividend - first operand\n     * @param divisor - second operand\n     * @dev Divide safely (and efficiently), rounding down\n     * @return - quotient; throws if overflow or rounding error\n     */\n    function bdiv(uint dividend, uint divisor) internal pure returns (uint) {\n        require(divisor != 0, \"ERR_DIV_ZERO\");\n\n        // Gas optimization\n        if (dividend == 0) {\n            return 0;\n        }\n\n        uint c0 = dividend * DesynConstants.BONE;\n        require(c0 / dividend == DesynConstants.BONE, \"ERR_DIV_INTERNAL\"); // bmul overflow\n\n        uint c1 = c0 + (divisor / 2);\n        require(c1 >= c0, \"ERR_DIV_INTERNAL\"); //  badd require\n\n        uint c2 = c1 / divisor;\n        return c2;\n    }\n\n    /**\n     * @notice Safe unsigned integer modulo\n     * @dev Returns the remainder of dividing two unsigned integers.\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     * @param dividend - first operand\n     * @param divisor - second operand -- cannot be zero\n     * @return - quotient; throws if overflow or rounding error\n     */\n    function bmod(uint dividend, uint divisor) internal pure returns (uint) {\n        require(divisor != 0, \"ERR_MODULO_BY_ZERO\");\n\n        return dividend % divisor;\n    }\n\n    /**\n     * @notice Safe unsigned integer max\n     * @dev Returns the greater of the two input values\n     *\n     * @param a - first operand\n     * @param b - second operand\n     * @return - the maximum of a and b\n     */\n    function bmax(uint a, uint b) internal pure returns (uint) {\n        return a >= b ? a : b;\n    }\n\n    /**\n     * @notice Safe unsigned integer min\n     * @dev returns b, if b < a; otherwise returns a\n     *\n     * @param a - first operand\n     * @param b - second operand\n     * @return - the lesser of the two input values\n     */\n    function bmin(uint a, uint b) internal pure returns (uint) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @notice Safe unsigned integer average\n     * @dev Guard against (a+b) overflow by dividing each operand separately\n     *\n     * @param a - first operand\n     * @param b - second operand\n     * @return - the average of the two values\n     */\n    function baverage(uint a, uint b) internal pure returns (uint) {\n        // (a + b) / 2 can overflow, so we distribute\n        return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);\n    }\n\n    /**\n     * @notice Babylonian square root implementation\n     * @dev (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)\n     * @param y - operand\n     * @return z - the square root result\n     */\n    function sqrt(uint y) internal pure returns (uint z) {\n        if (y > 3) {\n            z = y;\n            uint x = y / 2 + 1;\n            while (x < z) {\n                z = x;\n                x = (y / x + x) / 2;\n            }\n        } else if (y != 0) {\n            z = 1;\n        }\n    }\n}\n"
    },
    "contracts/interfaces/IConfigurableRightsPool.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.6.12;\n\n// Interface declarations\n\n// Introduce to avoid circularity (otherwise, the CRP and SmartPoolManager include each other)\n// Removing circularity allows flattener tools to work, which enables Etherscan verification\ninterface IConfigurableRightsPool {\n    function mintPoolShareFromLib(uint amount) external;\n\n    function pushPoolShareFromLib(address to, uint amount) external;\n\n    function pullPoolShareFromLib(address from, uint amount) external;\n\n    function burnPoolShareFromLib(uint amount) external;\n\n    function balanceOf(address account) external view returns (uint);\n\n    function totalSupply() external view returns (uint);\n\n    function getController() external view returns (address);\n\n    function vaultAddress() external view returns (address);\n}\n"
    },
    "contracts/libraries/Address.sol": {
      "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\n        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\n        // for accounts without code, i.e. `keccak256('')`\n        bytes32 codehash;\n        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            codehash := extcodehash(account)\n        }\n        return (codehash != accountHash && codehash != 0x0);\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, uint 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    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) 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(\n        address target,\n        bytes memory data,\n        uint value\n    ) 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(\n        address target,\n        bytes memory data,\n        uint value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        return _functionCallWithValue(target, data, value, errorMessage);\n    }\n\n    function _functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint weiValue,\n        string memory errorMessage\n    ) private returns (bytes memory) {\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: weiValue}(data);\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"
    },
    "contracts/libraries/DesynConstants.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.6.12;\n\n/**\n * @author Desyn Labs\n * @title Put all the constants in one place\n */\n\nlibrary DesynConstants {\n    // State variables (must be constant in a library)\n\n    // B \"ONE\" - all math is in the \"realm\" of 10 ** 18;\n    // where numeric 1 = 10 ** 18\n    uint public constant BONE = 10**18;\n    uint public constant MIN_WEIGHT = BONE;\n    uint public constant MAX_WEIGHT = BONE * 50;\n    uint public constant MAX_TOTAL_WEIGHT = BONE * 50;\n    uint public constant MIN_BALANCE = 0;\n    uint public constant MAX_BALANCE = BONE * 10**12;\n    uint public constant MIN_POOL_SUPPLY = BONE * 100;\n    uint public constant MAX_POOL_SUPPLY = BONE * 10**9;\n    uint public constant MIN_FEE = BONE / 10**6;\n    uint public constant MAX_FEE = BONE / 10;\n    //Fee Set\n    uint public constant MANAGER_MIN_FEE = 0;\n    uint public constant MANAGER_MAX_FEE = BONE / 10;\n    uint public constant ISSUE_MIN_FEE = BONE / 1000;\n    uint public constant ISSUE_MAX_FEE = BONE / 10;\n    uint public constant REDEEM_MIN_FEE = 0;\n    uint public constant REDEEM_MAX_FEE = BONE / 10;\n    uint public constant PERFERMANCE_MIN_FEE = 0;\n    uint public constant PERFERMANCE_MAX_FEE = BONE / 2;\n    // EXIT_FEE must always be zero, or ConfigurableRightsPool._pushUnderlying will fail\n    uint public constant EXIT_FEE = 0;\n    uint public constant MAX_IN_RATIO = BONE / 2;\n    uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;\n    // Must match BConst.MIN_BOUND_TOKENS and BConst.MAX_BOUND_TOKENS\n    uint public constant MIN_ASSET_LIMIT = 1;\n    uint public constant MAX_ASSET_LIMIT = 16;\n    uint public constant MAX_UINT = uint(-1);\n    uint public constant MAX_COLLECT_PERIOD = 60 days;\n}\n"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 20
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "metadata": {
      "useLiteralContent": true
    },
    "libraries": {}
  }
}