diff --git a/cadence/contracts/FlowYieldVaults.cdc b/cadence/contracts/FlowYieldVaults.cdc index d455eb99..4ac04d42 100644 --- a/cadence/contracts/FlowYieldVaults.cdc +++ b/cadence/contracts/FlowYieldVaults.cdc @@ -153,6 +153,10 @@ access(all) contract FlowYieldVaults { "Invalid Vault returns - requests \(ofToken.identifier) but returned \(result.getType().identifier)" } } + /// Closes the underlying position by repaying all debt and returning all collateral. + /// This method uses the AutoBalancer as a repayment source to swap yield tokens to debt tokens as needed. + /// Returns a Vault containing all collateral including any dust residuals. + access(FungibleToken.Withdraw) fun closePosition(collateralType: Type): @{FungibleToken.Vault} } /// StrategyComposer @@ -414,6 +418,23 @@ access(all) contract FlowYieldVaults { return <- res } + /// Closes the YieldVault by repaying all debt on the underlying position and returning all collateral. + /// This method properly closes the FlowALP position by using the AutoBalancer to swap yield tokens + /// to MOET for debt repayment, then returns all collateral including any dust residuals. + access(FungibleToken.Withdraw) fun close(): @{FungibleToken.Vault} { + let collateral <- self._borrowStrategy().closePosition(collateralType: self.vaultType) + + emit WithdrawnFromYieldVault( + id: self.uniqueID.id, + strategyType: self.getStrategyType(), + tokenType: collateral.getType().identifier, + amount: collateral.balance, + owner: self.owner?.address, + toUUID: collateral.uuid + ) + + return <- collateral + } /// Returns an authorized reference to the encapsulated Strategy access(self) view fun _borrowStrategy(): auth(FungibleToken.Withdraw) &{Strategy} { return &self.strategy as auth(FungibleToken.Withdraw) &{Strategy}? @@ -539,8 +560,9 @@ access(all) contract FlowYieldVaults { let yieldVault = (&self.yieldVaults[id] as auth(FungibleToken.Withdraw) &YieldVault?)! return <- yieldVault.withdraw(amount: amount) } - /// Withdraws and returns all available funds from the specified YieldVault, destroying the YieldVault and access to any - /// Strategy-related wiring with it + /// Closes the YieldVault by repaying all debt and returning all collateral, then destroys the YieldVault. + /// This properly closes the underlying FlowALP position by using the AutoBalancer to swap yield tokens + /// to MOET for debt repayment, ensuring all collateral (including dust) is returned to the caller. access(FungibleToken.Withdraw) fun closeYieldVault(_ id: UInt64): @{FungibleToken.Vault} { pre { self.yieldVaults[id] != nil: @@ -548,7 +570,7 @@ access(all) contract FlowYieldVaults { } let yieldVault <- self._withdrawYieldVault(id: id) - let res <- yieldVault.withdraw(amount: yieldVault.getYieldVaultBalance()) + let res <- yieldVault.close() Burner.burn(<-yieldVault) return <-res } diff --git a/cadence/contracts/FlowYieldVaultsAutoBalancers.cdc b/cadence/contracts/FlowYieldVaultsAutoBalancers.cdc index 5e127d57..8748dd8e 100644 --- a/cadence/contracts/FlowYieldVaultsAutoBalancers.cdc +++ b/cadence/contracts/FlowYieldVaultsAutoBalancers.cdc @@ -44,6 +44,20 @@ access(all) contract FlowYieldVaultsAutoBalancers { return self.account.capabilities.borrow<&DeFiActions.AutoBalancer>(publicPath) } + /// Creates a source from an AutoBalancer for external use (e.g., position close operations). + /// This allows bypassing position topUpSource to avoid circular dependency issues. + /// + /// @param id: The yield vault/AutoBalancer ID + /// @return Source that can withdraw from the AutoBalancer, or nil if not found + /// + access(account) fun createExternalSource(id: UInt64): {DeFiActions.Source}? { + let storagePath = self.deriveAutoBalancerPath(id: id, storage: true) as! StoragePath + if let autoBalancer = self.account.storage.borrow(from: storagePath) { + return autoBalancer.createBalancerSource() + } + return nil + } + /// Checks if an AutoBalancer has at least one active (Scheduled) transaction. /// Used by Supervisor to detect stuck yield vaults that need recovery. /// diff --git a/cadence/contracts/FlowYieldVaultsStrategiesV2.cdc b/cadence/contracts/FlowYieldVaultsStrategiesV2.cdc index 05f61355..7ee81669 100644 --- a/cadence/contracts/FlowYieldVaultsStrategiesV2.cdc +++ b/cadence/contracts/FlowYieldVaultsStrategiesV2.cdc @@ -42,7 +42,7 @@ access(all) contract FlowYieldVaultsStrategiesV2 { access(all) let univ3RouterEVMAddress: EVM.EVMAddress access(all) let univ3QuoterEVMAddress: EVM.EVMAddress - access(all) let config: {String: AnyStruct} + access(contract) let config: {String: AnyStruct} /// Canonical StoragePath where the StrategyComposerIssuer should be stored access(all) let IssuerStoragePath: StoragePath @@ -72,7 +72,11 @@ access(all) contract FlowYieldVaultsStrategiesV2 { } } - /// This strategy uses FUSDEV vault + /// This strategy uses FUSDEV vault (Morpho ERC4626). + /// Deposits collateral into a single FlowALP position, borrowing MOET as debt. + /// MOET is swapped to PYUSD0 and deposited into the Morpho FUSDEV ERC4626 vault. + /// Each strategy instance holds exactly one collateral type and one debt type (MOET). + /// PYUSD0 (the FUSDEV vault's underlying asset) cannot be used as collateral. access(all) resource FUSDEVStrategy : FlowYieldVaults.Strategy, DeFiActions.IdentifiableResource { /// An optional identifier allowing protocols to identify stacked connector operations by defining a protocol- /// specific Identifier to associated connectors on construction @@ -80,11 +84,20 @@ access(all) contract FlowYieldVaultsStrategiesV2 { access(self) let position: @FlowALPv0.Position access(self) var sink: {DeFiActions.Sink} access(self) var source: {DeFiActions.Source} + /// Tracks whether the underlying FlowALP position has been closed. Once true, + /// availableBalance() returns 0.0 to avoid panicking when the pool no longer + /// holds the position (e.g. during YieldVault burnCallback after close). + access(self) var positionClosed: Bool - init(id: DeFiActions.UniqueIdentifier, collateralType: Type, position: @FlowALPv0.Position) { + init( + id: DeFiActions.UniqueIdentifier, + collateralType: Type, + position: @FlowALPv0.Position + ) { self.uniqueID = id self.sink = position.createSink(type: collateralType) self.source = position.createSourceWithOptions(type: collateralType, pullFromTopUpSource: true) + self.positionClosed = false self.position <-position } @@ -96,10 +109,16 @@ access(all) contract FlowYieldVaultsStrategiesV2 { } /// Returns the amount available for withdrawal via the inner Source access(all) fun availableBalance(ofToken: Type): UFix64 { + if self.positionClosed { return 0.0 } return ofToken == self.source.getSourceType() ? self.source.minimumAvailable() : 0.0 } - /// Deposits up to the inner Sink's capacity from the provided authorized Vault reference + /// Deposits up to the inner Sink's capacity from the provided authorized Vault reference. + /// Only the single configured collateral type is accepted — one collateral type per position. access(all) fun deposit(from: auth(FungibleToken.Withdraw) &{FungibleToken.Vault}) { + pre { + from.getType() == self.sink.getSinkType(): + "FUSDEVStrategy position only accepts \(self.sink.getSinkType().identifier) as collateral, got \(from.getType().identifier)" + } self.sink.depositCapacity(from: from) } /// Withdraws up to the max amount, returning the withdrawn Vault. If the requested token type is unsupported, @@ -110,6 +129,118 @@ access(all) contract FlowYieldVaultsStrategiesV2 { } return <- self.source.withdrawAvailable(maxAmount: maxAmount) } + /// Closes the underlying FlowALP position by preparing repayment funds and closing with them. + /// + /// This method: + /// 1. Calculates debt amount from position + /// 2. Creates external yield token source from AutoBalancer + /// 3. Swaps yield tokens → MOET via stored swapper + /// 4. Closes position with prepared MOET vault + /// + /// This approach eliminates circular dependencies by preparing all funds externally + /// before calling the position's close method. + /// + access(FungibleToken.Withdraw) fun closePosition(collateralType: Type): @{FungibleToken.Vault} { + pre { + self.isSupportedCollateralType(collateralType): + "Unsupported collateral type \(collateralType.identifier)" + } + post { + result.getType() == collateralType: "Withdraw Vault (\(result.getType().identifier)) is not of a requested collateral type (\(collateralType.identifier))" + } + + // Step 1: Get debt amounts - returns {Type: UFix64} dictionary + let debtsByType = self.position.getTotalDebt() + + // Enforce: one debt type per position + assert( + debtsByType.length <= 1, + message: "FUSDEVStrategy position must have at most one debt type, found \(debtsByType.length)" + ) + + // Step 2: Calculate total debt amount + var totalDebtAmount: UFix64 = 0.0 + for debtAmount in debtsByType.values { + totalDebtAmount = totalDebtAmount + debtAmount + } + + // Step 3: If no debt, close with empty sources array + if totalDebtAmount == 0.0 { + let resultVaults <- self.position.closePosition( + repaymentSources: [] + ) + // With one collateral type and no debt the pool returns at most one vault. + // Zero vaults is possible when the collateral balance is dust that rounds down + // to zero (e.g. drawDownSink had no capacity, or token reserves were empty). + assert( + resultVaults.length <= 1, + message: "Expected 0 or 1 collateral vault from closePosition, got \(resultVaults.length)" + ) + // Zero vaults: dust collateral rounded down to zero — return an empty vault + if resultVaults.length == 0 { + destroy resultVaults + self.positionClosed = true + return <- DeFiActionsUtils.getEmptyVault(collateralType) + } + let collateralVault <- resultVaults.removeFirst() + destroy resultVaults + self.positionClosed = true + return <- collateralVault + } + + // Step 4: Create external yield token source from AutoBalancer + let yieldTokenSource = FlowYieldVaultsAutoBalancers.createExternalSource(id: self.id()!) + ?? panic("Could not create external source from AutoBalancer") + + // Step 5: Retrieve yield→MOET swapper from contract config + let swapperKey = FlowYieldVaultsStrategiesV2.getYieldToMoetSwapperConfigKey(self.uniqueID)! + let yieldToMoetSwapper = FlowYieldVaultsStrategiesV2.config[swapperKey] as! {DeFiActions.Swapper}? + ?? panic("No yield→MOET swapper found for strategy \(self.id()!)") + + // Step 6: Create a SwapSource that converts yield tokens to MOET when pulled by closePosition. + // The pool will call source.withdrawAvailable(maxAmount: debtAmount) which internally uses + // quoteIn(forDesired: debtAmount) to compute the exact yield token input needed. + let moetSource = SwapConnectors.SwapSource( + swapper: yieldToMoetSwapper, + source: yieldTokenSource, + uniqueID: self.copyID() + ) + + // Step 7: Close position - pool pulls exactly the debt amount from moetSource + let resultVaults <- self.position.closePosition(repaymentSources: [moetSource]) + + // With one collateral type and one debt type, the pool returns at most two vaults: + // the collateral vault and optionally a MOET overpayment dust vault. + assert( + resultVaults.length >= 1 && resultVaults.length <= 2, + message: "Expected 1 or 2 vaults from closePosition, got \(resultVaults.length)" + ) + + var collateralVault <- resultVaults.removeFirst() + assert( + collateralVault.getType() == collateralType, + message: "First vault returned from closePosition must be collateral (\(collateralType.identifier)), got \(collateralVault.getType().identifier)" + ) + + // Handle any overpayment dust (MOET) returned as the second vault + while resultVaults.length > 0 { + let dustVault <- resultVaults.removeFirst() + if dustVault.balance > 0.0 { + if dustVault.getType() == collateralType { + collateralVault.deposit(from: <-dustVault) + } else { + // @TODO implement swapping moet to collateral + destroy dustVault + } + } else { + destroy dustVault + } + } + + destroy resultVaults + self.positionClosed = true + return <- collateralVault + } /// Executed when a Strategy is burned, cleaning up the Strategy's stored AutoBalancer access(contract) fun burnCallback() { FlowYieldVaultsAutoBalancers._cleanupAutoBalancer(id: self.id()!) @@ -301,9 +432,46 @@ access(all) contract FlowYieldVaultsStrategiesV2 { uniqueID: uniqueID ) + // pullFromTopUpSource: false ensures Position maintains health buffer + // This prevents Position from being pushed to minHealth (1.1) limit + let positionSource = position.createSourceWithOptions( + type: collateralType, + pullFromTopUpSource: false // ← CONSERVATIVE: maintain safety buffer + ) + + // Create Collateral -> Yield swapper (reverse of yieldToCollateralSwapper) + // Allows AutoBalancer to pull collateral, swap to yield token + let collateralToYieldSwapper = self._createCollateralToYieldSwapper( + collateralConfig: collateralConfig, + yieldTokenEVMAddress: tokens.yieldTokenEVMAddress, + yieldTokenType: tokens.yieldTokenType, + collateralType: collateralType, + uniqueID: uniqueID + ) + + // Create Position swap source for AutoBalancer deficit recovery + // When AutoBalancer value drops below deposits, pulls collateral from Position + let positionSwapSource = SwapConnectors.SwapSource( + swapper: collateralToYieldSwapper, + source: positionSource, + uniqueID: uniqueID + ) + // Set AutoBalancer sink for overflow -> recollateralize balancerIO.autoBalancer.setSink(positionSwapSink, updateSinkID: true) + // Set AutoBalancer source for deficit recovery -> pull from Position + balancerIO.autoBalancer.setSource(positionSwapSource, updateSourceID: true) + + // Store yield→MOET swapper in contract config for later access during closePosition + let yieldToMoetSwapperKey = FlowYieldVaultsStrategiesV2.getYieldToMoetSwapperConfigKey(uniqueID)! + FlowYieldVaultsStrategiesV2.config[yieldToMoetSwapperKey] = yieldToMoetSwapper + + // @TODO implement moet to collateral swapper + // let moetToCollateralSwapperKey = FlowYieldVaultsStrategiesV2.getMoetToCollateralSwapperConfigKey(uniqueID) + // + // FlowYieldVaultsStrategiesV2.config[moetToCollateralSwapperKey] = moetToCollateralSwapper + // switch type { case Type<@FUSDEVStrategy>(): return <-create FUSDEVStrategy( @@ -514,6 +682,16 @@ access(all) contract FlowYieldVaultsStrategiesV2 { } } + /// @TODO + /// implement moet to collateral swapper + // access(self) fun _createMoetToCollateralSwapper( + // strategyType: Type, + // tokens: FlowYieldVaultsStrategiesV2.TokenBundle, + // uniqueID: DeFiActions.UniqueIdentifier + // ): SwapConnectors.MultiSwapper { + // // Direct MOET -> underlying via AMM + // } + access(self) fun _initAutoBalancerAndIO( oracle: {DeFiActions.PriceOracle}, yieldTokenType: Type, @@ -595,6 +773,40 @@ access(all) contract FlowYieldVaultsStrategiesV2 { uniqueID: uniqueID ) } + + /// Creates a Collateral -> Yield token swapper using UniswapV3 + /// This is the REVERSE of _createYieldToCollateralSwapper + /// Used by AutoBalancer to pull collateral from Position and swap to yield tokens + /// + access(self) fun _createCollateralToYieldSwapper( + collateralConfig: FlowYieldVaultsStrategiesV2.CollateralConfig, + yieldTokenEVMAddress: EVM.EVMAddress, + yieldTokenType: Type, + collateralType: Type, + uniqueID: DeFiActions.UniqueIdentifier + ): UniswapV3SwapConnectors.Swapper { + // Reverse the swap path: collateral -> yield (opposite of yield -> collateral) + let forwardPath = collateralConfig.yieldToCollateralUniV3AddressPath + let reversedTokenPath = forwardPath.reverse() + + // Reverse the fee path as well + let forwardFees = collateralConfig.yieldToCollateralUniV3FeePath + let reversedFeePath = forwardFees.reverse() + + // Verify the reversed path starts with collateral (ends with yield) + assert( + reversedTokenPath[reversedTokenPath.length - 1].equals(yieldTokenEVMAddress), + message: "Reversed path must end with yield token \(yieldTokenEVMAddress.toString())" + ) + + return self._createUniV3Swapper( + tokenPath: reversedTokenPath, + feePath: reversedFeePath, + inVault: collateralType, // ← Input is collateral + outVault: yieldTokenType, // ← Output is yield token + uniqueID: uniqueID + ) + } } access(all) entitlement Configure @@ -810,6 +1022,20 @@ access(all) contract FlowYieldVaultsStrategiesV2 { ) } + access(self) view fun getYieldToMoetSwapperConfigKey(_ uniqueID: DeFiActions.UniqueIdentifier?): String { + pre { + uniqueID != nil: "Missing UniqueIdentifier for swapper config key" + } + return "yieldToMoetSwapper_\(uniqueID!.id.toString())" + } + + access(self) view fun getMoetToCollateralSwapperConfigKey(_ uniqueID: DeFiActions.UniqueIdentifier?): String { + pre { + uniqueID != nil: "Missing UniqueIdentifier for swapper config key" + } + return "moetToCollateralSwapper_\(uniqueID!.id.toString())" + } + init( univ3FactoryEVMAddress: String, univ3RouterEVMAddress: String, diff --git a/cadence/contracts/PMStrategiesV1.cdc b/cadence/contracts/PMStrategiesV1.cdc index 366e5878..cd994d09 100644 --- a/cadence/contracts/PMStrategiesV1.cdc +++ b/cadence/contracts/PMStrategiesV1.cdc @@ -85,6 +85,16 @@ access(all) contract PMStrategiesV1 { } return <- self.source.withdrawAvailable(maxAmount: maxAmount) } + /// Closes the position by withdrawing all available collateral. + /// For simple strategies without FlowALP positions, this just withdraws all available balance. + access(FungibleToken.Withdraw) fun closePosition(collateralType: Type): @{FungibleToken.Vault} { + pre { + self.isSupportedCollateralType(collateralType): + "Unsupported collateral type \(collateralType.identifier)" + } + let availableBalance = self.availableBalance(ofToken: collateralType) + return <- self.withdraw(maxAmount: availableBalance, ofToken: collateralType) + } /// Executed when a Strategy is burned, cleaning up the Strategy's stored AutoBalancer access(contract) fun burnCallback() { FlowYieldVaultsAutoBalancers._cleanupAutoBalancer(id: self.id()!) @@ -150,6 +160,16 @@ access(all) contract PMStrategiesV1 { } return <- self.source.withdrawAvailable(maxAmount: maxAmount) } + /// Closes the position by withdrawing all available collateral. + /// For simple strategies without FlowALP positions, this just withdraws all available balance. + access(FungibleToken.Withdraw) fun closePosition(collateralType: Type): @{FungibleToken.Vault} { + pre { + self.isSupportedCollateralType(collateralType): + "Unsupported collateral type \(collateralType.identifier)" + } + let availableBalance = self.availableBalance(ofToken: collateralType) + return <- self.withdraw(maxAmount: availableBalance, ofToken: collateralType) + } /// Executed when a Strategy is burned, cleaning up the Strategy's stored AutoBalancer access(contract) fun burnCallback() { FlowYieldVaultsAutoBalancers._cleanupAutoBalancer(id: self.id()!) @@ -215,6 +235,16 @@ access(all) contract PMStrategiesV1 { } return <- self.source.withdrawAvailable(maxAmount: maxAmount) } + /// Closes the position by withdrawing all available collateral. + /// For simple strategies without FlowALP positions, this just withdraws all available balance. + access(FungibleToken.Withdraw) fun closePosition(collateralType: Type): @{FungibleToken.Vault} { + pre { + self.isSupportedCollateralType(collateralType): + "Unsupported collateral type \(collateralType.identifier)" + } + let availableBalance = self.availableBalance(ofToken: collateralType) + return <- self.withdraw(maxAmount: availableBalance, ofToken: collateralType) + } /// Executed when a Strategy is burned, cleaning up the Strategy's stored AutoBalancer access(contract) fun burnCallback() { FlowYieldVaultsAutoBalancers._cleanupAutoBalancer(id: self.id()!) diff --git a/cadence/contracts/mocks/MockFlowALPConsumer.cdc b/cadence/contracts/mocks/MockFlowALPConsumer.cdc index fb396eeb..7dd49271 100644 --- a/cadence/contracts/mocks/MockFlowALPConsumer.cdc +++ b/cadence/contracts/mocks/MockFlowALPConsumer.cdc @@ -14,7 +14,8 @@ access(all) contract MockFlowALPConsumer { /// Canonical path for where the wrapper is to be stored access(all) let WrapperStoragePath: StoragePath - /// Opens a FlowALP Position and returns a PositionWrapper containing that new position + /// Opens a FlowALP Position and returns a PositionWrapper containing that new position. + /// Requires a pool capability stored at FlowALPv0.PoolCapStoragePath in this contract's account. /// access(all) fun createPositionWrapper( @@ -23,23 +24,27 @@ access(all) contract MockFlowALPConsumer { repaymentSource: {DeFiActions.Source}?, pushToDrawDownSink: Bool ): @PositionWrapper { - return <- create PositionWrapper( - position: FlowALPv0.openPosition( - collateral: <-collateral, - issuanceSink: issuanceSink, - repaymentSource: repaymentSource, - pushToDrawDownSink: pushToDrawDownSink - ) + let poolCap = MockFlowALPConsumer.account.storage.load>( + from: FlowALPv0.PoolCapStoragePath + ) ?? panic("Missing pool capability - ensure MockFlowALPConsumer account has a pool capability stored at FlowALPv0.PoolCapStoragePath") + let poolRef = poolCap.borrow() ?? panic("Invalid Pool Capability") + let position <- poolRef.createPosition( + funds: <-collateral, + issuanceSink: issuanceSink, + repaymentSource: repaymentSource, + pushToDrawDownSink: pushToDrawDownSink ) + MockFlowALPConsumer.account.storage.save(poolCap, to: FlowALPv0.PoolCapStoragePath) + return <- create PositionWrapper(position: <-position) } /// A simple resource encapsulating a FlowALP Position access(all) resource PositionWrapper { - access(self) let position: FlowALPv0.Position + access(self) let position: @FlowALPv0.Position - init(position: FlowALPv0.Position) { - self.position = position + init(position: @FlowALPv0.Position) { + self.position <- position } /// NOT SAFE FOR PRODUCTION diff --git a/cadence/contracts/mocks/MockStrategies.cdc b/cadence/contracts/mocks/MockStrategies.cdc index 84fbdcc1..0ec49b14 100644 --- a/cadence/contracts/mocks/MockStrategies.cdc +++ b/cadence/contracts/mocks/MockStrategies.cdc @@ -52,11 +52,16 @@ access(all) contract MockStrategies { access(self) let position: @FlowALPv0.Position access(self) var sink: {DeFiActions.Sink} access(self) var source: {DeFiActions.Source} + /// Tracks whether the underlying FlowALP position has been closed. Once true, + /// availableBalance() returns 0.0 to avoid panicking when the pool no longer + /// holds the position (e.g. during YieldVault burnCallback after close). + access(self) var positionClosed: Bool init(id: DeFiActions.UniqueIdentifier, collateralType: Type, position: @FlowALPv0.Position) { self.uniqueID = id self.sink = position.createSink(type: collateralType) self.source = position.createSourceWithOptions(type: collateralType, pullFromTopUpSource: true) + self.positionClosed = false self.position <-position } @@ -68,6 +73,7 @@ access(all) contract MockStrategies { } /// Returns the amount available for withdrawal via the inner Source access(all) fun availableBalance(ofToken: Type): UFix64 { + if self.positionClosed { return 0.0 } return ofToken == self.source.getSourceType() ? self.source.minimumAvailable() : 0.0 } /// Deposits up to the inner Sink's capacity from the provided authorized Vault reference @@ -82,6 +88,152 @@ access(all) contract MockStrategies { } return <- self.source.withdrawAvailable(maxAmount: maxAmount) } + /// Closes the underlying FlowALP position by preparing repayment funds and closing with them. + /// + /// This method: + /// 1. Calculates debt amount from position + /// 2. Withdraws YT from AutoBalancer + /// 3. Swaps YT → MOET via external swapper + /// 4. Closes position with prepared MOET vault + /// + /// This approach eliminates circular dependencies by preparing all funds externally + /// before calling the position's close method. + /// + access(FungibleToken.Withdraw) fun closePosition(collateralType: Type): @{FungibleToken.Vault} { + pre { + self.isSupportedCollateralType(collateralType): + "Unsupported collateral type \(collateralType.identifier)" + } + + // Step 1: Get debt amounts from position - returns {Type: UFix64} dictionary + let debtsByType = self.position.getTotalDebt() + + // Step 2: Calculate total debt amount across all debt types + var totalDebtAmount: UFix64 = 0.0 + for debtAmount in debtsByType.values { + totalDebtAmount = totalDebtAmount + debtAmount + } + + // Step 3: If no debt, close with empty sources array + if totalDebtAmount == 0.0 { + let resultVaults <- self.position.closePosition( + repaymentSources: [] + ) + // Extract the first vault (should be collateral) + assert(resultVaults.length > 0, message: "No vaults returned from closePosition") + let collateralVault <- resultVaults.removeFirst() + destroy resultVaults + return <- collateralVault + } + + // Step 4: Create external YT source from AutoBalancer + let ytSource = FlowYieldVaultsAutoBalancers.createExternalSource(id: self.id()!) + ?? panic("Could not create external source from AutoBalancer") + let ytType = Type<@YieldToken.Vault>() + + // Step 5: Build one repayment source per debt type. + // If the debt token is the same as YT, use ytSource directly (no swap needed). + // Otherwise, use MockSwapper.quoteIn to pre-swap YT → debt token and wrap in a VaultSource. + // Pre-swapping with quoteIn guarantees the exact debt amount is delivered to the pool. + var repaymentSources: [{DeFiActions.Source}] = [] + var debtCaps: [Capability] = [] + var debtPaths: [StoragePath] = [] + + for debtType in debtsByType.keys { + let debtAmount = debtsByType[debtType]! + let swapper = MockSwapper.Swapper(inVault: ytType, outVault: debtType, uniqueID: self.copyID()!) + let ytAvailable = ytSource.minimumAvailable() + let ytNeededQuote = swapper.quoteIn(forDesired: debtAmount, reverse: false) + + let debtVault <- DeFiActionsUtils.getEmptyVault(debtType) + if ytAvailable >= ytNeededQuote.inAmount { + // Sufficient YT: quoteIn guarantees exactly debtAmount out + let ytPortion <- ytSource.withdrawAvailable(maxAmount: ytNeededQuote.inAmount) + debtVault.deposit(from: <-swapper.swap(quote: ytNeededQuote, inVault: <-ytPortion)) + } else { + // Insufficient YT: swap all available YT, then cover shortfall from collateral + let ytAllQuote = swapper.quoteOut(forProvided: ytAvailable, reverse: false) + let ytPortion <- ytSource.withdrawAvailable(maxAmount: ytAvailable) + debtVault.deposit(from: <-swapper.swap(quote: ytAllQuote, inVault: <-ytPortion)) + let shortfall = debtAmount - debtVault.balance + if shortfall > 0.0 { + let collateralToDebtSwapper = MockSwapper.Swapper( + inVault: collateralType, outVault: debtType, uniqueID: self.copyID()!) + let collateralQuote = collateralToDebtSwapper.quoteIn(forDesired: shortfall, reverse: false) + let collateralForDebt <- self.source.withdrawAvailable(maxAmount: collateralQuote.inAmount) + debtVault.deposit(from: <-collateralToDebtSwapper.swap(quote: collateralQuote, inVault: <-collateralForDebt)) + } + } + + let debtTempPath = StoragePath(identifier: "mockCloseDebt_\(self.uuid)_\(debtType.identifier)")! + MockStrategies.account.storage.save(<-debtVault, to: debtTempPath) + let debtCap = MockStrategies.account.capabilities.storage.issue(debtTempPath) + repaymentSources.append(FungibleTokenConnectors.VaultSource(min: nil, withdrawVault: debtCap, uniqueID: nil)) + debtCaps.append(debtCap) + debtPaths.append(debtTempPath) + } + + // Step 6: Close position - pool pulls each debt type's exact amount from its source + let resultVaults <- self.position.closePosition(repaymentSources: repaymentSources) + + // Step 7: Extract collateral vault (first returned vault) and optional overpayment vault(s) + assert(resultVaults.length > 0, message: "No vaults returned from closePosition") + var collateralVault <- resultVaults.removeFirst() + assert( + collateralVault.getType() == collateralType, + message: "First vault returned from closePosition must be collateral (\(collateralType.identifier)), got \(collateralVault.getType().identifier)" + ) + + // Step 8: Recover any remaining YT from the AutoBalancer and swap back to collateral + let remainingYtAmount = ytSource.minimumAvailable() + if remainingYtAmount > 0.0 { + let remainingYt <- ytSource.withdrawAvailable(maxAmount: remainingYtAmount) + let ytToCollateralSwapper = MockSwapper.Swapper( + inVault: ytType, + outVault: collateralType, + uniqueID: self.copyID()! + ) + collateralVault.deposit(from: <-ytToCollateralSwapper.swap(quote: nil, inVault: <-remainingYt)) + } + + // Step 9: Recover any un-consumed balance from pre-swapped debt temp vaults, then + // remove the now-empty vaults from storage to avoid accumulating stale state. + var capIdx = 0 + while capIdx < debtCaps.length { + let debtRef = debtCaps[capIdx].borrow()! + let remaining = debtRef.balance + if remaining > 0.0 { + let remainingDebt <- debtRef.withdraw(amount: remaining) + let swapper = MockSwapper.Swapper( + inVault: remainingDebt.getType(), + outVault: collateralType, + uniqueID: self.copyID()! + ) + collateralVault.deposit(from: <-swapper.swap(quote: nil, inVault: <-remainingDebt)) + } + destroy MockStrategies.account.storage.load<@{FungibleToken.Vault}>(from: debtPaths[capIdx])! + capIdx = capIdx + 1 + } + + // Step 10: Handle any additional vaults returned by closePosition (overpayments) + while resultVaults.length > 0 { + let dustVault <- resultVaults.removeFirst() + if dustVault.balance > 0.0 && dustVault.getType() != collateralType { + let dustToCollateralSwapper = MockSwapper.Swapper( + inVault: dustVault.getType(), + outVault: collateralType, + uniqueID: self.copyID()! + ) + collateralVault.deposit(from: <-dustToCollateralSwapper.swap(quote: nil, inVault: <-dustVault)) + } else { + destroy dustVault + } + } + + destroy resultVaults + self.positionClosed = true + return <- collateralVault + } /// Executed when a Strategy is burned, cleaning up the Strategy's stored AutoBalancer access(contract) fun burnCallback() { FlowYieldVaultsAutoBalancers._cleanupAutoBalancer(id: self.id()!) @@ -204,10 +356,23 @@ access(all) contract MockStrategies { // allows for YieldToken to be deposited to the Position let positionSwapSink = SwapConnectors.SwapSink(swapper: yieldToFlowSwapper, sink: positionSink, uniqueID: uniqueID) + // init FLOW -> YieldToken Swapper (reverse of yieldToFlowSwapper) + let flowToYieldSwapper = MockSwapper.Swapper( + inVault: collateralType, + outVault: yieldTokenType, + uniqueID: uniqueID + ) + // allows AutoBalancer to pull FLOW from Position and swap to YieldToken + let positionSwapSource = SwapConnectors.SwapSource(swapper: flowToYieldSwapper, source: positionSource, uniqueID: uniqueID) + // set the AutoBalancer's rebalance Sink which it will use to deposit overflown value, // recollateralizing the position autoBalancer.setSink(positionSwapSink, updateSinkID: true) + // set the AutoBalancer's rebalance Source which it will use to pull funds when value drops below deposits, + // pulling FLOW from the position and swapping to YieldToken + autoBalancer.setSource(positionSwapSource, updateSourceID: true) + // Use the same uniqueID passed to createStrategy so Strategy.burnCallback // calls _cleanupAutoBalancer with the correct ID return <-create TracerStrategy( diff --git a/cadence/contracts/mocks/MockStrategy.cdc b/cadence/contracts/mocks/MockStrategy.cdc index 267055e1..a60dfabf 100644 --- a/cadence/contracts/mocks/MockStrategy.cdc +++ b/cadence/contracts/mocks/MockStrategy.cdc @@ -111,6 +111,17 @@ access(all) contract MockStrategy { return <- self.source.withdrawAvailable(maxAmount: maxAmount) } + /// Closes the position by withdrawing all available collateral. + /// For simple mock strategies without FlowALP positions, this just withdraws all available balance. + access(FungibleToken.Withdraw) fun closePosition(collateralType: Type): @{FungibleToken.Vault} { + pre { + self.isSupportedCollateralType(collateralType): + "Unsupported collateral type \(collateralType.identifier)" + } + let availableBalance = self.availableBalance(ofToken: collateralType) + return <- self.withdraw(maxAmount: availableBalance, ofToken: collateralType) + } + access(contract) fun burnCallback() {} // no-op access(all) fun getComponentInfo(): DeFiActions.ComponentInfo { diff --git a/cadence/contracts/mocks/MockSwapper.cdc b/cadence/contracts/mocks/MockSwapper.cdc index 99ed06d4..e7861a45 100644 --- a/cadence/contracts/mocks/MockSwapper.cdc +++ b/cadence/contracts/mocks/MockSwapper.cdc @@ -75,7 +75,7 @@ access(all) contract MockSwapper { /// NOTE: This mock sources pricing data from the mocked oracle, allowing for pricing to be manually manipulated /// for testing and demonstration purposes access(all) fun swap(quote: {DeFiActions.Quote}?, inVault: @{FungibleToken.Vault}): @{FungibleToken.Vault} { - return <- self._swap(<-inVault, reverse: false) + return <- self._swap(quote: quote, from: <-inVault, reverse: false) } /// Performs a swap taking a Vault of type outVault, outputting a resulting inVault. Implementations may choose @@ -84,7 +84,7 @@ access(all) contract MockSwapper { /// NOTE: This mock sources pricing data from the mocked oracle, allowing for pricing to be manually manipulated /// for testing and demonstration purposes access(all) fun swapBack(quote: {DeFiActions.Quote}?, residual: @{FungibleToken.Vault}): @{FungibleToken.Vault} { - return <- self._swap(<-residual, reverse: true) + return <- self._swap(quote: quote, from: <-residual, reverse: true) } /// Internal estimator returning a quote for the amount in/out and in the desired direction @@ -114,8 +114,17 @@ access(all) contract MockSwapper { let uintInAmount = out ? uintAmount : (uintAmount / uintPrice) let uintOutAmount = out ? uintAmount * uintPrice : uintAmount - let inAmount = FlowALPMath.toUFix64Round(uintInAmount) - let outAmount = FlowALPMath.toUFix64Round(uintOutAmount) + // Round conservatively based on what's being calculated: + // - quoteOut (out=true): Use banker's rounding for balance - quotes are estimates used for + // availability checks and shouldn't systematically underestimate (which causes wrong branch selection) + // - quoteIn (out=false): Round UP the calculated input to ensure we can deliver the desired output + // The provided/desired amounts stay as-is without additional rounding + let inAmount = out + ? amount // provided input, use as-is + : FlowALPMath.toUFix64RoundUp(uintInAmount) // calculated input, round up + let outAmount = out + ? FlowALPMath.toUFix64RoundDown(uintOutAmount) // calculated output, banker's rounding for balanced estimates + : amount // desired output, use as-is (caller specifies exactly what they want) return SwapConnectors.BasicQuote( inType: reverse ? self.outVault : self.inVault, @@ -125,13 +134,16 @@ access(all) contract MockSwapper { ) } - access(self) fun _swap(_ from: @{FungibleToken.Vault}, reverse: Bool): @{FungibleToken.Vault} { + access(self) fun _swap(quote: {DeFiActions.Quote}?, from: @{FungibleToken.Vault}, reverse: Bool): @{FungibleToken.Vault} { let inAmount = from.balance var swapInVault = reverse ? MockSwapper.liquidityConnectors[from.getType()]! : MockSwapper.liquidityConnectors[self.inType()]! var swapOutVault = reverse ? MockSwapper.liquidityConnectors[self.inType()]! : MockSwapper.liquidityConnectors[self.outType()]! - swapInVault.depositCapacity(from: &from as auth(FungibleToken.Withdraw) &{FungibleToken.Vault}) + swapInVault.depositCapacity(from: &from as auth(FungibleToken.Withdraw) &{FungibleToken.Vault}) Burner.burn(<-from) - let outAmount = self.quoteOut(forProvided: inAmount, reverse: reverse).outAmount + + // Use the provided quote's outAmount when available to honor quoteIn's guarantee + // quoteIn rounds UP the input to ensure we can deliver the promised output + let outAmount = quote?.outAmount ?? self.quoteOut(forProvided: inAmount, reverse: reverse).outAmount var outVault <- swapOutVault.withdrawAvailable(maxAmount: outAmount) assert(outVault.balance == outAmount, diff --git a/cadence/tests/PMStrategiesV1_test.cdc b/cadence/tests/PMStrategiesV1_FUSDEV_test.cdc similarity index 66% rename from cadence/tests/PMStrategiesV1_test.cdc rename to cadence/tests/PMStrategiesV1_FUSDEV_test.cdc index cc17d205..f1b549c6 100644 --- a/cadence/tests/PMStrategiesV1_test.cdc +++ b/cadence/tests/PMStrategiesV1_FUSDEV_test.cdc @@ -1,4 +1,4 @@ -#test_fork(network: "mainnet", height: nil) +#test_fork(network: "mainnet", height: 143600000) // Pinned: FUSDEV vault has liquidity issues after ~143650000 import Test @@ -8,22 +8,24 @@ import "FlowYieldVaults" import "PMStrategiesV1" import "FlowYieldVaultsClosedBeta" -/// Fork test for PMStrategiesV1 — validates the full YieldVault lifecycle (create, deposit, withdraw, close) -/// against real mainnet state using Morpho ERC4626 connectors. +/// Fork test for PMStrategiesV1 FUSDEV strategy — validates the full YieldVault lifecycle +/// (create, deposit, withdraw, close) against real mainnet state. /// /// This test: /// - Forks Flow mainnet to access real EVM state (Morpho vaults, UniswapV3 pools) -/// - Configures PMStrategiesV1 strategies for both syWFLOWv (FLOW collateral) and FUSDEV (PYUSD0 collateral) -/// - Tests the complete yield vault lifecycle through the strategy factory +/// - Configures PMStrategiesV1 FUSDEV strategy (PYUSD0 collateral -> FUSDEV Morpho ERC4626 vault) +/// - Tests the complete yield vault lifecycle /// - Validates Morpho ERC4626 swap connectors work with real vault contracts /// +/// NOTE: This test is pinned to fork height 143600000 because the Morpho FUSDEV vault +/// experienced liquidity/state issues after block ~143650000 that prevent share redemptions +/// (EVM error 306: execution reverted). This is a mainnet vault issue, not a code regression. +/// /// Mainnet addresses: /// - Admin (FlowYieldVaults deployer): 0xb1d63873c3cc9f79 /// - UniV3 Factory: 0xca6d7Bb03334bBf135902e1d919a5feccb461632 /// - UniV3 Router: 0xeEDC6Ff75e1b10B903D9013c358e446a73d35341 /// - UniV3 Quoter: 0x370A8DF17742867a44e56223EC20D82092242C85 -/// - WFLOW: 0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e -/// - syWFLOWv (More vault): 0xCBf9a7753F9D2d0e8141ebB36d99f87AcEf98597 /// - PYUSD0: 0x99aF3EeA856556646C98c8B9b2548Fe815240750 /// - FUSDEV (Morpho vault): 0xd069d989e2F44B70c65347d1853C0c67e10a9F8D @@ -37,11 +39,6 @@ access(all) let userAccount = Test.getAccount(0x443472749ebdaac8) // --- Strategy Config Constants --- -/// syWFLOWvStrategy: FLOW collateral -> syWFLOWv Morpho ERC4626 vault -access(all) let syWFLOWvStrategyIdentifier = "A.b1d63873c3cc9f79.PMStrategiesV1.syWFLOWvStrategy" -access(all) let flowVaultIdentifier = "A.1654653399040a61.FlowToken.Vault" -access(all) let syWFLOWvEVMAddress = "0xCBf9a7753F9D2d0e8141ebB36d99f87AcEf98597" - /// FUSDEVStrategy: PYUSD0 collateral -> FUSDEV Morpho ERC4626 vault access(all) let fusdEvStrategyIdentifier = "A.b1d63873c3cc9f79.PMStrategiesV1.FUSDEVStrategy" access(all) let pyusd0VaultIdentifier = "A.1e4aa0b87d10b141.EVMVMBridgedToken_99af3eea856556646c98c8b9b2548fe815240750.Vault" @@ -56,7 +53,6 @@ access(all) let swapFeeTier: UInt32 = 100 // --- Test State --- -access(all) var syWFLOWvYieldVaultID: UInt64 = 0 access(all) var fusdEvYieldVaultID: UInt64 = 0 /* --- Test Helpers --- */ @@ -80,7 +76,7 @@ fun _executeTransactionFile(_ path: String, _ args: [AnyStruct], _ signers: [Tes /* --- Setup --- */ access(all) fun setup() { - log("==== PMStrategiesV1 Fork Test Setup ====") + log("==== PMStrategiesV1 FUSDEV Fork Test Setup ====") log("Deploying EVMAmountUtils contract ...") var err = Test.deployContract( @@ -161,89 +157,6 @@ access(all) fun setup() { log("==== Setup Complete ====") } -/* --- syWFLOWvStrategy Tests (FLOW collateral, Morpho syWFLOWv vault) --- */ - -access(all) fun testCreateSyWFLOWvYieldVault() { - log("Creating syWFLOWvStrategy yield vault with 1.0 FLOW...") - let result = _executeTransactionFile( - "../transactions/flow-yield-vaults/create_yield_vault.cdc", - [syWFLOWvStrategyIdentifier, flowVaultIdentifier, 1.0], - [userAccount] - ) - Test.expect(result, Test.beSucceeded()) - - // Retrieve the vault IDs - let idsResult = _executeScript( - "../scripts/flow-yield-vaults/get_yield_vault_ids.cdc", - [userAccount.address] - ) - Test.expect(idsResult, Test.beSucceeded()) - let ids = idsResult.returnValue! as! [UInt64]? - Test.assert(ids != nil && ids!.length > 0, message: "Expected at least one yield vault") - syWFLOWvYieldVaultID = ids![ids!.length - 1] - log("Created syWFLOWv yield vault ID: ".concat(syWFLOWvYieldVaultID.toString())) - - // Verify initial balance - let balResult = _executeScript( - "../scripts/flow-yield-vaults/get_yield_vault_balance.cdc", - [userAccount.address, syWFLOWvYieldVaultID] - ) - Test.expect(balResult, Test.beSucceeded()) - let balance = balResult.returnValue! as! UFix64? - Test.assert(balance != nil, message: "Expected balance to be available") - Test.assert(balance! > 0.0, message: "Expected positive balance after deposit") - log("syWFLOWv vault balance: ".concat(balance!.toString())) -} - -access(all) fun testDepositToSyWFLOWvYieldVault() { - log("Depositing 0.5 FLOW to syWFLOWv yield vault...") - let result = _executeTransactionFile( - "../transactions/flow-yield-vaults/deposit_to_yield_vault.cdc", - [syWFLOWvYieldVaultID, 0.5], - [userAccount] - ) - Test.expect(result, Test.beSucceeded()) - - let balResult = _executeScript( - "../scripts/flow-yield-vaults/get_yield_vault_balance.cdc", - [userAccount.address, syWFLOWvYieldVaultID] - ) - Test.expect(balResult, Test.beSucceeded()) - let balance = balResult.returnValue! as! UFix64? - Test.assert(balance != nil && balance! > 0.0, message: "Expected positive balance after additional deposit") - log("syWFLOWv vault balance after deposit: ".concat(balance!.toString())) -} - -access(all) fun testWithdrawFromSyWFLOWvYieldVault() { - log("Withdrawing 0.3 FLOW from syWFLOWv yield vault...") - let result = _executeTransactionFile( - "../transactions/flow-yield-vaults/withdraw_from_yield_vault.cdc", - [syWFLOWvYieldVaultID, 0.3], - [userAccount] - ) - Test.expect(result, Test.beSucceeded()) - - let balResult = _executeScript( - "../scripts/flow-yield-vaults/get_yield_vault_balance.cdc", - [userAccount.address, syWFLOWvYieldVaultID] - ) - Test.expect(balResult, Test.beSucceeded()) - let balance = balResult.returnValue! as! UFix64? - Test.assert(balance != nil && balance! > 0.0, message: "Expected positive balance after withdrawal") - log("syWFLOWv vault balance after withdrawal: ".concat(balance!.toString())) -} - -access(all) fun testCloseSyWFLOWvYieldVault() { - log("Closing syWFLOWv yield vault...") - let result = _executeTransactionFile( - "../transactions/flow-yield-vaults/close_yield_vault.cdc", - [syWFLOWvYieldVaultID], - [userAccount] - ) - Test.expect(result, Test.beSucceeded()) - log("syWFLOWv yield vault closed successfully") -} - /* --- FUSDEVStrategy Tests (PYUSD0 collateral, Morpho FUSDEV vault) --- */ access(all) fun testCreateFUSDEVYieldVault() { diff --git a/cadence/tests/PMStrategiesV1_syWFLOWv_test.cdc b/cadence/tests/PMStrategiesV1_syWFLOWv_test.cdc new file mode 100644 index 00000000..7a181a20 --- /dev/null +++ b/cadence/tests/PMStrategiesV1_syWFLOWv_test.cdc @@ -0,0 +1,290 @@ +#test_fork(network: "mainnet", height: nil) // Uses latest height - syWFLOWv works well at recent heights + +import Test + +import "EVM" +import "FlowToken" +import "FlowYieldVaults" +import "PMStrategiesV1" +import "FlowYieldVaultsClosedBeta" + +import "test_helpers.cdc" + +/// Fork test for PMStrategiesV1 syWFLOWv strategy — validates the full YieldVault lifecycle +/// (create, deposit, withdraw, close) against real mainnet state. +/// +/// This test: +/// - Forks Flow mainnet to access real EVM state (Morpho vaults, UniswapV3 pools) +/// - Configures PMStrategiesV1 syWFLOWv strategy (FLOW collateral -> syWFLOWv Morpho ERC4626 vault) +/// - Tests the complete yield vault lifecycle +/// - Validates Morpho ERC4626 swap connectors work with real vault contracts +/// +/// Mainnet addresses: +/// - Admin (FlowYieldVaults deployer): 0xb1d63873c3cc9f79 +/// - UniV3 Factory: 0xca6d7Bb03334bBf135902e1d919a5feccb461632 +/// - UniV3 Router: 0xeEDC6Ff75e1b10B903D9013c358e446a73d35341 +/// - UniV3 Quoter: 0x370A8DF17742867a44e56223EC20D82092242C85 +/// - WFLOW: 0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e +/// - syWFLOWv (More vault): 0xCBf9a7753F9D2d0e8141ebB36d99f87AcEf98597 + +// --- Accounts --- + +/// Mainnet admin account — deployer of PMStrategiesV1, FlowYieldVaults, FlowYieldVaultsClosedBeta +access(all) let adminAccount = Test.getAccount(0xb1d63873c3cc9f79) + +/// Mainnet user account — used to test yield vault operations +access(all) let userAccount = Test.getAccount(0x443472749ebdaac8) + +// --- Strategy Config Constants --- + +/// syWFLOWvStrategy: FLOW collateral -> syWFLOWv Morpho ERC4626 vault +access(all) let syWFLOWvStrategyIdentifier = "A.b1d63873c3cc9f79.PMStrategiesV1.syWFLOWvStrategy" +access(all) let flowVaultIdentifier = "A.1654653399040a61.FlowToken.Vault" +access(all) let syWFLOWvEVMAddress = "0xCBf9a7753F9D2d0e8141ebB36d99f87AcEf98597" + +/// ERC4626VaultStrategyComposer type and issuer path +access(all) let composerIdentifier = "A.b1d63873c3cc9f79.PMStrategiesV1.ERC4626VaultStrategyComposer" +access(all) let issuerStoragePath: StoragePath = /storage/PMStrategiesV1ComposerIssuer_0xb1d63873c3cc9f79 + +/// Swap fee tier for Morpho vault <-> underlying asset UniV3 pools +access(all) let swapFeeTier: UInt32 = 100 + +// --- Test State --- + +access(all) var syWFLOWvYieldVaultID: UInt64 = 0 + +/* --- Test Helpers --- */ + +access(all) +fun _executeTransactionFile(_ path: String, _ args: [AnyStruct], _ signers: [Test.TestAccount]): Test.TransactionResult { + let txn = Test.Transaction( + code: Test.readFile(path), + authorizers: signers.map(fun (s: Test.TestAccount): Address { return s.address }), + signers: signers, + arguments: args + ) + return Test.executeTransaction(txn) +} + +/* --- Setup --- */ + +access(all) fun setup() { + log("==== PMStrategiesV1 syWFLOWv Fork Test Setup ====") + + log("Deploying EVMAmountUtils contract ...") + var err = Test.deployContract( + name: "EVMAmountUtils", + path: "../../lib/FlowALP/FlowActions/cadence/contracts/connectors/evm/EVMAmountUtils.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + + log("Deploying UniswapV3SwapConnectors contract ...") + err = Test.deployContract( + name: "UniswapV3SwapConnectors", + path: "../../lib/FlowALP/FlowActions/cadence/contracts/connectors/evm/UniswapV3SwapConnectors.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + + // Deploy Morpho contracts (latest local code) to the forked environment + log("Deploying Morpho contracts...") + err = Test.deployContract( + name: "ERC4626Utils", + path: "../../lib/FlowALP/FlowActions/cadence/contracts/utils/ERC4626Utils.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + + err = Test.deployContract( + name: "ERC4626SwapConnectors", + path: "../../lib/FlowALP/FlowActions/cadence/contracts/connectors/evm/ERC4626SwapConnectors.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + + err = Test.deployContract( + name: "MorphoERC4626SinkConnectors", + path: "../../lib/FlowALP/FlowActions/cadence/contracts/connectors/evm/morpho/MorphoERC4626SinkConnectors.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + + err = Test.deployContract( + name: "MorphoERC4626SwapConnectors", + path: "../../lib/FlowALP/FlowActions/cadence/contracts/connectors/evm/morpho/MorphoERC4626SwapConnectors.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + + log("Deploying FlowYieldVaults contract ...") + err = Test.deployContract( + name: "FlowYieldVaults", + path: "../../cadence/contracts/FlowYieldVaults.cdc", + arguments: [] + ) + Test.expect(err, Test.beNil()) + + // Redeploy PMStrategiesV1 with latest local code to override mainnet version + log("Deploying PMStrategiesV1...") + err = Test.deployContract( + name: "PMStrategiesV1", + path: "../../cadence/contracts/PMStrategiesV1.cdc", + arguments: [ + "0xca6d7Bb03334bBf135902e1d919a5feccb461632", + "0xeEDC6Ff75e1b10B903D9013c358e446a73d35341", + "0x370A8DF17742867a44e56223EC20D82092242C85" + ] + ) + Test.expect(err, Test.beNil()) + + // Grant beta access to user account for testing yield vault operations + log("Granting beta access to user...") + var result = _executeTransactionFile( + "../transactions/flow-yield-vaults/admin/grant_beta.cdc", + [], + [adminAccount, userAccount] + ) + Test.expect(result, Test.beSucceeded()) + + log("==== Setup Complete ====") +} + +/* --- syWFLOWvStrategy Tests (FLOW collateral, Morpho syWFLOWv vault) --- */ + +access(all) fun testCreateSyWFLOWvYieldVault() { + log("Creating syWFLOWvStrategy yield vault with 1.0 FLOW...") + let result = _executeTransactionFile( + "../transactions/flow-yield-vaults/create_yield_vault.cdc", + [syWFLOWvStrategyIdentifier, flowVaultIdentifier, 1.0], + [userAccount] + ) + Test.expect(result, Test.beSucceeded()) + + // Retrieve the vault IDs + let idsResult = _executeScript( + "../scripts/flow-yield-vaults/get_yield_vault_ids.cdc", + [userAccount.address] + ) + Test.expect(idsResult, Test.beSucceeded()) + let ids = idsResult.returnValue! as! [UInt64]? + Test.assert(ids != nil && ids!.length > 0, message: "Expected at least one yield vault") + syWFLOWvYieldVaultID = ids![ids!.length - 1] + log("Created syWFLOWv yield vault ID: ".concat(syWFLOWvYieldVaultID.toString())) + + // Verify initial balance + let balResult = _executeScript( + "../scripts/flow-yield-vaults/get_yield_vault_balance.cdc", + [userAccount.address, syWFLOWvYieldVaultID] + ) + Test.expect(balResult, Test.beSucceeded()) + let balance = balResult.returnValue! as! UFix64? + Test.assert(balance != nil, message: "Expected balance to be available") + Test.assert(balance! > 0.0, message: "Expected positive balance after deposit") + log("syWFLOWv vault balance: ".concat(balance!.toString())) +} + +access(all) fun testDepositToSyWFLOWvYieldVault() { + let balBeforeResult = _executeScript( + "../scripts/flow-yield-vaults/get_yield_vault_balance.cdc", + [userAccount.address, syWFLOWvYieldVaultID] + ) + Test.expect(balBeforeResult, Test.beSucceeded()) + let balanceBefore = balBeforeResult.returnValue! as! UFix64? ?? 0.0 + + let depositAmount: UFix64 = 0.5 + log("Depositing 0.5 FLOW to syWFLOWv yield vault...") + let result = _executeTransactionFile( + "../transactions/flow-yield-vaults/deposit_to_yield_vault.cdc", + [syWFLOWvYieldVaultID, depositAmount], + [userAccount] + ) + Test.expect(result, Test.beSucceeded()) + + let balResult = _executeScript( + "../scripts/flow-yield-vaults/get_yield_vault_balance.cdc", + [userAccount.address, syWFLOWvYieldVaultID] + ) + Test.expect(balResult, Test.beSucceeded()) + let balance = balResult.returnValue! as! UFix64? + Test.assert( + equalAmounts(a: balance!, b: balanceBefore + depositAmount, tolerance: 0.01), + message: "Expected balance to increase by the deposit amount" + ) + log("syWFLOWv vault balance after deposit: ".concat(balance!.toString())) +} + +access(all) fun testWithdrawFromSyWFLOWvYieldVault() { + let balBeforeResult = _executeScript( + "../scripts/flow-yield-vaults/get_yield_vault_balance.cdc", + [userAccount.address, syWFLOWvYieldVaultID] + ) + Test.expect(balBeforeResult, Test.beSucceeded()) + let balanceBefore = balBeforeResult.returnValue! as! UFix64? ?? 0.0 + + let withdrawAmount: UFix64 = 0.3 + log("Withdrawing 0.3 FLOW from syWFLOWv yield vault...") + let result = _executeTransactionFile( + "../transactions/flow-yield-vaults/withdraw_from_yield_vault.cdc", + [syWFLOWvYieldVaultID, withdrawAmount], + [userAccount] + ) + Test.expect(result, Test.beSucceeded()) + + let balResult = _executeScript( + "../scripts/flow-yield-vaults/get_yield_vault_balance.cdc", + [userAccount.address, syWFLOWvYieldVaultID] + ) + Test.expect(balResult, Test.beSucceeded()) + let balance = balResult.returnValue! as! UFix64? + Test.assert( + equalAmounts(a: balance!, b: balanceBefore - withdrawAmount, tolerance: 0.01), + message: "Expected balance to decrease by the withdrawn amount" + ) + log("syWFLOWv vault balance after withdrawal: ".concat(balance!.toString())) +} + +access(all) fun testCloseSyWFLOWvYieldVault() { + let vaultBalBeforeResult = _executeScript( + "../scripts/flow-yield-vaults/get_yield_vault_balance.cdc", + [userAccount.address, syWFLOWvYieldVaultID] + ) + Test.expect(vaultBalBeforeResult, Test.beSucceeded()) + let vaultBalanceBefore = vaultBalBeforeResult.returnValue! as! UFix64? ?? 0.0 + + let flowBalBeforeResult = _executeScript( + "../scripts/flow-yield-vaults/get_flow_balance.cdc", + [userAccount.address] + ) + Test.expect(flowBalBeforeResult, Test.beSucceeded()) + let flowBalanceBefore = flowBalBeforeResult.returnValue! as! UFix64 + + log("Closing syWFLOWv yield vault...") + let result = _executeTransactionFile( + "../transactions/flow-yield-vaults/close_yield_vault.cdc", + [syWFLOWvYieldVaultID], + [userAccount] + ) + Test.expect(result, Test.beSucceeded()) + + // Vault balance should now be nil (vault no longer exists) + let vaultBalAfterResult = _executeScript( + "../scripts/flow-yield-vaults/get_yield_vault_balance.cdc", + [userAccount.address, syWFLOWvYieldVaultID] + ) + Test.expect(vaultBalAfterResult, Test.beSucceeded()) + Test.assert(vaultBalAfterResult.returnValue == nil, message: "Expected vault to no longer exist after close") + + // User's FLOW balance should have increased by approximately the vault's pre-close balance + let flowBalAfterResult = _executeScript( + "../scripts/flow-yield-vaults/get_flow_balance.cdc", + [userAccount.address] + ) + Test.expect(flowBalAfterResult, Test.beSucceeded()) + let flowBalanceAfter = flowBalAfterResult.returnValue! as! UFix64 + Test.assert( + equalAmounts(a: flowBalanceAfter, b: flowBalanceBefore + vaultBalanceBefore, tolerance: 0.01), + message: "Expected user FLOW balance to increase by approximately the vault balance" + ) + log("syWFLOWv yield vault closed successfully") +} diff --git a/cadence/tests/rebalance_scenario2_test.cdc b/cadence/tests/rebalance_scenario2_test.cdc index 4beb8734..51b48b47 100644 --- a/cadence/tests/rebalance_scenario2_test.cdc +++ b/cadence/tests/rebalance_scenario2_test.cdc @@ -23,22 +23,6 @@ access(all) let targetHealthFactor = 1.3 access(all) var snapshot: UInt64 = 0 -// Helper function to get Flow collateral from position -access(all) fun getFlowCollateralFromPosition(pid: UInt64): UFix64 { - let positionDetails = getPositionDetails(pid: pid, beFailed: false) - for balance in positionDetails.balances { - if balance.vaultType == Type<@FlowToken.Vault>() { - // Credit means it's a deposit (collateral) - if balance.direction.rawValue == 0 { // Credit = 0 - return balance.balance - } - } - } - return 0.0 -} - - - // Enhanced diagnostic precision tracking function with full call stack tracing access(all) fun performDiagnosticPrecisionTrace( yieldVaultID: UInt64, diff --git a/cadence/tests/rebalance_scenario3a_test.cdc b/cadence/tests/rebalance_scenario3a_test.cdc index 7e778f12..f111fb58 100644 --- a/cadence/tests/rebalance_scenario3a_test.cdc +++ b/cadence/tests/rebalance_scenario3a_test.cdc @@ -23,34 +23,6 @@ access(all) let targetHealthFactor = 1.3 access(all) var snapshot: UInt64 = 0 -// Helper function to get Flow collateral from position -access(all) fun getFlowCollateralFromPosition(pid: UInt64): UFix64 { - let positionDetails = getPositionDetails(pid: pid, beFailed: false) - for balance in positionDetails.balances { - if balance.vaultType == Type<@FlowToken.Vault>() { - // Credit means it's a deposit (collateral) - if balance.direction == FlowALPv0.BalanceDirection.Credit { - return balance.balance - } - } - } - return 0.0 -} - -// Helper function to get MOET debt from position -access(all) fun getMOETDebtFromPosition(pid: UInt64): UFix64 { - let positionDetails = getPositionDetails(pid: pid, beFailed: false) - for balance in positionDetails.balances { - if balance.vaultType == Type<@MOET.Vault>() { - // Debit means it's borrowed (debt) - if balance.direction == FlowALPv0.BalanceDirection.Debit { - return balance.balance - } - } - } - return 0.0 -} - access(all) fun setup() { deployContracts() diff --git a/cadence/tests/rebalance_scenario3b_test.cdc b/cadence/tests/rebalance_scenario3b_test.cdc index 069d83aa..8a521dbc 100644 --- a/cadence/tests/rebalance_scenario3b_test.cdc +++ b/cadence/tests/rebalance_scenario3b_test.cdc @@ -23,34 +23,6 @@ access(all) let targetHealthFactor = 1.3 access(all) var snapshot: UInt64 = 0 -// Helper function to get Flow collateral from position -access(all) fun getFlowCollateralFromPosition(pid: UInt64): UFix64 { - let positionDetails = getPositionDetails(pid: pid, beFailed: false) - for balance in positionDetails.balances { - if balance.vaultType == Type<@FlowToken.Vault>() { - // Credit means it's a deposit (collateral) - if balance.direction.rawValue == 0 { // Credit = 0 - return balance.balance - } - } - } - return 0.0 -} - -// Helper function to get MOET debt from position -access(all) fun getMOETDebtFromPosition(pid: UInt64): UFix64 { - let positionDetails = getPositionDetails(pid: pid, beFailed: false) - for balance in positionDetails.balances { - if balance.vaultType == Type<@MOET.Vault>() { - // Debit means it's borrowed (debt) - if balance.direction.rawValue == 1 { // Debit = 1 - return balance.balance - } - } - } - return 0.0 -} - access(all) fun setup() { deployContracts() diff --git a/cadence/tests/rebalance_scenario3c_test.cdc b/cadence/tests/rebalance_scenario3c_test.cdc index ef340e7e..06514569 100644 --- a/cadence/tests/rebalance_scenario3c_test.cdc +++ b/cadence/tests/rebalance_scenario3c_test.cdc @@ -23,34 +23,6 @@ access(all) let targetHealthFactor = 1.3 access(all) var snapshot: UInt64 = 0 -// Helper function to get Flow collateral from position -access(all) fun getFlowCollateralFromPosition(pid: UInt64): UFix64 { - let positionDetails = getPositionDetails(pid: pid, beFailed: false) - for balance in positionDetails.balances { - if balance.vaultType == Type<@FlowToken.Vault>() { - // Credit means it's a deposit (collateral) - if balance.direction == FlowALPv0.BalanceDirection.Credit { - return balance.balance - } - } - } - return 0.0 -} - -// Helper function to get MOET debt from position -access(all) fun getMOETDebtFromPosition(pid: UInt64): UFix64 { - let positionDetails = getPositionDetails(pid: pid, beFailed: false) - for balance in positionDetails.balances { - if balance.vaultType == Type<@MOET.Vault>() { - // Debit means it's borrowed (debt) - if balance.direction == FlowALPv0.BalanceDirection.Debit { - return balance.balance - } - } - } - return 0.0 -} - access(all) fun setup() { deployContracts() diff --git a/cadence/tests/rebalance_scenario3d_test.cdc b/cadence/tests/rebalance_scenario3d_test.cdc index 4a80a0eb..38fefdba 100644 --- a/cadence/tests/rebalance_scenario3d_test.cdc +++ b/cadence/tests/rebalance_scenario3d_test.cdc @@ -23,34 +23,6 @@ access(all) let targetHealthFactor = 1.3 access(all) var snapshot: UInt64 = 0 -// Helper function to get Flow collateral from position -access(all) fun getFlowCollateralFromPosition(pid: UInt64): UFix64 { - let positionDetails = getPositionDetails(pid: pid, beFailed: false) - for balance in positionDetails.balances { - if balance.vaultType == Type<@FlowToken.Vault>() { - // Credit means it's a deposit (collateral) - if balance.direction == FlowALPv0.BalanceDirection.Credit { - return balance.balance - } - } - } - return 0.0 -} - -// Helper function to get MOET debt from position -access(all) fun getMOETDebtFromPosition(pid: UInt64): UFix64 { - let positionDetails = getPositionDetails(pid: pid, beFailed: false) - for balance in positionDetails.balances { - if balance.vaultType == Type<@MOET.Vault>() { - // Debit means it's borrowed (debt) - if balance.direction == FlowALPv0.BalanceDirection.Debit { - return balance.balance - } - } - } - return 0.0 -} - access(all) fun setup() { deployContracts() diff --git a/cadence/tests/rebalance_scenario4_test.cdc b/cadence/tests/rebalance_scenario4_test.cdc new file mode 100644 index 00000000..b1a2000c --- /dev/null +++ b/cadence/tests/rebalance_scenario4_test.cdc @@ -0,0 +1,342 @@ +import Test +import BlockchainHelpers + +import "test_helpers.cdc" + +import "FlowToken" +import "MOET" +import "YieldToken" +import "MockStrategies" +import "FlowALPv0" + +access(all) let protocolAccount = Test.getAccount(0x0000000000000008) +access(all) let flowYieldVaultsAccount = Test.getAccount(0x0000000000000009) +access(all) let yieldTokenAccount = Test.getAccount(0x0000000000000010) + +access(all) var strategyIdentifier = Type<@MockStrategies.TracerStrategy>().identifier +access(all) var flowTokenIdentifier = Type<@FlowToken.Vault>().identifier +access(all) var yieldTokenIdentifier = Type<@YieldToken.Vault>().identifier +access(all) var moetTokenIdentifier = Type<@MOET.Vault>().identifier + +access(all) var snapshot: UInt64 = 0 +access(all) let TARGET_HEALTH: UFix128 = 1.3 +access(all) let SOLVENT_HEALTH_FLOOR: UFix128 = 1.0 + +access(all) +fun safeReset() { + let cur = getCurrentBlockHeight() + if cur > snapshot { + Test.reset(to: snapshot) + } +} + +access(all) +fun setup() { + deployContracts() + snapshot = getCurrentBlockHeight() +} + +/// Configure the environment after resetting to the post-deploy snapshot. +/// Each test resets to `snapshot` then calls this with its own starting prices. +access(all) +fun setupEnv(flowPrice: UFix64, yieldPrice: UFix64) { + setMockOraclePrice(signer: flowYieldVaultsAccount, forTokenIdentifier: yieldTokenIdentifier, price: yieldPrice) + setMockOraclePrice(signer: flowYieldVaultsAccount, forTokenIdentifier: flowTokenIdentifier, price: flowPrice) + + // mint tokens & set liquidity in mock swapper contract + let reserveAmount = 100_000_000.0 + setupMoetVault(protocolAccount, beFailed: false) + setupYieldVault(protocolAccount, beFailed: false) + mintFlow(to: protocolAccount, amount: reserveAmount) + mintMoet(signer: protocolAccount, to: protocolAccount.address, amount: reserveAmount, beFailed: false) + mintYield(signer: yieldTokenAccount, to: protocolAccount.address, amount: reserveAmount, beFailed: false) + setMockSwapperLiquidityConnector(signer: protocolAccount, vaultStoragePath: MOET.VaultStoragePath) + setMockSwapperLiquidityConnector(signer: protocolAccount, vaultStoragePath: YieldToken.VaultStoragePath) + setMockSwapperLiquidityConnector(signer: protocolAccount, vaultStoragePath: /storage/flowTokenVault) + + // setup FlowALP with a Pool & add FLOW as supported token + createAndStorePool(signer: protocolAccount, defaultTokenIdentifier: moetTokenIdentifier, beFailed: false) + addSupportedTokenFixedRateInterestCurve( + signer: protocolAccount, + tokenTypeIdentifier: flowTokenIdentifier, + collateralFactor: 0.8, + borrowFactor: 1.0, + yearlyRate: UFix128(0.1), + depositRate: 1_000_000.0, + depositCapacityCap: 1_000_000.0 + ) + + // Set MOET deposit limit fraction to 1.0 (100%) to allow full debt repayment in one transaction + // Default is 0.05 (5%) which would limit deposits to 50,000 MOET per operation + setDepositLimitFraction(signer: protocolAccount, tokenTypeIdentifier: moetTokenIdentifier, fraction: 1.0) + + // open wrapped position (pushToDrawDownSink) + // the equivalent of depositing reserves + let openRes = executeTransaction( + "../../lib/FlowALP/cadence/transactions/flow-alp/position/create_position.cdc", + [reserveAmount/2.0, /storage/flowTokenVault, true], + protocolAccount + ) + Test.expect(openRes, Test.beSucceeded()) + + // enable mocked Strategy creation + addStrategyComposer( + signer: flowYieldVaultsAccount, + strategyIdentifier: strategyIdentifier, + composerIdentifier: Type<@MockStrategies.TracerStrategyComposer>().identifier, + issuerStoragePath: MockStrategies.IssuerStoragePath, + beFailed: false + ) + + // Fund FlowYieldVaults account for scheduling fees (atomic initial scheduling) + mintFlow(to: flowYieldVaultsAccount, amount: 100.0) +} + +access(all) +fun test_RebalanceLowCollateralHighYieldPrices() { + // Scenario 4: Large FLOW position at real-world low FLOW price + // FLOW drops further while YT price surges — tests closeYieldVault at extreme price ratios + safeReset() + setupEnv(flowPrice: 0.03, yieldPrice: 1000.0) + + let fundingAmount = 1_000_000.0 + let flowPriceDecrease = 0.02 // FLOW: $0.03 → $0.02 + let yieldPriceIncrease = 1500.0 // YT: $1000.0 → $1500.0 + + let user = Test.createAccount() + mintFlow(to: user, amount: fundingAmount) + grantBeta(flowYieldVaultsAccount, user) + + createYieldVault( + signer: user, + strategyIdentifier: strategyIdentifier, + vaultIdentifier: flowTokenIdentifier, + amount: fundingAmount, + beFailed: false + ) + + var yieldVaultIDs = getYieldVaultIDs(address: user.address) + var pid = 1 as UInt64 + Test.assert(yieldVaultIDs != nil, message: "Expected user's YieldVault IDs to be non-nil but encountered nil") + Test.assertEqual(1, yieldVaultIDs!.length) + log("[Scenario4] YieldVault ID: \(yieldVaultIDs![0]), position ID: \(pid)") + + // --- Phase 1: FLOW price drops from $0.03 to $0.02 --- + setMockOraclePrice(signer: flowYieldVaultsAccount, forTokenIdentifier: flowTokenIdentifier, price: flowPriceDecrease) + + let ytBefore = getAutoBalancerBalance(id: yieldVaultIDs![0])! + let debtBefore = getMOETDebtFromPosition(pid: pid) + let collateralBefore = getFlowCollateralFromPosition(pid: pid) + + log("\n[Scenario4] Pre-rebalance state (vault created @ FLOW=$0.03, YT=$1000.0; FLOW oracle now $\(flowPriceDecrease))") + log(" YT balance: \(ytBefore) YT") + log(" FLOW collateral: \(collateralBefore) FLOW (value: \(collateralBefore * flowPriceDecrease) MOET @ $\(flowPriceDecrease)/FLOW)") + log(" MOET debt: \(debtBefore) MOET") + + rebalanceYieldVault(signer: flowYieldVaultsAccount, id: yieldVaultIDs![0], force: true, beFailed: false) + rebalancePosition(signer: protocolAccount, pid: pid, force: true, beFailed: false) + + let ytAfterFlowDrop = getAutoBalancerBalance(id: yieldVaultIDs![0])! + let debtAfterFlowDrop = getMOETDebtFromPosition(pid: pid) + let collateralAfterFlowDrop = getFlowCollateralFromPosition(pid: pid) + + log("\n[Scenario4] After rebalance (FLOW=$\(flowPriceDecrease), YT=$1000.0)") + log(" YT balance: \(ytAfterFlowDrop) YT") + log(" FLOW collateral: \(collateralAfterFlowDrop) FLOW (value: \(collateralAfterFlowDrop * flowPriceDecrease) MOET)") + log(" MOET debt: \(debtAfterFlowDrop) MOET") + + // The position was undercollateralized after FLOW price drop, so the topUpSource + // (AutoBalancer YT → MOET) should have repaid some debt, reducing both YT and MOET debt. + Test.assert(debtAfterFlowDrop < debtBefore, + message: "Expected MOET debt to decrease after rebalancing undercollateralized position, got \(debtAfterFlowDrop) (was \(debtBefore))") + Test.assert(ytAfterFlowDrop < ytBefore, + message: "Expected AutoBalancer YT to decrease after using topUpSource to repay debt, got \(ytAfterFlowDrop) (was \(ytBefore))") + // FLOW collateral is not touched by debt repayment + Test.assert(equalAmounts(a: collateralAfterFlowDrop, b: collateralBefore, tolerance: 0.001), + message: "Expected FLOW collateral to be unchanged after debt repayment rebalance, got \(collateralAfterFlowDrop) (was \(collateralBefore))") + + // --- Phase 2: YT price rises from $1000.0 to $1500.0 --- + setMockOraclePrice(signer: flowYieldVaultsAccount, forTokenIdentifier: yieldTokenIdentifier, price: yieldPriceIncrease) + + rebalanceYieldVault(signer: flowYieldVaultsAccount, id: yieldVaultIDs![0], force: true, beFailed: false) + + let ytAfterYTRise = getAutoBalancerBalance(id: yieldVaultIDs![0])! + let debtAfterYTRise = getMOETDebtFromPosition(pid: pid) + let collateralAfterYTRise = getFlowCollateralFromPosition(pid: pid) + + log("\n[Scenario4] After rebalance (FLOW=$\(flowPriceDecrease), YT=$\(yieldPriceIncrease))") + log(" YT balance: \(ytAfterYTRise) YT") + log(" FLOW collateral: \(collateralAfterYTRise) FLOW (value: \(collateralAfterYTRise * flowPriceDecrease) MOET)") + log(" MOET debt: \(debtAfterYTRise) MOET") + + // The AutoBalancer's YT is now worth 50% more, making its value exceed the deposit threshold. + // It should push excess YT → FLOW into the position, increasing collateral and reducing YT. + Test.assert(ytAfterYTRise < ytAfterFlowDrop, + message: "Expected AutoBalancer YT to decrease after pushing excess value to position, got \(ytAfterYTRise) (was \(ytAfterFlowDrop))") + Test.assert(collateralAfterYTRise > collateralAfterFlowDrop, + message: "Expected FLOW collateral to increase after AutoBalancer pushed YT→FLOW to position, got \(collateralAfterYTRise) (was \(collateralAfterFlowDrop))") + + let flowBalanceBefore = getBalance(address: user.address, vaultPublicPath: /public/flowTokenReceiver)! + + closeYieldVault(signer: user, id: yieldVaultIDs![0], beFailed: false) + + // After close, the vault should no longer exist and the user should have received their FLOW back + let flowBalanceAfter = getBalance(address: user.address, vaultPublicPath: /public/flowTokenReceiver)! + Test.assert(flowBalanceAfter > flowBalanceBefore, + message: "Expected user FLOW balance to increase after closing vault, got \(flowBalanceAfter) (was \(flowBalanceBefore))") + + yieldVaultIDs = getYieldVaultIDs(address: user.address) + Test.assert(yieldVaultIDs == nil || yieldVaultIDs!.length == 0, + message: "Expected no yield vaults after close but found \(yieldVaultIDs?.length ?? 0)") + + log("\n[Scenario4] Test complete") +} + +access(all) +fun test_RebalanceHighCollateralLowYieldPrices() { + // Scenario 5: High-value collateral with moderate price drop + // Tests rebalancing when FLOW drops 20% from $1000 → $800 + // This scenario tests whether position can handle moderate drops without liquidation + safeReset() + setupEnv(flowPrice: 1000.0, yieldPrice: 1.0) + + let fundingAmount = 100.0 + let initialFlowPrice = 1000.00 // Starting price for this scenario + let flowPriceDecrease = 800.00 // FLOW: $1000 → $800 (20% drop) + let yieldPriceIncrease = 1.5 // YT: $1.0 → $1.5 + + let user = Test.createAccount() + mintFlow(to: user, amount: fundingAmount) + grantBeta(flowYieldVaultsAccount, user) + + createYieldVault( + signer: user, + strategyIdentifier: strategyIdentifier, + vaultIdentifier: flowTokenIdentifier, + amount: fundingAmount, + beFailed: false + ) + + var yieldVaultIDs = getYieldVaultIDs(address: user.address) + var pid = 1 as UInt64 + Test.assert(yieldVaultIDs != nil, message: "Expected user's YieldVault IDs to be non-nil but encountered nil") + Test.assertEqual(1, yieldVaultIDs!.length) + log("[Scenario5] YieldVault ID: \(yieldVaultIDs![0]), position ID: \(pid)") + + let initialCollateral = getFlowCollateralFromPosition(pid: pid) + let initialDebt = getMOETDebtFromPosition(pid: pid) + let initialHealth = getPositionHealth(pid: pid, beFailed: false) + let initialCollateralValue = initialCollateral * initialFlowPrice + log("[Scenario5] Initial state (FLOW=$\(initialFlowPrice), YT=$1.0)") + log(" Funding: \(initialCollateral) FLOW") + log(" Collateral value: $\(initialCollateralValue)") + log(" Actual debt: $\(initialDebt) MOET") + log(" Initial health: \(initialHealth)") + + // --- Phase 1: FLOW price drops from $1000 to $800 (20% drop) --- + setMockOraclePrice(signer: flowYieldVaultsAccount, forTokenIdentifier: flowTokenIdentifier, price: flowPriceDecrease) + + let ytBefore = getAutoBalancerBalance(id: yieldVaultIDs![0])! + let debtBefore = getMOETDebtFromPosition(pid: pid) + let collateralBefore = getFlowCollateralFromPosition(pid: pid) + + // Read health from FlowALP so this test tracks protocol configuration changes. + let healthBeforeRebalance = getPositionHealth(pid: pid, beFailed: false) + let collateralValueBefore = collateralBefore * flowPriceDecrease + + log("[Scenario5] After price drop to $\(flowPriceDecrease) (BEFORE rebalance)") + log(" YT balance: \(ytBefore) YT") + log(" FLOW collateral: \(collateralBefore) FLOW") + log(" Collateral value: $\(collateralValueBefore) MOET") + log(" MOET debt: \(debtBefore) MOET") + log(" Health: \(healthBeforeRebalance)") + + // The price drop should push health below the rebalance target while keeping the position solvent. + Test.assert(healthBeforeRebalance < TARGET_HEALTH, + message: "Expected health to drop below TARGET_HEALTH (\(TARGET_HEALTH)) after 20% FLOW price drop, got \(healthBeforeRebalance)") + Test.assert(healthBeforeRebalance > SOLVENT_HEALTH_FLOOR, + message: "Expected health to remain above \(SOLVENT_HEALTH_FLOOR) after 20% FLOW price drop, got \(healthBeforeRebalance)") + + // Rebalance to restore health to the strategy target. + log("[Scenario5] Rebalancing position and yield vault...") + rebalanceYieldVault(signer: flowYieldVaultsAccount, id: yieldVaultIDs![0], force: true, beFailed: false) + rebalancePosition(signer: protocolAccount, pid: pid, force: true, beFailed: false) + + let ytAfterFlowDrop = getAutoBalancerBalance(id: yieldVaultIDs![0])! + let debtAfterFlowDrop = getMOETDebtFromPosition(pid: pid) + let collateralAfterFlowDrop = getFlowCollateralFromPosition(pid: pid) + let healthAfterRebalance = getPositionHealth(pid: pid, beFailed: false) + + log("[Scenario5] After rebalance (FLOW=$\(flowPriceDecrease), YT=$1.0)") + log(" YT balance: \(ytAfterFlowDrop) YT") + log(" FLOW collateral: \(collateralAfterFlowDrop) FLOW") + log(" Collateral value: $\(collateralAfterFlowDrop * flowPriceDecrease) MOET") + log(" MOET debt: \(debtAfterFlowDrop) MOET") + log(" Health: \(healthAfterRebalance)") + + // The position was undercollateralized (health < TARGET_HEALTH) after the FLOW price drop, + // so the topUpSource (AutoBalancer YT → MOET) should have repaid some debt. + Test.assert(debtAfterFlowDrop < debtBefore, + message: "Expected MOET debt to decrease after rebalancing undercollateralized position, got \(debtAfterFlowDrop) (was \(debtBefore))") + Test.assert(ytAfterFlowDrop < ytBefore, + message: "Expected AutoBalancer YT to decrease after using topUpSource to repay debt, got \(ytAfterFlowDrop) (was \(ytBefore))") + // Debt repayment only affects the MOET debit — FLOW collateral is untouched. + Test.assert(equalAmounts(a: collateralAfterFlowDrop, b: collateralBefore, tolerance: 0.000001), + message: "Expected FLOW collateral to be unchanged after debt repayment, got \(collateralAfterFlowDrop) (was \(collateralBefore))") + // The AutoBalancer has sufficient YT to cover the full repayment needed to reach the target. + Test.assert(equalAmounts128(a: healthAfterRebalance, b: TARGET_HEALTH, tolerance: 0.00000001), + message: "Expected health to be fully restored to TARGET_HEALTH (\(TARGET_HEALTH)) after rebalance, got \(healthAfterRebalance)") + + // --- Phase 2: YT price rises from $1.0 to $1.5 --- + log("[Scenario5] Phase 2: YT price increases to $\(yieldPriceIncrease)") + setMockOraclePrice(signer: flowYieldVaultsAccount, forTokenIdentifier: yieldTokenIdentifier, price: yieldPriceIncrease) + + rebalanceYieldVault(signer: flowYieldVaultsAccount, id: yieldVaultIDs![0], force: true, beFailed: false) + + let ytAfterYTRise = getAutoBalancerBalance(id: yieldVaultIDs![0])! + let debtAfterYTRise = getMOETDebtFromPosition(pid: pid) + let collateralAfterYTRise = getFlowCollateralFromPosition(pid: pid) + let healthAfterYTRise = getPositionHealth(pid: pid, beFailed: false) + + log("[Scenario5] After YT rise (FLOW=$\(flowPriceDecrease), YT=$\(yieldPriceIncrease))") + log(" YT balance: \(ytAfterYTRise) YT") + log(" FLOW collateral: \(collateralAfterYTRise) FLOW") + log(" Collateral value: $\(collateralAfterYTRise * flowPriceDecrease) MOET") + log(" MOET debt: \(debtAfterYTRise) MOET") + log(" Health: \(healthAfterYTRise)") + + // The AutoBalancer's YT is now worth 50% more, exceeding the upper threshold. + // It pushes excess YT → FLOW into the position, reducing YT and increasing FLOW collateral. + Test.assert(ytAfterYTRise < ytAfterFlowDrop, + message: "Expected AutoBalancer YT to decrease after pushing excess value to position, got \(ytAfterYTRise) (was \(ytAfterFlowDrop))") + Test.assert(collateralAfterYTRise > collateralAfterFlowDrop, + message: "Expected FLOW collateral to increase after AutoBalancer pushed YT→FLOW to position, got \(collateralAfterYTRise) (was \(collateralAfterFlowDrop))") + + // Rebalance both position and yield vault before closing to ensure everything is settled + log("\n[Scenario5] Rebalancing position and yield vault before close...") + rebalancePosition(signer: protocolAccount, pid: pid, force: true, beFailed: false) + rebalanceYieldVault(signer: flowYieldVaultsAccount, id: yieldVaultIDs![0], force: true, beFailed: false) + + let ytBeforeClose = getAutoBalancerBalance(id: yieldVaultIDs![0])! + let debtBeforeClose = getMOETDebtFromPosition(pid: pid) + let collateralBeforeClose = getFlowCollateralFromPosition(pid: pid) + log("[Scenario5] After final rebalance before close:") + log(" YT balance: \(ytBeforeClose) YT") + log(" FLOW collateral: \(collateralBeforeClose) FLOW") + log(" MOET debt: \(debtBeforeClose) MOET") + + let flowBalanceBefore = getBalance(address: user.address, vaultPublicPath: /public/flowTokenReceiver)! + + // Close the yield vault + log("\n[Scenario5] Closing yield vault...") + closeYieldVault(signer: user, id: yieldVaultIDs![0], beFailed: false) + + // User should receive their collateral back; vault should be destroyed. + let flowBalanceAfter = getBalance(address: user.address, vaultPublicPath: /public/flowTokenReceiver)! + Test.assert(flowBalanceAfter > flowBalanceBefore, + message: "Expected user FLOW balance to increase after closing vault, got \(flowBalanceAfter) (was \(flowBalanceBefore))") + + yieldVaultIDs = getYieldVaultIDs(address: user.address) + Test.assert(yieldVaultIDs == nil || yieldVaultIDs!.length == 0, + message: "Expected no yield vaults after close but found \(yieldVaultIDs?.length ?? 0)") +} diff --git a/cadence/tests/rebalance_yield_test.cdc b/cadence/tests/rebalance_yield_test.cdc index bbe9cce3..aaac6fd5 100644 --- a/cadence/tests/rebalance_yield_test.cdc +++ b/cadence/tests/rebalance_yield_test.cdc @@ -135,7 +135,7 @@ fun test_RebalanceYieldVaultScenario2() { log("[TEST] YieldVault balance after yield before \(yieldTokenPrice) rebalance: \(yieldVaultBalance ?? 0.0)") Test.assert( - yieldVaultBalance == expectedFlowBalance[index], + equalAmounts(a: yieldVaultBalance!, b: expectedFlowBalance[index], tolerance: 0.01), message: "YieldVault balance of \(yieldVaultBalance ?? 0.0) doesn't match an expected value \(expectedFlowBalance[index])" ) } diff --git a/cadence/tests/test_helpers.cdc b/cadence/tests/test_helpers.cdc index 5df0bd7a..301c5d5a 100644 --- a/cadence/tests/test_helpers.cdc +++ b/cadence/tests/test_helpers.cdc @@ -487,6 +487,16 @@ fun getPositionDetails(pid: UInt64, beFailed: Bool): FlowALPv0.PositionDetails { return res.returnValue as! FlowALPv0.PositionDetails } +access(all) +fun getPositionHealth(pid: UInt64, beFailed: Bool): UFix128 { + let res = _executeScript("../../lib/FlowALP/cadence/scripts/flow-alp/position_health.cdc", + [pid] + ) + Test.expect(res, beFailed ? Test.beFailed() : Test.beSucceeded()) + + return res.returnValue as! UFix128 +} + access(all) fun getReserveBalanceForType(vaultIdentifier: String): UFix64 { let res = _executeScript( @@ -544,6 +554,16 @@ fun addSupportedTokenFixedRateInterestCurve( Test.expect(additionRes, Test.beSucceeded()) } +access(all) +fun setDepositLimitFraction(signer: Test.TestAccount, tokenTypeIdentifier: String, fraction: UFix64) { + let setRes = _executeTransaction( + "../../lib/FlowALP/cadence/transactions/flow-alp/pool-governance/set_deposit_limit_fraction.cdc", + [tokenTypeIdentifier, fraction], + signer + ) + Test.expect(setRes, Test.beSucceeded()) +} + access(all) fun rebalancePosition(signer: Test.TestAccount, pid: UInt64, force: Bool, beFailed: Bool) { let rebalanceRes = _executeTransaction( @@ -670,6 +690,14 @@ fun equalAmounts(a: UFix64, b: UFix64, tolerance: UFix64): Bool { return b - a <= tolerance } +access(all) +fun equalAmounts128(a: UFix128, b: UFix128, tolerance: UFix128): Bool { + if a > b { + return a - b <= tolerance + } + return b - a <= tolerance +} + /* --- Formatting helpers --- */ access(all) fun formatValue(_ value: UFix64): String { @@ -956,3 +984,31 @@ fun setupPunchswap(deployer: Test.TestAccount, wflowAddress: String): {String: S punchswapV3FactoryAddress: punchswapV3FactoryAddress } } + +// Helper function to get Flow collateral from position +access(all) fun getFlowCollateralFromPosition(pid: UInt64): UFix64 { + let positionDetails = getPositionDetails(pid: pid, beFailed: false) + for balance in positionDetails.balances { + if balance.vaultType == Type<@FlowToken.Vault>() { + // Credit means it's a deposit (collateral) + if balance.direction == FlowALPv0.BalanceDirection.Credit { + return balance.balance + } + } + } + return 0.0 +} + +// Helper function to get MOET debt from position +access(all) fun getMOETDebtFromPosition(pid: UInt64): UFix64 { + let positionDetails = getPositionDetails(pid: pid, beFailed: false) + for balance in positionDetails.balances { + if balance.vaultType == Type<@MOET.Vault>() { + // Debit means it's borrowed (debt) + if balance.direction == FlowALPv0.BalanceDirection.Debit { + return balance.balance + } + } + } + return 0.0 +} diff --git a/cadence/tests/tracer_strategy_test.cdc b/cadence/tests/tracer_strategy_test.cdc index 455e8742..27d5a59d 100644 --- a/cadence/tests/tracer_strategy_test.cdc +++ b/cadence/tests/tracer_strategy_test.cdc @@ -1,3 +1,69 @@ +/// TracerStrategy Test Suite +/// +/// Tests the bidirectional capital flow between Position (FlowALP) and AutoBalancer +/// in response to yield token price changes. +/// +/// ## Architecture Overview +/// +/// ``` +/// User Deposit (FLOW) +/// ↓ +/// YieldVault (TracerStrategy) +/// ├─ Position (FlowALP) +/// │ ├─ Collateral: FLOW +/// │ ├─ Debt: MOET +/// │ ├─ Health: collateral_value / debt +/// │ ├─ Target Health: 1.3 +/// │ └─ Min Health: 1.1 (liquidation at 1.0) +/// │ +/// └─ AutoBalancer +/// ├─ Holdings: YieldToken (YT) +/// ├─ Tracks: deposit value vs current value +/// ├─ Thresholds: 0.95 (pull) / 1.05 (push) +/// └─ Rebalances: via positionSwapSource/Sink +/// ``` +/// +/// ## Capital Flow Mechanisms +/// +/// ### 1. Position → AutoBalancer (DrawDownSink: abaSwapSink) +/// - When: Position health > target (overcollateralized) +/// - How: Position borrows more MOET → swaps to YT → deposits to AutoBalancer +/// - Purpose: Maintain target health, increase YT holdings +/// +/// ### 2. AutoBalancer → Position (RebalanceSink: positionSwapSink) +/// - When: AutoBalancer value > deposits (surplus) +/// - How: Swaps YT → FLOW → deposits to Position +/// - Purpose: Recollateralize Position, lock in gains +/// +/// ### 3. Position ← AutoBalancer (RebalanceSource: positionSwapSource) +/// - When: AutoBalancer value < deposits (deficit) +/// - How: Pulls FLOW from Position → swaps to YT → refills AutoBalancer +/// - Purpose: Recover from YT price drops +/// - Limit: Position maintains health ≥ minHealth (aggressive) or target (conservative) +/// +/// ## Key Behaviors +/// +/// ### YT Price Increases (test_RebalanceYieldVaultSucceeds) +/// 1. YT price ↑ → AutoBalancer value > deposits +/// 2. AutoBalancer pushes surplus to Position (via rebalanceSink) +/// 3. Position health > target +/// 4. Position borrows more MOET, pushes to AutoBalancer (via drawDownSink) +/// 5. Result: Increased leverage, more YT exposure +/// +/// ### YT Price Decreases (test_RebalanceYieldVaultSucceedsAfterYieldPriceDecrease) +/// 1. YT price ↓ → AutoBalancer value < deposits +/// 2. AutoBalancer pulls FLOW from Position (via rebalanceSource) +/// 3. Swaps FLOW → YT to partially recover +/// 4. Position health drops (FLOW collateral reduced) +/// 5. Position pulls from topUpSource to restore health +/// 6. Result: Partial recovery, but still significant loss +/// +/// ### Position Health Independence +/// - Position health = FLOW_value / MOET_debt +/// - Position holds FLOW (not YT), so YT price changes don't directly affect Position health +/// - Position health only changes when AutoBalancer pulls/pushes collateral +/// - This is why position rebalancing appears as "no-op" after YT price changes alone +/// import Test import BlockchainHelpers @@ -180,18 +246,20 @@ fun test_RebalanceYieldVaultSucceeds() { let autoBalancerValueAfter = getAutoBalancerCurrentValue(id: yieldVaultID)! let yieldVaultBalanceAfterPriceIncrease = getYieldVaultBalance(address: user.address, yieldVaultID: yieldVaultID) + // Rebalance YieldVault: AutoBalancer detects surplus (YT value increased from $61.54 to $73.85) + // and pushes excess value to Position via rebalanceSink (positionSwapSink: YT -> FLOW swap -> Position) rebalanceYieldVault(signer: flowYieldVaultsAccount, id: yieldVaultID, force: true, beFailed: false) - // TODO - assert against pre- and post- getYieldVaultBalance() diff once protocol assesses balance correctly - // for now we can use events to intercept fund flows between pre- and post- Position & AutoBalancer state - - // assess how much FLOW was deposited into the position + // Verify AutoBalancer pushed surplus to Position by checking Deposited event let autoBalancerRecollateralizeEvent = getLastPositionDepositedEvent(Test.eventsOfType(Type())) as! FlowALPv0.Deposited Test.assertEqual(positionID, autoBalancerRecollateralizeEvent.pid) Test.assertEqual(autoBalancerRecollateralizeEvent.amount, (autoBalancerValueAfter - autoBalancerValueBefore) / startingFlowPrice ) + // Position rebalance: Position health increased above target (1.3) due to AutoBalancer depositing + // extra collateral. Position rebalances by borrowing more MOET and pushing to drawDownSink + // (abaSwapSink: MOET -> YT -> AutoBalancer) to bring health back to target. rebalancePosition(signer: protocolAccount, pid: positionID, force: true, beFailed: false) let positionDetails = getPositionDetails(pid: positionID, beFailed: false) @@ -263,7 +331,13 @@ fun test_RebalanceYieldVaultSucceedsAfterYieldPriceDecrease() { log("YieldVault balance before rebalance: \(yieldVaultBalance ?? 0.0)") + // Rebalance YieldVault: AutoBalancer detects deficit (YT value dropped from $61.54 to $6.15) + // and pulls FLOW from Position via rebalanceSource, swaps to YT to partially recover rebalanceYieldVault(signer: flowYieldVaultsAccount, id: yieldVaultIDs![0], force: true, beFailed: false) + + // Position rebalance: Position health dropped below target after AutoBalancer pulled collateral, + // so it pulls from topUpSource to restore health. Position holds FLOW (not YT), so its health + // is not directly affected by YT price changes - only by AutoBalancer pulling collateral. rebalancePosition(signer: protocolAccount, pid: positionID, force: true, beFailed: false) closeYieldVault(signer: user, id: yieldVaultIDs![0], beFailed: false) @@ -273,14 +347,20 @@ fun test_RebalanceYieldVaultSucceedsAfterYieldPriceDecrease() { Test.assertEqual(0, yieldVaultIDs!.length) let flowBalanceAfter = getBalance(address: user.address, vaultPublicPath: /public/flowTokenReceiver)! - let expectedBalance = fundingAmount * 0.5 - Test.assert((flowBalanceAfter-flowBalanceBefore) <= expectedBalance, - message: "Expected user's Flow balance after rebalance to be less than the original, due to decrease in yield price but got \(flowBalanceAfter)") - - Test.assert( - (flowBalanceAfter-flowBalanceBefore) > 0.1, - message: "Expected user's Flow balance after rebalance to be more than zero but got \(flowBalanceAfter)" - ) + // After rebalancing, actual loss is ~30-35% (user gets back ~65-70 FLOW from 100 FLOW deposit) + // + // Loss breakdown: + // 1. YT price drops 90% ($1.00 -> $0.10), AutoBalancer holds ~61.54 YT + // 2. AutoBalancer value drops from $61.54 to $6.15 (loses $55.39) + // 3. AutoBalancer pulls ~24 FLOW from Position via rebalanceSource, swaps to YT + // 4. Position health drops from 1.3 to ~1.1, triggers topUpSource pull to restore health + // 5. User ends up with ~65-70 FLOW (30-35% loss) + // + // This is significantly better than without rebalanceSource (would be ~94% loss) + // but still substantial due to the extreme 90% price crash. + let returned = flowBalanceAfter - flowBalanceBefore + Test.assert(equalAmounts(a: returned, b: fundingAmount * 0.65, tolerance: 1.0), + message: "Expected ~65-70 FLOW returned after 90% YT crash (got \(returned))") } access(all) diff --git a/cadence/transactions/flow-yield-vaults/close_yield_vault.cdc b/cadence/transactions/flow-yield-vaults/close_yield_vault.cdc index 5c19e38b..20c2b6a5 100644 --- a/cadence/transactions/flow-yield-vaults/close_yield_vault.cdc +++ b/cadence/transactions/flow-yield-vaults/close_yield_vault.cdc @@ -35,7 +35,7 @@ transaction(id: UInt64) { let vaultCap = signer.capabilities.storage.issue<&{FungibleToken.Vault}>(vaultData.storagePath) let receiverCap = signer.capabilities.storage.issue<&{FungibleToken.Vault}>(vaultData.storagePath) signer.capabilities.publish(vaultCap, at: vaultData.metadataPath) - signer.capabilities.publish(vaultCap, at: vaultData.receiverPath) + signer.capabilities.publish(receiverCap, at: vaultData.receiverPath) } // reference the signer's receiver diff --git a/cadence/transactions/flow-yield-vaults/withdraw_from_yield_vault.cdc b/cadence/transactions/flow-yield-vaults/withdraw_from_yield_vault.cdc index 86427fbd..cecda16f 100644 --- a/cadence/transactions/flow-yield-vaults/withdraw_from_yield_vault.cdc +++ b/cadence/transactions/flow-yield-vaults/withdraw_from_yield_vault.cdc @@ -36,7 +36,7 @@ transaction(id: UInt64, amount: UFix64) { let vaultCap = signer.capabilities.storage.issue<&{FungibleToken.Vault}>(vaultData.storagePath) let receiverCap = signer.capabilities.storage.issue<&{FungibleToken.Vault}>(vaultData.storagePath) signer.capabilities.publish(vaultCap, at: vaultData.metadataPath) - signer.capabilities.publish(vaultCap, at: vaultData.receiverPath) + signer.capabilities.publish(receiverCap, at: vaultData.receiverPath) } // reference the signer's receiver diff --git a/flow.json b/flow.json index dd1f2ee7..9bc8b02b 100644 --- a/flow.json +++ b/flow.json @@ -1,5 +1,17 @@ { "contracts": { + "AdversarialReentrancyConnectors": { + "source": "./lib/FlowALP/cadence/tests/contracts/AdversarialReentrancyConnectors.cdc", + "aliases": { + "testing": "0000000000000008" + } + }, + "AdversarialTypeSpoofingConnectors": { + "source": "./lib/FlowALP/cadence/tests/contracts/AdversarialTypeSpoofingConnectors.cdc", + "aliases": { + "testing": "0000000000000008" + } + }, "BandOracleConnectors": { "source": "./lib/FlowALP/FlowActions/cadence/contracts/connectors/band-oracle/BandOracleConnectors.cdc", "aliases": { diff --git a/lib/FlowALP b/lib/FlowALP index d9970e3d..ee6fb772 160000 --- a/lib/FlowALP +++ b/lib/FlowALP @@ -1 +1 @@ -Subproject commit d9970e3d7aedffcb15eb1f953b299173c137f718 +Subproject commit ee6fb772aa24ab9867e0e28bacd8e9e1a0f1fe58