diff --git a/contracts/fund/FundV3WindDown.sol b/contracts/fund/FundV3WindDown.sol new file mode 100644 index 00000000..c3ab974e --- /dev/null +++ b/contracts/fund/FundV3WindDown.sol @@ -0,0 +1,428 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity >=0.6.10 <0.8.0; +pragma experimental ABIEncoderV2; + +import "@openzeppelin/contracts/access/Ownable.sol"; +import "@openzeppelin/contracts/math/SafeMath.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; + +import "../interfaces/IAprOracle.sol"; +import "../interfaces/IBallot.sol"; +import "../interfaces/IFundForPrimaryMarketV3.sol"; +import "../interfaces/IFundV3.sol"; +import "../interfaces/IPrimaryMarketV3.sol"; +import "../interfaces/ITrancheIndexV2.sol"; +import "../interfaces/ITwapOracleV2.sol"; +import "../interfaces/IWrappedERC20.sol"; +import "../utils/CoreUtility.sol"; + +interface IFundV3WindDownAprOracle { + // FundV3 has a public aprOracle variable, but IFundV3 does not include its getter. + function aprOracle() external view returns (IAprOracle); +} + +contract FundV3WindDown is + ITwapOracleV2, + IAprOracle, + IBallot, + IPrimaryMarketV3, + ITrancheIndexV2, + Ownable, + ReentrancyGuard, + CoreUtility +{ + using SafeMath for uint256; + + event Initialized( + uint256 frozenPrice, + uint256 frozenNavB, + uint256 frozenNavR, + uint256 frozenSplitRatio, + uint256 totalUnderlying, + uint256 totalSupplyQ, + uint256 totalSupplyB, + uint256 totalSupplyR + ); + event Activated(); + event Deactivated(); + event RedeemedAll( + address indexed account, + address indexed recipient, + uint256 inQ, + uint256 inB, + uint256 inR, + uint256 underlying + ); + + uint256 public constant MAX_STRATEGY_UNDERLYING_DUST = 1; + uint256 private constant UNIT = 1e18; + + address public immutable override fund; + ITwapOracleV2 public immutable oldTwapOracle; + IAprOracle public immutable oldAprOracle; + uint256 public immutable freezeDay; + + bool public initialized; + bool public active; + + uint256 public frozenPrice; + uint256 public frozenNavB; + uint256 public frozenNavR; + uint256 public frozenSplitRatio; + uint256 public initializedTotalUnderlying; + uint256 public initializedTotalSupplyQ; + uint256 public initializedTotalSupplyB; + uint256 public initializedTotalSupplyR; + + uint256 private _underlyingPerQ; + uint256 private _underlyingPerB; + uint256 private _underlyingPerR; + + constructor(address fund_, uint256 freezeDay_) public Ownable() { + require(fund_ != address(0), "Zero fund"); + require(freezeDay_ == _endOfDay(freezeDay_.sub(1)), "Invalid freeze day"); + require(freezeDay_ > block.timestamp, "Freeze day not future"); + + // Capture the original oracles at deployment. This contract must be deployed + // before the fund is updated to point at the wind-down contract. + ITwapOracleV2 oldTwapOracle_ = IFundV3(fund_).twapOracle(); + IAprOracle oldAprOracle_ = IFundV3WindDownAprOracle(fund_).aprOracle(); + require(address(oldTwapOracle_) != address(0), "Zero TWAP oracle"); + require(address(oldAprOracle_) != address(0), "Zero APR oracle"); + + fund = fund_; + oldTwapOracle = oldTwapOracle_; + oldAprOracle = oldAprOracle_; + freezeDay = freezeDay_; + } + + // ITwapOracle / ITwapOracleV2 implementation. + + function getTwap(uint256 timestamp) external view override returns (uint256) { + if (timestamp > freezeDay) { + // FundV3.settle() requires a nonzero TWAP. Returning zero after T + // permanently blocks future settlements and rebalances. + return 0; + } + return oldTwapOracle.getTwap(timestamp); + } + + function getLatest() external view override returns (uint256) { + if (block.timestamp < freezeDay) { + return oldTwapOracle.getLatest(); + } + if (initialized) { + return frozenPrice; + } + // Before initialize(), swap pools can still sync after final settlement + // using the frozen settlement TWAP instead of the live oracle price. + uint256 price = oldTwapOracle.getTwap(freezeDay); + require(price != 0, "Frozen price not ready"); + return price; + } + + // IAprOracle implementation. + + function capture() external override returns (uint256 dailyRate) { + // The old APR proxy performs the ShareStaking rebalance safety check. + // Keep that side effect/check, then force the BISHOP rate to zero for + // the frozen settlement day and later. Once T has arrived, use the fund + // day so delayed pre-T settlements still receive the old APR. + dailyRate = oldAprOracle.capture(); + if (block.timestamp >= freezeDay && IFundV3(fund).currentDay() >= freezeDay) { + return 0; + } + } + + // IBallot implementation. + + function count(uint256) external view override returns (uint256) { + return 0; + } + + function syncWithVotingEscrow(address) external override {} + + // IPrimaryMarketV3 view implementation. + + function getCreation(uint256) external view override returns (uint256 outQ) { + return 0; + } + + function getCreationForQ(uint256) external view override returns (uint256) { + revert("Wind down"); + } + + function getRedemption(uint256) external view override returns (uint256, uint256) { + revert("Wind down"); + } + + function getRedemptionForUnderlying(uint256) external view override returns (uint256) { + revert("Wind down"); + } + + function getSplit(uint256) external view override returns (uint256 outB) { + return 0; + } + + function getSplitForB(uint256) external view override returns (uint256 inQ) { + return 0; + } + + function getMerge(uint256) external view override returns (uint256 outQ, uint256 feeQ) { + return (0, 0); + } + + function getMergeForQ(uint256) external view override returns (uint256 inB) { + return 0; + } + + function canBeRemovedFromFund() external view override returns (bool) { + return true; + } + + // IPrimaryMarketV3 state-changing implementation. Legacy operations are + // intentionally blocked; users exit through redeemAll() or redeemAllAndUnwrap(). + + function create(address, uint256, uint256) external override returns (uint256) { + revert("Wind down"); + } + + function redeem(address, uint256, uint256, uint256) external override returns (uint256) { + revert("Wind down"); + } + + function redeemAndUnwrap( + address, + uint256, + uint256, + uint256 + ) external override returns (uint256) { + revert("Wind down"); + } + + function queueRedemption( + address, + uint256, + uint256, + uint256 + ) external override returns (uint256, uint256) { + revert("Wind down"); + } + + function claimRedemptions(address, uint256[] calldata) external override returns (uint256) { + revert("Wind down"); + } + + function claimRedemptionsAndUnwrap( + address, + uint256[] calldata + ) external override returns (uint256) { + revert("Wind down"); + } + + function split(address, uint256, uint256) external override returns (uint256) { + revert("Wind down"); + } + + function merge(address, uint256, uint256) external override returns (uint256) { + revert("Wind down"); + } + + function settle(uint256) external override {} + + // Wind-down owner controls. + + function initialize() external onlyOwner { + require(!initialized, "Already initialized"); + + IFundV3 fundContract = IFundV3(fund); + _checkFundReady(fundContract); + require(fundContract.currentDay() > freezeDay, "Final settlement not done"); + + uint256 price = oldTwapOracle.getTwap(freezeDay); + require(price != 0, "Frozen price not ready"); + + // Use the actual hot token balance, not getTotalUnderlying(), because + // getTotalUnderlying() includes stale strategy-accounting dust. + (uint256 navB, uint256 navR) = fundContract.historicalNavs(freezeDay); + uint256 navSum = navB.add(navR); + uint256 splitRatio = fundContract.splitRatio(); + uint256 totalUnderlying = IERC20(fundContract.tokenUnderlying()).balanceOf(fund); + uint256 totalSupplyQ = fundContract.trancheTotalSupply(TRANCHE_Q); + uint256 totalSupplyB = fundContract.trancheTotalSupply(TRANCHE_B); + uint256 totalSupplyR = fundContract.trancheTotalSupply(TRANCHE_R); + + uint256 valuePerQ = splitRatio.mul(navSum).div(UNIT); + uint256 totalValueShares = totalSupplyQ.mul(valuePerQ).add(totalSupplyB.mul(navB)).add( + totalSupplyR.mul(navR) + ); + require(totalUnderlying > 0, "No underlying"); + require(totalValueShares > 0, "No share value"); + + // Fixed per-token rates make redemption order irrelevant; after B/R + // burns, FundV3's equivalent-total supply formulas become unreliable. + frozenPrice = price; + frozenNavB = navB; + frozenNavR = navR; + frozenSplitRatio = splitRatio; + initializedTotalUnderlying = totalUnderlying; + initializedTotalSupplyQ = totalSupplyQ; + initializedTotalSupplyB = totalSupplyB; + initializedTotalSupplyR = totalSupplyR; + _underlyingPerQ = totalUnderlying.mul(valuePerQ).mul(UNIT).div(totalValueShares); + _underlyingPerB = totalUnderlying.mul(navB).mul(UNIT).div(totalValueShares); + _underlyingPerR = totalUnderlying.mul(navR).mul(UNIT).div(totalValueShares); + initialized = true; + + emit Initialized( + price, + navB, + navR, + splitRatio, + totalUnderlying, + totalSupplyQ, + totalSupplyB, + totalSupplyR + ); + } + + function activate() external onlyOwner { + require(initialized, "Not initialized"); + require(!active, "Already active"); + + IFundV3 fundContract = IFundV3(fund); + _checkFundReady(fundContract); + require( + IERC20(fundContract.tokenUnderlying()).balanceOf(fund) >= + _getTotalRedeemableUnderlying(fundContract), + "Insufficient underlying" + ); + + active = true; + emit Activated(); + } + + function deactivate() external onlyOwner { + require(active, "Not active"); + active = false; + emit Deactivated(); + } + + // Wind-down redemption views. + + function underlyingPerQ() external view returns (uint256) { + _requireInitialized(); + return _underlyingPerQ; + } + + function underlyingPerB() external view returns (uint256) { + _requireInitialized(); + return _underlyingPerB; + } + + function underlyingPerR() external view returns (uint256) { + _requireInitialized(); + return _underlyingPerR; + } + + function getRedeemAll(address account) public view returns (uint256 underlying) { + _requireInitialized(); + (uint256 inQ, uint256 inB, uint256 inR) = IFundV3(fund).trancheAllBalanceOf(account); + return _getUnderlying(inQ, inB, inR); + } + + // Wind-down redemption entrypoint. + + function redeemAll( + address recipient, + uint256 minUnderlying + ) external nonReentrant returns (uint256 underlying) { + (uint256 inQ, uint256 inB, uint256 inR, uint256 underlying_) = _burnRedeemAll( + minUnderlying + ); + underlying = underlying_; + + IFundForPrimaryMarketV3(fund).primaryMarketTransferUnderlying(recipient, underlying, 0); + + emit RedeemedAll(msg.sender, recipient, inQ, inB, inR, underlying); + } + + function redeemAllAndUnwrap( + address recipient, + uint256 minUnderlying + ) external nonReentrant returns (uint256 underlying) { + (uint256 inQ, uint256 inB, uint256 inR, uint256 underlying_) = _burnRedeemAll( + minUnderlying + ); + underlying = underlying_; + + IFundForPrimaryMarketV3(fund).primaryMarketTransferUnderlying(address(this), underlying, 0); + IWrappedERC20(IFundV3(fund).tokenUnderlying()).withdraw(underlying); + (bool success, ) = recipient.call{value: underlying}(""); + require(success, "Transfer failed"); + + emit RedeemedAll(msg.sender, recipient, inQ, inB, inR, underlying); + } + + // Internal helpers. + + function _burnRedeemAll( + uint256 minUnderlying + ) private returns (uint256 inQ, uint256 inB, uint256 inR, uint256 underlying) { + require(active, "Not active"); + + IFundV3 fundContract = IFundV3(fund); + uint256 version = fundContract.getRebalanceSize(); + (inQ, inB, inR) = fundContract.trancheAllBalanceOf(msg.sender); + underlying = _getUnderlying(inQ, inB, inR); + require(underlying >= minUnderlying && underlying > 0, "Min underlying redeemed"); + + IFundForPrimaryMarketV3 fundForPrimaryMarket = IFundForPrimaryMarketV3(fund); + if (inQ > 0) { + fundForPrimaryMarket.primaryMarketBurn(TRANCHE_Q, msg.sender, inQ, version); + } + if (inB > 0) { + fundForPrimaryMarket.primaryMarketBurn(TRANCHE_B, msg.sender, inB, version); + } + if (inR > 0) { + fundForPrimaryMarket.primaryMarketBurn(TRANCHE_R, msg.sender, inR, version); + } + } + + function _checkFundReady(IFundV3 fundContract) private view { + require(fundContract.primaryMarket() == address(this), "Not primary market"); + require(fundContract.strategy() == address(0), "Strategy not cleared"); + require( + fundContract.getStrategyUnderlying() <= MAX_STRATEGY_UNDERLYING_DUST, + "Strategy underlying not cleared" + ); + require(fundContract.getTotalDebt() == 0, "Debt not cleared"); + } + + function _getUnderlying(uint256 inQ, uint256 inB, uint256 inR) private view returns (uint256) { + return + inQ.mul(_underlyingPerQ).div(UNIT).add(inB.mul(_underlyingPerB).div(UNIT)).add( + inR.mul(_underlyingPerR).div(UNIT) + ); + } + + function _getTotalRedeemableUnderlying(IFundV3 fundContract) private view returns (uint256) { + return + _getUnderlying( + fundContract.trancheTotalSupply(TRANCHE_Q), + fundContract.trancheTotalSupply(TRANCHE_B), + fundContract.trancheTotalSupply(TRANCHE_R) + ); + } + + function _requireInitialized() private view { + require(initialized, "Not initialized"); + } + + function _endOfDay(uint256 timestamp) private pure returns (uint256) { + return ((timestamp.add(1 days) - SETTLEMENT_TIME) / 1 days) * 1 days + SETTLEMENT_TIME; + } + + receive() external payable {} +} diff --git a/contracts/fund/PrimaryMarketV4.sol b/contracts/fund/PrimaryMarketV4.sol new file mode 100644 index 00000000..e307d34a --- /dev/null +++ b/contracts/fund/PrimaryMarketV4.sol @@ -0,0 +1,586 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity >=0.6.10 <0.8.0; +pragma experimental ABIEncoderV2; + +import "@openzeppelin/contracts/math/Math.sol"; +import "@openzeppelin/contracts/math/SafeMath.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; +import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; + +import "../utils/SafeDecimalMath.sol"; + +import "../interfaces/IPrimaryMarketV3.sol"; +import "../interfaces/IFundV3.sol"; +import "../interfaces/IFundForPrimaryMarketV4.sol"; +import "../interfaces/ITrancheIndexV2.sol"; +import "../interfaces/IWrappedERC20.sol"; + +contract PrimaryMarketV4 is IPrimaryMarketV3, ReentrancyGuard, ITrancheIndexV2, Ownable { + event Created(address indexed account, uint256 underlying, uint256 outQ); + event Redeemed(address indexed account, uint256 inQ, uint256 underlying, uint256 feeQ); + event Split(address indexed account, uint256 inQ, uint256 outB, uint256 outR); + event Merged( + address indexed account, + uint256 outQ, + uint256 inB, + uint256 inR, + uint256 feeUnderlying + ); + event RedemptionQueued(address indexed account, uint256 index, uint256 underlying); + event RedemptionPopped(uint256 count, uint256 newHead, uint256 requiredUnderlying); + event RedemptionClaimed(address indexed account, uint256 index, uint256 underlying); + event FundCapUpdated(uint256 newCap); + event RedemptionFeeRateUpdated(uint256 newRedemptionFeeRate); + event MergeFeeRateUpdated(uint256 newMergeFeeRate); + + using SafeMath for uint256; + using SafeDecimalMath for uint256; + using SafeERC20 for IERC20; + + struct QueuedRedemption { + address account; + uint256 underlying; + uint256 previousPrefixSum; + } + + uint256 private constant MAX_REDEMPTION_FEE_RATE = 0.01e18; + uint256 private constant MAX_MERGE_FEE_RATE = 0.01e18; + + address public immutable override fund; + bool public immutable redemptionFlag; + bool public immutable splitFlag; + IERC20 private immutable _tokenUnderlying; + + uint256 public redemptionFeeRate; + uint256 public mergeFeeRate; + + /// @notice The upper limit of underlying that the fund can hold. This contract rejects + /// creations that may break this limit. + /// @dev This limit can be bypassed if the fund has multiple primary markets. + /// + /// Set it to uint(-1) to skip the check and save gas. + uint256 public fundCap; + + /// @notice Queue of redemptions that cannot be claimed yet. Key is a sequential index + /// starting from zero. Value is a tuple of user address, redeemed underlying and + /// prefix sum before this entry. + mapping(uint256 => QueuedRedemption) public queuedRedemptions; + + /// @notice Total underlying tokens of claimable queued redemptions. + uint256 public claimableUnderlying; + + /// @notice Index of the redemption queue head. All redemptions with index smaller than + /// this value can be claimed now. + uint256 public redemptionQueueHead; + + /// @notice Index of the redemption following the last entry of the queue. The next queued + /// redemption will be written at this index. + uint256 public redemptionQueueTail; + + constructor( + address fund_, + uint256 redemptionFeeRate_, + uint256 mergeFeeRate_, + uint256 fundCap_, + bool redemptionFlag_, + bool splitFlag_ + ) public Ownable() { + fund = fund_; + _tokenUnderlying = IERC20(IFundV3(fund_).tokenUnderlying()); + _updateRedemptionFeeRate(redemptionFeeRate_); + _updateMergeFeeRate(mergeFeeRate_); + _updateFundCap(fundCap_); + redemptionFlag = redemptionFlag_; + splitFlag = splitFlag_; + } + + /// @notice Calculate the result of a creation. + /// @param underlying Underlying amount spent for the creation + /// @return outQ Created QUEEN amount + function getCreation(uint256 underlying) public view override returns (uint256 outQ) { + uint256 fundUnderlying = IFundV3(fund).getTotalUnderlying(); + uint256 fundEquivalentTotalQ = IFundV3(fund).getEquivalentTotalQ(); + require(fundUnderlying.add(underlying) <= fundCap, "Exceed fund cap"); + if (fundEquivalentTotalQ == 0) { + outQ = underlying.mul(IFundV3(fund).underlyingDecimalMultiplier()); + uint256 splitRatio = IFundV3(fund).splitRatio(); + require(splitRatio != 0, "Fund is not initialized"); + uint256 settledDay = IFundV3(fund).currentDay() - 1 days; + uint256 underlyingPrice = IFundV3(fund).twapOracle().getTwap(settledDay); + (uint256 navB, uint256 navR) = IFundV3(fund).historicalNavs(settledDay); + outQ = outQ.mul(underlyingPrice).div(splitRatio).divideDecimal(navB.add(navR)); + } else { + require( + fundUnderlying != 0, + "Cannot create QUEEN for fund with shares but no underlying" + ); + outQ = underlying.mul(fundEquivalentTotalQ).div(fundUnderlying); + } + } + + /// @notice Calculate the amount of underlying tokens to create at least the given QUEEN amount. + /// This only works with non-empty fund for simplicity. + /// @param minOutQ Minimum received QUEEN amount + /// @return underlying Underlying amount that should be used for creation + function getCreationForQ(uint256 minOutQ) external view override returns (uint256 underlying) { + // Assume: + // minOutQ * fundUnderlying = a * fundEquivalentTotalQ - b + // where a and b are integers and 0 <= b < fundEquivalentTotalQ + // Then + // underlying = a + // getCreation(underlying) + // = floor(a * fundEquivalentTotalQ / fundUnderlying) + // >= floor((a * fundEquivalentTotalQ - b) / fundUnderlying) + // = minOutQ + // getCreation(underlying - 1) + // = floor((a * fundEquivalentTotalQ - fundEquivalentTotalQ) / fundUnderlying) + // < (a * fundEquivalentTotalQ - b) / fundUnderlying + // = minOutQ + uint256 fundUnderlying = IFundV3(fund).getTotalUnderlying(); + uint256 fundEquivalentTotalQ = IFundV3(fund).getEquivalentTotalQ(); + require(fundEquivalentTotalQ > 0, "Cannot calculate creation for empty fund"); + return minOutQ.mul(fundUnderlying).add(fundEquivalentTotalQ - 1).div(fundEquivalentTotalQ); + } + + function _getRedemption(uint256 inQ) private view returns (uint256 underlying) { + uint256 fundUnderlying = IFundV3(fund).getTotalUnderlying(); + uint256 fundEquivalentTotalQ = IFundV3(fund).getEquivalentTotalQ(); + underlying = inQ.mul(fundUnderlying).div(fundEquivalentTotalQ); + } + + /// @notice Calculate the result of a redemption. + /// @param inQ QUEEN amount spent for the redemption + /// @return underlying Redeemed underlying amount + /// @return feeQ QUEEN amount charged as redemption fee + function getRedemption( + uint256 inQ + ) public view override returns (uint256 underlying, uint256 feeQ) { + feeQ = inQ.multiplyDecimal(redemptionFeeRate); + underlying = _getRedemption(inQ - feeQ); + } + + /// @notice Calculate the amount of QUEEN that can be redeemed for at least the given amount + /// of underlying tokens. + /// @dev The return value may not be the minimum solution due to rounding errors. + /// @param minUnderlying Minimum received underlying amount + /// @return inQ QUEEN amount that should be redeemed + function getRedemptionForUnderlying( + uint256 minUnderlying + ) external view override returns (uint256 inQ) { + // Assume: + // minUnderlying * fundEquivalentTotalQ = a * fundUnderlying - b + // a * 1e18 = c * (1e18 - redemptionFeeRate) + d + // where + // a, b, c, d are integers + // 0 <= b < fundUnderlying + // 0 <= d < 1e18 - redemeptionFeeRate + // Then + // inQAfterFee = a + // inQ = c + // getRedemption(inQ).underlying + // = floor((c - floor(c * redemptionFeeRate / 1e18)) * fundUnderlying / fundEquivalentTotalQ) + // = floor(ceil(c * (1e18 - redemptionFeeRate) / 1e18) * fundUnderlying / fundEquivalentTotalQ) + // = floor(((c * (1e18 - redemptionFeeRate) + d) / 1e18) * fundUnderlying / fundEquivalentTotalQ) + // = floor(a * fundUnderlying / fundEquivalentTotalQ) + // => floor((a * fundUnderlying - b) / fundEquivalentTotalQ) + // = minUnderlying + uint256 fundUnderlying = IFundV3(fund).getTotalUnderlying(); + uint256 fundEquivalentTotalQ = IFundV3(fund).getEquivalentTotalQ(); + uint256 inQAfterFee = minUnderlying.mul(fundEquivalentTotalQ).add(fundUnderlying - 1).div( + fundUnderlying + ); + return inQAfterFee.divideDecimal(1e18 - redemptionFeeRate); + } + + /// @notice Calculate the result of a split. + /// @param inQ QUEEN amount to be split + /// @return outB Received BISHOP amount, which is also received ROOK amount + function getSplit(uint256 inQ) public view override returns (uint256 outB) { + return inQ.multiplyDecimal(IFundV3(fund).splitRatio()); + } + + /// @notice Calculate the amount of QUEEN that can be split into at least the given amount of + /// BISHOP and ROOK. + /// @param minOutB Received BISHOP amount, which is also received ROOK amount + /// @return inQ QUEEN amount that should be split + function getSplitForB(uint256 minOutB) external view override returns (uint256 inQ) { + uint256 splitRatio = IFundV3(fund).splitRatio(); + return minOutB.mul(1e18).add(splitRatio.sub(1)).div(splitRatio); + } + + /// @notice Calculate the result of a merge. + /// @param inB Spent BISHOP amount, which is also spent ROOK amount + /// @return outQ Received QUEEN amount + /// @return feeQ QUEEN amount charged as merge fee + function getMerge(uint256 inB) public view override returns (uint256 outQ, uint256 feeQ) { + uint256 outQBeforeFee = inB.divideDecimal(IFundV3(fund).splitRatio()); + feeQ = outQBeforeFee.multiplyDecimal(mergeFeeRate); + outQ = outQBeforeFee.sub(feeQ); + } + + /// @notice Calculate the amount of BISHOP and ROOK that can be merged into at least + /// the given amount of QUEEN. + /// @dev The return value may not be the minimum solution due to rounding errors. + /// @param minOutQ Minimum received QUEEN amount + /// @return inB BISHOP amount that should be merged, which is also spent ROOK amount + function getMergeForQ(uint256 minOutQ) external view override returns (uint256 inB) { + // Assume: + // minOutQ * 1e18 = a * (1e18 - mergeFeeRate) + b + // c = ceil(a * splitRatio / 1e18) + // where a and b are integers and 0 <= b < 1e18 - mergeFeeRate + // Then + // outQBeforeFee = a + // inB = c + // getMerge(inB).outQ + // = c * 1e18 / splitRatio - floor(c * 1e18 / splitRatio * mergeFeeRate / 1e18) + // = ceil(c * 1e18 / splitRatio * (1e18 - mergeFeeRate) / 1e18) + // >= ceil(a * (1e18 - mergeFeeRate) / 1e18) + // = (a * (1e18 - mergeFeeRate) + b) / 1e18 // because b < 1e18 + // = minOutQ + uint256 outQBeforeFee = minOutQ.divideDecimal(1e18 - mergeFeeRate); + inB = outQBeforeFee.mul(IFundV3(fund).splitRatio()).add(1e18 - 1).div(1e18); + } + + /// @notice Return index of the first queued redemption that cannot be claimed now. + /// Users can use this function to determine which indices can be passed to + /// `claimRedemptions()`. + /// @return Index of the first redemption that cannot be claimed now + function getNewRedemptionQueueHead() external view returns (uint256) { + uint256 available = _tokenUnderlying.balanceOf(fund); + uint256 l = redemptionQueueHead; + uint256 r = redemptionQueueTail; + uint256 startPrefixSum = queuedRedemptions[l].previousPrefixSum; + // overflow is desired + if (queuedRedemptions[r].previousPrefixSum - startPrefixSum <= available) { + return r; + } + // Iteration count is bounded by log2(tail - head), which is at most 256. + while (l + 1 < r) { + uint256 m = (l + r) / 2; + if (queuedRedemptions[m].previousPrefixSum - startPrefixSum <= available) { + l = m; + } else { + r = m; + } + } + return l; + } + + /// @notice Search in the redemption queue. + /// @param account Owner of the redemptions, or zero address to return all redemptions + /// @param startIndex Redemption index where the search starts, or zero to start from the head + /// @param maxIterationCount Maximum number of redemptions to be scanned, or zero for no limit + /// @return indices Indices of found redemptions + /// @return underlying Total underlying of found redemptions + function getQueuedRedemptions( + address account, + uint256 startIndex, + uint256 maxIterationCount + ) external view returns (uint256[] memory indices, uint256 underlying) { + uint256 head = redemptionQueueHead; + uint256 tail = redemptionQueueTail; + if (startIndex == 0) { + startIndex = head; + } else { + require(startIndex >= head && startIndex <= tail, "startIndex out of bound"); + } + uint256 endIndex = tail; + if (maxIterationCount != 0 && tail - startIndex > maxIterationCount) { + endIndex = startIndex + maxIterationCount; + } + indices = new uint256[](endIndex - startIndex); + uint256 count = 0; + for (uint256 i = startIndex; i < endIndex; i++) { + if (account == address(0) || queuedRedemptions[i].account == account) { + indices[count] = i; + underlying += queuedRedemptions[i].underlying; + count++; + } + } + if (count != endIndex - startIndex) { + // Shrink the array + assembly { + mstore(indices, count) + } + } + } + + /// @notice Return whether the fund can change its primary market to another contract. + function canBeRemovedFromFund() external view override returns (bool) { + return redemptionQueueHead == redemptionQueueTail; + } + + /// @notice Create QUEEN using underlying tokens. This function should be called by + /// a smart contract, which transfers underlying tokens to this contract + /// in the same transaction. + /// @param recipient Address that will receive created QUEEN + /// @param minOutQ Minimum QUEEN amount to be received + /// @param version The latest rebalance version + /// @return outQ Received QUEEN amount + function create( + address recipient, + uint256 minOutQ, + uint256 version + ) external override nonReentrant returns (uint256 outQ) { + uint256 underlying = _tokenUnderlying.balanceOf(address(this)).sub(claimableUnderlying); + outQ = getCreation(underlying); + require(outQ >= minOutQ && outQ > 0, "Min QUEEN created"); + IFundForPrimaryMarketV4(fund).primaryMarketMint(TRANCHE_Q, recipient, outQ, version); + _tokenUnderlying.safeTransfer(fund, underlying); + emit Created(recipient, underlying, outQ); + } + + /// @notice Redeem QUEEN to get underlying tokens back. Revert if there are still some + /// queued redemptions that cannot be claimed now. + /// @param recipient Address that will receive redeemed underlying tokens + /// @param inQ Spent QUEEN amount + /// @param minUnderlying Minimum amount of underlying tokens to be received + /// @param version The latest rebalance version + /// @return underlying Received underlying amount + function redeem( + address recipient, + uint256 inQ, + uint256 minUnderlying, + uint256 version + ) external override nonReentrant returns (uint256 underlying) { + underlying = _redeem(recipient, inQ, minUnderlying, version); + } + + /// @notice Redeem QUEEN to get native currency back. The underlying must be wrapped token + /// of the native currency. Revert if there are still some queued redemptions that + /// cannot be claimed now. + /// @param recipient Address that will receive redeemed underlying tokens + /// @param inQ Spent QUEEN amount + /// @param minUnderlying Minimum amount of underlying tokens to be received + /// @param version The latest rebalance version + /// @return underlying Received underlying amount + function redeemAndUnwrap( + address recipient, + uint256 inQ, + uint256 minUnderlying, + uint256 version + ) external override nonReentrant returns (uint256 underlying) { + underlying = _redeem(address(this), inQ, minUnderlying, version); + IWrappedERC20(address(_tokenUnderlying)).withdraw(underlying); + (bool success, ) = recipient.call{value: underlying}(""); + require(success, "Transfer failed"); + } + + function _redeem( + address recipient, + uint256 inQ, + uint256 minUnderlying, + uint256 version + ) private allowRedemption returns (uint256 underlying) { + uint256 feeQ; + (underlying, feeQ) = getRedemption(inQ); + IFundForPrimaryMarketV4(fund).primaryMarketBurn(TRANCHE_Q, msg.sender, inQ, version); + _popRedemptionQueue(0); + require(underlying >= minUnderlying && underlying > 0, "Min underlying redeemed"); + // Redundant check for user-friendly revert message. + require(underlying <= _tokenUnderlying.balanceOf(fund), "Not enough underlying in fund"); + IFundForPrimaryMarketV4(fund).primaryMarketTransferUnderlying(recipient, underlying, feeQ); + emit Redeemed(recipient, inQ, underlying, feeQ); + } + + /// @notice Redeem QUEEN and wait in the redemption queue. Redeemed underlying tokens will + /// be claimable when the fund has enough balance to pay this redemption and all + /// previous ones in the queue. + /// @param recipient Address that will receive redeemed underlying tokens + /// @param inQ Spent QUEEN amount + /// @param minUnderlying Minimum amount of underlying tokens to be received + /// @param version The latest rebalance version + /// @return underlying Received underlying amount + /// @return index Index of the queued redemption + function queueRedemption( + address recipient, + uint256 inQ, + uint256 minUnderlying, + uint256 version + ) external override nonReentrant allowRedemption returns (uint256 underlying, uint256 index) { + uint256 feeQ; + (underlying, feeQ) = getRedemption(inQ); + IFundForPrimaryMarketV4(fund).primaryMarketBurn(TRANCHE_Q, msg.sender, inQ, version); + require(underlying >= minUnderlying && underlying > 0, "Min underlying redeemed"); + index = redemptionQueueTail; + QueuedRedemption storage newRedemption = queuedRedemptions[index]; + newRedemption.account = recipient; + newRedemption.underlying = underlying; + // overflow is desired + queuedRedemptions[index + 1].previousPrefixSum = + newRedemption.previousPrefixSum + + underlying; + redemptionQueueTail = index + 1; + IFundForPrimaryMarketV4(fund).primaryMarketAddDebtAndFee(underlying, feeQ); + emit Redeemed(recipient, inQ, underlying, feeQ); + emit RedemptionQueued(recipient, index, underlying); + } + + /// @notice Remove a given number of redemptions from the front of the redemption queue and + /// fetch underlying tokens of these redemptions from the fund. Revert if the fund + /// cannot pay these redemptions now. + /// @param count The number of redemptions to be removed, or zero to completely empty the queue + function popRedemptionQueue(uint256 count) external nonReentrant { + _popRedemptionQueue(count); + } + + function _popRedemptionQueue(uint256 count) private { + uint256 oldHead = redemptionQueueHead; + uint256 oldTail = redemptionQueueTail; + uint256 newHead; + if (count == 0) { + if (oldHead == oldTail) { + return; + } + newHead = oldTail; + } else { + newHead = oldHead.add(count); + require(newHead <= oldTail, "Redemption queue out of bound"); + } + // overflow is desired + uint256 requiredUnderlying = queuedRedemptions[newHead].previousPrefixSum - + queuedRedemptions[oldHead].previousPrefixSum; + // Redundant check for user-friendly revert message. + require( + requiredUnderlying <= _tokenUnderlying.balanceOf(fund), + "Not enough underlying in fund" + ); + claimableUnderlying = claimableUnderlying.add(requiredUnderlying); + IFundForPrimaryMarketV4(fund).primaryMarketPayDebt(requiredUnderlying); + redemptionQueueHead = newHead; + emit RedemptionPopped(newHead - oldHead, newHead, requiredUnderlying); + } + + /// @notice Claim underlying tokens of queued redemptions. All these redemptions must + /// belong to the same account. + /// @param account Recipient of the redemptions + /// @param indices Indices of the redemptions in the queue, which must be in increasing order + /// @return underlying Total claimed underlying amount + function claimRedemptions( + address account, + uint256[] calldata indices + ) external override nonReentrant returns (uint256 underlying) { + underlying = _claimRedemptions(account, indices); + _tokenUnderlying.safeTransfer(account, underlying); + } + + /// @notice Claim native currency of queued redemptions. The underlying must be wrapped token + /// of the native currency. All these redemptions must belong to the same account. + /// @param account Recipient of the redemptions + /// @param indices Indices of the redemptions in the queue, which must be in increasing order + /// @return underlying Total claimed underlying amount + function claimRedemptionsAndUnwrap( + address account, + uint256[] calldata indices + ) external override nonReentrant returns (uint256 underlying) { + underlying = _claimRedemptions(account, indices); + IWrappedERC20(address(_tokenUnderlying)).withdraw(underlying); + (bool success, ) = account.call{value: underlying}(""); + require(success, "Transfer failed"); + } + + function _claimRedemptions( + address account, + uint256[] calldata indices + ) private returns (uint256 underlying) { + uint256 count = indices.length; + if (count == 0) { + return 0; + } + uint256 head = redemptionQueueHead; + if (indices[count - 1] >= head) { + _popRedemptionQueue(indices[count - 1] - head + 1); + } + for (uint256 i = 0; i < count; i++) { + require(i == 0 || indices[i] > indices[i - 1], "Indices out of order"); + QueuedRedemption storage redemption = queuedRedemptions[indices[i]]; + uint256 redemptionUnderlying = redemption.underlying; + require( + redemption.account == account && redemptionUnderlying != 0, + "Invalid redemption index" + ); + underlying = underlying.add(redemptionUnderlying); + emit RedemptionClaimed(account, indices[i], redemptionUnderlying); + delete queuedRedemptions[indices[i]]; + } + claimableUnderlying = claimableUnderlying.sub(underlying); + } + + function split( + address recipient, + uint256 inQ, + uint256 version + ) external override allowSplit returns (uint256 outB) { + outB = getSplit(inQ); + IFundForPrimaryMarketV4(fund).primaryMarketBurn(TRANCHE_Q, msg.sender, inQ, version); + IFundForPrimaryMarketV4(fund).primaryMarketMint(TRANCHE_B, recipient, outB, version); + IFundForPrimaryMarketV4(fund).primaryMarketMint(TRANCHE_R, recipient, outB, version); + emit Split(recipient, inQ, outB, outB); + } + + function merge( + address recipient, + uint256 inB, + uint256 version + ) external override returns (uint256 outQ) { + uint256 feeQ; + (outQ, feeQ) = getMerge(inB); + IFundForPrimaryMarketV4(fund).primaryMarketBurn(TRANCHE_B, msg.sender, inB, version); + IFundForPrimaryMarketV4(fund).primaryMarketBurn(TRANCHE_R, msg.sender, inB, version); + IFundForPrimaryMarketV4(fund).primaryMarketMint(TRANCHE_Q, recipient, outQ, version); + IFundForPrimaryMarketV4(fund).primaryMarketAddDebtAndFee(0, feeQ); + emit Merged(recipient, outQ, inB, inB, feeQ); + } + + /// @dev Nothing to do for daily fund settlement. + function settle(uint256 day) external override onlyFund {} + + function _updateFundCap(uint256 newCap) private { + fundCap = newCap; + emit FundCapUpdated(newCap); + } + + function updateFundCap(uint256 newCap) external onlyOwner { + _updateFundCap(newCap); + } + + function _updateRedemptionFeeRate(uint256 newRedemptionFeeRate) private { + require(newRedemptionFeeRate <= MAX_REDEMPTION_FEE_RATE, "Exceed max redemption fee rate"); + redemptionFeeRate = newRedemptionFeeRate; + emit RedemptionFeeRateUpdated(newRedemptionFeeRate); + } + + function updateRedemptionFeeRate(uint256 newRedemptionFeeRate) external onlyOwner { + _updateRedemptionFeeRate(newRedemptionFeeRate); + } + + function _updateMergeFeeRate(uint256 newMergeFeeRate) private { + require(newMergeFeeRate <= MAX_MERGE_FEE_RATE, "Exceed max merge fee rate"); + mergeFeeRate = newMergeFeeRate; + emit MergeFeeRateUpdated(newMergeFeeRate); + } + + function updateMergeFeeRate(uint256 newMergeFeeRate) external onlyOwner { + _updateMergeFeeRate(newMergeFeeRate); + } + + /// @notice Receive unwrapped transfer from the wrapped token. + receive() external payable {} + + modifier onlyFund() { + require(msg.sender == fund, "Only fund"); + _; + } + + modifier allowRedemption() { + require(redemptionFlag, "Redemption N/A"); + _; + } + + modifier allowSplit() { + require(splitFlag, "Split N/A"); + _; + } +} diff --git a/contracts/governance/CrossChainWrappedToken.sol b/contracts/governance/CrossChainWrappedToken.sol new file mode 100644 index 00000000..9c79fa3f --- /dev/null +++ b/contracts/governance/CrossChainWrappedToken.sol @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity >=0.6.10 <0.8.0; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "../layerzero/NonblockingLzApp.sol"; + +contract CrossChainWrappedToken is ERC20, NonblockingLzApp { + event CrossChainWrapped(uint256 amount); + event CrossChainUnwrapping(address account, uint256 amount); + + uint16 public immutable subLzChainID; + + constructor( + string memory name_, + string memory symbol_, + uint16 subLzChainID_, + address endpoint_ + ) public ERC20(name_, symbol_) NonblockingLzApp(endpoint_) { + subLzChainID = subLzChainID_; + } + + function unwrap(address to, uint256 amount, bytes memory adapterParams) external payable { + require(amount != 0); + _burn(msg.sender, amount); + + _checkGasLimit(subLzChainID, 0 /*type*/, adapterParams, 0 /*extraGas*/); + _lzSend( + subLzChainID, + abi.encode(to, amount), + msg.sender == tx.origin ? msg.sender : payable(owner()), // To avoid reentrancy + address(0x0), + adapterParams, + msg.value + ); + emit CrossChainUnwrapping(to, amount); + } + + /// @dev Receive the cross-chain message and mint the wrapped token + function _nonblockingLzReceive( + uint16, + bytes memory, + uint64, + bytes memory data + ) internal override { + uint256 amount = abi.decode(data, (uint256)); + _mint(owner(), amount); + emit CrossChainWrapped(amount); + } +} diff --git a/contracts/governance/CrossChainWrapper.sol b/contracts/governance/CrossChainWrapper.sol new file mode 100644 index 00000000..1a985232 --- /dev/null +++ b/contracts/governance/CrossChainWrapper.sol @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity >=0.6.10 <0.8.0; + +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; +import "../layerzero/NonblockingLzApp.sol"; + +contract CrossChainWrapper is NonblockingLzApp { + event CrossChainWrapping(uint256 amount); + event CrossChainUnwrapped(address account, uint256 amount); + + using SafeERC20 for IERC20; + + uint16 public immutable mainLzChainID; + IERC20 public immutable token; + + constructor( + uint16 mainLzChainID_, + address token_, + address endpoint_ + ) public NonblockingLzApp(endpoint_) { + mainLzChainID = mainLzChainID_; + token = IERC20(token_); + } + + function wrap(uint256 amount, bytes memory adapterParams) external payable { + token.safeTransferFrom(msg.sender, address(this), amount); + + _checkGasLimit(mainLzChainID, 0 /*type*/, adapterParams, 0 /*extraGas*/); + _lzSend( + mainLzChainID, + abi.encode(amount), + msg.sender == tx.origin ? msg.sender : payable(owner()), // To avoid reentrancy + address(0x0), + adapterParams, + msg.value + ); + + emit CrossChainWrapping(amount); + } + + /// @dev Receive the cross-chain message and unwrap the token + function _nonblockingLzReceive( + uint16, + bytes memory, + uint64, + bytes memory data + ) internal override { + (address to, uint256 amount) = abi.decode(data, (address, uint256)); + token.safeTransfer(to, amount); + emit CrossChainUnwrapped(to, amount); + } +} diff --git a/test/fundV3WindDown.ts b/test/fundV3WindDown.ts new file mode 100644 index 00000000..4e2ed973 --- /dev/null +++ b/test/fundV3WindDown.ts @@ -0,0 +1,931 @@ +import { expect } from "chai"; +import { BigNumber, Contract, Wallet } from "ethers"; +import type { Fixture, MockContract, MockProvider } from "ethereum-waffle"; +import { waffle, ethers } from "hardhat"; +const { loadFixture } = waffle; +const { parseEther } = ethers.utils; + +import { deployMockForName } from "./mock"; +import { + TRANCHE_Q, + TRANCHE_B, + TRANCHE_R, + DAY, + HOUR, + SETTLEMENT_TIME, + FixtureWalletMap, + advanceBlockAtTime, +} from "./utils"; + +const ROLE_UPDATE_MIN_DELAY = DAY * 3; + +function endOfDay(timestamp: number): number { + return Math.floor((timestamp + DAY - SETTLEMENT_TIME) / DAY) * DAY + SETTLEMENT_TIME; +} + +describe("FundV3WindDown", function () { + interface BasicFixtureData { + readonly wallets: FixtureWalletMap; + readonly freezeDay: number; + readonly fund: string; + readonly fundMock: MockContract; + readonly oldTwapOracle: MockContract; + readonly oldAprOracle: MockContract; + readonly windDown: Contract; + } + + interface IntegrationFixtureData { + readonly wallets: FixtureWalletMap; + readonly freezeDay: number; + readonly tokenUnderlying: Contract; + readonly oldTwapOracle: MockContract; + readonly oldAprOracle: MockContract; + readonly oldPrimaryMarket: MockContract; + readonly fund: Contract; + readonly windDown: Contract; + } + + let basicFixture: Fixture; + let integrationFixture: Fixture; + let delayedSettlementFixture: Fixture; + let gapIntegrationFixture: Fixture; + let rebalanceIntegrationFixture: Fixture; + let wrappedIntegrationFixture: Fixture; + + async function deployBasicFixture( + _wallets: Wallet[], + provider: MockProvider + ): Promise { + const [owner, user1] = provider.getWallets(); + const now = (await ethers.provider.getBlock("latest")).timestamp; + const freezeDay = endOfDay(now + DAY); + + const oldTwapOracle = await deployMockForName(owner, "ITwapOracleV2"); + const oldAprOracle = await deployMockForName(owner, "IAprOracle"); + const fund = await deployMockForName(owner, "FundV3"); + await fund.mock.twapOracle.returns(oldTwapOracle.address); + await fund.mock.aprOracle.returns(oldAprOracle.address); + + const WindDown = await ethers.getContractFactory("FundV3WindDown"); + const windDown = await WindDown.connect(owner).deploy(fund.address, freezeDay); + + return { + wallets: { owner, user1 }, + freezeDay, + fund: fund.address, + fundMock: fund, + oldTwapOracle, + oldAprOracle, + windDown, + }; + } + + async function deployPendingIntegrationFixture( + provider: MockProvider, + settlementPrice: BigNumber = parseEther("1"), + freezeDayDelay: number = 0, + wrappedUnderlying: boolean = false + ): Promise { + const [user1, user2, owner, feeCollector] = provider.getWallets(); + const now = (await ethers.provider.getBlock("latest")).timestamp; + await advanceBlockAtTime(endOfDay(now + DAY) - HOUR); + + const oldTwapOracle = await deployMockForName(owner, "ITwapOracleV2"); + await oldTwapOracle.mock.getTwap.returns(settlementPrice); + await oldTwapOracle.mock.getLatest.returns(parseEther("1")); + + const oldAprOracle = await deployMockForName(owner, "IAprOracle"); + await oldAprOracle.mock.capture.returns(0); + + const ballot = await deployMockForName(owner, "IBallot"); + await ballot.mock.count.returns(0); + + const shareQ = await deployMockForName(owner, "IShareV2"); + const shareB = await deployMockForName(owner, "IShareV2"); + const shareR = await deployMockForName(owner, "IShareV2"); + for (const share of [shareQ, shareB, shareR]) { + await share.mock.fundEmitTransfer.returns(); + await share.mock.fundEmitApproval.returns(); + } + + const oldPrimaryMarket = await deployMockForName(owner, "IPrimaryMarketV3"); + await oldPrimaryMarket.mock.settle.returns(); + await oldPrimaryMarket.mock.canBeRemovedFromFund.returns(true); + + let tokenUnderlying: Contract; + if (wrappedUnderlying) { + const MockWrappedToken = await ethers.getContractFactory("MockWrappedToken"); + tokenUnderlying = await MockWrappedToken.connect(owner).deploy("Wrapped BNB", "WBNB"); + } else { + const MockToken = await ethers.getContractFactory("MockToken"); + tokenUnderlying = await MockToken.connect(owner).deploy("Mock BTCB", "BTCB", 18); + } + + const Fund = await ethers.getContractFactory("FundV3"); + const fund = await Fund.connect(owner).deploy([ + tokenUnderlying.address, + 18, + shareQ.address, + shareB.address, + shareR.address, + oldPrimaryMarket.address, + ethers.constants.AddressZero, + 0, + parseEther("10"), + parseEther("0.1"), + oldTwapOracle.address, + oldAprOracle.address, + ballot.address, + feeCollector.address, + ]); + await fund.initialize(parseEther("1"), parseEther("1"), parseEther("1"), 0); + const freezeDay = (await fund.currentDay()).toNumber() + freezeDayDelay; + + const WindDown = await ethers.getContractFactory("FundV3WindDown"); + const windDown = await WindDown.connect(owner).deploy(fund.address, freezeDay); + + if (wrappedUnderlying) { + await tokenUnderlying.connect(owner).deposit({ value: parseEther("90") }); + await tokenUnderlying.connect(owner).transfer(fund.address, parseEther("90")); + } else { + await tokenUnderlying.mint(fund.address, parseEther("90")); + } + await oldPrimaryMarket.call( + fund, + "primaryMarketMint", + TRANCHE_Q, + user1.address, + parseEther("10"), + 0 + ); + await oldPrimaryMarket.call( + fund, + "primaryMarketMint", + TRANCHE_B, + user1.address, + parseEther("20"), + 0 + ); + await oldPrimaryMarket.call( + fund, + "primaryMarketMint", + TRANCHE_R, + user1.address, + parseEther("20"), + 0 + ); + + await fund.connect(owner).updateTwapOracle(windDown.address); + await fund.connect(owner).updateAprOracle(windDown.address); + await fund.connect(owner).updateBallot(windDown.address); + await fund.connect(owner).proposePrimaryMarketUpdate(windDown.address); + + return { + wallets: { user1, user2, owner, feeCollector }, + freezeDay, + tokenUnderlying, + oldTwapOracle, + oldAprOracle, + oldPrimaryMarket, + fund, + windDown, + }; + } + + async function deployIntegrationFixture( + _wallets: Wallet[], + provider: MockProvider + ): Promise { + const data = await deployPendingIntegrationFixture(provider); + + await advanceBlockAtTime(data.freezeDay + 1); + await data.fund.settle(); + + await advanceBlockAtTime(data.freezeDay + ROLE_UPDATE_MIN_DELAY + 1); + await data.fund.connect(data.wallets.owner).applyPrimaryMarketUpdate(data.windDown.address); + + return data; + } + + async function deployDelayedSettlementFixture( + _wallets: Wallet[], + provider: MockProvider + ): Promise { + const data = await deployPendingIntegrationFixture(provider, parseEther("1"), DAY); + + await advanceBlockAtTime(data.freezeDay + 1); + + return data; + } + + async function deployGapIntegrationFixture( + _wallets: Wallet[], + provider: MockProvider + ): Promise { + const data = await deployPendingIntegrationFixture(provider); + + await advanceBlockAtTime(data.freezeDay + 1); + await data.fund.settle(); + + const version = await data.fund.getRebalanceSize(); + await data.oldPrimaryMarket.call( + data.fund, + "primaryMarketBurn", + TRANCHE_Q, + data.wallets.user1.address, + parseEther("2"), + version + ); + await data.oldPrimaryMarket.call( + data.fund, + "primaryMarketMint", + TRANCHE_B, + data.wallets.user1.address, + parseEther("2"), + version + ); + await data.oldPrimaryMarket.call( + data.fund, + "primaryMarketMint", + TRANCHE_R, + data.wallets.user1.address, + parseEther("2"), + version + ); + await data.oldPrimaryMarket.call( + data.fund, + "primaryMarketBurn", + TRANCHE_Q, + data.wallets.user1.address, + parseEther("1"), + version + ); + await data.oldPrimaryMarket.call( + data.fund, + "primaryMarketTransferUnderlying", + data.wallets.user2.address, + parseEther("3"), + 0 + ); + + await advanceBlockAtTime(data.freezeDay + ROLE_UPDATE_MIN_DELAY + 1); + await data.fund.connect(data.wallets.owner).applyPrimaryMarketUpdate(data.windDown.address); + + return data; + } + + async function deployRebalanceIntegrationFixture( + _wallets: Wallet[], + provider: MockProvider + ): Promise { + const data = await deployPendingIntegrationFixture(provider, parseEther("4")); + + await advanceBlockAtTime(data.freezeDay + 1); + await expect(() => data.fund.settle()).to.callMocks({ + func: data.oldAprOracle.mock.capture, + rets: [parseEther("0.05")], + }); + + await advanceBlockAtTime(data.freezeDay + ROLE_UPDATE_MIN_DELAY + 1); + await data.fund.connect(data.wallets.owner).applyPrimaryMarketUpdate(data.windDown.address); + + return data; + } + + async function deployWrappedIntegrationFixture( + _wallets: Wallet[], + provider: MockProvider + ): Promise { + const data = await deployPendingIntegrationFixture(provider, parseEther("1"), 0, true); + + await advanceBlockAtTime(data.freezeDay + 1); + await data.fund.settle(); + + await advanceBlockAtTime(data.freezeDay + ROLE_UPDATE_MIN_DELAY + 1); + await data.fund.connect(data.wallets.owner).applyPrimaryMarketUpdate(data.windDown.address); + + return data; + } + + before(function () { + basicFixture = deployBasicFixture; + integrationFixture = deployIntegrationFixture; + delayedSettlementFixture = deployDelayedSettlementFixture; + gapIntegrationFixture = deployGapIntegrationFixture; + rebalanceIntegrationFixture = deployRebalanceIntegrationFixture; + wrappedIntegrationFixture = deployWrappedIntegrationFixture; + }); + + describe("constructor", function () { + it("Should store immutable configuration", async function () { + const { freezeDay, fund, oldTwapOracle, oldAprOracle, windDown } = await loadFixture( + basicFixture + ); + + expect(await windDown.fund()).to.equal(fund); + expect(await windDown.oldTwapOracle()).to.equal(oldTwapOracle.address); + expect(await windDown.oldAprOracle()).to.equal(oldAprOracle.address); + expect(await windDown.freezeDay()).to.equal(freezeDay); + }); + + it("Should require an aligned future freeze day", async function () { + const { wallets, freezeDay, fund, oldTwapOracle, oldAprOracle } = await loadFixture( + basicFixture + ); + const { owner } = wallets; + const WindDown = await ethers.getContractFactory("FundV3WindDown"); + + await expect( + WindDown.deploy(ethers.constants.AddressZero, freezeDay) + ).to.be.revertedWith("Zero fund"); + await expect(WindDown.deploy(oldTwapOracle.address, freezeDay + 1)).to.be.revertedWith( + "Invalid freeze day" + ); + + const fundWithoutTwap = await deployMockForName(owner, "FundV3"); + await fundWithoutTwap.mock.twapOracle.returns(ethers.constants.AddressZero); + await fundWithoutTwap.mock.aprOracle.returns(oldAprOracle.address); + await expect(WindDown.deploy(fundWithoutTwap.address, freezeDay)).to.be.revertedWith( + "Zero TWAP oracle" + ); + + const fundWithoutApr = await deployMockForName(owner, "FundV3"); + await fundWithoutApr.mock.twapOracle.returns(oldTwapOracle.address); + await fundWithoutApr.mock.aprOracle.returns(ethers.constants.AddressZero); + await expect(WindDown.deploy(fundWithoutApr.address, freezeDay)).to.be.revertedWith( + "Zero APR oracle" + ); + + await advanceBlockAtTime(freezeDay + 1); + await expect(WindDown.deploy(fund, freezeDay)).to.be.revertedWith( + "Freeze day not future" + ); + }); + }); + + describe("oracle and ballot behavior", function () { + it("Should delegate TWAP through freeze day and return zero after it", async function () { + const { freezeDay, oldTwapOracle, windDown } = await loadFixture(basicFixture); + await oldTwapOracle.mock.getTwap.withArgs(freezeDay - DAY).returns(parseEther("0.9")); + await oldTwapOracle.mock.getTwap.withArgs(freezeDay).returns(parseEther("1")); + + expect(await windDown.getTwap(freezeDay - DAY)).to.equal(parseEther("0.9")); + expect(await windDown.getTwap(freezeDay)).to.equal(parseEther("1")); + expect(await windDown.getTwap(freezeDay + DAY)).to.equal(0); + }); + + it("Should use live latest price before T and frozen TWAP at or after T", async function () { + const { freezeDay, oldTwapOracle, windDown } = await loadFixture(basicFixture); + await oldTwapOracle.mock.getLatest.returns(parseEther("1.1")); + await oldTwapOracle.mock.getTwap.withArgs(freezeDay).returns(parseEther("1")); + + expect(await windDown.getLatest()).to.equal(parseEther("1.1")); + + await advanceBlockAtTime(freezeDay); + expect(await windDown.getLatest()).to.equal(parseEther("1")); + }); + + it("Should revert if the frozen latest price is not ready", async function () { + const { freezeDay, oldTwapOracle, windDown } = await loadFixture(basicFixture); + await oldTwapOracle.mock.getTwap.withArgs(freezeDay).returns(0); + + await advanceBlockAtTime(freezeDay); + await expect(windDown.getLatest()).to.be.revertedWith("Frozen price not ready"); + }); + + it("Should return old APR before T and zero from fund day T while still calling old APR", async function () { + const { freezeDay, fundMock, oldAprOracle, windDown } = await loadFixture(basicFixture); + const rate = parseEther("0.001"); + await oldAprOracle.mock.capture.returns(rate); + + expect(await windDown.callStatic.capture()).to.equal(rate); + + await advanceBlockAtTime(freezeDay); + await fundMock.mock.currentDay.returns(freezeDay - DAY); + expect(await windDown.callStatic.capture()).to.equal(rate); + + await fundMock.mock.currentDay.returns(freezeDay); + expect(await windDown.callStatic.capture()).to.equal(0); + }); + + it("Should preserve APR for delayed pre-freeze settlement and freeze day T", async function () { + const { freezeDay, fund, oldAprOracle } = await loadFixture(delayedSettlementFixture); + const rate = parseEther("0.001"); + const previousDay = freezeDay - DAY; + + expect(await fund.currentDay()).to.equal(previousDay); + await expect(() => fund.settle()).to.callMocks({ + func: oldAprOracle.mock.capture, + rets: [rate], + }); + expect(await fund.historicalInterestRate(previousDay)).to.equal(rate); + expect(await fund.currentDay()).to.equal(freezeDay); + + await expect(() => fund.settle()).to.callMocks({ + func: oldAprOracle.mock.capture, + rets: [rate], + }); + expect(await fund.historicalInterestRate(freezeDay)).to.equal(0); + expect(await fund.currentDay()).to.equal(freezeDay + DAY); + }); + + it("Should return zero ballot weight and no-op voting escrow sync", async function () { + const { windDown } = await loadFixture(basicFixture); + + expect(await windDown.count(123)).to.equal(0); + await windDown.syncWithVotingEscrow(ethers.constants.AddressZero); + }); + }); + + describe("primary market stubs", function () { + it("Should expose blocked view stubs", async function () { + const { windDown } = await loadFixture(basicFixture); + + expect(await windDown.getCreation(1)).to.equal(0); + await expect(windDown.getCreationForQ(1)).to.be.revertedWith("Wind down"); + await expect(windDown.getRedemption(1)).to.be.revertedWith("Wind down"); + await expect(windDown.getRedemptionForUnderlying(1)).to.be.revertedWith("Wind down"); + expect(await windDown.getSplit(1)).to.equal(0); + expect(await windDown.getSplitForB(1)).to.equal(0); + expect(await windDown.getMerge(1)).to.eql([BigNumber.from(0), BigNumber.from(0)]); + expect(await windDown.getMergeForQ(1)).to.equal(0); + expect(await windDown.canBeRemovedFromFund()).to.equal(true); + }); + + it("Should block old primary market operations", async function () { + const { windDown } = await loadFixture(basicFixture); + const recipient = ethers.constants.AddressZero; + + await expect(windDown.create(recipient, 0, 0)).to.be.revertedWith("Wind down"); + await expect(windDown.redeem(recipient, 1, 0, 0)).to.be.revertedWith("Wind down"); + await expect(windDown.redeemAndUnwrap(recipient, 1, 0, 0)).to.be.revertedWith( + "Wind down" + ); + await expect(windDown.queueRedemption(recipient, 1, 0, 0)).to.be.revertedWith( + "Wind down" + ); + await expect(windDown.claimRedemptions(recipient, [])).to.be.revertedWith("Wind down"); + await expect(windDown.claimRedemptionsAndUnwrap(recipient, [])).to.be.revertedWith( + "Wind down" + ); + await expect(windDown.split(recipient, 1, 0)).to.be.revertedWith("Wind down"); + await expect(windDown.merge(recipient, 1, 0)).to.be.revertedWith("Wind down"); + await windDown.settle(0); + }); + + it("Should hide redemption rates before initialization", async function () { + const { windDown } = await loadFixture(basicFixture); + + await expect(windDown.underlyingPerQ()).to.be.revertedWith("Not initialized"); + await expect(windDown.underlyingPerB()).to.be.revertedWith("Not initialized"); + await expect(windDown.underlyingPerR()).to.be.revertedWith("Not initialized"); + await expect(windDown.getRedeemAll(ethers.constants.AddressZero)).to.be.revertedWith( + "Not initialized" + ); + }); + + it("Should enforce readiness before initialization", async function () { + const { wallets, freezeDay, fundMock, windDown, oldTwapOracle } = await loadFixture( + basicFixture + ); + const { user1 } = wallets; + + await fundMock.mock.primaryMarket.returns(ethers.constants.AddressZero); + await expect(windDown.initialize()).to.be.revertedWith("Not primary market"); + + await fundMock.mock.primaryMarket.returns(windDown.address); + await fundMock.mock.strategy.returns(user1.address); + await expect(windDown.initialize()).to.be.revertedWith("Strategy not cleared"); + + await fundMock.mock.strategy.returns(ethers.constants.AddressZero); + await fundMock.mock.getStrategyUnderlying.returns(2); + await expect(windDown.initialize()).to.be.revertedWith( + "Strategy underlying not cleared" + ); + + await fundMock.mock.getStrategyUnderlying.returns(1); + await fundMock.mock.getTotalDebt.returns(1); + await expect(windDown.initialize()).to.be.revertedWith("Debt not cleared"); + + await fundMock.mock.getTotalDebt.returns(0); + await fundMock.mock.currentDay.returns(freezeDay); + await expect(windDown.initialize()).to.be.revertedWith("Final settlement not done"); + + await fundMock.mock.currentDay.returns(freezeDay + DAY); + await oldTwapOracle.mock.getTwap.withArgs(freezeDay).returns(0); + await expect(windDown.initialize()).to.be.revertedWith("Frozen price not ready"); + }); + + it("Should enforce readiness before activation", async function () { + const { wallets, freezeDay, fundMock, oldTwapOracle, windDown } = await loadFixture( + basicFixture + ); + const { owner, user1 } = wallets; + const MockToken = await ethers.getContractFactory("MockToken"); + const tokenUnderlying = await MockToken.connect(owner).deploy("Mock BTCB", "BTCB", 18); + + await tokenUnderlying.mint(fundMock.address, parseEther("90")); + await fundMock.mock.primaryMarket.returns(windDown.address); + await fundMock.mock.strategy.returns(ethers.constants.AddressZero); + await fundMock.mock.getStrategyUnderlying.returns(0); + await fundMock.mock.getTotalDebt.returns(0); + await fundMock.mock.currentDay.returns(freezeDay + DAY); + await oldTwapOracle.mock.getTwap.withArgs(freezeDay).returns(parseEther("1")); + await fundMock.mock.historicalNavs + .withArgs(freezeDay) + .returns(parseEther("1"), parseEther("2")); + await fundMock.mock.splitRatio.returns(parseEther("1")); + await fundMock.mock.tokenUnderlying.returns(tokenUnderlying.address); + await fundMock.mock.trancheTotalSupply.withArgs(TRANCHE_Q).returns(parseEther("10")); + await fundMock.mock.trancheTotalSupply.withArgs(TRANCHE_B).returns(parseEther("20")); + await fundMock.mock.trancheTotalSupply.withArgs(TRANCHE_R).returns(parseEther("20")); + + await windDown.initialize(); + + await fundMock.mock.primaryMarket.returns(ethers.constants.AddressZero); + await expect(windDown.activate()).to.be.revertedWith("Not primary market"); + + await fundMock.mock.primaryMarket.returns(windDown.address); + await fundMock.mock.strategy.returns(user1.address); + await expect(windDown.activate()).to.be.revertedWith("Strategy not cleared"); + + await fundMock.mock.strategy.returns(ethers.constants.AddressZero); + await fundMock.mock.getStrategyUnderlying.returns(2); + await expect(windDown.activate()).to.be.revertedWith("Strategy underlying not cleared"); + + await fundMock.mock.getStrategyUnderlying.returns(1); + await fundMock.mock.getTotalDebt.returns(1); + await expect(windDown.activate()).to.be.revertedWith("Debt not cleared"); + }); + }); + + describe("wind-down redemption", function () { + it("Should initialize deterministic redemption rates after final settlement and PM apply", async function () { + const { freezeDay, fund, windDown } = await loadFixture(integrationFixture); + + await expect(windDown.initialize()) + .to.emit(windDown, "Initialized") + .withArgs( + parseEther("1"), + parseEther("1"), + parseEther("2"), + parseEther("1"), + parseEther("90"), + parseEther("10"), + parseEther("20"), + parseEther("20") + ); + + expect(await fund.primaryMarket()).to.equal(windDown.address); + expect(await fund.currentDay()).to.equal(freezeDay + DAY); + expect(await fund.historicalInterestRate(freezeDay)).to.equal(0); + expect(await windDown.frozenPrice()).to.equal(parseEther("1")); + expect(await windDown.frozenNavB()).to.equal(parseEther("1")); + expect(await windDown.frozenNavR()).to.equal(parseEther("2")); + expect(await windDown.underlyingPerQ()).to.equal(parseEther("3")); + expect(await windDown.underlyingPerB()).to.equal(parseEther("1")); + expect(await windDown.underlyingPerR()).to.equal(parseEther("2")); + expect(await windDown.active()).to.equal(false); + }); + + it("Should initialize from actual supplies and hot balance after old PM gap actions", async function () { + const { wallets, freezeDay, tokenUnderlying, fund, windDown } = await loadFixture( + gapIntegrationFixture + ); + const { user1, user2 } = wallets; + + expect(await tokenUnderlying.balanceOf(fund.address)).to.equal(parseEther("87")); + expect(await tokenUnderlying.balanceOf(user2.address)).to.equal(parseEther("3")); + await expect(windDown.initialize()) + .to.emit(windDown, "Initialized") + .withArgs( + parseEther("1"), + parseEther("1"), + parseEther("2"), + parseEther("1"), + parseEther("87"), + parseEther("7"), + parseEther("22"), + parseEther("22") + ); + + expect(await fund.currentDay()).to.equal(freezeDay + DAY); + expect(await windDown.underlyingPerQ()).to.equal(parseEther("3")); + expect(await windDown.underlyingPerB()).to.equal(parseEther("1")); + expect(await windDown.underlyingPerR()).to.equal(parseEther("2")); + expect(await windDown.getRedeemAll(user1.address)).to.equal(parseEther("87")); + }); + + it("Should initialize after a final-settlement rebalance and block later settlement", async function () { + const { freezeDay, fund, windDown } = await loadFixture(rebalanceIntegrationFixture); + + expect(await fund.getRebalanceSize()).to.equal(1); + expect(await fund.currentDay()).to.equal(freezeDay + DAY); + expect(await fund.historicalInterestRate(freezeDay)).to.equal(0); + + const navs = await fund.historicalNavs(freezeDay); + expect(navs.navB).to.equal(parseEther("1")); + expect(navs.navR).to.equal(parseEther("1")); + + await expect(fund.settle()).to.be.revertedWith( + "Underlying price for settlement is not ready yet" + ); + + await windDown.initialize(); + expect(await windDown.frozenPrice()).to.equal(parseEther("4")); + expect(await windDown.frozenNavB()).to.equal(parseEther("1")); + expect(await windDown.frozenNavR()).to.equal(parseEther("1")); + expect(await windDown.frozenSplitRatio()).to.equal(parseEther("6")); + expect(await windDown.getLatest()).to.equal(parseEther("4")); + }); + + it("Should redeem stale user balances after a final-settlement rebalance", async function () { + const { wallets, tokenUnderlying, fund, windDown } = await loadFixture( + rebalanceIntegrationFixture + ); + const { user1, user2 } = wallets; + + expect(await fund.getRebalanceSize()).to.equal(1); + expect(await fund.trancheBalanceVersion(user1.address)).to.equal(0); + + await windDown.initialize(); + await windDown.activate(); + + const expectedUnderlying = await windDown.getRedeemAll(user1.address); + expect(expectedUnderlying.gt(0)).to.equal(true); + + const fundBalanceBefore = await tokenUnderlying.balanceOf(fund.address); + const user2BalanceBefore = await tokenUnderlying.balanceOf(user2.address); + await windDown.connect(user1).redeemAll(user2.address, expectedUnderlying); + + expect(await fund.trancheBalanceVersion(user1.address)).to.equal(1); + expect(await tokenUnderlying.balanceOf(fund.address)).to.equal( + fundBalanceBefore.sub(expectedUnderlying) + ); + expect(await tokenUnderlying.balanceOf(user2.address)).to.equal( + user2BalanceBefore.add(expectedUnderlying) + ); + expect(await fund.trancheTotalSupply(TRANCHE_Q)).to.equal(0); + expect(await fund.trancheTotalSupply(TRANCHE_B)).to.equal(0); + expect(await fund.trancheTotalSupply(TRANCHE_R)).to.equal(0); + }); + + it("Should require owner-only initialization and activation", async function () { + const { wallets, windDown } = await loadFixture(integrationFixture); + const { user1 } = wallets; + + await expect(windDown.connect(user1).initialize()).to.be.revertedWith( + "Ownable: caller is not the owner" + ); + await windDown.initialize(); + await expect(windDown.connect(user1).activate()).to.be.revertedWith( + "Ownable: caller is not the owner" + ); + await windDown.activate(); + await expect(windDown.connect(user1).deactivate()).to.be.revertedWith( + "Ownable: caller is not the owner" + ); + }); + + it("Should enforce one-shot initialization and active state guards", async function () { + const { windDown } = await loadFixture(integrationFixture); + + await expect(windDown.deactivate()).to.be.revertedWith("Not active"); + + await windDown.initialize(); + await expect(windDown.initialize()).to.be.revertedWith("Already initialized"); + + await windDown.activate(); + await expect(windDown.activate()).to.be.revertedWith("Already active"); + + await windDown.deactivate(); + await expect(windDown.deactivate()).to.be.revertedWith("Not active"); + await expect(windDown.activate()).to.emit(windDown, "Activated"); + }); + + it("Should activate, deactivate, and require active redemptions", async function () { + const { wallets, windDown } = await loadFixture(integrationFixture); + const { user1, user2 } = wallets; + + await windDown.initialize(); + await expect(windDown.connect(user1).redeemAll(user2.address, 0)).to.be.revertedWith( + "Not active" + ); + await expect( + windDown.connect(user1).redeemAllAndUnwrap(user2.address, 0) + ).to.be.revertedWith("Not active"); + + await expect(windDown.activate()).to.emit(windDown, "Activated"); + expect(await windDown.active()).to.equal(true); + await expect(windDown.deactivate()).to.emit(windDown, "Deactivated"); + expect(await windDown.active()).to.equal(false); + await expect(windDown.connect(user1).redeemAll(user2.address, 0)).to.be.revertedWith( + "Not active" + ); + await expect( + windDown.connect(user1).redeemAllAndUnwrap(user2.address, 0) + ).to.be.revertedWith("Not active"); + }); + + it("Should reject activation when fund balance cannot cover outstanding redemptions", async function () { + const { wallets, tokenUnderlying, fund, windDown } = await loadFixture( + integrationFixture + ); + const { owner } = wallets; + + await windDown.initialize(); + await tokenUnderlying.connect(owner).burn(fund.address, 1); + + await expect(windDown.activate()).to.be.revertedWith("Insufficient underlying"); + }); + + it("Should redeem all latest-version Q/B/R at fixed rates", async function () { + const { wallets, tokenUnderlying, fund, windDown } = await loadFixture( + integrationFixture + ); + const { user1, user2 } = wallets; + const expectedUnderlying = parseEther("90"); + + await windDown.initialize(); + await windDown.activate(); + + expect(await windDown.getRedeemAll(user1.address)).to.equal(expectedUnderlying); + await expect( + windDown.connect(user1).redeemAll(user2.address, expectedUnderlying.add(1)) + ).to.be.revertedWith("Min underlying redeemed"); + + const fundBalanceBefore = await tokenUnderlying.balanceOf(fund.address); + const user2BalanceBefore = await tokenUnderlying.balanceOf(user2.address); + const tx = await windDown.connect(user1).redeemAll(user2.address, expectedUnderlying); + await expect(tx) + .to.emit(windDown, "RedeemedAll") + .withArgs( + user1.address, + user2.address, + parseEther("10"), + parseEther("20"), + parseEther("20"), + expectedUnderlying + ); + expect(await tokenUnderlying.balanceOf(fund.address)).to.equal( + fundBalanceBefore.sub(expectedUnderlying) + ); + expect(await tokenUnderlying.balanceOf(user2.address)).to.equal( + user2BalanceBefore.add(expectedUnderlying) + ); + + expect(await fund.trancheTotalSupply(TRANCHE_Q)).to.equal(0); + expect(await fund.trancheTotalSupply(TRANCHE_B)).to.equal(0); + expect(await fund.trancheTotalSupply(TRANCHE_R)).to.equal(0); + expect(await windDown.getRedeemAll(user1.address)).to.equal(0); + }); + + it("Should redeem all latest-version Q/B/R and unwrap native underlying", async function () { + const { wallets, tokenUnderlying, fund, windDown } = await loadFixture( + wrappedIntegrationFixture + ); + const { user1, user2 } = wallets; + const expectedUnderlying = parseEther("90"); + + await windDown.initialize(); + await windDown.activate(); + + expect( + await windDown + .connect(user1) + .callStatic.redeemAllAndUnwrap(user2.address, expectedUnderlying) + ).to.equal(expectedUnderlying); + + const user2BalanceBefore = await ethers.provider.getBalance(user2.address); + const tx = await windDown + .connect(user1) + .redeemAllAndUnwrap(user2.address, expectedUnderlying); + await expect(tx) + .to.emit(windDown, "RedeemedAll") + .withArgs( + user1.address, + user2.address, + parseEther("10"), + parseEther("20"), + parseEther("20"), + expectedUnderlying + ); + + expect(await ethers.provider.getBalance(user2.address)).to.equal( + user2BalanceBefore.add(expectedUnderlying) + ); + expect(await tokenUnderlying.balanceOf(fund.address)).to.equal(0); + expect(await tokenUnderlying.balanceOf(windDown.address)).to.equal(0); + expect(await windDown.getRedeemAll(user1.address)).to.equal(0); + }); + + it("Should reactivate after partial redemptions using current outstanding supply", async function () { + const { wallets, tokenUnderlying, fund, windDown } = await loadFixture( + integrationFixture + ); + const { user1, user2 } = wallets; + const version = await fund.getRebalanceSize(); + const expectedHalfUnderlying = parseEther("45"); + + await fund + .connect(user1) + .trancheTransfer(TRANCHE_Q, user2.address, parseEther("5"), version); + await fund + .connect(user1) + .trancheTransfer(TRANCHE_B, user2.address, parseEther("10"), version); + await fund + .connect(user1) + .trancheTransfer(TRANCHE_R, user2.address, parseEther("10"), version); + + await windDown.initialize(); + await windDown.activate(); + + await windDown.connect(user1).redeemAll(user1.address, expectedHalfUnderlying); + expect(await tokenUnderlying.balanceOf(fund.address)).to.equal(expectedHalfUnderlying); + + await windDown.deactivate(); + await expect(windDown.activate()).to.emit(windDown, "Activated"); + + await windDown.connect(user2).redeemAll(user2.address, expectedHalfUnderlying); + expect(await tokenUnderlying.balanceOf(fund.address)).to.equal(0); + }); + + it("Should keep fixed-rate redemption order-independent with rounding dust", async function () { + async function prepareRoundingScenario() { + const data = await loadFixture(integrationFixture); + const { user1, user2, owner } = data.wallets; + const version = await data.fund.getRebalanceSize(); + + await data.fund + .connect(user1) + .trancheTransfer(TRANCHE_Q, user2.address, parseEther("3"), version); + await data.fund + .connect(user1) + .trancheTransfer(TRANCHE_B, user2.address, parseEther("7"), version); + await data.fund + .connect(user1) + .trancheTransfer(TRANCHE_R, user2.address, parseEther("11"), version); + await data.tokenUnderlying.connect(owner).mint(data.fund.address, parseEther("1")); + + await data.windDown.initialize(); + const expectedUser1 = await data.windDown.getRedeemAll(user1.address); + const expectedUser2 = await data.windDown.getRedeemAll(user2.address); + const initialFundBalance = await data.tokenUnderlying.balanceOf(data.fund.address); + await data.windDown.activate(); + + return { ...data, expectedUser1, expectedUser2, initialFundBalance }; + } + + const first = await prepareRoundingScenario(); + await first.windDown + .connect(first.wallets.user1) + .redeemAll(first.wallets.user1.address, 0); + await first.windDown + .connect(first.wallets.user2) + .redeemAll(first.wallets.user2.address, 0); + + const firstDust = first.initialFundBalance + .sub(first.expectedUser1) + .sub(first.expectedUser2); + expect(firstDust.toNumber()).to.be.greaterThan(0); + expect(firstDust.toNumber()).to.be.lessThan(20); + expect(await first.tokenUnderlying.balanceOf(first.wallets.user1.address)).to.equal( + first.expectedUser1 + ); + expect(await first.tokenUnderlying.balanceOf(first.wallets.user2.address)).to.equal( + first.expectedUser2 + ); + expect(await first.tokenUnderlying.balanceOf(first.fund.address)).to.equal(firstDust); + + const second = await prepareRoundingScenario(); + await second.windDown + .connect(second.wallets.user2) + .redeemAll(second.wallets.user2.address, 0); + await second.windDown + .connect(second.wallets.user1) + .redeemAll(second.wallets.user1.address, 0); + + const secondDust = second.initialFundBalance + .sub(second.expectedUser1) + .sub(second.expectedUser2); + expect(secondDust).to.equal(firstDust); + expect(await second.tokenUnderlying.balanceOf(second.wallets.user1.address)).to.equal( + second.expectedUser1 + ); + expect(await second.tokenUnderlying.balanceOf(second.wallets.user2.address)).to.equal( + second.expectedUser2 + ); + expect(await second.tokenUnderlying.balanceOf(second.fund.address)).to.equal( + secondDust + ); + }); + + it("Should return initialized frozen price from getLatest", async function () { + const { freezeDay, oldTwapOracle, windDown } = await loadFixture(integrationFixture); + await windDown.initialize(); + await oldTwapOracle.mock.getTwap.withArgs(freezeDay).returns(parseEther("2")); + + expect(await windDown.getLatest()).to.equal(parseEther("1")); + }); + }); +}); diff --git a/test/primaryMarketV4.ts b/test/primaryMarketV4.ts new file mode 100644 index 00000000..0b37e527 --- /dev/null +++ b/test/primaryMarketV4.ts @@ -0,0 +1,1252 @@ +import { expect } from "chai"; +import { BigNumber, BigNumberish, constants, Contract, Wallet } from "ethers"; +import type { Fixture, MockContract, MockProvider } from "ethereum-waffle"; +import { waffle, ethers } from "hardhat"; +const { loadFixture } = waffle; +const { parseEther, parseUnits } = ethers.utils; +const parseBtc = (value: string) => parseUnits(value, 8); +import { deployMockForName } from "./mock"; +import { TRANCHE_Q, TRANCHE_B, TRANCHE_R, DAY, FixtureWalletMap } from "./utils"; + +const BTC_TO_ETHER = parseUnits("1", 10); +const REDEMPTION_FEE_BPS = 35; +const MERGE_FEE_BPS = 45; + +const TOTAL_UNDERLYING = parseBtc("10"); +const EQUIVALENT_TOTAL_Q = parseEther("10000"); +const SPLIT_RATIO = parseEther("400"); + +describe("PrimaryMarketV4", function () { + interface FixtureData { + readonly wallets: FixtureWalletMap; + readonly btc: Contract; + readonly twapOracle: MockContract; + readonly fund: Contract; + readonly primaryMarket: Contract; + } + + let currentFixture: Fixture; + let fixtureData: FixtureData; + + let user1: Wallet; + let user2: Wallet; + let addr1: string; + let addr2: string; + let owner: Wallet; + let btc: Contract; + let twapOracle: MockContract; + let fund: Contract; + let primaryMarket: Contract; + + async function deployFixture(_wallets: Wallet[], provider: MockProvider): Promise { + const [user1, user2, owner] = provider.getWallets(); + + const MockToken = await ethers.getContractFactory("MockToken"); + const btc = await MockToken.connect(owner).deploy("Wrapped BTC", "BTC", 8); + const twapOracle = await deployMockForName(owner, "ITwapOracle"); + const fund = await deployMockForName(owner, "FundV4"); + await fund.mock.twapOracle.returns(twapOracle.address); + await fund.mock.tokenUnderlying.returns(btc.address); + await fund.mock.underlyingDecimalMultiplier.returns(1e10); + await fund.mock.getTotalUnderlying.returns(TOTAL_UNDERLYING); + await fund.mock.getEquivalentTotalQ.returns(EQUIVALENT_TOTAL_Q); + await fund.mock.splitRatio.returns(SPLIT_RATIO); + await fund.mock.strategy.returns(ethers.constants.AddressZero); + await btc.mint(fund.address, TOTAL_UNDERLYING); + const PrimaryMarket = await ethers.getContractFactory("PrimaryMarketV4"); + const primaryMarket = await PrimaryMarket.connect(owner).deploy( + fund.address, + parseEther("0.0001").mul(REDEMPTION_FEE_BPS), + parseEther("0.0001").mul(MERGE_FEE_BPS), + BigNumber.from(1).shl(256).sub(1), + true, + true + ); + + return { + wallets: { user1, user2, owner }, + btc, + twapOracle, + fund, + primaryMarket: primaryMarket.connect(user1), + }; + } + + before(function () { + currentFixture = deployFixture; + }); + + beforeEach(async function () { + fixtureData = await loadFixture(currentFixture); + user1 = fixtureData.wallets.user1; + user2 = fixtureData.wallets.user2; + addr1 = user1.address; + addr2 = user2.address; + owner = fixtureData.wallets.owner; + btc = fixtureData.btc; + twapOracle = fixtureData.twapOracle; + fund = fixtureData.fund; + primaryMarket = fixtureData.primaryMarket; + }); + + describe("create()", function () { + const inBtc = parseBtc("1"); + const outQ = inBtc.mul(EQUIVALENT_TOTAL_Q).div(TOTAL_UNDERLYING); + + it("Should transfer underlying to fund", async function () { + await fund.mock.primaryMarketMint.returns(); + await btc.mint(primaryMarket.address, inBtc); + await expect(() => primaryMarket.create(addr2, 0, 0)).to.changeTokenBalances( + btc, + [primaryMarket, fund], + [inBtc.mul(-1), inBtc] + ); + }); + + it("Should mint QUEEN to the given recipient", async function () { + const version = 999; + await btc.mint(primaryMarket.address, inBtc); + await expect(() => primaryMarket.create(addr2, 0, version)).to.callMocks({ + func: fund.mock.primaryMarketMint.withArgs(TRANCHE_Q, addr2, outQ, version), + }); + }); + + it("Should return created QUEEN amount", async function () { + await fund.mock.primaryMarketMint.returns(); + await btc.mint(primaryMarket.address, inBtc); + expect(await primaryMarket.callStatic.create(addr2, 0, 0)).to.equal(outQ); + }); + + it("Should check min QUEEN created", async function () { + await fund.mock.primaryMarketMint.returns(); + await btc.mint(primaryMarket.address, inBtc); + await expect(primaryMarket.create(addr2, outQ.add(1), 0)).to.be.revertedWith( + "Min QUEEN created" + ); + await primaryMarket.create(addr2, outQ, 0); + }); + + it("Should revert if no QUEEN can be created", async function () { + await expect(primaryMarket.create(addr2, 0, 0)).to.be.revertedWith("Min QUEEN created"); + + await fund.mock.getEquivalentTotalQ.returns(1); + await fund.mock.getTotalUnderlying.returns(parseBtc("10")); + await btc.mint(primaryMarket.address, parseBtc("1")); + await expect(primaryMarket.create(addr2, 0, 0)).to.be.revertedWith("Min QUEEN created"); + }); + + it("Should check fund cap", async function () { + await fund.mock.primaryMarketMint.returns(); + await primaryMarket.connect(owner).updateFundCap(TOTAL_UNDERLYING.add(inBtc).sub(1)); + await btc.mint(primaryMarket.address, inBtc); + await expect(primaryMarket.create(addr2, 0, 0)).to.be.revertedWith("Exceed fund cap"); + await primaryMarket.connect(owner).updateFundCap(TOTAL_UNDERLYING.add(inBtc)); + await primaryMarket.create(addr2, 0, 0); + }); + + it("Should revert if the fund is not initialized", async function () { + await fund.mock.getEquivalentTotalQ.returns(0); + await fund.mock.splitRatio.returns(0); + await btc.mint(primaryMarket.address, inBtc); + await expect(primaryMarket.create(addr2, 0, 0)).to.be.revertedWith( + "Fund is not initialized" + ); + }); + + it("Should create using split ratio when fund was empty", async function () { + await fund.mock.getEquivalentTotalQ.returns(0); + await fund.mock.getTotalUnderlying.returns(parseBtc("10")); // underlying can be non-zero + const currentDay = 1609556400; // 2021-01-02 03:00:00 + await fund.mock.currentDay.returns(currentDay); + await twapOracle.mock.getTwap.withArgs(currentDay - DAY).returns(parseEther("1000")); + const navB = parseEther("1.2"); + const navR = parseEther("1.8"); + await fund.mock.historicalNavs.withArgs(currentDay - DAY).returns(navB, navR); + await fund.mock.primaryMarketMint.returns(); + await btc.mint(primaryMarket.address, inBtc); + expect(await primaryMarket.callStatic.create(addr2, 0, 0)).equal( + inBtc + .mul(BTC_TO_ETHER) + .mul(parseEther("1000")) + .div(SPLIT_RATIO) + .mul(parseEther("1")) + .div(navB.add(navR)) + ); + }); + + it("Should emit an event", async function () { + await fund.mock.primaryMarketMint.returns(); + await btc.mint(primaryMarket.address, inBtc); + await expect(primaryMarket.create(addr2, 0, 0)) + .to.emit(primaryMarket, "Created") + .withArgs(addr2, inBtc, outQ); + }); + }); + + describe("redeem()", function () { + const inQ = parseEther("1"); + const feeQ = inQ.mul(REDEMPTION_FEE_BPS).div(10000); + const outBtc = inQ.sub(feeQ).mul(TOTAL_UNDERLYING).div(EQUIVALENT_TOTAL_Q); + + it("Should burn QUEEN and transfer underlying", async function () { + const version = 999; + await expect(() => primaryMarket.redeem(addr2, inQ, 0, version)).to.callMocks( + { + func: fund.mock.primaryMarketBurn.withArgs(TRANCHE_Q, addr1, inQ, version), + }, + { + func: fund.mock.primaryMarketTransferUnderlying.withArgs(addr2, outBtc, feeQ), + } + ); + }); + + it("Should return redeemed underlying amount", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketTransferUnderlying.returns(); + expect(await primaryMarket.callStatic.redeem(addr2, inQ, 0, 0)).to.equal(outBtc); + }); + + it("Should check min underlying redeemed", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketTransferUnderlying.returns(); + await expect(primaryMarket.redeem(addr2, inQ, outBtc.add(1), 0)).to.be.revertedWith( + "Min underlying redeemed" + ); + await primaryMarket.redeem(addr2, inQ, outBtc, 0); + }); + + it("Should revert if no underlying can be redeemed", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketTransferUnderlying.returns(); + await fund.mock.getEquivalentTotalQ.returns(parseEther("10000")); + await fund.mock.getTotalUnderlying.returns(1); + await expect(primaryMarket.redeem(addr2, 1, 0, 0)).to.be.revertedWith( + "Min underlying redeemed" + ); + }); + + it("Should revert on not enough available hot balance", async function () { + await btc.burn(fund.address, TOTAL_UNDERLYING); + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketTransferUnderlying.returns(); + + await btc.mint(fund.address, outBtc.sub(1)); + await expect(primaryMarket.redeem(addr2, inQ, 0, 0)).to.be.revertedWith( + "Not enough underlying in fund" + ); + await btc.mint(fund.address, 1); + await primaryMarket.redeem(addr2, inQ, 0, 0); + }); + + it("Should emit an event", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketTransferUnderlying.returns(); + await expect(primaryMarket.redeem(addr2, inQ, outBtc, 0)) + .to.emit(primaryMarket, "Redeemed") + .withArgs(addr2, inQ, outBtc, feeQ); + }); + }); + + describe("split()", function () { + const inQ = parseEther("10"); + const outB = inQ.mul(SPLIT_RATIO).div(parseEther("1")); + + it("Should burn and mint tranche tokens and add fee debt", async function () { + const version = 999; + await expect(() => primaryMarket.split(addr2, inQ, version)).to.callMocks( + { + func: fund.mock.primaryMarketBurn.withArgs(TRANCHE_Q, addr1, inQ, version), + }, + { + func: fund.mock.primaryMarketMint.withArgs(TRANCHE_B, addr2, outB, version), + }, + { + func: fund.mock.primaryMarketMint.withArgs(TRANCHE_R, addr2, outB, version), + } + ); + }); + + it("Should return split amount", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketMint.returns(); + expect(await primaryMarket.callStatic.split(addr2, 0, 0)).to.equal(0); + expect(await primaryMarket.callStatic.split(addr2, inQ, 0)).to.equal(outB); + }); + + it("Should round down the result", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketMint.returns(); + await fund.mock.splitRatio.returns(parseEther("1.5")); + expect(await primaryMarket.callStatic.split(addr2, 1, 0)).to.equal(1); + expect(await primaryMarket.callStatic.split(addr2, 5, 0)).to.equal(7); + }); + + it("Should emit an event", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketMint.returns(); + await expect(primaryMarket.split(addr2, inQ, 0)) + .to.emit(primaryMarket, "Split") + .withArgs(addr2, inQ, outB, outB); + }); + }); + + describe("merge()", function () { + const inB = parseEther("10"); + const outQBeforeFee = inB.mul(parseEther("1")).div(SPLIT_RATIO); + const feeQ = outQBeforeFee.mul(MERGE_FEE_BPS).div(10000); + const outQ = outQBeforeFee.sub(feeQ); + + it("Should burn and mint tranche tokens and add fee debt", async function () { + const version = 999; + await expect(() => primaryMarket.merge(addr2, inB, version)).to.callMocks( + { + func: fund.mock.primaryMarketBurn.withArgs(TRANCHE_B, addr1, inB, version), + }, + { + func: fund.mock.primaryMarketBurn.withArgs(TRANCHE_R, addr1, inB, version), + }, + { + func: fund.mock.primaryMarketMint.withArgs(TRANCHE_Q, addr2, outQ, version), + }, + { + func: fund.mock.primaryMarketAddDebtAndFee.withArgs(0, feeQ), + } + ); + }); + + it("Should return merged amount", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketMint.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + expect(await primaryMarket.callStatic.merge(addr2, 0, 0)).to.equal(0); + expect(await primaryMarket.callStatic.merge(addr2, inB, 0)).to.equal(outQ); + }); + + it("Should round down the result", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketMint.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + await fund.mock.splitRatio.returns(parseEther("1.5")); + expect(await primaryMarket.callStatic.merge(addr2, 4, 0)).to.equal(2); + expect(await primaryMarket.callStatic.merge(addr2, 8, 0)).to.equal(5); + }); + + it("Should emit an event", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketMint.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + await expect(primaryMarket.merge(addr2, inB, 0)) + .to.emit(primaryMarket, "Merged") + .withArgs(addr2, outQ, inB, inB, feeQ); + }); + }); + + describe("queueRedemption()", function () { + const inQ = parseEther("1"); + const feeQ = inQ.mul(REDEMPTION_FEE_BPS).div(10000); + const outBtc = inQ.sub(feeQ).mul(TOTAL_UNDERLYING).div(EQUIVALENT_TOTAL_Q); + + it("Should burn QUEEN and add debt", async function () { + const version = 999; + await expect(() => primaryMarket.queueRedemption(addr2, inQ, 0, version)).to.callMocks( + { + func: fund.mock.primaryMarketBurn.withArgs(TRANCHE_Q, addr1, inQ, version), + }, + { + func: fund.mock.primaryMarketAddDebtAndFee.withArgs(outBtc, feeQ), + } + ); + }); + + it("Should return redeemed underlying amount", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + const ret = await primaryMarket.callStatic.queueRedemption(addr2, inQ, 0, 0); + expect(ret.underlying).to.equal(outBtc); + }); + + it("Should check min underlying redeemed", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + await expect( + primaryMarket.queueRedemption(addr2, inQ, outBtc.add(1), 0) + ).to.be.revertedWith("Min underlying redeemed"); + await primaryMarket.queueRedemption(addr2, inQ, outBtc, 0); + }); + + it("Should revert if no underlying can be redeemed", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + await fund.mock.getEquivalentTotalQ.returns(parseEther("10000")); + await fund.mock.getTotalUnderlying.returns(1); + await expect(primaryMarket.queueRedemption(addr2, 1, 0, 0)).to.be.revertedWith( + "Min underlying redeemed" + ); + }); + + it("Should return index in the queue", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + const ret0 = await primaryMarket.callStatic.queueRedemption(addr2, inQ, 0, 0); + expect(ret0.index).to.equal(0); + await primaryMarket.queueRedemption(addr2, inQ, 0, 0); + await primaryMarket.queueRedemption(addr2, inQ, 0, 0); + const ret1 = await primaryMarket.callStatic.queueRedemption(addr2, inQ, 0, 0); + expect(ret1.index).to.equal(2); + }); + + it("Should append redemption to the queue", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + + await primaryMarket.queueRedemption(addr2, inQ, 0, 0); + expect(await primaryMarket.redemptionQueueTail()).to.equal(1); + const redemption0 = await primaryMarket.queuedRedemptions(0); + expect(redemption0.account).to.equal(addr2); + expect(redemption0.underlying).to.equal(outBtc); + expect(redemption0.previousPrefixSum).to.equal(0); + expect((await primaryMarket.queuedRedemptions(1)).previousPrefixSum).to.equal(outBtc); + + await primaryMarket.queueRedemption(addr1, inQ.mul(2), 0, 0); + expect(await primaryMarket.redemptionQueueTail()).to.equal(2); + const redemption1 = await primaryMarket.queuedRedemptions(1); + expect(redemption1.account).to.equal(addr1); + expect(redemption1.underlying).to.equal(outBtc.mul(2)); + expect(redemption1.previousPrefixSum).to.equal(outBtc); + expect((await primaryMarket.queuedRedemptions(2)).previousPrefixSum).to.equal( + outBtc.mul(3) + ); + }); + + it("Should emit Redeemed event", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + await expect(primaryMarket.queueRedemption(addr2, inQ, outBtc, 0)) + .to.emit(primaryMarket, "Redeemed") + .withArgs(addr2, inQ, outBtc, feeQ); + }); + + it("Should emit RedemptionQueued event", async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + await primaryMarket.queueRedemption(addr2, inQ.mul(2), 0, 0); + await expect(primaryMarket.queueRedemption(addr2, inQ, 0, 0)) + .to.emit(primaryMarket, "RedemptionQueued") + .withArgs(addr2, 1, outBtc); + }); + }); + + describe("Redemption queue", function () { + const outBtcList: BigNumber[] = []; + const outPrefixSum: BigNumber[] = []; + + beforeEach(async function () { + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + await btc.burn(fund.address, TOTAL_UNDERLYING); // Remove all underlying from the fund + const inputList = [ + { addr: addr2, inQ: parseEther("1") }, + { addr: addr1, inQ: parseEther("3") }, + { addr: addr2, inQ: parseEther("12") }, + { addr: addr2, inQ: parseEther("7") }, + ]; + let sum = BigNumber.from(0); + outBtcList.length = 0; // clear the array + outPrefixSum.length = 0; // clear the array + for (const { addr, inQ } of inputList) { + await primaryMarket.queueRedemption(addr, inQ, 0, 0); + const feeBtc = inQ + .mul(TOTAL_UNDERLYING) + .div(EQUIVALENT_TOTAL_Q) + .mul(REDEMPTION_FEE_BPS) + .div(10000); + const outBtc = inQ.mul(TOTAL_UNDERLYING).div(EQUIVALENT_TOTAL_Q).sub(feeBtc); + outBtcList.push(outBtc); + sum = sum.add(outBtc); + outPrefixSum.push(sum); + } + }); + + describe("getNewRedemptionQueueHead()", function () { + it("Should return the old head when no underlying is available", async function () { + expect(await primaryMarket.getNewRedemptionQueueHead()).to.equal(0); + }); + + it("Should return the correct new head", async function () { + await btc.mint(fund.address, outPrefixSum[2]); + expect(await primaryMarket.getNewRedemptionQueueHead()).to.equal(3); + await btc.mint(fund.address, outPrefixSum[3].mul(100)); + expect(await primaryMarket.getNewRedemptionQueueHead()).to.equal(4); + }); + }); + + describe("getQueuedRedemptions()", function () { + async function getQueuedRedemptions( + addr: string | null, + startIndex: BigNumberish, + maxIterationCount: BigNumberish + ): Promise<{ indices: number[]; underlying: BigNumber }> { + const ret = await primaryMarket.getQueuedRedemptions( + addr ?? ethers.constants.AddressZero, + startIndex, + maxIterationCount + ); + return { + indices: ret.indices.map((x: BigNumber) => x.toNumber()), + underlying: ret.underlying, + }; + } + + it("Should return a slice of the queue", async function () { + expect(await getQueuedRedemptions(null, 0, 0)).to.eql({ + indices: [0, 1, 2, 3], + underlying: outPrefixSum[3], + }); + expect(await getQueuedRedemptions(null, 1, 0)).to.eql({ + indices: [1, 2, 3], + underlying: outBtcList[1].add(outBtcList[2]).add(outBtcList[3]), + }); + expect(await getQueuedRedemptions(null, 1, 2)).to.eql({ + indices: [1, 2], + underlying: outBtcList[1].add(outBtcList[2]), + }); + expect(await getQueuedRedemptions(null, 1, 100)).to.eql({ + indices: [1, 2, 3], + underlying: outBtcList[1].add(outBtcList[2]).add(outBtcList[3]), + }); + expect(await getQueuedRedemptions(null, 4, 0)).to.eql({ + indices: [], + underlying: BigNumber.from(0), + }); + }); + + it("Should filter by address", async function () { + expect(await getQueuedRedemptions(addr1, 0, 0)).to.eql({ + indices: [1], + underlying: outBtcList[1], + }); + expect(await getQueuedRedemptions(addr1, 0, 1)).to.eql({ + indices: [], + underlying: BigNumber.from(0), + }); + expect(await getQueuedRedemptions(addr2, 0, 0)).to.eql({ + indices: [0, 2, 3], + underlying: outBtcList[0].add(outBtcList[2]).add(outBtcList[3]), + }); + expect(await getQueuedRedemptions(addr2, 0, 3)).to.eql({ + indices: [0, 2], + underlying: outBtcList[0].add(outBtcList[2]), + }); + expect(await getQueuedRedemptions(addr2, 1, 100)).to.eql({ + indices: [2, 3], + underlying: outBtcList[2].add(outBtcList[3]), + }); + expect(await getQueuedRedemptions(owner.address, 0, 0)).to.eql({ + indices: [], + underlying: BigNumber.from(0), + }); + }); + + it("Should revert if start index is out of bound", async function () { + await expect(getQueuedRedemptions(null, 5, 0)).to.be.revertedWith( + "startIndex out of bound" + ); + }); + }); + + describe("popRedemptionQueue()", function () { + it("Should revert if there's no enough balance in fund", async function () { + await expect(primaryMarket.popRedemptionQueue(1)).to.be.revertedWith( + "Not enough underlying in fund" + ); + await btc.mint(fund.address, outPrefixSum[1].sub(1)); + await expect(primaryMarket.popRedemptionQueue(2)).to.be.revertedWith( + "Not enough underlying in fund" + ); + }); + + it("Should call fund to pay debt", async function () { + await btc.mint(fund.address, outPrefixSum[1]); + await expect(() => primaryMarket.popRedemptionQueue(2)).to.callMocks({ + func: fund.mock.primaryMarketPayDebt.withArgs(outPrefixSum[1]), + }); + }); + + it("Should revert if count is out of bound", async function () { + await fund.mock.primaryMarketPayDebt.returns(); + await btc.mint(fund.address, TOTAL_UNDERLYING); + await expect(primaryMarket.popRedemptionQueue(9)).to.be.revertedWith( + "Redemption queue out of bound" + ); + await primaryMarket.popRedemptionQueue(1); + await expect(primaryMarket.popRedemptionQueue(4)).to.be.revertedWith( + "Redemption queue out of bound" + ); + await primaryMarket.popRedemptionQueue(3); + }); + + it("Should update queue head and keep entries unchanged", async function () { + await fund.mock.primaryMarketPayDebt.returns(); + await btc.mint(fund.address, outPrefixSum[1]); + await primaryMarket.popRedemptionQueue(2); + expect(await primaryMarket.redemptionQueueHead()).to.equal(2); + expect(await primaryMarket.redemptionQueueTail()).to.equal(4); + const redemption0 = await primaryMarket.queuedRedemptions(0); + expect(redemption0.account).to.equal(addr2); + expect(redemption0.underlying).to.equal(outBtcList[0]); + expect(redemption0.previousPrefixSum).to.equal(0); + const redemption1 = await primaryMarket.queuedRedemptions(1); + expect(redemption1.account).to.equal(addr1); + expect(redemption1.underlying).to.equal(outBtcList[1]); + expect(redemption1.previousPrefixSum).to.equal(outPrefixSum[0]); + const redemption2 = await primaryMarket.queuedRedemptions(2); + expect(redemption2.account).to.equal(addr2); + expect(redemption2.underlying).to.equal(outBtcList[2]); + expect(redemption2.previousPrefixSum).to.equal(outPrefixSum[1]); + }); + + it("Should update total claimable amount", async function () { + await fund.mock.primaryMarketPayDebt.returns(); + await btc.mint(fund.address, outPrefixSum[1]); + await primaryMarket.popRedemptionQueue(2); + expect(await primaryMarket.claimableUnderlying()).to.equal(outPrefixSum[1]); + }); + + it("Should clear the queue if count is zero", async function () { + await fund.mock.primaryMarketPayDebt.returns(); + await btc.mint(fund.address, TOTAL_UNDERLYING); + await primaryMarket.popRedemptionQueue(0); + expect(await primaryMarket.redemptionQueueHead()).to.equal(4); + expect(await primaryMarket.redemptionQueueTail()).to.equal(4); + await primaryMarket.popRedemptionQueue(0); + expect(await primaryMarket.redemptionQueueHead()).to.equal(4); + expect(await primaryMarket.redemptionQueueTail()).to.equal(4); + expect(await primaryMarket.getNewRedemptionQueueHead()).to.equal(4); + }); + + it("Should emit an event", async function () { + await fund.mock.primaryMarketPayDebt.returns(); + await btc.mint(fund.address, TOTAL_UNDERLYING); + await expect(primaryMarket.popRedemptionQueue(2)) + .to.emit(primaryMarket, "RedemptionPopped") + .withArgs(2, 2, outPrefixSum[1]); + await expect(primaryMarket.popRedemptionQueue(2)) + .to.emit(primaryMarket, "RedemptionPopped") + .withArgs(2, 4, outPrefixSum[3].sub(outPrefixSum[1])); + }); + }); + + describe("claimRedemptions()", async function () { + beforeEach(async function () { + await fund.mock.primaryMarketPayDebt.returns(); + }); + + it("Should revert if account and indices do not match", async function () { + await btc.mint(fund.address, TOTAL_UNDERLYING); + await expect(primaryMarket.claimRedemptions(addr1, [0])).to.be.revertedWith( + "Invalid redemption index" + ); + await expect(primaryMarket.claimRedemptions(addr1, [0, 1])).to.be.revertedWith( + "Invalid redemption index" + ); + await expect(primaryMarket.claimRedemptions(addr2, [0, 1])).to.be.revertedWith( + "Invalid redemption index" + ); + }); + + it("Should require indices to be in increasing order", async function () { + await btc.mint(fund.address, TOTAL_UNDERLYING); + await expect(primaryMarket.claimRedemptions(addr2, [2, 0])).to.be.revertedWith( + "Indices out of order" + ); + await expect(primaryMarket.claimRedemptions(addr2, [0, 3, 2])).to.be.revertedWith( + "Indices out of order" + ); + }); + + it("Should revert if there's no enough balance in fund", async function () { + await btc.mint(fund.address, outPrefixSum[2].sub(1)); + await expect(primaryMarket.claimRedemptions(addr2, [0, 2])).to.be.revertedWith( + "Not enough underlying in fund" + ); + }); + + it("Should transfer underlying and return claimed amount", async function () { + await btc.mint(fund.address, TOTAL_UNDERLYING); + await btc.mint(primaryMarket.address, TOTAL_UNDERLYING); + + const amount1 = outBtcList[1]; + expect(await primaryMarket.callStatic.claimRedemptions(addr1, [1])).to.equal( + amount1 + ); + await expect(() => + primaryMarket.claimRedemptions(addr1, [1]) + ).to.changeTokenBalances(btc, [user1, primaryMarket], [amount1, amount1.mul(-1)]); + + const amount2 = outBtcList[0].add(outBtcList[3]); + expect(await primaryMarket.callStatic.claimRedemptions(addr2, [0, 3])).to.equal( + amount2 + ); + await expect(() => + primaryMarket.claimRedemptions(addr2, [0, 3]) + ).to.changeTokenBalances(btc, [user2, primaryMarket], [amount2, amount2.mul(-1)]); + }); + + it("Should update redemption queue head and delete redemptions", async function () { + await btc.mint(fund.address, TOTAL_UNDERLYING); + await btc.mint(primaryMarket.address, TOTAL_UNDERLYING); + + await primaryMarket.claimRedemptions(addr1, [1]); + expect(await primaryMarket.redemptionQueueHead()).to.equal(2); + const redemption1 = await primaryMarket.queuedRedemptions(1); + expect(redemption1.account).to.equal(ethers.constants.AddressZero); + expect(redemption1.underlying).to.equal(0); + expect(redemption1.previousPrefixSum).to.equal(0); + + await primaryMarket.claimRedemptions(addr2, [0, 3]); + expect(await primaryMarket.redemptionQueueHead()).to.equal(4); + const redemption0 = await primaryMarket.queuedRedemptions(0); + expect(redemption0.account).to.equal(ethers.constants.AddressZero); + expect(redemption0.underlying).to.equal(0); + expect(redemption0.previousPrefixSum).to.equal(0); + const redemption3 = await primaryMarket.queuedRedemptions(3); + expect(redemption3.account).to.equal(ethers.constants.AddressZero); + expect(redemption3.underlying).to.equal(0); + expect(redemption3.previousPrefixSum).to.equal(0); + }); + + it("Should update total claimable amount", async function () { + await btc.mint(fund.address, TOTAL_UNDERLYING); + await btc.mint(primaryMarket.address, TOTAL_UNDERLYING); + + await primaryMarket.claimRedemptions(addr1, [1]); + expect(await primaryMarket.claimableUnderlying()).to.equal(outBtcList[0]); + + await primaryMarket.claimRedemptions(addr2, [0, 3]); + expect(await primaryMarket.claimableUnderlying()).to.equal(outBtcList[2]); + }); + + it("Should do nothing if the index array is empty", async function () { + expect(await primaryMarket.callStatic.claimRedemptions(addr1, [])).to.equal(0); + await expect(() => primaryMarket.claimRedemptions(addr1, [])).to.changeTokenBalance( + btc, + user1, + 0 + ); + }); + + it("Should revert if already claimed", async function () { + await btc.mint(fund.address, TOTAL_UNDERLYING); + await btc.mint(primaryMarket.address, TOTAL_UNDERLYING); + await primaryMarket.claimRedemptions(addr2, [2]); + await expect(primaryMarket.claimRedemptions(addr2, [2])).to.be.revertedWith( + "Invalid redemption index" + ); + await expect(primaryMarket.claimRedemptions(addr1, [0, 2, 3])).to.be.revertedWith( + "Invalid redemption index" + ); + }); + + it("Should emit an event for each claimed redemption", async function () { + await btc.mint(fund.address, TOTAL_UNDERLYING); + await btc.mint(primaryMarket.address, TOTAL_UNDERLYING); + const tx = await primaryMarket.claimRedemptions(addr2, [2, 3]); + const receipt = await ethers.provider.getTransactionReceipt(tx.hash); + const topic = primaryMarket.interface.getEventTopic("RedemptionClaimed"); + const expectedLogs = receipt.logs + .filter((x) => x.topics.includes(topic)) + .map((x) => primaryMarket.interface.parseLog(x)); + expect(expectedLogs.length).to.equal(2); + expect(expectedLogs[0].args.account).to.equal(addr2); + expect(expectedLogs[0].args.index).to.equal(2); + expect(expectedLogs[0].args.underlying).to.equal(outBtcList[2]); + expect(expectedLogs[1].args.account).to.equal(addr2); + expect(expectedLogs[1].args.index).to.equal(3); + expect(expectedLogs[1].args.underlying).to.equal(outBtcList[3]); + }); + }); + + describe("redeem()", async function () { + it("Should revert if there's no enough balance in fund", async function () { + await btc.mint(fund.address, outPrefixSum[3].sub(1)); + await expect(primaryMarket.redeem(addr2, parseEther("1"), 0, 0)).to.be.revertedWith( + "Not enough underlying in fund" + ); + }); + + it("Should pop all queued redemptions", async function () { + await btc.mint(fund.address, outPrefixSum[3]); + await fund.mock.primaryMarketTransferUnderlying.returns(); + await expect(() => primaryMarket.redeem(addr2, parseEther("1"), 0, 0)).to.callMocks( + { + func: fund.mock.primaryMarketPayDebt.withArgs(outPrefixSum[3]), + } + ); + expect(await primaryMarket.redemptionQueueHead()).to.equal(4); + expect(await primaryMarket.claimableUnderlying()).to.equal(outPrefixSum[3]); + }); + }); + + describe("create()", function () { + it("Should create when claimable underlying is not zero", async function () { + await btc.mint(fund.address, outPrefixSum[3]); + await fund.mock.primaryMarketPayDebt.returns(); + await primaryMarket.popRedemptionQueue(0); + expect(await primaryMarket.claimableUnderlying()).to.equal(outPrefixSum[3]); + await btc.mint(primaryMarket.address, outPrefixSum[3]); + + const inBtc = parseBtc("1"); + const outQ = inBtc.mul(EQUIVALENT_TOTAL_Q).div(TOTAL_UNDERLYING); + await btc.mint(primaryMarket.address, inBtc); + await fund.mock.primaryMarketMint.returns(); + expect(await primaryMarket.callStatic.create(addr2, 0, 0)).to.equal(outQ); + await expect(() => primaryMarket.create(addr2, 0, 0)).to.changeTokenBalances( + btc, + [primaryMarket, fund], + [inBtc.mul(-1), inBtc] + ); + }); + }); + }); + + describe("Redemption queue prefix sum", function () { + it("Should overflow in additions and substractions", async function () { + await primaryMarket.connect(owner).updateRedemptionFeeRate(0); + + const BIG_UNIT = BigNumber.from(1).shl(252); // 1/16 of 2^256 + await fund.mock.getTotalUnderlying.returns(BIG_UNIT.mul(3)); + await fund.mock.getEquivalentTotalQ.returns(3); + await btc.burn(fund.address, TOTAL_UNDERLYING); // clear btc minted before + + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + await primaryMarket.queueRedemption(addr2, 3, 0, 0); // prefix sum: 3 + await primaryMarket.queueRedemption(addr2, 3, 0, 0); // prefix sum: 6 + await primaryMarket.queueRedemption(addr2, 3, 0, 0); // prefix sum: 9 + await primaryMarket.queueRedemption(addr2, 3, 0, 0); // prefix sum: 12 + await primaryMarket.queueRedemption(addr2, 2, 0, 0); // prefix sum: 14 + await primaryMarket.queueRedemption(addr2, 3, 0, 0); // prefix sum: 1 (overflow) + await primaryMarket.queueRedemption(addr2, 3, 0, 0); // prefix sum: 4 + await primaryMarket.queueRedemption(addr2, 3, 0, 0); // prefix sum: 7 + await primaryMarket.queueRedemption(addr2, 3, 0, 0); // prefix sum: 10 + await primaryMarket.queueRedemption(addr2, 3, 0, 0); // prefix sum: 13 + await primaryMarket.queueRedemption(addr2, 3, 0, 0); // prefix sum: 0 (overflow) + await primaryMarket.queueRedemption(addr2, 1, 0, 0); // prefix sum: 1 + + // Check overflow in additions + const getPreviousPrefixSum = async (index: number) => + (await primaryMarket.queuedRedemptions(index)).previousPrefixSum; + expect(await getPreviousPrefixSum(5)).to.equal(BIG_UNIT.mul(14)); + expect(await getPreviousPrefixSum(6)).to.equal(BIG_UNIT); + expect(await getPreviousPrefixSum(11)).to.equal(0); + expect(await getPreviousPrefixSum(12)).to.equal(BIG_UNIT); + + // Check overflow in substractions + await btc.mint(fund.address, BIG_UNIT.mul(14)); + await expect(() => primaryMarket.popRedemptionQueue(5)).to.callMocks({ + func: fund.mock.primaryMarketPayDebt.withArgs(BIG_UNIT.mul(14)), + }); + await btc.burn(fund.address, BIG_UNIT.mul(14)); + await btc.mint(primaryMarket.address, BIG_UNIT.mul(14)); + await primaryMarket.claimRedemptions(addr2, [0, 1, 2, 3, 4]); + await btc.burn(addr2, BIG_UNIT.mul(14)); + + await btc.mint(fund.address, BIG_UNIT.mul(12)); + await expect(() => primaryMarket.popRedemptionQueue(4)).to.callMocks({ + func: fund.mock.primaryMarketPayDebt.withArgs(BIG_UNIT.mul(12)), // overflow 10 - 14 + }); + await btc.burn(fund.address, BIG_UNIT.mul(12)); + await btc.mint(primaryMarket.address, BIG_UNIT.mul(12)); + await primaryMarket.claimRedemptions(addr2, [5, 6, 7, 8]); + await btc.burn(addr2, BIG_UNIT.mul(12)); + + await btc.mint(fund.address, BIG_UNIT.mul(6)); + await expect(() => primaryMarket.popRedemptionQueue(2)).to.callMocks({ + func: fund.mock.primaryMarketPayDebt.withArgs(BIG_UNIT.mul(6)), // overflow 0 - 10 + }); + }); + }); + + describe("Reverse getters", function () { + it("getCreationForQ()", async function () { + await fund.mock.getTotalUnderlying.returns(7); + await fund.mock.getEquivalentTotalQ.returns(10); + expect(await primaryMarket.getCreationForQ(0)).to.equal(0); + expect(await primaryMarket.getCreationForQ(1)).to.equal(1); + + // More QUEEN can be created + expect(await primaryMarket.getCreationForQ(6)).to.equal(5); + expect(await primaryMarket.getCreation(5)).to.equal(7); + }); + + it("getRedemptionForUnderlying()", async function () { + await fund.mock.getTotalUnderlying.returns(10000); + await fund.mock.getEquivalentTotalQ.returns(7000); + await primaryMarket.connect(owner).updateRedemptionFeeRate(parseEther("0.003")); + expect(await primaryMarket.getRedemptionForUnderlying(0)).to.equal(0); + expect(await primaryMarket.getRedemptionForUnderlying(997)).to.equal(700); + + // Less QUEEN can be redeemed, i.e. suboptimal solution + expect(await primaryMarket.getRedemptionForUnderlying(1423)).to.equal(1000); + expect((await primaryMarket.getRedemption(999)).underlying).to.equal(1424); + }); + + it("getSplitForB()", async function () { + await fund.mock.splitRatio.returns(parseEther("1.5")); + expect(await primaryMarket.getSplitForB(0)).to.equal(0); + expect(await primaryMarket.getSplitForB(1)).to.equal(1); + expect(await primaryMarket.getSplitForB(2)).to.equal(2); + expect(await primaryMarket.getSplitForB(5)).to.equal(4); + expect(await primaryMarket.getSplitForB(parseEther("3"))).to.equal(parseEther("2")); + }); + + it("getMergeForQ()", async function () { + await fund.mock.splitRatio.returns(parseEther("0.75")); + await primaryMarket.connect(owner).updateMergeFeeRate(parseEther("0.003")); + expect(await primaryMarket.getMergeForQ(0)).to.equal(0); + expect(await primaryMarket.getMergeForQ(9970)).to.equal(7500); + + // More QUEEN can be received + expect(await primaryMarket.getMergeForQ(1000)).to.equal(753); + expect((await primaryMarket.getMerge(753)).outQ).to.equal(1001); + + // Less BISHOP/ROOK can be spent, i.e. suboptimal solution + expect(await primaryMarket.getMergeForQ(665)).to.equal(501); + expect((await primaryMarket.getMerge(500)).outQ).to.equal(665); + }); + }); + + describe("Wrapped native currency", function () { + const ETH_TOTAL_UNDERLYING = parseEther("10"); + let weth: Contract; + + beforeEach(async function () { + const MockWrappedToken = await ethers.getContractFactory("MockWrappedToken"); + weth = await MockWrappedToken.connect(owner).deploy("Wrapped ETH", "ETH"); + weth = weth.connect(user1); + await fund.mock.tokenUnderlying.returns(weth.address); + await fund.mock.getTotalUnderlying.returns(ETH_TOTAL_UNDERLYING); + await fund.mock.getEquivalentTotalQ.returns(EQUIVALENT_TOTAL_Q); + const PrimaryMarket = await ethers.getContractFactory("PrimaryMarketV4"); + primaryMarket = await PrimaryMarket.connect(owner).deploy( + fund.address, + parseEther("0.0001").mul(REDEMPTION_FEE_BPS), + parseEther("0.0001").mul(MERGE_FEE_BPS), + BigNumber.from(1).shl(256).sub(1), + true, + true + ); + primaryMarket = primaryMarket.connect(user1); + }); + + it("redeemAndUnwrap()", async function () { + const inQ = parseEther("1"); + const feeQ = inQ.mul(REDEMPTION_FEE_BPS).div(10000); + const outEth = inQ.sub(feeQ).mul(ETH_TOTAL_UNDERLYING).div(EQUIVALENT_TOTAL_Q); + const version = 999; + await weth.connect(owner).deposit({ value: outEth.mul(2) }); + await weth.connect(owner).transfer(primaryMarket.address, outEth); + await weth.connect(owner).transfer(fund.address, outEth); + await fund.mock.primaryMarketBurn.withArgs(TRANCHE_Q, addr1, inQ, version).returns(); + await fund.mock.primaryMarketTransferUnderlying + .withArgs(primaryMarket.address, outEth, feeQ) + .returns(); + expect(await primaryMarket.callStatic.redeemAndUnwrap(addr2, inQ, 0, version)).to.equal( + outEth + ); + await expect(() => + primaryMarket.redeemAndUnwrap(addr2, inQ, 0, version) + ).to.changeEtherBalance(user2, outEth); + expect(await weth.balanceOf(primaryMarket.address)).to.equal(0); + }); + + it("claimRedemptionsAndUnwrap()", async function () { + const inQ = parseEther("1"); + const feeQ = inQ.mul(REDEMPTION_FEE_BPS).div(10000); + const outEth = inQ.sub(feeQ).mul(ETH_TOTAL_UNDERLYING).div(EQUIVALENT_TOTAL_Q); + await weth.connect(owner).deposit({ value: outEth.mul(2) }); + await weth.connect(owner).transfer(primaryMarket.address, outEth); + await weth.connect(owner).transfer(fund.address, outEth); + await fund.mock.primaryMarketBurn.returns(); + await fund.mock.primaryMarketAddDebtAndFee.returns(); + await primaryMarket.queueRedemption(addr2, inQ, 0, 0); + + await fund.mock.primaryMarketPayDebt.withArgs(outEth).returns(); + expect(await primaryMarket.callStatic.claimRedemptionsAndUnwrap(addr2, [0])).to.equal( + outEth + ); + await expect(() => + primaryMarket.claimRedemptionsAndUnwrap(addr2, [0]) + ).to.changeEtherBalance(user2, outEth); + expect(await weth.balanceOf(primaryMarket.address)).to.equal(0); + }); + }); + + describe("PrimaryMarketRouter", function () { + const inBtc = parseBtc("1"); + const outQ = inBtc.mul(EQUIVALENT_TOTAL_Q).div(TOTAL_UNDERLYING); + const outB = outQ.mul(100); + const version = 1; + const minLpOut = parseEther("1"); + + let tokenB: MockContract; + let primaryMarket: MockContract; + let shareStaking: MockContract; + let swapRouter: MockContract; + let swap: MockContract; + let primaryMarketRouter: Contract; + + beforeEach(async function () { + btc = await deployMockForName(owner, "IERC20"); + tokenB = await deployMockForName(owner, "IERC20"); + await fund.mock.tokenUnderlying.returns(btc.address); + await fund.mock.tokenB.returns(tokenB.address); + + primaryMarket = await deployMockForName(owner, "PrimaryMarketV4"); + await primaryMarket.mock.fund.returns(fund.address); + + shareStaking = await deployMockForName(owner, "ShareStaking"); + + swap = await deployMockForName(owner, "StableSwapV2"); + swapRouter = await deployMockForName(owner, "SwapRouter"); + await swapRouter.mock.getSwap.returns(swap.address); + + const PrimaryMarketRouter = await ethers.getContractFactory("PrimaryMarketRouter"); + primaryMarketRouter = await PrimaryMarketRouter.connect(owner).deploy( + primaryMarket.address + ); + primaryMarketRouter = primaryMarketRouter.connect(user1); + }); + + describe("split", function () { + beforeEach(async function () { + await fund.mock.trancheTransferFrom + .withArgs(TRANCHE_Q, addr1, primaryMarketRouter.address, outQ, version) + .returns(); + await primaryMarket.mock.split + .withArgs(primaryMarketRouter.address, outQ, version) + .returns(outB); + }); + + it("Should revert if lp out less than minLpOut", async function () { + await fund.mock.trancheTransfer + .withArgs(TRANCHE_B, swap.address, outB, version) + .returns(); + await swap.mock.addLiquidity.withArgs(version, addr1).returns(minLpOut); + + await expect( + primaryMarketRouter.splitAndStake( + outQ, + swapRouter.address, + btc.address, + minLpOut.add(1), + shareStaking.address, + version + ) + ).to.be.revertedWith("Insufficient output"); + }); + + it("Should split and stake both bishop and rook", async function () { + await expect(() => + primaryMarketRouter.splitAndStake( + outQ, + swapRouter.address, + btc.address, + minLpOut, + shareStaking.address, + version + ) + ).to.callMocks( + { + func: fund.mock.trancheTransfer.withArgs( + TRANCHE_B, + swap.address, + outB, + version + ), + }, + { + func: swap.mock.addLiquidity.withArgs(version, addr1), + rets: [minLpOut], + }, + { + func: fund.mock.trancheTransfer.withArgs( + TRANCHE_R, + shareStaking.address, + outB, + version + ), + }, + { + func: shareStaking.mock.deposit.withArgs(TRANCHE_R, outB, addr1, version), + } + ); + }); + + it("Should split and stake bishop and transfer back rook", async function () { + await expect(() => + primaryMarketRouter.splitAndStake( + outQ, + swapRouter.address, + btc.address, + minLpOut, + constants.AddressZero, + version + ) + ).to.callMocks( + { + func: fund.mock.trancheTransfer.withArgs( + TRANCHE_B, + swap.address, + outB, + version + ), + }, + { + func: swap.mock.addLiquidity.withArgs(version, addr1), + rets: [minLpOut], + }, + { + func: fund.mock.trancheTransfer.withArgs(TRANCHE_R, addr1, outB, version), + } + ); + }); + }); + + describe("create()", function () { + it("Should create by calling primary market create", async function () { + await expect(() => + primaryMarketRouter.create(addr1, inBtc, outQ, version) + ).to.callMocks( + { + func: btc.mock.transferFrom.withArgs(addr1, primaryMarket.address, inBtc), + rets: [true], + }, + { + func: primaryMarket.mock.create.withArgs(addr1, outQ, version), + rets: [outQ], + } + ); + }); + + it("Should buy by calling primary market create", async function () { + await expect(() => + primaryMarketRouter.buy(version, outQ, addr1, "0x") + ).to.callMocks( + { + func: btc.mock.balanceOf.withArgs(primaryMarketRouter.address), + rets: [inBtc], + }, + { + func: btc.mock.transfer.withArgs(primaryMarket.address, inBtc), + rets: [true], + }, + { + func: primaryMarket.mock.create.withArgs(addr1, outQ, version), + rets: [outQ], + } + ); + }); + + it("Should stake after creation", async function () { + await expect(() => + primaryMarketRouter.createAndStake(inBtc, outQ, shareStaking.address, version) + ).to.callMocks( + { + func: btc.mock.transferFrom.withArgs(addr1, primaryMarket.address, inBtc), + rets: [true], + }, + { + func: primaryMarket.mock.create.withArgs( + shareStaking.address, + outQ, + version + ), + rets: [outQ], + }, + { + func: shareStaking.mock.deposit.withArgs(TRANCHE_Q, outQ, addr1, version), + } + ); + }); + + it("Should split and stake after creation", async function () { + await expect(() => + primaryMarketRouter.createSplitAndStake( + inBtc, + outQ, + swapRouter.address, + btc.address, + minLpOut, + shareStaking.address, + version + ) + ).to.callMocks( + { + func: btc.mock.transferFrom.withArgs(addr1, primaryMarket.address, inBtc), + rets: [true], + }, + { + func: primaryMarket.mock.create.withArgs( + primaryMarketRouter.address, + outQ, + version + ), + rets: [outQ], + }, + { + func: primaryMarket.mock.split.withArgs( + primaryMarketRouter.address, + outQ, + version + ), + rets: [outB], + }, + { + func: fund.mock.trancheTransfer.withArgs( + TRANCHE_B, + swap.address, + outB, + version + ), + }, + { + func: swap.mock.addLiquidity.withArgs(version, addr1), + rets: [minLpOut], + }, + { + func: fund.mock.trancheTransfer.withArgs( + TRANCHE_R, + shareStaking.address, + outB, + version + ), + }, + { + func: shareStaking.mock.deposit.withArgs(TRANCHE_R, outB, addr1, version), + } + ); + }); + }); + + describe("redeem()", function () { + it("Should sell by calling primary market redeem", async function () { + await expect(() => + primaryMarketRouter.sell(version, inBtc, addr1, "0x") + ).to.callMocks( + { + func: fund.mock.trancheBalanceOf.withArgs( + TRANCHE_Q, + primaryMarketRouter.address + ), + rets: [outQ], + }, + { + func: primaryMarket.mock.redeem.withArgs(addr1, outQ, inBtc, version), + rets: [inBtc], + } + ); + }); + }); + }); +});