From 0834c13e8ccfb883f32bf91645ca3797e7c949c4 Mon Sep 17 00:00:00 2001 From: 0xSachinK Date: Mon, 28 Mar 2022 18:48:38 +0530 Subject: [PATCH 1/5] Add IPerpV2LeverageModuleV2 interface --- .../interfaces/IPerpV2LeverageModuleV2.sol | 272 ++++++++++++++++++ 1 file changed, 272 insertions(+) create mode 100644 contracts/interfaces/IPerpV2LeverageModuleV2.sol diff --git a/contracts/interfaces/IPerpV2LeverageModuleV2.sol b/contracts/interfaces/IPerpV2LeverageModuleV2.sol new file mode 100644 index 000000000..21bcfba4e --- /dev/null +++ b/contracts/interfaces/IPerpV2LeverageModuleV2.sol @@ -0,0 +1,272 @@ +/* + Copyright 2022 Set Labs Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + SPDX-License-Identifier: Apache License, Version 2.0 +*/ +pragma solidity 0.6.10; +pragma experimental "ABIEncoderV2"; + +import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + +import { ISetToken } from "./ISetToken.sol"; +import { IDebtIssuanceModule } from "./IDebtIssuanceModule.sol"; +import { IAccountBalance } from "./external/perp-v2/IAccountBalance.sol"; +import { IClearingHouse } from "./external/perp-v2/IClearingHouse.sol"; +import { IExchange } from "./external/perp-v2/IExchange.sol"; +import { IVault } from "./external/perp-v2/IVault.sol"; +import { IQuoter } from "./external/perp-v2/IQuoter.sol"; +import { IMarketRegistry } from "./external/perp-v2/IMarketRegistry.sol"; +import { PerpV2Positions } from "../protocol/integration/lib/PerpV2Positions.sol"; + +/** + * @title IPerpV2LeverageModuleV2 + * @author Set Protocol + * + * Interface for the PerpV2LeverageModuleV2. Only specifies Manager permissioned functions, events + * and getters. PerpV2LeverageModuleV2 also inherits from ModuleBase and SetTokenAccessible which support + * additional methods. + */ +interface IPerpV2LeverageModuleV2 { + + /* ============ Structs ============ */ + + // Note: when `pendingFundingPayments` is positive it will be credited to account on settlement, + // when negative it's a debt owed that will be repaid on settlement. (PerpProtocol.Exchange returns the value + // with the opposite meaning, e.g positively signed payments are owed by account to system). + struct AccountInfo { + int256 collateralBalance; // Quantity of collateral deposited in Perp vault in 10**18 decimals + int256 owedRealizedPnl; // USDC quantity of profit and loss in 10**18 decimals not yet settled to vault + int256 pendingFundingPayments; // USDC quantity of pending funding payments in 10**18 decimals + int256 netQuoteBalance; // USDC quantity of net quote balance for all open positions in Perp account + } + + /* ============ Events ============ */ + + /** + * @dev Emitted on trade + * @param _setToken Instance of SetToken + * @param _baseToken Virtual token minted by the Perp protocol + * @param _deltaBase Change in baseToken position size resulting from trade + * @param _deltaQuote Change in vUSDC position size resulting from trade + * @param _protocolFee Quantity in collateral decimals sent to fee recipient during lever trade + * @param _isBuy True when baseToken is being bought, false when being sold + */ + event PerpTraded( + ISetToken indexed _setToken, + address indexed _baseToken, + uint256 _deltaBase, + uint256 _deltaQuote, + uint256 _protocolFee, + bool _isBuy + ); + + /** + * @dev Emitted on deposit (not issue or redeem) + * @param _setToken Instance of SetToken + * @param _collateralToken Token being deposited as collateral (USDC) + * @param _amountDeposited Amount of collateral being deposited into Perp + */ + event CollateralDeposited( + ISetToken indexed _setToken, + IERC20 _collateralToken, + uint256 _amountDeposited + ); + + /** + * @dev Emitted on withdraw (not issue or redeem) + * @param _setToken Instance of SetToken + * @param _collateralToken Token being withdrawn as collateral (USDC) + * @param _amountWithdrawn Amount of collateral being withdrawn from Perp + */ + event CollateralWithdrawn( + ISetToken indexed _setToken, + IERC20 _collateralToken, + uint256 _amountWithdrawn + ); + + /* ============ State Variable Getters ============ */ + + // PerpV2 contract which provides getters for base, quote, and owedRealizedPnl balances + function perpAccountBalance() external view returns(IAccountBalance); + + // PerpV2 contract which provides a trading API + function perpClearingHouse() external view returns(IClearingHouse); + + // PerpV2 contract which manages trading logic. Provides getters for UniswapV3 pools and pending funding balances + function perpExchange() external view returns(IExchange); + + // PerpV2 contract which handles deposits and withdrawals. Provides getter for collateral balances + function perpVault() external view returns(IVault); + + // PerpV2 contract which makes it possible to simulate a trade before it occurs + function perpQuoter() external view returns(IQuoter); + + // PerpV2 contract which provides a getter for baseToken UniswapV3 pools + function perpMarketRegistry() external view returns(IMarketRegistry); + + // Token (USDC) used as a vault deposit, Perp currently only supports USDC as it's settlement and collateral token + function collateralToken() external view returns(IERC20); + + // Decimals of collateral token. We set this in the constructor for later reading + function collateralDecimals() external view returns(uint8); + + /* ============ External Functions ============ */ + + /** + * @dev MANAGER ONLY: Initializes this module to the SetToken. Either the SetToken needs to be on the + * allowed list or anySetAllowed needs to be true. + * + * @param _setToken Instance of the SetToken to initialize + */ + function initialize(ISetToken _setToken) external; + + /** + * @dev MANAGER ONLY: Allows manager to buy or sell perps to change exposure to the underlying baseToken. + * Providing a positive value for `_baseQuantityUnits` buys vToken on UniswapV3 via Perp's ClearingHouse, + * Providing a negative value sells the token. `_quoteBoundQuantityUnits` defines a min-receive-like slippage + * bound for the amount of vUSDC quote asset the trade will either pay or receive as a result of the action. + * + * NOTE: This method doesn't update the externalPositionUnit because it is a function of UniswapV3 virtual + * token market prices and needs to be generated on the fly to be meaningful. + * + * As a user when levering, e.g increasing the magnitude of your position, you'd trade as below + * | ----------------------------------------------------------------------------------------------- | + * | Type | Action | Goal | `quoteBoundQuantity` | `baseQuantityUnits` | + * | ----- |-------- | ------------------------- | --------------------------- | ------------------- | + * | Long | Buy | pay least amt. of vQuote | upper bound of input quote | positive | + * | Short | Sell | get most amt. of vQuote | lower bound of output quote | negative | + * | ----------------------------------------------------------------------------------------------- | + * + * As a user when delevering, e.g decreasing the magnitude of your position, you'd trade as below + * | ----------------------------------------------------------------------------------------------- | + * | Type | Action | Goal | `quoteBoundQuantity` | `baseQuantityUnits` | + * | ----- |-------- | ------------------------- | --------------------------- | ------------------- | + * | Long | Sell | get most amt. of vQuote | upper bound of input quote | negative | + * | Short | Buy | pay least amt. of vQuote | lower bound of output quote | positive | + * | ----------------------------------------------------------------------------------------------- | + * + * @param _setToken Instance of the SetToken + * @param _baseToken Address virtual token being traded + * @param _baseQuantityUnits Quantity of virtual token to trade in position units + * @param _quoteBoundQuantityUnits Max/min of vQuote asset to pay/receive when buying or selling + */ + function trade( + ISetToken _setToken, + address _baseToken, + int256 _baseQuantityUnits, + uint256 _quoteBoundQuantityUnits + ) + external; + + /** + * @dev MANAGER ONLY: Deposits default position collateral token into the PerpV2 Vault, increasing + * the size of the Perp account external position. This method is useful for establishing initial + * collateralization ratios, e.g the flow when setting up a 2X external position would be to deposit + * 100 units of USDC and execute a lever trade for ~200 vUSDC worth of vToken with the difference + * between these made up as automatically "issued" margin debt in the PerpV2 system. + * + * @param _setToken Instance of the SetToken + * @param _collateralQuantityUnits Quantity of collateral to deposit in position units + */ + function deposit(ISetToken _setToken, uint256 _collateralQuantityUnits) external; + + + /** + * @dev MANAGER ONLY: Withdraws collateral token from the PerpV2 Vault to a default position on + * the SetToken. This method is useful when adjusting the overall composition of a Set which has + * a Perp account external position as one of several components. + * + * NOTE: Within PerpV2, `withdraw` settles `owedRealizedPnl` and any pending funding payments + * to the Perp vault prior to transfer. + * + * @param _setToken Instance of the SetToken + * @param _collateralQuantityUnits Quantity of collateral to withdraw in position units + */ + function withdraw(ISetToken _setToken, uint256 _collateralQuantityUnits) external; + + + /* ============ External Getter Functions ============ */ + + /** + * @dev Gets the positive equity collateral externalPositionUnit that would be calculated for + * issuing a quantity of SetToken, representing the amount of collateral that would need to + * be transferred in per SetToken. Values in the returned arrays map to the same index in the + * SetToken's components array + * + * @param _setToken Instance of SetToken + * @param _setTokenQuantity Number of sets to issue + * + * @return equityAdjustments array containing a single element and an empty debtAdjustments array + */ + function getIssuanceAdjustments(ISetToken _setToken, uint256 _setTokenQuantity) + external + returns (int256[] memory, int256[] memory); + + + /** + * @dev Gets the positive equity collateral externalPositionUnit that would be calculated for + * redeeming a quantity of SetToken representing the amount of collateral returned per SetToken. + * Values in the returned arrays map to the same index in the SetToken's components array. + * + * @param _setToken Instance of SetToken + * @param _setTokenQuantity Number of sets to issue + * + * @return equityAdjustments array containing a single element and an empty debtAdjustments array + */ + function getRedemptionAdjustments(ISetToken _setToken, uint256 _setTokenQuantity) + external + returns (int256[] memory, int256[] memory); + + /** + * @dev Returns a PositionUnitNotionalInfo array representing all positions open for the SetToken. + * + * @param _setToken Instance of SetToken + * + * @return PositionUnitInfo array, in which each element has properties: + * + * + baseToken: address, + * + baseBalance: baseToken balance as notional quantity (10**18) + * + quoteBalance: USDC quote asset balance as notional quantity (10**18) + */ + function getPositionNotionalInfo(ISetToken _setToken) external view returns (PerpV2Positions.PositionNotionalInfo[] memory); + + /** + * @dev Returns a PositionUnitInfo array representing all positions open for the SetToken. + * + * @param _setToken Instance of SetToken + * + * @return PositionUnitInfo array, in which each element has properties: + * + * + baseToken: address, + * + baseUnit: baseToken balance as position unit (10**18) + * + quoteUnit: USDC quote asset balance as position unit (10**18) + */ + function getPositionUnitInfo(ISetToken _setToken) external view returns (PerpV2Positions.PositionUnitInfo[] memory); + + /** + * @dev Gets Perp account info for SetToken. Returns an AccountInfo struct containing account wide + * (rather than position specific) balance info + * + * @param _setToken Instance of the SetToken + * + * @return accountInfo struct with properties for: + * + * + collateral balance (10**18, regardless of underlying collateral decimals) + * + owed realized Pnl` (10**18) + * + pending funding payments (10**18) + * + net quote balance (10**18) + */ + function getAccountInfo(ISetToken _setToken) external view returns (AccountInfo memory accountInfo); +} \ No newline at end of file From ba80159f7da58a0bb1e385cb8a50a1bf0e61a6b3 Mon Sep 17 00:00:00 2001 From: 0xSachinK Date: Mon, 28 Mar 2022 18:49:17 +0530 Subject: [PATCH 2/5] Add IPerpV2BasisTradingModule interface --- .../interfaces/IPerpV2BasisTradingModule.sol | 168 ++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 contracts/interfaces/IPerpV2BasisTradingModule.sol diff --git a/contracts/interfaces/IPerpV2BasisTradingModule.sol b/contracts/interfaces/IPerpV2BasisTradingModule.sol new file mode 100644 index 000000000..5ea69803d --- /dev/null +++ b/contracts/interfaces/IPerpV2BasisTradingModule.sol @@ -0,0 +1,168 @@ +/* + Copyright 2022 Set Labs Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + SPDX-License-Identifier: Apache License, Version 2.0 +*/ +pragma solidity 0.6.10; +pragma experimental "ABIEncoderV2"; + +import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + +import { ISetToken } from "./ISetToken.sol"; +import { IDebtIssuanceModule } from "./IDebtIssuanceModule.sol"; +import { IAccountBalance } from "./external/perp-v2/IAccountBalance.sol"; +import { IClearingHouse } from "./external/perp-v2/IClearingHouse.sol"; +import { IExchange } from "./external/perp-v2/IExchange.sol"; +import { IVault } from "./external/perp-v2/IVault.sol"; +import { IQuoter } from "./external/perp-v2/IQuoter.sol"; +import { IMarketRegistry } from "./external/perp-v2/IMarketRegistry.sol"; +import { PerpV2Positions } from "../protocol/integration/lib/PerpV2Positions.sol"; + +import { IPerpV2LeverageModuleV2 } from "./IPerpV2LeverageModuleV2.sol"; + +/** + * @title IPerpV2BasisTradingModule + * @author Set Protocol + * + * Interface for the PerpV2BasisTradingModule. Only specifies Manager permissioned functions, events + * and getters. PerpV2BasisTradingModule also inherits from ModuleBaseV2 and SetTokenAccessible which support + * additional methods. + */ +interface IPerpV2BasisTradingModule is IPerpV2LeverageModuleV2 { + + /* ============ Structs ============ */ + + struct FeeState { + address feeRecipient; // Address to accrue fees to + uint256 maxPerformanceFeePercentage; // Max performance fee manager commits to using (1% = 1e16, 100% = 1e18) + uint256 performanceFeePercentage; // Performance fees accrued to manager (1% = 1e16, 100% = 1e18) + } + + /* ============ Events ============ */ + + /** + * @dev Emitted on performance fee update + * @param _setToken Instance of SetToken + * @param _newPerformanceFee New performance fee percentage (1% = 1e16) + */ + event PerformanceFeeUpdated(ISetToken indexed _setToken, uint256 _newPerformanceFee); + + /** + * @dev Emitted on fee recipient update + * @param _setToken Instance of SetToken + * @param _newFeeRecipient New performance fee recipient + */ + event FeeRecipientUpdated(ISetToken indexed _setToken, address _newFeeRecipient); + + /** + * @dev Emitted on funding withdraw + * @param _setToken Instance of SetToken + * @param _collateralToken Token being withdrawn as funding (USDC) + * @param _amountWithdrawn Amount of funding being withdrawn from Perp (USDC) + * @param _managerFee Amount of performance fee accrued to manager (USDC) + * @param _protocolFee Amount of performance fee accrued to protocol (USDC) + */ + event FundingWithdrawn( + ISetToken indexed _setToken, + IERC20 _collateralToken, + uint256 _amountWithdrawn, + uint256 _managerFee, + uint256 _protocolFee + ); + + /* ============ State Variable Getters ============ */ + + // Mapping to store fee settings for each SetToken + function feeSettings(ISetToken _setToken) external view returns(FeeState memory); + + // Mapping to store funding that has been settled on Perpetual Protocol due to actions via this module + // and hasn't been withdrawn for reinvesting yet. Values are stored in precise units (10e18). + function settledFunding(ISetToken _settledFunding) external view returns (uint256); + + /* ============ External Functions ============ */ + + /** + * @dev MANAGER ONLY: Initializes this module to the SetToken and sets fee settings. Either the SetToken needs to + * be on the allowed list or anySetAllowed needs to be true. + * + * @param _setToken Instance of the SetToken to initialize + */ + function initialize( + ISetToken _setToken, + FeeState memory _settings + ) + external; + + /** + * @dev MANAGER ONLY: Similar to PerpV2LeverageModuleV2#trade. Allows manager to buy or sell perps to change exposure + * to the underlying baseToken. Any pending funding that would be settled during opening a position on Perpetual + * protocol is added to (or subtracted from) `settledFunding[_setToken]` and can be withdrawn later using + * `withdrawFundingAndAccrueFees` by the SetToken manager. + * NOTE: Calling a `nonReentrant` function from another `nonReentrant` function is not supported. Hence, we can't + * add the `nonReentrant` modifier here because `PerpV2LeverageModuleV2#trade` function has a reentrancy check. + * NOTE: This method doesn't update the externalPositionUnit because it is a function of UniswapV3 virtual + * token market prices and needs to be generated on the fly to be meaningful. + * + * @param _setToken Instance of the SetToken + * @param _baseToken Address virtual token being traded + * @param _baseQuantityUnits Quantity of virtual token to trade in position units + * @param _quoteBoundQuantityUnits Max/min of vQuote asset to pay/receive when buying or selling + */ + function tradeAndTrackFunding( + ISetToken _setToken, + address _baseToken, + int256 _baseQuantityUnits, + uint256 _quoteBoundQuantityUnits + ) + external; + + /** + * @dev MANAGER ONLY: Withdraws tracked settled funding (in USDC) from the PerpV2 Vault to a default position + * on the SetToken. Collects manager and protocol performance fees on the withdrawn amount. + * This method is useful when withdrawing funding to be reinvested into the Basis Trading product. + * + * NOTE: Within PerpV2, `withdraw` settles `owedRealizedPnl` and any pending funding payments + * to the Perp vault prior to transfer. + * + * @param _setToken Instance of the SetToken + * @param _notionalFunding Notional amount of funding to withdraw (in USDC decimals) + */ + function withdrawFundingAndAccrueFees( + ISetToken _setToken, + uint256 _notionalFunding + ) + external; + + /** + * @dev MANAGER ONLY. Update performance fee percentage. + * + * @param _setToken Instance of SetToken + * @param _newFee New performance fee percentage in precise units (1e16 = 1%) + */ + function updatePerformanceFee( + ISetToken _setToken, + uint256 _newFee + ) + external; + + /** + * @dev MANAGER ONLY. Update performance fee recipient (address to which performance fees are sent). + * + * @param _setToken Instance of SetToken + * @param _newFeeRecipient Address of new fee recipient + */ + function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient) + external; +} \ No newline at end of file From 612d3328feba8ce6ed6a9b7acddb80a6820449e3 Mon Sep 17 00:00:00 2001 From: 0xSachinK Date: Mon, 28 Mar 2022 19:02:45 +0530 Subject: [PATCH 3/5] Remove IPerpV2LeverageModule.sol --- .../interfaces/IPerpV2LeverageModule.sol | 280 ------------------ 1 file changed, 280 deletions(-) delete mode 100644 contracts/interfaces/IPerpV2LeverageModule.sol diff --git a/contracts/interfaces/IPerpV2LeverageModule.sol b/contracts/interfaces/IPerpV2LeverageModule.sol deleted file mode 100644 index 090ae9f97..000000000 --- a/contracts/interfaces/IPerpV2LeverageModule.sol +++ /dev/null @@ -1,280 +0,0 @@ -/* - Copyright 2021 Set Labs Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - SPDX-License-Identifier: Apache License, Version 2.0 -*/ -pragma solidity 0.6.10; -pragma experimental "ABIEncoderV2"; - -import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; - -import { ISetToken } from "./ISetToken.sol"; -import { IDebtIssuanceModule } from "./IDebtIssuanceModule.sol"; -import { IAccountBalance } from "./external/perp-v2/IAccountBalance.sol"; -import { IClearingHouse } from "./external/perp-v2/IClearingHouse.sol"; -import { IExchange } from "./external/perp-v2/IExchange.sol"; -import { IVault } from "./external/perp-v2/IVault.sol"; -import { IQuoter } from "./external/perp-v2/IQuoter.sol"; -import { IMarketRegistry } from "./external/perp-v2/IMarketRegistry.sol"; -import { PerpV2Positions } from "../protocol/integration/lib/PerpV2Positions.sol"; - -/** - * @title IPerpV2LeverageModule - * @author Set Protocol - * - * Interface for the PerpV2LeverageModule. Only specifies Manager permissioned functions, events - * and getters. PerpV2LeverageModule also inherits from ModuleBase and SetTokenAccessible which support - * additional methods. - */ -interface IPerpV2LeverageModule { - - /* ============ Structs ============ */ - - // Note: when `pendingFundingPayments` is positive it will be credited to account on settlement, - // when negative it's a debt owed that will be repaid on settlement. (PerpProtocol.Exchange returns the value - // with the opposite meaning, e.g positively signed payments are owed by account to system). - struct AccountInfo { - int256 collateralBalance; // Quantity of collateral deposited in Perp vault in 10**18 decimals - int256 owedRealizedPnl; // USDC quantity of profit and loss in 10**18 decimals not yet settled to vault - int256 pendingFundingPayments; // USDC quantity of pending funding payments in 10**18 decimals - int256 netQuoteBalance; // USDC quantity of net quote balance for all open positions in Perp account - } - - /* ============ Events ============ */ - - /** - * @dev Emitted on trade - * @param _setToken Instance of SetToken - * @param _baseToken Virtual token minted by the Perp protocol - * @param _deltaBase Change in baseToken position size resulting from trade - * @param _deltaQuote Change in vUSDC position size resulting from trade - * @param _protocolFee Quantity in collateral decimals sent to fee recipient during lever trade - * @param _isBuy True when baseToken is being bought, false when being sold - */ - event PerpTraded( - ISetToken indexed _setToken, - address indexed _baseToken, - uint256 _deltaBase, - uint256 _deltaQuote, - uint256 _protocolFee, - bool _isBuy - ); - - /** - * @dev Emitted on deposit (not issue or redeem) - * @param _setToken Instance of SetToken - * @param _collateralToken Token being deposited as collateral (USDC) - * @param _amountDeposited Amount of collateral being deposited into Perp - */ - event CollateralDeposited( - ISetToken indexed _setToken, - IERC20 _collateralToken, - uint256 _amountDeposited - ); - - /** - * @dev Emitted on withdraw (not issue or redeem) - * @param _setToken Instance of SetToken - * @param _collateralToken Token being withdrawn as collateral (USDC) - * @param _amountWithdrawn Amount of collateral being withdrawn from Perp - */ - event CollateralWithdrawn( - ISetToken indexed _setToken, - IERC20 _collateralToken, - uint256 _amountWithdrawn - ); - - /* ============ State Variable Getters ============ */ - - // PerpV2 contract which provides getters for base, quote, and owedRealizedPnl balances - function perpAccountBalance() external view returns(IAccountBalance); - - // PerpV2 contract which provides a trading API - function perpClearingHouse() external view returns(IClearingHouse); - - // PerpV2 contract which manages trading logic. Provides getters for UniswapV3 pools and pending funding balances - function perpExchange() external view returns(IExchange); - - // PerpV2 contract which handles deposits and withdrawals. Provides getter for collateral balances - function perpVault() external view returns(IVault); - - // PerpV2 contract which makes it possible to simulate a trade before it occurs - function perpQuoter() external view returns(IQuoter); - - // PerpV2 contract which provides a getter for baseToken UniswapV3 pools - function perpMarketRegistry() external view returns(IMarketRegistry); - - // Token (USDC) used as a vault deposit, Perp currently only supports USDC as it's settlement and collateral token - function collateralToken() external view returns(IERC20); - - // Decimals of collateral token. We set this in the constructor for later reading - function collateralDecimals() external view returns(uint8); - - /* ============ External Functions ============ */ - - /** - * @dev MANAGER ONLY: Initializes this module to the SetToken. Either the SetToken needs to be on the - * allowed list or anySetAllowed needs to be true. - * - * @param _setToken Instance of the SetToken to initialize - */ - function initialize(ISetToken _setToken) external; - - /** - * @dev MANAGER ONLY: Allows manager to buy or sell perps to change exposure to the underlying baseToken. - * Providing a positive value for `_baseQuantityUnits` buys vToken on UniswapV3 via Perp's ClearingHouse, - * Providing a negative value sells the token. `_quoteBoundQuantityUnits` defines a min-receive-like slippage - * bound for the amount of vUSDC quote asset the trade will either pay or receive as a result of the action. - * - * NOTE: This method doesn't update the externalPositionUnit because it is a function of UniswapV3 virtual - * token market prices and needs to be generated on the fly to be meaningful. - * - * As a user when levering, e.g increasing the magnitude of your position, you'd trade as below - * | ----------------------------------------------------------------------------------------------- | - * | Type | Action | Goal | `quoteBoundQuantity` | `baseQuantityUnits` | - * | ----- |-------- | ------------------------- | --------------------------- | ------------------- | - * | Long | Buy | pay least amt. of vQuote | upper bound of input quote | positive | - * | Short | Sell | get most amt. of vQuote | lower bound of output quote | negative | - * | ----------------------------------------------------------------------------------------------- | - * - * As a user when delevering, e.g decreasing the magnitude of your position, you'd trade as below - * | ----------------------------------------------------------------------------------------------- | - * | Type | Action | Goal | `quoteBoundQuantity` | `baseQuantityUnits` | - * | ----- |-------- | ------------------------- | --------------------------- | ------------------- | - * | Long | Sell | get most amt. of vQuote | upper bound of input quote | negative | - * | Short | Buy | pay least amt. of vQuote | lower bound of output quote | positive | - * | ----------------------------------------------------------------------------------------------- | - * - * @param _setToken Instance of the SetToken - * @param _baseToken Address virtual token being traded - * @param _baseQuantityUnits Quantity of virtual token to trade in position units - * @param _quoteBoundQuantityUnits Max/min of vQuote asset to pay/receive when buying or selling - */ - function trade( - ISetToken _setToken, - address _baseToken, - int256 _baseQuantityUnits, - uint256 _quoteBoundQuantityUnits - ) - external; - - /** - * @dev MANAGER ONLY: Deposits default position collateral token into the PerpV2 Vault, increasing - * the size of the Perp account external position. This method is useful for establishing initial - * collateralization ratios, e.g the flow when setting up a 2X external position would be to deposit - * 100 units of USDC and execute a lever trade for ~200 vUSDC worth of vToken with the difference - * between these made up as automatically "issued" margin debt in the PerpV2 system. - * - * @param _setToken Instance of the SetToken - * @param _collateralQuantityUnits Quantity of collateral to deposit in position units - */ - function deposit(ISetToken _setToken, uint256 _collateralQuantityUnits) external; - - - /** - * @dev MANAGER ONLY: Withdraws collateral token from the PerpV2 Vault to a default position on - * the SetToken. This method is useful when adjusting the overall composition of a Set which has - * a Perp account external position as one of several components. - * - * NOTE: Within PerpV2, `withdraw` settles `owedRealizedPnl` and any pending funding payments - * to the Perp vault prior to transfer. - * - * @param _setToken Instance of the SetToken - * @param _collateralQuantityUnits Quantity of collateral to withdraw in position units - */ - function withdraw(ISetToken _setToken, uint256 _collateralQuantityUnits) external; - - - /* ============ External Getter Functions ============ */ - - /** - * @dev Gets the positive equity collateral externalPositionUnit that would be calculated for - * issuing a quantity of SetToken, representing the amount of collateral that would need to - * be transferred in per SetToken. Values in the returned arrays map to the same index in the - * SetToken's components array - * - * @param _setToken Instance of SetToken - * @param _setTokenQuantity Number of sets to issue - * - * @return equityAdjustments array containing a single element and an empty debtAdjustments array - */ - function getIssuanceAdjustments(ISetToken _setToken, uint256 _setTokenQuantity) - external - returns (int256[] memory, int256[] memory); - - - /** - * @dev Gets the positive equity collateral externalPositionUnit that would be calculated for - * redeeming a quantity of SetToken representing the amount of collateral returned per SetToken. - * Values in the returned arrays map to the same index in the SetToken's components array. - * - * @param _setToken Instance of SetToken - * @param _setTokenQuantity Number of sets to issue - * - * @return equityAdjustments array containing a single element and an empty debtAdjustments array - */ - function getRedemptionAdjustments(ISetToken _setToken, uint256 _setTokenQuantity) - external - returns (int256[] memory, int256[] memory); - - /** - * @dev Returns a PositionUnitNotionalInfo array representing all positions open for the SetToken. - * - * @param _setToken Instance of SetToken - * - * @return PositionUnitInfo array, in which each element has properties: - * - * + baseToken: address, - * + baseBalance: baseToken balance as notional quantity (10**18) - * + quoteBalance: USDC quote asset balance as notional quantity (10**18) - */ - function getPositionNotionalInfo(ISetToken _setToken) external view returns (PerpV2Positions.PositionNotionalInfo[] memory); - - /** - * @dev Returns a PositionUnitInfo array representing all positions open for the SetToken. - * - * @param _setToken Instance of SetToken - * - * @return PositionUnitInfo array, in which each element has properties: - * - * + baseToken: address, - * + baseUnit: baseToken balance as position unit (10**18) - * + quoteUnit: USDC quote asset balance as position unit (10**18) - */ - function getPositionUnitInfo(ISetToken _setToken) external view returns (PerpV2Positions.PositionUnitInfo[] memory); - - /** - * @dev Gets Perp account info for SetToken. Returns an AccountInfo struct containing account wide - * (rather than position specific) balance info - * - * @param _setToken Instance of the SetToken - * - * @return accountInfo struct with properties for: - * - * + collateral balance (10**18, regardless of underlying collateral decimals) - * + owed realized Pnl` (10**18) - * + pending funding payments (10**18) - * + net quote balance (10**18) - */ - function getAccountInfo(ISetToken _setToken) external view returns (AccountInfo memory accountInfo); - - /** - * @dev Gets the mid-point price of a virtual asset from UniswapV3 markets maintained by Perp Protocol - * - * @param _baseToken Address of virtual token to price - * @return price Mid-point price of virtual token in UniswapV3 AMM market - */ - function getAMMSpotPrice(address _baseToken) external view returns (uint256 price); -} \ No newline at end of file From eafe2ee3e171d6f5bdea869742989e72425139c4 Mon Sep 17 00:00:00 2001 From: 0xSachinK Date: Mon, 28 Mar 2022 19:05:54 +0530 Subject: [PATCH 4/5] Fix compilation: User IPerpV2LeverageModuleV2 in Perp veiwer --- .../PerpV2LeverageModuleViewer.sol | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/contracts/protocol-viewers/PerpV2LeverageModuleViewer.sol b/contracts/protocol-viewers/PerpV2LeverageModuleViewer.sol index 12acaae8a..b3cccbff8 100644 --- a/contracts/protocol-viewers/PerpV2LeverageModuleViewer.sol +++ b/contracts/protocol-viewers/PerpV2LeverageModuleViewer.sol @@ -28,7 +28,7 @@ import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol" import { IAccountBalance } from "../interfaces/external/perp-v2/IAccountBalance.sol"; import { IClearingHouseConfig } from "../interfaces/external/perp-v2/IClearingHouseConfig.sol"; import { IIndexPrice } from "../interfaces/external/perp-v2/IIndexPrice.sol"; -import { IPerpV2LeverageModule } from "../interfaces/IPerpV2LeverageModule.sol"; +import { IPerpV2LeverageModuleV2 } from "../interfaces/IPerpV2LeverageModuleV2.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; import { PerpV2Positions } from "../protocol/integration/lib/PerpV2Positions.sol"; import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; @@ -39,7 +39,7 @@ import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; * @author Set Protocol * * PerpV2LeverageModuleViewer enables queries of information regarding open PerpV2 positions - * specifically for leverage ratios and issuance maximums. + * specifically for leverage ratios and issuance maximums. */ contract PerpV2LeverageModuleViewer { using SafeCast for int256; @@ -61,7 +61,7 @@ contract PerpV2LeverageModuleViewer { /* ============ State Variables ============ */ - IPerpV2LeverageModule public immutable perpModule; // PerpV2LeverageModule instance + IPerpV2LeverageModuleV2 public immutable perpModule; // PerpV2LeverageModule instance IAccountBalance public immutable perpAccountBalance; // Perp's Account Balance contract IClearingHouseConfig public immutable perpClearingHouseConfig; // PerpV2's ClearingHouseConfig contract ERC20 public immutable vQuoteToken; // Virtual Quote asset for PerpV2 (vUSDC) @@ -78,7 +78,7 @@ contract PerpV2LeverageModuleViewer { * @param _vQuoteToken Address of virtual Quote asset for PerpV2 (vUSDC) */ constructor( - IPerpV2LeverageModule _perpModule, + IPerpV2LeverageModuleV2 _perpModule, IAccountBalance _perpAccountBalance, IClearingHouseConfig _perpClearingHouseConfig, ERC20 _vQuoteToken @@ -103,7 +103,7 @@ contract PerpV2LeverageModuleViewer { * We want to find the point where freeCollateral = 0 after all trades have been executed. * freeCollateral = 0 => totalDebt = min(totalCollateral, accountValue) / initialMarginRatio * and, availableDebt = totalDebt - currentDebt - * + * * Now, accountValue = totalCollateral + unrealizedPnl * if unrealizedPnl >=0: * min(totalCollateral, accountValue) = totalCollateral @@ -113,7 +113,7 @@ contract PerpV2LeverageModuleViewer { * availableDebt = ((totalCollateral + unrealizedPnl) / imRatio) - currentDebt * * We also know that any slippage gets accrued to unrealizedPnl BEFORE any new collateral is being deposited so - * we need to account for our expected slippage accrual impact on accountValue by subtracting our expected amount + * we need to account for our expected slippage accrual impact on accountValue by subtracting our expected amount * of slippage divided by the imRatio from the availableDebt. We can then divide the availableDebtWithSlippage by * the absolute value of our current position and multiply by our totalSupply to get the max issue amount. * @@ -162,7 +162,7 @@ contract PerpV2LeverageModuleViewer { /** * @dev Returns relevant data for displaying current positions. Identifying info for each position plus current * size, index price, and leverage of each vAsset with an open position is returned. The sum quantity of vUSDC - * is returned along with identifying info in last index of array. + * is returned along with identifying info in last index of array. * * @param _setToken Instance of SetToken * @@ -217,7 +217,7 @@ contract PerpV2LeverageModuleViewer { * @return Total collateral value attributed to SetToken */ function _calculateTotalCollateralValue(ISetToken _setToken) internal view returns (int256) { - IPerpV2LeverageModule.AccountInfo memory accountInfo = perpModule.getAccountInfo(_setToken); + IPerpV2LeverageModuleV2.AccountInfo memory accountInfo = perpModule.getAccountInfo(_setToken); return accountInfo.collateralBalance .add(accountInfo.owedRealizedPnl) From 150aa5b8a59527f95cb0d87f6099c77031c491e2 Mon Sep 17 00:00:00 2001 From: 0xSachinK Date: Mon, 28 Mar 2022 21:38:49 +0530 Subject: [PATCH 5/5] Remove unncessary imports --- contracts/interfaces/IPerpV2BasisTradingModule.sol | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/contracts/interfaces/IPerpV2BasisTradingModule.sol b/contracts/interfaces/IPerpV2BasisTradingModule.sol index 5ea69803d..4c0f89400 100644 --- a/contracts/interfaces/IPerpV2BasisTradingModule.sol +++ b/contracts/interfaces/IPerpV2BasisTradingModule.sol @@ -20,17 +20,8 @@ pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import { ISetToken } from "./ISetToken.sol"; -import { IDebtIssuanceModule } from "./IDebtIssuanceModule.sol"; -import { IAccountBalance } from "./external/perp-v2/IAccountBalance.sol"; -import { IClearingHouse } from "./external/perp-v2/IClearingHouse.sol"; -import { IExchange } from "./external/perp-v2/IExchange.sol"; -import { IVault } from "./external/perp-v2/IVault.sol"; -import { IQuoter } from "./external/perp-v2/IQuoter.sol"; -import { IMarketRegistry } from "./external/perp-v2/IMarketRegistry.sol"; -import { PerpV2Positions } from "../protocol/integration/lib/PerpV2Positions.sol"; - import { IPerpV2LeverageModuleV2 } from "./IPerpV2LeverageModuleV2.sol"; +import { ISetToken } from "./ISetToken.sol"; /** * @title IPerpV2BasisTradingModule