Проверенный контрактЧастичноеMIT
UniswapV3PositionVault
Адрес0xd40c0b40553f18d9b8b99425f64edfbd542e8b60
- Баланс
0 ETH
- Транзакций
1
- Компилятор
solc 0.8.37
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.37+commit.f401782d
- Язык
- solidity
- Оптимизация
- Да, 60 прогонов
- Версия EVM
- cancun
- Через IR
- да
- Лицензия
- MIT
- Совпадение
- Частичноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 399 142
- Транзакция создания
- 0x2ef32ccf42…836109749d
- Библиотеки
- src/UniswapV3PositionVault.sol:UniswapV3VaultMath0x8c7f…22f084
41 файл
Исходный код большой: показывается один файл. Выберите файл в списке.
- src/UniswapV3PositionVault.solглавный100,34 КБ
- lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol8,33 КБ
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol9,28 КБ
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol6,57 КБ
- lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol12,13 КБ
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1,19 КБ
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol4,51 КБ
- lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol1,15 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3,34 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4,45 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 Б
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol637 Б
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 Б
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol882 Б
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6,54 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6,24 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol473 Б
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2,78 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 Б
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13,28 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol997 Б
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Address.sol6 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Errors.sol896 Б
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Panic.sol1,97 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4,18 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 Б
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol32,35 КБ
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34,94 КБ
- src/IUniswapV3PositionVault.sol40,99 КБ
- src/interfaces/AggregatorV3Interface.sol1,74 КБ
- src/interfaces/INonfungiblePositionManager.sol7,82 КБ
- src/interfaces/IUniswapV3Factory.sol1,06 КБ
- src/interfaces/IUniswapV3Pool.sol4,77 КБ
- src/libraries/UniswapV3VaultMath.sol86,03 КБ
- src/libraries/uniswap/FixedPoint96.sol737 Б
- src/libraries/uniswap/FullMath.sol5,87 КБ
- src/libraries/uniswap/LiquidityAmounts.sol7,34 КБ
- src/libraries/uniswap/SafeCast.sol1,4 КБ
- src/libraries/uniswap/SqrtPriceMath.sol11,5 КБ
- src/libraries/uniswap/TickMath.sol9,77 КБ
- src/libraries/uniswap/UnsafeMath.sol1,02 КБ
src/UniswapV3PositionVault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IUniswapV3PositionVault} from "./IUniswapV3PositionVault.sol";
import {INonfungiblePositionManager} from "./interfaces/INonfungiblePositionManager.sol";
import {IUniswapV3Factory} from "./interfaces/IUniswapV3Factory.sol";
import {IUniswapV3Pool} from "./interfaces/IUniswapV3Pool.sol";
import {UniswapV3VaultMath} from "./libraries/UniswapV3VaultMath.sol";
/// @title UniswapV3PositionVault
/// @author KPK
/// @notice An ERC-20 share token backed by a single Uniswap v3 liquidity position.
/// @dev The vault owns at most one position NFT on one fixed pool, chosen at initialization and
/// never changed, and at most one ranged order on the same pool. A curator opens, moves and
/// closes that position; investors buy in at the vault's aggregate token ratio, across the
/// position, the idle balances and the ranged order, and redeem for a slice of it paid in
/// both tokens. The ranged order is the curator's limit order: a second NFT exactly one tick
/// spacing wide, wholly on one side of the price, holding the one token it is selling.
/// pinned: test/UniswapV3PositionVault.t.sol::test_initialize_cannotRunTwice
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_createRangedOrder_sellSitsOneSpacingAboveSpotAndHoldsOnlyToken0
///
/// A share is a pro-rata claim on the whole vault, meaning the position's liquidity, the
/// ranged order and any idle token balances together. Deposits and redemptions move all
/// three, so tokens that are waiting to be folded back into the position, or resting in an
/// order, are never given away to, or taken from, a single investor. Every deposit and
/// redemption first collects the fees of both NFTs, which is what makes fees accrue to
/// existing holders before a new one is priced. Folding those balances back into the
/// position is a curator action, behind the manipulation guard, because buying liquidity at
/// a price the caller picked is a way to take value out.
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_deposit_paysForTheOrdersShareSoExistingHoldersKeepTheirs
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_redeem_paysAProRataSliceOfTheOrder
///
/// All Uniswap arithmetic comes from Uniswap's own libraries, vendored under
/// src/libraries/uniswap and composed in UniswapV3VaultMath. Amounts the vault takes in are
/// rounded up and amounts it pays out, tokens and shares alike, are rounded down, so
/// rounding always favours the pool of existing shareholders over the account currently
/// transacting.
///
/// Tokens that do not move their full transferred amount, such as fee-on-transfer or
/// rebasing tokens, are not supported and must not be configured. Nor are tokens whose
/// approve or transfer runs code that can move the pool: such a token makes the calls that
/// add liquidity revert PriceMoved rather than misprice.
contract UniswapV3PositionVault is
Initializable,
UUPSUpgradeable,
AccessControlUpgradeable,
ERC20Upgradeable,
ReentrancyGuardUpgradeable,
IUniswapV3PositionVault,
IERC721Receiver
{
using SafeERC20 for IERC20;
//
// Constants
//
/// @notice Role identifier for the account that manages the position.
bytes32 public constant CURATOR = keccak256("CURATOR");
/// @notice Role identifier for accounts allowed to hold shares.
/// @dev Granting this role to address(0) opens the vault to everyone, which is how a
/// permissionless deployment is expressed without a separate flag.
bytes32 public constant INVESTOR = keccak256("INVESTOR");
/// @dev Largest deviation cap that can be configured, in basis points: 10000 admits a halving or
/// a doubling of the price.
uint256 private constant _MAX_BPS = 10_000;
//
// State Variables
//
/// @notice The pool's token0.
IERC20 public token0;
/// @notice The pool's token1.
IERC20 public token1;
/// @notice The Uniswap v3 pool the vault provides liquidity to.
IUniswapV3Pool public pool;
/// @notice The Uniswap v3 position manager that custodies the position NFT.
INonfungiblePositionManager public positionManager;
/// @notice The pool's fee tier, in hundredths of a basis point.
uint24 public fee;
/// @notice The pool's tick spacing, cached at initialization.
int24 public tickSpacing;
/// @notice Length of the manipulation-guard window, in seconds.
uint32 public twapPeriod;
/// @notice Maximum tolerated deviation of spot price from the average, in basis points.
uint16 public maxTwapDeviationBps;
/// @dev True only while this contract is inside its own position mint. Today's position manager
/// mints with _mint rather than _safeMint, so the receive hook is never actually reached
/// during a mint of ours and this flag is never observed true; it is here so that a manager
/// which did use _safeMint would still be able to deliver, rather than have the vault
/// refuse the position it just paid for.
bool private _minting;
/// @notice Id of the position NFT the vault currently holds, or 0 when it holds none.
/// @dev Changes every time a position is opened or closed, so integrators must read it
/// rather than cache it.
uint256 public activeTokenId;
/// @dev `10**decimals1`, the numerator of the human-price scaling.
uint256 public priceScaleNum;
/// @dev `1e18 * 10**decimals0`, the denominator of the human-price scaling.
uint256 public priceScaleDen;
/// @notice The optional Chainlink cross-check.
/// @dev It is fully off only when ALL THREE addresses are zero. Zeroing the two PRICE feeds
/// while leaving sequencerUptimeFeed set is a supported configuration and still runs
/// the sequencer check, which can still reject a guarded call — see _checkSlippage.
/// @dev Deliberately not an initialize parameter. Feeds are the one piece of this vault's
/// configuration that can stop being correct without anything about the vault changing,
/// so it is the one piece that has a setter — see setOracleConfig.
///
/// DECLARED AT THE TAIL rather than beside maxTwapDeviationBps, where it belongs by
/// subject. It takes three slots, and declaring it next to the other guard
/// configuration pushed _minting, activeTokenId, priceScaleNum and priceScaleDen down
/// by three. An in-place upgrade of a live proxy would then have read activeTokenId as
/// zero — orphaning the position NFT while the manager still reported the vault as its
/// owner, with no recovery function able to reach it — and read both price scales as
/// zero, reverting every conversion. Appending leaves every earlier slot where it was,
/// which is the property the gap exists to provide.
IUniswapV3PositionVault.OracleConfig public oracleConfig;
/// @dev Id of the ranged order's NFT, or 0 when there is none; read it through rangedOrderId().
/// One at a time: a single slot keeps every accounting path that has to count the order a
/// fixed amount of work.
uint256 private _rangedOrderTokenId;
/// @dev The side the ranged order was placed on, true for a sell of token0. Stored rather than
/// inferred because nothing else on chain records it: once an order has filled it sits on
/// the other side of the price holding the other token, where a fresh order of the
/// opposite side would sit. Not cleared when the order closes; rangedOrderId() reports it only
/// alongside a live id.
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_unwindRangedOrder_returnsAnUntouchedOrderToIdle
bool private _rangedOrderZeroForOne;
/// @notice Gap for upgradeability.
/// @dev 45, not 50: oracleConfig took three slots out of it and the ranged order two, so the
/// total footprint is unchanged and nothing above them moved. Every future append repeats
/// that arithmetic — take from the gap, never from the variables above it. Nothing
/// automated enforces this: the tests deploy through UnsafeUpgrades, which skips layout
/// validation.
uint256[45] private __gap;
//
// Constructor
//
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
//
// Initialization
//
/// @notice Initializes the vault against one Uniswap v3 pool.
/// @dev The pool is resolved through the position manager's own factory, so a mismatched
/// token pair or fee tier fails here rather than at the first position.
/// @param params Initialization parameters.
function initialize(InitParams memory params) external initializer {
__UUPSUpgradeable_init();
__AccessControl_init();
__ERC20_init(params.name, params.symbol);
__ReentrancyGuard_init();
if (params.admin == address(0) || params.curator == address(0) || params.positionManager == address(0)) {
revert ZeroAddress();
}
if (params.token0 >= params.token1) revert TokensNotSorted();
address poolAddress = IUniswapV3Factory(INonfungiblePositionManager(params.positionManager).factory())
.getPool(params.token0, params.token1, params.fee);
if (poolAddress == address(0)) revert PoolNotFound();
uint8 decimals0 = IERC20Metadata(params.token0).decimals();
uint8 decimals1 = IERC20Metadata(params.token1).decimals();
if (decimals0 > 18 || decimals1 > 18) revert UnsupportedDecimals();
// Bounded because _checkSlippage clamps every CALLER argument to _MAX_BPS, so a vault
// configured above it could not be addressed by the per-call API at all: passing the
// documented maximum of 10000 would silently tighten a 12000 vault to 10000 rather than
// reproduce it. That is safe in direction but it falsifies the claim this parameter rests
// on — that 10000 reproduces what these calls enforced before it existed — and it would
// have made the mechanical update of every existing call site behaviour-changing for such a
// deployment.
//
// It binds NEW deployments only, and that limit is deliberate rather than overlooked.
// initialize is initializer-guarded, so a proxy deployed before this change while holding a
// cap above 10000 would carry it across an upgrade untouched and the claim would still be
// false for that proxy. Handling it would mean adding upgrade-migration machinery to a
// contract that has never been upgraded, for a proxy that does not exist:
// docs/DEPLOYED_ADDRESSES.md records no live deployment from this repository. If one is
// ever created before this lands, clamping it belongs in that migration, not here.
// BOTH ends, because a zero cap is the worse of the two and was the one left behind. The
// deploy script has always refused both; an earlier commit promoted only the upper half in
// here. At zero, _checkSlippage computes bound = min(caller, 0) = 0 and twapCheck refuses
// unless spot equals the average to the wei — so no position can ever be opened, no shares
// are ever minted, and since there is no recovery function any tokens already moved in are
// stuck for good. There is no setter for this field; only an upgrade recovers it.
if (params.maxTwapDeviationBps == 0 || params.maxTwapDeviationBps > _MAX_BPS) {
revert InvalidArguments();
}
// And a zero window, for the same reason and with a worse symptom. It was previously
// recorded-and-accepted on the grounds that it fails loudly, which is true — but the cap
// check above turned that into an inconsistency rather than a decision: the two values sit
// in one struct, both brick the vault permanently when zero, both have no setter, and only
// one was refused. requireTwapAvailable cannot catch it, because observe([0, 0]) is a
// perfectly answerable request; the failure surfaces later, inside meanTick, as a division
// by zero. So it is not even the typed revert the cap gives you.
if (params.twapPeriod == 0) revert InvalidArguments();
token0 = IERC20(params.token0);
token1 = IERC20(params.token1);
pool = IUniswapV3Pool(poolAddress);
positionManager = INonfungiblePositionManager(params.positionManager);
fee = params.fee;
tickSpacing = IUniswapV3Pool(poolAddress).tickSpacing();
// The third check on the guard's configuration, for the same reason as the two above —
// getting any of them wrong does not weaken the vault, it stops it. A window the pool has no
// history for makes every guarded call revert until somebody else grows the pool's
// observation buffer. Note this one cannot catch a ZERO window: observe([0, 0]) is a
// perfectly answerable request, which is why the explicit check sits further up.
//
// What is still NOT second-guessed is where between 1 and 10000 the tolerance should sit.
// That is a judgement about the pool and one implementation serves pools of very different
// character, so any constant baked in here would be wrong for some of them. All three checks
// reject values that are not settings at all; none of them picks a setting.
UniswapV3VaultMath.requireTwapAvailable(pool, params.twapPeriod);
twapPeriod = params.twapPeriod;
maxTwapDeviationBps = params.maxTwapDeviationBps;
priceScaleNum = 10 ** decimals1;
priceScaleDen = 1e18 * 10 ** decimals0;
_grantRole(DEFAULT_ADMIN_ROLE, params.admin);
_grantRole(CURATOR, params.curator);
}
//
// Authorization
//
/// @notice Restricts a function to the default admin.
modifier isAdmin() {
if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert NotAuthorized();
_;
}
/// @notice Restricts a function to the curator.
modifier isCurator() {
if (!hasRole(CURATOR, msg.sender)) revert NotAuthorized();
_;
}
/// @notice Rejects a call mined after the caller's deadline.
/// @param deadline The latest timestamp at which the call may execute.
modifier checkDeadline(uint256 deadline) {
if (block.timestamp > deadline) revert DeadlineExpired();
_;
}
/// @notice Whether an account may hold shares.
/// @dev Granting INVESTOR to address(0) opens the vault, which is checked first so an open
/// vault costs a single role lookup.
/// @param account The address to check.
/// @return True when the account may hold, receive or burn shares.
function isInvestor(address account) public view returns (bool) {
return hasRole(INVESTOR, address(0)) || hasRole(INVESTOR, account);
}
//
// Investor Operations
//
/// @notice Buys into the position with both token amounts, in the shape of increaseLiquidity.
/// @dev The caller offers as much of each token as they are willing to spend and the vault
/// takes what its own ratio needs (the position, the idle balances and the ranged order
/// together), bounded by whichever offer is the tighter of the two. Neither amount is
/// ever exceeded; the remainder is simply not
/// taken. The fees of the position and of any ranged order are collected into the idle
/// balance first, so they belong to existing holders and are charged to this deposit
/// rather than shared with it. They are not folded back into the position: that is a
/// curator action, for the reason given on _compound. The ranged order is charged the
/// same way as the idle balance, pro-rata, and what is paid for it joins the idle balance.
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_deposit_paysForTheOrdersShareSoExistingHoldersKeepTheirs
///
/// Both bounds are amounts rather than percentages, because what the second side costs
/// is not a function of price alone. It scales with the caller's share of the vault,
/// which is their amount over the vault's holding of that token — so offering a token
/// the vault holds almost none of buys a large fraction of the vault and is charged the
/// matching fraction of the other side. That is pro-rata, and the shares are worth what
/// they cost, but it can be far more than expected, and a percentage bound cannot catch
/// it: the charge is not off the fair price, it is the fair price of a much larger
/// purchase. Two absolute amounts catch it.
///
/// Pass what you actually hold rather than a sentinel; a very large value for both sides
/// has no meaningful answer and the share arithmetic will revert rather than return one.
/// UniswapV3PositionVaultLens.previewDepositCounterAmount quotes one side against the
/// other, at the vault's ratio.
///
/// Do not pass zero for a side you simply do not want to spend. Zero does not mean "I
/// hold none of this"; it means "cap my deposit at what zero of it buys", and since the
/// deposit is the smaller of the two sides' share counts, that caps the whole deposit at
/// nothing and reverts ZeroShares. A side is skipped only when the vault holds literally
/// none of it, position amount, idle balance and ranged order all zero, and that state is
/// not one to build a call on: any address can end it by sending a single wei, after
/// which the zero offer is refused permanently. For a side you do not want to bind, pass
/// an amount you can cover that sits above its pro-rata charge, which is your share of the
/// vault's holding of that token and is a wei when the vault holds a wei.
/// UniswapV3PositionVaultLens.previewDeposit reverts the same way on the same inputs, so
/// quoting first shows this before a deposit does.
/// pinned: test/UniswapV3PositionVault.t.sol::test_deposit_zeroOfferIsRefusedOnceTheVaultHoldsAnyOfThatSide
///
/// The two amounts bound what leaves the caller's wallet. They say nothing about what
/// comes back, so minShares bounds that: it is the only limit on the rate at which the
/// deposit is filled. It matters because a deposit takes what the ratio needs at the
/// pool's price when the transaction lands, not when it was signed, so a caller who
/// offered generously on both sides could be filled at a size they did not intend.
/// Quote it with UniswapV3PositionVaultLens.previewDeposit, which returns the share count
/// a deposit of these amounts would mint. Not UniswapV3PositionVaultLens.previewLiquidity:
/// that prices the position alone, while shares are supply times added liquidity over the
/// position's liquidity and a deposit also pays for the idle balances and the ranged
/// order, so the two are different quantities. Zero accepts any fill.
/// pinned: test/UniswapV3PositionVault.t.sol::test_previewDeposit_isNotTheSameAsPreviewLiquidity
///
/// That bounds the amount. What bounds the price is maxSlippageBps, below.
/// @param amount0Desired The most token0 to spend.
/// @param amount1Desired The most token1 to spend.
/// @param minShares The fewest shares the caller will accept. Zero to accept any.
/// @param maxSlippageBps How far the pool's price may sit from its recent average, in basis
/// points, in either direction: max(spot/average, average/spot) - 1.
/// Between 1 and 10000, and the vault's own tolerance caps it, so
/// this can only tighten the guard and never loosen it. 10000 does not
/// waive the check here — it accepts the vault's tolerance. Only redeem
/// waives, and only because its payout does not depend on the price.
/// @param deadline Latest timestamp at which the deposit may execute.
/// @return shares Shares minted to the caller.
/// @return amount0 Token0 actually taken.
/// @return amount1 Token1 actually taken.
function deposit(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 minShares,
uint16 maxSlippageBps,
uint256 deadline
) external nonReentrant checkDeadline(deadline) returns (uint256 shares, uint256 amount0, uint256 amount1) {
if (!isInvestor(msg.sender)) revert NotInvestor(msg.sender);
uint256 tokenId = activeTokenId;
if (tokenId == 0) revert NoActivePosition();
// Collect, but do not fold. Collecting is price-independent: the fees land in the idle
// balance, which is read below and charged to this depositor pro-rata, so the fees a
// position earned before they arrived still belong to the holders who were here for them.
// Folding is not price-independent, and it is not this caller's to trigger. See _compound.
_collect(tokenId, type(uint128).max, type(uint128).max);
_collectRangedOrder();
// The tighter of the caller's bound and the vault's. What the caller bounds by amount is
// below; this bounds the price those amounts are computed at, and _increaseLiquidity holds
// the increase to it.
uint160 sqrtPriceX96 = _checkSlippage(maxSlippageBps);
// Everything outside the position: the idle balances and the ranged order, the order valued
// rounding up at the price the guard just checked. The deposit buys a slice of it like any
// other holding, so it pays for its share of the order rather than diluting the holders who
// funded it. That valuation is not a door for a manipulated price: a one-sided order's
// holding does not depend on the price at all, and a band's holdings at the true price are
// the cheapest point on its curve, so a price pushed into a straddled order makes the
// depositor pay more. Read through the same function the previews use, which also owns the
// supply floor, so a guard added there refuses the same states here.
// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_deposit_paysForTheOrdersShareSoExistingHoldersKeepTheirs
(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
uint256 idle0,
uint256 idle1,
uint256 supply
) = _depositQuoteState(sqrtPriceX96);
(uint256 targetShares, uint256 charge0, uint256 charge1, uint256 pulled0, uint256 pulled1) = UniswapV3VaultMath.depositPlan(
sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, liquidity, idle0, idle1, supply, amount0Desired, amount1Desired
);
// The hard guarantee, each side against the caller's own number.
if (pulled0 > amount0Desired || pulled1 > amount1Desired) revert SlippageExceeded(pulled0, pulled1);
if (pulled0 != 0) token0.safeTransferFrom(msg.sender, address(this), pulled0);
if (pulled1 != 0) token1.safeTransferFrom(msg.sender, address(this), pulled1);
uint128 mintedLiquidity;
(mintedLiquidity, amount0, amount1) = _increaseLiquidity(tokenId, charge0, charge1, sqrtPriceX96);
// Price the shares on the liquidity the position actually gained, then cap at what the
// named amount paid for, so the idle share charged below cannot exceed what was taken.
shares = UniswapV3VaultMath.sharesForLiquidity(supply, mintedLiquidity, liquidity);
if (shares > targetShares) shares = targetShares;
if (shares == 0) revert ZeroShares();
if (shares < minShares) revert InsufficientShares(shares, minShares);
amount0 += UniswapV3VaultMath.idleShare(idle0, shares, supply);
amount1 += UniswapV3VaultMath.idleShare(idle1, shares, supply);
_mint(msg.sender, shares);
if (pulled0 > amount0) token0.safeTransfer(msg.sender, pulled0 - amount0);
if (pulled1 > amount1) token1.safeTransfer(msg.sender, pulled1 - amount1);
emit Deposit(msg.sender, shares, amount0, amount1, mintedLiquidity);
}
/// @notice Sells shares back for a pro-rata slice of the vault, paid in both tokens.
/// @dev Withdraws the caller's share of the position's liquidity, of the ranged order's
/// liquidity and of any idle balance. Both NFTs' fees are collected into the idle
/// balance first and the liquidity slices are withdrawn principal only, so the redeemer
/// takes the same pro-rata share of the fees as of everything else and leaves the rest
/// to the remaining holders.
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_redeem_takesTheOrdersUncollectedFeesWithIt
/// @param shares Shares to burn.
/// @param maxSlippageBps How far the pool's price may sit from its recent average, in basis
/// points, in either direction: max(spot/average, average/spot) - 1,
/// bounding the split between the two tokens. Must be between 1 and
/// 10000, and it is capped by the vault's own tolerance.
///
/// Pass 10000 to waive it. What a redemption pays is the caller's share
/// of the position's liquidity, of the ranged order's liquidity and of
/// the idle balances, and none depends on the price; only the split
/// between the two tokens does. So a redeemer always has a way out, and
/// the guard cannot become a lock during exactly the volatility that
/// makes people want to leave. It is skipped outright when the vault
/// holds neither a position nor a ranged order, where a redemption is two
/// pro-rata transfers and there is nothing a price could affect.
/// @param deadline Latest timestamp at which the redemption may execute.
/// @return amount0 Token0 paid to the caller.
/// @return amount1 Token1 paid to the caller.
function redeem(uint256 shares, uint16 maxSlippageBps, uint256 deadline)
external
nonReentrant
checkDeadline(deadline)
returns (uint256 amount0, uint256 amount1)
{
if (shares == 0) revert ZeroShares();
if (!isInvestor(msg.sender)) revert NotInvestor(msg.sender);
if (maxSlippageBps < _MAX_BPS && (activeTokenId != 0 || _rangedOrderTokenId != 0)) {
_checkSlippage(maxSlippageBps);
} else if (maxSlippageBps == 0 || maxSlippageBps > _MAX_BPS) {
revert InvalidArguments();
}
// Collected, not folded, for the reason given on _compound: a redemption's payout does not
// depend on the price, but folding at the pool's current price does, and this path can be
// reached with the price guard waived.
uint256 openTokenId = activeTokenId;
if (openTokenId != 0) _collect(openTokenId, type(uint128).max, type(uint128).max);
_collectRangedOrder();
uint256 supply = totalSupply();
uint256 idle0 = token0.balanceOf(address(this));
uint256 idle1 = token1.balanceOf(address(this));
// The same slice of each NFT's liquidity, so the claim is on liquidity in both and the price
// sets only the split between the two tokens, never the size of the claim.
uint128 burnedLiquidity;
if (openTokenId != 0) (burnedLiquidity, amount0, amount1) = _withdrawShare(openTokenId, shares, supply);
uint256 orderId = _rangedOrderTokenId;
if (orderId != 0) {
(, uint256 order0, uint256 order1) = _withdrawShare(orderId, shares, supply);
amount0 += order0;
amount1 += order1;
}
amount0 += UniswapV3VaultMath.idleShareDown(idle0, shares, supply);
amount1 += UniswapV3VaultMath.idleShareDown(idle1, shares, supply);
if (amount0 == 0 && amount1 == 0) revert ZeroShares();
_burn(msg.sender, shares);
if (amount0 != 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 != 0) token1.safeTransfer(msg.sender, amount1);
emit Redeem(msg.sender, shares, amount0, amount1, burnedLiquidity);
}
//
// Curator Operations
//
/// @notice Opens the vault's only position, funded by both token amounts.
/// @dev The curator names a price range and how much of each token to commit, and the vault
/// mints the liquidity the tighter of the two funds. Both amounts are maxima; neither is
/// exceeded, and both must already be sitting in the vault.
///
/// Both are bounded for the same reason a deposit's are. What the second side costs is a
/// steep function of price near a range boundary, and the manipulation guard bounds the
/// price only to the vault's own tolerance, not to zero. Measured on the mainnet
/// USDC/WETH pool with a range five percent wide: a 190 basis point move, inside the
/// two hundred point tolerance the fixture ships, takes what 100,000 USDC needs
/// alongside it from 41.9 WETH to 93.6. Minting is the direction a wrong price
/// punishes — buying liquidity at P' and valuing it at P costs the difference — so a
/// curator who named one amount and let the other follow could be made to commit more
/// than twice what they quoted, bounded only by what the vault happens to hold.
/// @param priceLower Lower bound of the range, as a 1e18-scaled human price.
/// @param priceUpper Upper bound of the range.
/// @param amount0Desired The most token0 to commit.
/// @param amount1Desired The most token1 to commit.
/// @param maxSlippageBps How far the pool's price may sit from its recent average, in basis
/// points, in either direction: max(spot/average, average/spot) - 1.
/// Between 1 and 10000, capped by the vault's own tolerance. The
/// measurement above is why this is worth passing tightly: inside a 200
/// point tolerance the second side's cost more than doubled.
/// @param deadline Latest timestamp at which the call may execute.
/// @return tokenId The new position's NFT id.
/// @return liquidity Liquidity minted.
/// @return amount0 Token0 actually committed.
/// @return amount1 Token1 actually committed.
function createPosition(
uint256 priceLower,
uint256 priceUpper,
uint256 amount0Desired,
uint256 amount1Desired,
uint16 maxSlippageBps,
uint256 deadline
)
external
nonReentrant
isCurator
checkDeadline(deadline)
returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)
{
if (activeTokenId != 0) revert PositionAlreadyActive();
if (amount0Desired == 0 && amount1Desired == 0) revert InvalidArguments();
uint160 sqrtPriceX96 = _checkSlippage(maxSlippageBps);
(int24 tickLower, int24 tickUpper) = _priceRangeToTicks(priceLower, priceUpper);
(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96) = UniswapV3VaultMath.sqrtRatiosForTicks(tickLower, tickUpper);
(uint128 fundable, uint256 need0, uint256 need1) =
UniswapV3VaultMath.positionPlan(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired);
if (fundable == 0) revert InvalidArguments();
_requireIdle(token0, need0);
_requireIdle(token1, need1);
(tokenId, liquidity, amount0, amount1) = _mintPosition(tickLower, tickUpper, need0, need1, sqrtPriceX96);
_bootstrapShares(liquidity);
}
/// @notice Closes the vault's position, leaving everything it held idle in the vault.
/// @dev Collects fees and principal together and burns the NFT, so activeTokenId returns to
/// zero. Shares are untouched; holders now own idle tokens instead of the position's
/// liquidity; a live ranged order is untouched.
///
/// Unguarded, and deliberately so — this was briefly changed and changed back, so the
/// reason is recorded with its arithmetic rather than asserted.
///
/// Releasing liquidity at a manipulated price does not cost the vault anything; it PAYS
/// it. A position's value is concave in the price, so the basket a release hands back is
/// the tangent to that curve at the price it was taken at, and a tangent to a concave
/// curve lies above it everywhere. Releasing liquidity L at a wrong sqrt price s' and
/// marking the basket at the true s gives an excess of exactly L(s - s')^2 / s', which
/// is non-negative whichever side the price was pushed. Checked numerically on a range
/// of [P=1, P=4] at a true sqrt price of 1.5: a release at 1.0 is worth 1.125 against
/// the position's 0.875, and one at 2.0 is worth 1.000. There is no sandwich to run.
///
/// This is the mirror of the mint paths and not a contradiction of them. The same
/// L(s - s')^2 / s' is a cost when the vault ACQUIRES liquidity at s' and a gain when it
/// releases. The asymmetry is about which side of the trade the vault is on, not about
/// curvature, and it is why compound and rebalance are guarded while this is not.
///
/// A deadline would be the same mistake: there is no price at which this call becomes a
/// worse outcome than not making it, so there is nothing for one to protect. What a
/// guard here WOULD do is block the curator from closing the position during exactly the
/// volatility that makes closing it urgent.
/// @return amount0 Token0 returned to the vault.
/// @return amount1 Token1 returned to the vault.
function unwindPosition() external nonReentrant isCurator returns (uint256 amount0, uint256 amount1) {
uint256 tokenId = activeTokenId;
if (tokenId == 0) revert NoActivePosition();
(amount0, amount1) = _unwind(tokenId);
}
/// @notice Collects the position's fees and folds every idle balance back into it.
/// @dev Fees are compounded rather than distributed, and this is where that happens. The
/// investor paths collect without folding, because buying liquidity at a price the
/// caller arrived at is a way to take value out of the vault; folding is therefore a
/// curator action, behind the manipulation guard.
///
/// It folds more than fees. Anything sitting idle goes in: the residue a trim or a
/// non-trading rebalance left behind, and anything donated. That is why it is not called
/// compoundFees.
///
/// Returning zero is a normal outcome, not a failure. A one-sided idle balance cannot be
/// paired into a range that straddles the price, so nothing is added. The fees are
/// collected before that pairing is attempted, so reverting on a zero result would throw
/// away a collection that had already happened — which is what the old addLiquidity did,
/// and why the two were merged rather than one being renamed.
///
/// A fold happens at the price the guard checked; if the pool has moved by the time the
/// position manager reads it, compound reverts PriceMoved.
/// pinned: test/UniswapV3PositionVault.PinnedPrice.t.sol::test_compound_refusesAMovedPrice
///
/// fractionBps is the share of the vault's TOTAL capital to leave deployed — the same
/// quantity rebalance takes, measured the same way, so passing the fraction the position
/// was opened at does exactly what it looks like: it folds the fees and leaves the
/// reserve where it is. Passing 10000 deploys everything. A live ranged order counts
/// toward that capital and its fees are collected and folded, but the order itself is
/// left working: only what is idle is ever folded.
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_compound_collectsTheOrdersFeesAndLeavesItInPlace
///
/// It is idempotent. Calling compound twice with the same fraction folds on the first
/// call and does nothing on the second, because the target is a level rather than an
/// increment. A fraction below what is already deployed also folds nothing; this
/// function never removes liquidity, so reducing exposure is a rebalance.
///
/// This is deliberately not remembered between calls. The vault stores no intended
/// exposure, so nothing reconciles two calls made at different fractions: the reserve is
/// whatever the last call left behind, and maintaining it is the curator's business.
/// @param fractionBps Share of the fundable maximum to fold in, in basis points. Must be
/// between 1 and 10000.
/// @param maxSlippageBps How far the pool's price may sit from its recent average, in basis
/// points, in either direction: max(spot/average, average/spot) - 1.
/// Between 1 and 10000, capped by the vault's own tolerance.
/// @param deadline Latest timestamp at which the call may execute. It folds at the pool's
/// current price, so a stale one compounds at a ratio the curator never chose.
/// @return liquidity Liquidity added back into the position, zero when nothing could be paired.
function compound(uint16 fractionBps, uint16 maxSlippageBps, uint256 deadline)
external
nonReentrant
isCurator
checkDeadline(deadline)
returns (uint128 liquidity)
{
if (fractionBps == 0 || fractionBps > _MAX_BPS) revert InvalidArguments();
if (activeTokenId == 0) revert NoActivePosition();
liquidity = _compound(fractionBps, _checkSlippage(maxSlippageBps));
}
/// @notice Withdraws part of the position's liquidity into the vault's idle balances.
/// @dev The withdrawn tokens stay in the vault and remain owned pro-rata by shareholders.
/// Unguarded, for the reason set out in full on unwindPosition: a release is the
/// favourable direction, worth L(s - s')^2 / s' MORE at the true price than the position
/// it replaced, whichever way the price was pushed.
/// @param liquidity Liquidity to withdraw.
/// @return amount0 Token0 released.
/// @return amount1 Token1 released.
function removeLiquidity(uint128 liquidity)
external
nonReentrant
isCurator
returns (uint256 amount0, uint256 amount1)
{
uint256 tokenId = activeTokenId;
if (tokenId == 0) revert NoActivePosition();
(,, uint128 current) = _positionRange(tokenId);
if (liquidity == 0 || liquidity > current) revert InvalidArguments();
// Trimming everything is allowed and leaves the NFT open at zero liquidity, which is not
// the same state as having no position: the range survives, so compound can refill it. What
// cannot happen in that state is a deposit — shares are priced as a fraction of the
// position's liquidity and there is none to take a fraction of — so deposit reverts
// NoActivePosition until the curator refills or replaces the range.
(amount0, amount1) = _withdrawLiquidity(tokenId, liquidity);
emit LiquidityRemoved(tokenId, liquidity, amount0, amount1);
}
/// @notice Moves the vault's liquidity into a new price range, deploying a chosen fraction of it.
/// @dev Collects fees, closes the current position, and mints into the new range. Nothing is
/// traded — this vault has no swap — so the two balances arrive at the new range in
/// whatever ratio the old position and its fees produced, and the range must be chosen
/// to suit them. Liquidity needs both tokens in the proportion the range implies, so
/// whichever side the range needs less of is what binds, and the surplus of the other
/// stays idle.
///
/// That coupling is the price of having no swap, and it is not a trap: for any ratio
/// there is SOME range that consumes almost all of it, because the ratio a range wants
/// sweeps continuously from all token0 (a range entirely above the spot price) to all
/// token1 (one entirely below). Almost all rather than all — the mint consumes the
/// binding side and leaves the other's rounding dust behind. What it does mean is that the range
/// is no longer a free choice — it is a choice constrained by what the vault is holding
/// when the call is made.
///
/// fractionBps then scales that down deliberately. At 10000 the position is the largest
/// the balances support, which is what this function used to do unconditionally. Below
/// that, the position is opened with that share of the maximum and the rest is left
/// idle, still owned pro-rata by shareholders and still redeemable — a standing reserve
/// rather than an accident of the ratio. A curator sizing exposure by a Kelly criterion
/// has somewhere to put the answer.
///
/// The fraction applies to the vault's WHOLE capital, because by the time it is applied
/// the unwind above has moved the old position's principal and its uncollected fees into
/// the idle balance alongside whatever was already there, and a live ranged order is
/// closed in the same step for the same reason. There is no source of funds it does not
/// cover. A curator who wants an order beside the new position places a fresh one after
/// this call, in the same batch when the two have to land together.
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_rebalance_unwindsALiveOrderFirst
///
/// The pool's price is still checked against its own time-weighted average, because the
/// mint prices both sides at the current price even though no trade happens.
/// @param priceLower Lower bound of the new range, as a 1e18-scaled human price.
/// @param priceUpper Upper bound of the new range, as a 1e18-scaled human price.
/// @param fractionBps Share of the maximum fundable liquidity to deploy, in basis points.
/// 10000 deploys as much as the balances allow; 2500 deploys a quarter of
/// it and leaves the rest idle. Must be between 1 and 10000 — zero would
/// open no position at all, which is what unwindPosition is for.
/// @param maxSlippageBps How far the pool's price may sit from its recent average, in basis
/// points, in either direction: max(spot/average, average/spot) - 1.
/// Between 1 and 10000, capped by the vault's own tolerance. A
/// rebalance is the call this matters most on: it unwinds at the price and
/// re-mints at it, and the curator's transaction sits in a public mempool
/// where anyone may move the pool around it.
/// @param deadline Latest timestamp at which the move may execute.
/// @return tokenId The new position NFT id.
/// @return liquidity Liquidity minted.
/// @return amount0 Token0 consumed by the mint.
/// @return amount1 Token1 consumed by the mint.
function rebalance(
uint256 priceLower,
uint256 priceUpper,
uint16 fractionBps,
uint16 maxSlippageBps,
uint256 deadline
)
external
nonReentrant
isCurator
checkDeadline(deadline)
returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)
{
if (fractionBps == 0 || fractionBps > _MAX_BPS) revert InvalidArguments();
return _rebalance(priceLower, priceUpper, fractionBps, maxSlippageBps);
}
/// @notice Places a ranged order: a one-sided position exactly one tick spacing wide that the
/// curator uses as a limit order.
/// @dev A sell (zeroForOne) holds token0 in a band wholly at or above the price and converts it
/// to token1 as the price rises through; a buy holds token1 in a band wholly at or below
/// the price and converts as it falls. A band crossed in full executes at the geometric
/// mean of its two edges, the middle of the band in ticks, and is paid the pool's fee on
/// what it converts.
///
/// The band is named in ticks rather than prices because it is one spacing wide: a human
/// price snapped onto the grid can land one spacing off at a boundary, and for an order
/// that narrow, one spacing off is all of it. UniswapV3PositionVaultLens.activePosition
/// and UniswapV3PositionVaultLens.rangedOrder report ticks, so a curator placing an order
/// against the position's own range reads and writes one unit.
/// UniswapV3PositionVaultLens.rangedOrderTicks gives the two bands next to the price.
///
/// It is named rather than derived from spot at execution. A derived band follows
/// whatever spot the call lands at, so anyone able to order transactions around it could
/// push spot within the tolerance, have the band placed next to the pushed price and buy
/// through it. A named band lands where the curator chose or reverts.
///
/// Guarded like every other door that acquires liquidity, because the curator names the
/// band. A one-sided mint costs the same amount of its token at any price, but a band
/// placed one spacing from a spot the curator has just pushed sells the vault's token at
/// the pushed price to whoever pushes it back. maxSlippageBps holds spot to the pool's own
/// average, and to the oracle where one is configured. It bounds spot, not the band: the
/// band sits beyond spot by at least the rest of spot's spacing, and further if it is
/// named further out. The order is planned and minted at the price the guard checked,
/// or not at all; see PriceMoved.
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_createRangedOrder_refusesAManipulatedPrice
///
/// A stale order can still land: a sell signed below its band, after the market has risen
/// through it, mints if the price is pushed back under the band within that tolerance. The
/// deadline bounds it, so keep it short.
///
/// The amount must already be idle, and the pool never takes more of it. It can take
/// less: the liquidity the amount buys is rounded down through an intermediate product,
/// which for a sell at a very low raw price loses a material fraction (measured
/// 2026-11-03: 4.5% at tick -665,000, under a millionth from -500,000 up). What is not
/// committed stays idle. One order at a time; a live one has to be unwound first.
/// pinned: test/UniswapV3PositionVault.Math.t.sol::testFuzz_rangedOrderPlan_mintsExactlyItsPlan
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_createRangedOrder_sellSitsOneSpacingAboveSpotAndHoldsOnlyToken0
/// @param tickLower Lower tick of the band, on the pool's spacing grid.
/// @param zeroForOne True to sell token0 from a band above the price, false to sell token1 from
/// one below it.
/// @param amount Amount of the token being sold to commit.
/// @param maxSlippageBps How far the pool's price may sit from its recent average, in basis
/// points. Between 1 and 10000, capped by the vault's own tolerance.
/// @param deadline Latest timestamp at which the call may execute.
/// @return tokenId The order's NFT id.
/// @return liquidity Liquidity minted.
/// @return amount0 Token0 committed; zero for a buy.
/// @return amount1 Token1 committed; zero for a sell.
function createRangedOrder(
int24 tickLower,
bool zeroForOne,
uint256 amount,
uint16 maxSlippageBps,
uint256 deadline
)
external
nonReentrant
isCurator
checkDeadline(deadline)
returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)
{
if (_rangedOrderTokenId != 0) revert RangedOrderAlreadyActive();
_requireIdle(zeroForOne ? token0 : token1, amount);
uint160 sqrtPriceX96 = _checkSlippage(maxSlippageBps);
(int24 tickUpper,, uint256 need0, uint256 need1) =
UniswapV3VaultMath.rangedOrderPlan(sqrtPriceX96, tickLower, tickSpacing, zeroForOne, amount);
(tokenId, liquidity, amount0, amount1) = _mintLiquidity(tickLower, tickUpper, need0, need1, sqrtPriceX96);
_rangedOrderTokenId = tokenId;
_rangedOrderZeroForOne = zeroForOne;
emit RangedOrderCreated(tokenId, zeroForOne, tickLower, tickUpper, liquidity, amount0, amount1);
}
/// @notice Closes the ranged order, leaving everything it held idle in the vault.
/// @dev Collects principal and fees together and burns the NFT. Unguarded for the reason set
/// out on unwindPosition: a release is the favourable direction.
///
/// onlyIfFilled is not price protection and is not needed as such. It is how the curator
/// says "only if it has filled". A fold is built after seeing an order convert, and the
/// price can come back through a one-spacing band before it lands; its principal is then
/// the token it started with, and the check turns that into a revert rather than an
/// unwind nobody wanted.
///
/// Filled means spot at or past the band's far edge, where the order's principal is only
/// the token it converts into: see _requireRangedOrderFilled. A partial fill and a round
/// trip back are short of it, and are refused, as is a dust order whose unsold principal
/// rounds to nothing. Fees do not count: a crossing pays the order a fee in the token it
/// converts into, so fees say nothing about whether it filled. The check runs only when
/// onlyIfFilled is set; rebalance calls _unwindRangedOrder, which skips it.
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_unwindRangedOrder_onlyIfFilledRefusesASellThatCameBack
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_unwindRangedOrder_onlyIfFilledRefusesAPartFilledSell
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_unwindRangedOrder_onlyIfFilledRefusesADustSellShortOfItsEdge
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_unwindRangedOrder_onlyIfFilledUnwindsASellSittingOnItsUpperEdge
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_unwindRangedOrder_onlyIfFilledUnwindsAFilledBuy
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_unwindRangedOrder_onlyIfFilledRefusesABuyThatCameBack
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_unwindRangedOrder_onlyIfFilledRefusesAPartFilledBuy
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_unwindRangedOrder_onlyIfFilledUnwindsABuySittingOnItsLowerEdge
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_unwindRangedOrder_onlyIfFilledUnwindsAnOrderEmptiedByRedemptions
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_rebalance_unwindsALiveOrderFirst
/// @param onlyIfFilled True to revert RangedOrderNotFilled unless the order has wholly
/// converted; false to unwind whatever it holds.
/// @return amount0 Token0 returned to the vault, principal and fees together.
/// @return amount1 Token1 returned to the vault, principal and fees together.
function unwindRangedOrder(bool onlyIfFilled)
external
nonReentrant
isCurator
returns (uint256 amount0, uint256 amount1)
{
uint256 tokenId = _rangedOrderTokenId;
if (tokenId == 0) revert NoRangedOrder();
// Before the burn: the band is read from the NFT, which the burn destroys.
if (onlyIfFilled) _requireRangedOrderFilled(tokenId);
(amount0, amount1) = _unwindRangedOrder(tokenId);
}
//
// View Functions
//
/// @notice The ranged order's NFT id and the side it was placed on.
/// @dev (0, false) when there is none. The band, liquidity and fees live on the position
/// manager, where UniswapV3PositionVaultLens.rangedOrder reads them. The side is stored
/// because nothing else on chain records it: a filled sell and a fresh buy sit in the same
/// place holding the same token.
/// @return tokenId The order's NFT id, or 0 when there is none.
/// @return zeroForOne True for a sell of token0, false for a sell of token1.
function rangedOrderId() external view returns (uint256 tokenId, bool zeroForOne) {
tokenId = _rangedOrderTokenId;
if (tokenId != 0) zeroForOne = _rangedOrderZeroForOne;
}
/// @notice Runs the price guard every price-sensitive door runs, without acting.
/// @dev The same argument validation, the same clamp to maxTwapDeviationBps, the same TWAP and
/// oracle legs and the same typed errors as deposit, createPosition, compound, rebalance
/// and createRangedOrder at this bound. A keeper can call it before sending. The deploy script's
/// post-flight calls it at 10000, which resolves to the vault's own cap,
/// maxTwapDeviationBps, so the implementation the proxy points at is the one that judges
/// its oracle, on either deploy path.
/// @param maxSlippageBps The tolerance to check at, in basis points, between 1 and 10000.
/// @return sqrtPriceX96 The pool's current sqrt price, which passed.
function checkPrice(uint16 maxSlippageBps) external view returns (uint160 sqrtPriceX96) {
return _checkSlippage(maxSlippageBps);
}
//
// Callbacks
//
/// @inheritdoc IERC721Receiver
/// @dev The vault only ever holds a position it minted itself, so a token offered through
/// safeTransferFrom outside a mint is refused. In practice that is every token offered
/// this way: the position manager mints with _mint, which invokes no hook, so this
/// function is unreachable during the vault's own mint and _minting is never seen true
/// here. The flag is kept for a manager that minted with _safeMint; see its declaration.
///
/// Refusing here is not a guarantee that nothing else can arrive: a plain transferFrom
/// invokes no hook either, so any ERC-721 can still be parked on the vault, and there is no
/// recovery path of any kind, so it stays there forever. It is inert rather than dangerous,
/// since every id the vault hands the position manager is read from activeTokenId or
/// _rangedOrderTokenId. The same is true of any ERC-20 that is not one of the pool's two:
/// nothing can move it out, by design.
function onERC721Received(address, address, uint256, bytes calldata) external view override returns (bytes4) {
if (!_minting || msg.sender != address(positionManager)) revert UnexpectedNft();
return IERC721Receiver.onERC721Received.selector;
}
//
// Overrides
//
/// @notice Sets, changes or disables the Chainlink cross-check.
/// @dev On the admin rather than the curator, and the reason is worth stating because it is
/// the same reason the price tolerance is a call argument instead of stored state. This
/// setter adds the admin no power it lacks: the admin authorises upgrades, so it can
/// already change anything about this contract. Giving the same setter to the curator
/// WOULD add one — the curator is the party whose operations these guards constrain,
/// and letting it point the feeds at its own contract, or simply zero them, would let
/// it switch off the check on its own actions in a single transaction.
///
/// Zeroing both feeds is allowed, because a feed that has been deprecated has to be
/// removable without an upgrade. It is a reduction in protection, so it emits.
///
/// Feed decimals are read here and stored, rather than read on every guarded call.
/// Chainlink documents them as fixed for a feed, and re-pointing the vault at a different
/// feed comes through here and re-reads them. Call this again after a feed migration
/// rather than assuming the cache tracks it.
///
/// What is NOT validated is whether the heartbeats match what Chainlink publishes for
/// these feeds, because nothing on chain can tell. Too short freezes curator operations
/// for no reason; too long accepts an answer nobody should act on. Only a ceiling is
/// enforced: a heartbeat above 7 days, or a grace period above 1 day, reverts
/// InvalidArguments, bounding how far a unit slip such as milliseconds for seconds can go. Read
/// the published parameters for the chain being deployed to.
/// @param feed0 The token0/USD feed, or address(0) to disable the PRICE
/// cross-check. The sequencer check is separate and keeps
/// running if sequencerUptimeFeed is set.
/// @param heartbeat0 Maximum age of feed0's answer, in seconds.
/// @param feed1 The token1/USD feed. Set alongside feed0 or not at all.
/// @param heartbeat1 Maximum age of feed1's answer, in seconds.
/// @param sequencerUptimeFeed The L2 sequencer uptime feed, or address(0) if none exists.
/// @param sequencerGracePeriod Seconds to wait after the sequencer returns before trusting it.
function setOracleConfig(
address feed0,
uint32 heartbeat0,
address feed1,
uint32 heartbeat1,
address sequencerUptimeFeed,
uint32 sequencerGracePeriod
) external nonReentrant isAdmin {
UniswapV3VaultMath.writeOracleConfig(
oracleConfig, feed0, heartbeat0, feed1, heartbeat1, sequencerUptimeFeed, sequencerGracePeriod
);
}
/// @inheritdoc UUPSUpgradeable
// solhint-disable-next-line no-empty-blocks
function _authorizeUpgrade(
address /* newImplementation */
)
internal
view
override(UUPSUpgradeable)
isAdmin
{
// Authorization is handled by the isAdmin modifier
}
/// @inheritdoc ERC20Upgradeable
/// @dev Single point where the investor gate is enforced. Minting checks the recipient, burning
/// checks the holder and a transfer checks both, so shares can never reach an account that
/// is not permitted to hold them.
function _update(address from, address to, uint256 value) internal override(ERC20Upgradeable) {
if (from != address(0) && !isInvestor(from)) revert NotInvestor(from);
if (to != address(0) && !isInvestor(to)) revert NotInvestor(to);
super._update(from, to, value);
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view override(AccessControlUpgradeable) returns (bool) {
return interfaceId == type(IERC721Receiver).interfaceId || super.supportsInterface(interfaceId);
}
//
// Internal Functions
//
/// @notice Collects the position's fees and folds every idle balance back into it.
/// @dev Two steps, and only the first one is shared with the investor paths: deposit and
/// redeem call _collect directly, so fees are already in the vault when a share price is
/// computed, but nothing is folded back on their behalf. Folding is this function's
/// second step and belongs to the curator alone, for the reason below. A one-sided
/// remainder cannot be added at the pool's ratio and stays idle, still owned pro-rata,
/// until a rebalance moves the position to a range that balance can fund. The vault has
/// no swap, so that is the only way a one-sided remainder returns to work.
///
/// Only the curator's own entry points reach this, and only behind the price guard.
///
/// Folding buys liquidity at whatever price the pool is at, and a wrong price is costly:
/// liquidity acquired at P' and valued at the true price P costs an excess of
/// (sqrt(P') - sqrt(P))^2 / sqrt(P') per unit, positive for every P' other than P.
///
/// Releasing has the same curvature, not the opposite one — the value of a fixed amount of
/// liquidity is convex in sqrt(price), so a release at P' over-pays the releaser by that
/// same expression. What differs is who carries it. When the vault folds, the vault is the
/// one transacting at the bad price and the excess is paid out of every holder's stake.
/// When a redeemer releases, they receive a fixed fraction of the position's LIQUIDITY,
/// which is what it is whatever the price; the excess they collect comes from the pool, and
/// moving the pool there and back costs them the same amount before fees. The holders who
/// stay keep the same liquidity per share either way.
///
/// So the reason a redemption needs no guard is that shares are a claim on liquidity rather
/// than on value, and the reason this needs one is that folding converts holders' idle
/// balances into liquidity at a price someone else can choose. Do not read it as "releasing
/// is safe, acquiring is not" and waive a guard on that basis: any path where the VAULT is
/// the one transacting needs the guard, in either direction.
///
/// It folds idle balances, not just dust. removeLiquidity and a rebalance held at a
/// fraction both leave a large balance behind on purpose, so an investor path that folded
/// would let anyone holding a single share pick the price at which the vault bought back
/// in. Both investor paths therefore collect without folding, and the balance waits for a
/// curator call that is guarded and deliberately timed.
///
/// The fold happens at the guard's price or not at all: _increaseLiquidity refuses any move
/// since the guard, _collect's included; see PriceMoved.
/// @param fractionBps The share of the vault's TOTAL capital to leave deployed, in basis points
/// — the same quantity rebalance takes, measured the same way.
///
/// Measuring it against the idle balance instead is the defect this replaced,
/// and it was not a small one: the fraction then moved the deployed share from
/// d to d + f(1-d) on every call, so a vault held at 48% reached 96% after
/// eight compounds with no fees accruing at all. Worse, no argument could have
/// prevented it — the value that would have held the share steady depends on
/// fees collected inside this function, after the argument is already fixed,
/// and the position manager's tokensOwed is stale until the position is
/// touched, so it was not computable off-chain either.
///
/// Measured against total capital it is idempotent, exactly as it is on
/// rebalance: calling compound twice with the same fraction folds fees the
/// first time and does nothing the second.
/// @param sqrtPriceX96 The price compound's guard checked.
function _compound(uint16 fractionBps, uint160 sqrtPriceX96) internal returns (uint128 added) {
uint256 tokenId = activeTokenId;
if (tokenId == 0) return 0;
(uint256 fees0, uint256 fees1) = _collect(tokenId, type(uint128).max, type(uint128).max);
{
// The order's fees are the vault's like any other, so they are collected and folded with
// the rest. The order itself stays where it is: a working order is not idle.
(uint256 orderFees0, uint256 orderFees1) = _collectRangedOrder();
fees0 += orderFees0;
fees1 += orderFees1;
}
(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity) = _positionRange(tokenId);
// The target is a share of everything the vault holds, so the position's own value has to be
// counted alongside the idle balance and the ranged order. All three are converted to the
// one unit that is comparable across them — the liquidity this range could fund — and the
// fold is whatever closes the gap. Collecting first is what makes the idle balance complete
// at this point. The order counts toward the target but is never folded: only idle is.
uint128 capital;
{
(uint256 held0, uint256 held1) =
UniswapV3VaultMath.amountsForLiquidity(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, liquidity, false);
(uint256 outside0, uint256 outside1) = _idleAndOrder(false, sqrtPriceX96);
capital = UniswapV3VaultMath.mintableLiquidity(
sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, held0 + outside0, held1 + outside1
);
}
uint128 wanted = uint128(UniswapV3VaultMath.fractionOf(capital, fractionBps));
// Already at or above the target: fold nothing. This is what makes a repeated call a no-op
// rather than a ratchet, and it is also the ordinary outcome of compounding a vault that is
// already fully deployed and has earned nothing since.
if (wanted <= liquidity) {
if (fees0 != 0 || fees1 != 0) emit Compounded(tokenId, fees0, fees1, 0, 0, 0);
return 0;
}
(uint128 planned, uint256 need0, uint256 need1) = UniswapV3VaultMath.liquidityPlan(
sqrtPriceX96,
sqrtRatioAX96,
sqrtRatioBX96,
wanted - liquidity,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
// Clipping can leave amounts that fund no liquidity while the range still straddles the
// price. A ranged order holding the binding token makes that ordinary, since it counts toward
// the target but cannot be folded, and the pool refuses a mint of zero liquidity with no data.
// Nothing to fold is a normal outcome here, not a failure.
// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_compound_returnsZeroWhenAnOrderHoldsAllTheIdleOfTheBindingSide
if (planned == 0) {
if (fees0 != 0 || fees1 != 0) emit Compounded(tokenId, fees0, fees1, 0, 0, 0);
return 0;
}
uint256 used0;
uint256 used1;
(added, used0, used1) = _increaseLiquidity(tokenId, need0, need1, sqrtPriceX96);
emit Compounded(tokenId, fees0, fees1, added, used0, used1);
}
/// @notice Replaces the vault's position with one in a new range.
/// @dev The unwind is what makes the fraction mean what it says. By the time the mint runs,
/// the old position's principal and its uncollected fees are both sitting in the vault's
/// token balances alongside anything that was already idle, and so is everything a live
/// ranged order held, so the two numbers the mint scales are the vault's entire capital —
/// there is no third pot the fraction misses.
/// @param priceLower Lower bound of the new range.
/// @param priceUpper Upper bound of the new range.
/// @param fractionBps Share of the fundable maximum to deploy, in basis points.
/// @param maxSlippageBps The caller's price tolerance, in basis points.
/// @return tokenId The new position NFT id.
/// @return liquidity Liquidity minted.
/// @return amount0 Token0 consumed by the mint.
/// @return amount1 Token1 consumed by the mint.
function _rebalance(uint256 priceLower, uint256 priceUpper, uint16 fractionBps, uint16 maxSlippageBps)
internal
returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)
{
// Checked once, before the unwind, and the mint happens at that price or not at all:
// _mintPosition refuses any move since, the unwind's included; see PriceMoved.
uint160 sqrtPriceX96 = _checkSlippage(maxSlippageBps);
(int24 tickLower, int24 tickUpper) = _priceRangeToTicks(priceLower, priceUpper);
uint256 oldTokenId = activeTokenId;
if (oldTokenId != 0) _unwind(oldTokenId);
uint256 orderId = _rangedOrderTokenId;
if (orderId != 0) _unwindRangedOrder(orderId);
if (token0.balanceOf(address(this)) == 0 && token1.balanceOf(address(this)) == 0) {
revert NothingToRebalance();
}
(tokenId, liquidity, amount0, amount1) = _mintFraction(tickLower, tickUpper, fractionBps, sqrtPriceX96);
_bootstrapShares(liquidity);
emit Rebalanced(
oldTokenId,
tokenId,
fractionBps,
liquidity,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
}
/// @notice Mints a chosen share of the largest position the vault's balances could fund.
/// @dev Plans at the price the guard checked; _mintPosition refuses the mint if the pool has
/// moved since.
/// @param tickLower Lower tick boundary.
/// @param tickUpper Upper tick boundary.
/// @param fractionBps Share of the fundable maximum to deploy, in basis points. Applied by
/// scaling both balances, which is exactly a share of the liquidity because
/// mintableLiquidity is homogeneous of degree one in the amounts.
/// @param sqrtPriceX96 The price the guard checked.
/// @return tokenId The new position NFT id.
/// @return liquidity Liquidity minted.
/// @return amount0 Token0 consumed.
/// @return amount1 Token1 consumed.
function _mintFraction(int24 tickLower, int24 tickUpper, uint16 fractionBps, uint160 sqrtPriceX96)
internal
returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)
{
uint256 need0;
uint256 need1;
{
(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96) = UniswapV3VaultMath.sqrtRatiosForTicks(tickLower, tickUpper);
(liquidity, need0, need1) = UniswapV3VaultMath.positionPlan(
sqrtPriceX96,
sqrtRatioAX96,
sqrtRatioBX96,
UniswapV3VaultMath.fractionOf(token0.balanceOf(address(this)), fractionBps),
UniswapV3VaultMath.fractionOf(token1.balanceOf(address(this)), fractionBps)
);
}
if (liquidity == 0) revert NothingToRebalance();
(tokenId, liquidity, amount0, amount1) = _mintPosition(tickLower, tickUpper, need0, need1, sqrtPriceX96);
}
/// @notice Closes the vault's position and burns its NFT, leaving its contents idle in the vault.
/// @param tokenId The position NFT id.
/// @return amount0 Token0 returned to the vault.
/// @return amount1 Token1 returned to the vault.
function _unwind(uint256 tokenId) internal returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = _burnPosition(tokenId);
activeTokenId = 0;
emit PositionUnwound(tokenId, amount0, amount1);
}
/// @notice Closes the ranged order and burns its NFT, leaving its contents idle in the vault.
/// @param tokenId The order's NFT id.
/// @return amount0 Token0 returned to the vault, principal and fees combined.
/// @return amount1 Token1 returned to the vault, principal and fees combined.
function _unwindRangedOrder(uint256 tokenId) internal returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = _burnPosition(tokenId);
_rangedOrderTokenId = 0;
emit RangedOrderUnwound(tokenId, amount0, amount1);
}
/// @notice Withdraws all of an NFT's liquidity and everything it is owed, then burns it.
/// @param tokenId The NFT id.
/// @return amount0 Token0 returned to the vault, principal and fees combined.
/// @return amount1 Token1 returned to the vault, principal and fees combined.
function _burnPosition(uint256 tokenId) internal returns (uint256 amount0, uint256 amount1) {
(,, uint128 liquidity,,) = _position(tokenId);
if (liquidity != 0) _decreaseLiquidity(tokenId, liquidity);
(amount0, amount1) = _collect(tokenId, type(uint128).max, type(uint128).max);
positionManager.burn(tokenId);
}
/// @notice Mints the vault's position and records it as the active one.
/// @param tickLower Lower tick boundary.
/// @param tickUpper Upper tick boundary.
/// @param need0 Token0 to offer.
/// @param need1 Token1 to offer.
/// @param sqrtPriceX96 The price the guard checked and the plan used.
/// @return tokenId The new position NFT id.
/// @return liquidity Liquidity minted.
/// @return amount0 Token0 consumed.
/// @return amount1 Token1 consumed.
function _mintPosition(int24 tickLower, int24 tickUpper, uint256 need0, uint256 need1, uint160 sqrtPriceX96)
internal
returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)
{
(tokenId, liquidity, amount0, amount1) = _mintLiquidity(tickLower, tickUpper, need0, need1, sqrtPriceX96);
activeTokenId = tokenId;
emit PositionCreated(tokenId, tickLower, tickUpper, liquidity, amount0, amount1);
}
/// @notice Mints a position NFT to the vault. The caller records what it is for.
/// @param tickLower Lower tick boundary.
/// @param tickUpper Upper tick boundary.
/// @dev The position manager's amount0Min/amount1Min sit at zero, and that is not a gap in
/// slippage protection. Those minimums catch the price moving between a transaction being
/// signed and being mined; need0 and need1 were derived in THIS transaction, so a minimum
/// derived from them would compare the price against itself. What bounds the price is the
/// guard at entry, against the pool's own average and the oracle, and _requireUnmoved holds
/// the mint to the price it checked; see PriceMoved.
/// @param need0 Token0 to offer.
/// @param need1 Token1 to offer.
/// @param sqrtPriceX96 The price the guard checked and the plan used.
/// @return tokenId The new position NFT id.
/// @return liquidity Liquidity minted.
/// @return amount0 Token0 consumed.
/// @return amount1 Token1 consumed.
function _mintLiquidity(int24 tickLower, int24 tickUpper, uint256 need0, uint256 need1, uint160 sqrtPriceX96)
internal
returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)
{
_approve(token0, need0);
_approve(token1, need1);
_requireUnmoved(sqrtPriceX96);
_minting = true;
(tokenId, liquidity, amount0, amount1) = positionManager.mint(
INonfungiblePositionManager.MintParams({
token0: address(token0),
token1: address(token1),
fee: fee,
tickLower: tickLower,
tickUpper: tickUpper,
amount0Desired: need0,
amount1Desired: need1,
amount0Min: 0,
amount1Min: 0,
recipient: address(this),
deadline: block.timestamp
})
);
_minting = false;
_resetApproval(token0);
_resetApproval(token1);
}
/// @notice Withdraws owed tokens from a position.
/// @param tokenId The position NFT id.
/// @param max0 Upper bound on the token0 withdrawn.
/// @param max1 Upper bound on the token1 withdrawn.
/// @return amount0 Token0 withdrawn.
/// @return amount1 Token1 withdrawn.
function _collect(uint256 tokenId, uint128 max0, uint128 max1) internal returns (uint256 amount0, uint256 amount1) {
return positionManager.collect(
INonfungiblePositionManager.CollectParams({
tokenId: tokenId, recipient: address(this), amount0Max: max0, amount1Max: max1
})
);
}
/// @notice Burns liquidity, moving its principal into the position's owed balance.
/// @dev The position manager's minimums are zero. Where a bound applies, it is the price
/// guard at the entry of the door that led here, rebalance or redeem, which constrains
/// the price the burn converts at; a minimum computed here would come from that same
/// checked price and add nothing. redeem may waive its guard, deliberately: a redemption
/// pays a pro-rata claim on liquidity, so the price sets only the split between the two
/// tokens and never the size of the claim.
///
/// unwindPosition, unwindRangedOrder and removeLiquidity reach this with no price guard at
/// all, by design: a release at a wrong price leaves the vault better off, for the reason
/// recorded on unwindPosition.
/// @param tokenId The position NFT id.
/// @param liquidity Liquidity to burn.
/// @return amount0 Token0 released.
/// @return amount1 Token1 released.
function _decreaseLiquidity(uint256 tokenId, uint128 liquidity)
internal
returns (uint256 amount0, uint256 amount1)
{
return positionManager.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: tokenId, liquidity: liquidity, amount0Min: 0, amount1Min: 0, deadline: block.timestamp
})
);
}
/// @notice Burns liquidity and withdraws exactly the principal it released.
/// @dev Collecting exactly the released principal, rather than everything owed, is what stops
/// a partial withdrawal from also sweeping fees that belong to the remaining holders.
/// @param tokenId The position NFT id.
/// @param liquidity Liquidity to withdraw.
/// @return amount0 Token0 received.
/// @return amount1 Token1 received.
function _withdrawLiquidity(uint256 tokenId, uint128 liquidity)
internal
returns (uint256 amount0, uint256 amount1)
{
(uint256 principal0, uint256 principal1) = _decreaseLiquidity(tokenId, liquidity);
// The position manager rejects a collect for nothing, with no error data, so a decrease
// whose principal rounded away has to stop here. It is reachable: a position sitting
// wholly on one side of the price releases zero of the other token by construction, and
// the side it does hold truncates to zero for a small enough amount of liquidity. Letting
// it through would take an investor's redemption down with it.
if (principal0 == 0 && principal1 == 0) return (0, 0);
return _collect(tokenId, SafeCast.toUint128(principal0), SafeCast.toUint128(principal1));
}
/// @notice Withdraws a share count's slice of an NFT's liquidity, principal only.
/// @param tokenId The NFT id.
/// @param shares The share count being redeemed.
/// @param supply The share supply before the redemption.
/// @return liquidity Liquidity withdrawn, rounded down.
/// @return amount0 Token0 received.
/// @return amount1 Token1 received.
function _withdrawShare(uint256 tokenId, uint256 shares, uint256 supply)
internal
returns (uint128 liquidity, uint256 amount0, uint256 amount1)
{
(,, uint128 held,,) = _position(tokenId);
liquidity = UniswapV3VaultMath.liquidityForShares(held, shares, supply);
if (liquidity != 0) (amount0, amount1) = _withdrawLiquidity(tokenId, liquidity);
}
/// @notice Collects everything the ranged order is owed, when there is one.
/// @dev Touching the order is also what makes the position manager bring its fees up to date,
/// so a path that prices shares calls this before it reads the order.
/// @return amount0 Token0 collected.
/// @return amount1 Token1 collected.
function _collectRangedOrder() internal returns (uint256 amount0, uint256 amount1) {
uint256 tokenId = _rangedOrderTokenId;
if (tokenId != 0) (amount0, amount1) = _collect(tokenId, type(uint128).max, type(uint128).max);
}
/// @notice The vault's idle balances plus everything its ranged order holds.
/// @dev Everything a share is a claim on apart from the main position, as _compound values
/// it when sizing total capital, at the price its guard checked. deposit and
/// UniswapV3PositionVaultLens reach the same arithmetic through UniswapV3VaultMath
/// directly, and redeem does not read it: it pays a slice of each NFT's liquidity and of
/// the raw balances.
/// @param roundUp Whether to round the order's principal up. _compound, the one caller,
/// passes false to count the order at what it would release.
/// @param sqrtPriceX96 The price to value the order at.
/// @return amount0 Token0 idle or held by the order.
/// @return amount1 Token1 idle or held by the order.
function _idleAndOrder(bool roundUp, uint160 sqrtPriceX96)
internal
view
returns (uint256 amount0, uint256 amount1)
{
return UniswapV3VaultMath.idleAndOrder(
token0, token1, positionManager, sqrtPriceX96, address(this), _rangedOrderTokenId, roundUp
);
}
/// @notice deposit's reader: UniswapV3VaultMath.depositState for this vault, plus its supply.
/// @dev deposit passes the price its guard checked. The lens previews call the same library
/// function with the vault as holder and spot as the price; the refusals are there.
/// @param sqrtPriceX96 The price to value the ranged order at.
/// @return sqrtRatioAX96 The position's lower sqrt ratio.
/// @return sqrtRatioBX96 The position's upper sqrt ratio.
/// @return liquidity The position's current liquidity.
/// @return idle0 Token0 outside the position: idle, owed and held by the order.
/// @return idle1 Token1 outside the position: idle, owed and held by the order.
/// @return supply The current share supply.
function _depositQuoteState(uint160 sqrtPriceX96)
internal
view
returns (
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
uint256 idle0,
uint256 idle1,
uint256 supply
)
{
supply = totalSupply();
(sqrtRatioAX96, sqrtRatioBX96, liquidity, idle0, idle1) = UniswapV3VaultMath.depositState(
positionManager, sqrtPriceX96, token0, token1, address(this), activeTokenId, _rangedOrderTokenId, supply
);
}
/// @notice Adds liquidity to the active position from the vault's own balances.
/// @dev The position manager's minimums are zero, and the previous version of this comment
/// said slippage was enforced by the caller-facing function against the totals it
/// reports. compound enforced no such thing, and deposit's check is a MAXIMUM against
/// the caller's own offer rather than a minimum on the fill. The price is bounded by
/// maxSlippageBps at entry; see _mintLiquidity for why a minimum derived from the same
/// transaction's spot price would be comparing the price against itself.
///
/// Every increase, deposit's and _compound's alike, is held to the price its guard
/// checked: _requireUnmoved re-reads slot0 after the approvals, immediately before the
/// position manager; see PriceMoved. deposit also prices shares on the liquidity this
/// call actually added, so a short fill buys fewer shares rather than diluting anyone,
/// and the caller's minShares bounds how few.
/// @param tokenId The position NFT id.
/// @param need0 Token0 to offer.
/// @param need1 Token1 to offer.
/// @param sqrtPriceX96 The price the guard checked and the plan used.
/// @return liquidity Liquidity added.
/// @return amount0 Token0 consumed.
/// @return amount1 Token1 consumed.
function _increaseLiquidity(uint256 tokenId, uint256 need0, uint256 need1, uint160 sqrtPriceX96)
internal
returns (uint128 liquidity, uint256 amount0, uint256 amount1)
{
if (need0 == 0 && need1 == 0) return (0, 0, 0);
_approve(token0, need0);
_approve(token1, need1);
_requireUnmoved(sqrtPriceX96);
(liquidity, amount0, amount1) = positionManager.increaseLiquidity(
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: tokenId,
amount0Desired: need0,
amount1Desired: need1,
amount0Min: 0,
amount1Min: 0,
deadline: block.timestamp
})
);
_resetApproval(token0);
_resetApproval(token1);
}
/// @notice Reverts unless the pool's price is fair enough for a caller's own tolerance.
/// @dev An investor's bound and the vault's own both apply, and the tighter one wins, so a
/// caller can ask for more protection than the admin configured but never less.
/// @param maxSlippageBps The caller's tolerance, in basis points.
/// @return sqrtPriceX96 The pool's sqrt price, as checked. Every door that adds liquidity plans at
/// it and mints at it; see PriceMoved.
function _checkSlippage(uint16 maxSlippageBps) internal view returns (uint160 sqrtPriceX96) {
if (maxSlippageBps == 0 || maxSlippageBps > _MAX_BPS) revert InvalidArguments();
uint16 cap = maxTwapDeviationBps;
uint16 bound = maxSlippageBps < cap ? maxSlippageBps : cap;
sqrtPriceX96 = UniswapV3VaultMath.checkPriceDeviation(pool, twapPeriod, bound);
// The oracle cross-check, when one is configured, at the same bound. Both checks apply:
// the pool must agree with its own recent history AND with an external feed. Holding a
// price off for the length of the window defeats the first and not the second.
//
// Hooked here, beside the pool's own check, whose sole call site this is: every door that
// takes a tolerance reaches both through this function, and redeem's waiver skips both for
// the same reason it skips the rest: a redemption's payout is a pro-rata claim that no
// price changes.
// pinned: test/UniswapV3PositionVault.Oracle.t.sol::test_oracle_theSequencerGuardRunsWithNoPriceFeedsConfigured
// Either half is enough to be worth the call. Gating on feed0 alone made the sequencer
// check dead storage on exactly the configuration that most needs it: a chain with no
// Chainlink pair for this pool — the case the price check is documented as optional for —
// but a published uptime feed. setOracleConfig accepted that, stored it, emitted an event
// announcing it, and then never ran it.
if (oracleConfig.feed0 != address(0) || oracleConfig.sequencerUptimeFeed != address(0)) {
UniswapV3VaultMath.oracleCheck(sqrtPriceX96, priceScaleNum, priceScaleDen, bound, oracleConfig);
}
}
/// @notice Mints the opening share supply when the vault has none.
/// @dev Shares start one-to-one with liquidity. A donation cannot then be turned against the
/// next depositor the way it can in a vault that prices shares off a balance, because
/// donated tokens are claimed pro-rata by every holder rather than by whoever deposits
/// next. What that argument needs, and what the floor here supplies, is a supply large
/// enough that a deposit's floor division is not itself a way to take a fraction of the
/// deposit: the opening liquidity must be at least UniswapV3VaultMath.MIN_SHARES, and a
/// deposit priced against a supply below it is refused. The ratio itself can be driven
/// far — a redemption may leave whatever it leaves, and the vault can then be refunded —
/// but no deposit is ever priced while it has been, which is where the harm would land.
/// The mint goes through _update, which enforces the investor gate on the recipient. So
/// the CURATOR must hold INVESTOR for this to succeed, and on a vault that is not open
/// to everyone that grant is load-bearing rather than cosmetic: revoking it — a natural
/// tightening, since a curator is an operator rather than an investor — leaves
/// createPosition and the supply-zero rebalance reverting NotInvestor with no way to
/// open the first position. The deploy script grants it for this reason.
/// @param liquidity Liquidity just minted, which becomes the opening supply.
function _bootstrapShares(uint128 liquidity) internal {
if (totalSupply() != 0) return;
if (liquidity < UniswapV3VaultMath.MIN_SHARES) revert SupplyTooSmall(liquidity, UniswapV3VaultMath.MIN_SHARES);
_mint(msg.sender, liquidity);
}
/// @notice The pool's current sqrt price.
/// @return sqrtPriceX96 The pool's current sqrt price.
function _spotSqrtPrice() internal view returns (uint160 sqrtPriceX96) {
(sqrtPriceX96,,,,,,) = pool.slot0();
}
/// @notice Reverts unless the pool still sits at the price the guard checked.
/// @dev Called after the approvals and immediately before the position manager, which reads
/// slot0 itself with no call in between; see PriceMoved.
/// pinned: test/UniswapV3PositionVault.PinnedPrice.t.sol::test_createPosition_reReadsAfterTheApprovalsAndBeforeTheMint
/// pinned: test/UniswapV3PositionVault.PinnedPrice.t.sol::test_rebalance_reReadsAfterTheApprovalsAndBeforeTheMint
/// pinned: test/UniswapV3PositionVault.PinnedPrice.t.sol::test_compound_reReadsAfterTheApprovalsAndBeforeTheIncrease
/// pinned: test/UniswapV3PositionVault.PinnedPrice.t.sol::test_deposit_reReadsAfterTheApprovalsAndBeforeTheIncrease
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_createRangedOrder_refusesAMovedPrice
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_createRangedOrder_reReadsAfterTheApprovalsAndBeforeTheMint
/// @param sqrtPriceX96 The price the guard checked.
function _requireUnmoved(uint160 sqrtPriceX96) internal view {
uint160 current = _spotSqrtPrice();
if (current != sqrtPriceX96) revert PriceMoved(sqrtPriceX96, current);
}
/// @notice Reverts unless the ranged order has wholly converted out of the token it sells.
/// @dev Filled is spot at or past the band's far edge: at or above its upper sqrt ratio for a
/// sell, at or below its lower for a buy. The comparison is inclusive, so the edge counts
/// as filled: on its upper edge a sell's principal is already all token1. Comparing sqrt
/// prices is exact when the price stops exactly on the edge tick; slot0.tick is not,
/// because a price that falls onto a boundary leaves it one below, which would refuse a
/// sell sitting filled on its upper edge.
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_unwindRangedOrder_onlyIfFilledUnwindsASellSittingOnItsUpperEdge
///
/// Principal is not the test: decreaseLiquidity rounds it down, so a dust order releases
/// none of the token it sells while spot is still short of the edge.
/// pinned: test/UniswapV3PositionVault.RangedOrder.t.sol::test_unwindRangedOrder_onlyIfFilledRefusesADustSellShortOfItsEdge
/// @param tokenId The order's NFT id.
function _requireRangedOrderFilled(uint256 tokenId) internal view {
(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity) = _positionRange(tokenId);
// Redemptions have taken all of it: nothing is left to sell, so there is nothing to fill.
if (liquidity == 0) return;
uint160 sqrtPriceX96 = _spotSqrtPrice();
bool sell = _rangedOrderZeroForOne;
uint160 edgeSqrtPriceX96 = sell ? sqrtRatioBX96 : sqrtRatioAX96;
if (sell ? sqrtPriceX96 < edgeSqrtPriceX96 : sqrtPriceX96 > edgeSqrtPriceX96) {
revert RangedOrderNotFilled(sqrtPriceX96, edgeSqrtPriceX96);
}
}
/// @notice Snaps a human price range onto the pool's usable ticks.
/// @dev The lower bound rounds down and the upper bound rounds up, so the resulting range
/// contains the prices that were asked for, except a bound beyond the pool's outermost
/// usable tick, which is clamped to it.
/// pinned: test/UniswapV3PositionVault.Math.t.sol::test_priceRangeToTicks_coversTheRequestedPrices
/// @param priceLower Lower bound, as a 1e18-scaled human price.
/// @param priceUpper Upper bound, as a 1e18-scaled human price.
/// @return tickLower The snapped lower tick.
/// @return tickUpper The snapped upper tick.
function _priceRangeToTicks(uint256 priceLower, uint256 priceUpper)
internal
view
returns (int24 tickLower, int24 tickUpper)
{
return UniswapV3VaultMath.priceRangeToTicks(priceLower, priceUpper, tickSpacing, priceScaleNum, priceScaleDen);
}
/// @notice A position's range bounds and liquidity, without the pool price.
/// @dev For the callers that price at the guard's checked price or not at all; reading slot0
/// for them would be a call whose answer is thrown away.
/// @param tokenId The position NFT id.
/// @return sqrtRatioAX96 The position's lower sqrt ratio.
/// @return sqrtRatioBX96 The position's upper sqrt ratio.
/// @return liquidity The position's liquidity.
function _positionRange(uint256 tokenId)
internal
view
returns (uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity)
{
(int24 tickLower, int24 tickUpper, uint128 held,,) = _position(tokenId);
liquidity = held;
(sqrtRatioAX96, sqrtRatioBX96) = UniswapV3VaultMath.sqrtRatiosForTicks(tickLower, tickUpper);
}
/// @notice The fields of a position the vault cares about.
/// @dev The position manager returns twelve values; decoding them in one place keeps that
/// decoding out of every caller.
/// @param tokenId The position NFT id.
/// @return tickLower Lower tick boundary.
/// @return tickUpper Upper tick boundary.
/// @return liquidity Liquidity currently held.
/// @return tokensOwed0 Token0 collectable from the position.
/// @return tokensOwed1 Token1 collectable from the position.
function _position(uint256 tokenId)
internal
view
returns (int24 tickLower, int24 tickUpper, uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1)
{
(,,,,, tickLower, tickUpper, liquidity,,, tokensOwed0, tokensOwed1) = positionManager.positions(tokenId);
}
/// @notice Reverts unless the vault already holds the required amount of a token.
/// @param token The token to check.
/// @param required The amount needed.
function _requireIdle(IERC20 token, uint256 required) internal view {
uint256 available = token.balanceOf(address(this));
if (required > available) revert InsufficientIdleBalance(address(token), required, available);
}
/// @notice Approves the position manager for an exact amount.
/// @param token The token to approve.
/// @param amount The allowance to set.
function _approve(IERC20 token, uint256 amount) internal {
if (amount != 0) token.forceApprove(address(positionManager), amount);
}
/// @notice Clears the position manager's allowance.
/// @dev Called after every position manager interaction so no standing allowance is left.
/// @param token The token whose allowance to clear.
function _resetApproval(IERC20 token) internal {
if (token.allowance(address(this), address(positionManager)) != 0) {
token.forceApprove(address(positionManager), 0);
}
}
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"src/UniswapV3PositionVault.sol": {
"UniswapV3VaultMath": "0x8c7f62536d7c0fdea0a6fac4a175158ccb22f084"
}
},
"optimizer": {
"runs": 60,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.