Verified contractExactMIT
TaxHook
Address0x2ce50a64de46a3c335f55ea240b7fa235e6ba0cc
- Balance
0 ETH
- Transactions
10
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,173,068
- Creation transaction
- 0xce9ba67be7…33b37e2f30
14 files
- src/TaxHook.solmain52.21 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol216 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13.96 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- src/interfaces/IUniswapV4Minimal.sol5.87 KB
- src/libraries/BitMath.sol2.61 KB
- src/libraries/CustomRevert.sol5.17 KB
- src/libraries/SniperRate.sol5.41 KB
- src/libraries/TickMath.sol12.8 KB
src/TaxHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {PoolKey, IPoolManagerMinimal} from "./interfaces/IUniswapV4Minimal.sol";
import {SniperRate} from "./libraries/SniperRate.sol";
import {TickMath} from "./libraries/TickMath.sol";
interface ILiquidityLockerMinimal {
function increaseLiquidity(
address pool,
address tokenA,
uint256 amountA,
address tokenB,
uint256 amountB
) external;
function positionOf(address pool) external view returns (uint256);
}
interface IOwned {
function launchConfig() external view returns (address);
function owner() external view returns (address);
function guardian() external view returns (address);
function platformTreasury() external view returns (address);
}
interface IFeeRouting {
function feeSplitter() external view returns (address);
function creatorRecipient(address token) external view returns (address);
function setLimitExempt(address account, bool exempt) external;
}
interface IReplacementVault {
function poolId() external view returns (bytes32);
function token() external view returns (address);
function taxHook() external view returns (address);
function setStakingPaused(bool paused) external;
}
interface ICompoundingAdapter {
/// @dev How much of a single-asset balance to sell so the rest can be
/// paired, and what that sale is worth at the pool's current price.
function compoundSplit(uint256 tokenId, address tokenIn, uint256 amountIn)
external
view
returns (uint256 sellAmount, uint256 expectedOut);
}
/**
* The tax on a taxed launch, charged by Uniswap V4 on every swap.
*
* A hook rather than a transfer tax: the factory seeds the pool with the whole
* supply and V4 settles on exact amounts, so a token that delivers less than
* it promises breaks the launch and every quote after it. Wallet-to-wallet
* transfers are therefore untaxed; only trades are.
*
* The tax is denominated in the QUOTE asset (USDC, WETH), never the launched
* token. A buyer pays it out of the quote going in, a seller out of the quote
* coming out. Every one of the four swap kinds is charged in exactly one
* callback: where the quote is the specified currency in `beforeSwap`, where
* it is the unspecified one in `afterSwap`.
*
* Every trade pays a standard fee of 1%, charged here rather than as a pool
* fee: half to the platform, half straight to the creator's payee. The pool is
* opened at a zero LP fee, so no liquidity anyone else adds to it earns a
* share of that 1%. On top, the creator picks 0% to 9% for buys and sells and
* all of it is theirs; a trader pays 1% to 10% in all. The creator's tax is split
* between themselves, the pool, stakers and the burn. Creator, platform and
* stakers are paid in quote. The pool's share is paired and added to the
* locked position. The burn share waits as quote until someone with a price
* converts it: the token is bought back and destroyed, so a burn is always a
* burn of the launched token and never of the quote.
*
* Nothing is paid out during a swap. The hook books counters; payout, compound
* and burn are separate calls, so a destination that cannot receive can never
* fail a trade.
*
* Who is who:
* - The launcher: whoever launched the token through the platform. An outside
* party the protocol has no control over. Their share is paid wherever
* FeeSplitter currently sends their pool fee (`creatorPayee`), with
* `creator`, the launch-time recipient, as the fallback; `taxAdmin` is the
* key they launched from. They are paid the creator share
* and, on a dynamic launch, may lower the rates and change the split within
* the caps. Nothing else: no compound, no burn, no fail-open.
* - The protocol: LaunchConfig's owner (the timelock), its guardian (the
* Safe), its platform treasury, and the keeper the owner sets here. Only
* these convert the booked liquidity and burn shares or stop a pool's tax.
* - `protocolDeployer`: the key that deployed this hook. It wires the factory
* and the adapter once each and has no power after that.
*/
contract TaxHook {
using SafeERC20 for IERC20;
uint16 internal constant BPS_DENOMINATOR = 10_000;
/// @notice The platform's half of the standard fee, in basis points of the
/// trade, charged on every swap whatever the creator set.
uint16 public constant PLATFORM_BPS = 50;
/// @notice The creator's half of the standard fee. Booked to the creator's
/// payee directly, never through the four-way split, so a creator
/// earns it at a 0% tax and however their tax is routed.
uint16 public constant CREATOR_BASE_BPS = 50;
/// @notice The standard fee: what every trade pays before the creator's
/// tax. Charged by this hook, not by the pool, which is opened at a
/// zero LP fee for exactly that reason.
uint16 public constant STANDARD_FEE_BPS = PLATFORM_BPS + CREATOR_BASE_BPS;
/// @notice The most a creator may charge on top of the standard fee.
uint16 public constant MAX_CREATOR_BPS = 900;
/// @dev Sanity floor on the compound's internal buy, against spot. Not
/// sandwich protection: spot is what a sandwich moves. The caller's
/// own off-chain floor is the protection; this catches the absurd.
uint16 internal constant COMPOUND_MIN_OUT_BPS = 7_000;
/// @notice How far one compound or burn may move the pool's sqrt price,
/// about 2% on price. A larger balance converts over several
/// calls; what a call cannot spend stays booked.
uint16 public constant MAX_STEP_SQRT_BPS = 100;
/// @dev `_pools` in the PoolManager's storage; slot0's low 160 bits are
/// the sqrt price. Same slot the V4 adapter reads.
uint256 private constant POOLS_SLOT = 6;
address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
IPoolManagerMinimal public immutable poolManager;
address public immutable liquidityLocker;
/// @dev `buyBps`/`sellBps` are the creator's own rates; the standard fee
/// (STANDARD_FEE_BPS) is added at charge time so it cannot drift per pool. The
/// four shares are proportions of the creator's take and sum to 10,000.
struct Tax {
uint16 buyBps;
uint16 sellBps;
uint16 creatorShareBps;
uint16 liquidityShareBps;
uint16 dividendShareBps;
uint16 burnShareBps;
/// @dev Sniper tax: for `sniperDuration` seconds after `startedAt`
/// the trader's total opens at 80% and falls in a straight line
/// to the configured rate. Written once; a restartable schedule
/// is a rug button.
uint40 startedAt;
uint32 sniperDuration;
address token;
address creator;
/// @dev Control key for a dynamic launch, separate from the payout
/// address. Set once, never moved.
address taxAdmin;
/// @dev The locker's handle for this pool.
address pool;
/// @dev The pool's other currency, which is what the tax is charged in.
address quote;
address dividendVault;
bool configured;
/// @dev Whether `taxAdmin` may lower the rates and change the split
/// later. Never past the caps a static launch has. Written once.
bool dynamic;
}
/// @dev Raw storage: a landed split is applied on the next swap. Read
/// `taxConfig` / `currentRates` instead.
mapping(bytes32 poolId => Tax) public taxOf;
struct PendingSplit {
uint16 creatorShareBps;
uint16 liquidityShareBps;
uint16 dividendShareBps;
uint16 burnShareBps;
/// @dev Zero means nothing is pending.
uint40 effectiveAt;
}
mapping(bytes32 poolId => PendingSplit) public pendingSplitOf;
uint32 public constant SPLIT_CHANGE_DELAY = 24 hours;
/// @notice Charged and not yet paid out, per pool, in the pool's quote.
mapping(bytes32 poolId => uint256) public pendingCreator;
mapping(bytes32 poolId => uint256) public pendingLiquidity;
mapping(bytes32 poolId => uint256) public pendingDividend;
/// @notice Quote waiting to be converted into the token and destroyed.
mapping(bytes32 poolId => uint256) public pendingBurn;
mapping(bytes32 poolId => uint256) public pendingPlatform;
/// @notice Launched token left over from a compound's approximate split,
/// spent by the next one.
mapping(bytes32 poolId => uint256) public pendingToken;
/// @dev Write-once by `protocolDeployer`. Set after construction because the hook's
/// address is mined from its constructor arguments and the factory
/// needs the hook first.
address public tokenFactory;
/// @dev An explicit argument, not `msg.sender`: CREATE2 broadcasts route
/// through the deterministic deployer, so the sender is not the key.
address public immutable protocolDeployer;
/// @dev Consulted only for the compound's split. Write-once by `protocolDeployer`.
address public ammAdapter;
/// @notice The protocol's bot for compound and burn. Set by LaunchConfig's owner.
address public keeper;
event TaxConfigured(bytes32 indexed poolId, address indexed token, uint16 buyBps, uint16 sellBps);
event TaxUpdated(
bytes32 indexed poolId,
uint16 buyBps,
uint16 sellBps,
uint16 creatorShareBps,
uint16 liquidityShareBps,
uint16 dividendShareBps,
uint16 burnShareBps
);
event TaxScheduleCancelled(bytes32 indexed poolId);
event TaxSplitApplied(
bytes32 indexed poolId,
uint16 creatorShareBps,
uint16 liquidityShareBps,
uint16 dividendShareBps,
uint16 burnShareBps
);
event TaxSplitScheduled(
bytes32 indexed poolId,
uint16 creatorShareBps,
uint16 liquidityShareBps,
uint16 dividendShareBps,
uint16 burnShareBps,
uint40 effectiveAt
);
/// @dev Booked as an ERC-6909 claim on the quote; redeemed by the next
/// payout, compound or burn.
event TaxClaimed(bytes32 indexed poolId, uint256 amount);
/// @dev `amount` is in the pool's quote.
event TaxCharged(bytes32 indexed poolId, bool isBuy, uint256 amount);
event Distributed(bytes32 indexed poolId, address indexed to, uint256 amount);
event PayoutFailed(bytes32 indexed poolId, address indexed to, uint256 amount);
event Burned(bytes32 indexed poolId, uint256 quoteSpent, uint256 tokensBurned);
event DividendVaultMigrated(bytes32 indexed poolId, address indexed from, address indexed to);
event FailedOpen(bytes32 indexed poolId);
event AllFailedOpen();
event BookedReleased(bytes32 indexed poolId, uint256 quote, uint256 tokensBurned);
event KeeperSet(address indexed keeper);
error NotPoolManager();
error NotTokenFactory();
error AlreadyConfigured();
error PoolNotInitialized();
error NotConfigured();
error BadTax();
error TaxIsStatic();
error TaxCanOnlyFall();
error NotTaxAdmin();
/// @dev The pool filled less than the amount the tax was computed on.
error PartialFill();
error DeltaOverflow();
/// @dev compound/burn by anyone but the platform treasury or the keeper.
error NotCompounder();
error NotAdmin();
/// @dev compound/burn without a priced floor.
error NoFloor();
error CompoundInProgress();
error NotRedeeming();
error CompoundSlippage(uint256 out, uint256 minOut);
error CompoundNoop();
/// @dev A second pool wearing this hook on a token it already taxes.
error SiblingPool();
error NotLaunchAdapter();
error ReleaseNotDue();
error TaxedLaunchesStopped();
/// @dev A second compound or burn on one pool in one block.
error OncePerBlock();
constructor(
IPoolManagerMinimal poolManager_,
address liquidityLocker_,
address protocolDeployer_
) {
if (address(poolManager_) == address(0)) revert BadTax();
if (liquidityLocker_ == address(0)) revert BadTax();
if (protocolDeployer_ == address(0)) revert BadTax();
poolManager = poolManager_;
liquidityLocker = liquidityLocker_;
protocolDeployer = protocolDeployer_;
}
/// @notice LaunchConfig's treasury, read at payout so a rotation there
/// moves the platform's share and its compound rights with it.
function platformTreasury() public view returns (address) {
return IOwned(IOwned(tokenFactory).launchConfig()).platformTreasury();
}
function setTokenFactory(address factory) external {
if (msg.sender != protocolDeployer) revert NotAdmin();
if (tokenFactory != address(0)) revert AlreadyConfigured();
if (factory == address(0)) revert BadTax();
tokenFactory = factory;
}
function setAmmAdapter(address adapter) external {
if (msg.sender != protocolDeployer) revert NotAdmin();
if (ammAdapter != address(0)) revert AlreadyConfigured();
if (adapter == address(0)) revert BadTax();
ammAdapter = adapter;
}
enum UnlockMode { None, Redeem, Swap }
UnlockMode private _unlockMode;
/// @dev A compound or burn in flight; the counters it reads are stale
/// until it writes them back.
bool private _busy;
mapping(address token => bytes32 poolId) public canonicalPoolOf;
/// @notice The block of a pool's last compound or burn. MAX_STEP_SQRT_BPS
/// bounds one conversion; a block that held many would have no bound.
mapping(bytes32 poolId => uint256) public lastConversionBlock;
/// @notice A pool that trades untaxed for good. For a bug in the swap
/// path: a pool's hook and its locked liquidity can never be
/// replaced, so a swap that reverts would otherwise be a pool that
/// can never trade again.
mapping(bytes32 poolId => bool) public failedOpen;
/// @notice Every pool on this hook, present and future, trades untaxed.
bool public allFailedOpen;
mapping(bytes32 poolId => uint40) public failedOpenAt;
uint40 public allFailedOpenAt;
/// @notice How long after failing open keepers keep the chance to compound
/// and burn before the booked shares can be released.
uint32 public constant RELEASE_DELAY = 7 days;
mapping(bytes32 poolId => address[]) private _retiredVaults;
modifier onlyPoolManager() {
if (msg.sender != address(poolManager)) revert NotPoolManager();
_;
}
function poolId(PoolKey memory key) public pure returns (bytes32) {
return keccak256(abi.encode(key));
}
/// @notice Records a pool's tax. Once, at launch, by the factory.
function configure(
PoolKey memory key,
address token,
address creator,
uint16 buyBps,
uint16 sellBps,
uint16 creatorShareBps,
uint16 liquidityShareBps,
uint16 dividendShareBps,
uint16 burnShareBps,
address pool,
address dividendVault,
address quote,
uint32 sniperDuration,
address taxAdmin,
bool dynamic
) external {
if (msg.sender != tokenFactory) revert NotTokenFactory();
// A launch would promise a tax this hook will never charge.
if (allFailedOpen) revert TaxedLaunchesStopped();
bytes32 id = poolId(key);
if (taxOf[id].configured) revert AlreadyConfigured();
if (token == address(0) || creator == address(0)) revert BadTax();
// The key must name this hook and the pair must be exactly token/quote,
// or a factory bug taxes the wrong currency of the wrong pool. Any LP
// fee would be charged on top of the standard fee this hook takes.
if (key.fee != 0 || key.hooks != address(this)) revert BadTax();
if (token != key.currency0 && token != key.currency1) revert BadTax();
address other = token == key.currency0 ? key.currency1 : key.currency0;
if (quote != other || quote == token || quote == address(0)) revert BadTax();
if (dynamic && taxAdmin == address(0)) revert BadTax();
// A key that drifted from the adapter's would tax a pool nobody trades.
if (_sqrtPrice(id) == 0) revert PoolNotInitialized();
_requireValidTax(
buyBps,
sellBps,
creatorShareBps,
liquidityShareBps,
dividendShareBps,
burnShareBps,
pool != address(0),
dividendVault != address(0),
sniperDuration
);
canonicalPoolOf[token] = id;
taxOf[id] = Tax({
buyBps: buyBps,
sellBps: sellBps,
creatorShareBps: creatorShareBps,
liquidityShareBps: liquidityShareBps,
dividendShareBps: dividendShareBps,
burnShareBps: burnShareBps,
startedAt: uint40(block.timestamp),
sniperDuration: sniperDuration,
token: token,
creator: creator,
taxAdmin: taxAdmin,
pool: pool,
quote: quote,
dividendVault: dividendVault,
configured: true,
dynamic: dynamic
});
emit TaxConfigured(id, token, buyBps, sellBps);
}
/**
* Charges where the quote is the specified currency: an exact-input BUY
* (quote in) and an exact-output SELL (quote out). The other two kinds
* are charged in `afterSwap`. Both kinds must be charged: the pool is
* public and a router picks whichever door is cheaper.
*
* The returned delta is packed, specified amount in the high 128 bits.
* Positive is owed to the hook: on exact-input it shrinks what the pool
* swaps, on exact-output it grows what the pool must produce.
*/
function beforeSwap(
address,
PoolKey calldata key,
IPoolManagerMinimal.SwapParams calldata params,
bytes calldata
) external onlyPoolManager returns (bytes4, int256, uint24) {
bytes32 id = poolId(key);
if (!taxOf[id].configured || _isFailedOpen(id)) return (this.beforeSwap.selector, 0, 0);
_settlePendingSplit(id);
Tax memory tax = taxOf[id];
bool buying = params.zeroForOne != (key.currency0 == tax.token);
bool exactInput = params.amountSpecified < 0;
uint256 amount;
if (buying && exactInput) {
amount = _charge(id, tax, uint256(-params.amountSpecified), _effectiveCreatorBps(tax, tax.buyBps), true);
} else if (!buying && !exactInput) {
// The trader asked for `net` quote; the rate is on the gross, so
// the pool is asked for the gross and the tax is the difference.
uint16 creatorBps = _effectiveCreatorBps(tax, tax.sellBps);
uint256 gross = _grossUp(uint256(params.amountSpecified), creatorBps);
amount = _charge(id, tax, gross, creatorBps, false);
} else {
return (this.beforeSwap.selector, 0, 0);
}
if (amount == 0) return (this.beforeSwap.selector, 0, 0);
_collect(id, tax.quote, amount);
return (this.beforeSwap.selector, int256(_delta(amount)) << 128, 0);
}
/**
* Charges where the quote is the unspecified currency: an exact-input
* SELL (quote out) and an exact-output BUY (quote in). A positive return
* is owed to the hook on the unspecified side: a seller receives that
* much less, a buyer pays that much more.
*/
function afterSwap(
address,
PoolKey calldata key,
IPoolManagerMinimal.SwapParams calldata params,
int256 delta,
bytes calldata
) external onlyPoolManager returns (bytes4, int128) {
bytes32 id = poolId(key);
if (!taxOf[id].configured || _isFailedOpen(id)) return (this.afterSwap.selector, 0);
_settlePendingSplit(id);
Tax memory tax = taxOf[id];
bool tokenIsCurrency0 = key.currency0 == tax.token;
bool buying = params.zeroForOne != tokenIsCurrency0;
bool exactInput = params.amountSpecified < 0;
// The trader's side of the trade in the quote.
int128 quoteDelta = tokenIsCurrency0
? int128(int256(uint256(delta) & type(uint128).max))
: int128(delta >> 128);
uint256 amount;
if (!buying && exactInput) {
if (quoteDelta <= 0) return (this.afterSwap.selector, 0);
amount = _charge(id, tax, uint128(quoteDelta), _effectiveCreatorBps(tax, tax.sellBps), false);
} else if (buying && !exactInput) {
if (quoteDelta >= 0) return (this.afterSwap.selector, 0);
uint16 creatorBps = _effectiveCreatorBps(tax, tax.buyBps);
uint256 gross = _grossUp(uint256(uint128(-quoteDelta)), creatorBps);
amount = _charge(id, tax, gross, creatorBps, true);
} else {
_requireFullFill(tax, params, quoteDelta, buying);
return (this.afterSwap.selector, 0);
}
if (amount == 0) return (this.afterSwap.selector, 0);
_collect(id, tax.quote, amount);
return (this.afterSwap.selector, _delta(amount));
}
/// @dev A hook delta is an int128: checked, never a silent wrap (audit
/// 2026-10-03 HK-4; unreachable with real supplies, as V4 itself
/// bounds a swap's amounts to int128).
function _delta(uint256 amount) private pure returns (int128) {
if (amount > uint128(type(int128).max)) revert DeltaOverflow();
return int128(int256(amount));
}
/// @dev Never `take` mid-swap: the trader has not settled yet and a router
/// that pays before swapping would be short by the tax. A claim moves
/// no balance and is redeemed by the next entry point.
function _collect(bytes32 id, address currency, uint256 amount) private {
poolManager.mint(address(this), uint256(uint160(currency)), amount);
emit TaxClaimed(id, amount);
}
function _redeem(address currency) private {
uint256 claims = poolManager.balanceOf(address(this), uint256(uint160(currency)));
if (claims == 0) return;
_unlockMode = UnlockMode.Redeem;
poolManager.unlock(abi.encode(UnlockMode.Redeem, abi.encode(currency, claims)));
_unlockMode = UnlockMode.None;
}
/// @notice Redeems the booked claims on their own. Reverts inside a V4
/// unlock, so a caller that will pay out from within one runs this first.
function redeem(PoolKey memory key) external {
if (_busy) revert CompoundInProgress();
Tax storage tax = taxOf[poolId(key)];
if (!tax.configured) revert NotConfigured();
_redeem(tax.quote);
}
/// @dev The hook's own exact-input swap on its own pool. Proceeds are the
/// swap's delta, not an adapter's report.
function _swapExactIn(PoolKey memory key, address tokenIn, uint256 amountIn, uint256 minOut)
private
returns (uint256 out, uint256 spent)
{
_unlockMode = UnlockMode.Swap;
bytes memory ret = poolManager.unlock(abi.encode(UnlockMode.Swap, abi.encode(key, tokenIn, amountIn)));
_unlockMode = UnlockMode.None;
(out, spent) = abi.decode(ret, (uint256, uint256));
// `minOut` is for all of `amountIn`; a step that stopped at its price
// limit is held to the same rate on what it spent.
if (out * amountIn < minOut * spent) revert CompoundSlippage(out, (minOut * spent) / amountIn);
}
/// @dev At most MAX_STEP_SQRT_BPS from the current sqrt price, in the
/// direction the hook's buy moves it.
function _stepLimit(PoolKey memory key, bool zeroForOne) private view returns (uint160) {
uint256 sqrtP = _sqrtPrice(poolId(key));
if (zeroForOne) {
uint256 lo = (sqrtP * (BPS_DENOMINATOR - MAX_STEP_SQRT_BPS)) / BPS_DENOMINATOR;
return lo <= TickMath.MIN_SQRT_PRICE ? TickMath.MIN_SQRT_PRICE + 1 : uint160(lo);
}
uint256 hi = (sqrtP * (BPS_DENOMINATOR + MAX_STEP_SQRT_BPS)) / BPS_DENOMINATOR;
return hi >= TickMath.MAX_SQRT_PRICE ? TickMath.MAX_SQRT_PRICE - 1 : uint160(hi);
}
/// @dev slot0's low 160 bits; zero until the pool is initialised.
function _sqrtPrice(bytes32 id) private view returns (uint160) {
return uint160(uint256(poolManager.extsload(keccak256(abi.encodePacked(id, POOLS_SLOT)))));
}
function unlockCallback(bytes calldata data) external onlyPoolManager returns (bytes memory) {
(UnlockMode mode, bytes memory inner) = abi.decode(data, (UnlockMode, bytes));
if (mode != _unlockMode || mode == UnlockMode.None) revert NotRedeeming();
if (mode == UnlockMode.Redeem) {
(address claimed, uint256 amount) = abi.decode(inner, (address, uint256));
poolManager.burn(address(this), uint256(uint160(claimed)), amount);
poolManager.take(claimed, address(this), amount);
return "";
}
(PoolKey memory key, address tokenIn, uint256 amountIn) = abi.decode(inner, (PoolKey, address, uint256));
bool zeroForOne = key.currency0 == tokenIn;
address tokenOut = zeroForOne ? key.currency1 : key.currency0;
int256 delta = poolManager.swap(
key,
IPoolManagerMinimal.SwapParams({
zeroForOne: zeroForOne,
amountSpecified: -int256(amountIn),
sqrtPriceLimitX96: _stepLimit(key, zeroForOne)
}),
""
);
int128 d0 = int128(delta >> 128);
int128 d1 = int128(int256(uint256(delta) & type(uint128).max));
int128 owedIn = zeroForOne ? d0 : d1;
int128 gotOut = zeroForOne ? d1 : d0;
if (owedIn > 0 || gotOut < 0) revert CompoundSlippage(0, 0);
uint256 paid = uint256(uint128(-owedIn));
poolManager.sync(tokenIn);
IERC20(tokenIn).safeTransfer(address(poolManager), paid);
poolManager.settle();
uint256 out = uint256(uint128(gotOut));
poolManager.take(tokenOut, address(this), out);
return abi.encode(out, paid);
}
/**
* Pays out the platform, creator and stakers legs, in quote. Permissionless.
* A leg that cannot receive is re-booked rather than reverted on, so it
* cannot hold the others hostage. The liquidity and burn legs need a
* price; see `compound` and `burn`.
*/
function distribute(PoolKey memory key) external {
if (_busy) revert CompoundInProgress();
bytes32 id = poolId(key);
Tax memory tax = taxOf[id];
if (!tax.configured) revert NotConfigured();
IERC20 quote = IERC20(tax.quote);
uint256 owed = pendingPlatform[id] + pendingCreator[id] + pendingDividend[id];
// Only when short: a redeem from inside a V4 unlock is refused.
if (quote.balanceOf(address(this)) < owed) _redeem(tax.quote);
_pay(id, pendingPlatform, quote, platformTreasury());
_pay(id, pendingCreator, quote, _creatorPayee(tax));
_pay(id, pendingDividend, quote, tax.dividendVault);
}
/// @notice Where the creator leg is paid right now.
function creatorPayee(PoolKey memory key) external view returns (address) {
Tax memory tax = taxOf[poolId(key)];
if (!tax.configured) revert NotConfigured();
return _creatorPayee(tax);
}
/**
* FeeSplitter's current recipient for the token, falling back to the
* address set at launch.
*
* One setting for both of the creator's streams. The pool fee has always
* followed `FeeSplitter.setRecipient`; the tax used to stay on the launch
* address forever, so a creator who later pointed their earnings at a
* FeeShare split the pool fee and not the tax, while the page said
* everything was split (audit 2026-09-23 FS-3). Reading the recipient at
* payout closes that without a second setter to keep in step.
*
* The same parties who can move the pool fee can now move the tax leg:
* the token's creator, and FeeSplitter's owner as a recovery backstop.
* Rates and the four-way split are untouched; only whose wallet the
* creator's own share lands in follows the creator's choice.
*
* A failed or empty read falls back rather than reverts, so FeeSplitter
* can never block a payout.
*/
function _creatorPayee(Tax memory tax) private view returns (address to) {
to = tax.creator;
try IFeeRouting(tokenFactory).feeSplitter() returns (address splitter) {
if (splitter.code.length == 0) return to;
try IFeeRouting(splitter).creatorRecipient(tax.token) returns (address current) {
if (current != address(0)) to = current;
} catch {}
} catch {}
}
/**
* Pairs the booked liquidity share and adds it to the locked position.
* Gated and floored: the buy goes through the pool at spot, which is what
* a sandwich moves, so it is triggered by someone with a price from
* outside the block. `minTokenOut` is that price.
*/
function compound(PoolKey memory key, uint256 minTokenOut) external {
bytes32 id = poolId(key);
Tax memory tax = taxOf[id];
if (!tax.configured) revert NotConfigured();
_requireCompounder();
if (_busy) revert CompoundInProgress();
_redeem(tax.quote);
uint256 amount = pendingLiquidity[id];
if (amount == 0) return;
if (minTokenOut == 0) revert NoFloor();
_takeConversionSlot(id);
uint256 tokenBefore = pendingToken[id];
_busy = true;
(uint256 quoteLeft, uint256 tokenLeft) = this.compoundStep(id, key, tax, amount, minTokenOut);
_busy = false;
// Spend what was taken, keep what arrived: the locker call can route
// trades through this pool and book more tax into these counters.
uint256 quoteSpent;
if (quoteLeft > amount) pendingLiquidity[id] += quoteLeft - amount;
else quoteSpent = amount - quoteLeft;
pendingLiquidity[id] -= quoteSpent;
pendingToken[id] = pendingToken[id] + tokenLeft - tokenBefore;
emit Distributed(id, tax.pool, quoteSpent);
}
/// @dev One call frame that `compound` owns. Not an entry point.
function compoundStep(bytes32 id, PoolKey memory key, Tax memory tax, uint256 amount, uint256 minTokenOut)
external
returns (uint256 quoteLeft, uint256 tokenLeft)
{
require(msg.sender == address(this), "self only");
address adapter = ammAdapter;
require(adapter != address(0), "no adapter");
uint256 tokenId = ILiquidityLockerMinimal(liquidityLocker).positionOf(tax.pool);
require(tokenId != 0, "pool not locked");
uint256 tokenOnHand = pendingToken[id];
(uint256 buyAmount, uint256 expectedOut) =
ICompoundingAdapter(adapter).compoundSplit(tokenId, tax.quote, amount);
require(buyAmount <= amount, "bad split");
uint256 quoteToPair = amount - buyAmount;
if (buyAmount > 0) {
uint256 minOut = (expectedOut * COMPOUND_MIN_OUT_BPS) / BPS_DENOMINATOR;
if (minTokenOut > minOut) minOut = minTokenOut;
(uint256 bought, uint256 spent) = _swapExactIn(key, tax.quote, buyAmount, minOut);
tokenOnHand += bought;
// The pool ran out of range before taking it all.
quoteToPair += buyAmount - spent;
}
uint256 tokenBefore = IERC20(tax.token).balanceOf(address(this));
uint256 quoteBefore = IERC20(tax.quote).balanceOf(address(this));
IERC20(tax.token).forceApprove(liquidityLocker, tokenOnHand);
IERC20(tax.quote).forceApprove(liquidityLocker, quoteToPair);
ILiquidityLockerMinimal(liquidityLocker).increaseLiquidity(
tax.pool,
tax.quote,
quoteToPair,
tax.token,
tokenOnHand
);
IERC20(tax.token).forceApprove(liquidityLocker, 0);
IERC20(tax.quote).forceApprove(liquidityLocker, 0);
// Measured: the locker refunds whichever side the range cannot take.
uint256 tokenAfter = IERC20(tax.token).balanceOf(address(this));
uint256 quoteAfter = IERC20(tax.quote).balanceOf(address(this));
tokenLeft = tokenOnHand + tokenAfter - tokenBefore;
quoteLeft = quoteToPair + quoteAfter - quoteBefore;
if (tokenAfter >= tokenBefore && quoteAfter >= quoteBefore && buyAmount == 0) revert CompoundNoop();
}
/**
* Converts the booked burn share: buys the token with it and destroys
* what was bought. Gated and floored for the same reason `compound` is.
* The only floor is the caller's; there is no spot reference here.
*/
function burn(PoolKey memory key, uint256 minTokenOut) external {
bytes32 id = poolId(key);
Tax memory tax = taxOf[id];
if (!tax.configured) revert NotConfigured();
_requireCompounder();
if (_busy) revert CompoundInProgress();
_redeem(tax.quote);
uint256 amount = pendingBurn[id];
if (amount == 0) return;
if (minTokenOut == 0) revert NoFloor();
_takeConversionSlot(id);
pendingBurn[id] = 0;
_busy = true;
(uint256 bought, uint256 spent) = _swapExactIn(key, tax.quote, amount, minTokenOut);
_busy = false;
pendingBurn[id] += amount - spent;
IERC20(tax.token).safeTransfer(BURN_ADDRESS, bought);
emit Burned(id, spent, bought);
}
function _takeConversionSlot(bytes32 id) private {
if (lastConversionBlock[id] == block.number) revert OncePerBlock();
lastConversionBlock[id] = block.number;
}
function _requireCompounder() private view {
if (msg.sender != keeper && msg.sender != platformTreasury()) revert NotCompounder();
}
function setKeeper(address keeper_) external {
if (msg.sender != IOwned(IOwned(tokenFactory).launchConfig()).owner()) revert NotAdmin();
keeper = keeper_;
emit KeeperSet(keeper_);
}
/// @dev Effects before interaction; the amount is put back if the
/// transfer did not go through so the next call tries again. Never to
/// this hook, which would book the quote to nobody, nor to the
/// PoolManager, where it would settle whoever holds the unlock.
function _pay(
bytes32 id,
mapping(bytes32 => uint256) storage pending,
IERC20 erc20,
address to
) private {
uint256 amount = pending[id];
if (amount == 0) return;
pending[id] = 0;
if (to != address(this) && to != address(poolManager) && _tryTransfer(erc20, to, amount)) {
emit Distributed(id, to, amount);
} else {
pending[id] += amount;
emit PayoutFailed(id, to, amount);
}
}
function _tryTransfer(IERC20 erc20, address to, uint256 amount) private returns (bool) {
(bool ok, bytes memory ret) = address(erc20).call(
abi.encodeCall(IERC20.transfer, (to, amount))
);
return ok && (ret.length == 0 ? address(erc20).code.length > 0 : abi.decode(ret, (bool)));
}
/// @notice Rates can only fall, and fall at once. Every split change
/// waits SPLIT_CHANGE_DELAY. Resubmitting the current split
/// cancels a pending one; resubmitting the pending split keeps
/// its clock, so a rate cut need not restart the wait.
function updateTax(
PoolKey memory key,
uint16 buyBps,
uint16 sellBps,
uint16 creatorShareBps,
uint16 liquidityShareBps,
uint16 dividendShareBps,
uint16 burnShareBps
) external {
bytes32 id = poolId(key);
Tax storage tax = taxOf[id];
if (!tax.configured) revert NotConfigured();
if (!tax.dynamic) revert TaxIsStatic();
if (msg.sender != tax.taxAdmin) revert NotTaxAdmin();
_requireValidTax(
buyBps,
sellBps,
creatorShareBps,
liquidityShareBps,
dividendShareBps,
burnShareBps,
tax.pool != address(0),
tax.dividendVault != address(0),
tax.sniperDuration
);
_settlePendingSplit(id);
if (buyBps > tax.buyBps || sellBps > tax.sellBps) revert TaxCanOnlyFall();
tax.buyBps = buyBps;
tax.sellBps = sellBps;
bool splitChanges = creatorShareBps != tax.creatorShareBps || liquidityShareBps != tax.liquidityShareBps
|| dividendShareBps != tax.dividendShareBps || burnShareBps != tax.burnShareBps;
PendingSplit memory p = pendingSplitOf[id];
bool keepsPending = p.effectiveAt != 0 && creatorShareBps == p.creatorShareBps
&& liquidityShareBps == p.liquidityShareBps && dividendShareBps == p.dividendShareBps
&& burnShareBps == p.burnShareBps;
if (p.effectiveAt != 0 && !keepsPending) {
delete pendingSplitOf[id];
emit TaxScheduleCancelled(id);
}
if (splitChanges && !keepsPending) {
uint40 at = uint40(block.timestamp + SPLIT_CHANGE_DELAY);
pendingSplitOf[id] = PendingSplit({
creatorShareBps: creatorShareBps,
liquidityShareBps: liquidityShareBps,
dividendShareBps: dividendShareBps,
burnShareBps: burnShareBps,
effectiveAt: at
});
emit TaxSplitScheduled(id, creatorShareBps, liquidityShareBps, dividendShareBps, burnShareBps, at);
}
emit TaxUpdated(
id,
tax.buyBps,
tax.sellBps,
tax.creatorShareBps,
tax.liquidityShareBps,
tax.dividendShareBps,
tax.burnShareBps
);
}
/// @notice Points a pool's staking share at a replacement vault. Only
/// income from here on moves; stakes never pass through the hook.
/// The old vault is paused, which waives its exit fee, and can
/// never be migrated back to.
/// @dev Only LaunchConfig's owner. The pause is best effort: a vault that
/// cannot take it must not block the move.
function migrateDividendVault(PoolKey memory key, address vault) external {
if (msg.sender != IOwned(IOwned(tokenFactory).launchConfig()).owner()) revert NotAdmin();
bytes32 id = poolId(key);
Tax storage tax = taxOf[id];
if (tax.dividendVault == address(0)) revert NotConfigured();
if (
vault.code.length == 0 || IReplacementVault(vault).poolId() != id
|| IReplacementVault(vault).token() != tax.token || IReplacementVault(vault).taxHook() != address(this)
) revert BadTax();
address old = tax.dividendVault;
if (vault == old) revert BadTax();
address[] storage retired = _retiredVaults[id];
for (uint256 i; i < retired.length; ++i) {
if (retired[i] == vault) revert BadTax();
}
emit DividendVaultMigrated(id, old, vault);
_retiredVaults[id].push(old);
tax.dividendVault = vault;
// Cap-exempt like the launch vault (TokenFactory._initLimits), or a
// capped token's new vault holds one wallet's cap in total (FT-4).
IFeeRouting(tokenFactory).setLimitExempt(vault, true);
try IReplacementVault(old).setStakingPaused(true) {} catch {}
}
/// @notice Stops taxing one pool, for good: both swap callbacks return
/// before any tax logic runs. What was already booked can still be
/// paid out.
/// @dev Only LaunchConfig's guardian, the protocol multisig, and at once.
/// No delay because it can only take tax away; one-way because
/// switching it back would be an instant raise.
function failOpen(PoolKey memory key) external {
_requireGuardian();
bytes32 id = poolId(key);
if (!taxOf[id].configured) revert NotConfigured();
if (failedOpen[id]) return;
failedOpen[id] = true;
failedOpenAt[id] = uint40(block.timestamp);
emit FailedOpen(id);
}
/// @notice `failOpen` for every pool on this hook, and no taxed launch on it again.
function failOpenAll() external {
_requireGuardian();
if (allFailedOpen) return;
allFailedOpen = true;
allFailedOpenAt = uint40(block.timestamp);
emit AllFailedOpen();
}
/**
* The way out for booked liquidity and burn shares when compound or burn
* can no longer run (a broken adapter, locker or pool). Only on a pool that
* failed open at least RELEASE_DELAY ago, only by LaunchConfig's owner, and
* to fixed places: the quote joins the creator's leg, paid by `distribute`,
* and leftover launched token is burned.
*/
function releaseBooked(PoolKey memory key) external {
if (msg.sender != IOwned(IOwned(tokenFactory).launchConfig()).owner()) revert NotAdmin();
if (_busy) revert CompoundInProgress();
bytes32 id = poolId(key);
Tax memory tax = taxOf[id];
if (!tax.configured) revert NotConfigured();
uint256 at = failedOpen[id] ? failedOpenAt[id] : 0;
if (allFailedOpen && (at == 0 || allFailedOpenAt < at)) at = allFailedOpenAt;
if (at == 0 || block.timestamp < at + RELEASE_DELAY) revert ReleaseNotDue();
uint256 quote = pendingLiquidity[id] + pendingBurn[id];
uint256 tokens = pendingToken[id];
pendingLiquidity[id] = 0;
pendingBurn[id] = 0;
pendingToken[id] = 0;
pendingCreator[id] += quote;
if (tokens > 0) IERC20(tax.token).safeTransfer(BURN_ADDRESS, tokens);
emit BookedReleased(id, quote, tokens);
}
function _requireGuardian() private view {
if (msg.sender != IOwned(IOwned(tokenFactory).launchConfig()).guardian()) revert NotAdmin();
}
function _isFailedOpen(bytes32 id) private view returns (bool) {
return allFailedOpen || failedOpen[id];
}
/// @notice Vaults a pool no longer pays, so a site can still show a
/// staker the stake they have to move.
function retiredVaultsOf(bytes32 id) external view returns (address[] memory) {
return _retiredVaults[id];
}
function _settlePendingSplit(bytes32 id) private {
PendingSplit memory p = pendingSplitOf[id];
if (p.effectiveAt == 0 || block.timestamp < p.effectiveAt) return;
Tax storage tax = taxOf[id];
tax.creatorShareBps = p.creatorShareBps;
tax.liquidityShareBps = p.liquidityShareBps;
tax.dividendShareBps = p.dividendShareBps;
tax.burnShareBps = p.burnShareBps;
delete pendingSplitOf[id];
emit TaxSplitApplied(id, p.creatorShareBps, p.liquidityShareBps, p.dividendShareBps, p.burnShareBps);
}
function _overlayPendingSplit(bytes32 id, Tax memory tax) private view {
PendingSplit memory p = pendingSplitOf[id];
if (p.effectiveAt == 0 || block.timestamp < p.effectiveAt) return;
tax.creatorShareBps = p.creatorShareBps;
tax.liquidityShareBps = p.liquidityShareBps;
tax.dividendShareBps = p.dividendShareBps;
tax.burnShareBps = p.burnShareBps;
}
/// @notice The split change waiting for `key`, all zero when none.
function pendingSplit(PoolKey memory key)
external
view
returns (
uint16 creatorShareBps,
uint16 liquidityShareBps,
uint16 dividendShareBps,
uint16 burnShareBps,
uint40 effectiveAt
)
{
bytes32 id = poolId(key);
PendingSplit memory p = pendingSplitOf[id];
if (p.effectiveAt == 0 || block.timestamp >= p.effectiveAt || _isFailedOpen(id)) return (0, 0, 0, 0, 0);
return (p.creatorShareBps, p.liquidityShareBps, p.dividendShareBps, p.burnShareBps, p.effectiveAt);
}
/// @dev The one place the ceiling lives, shared by launch and update.
function _requireValidTax(
uint16 buyBps,
uint16 sellBps,
uint16 creatorShareBps,
uint16 liquidityShareBps,
uint16 dividendShareBps,
uint16 burnShareBps,
bool hasPool,
bool hasVault,
uint32 sniperDuration
) private pure {
if (buyBps > MAX_CREATOR_BPS || sellBps > MAX_CREATOR_BPS) revert BadTax();
uint256 shares = uint256(creatorShareBps) + liquidityShareBps + dividendShareBps + burnShareBps;
if (shares != BPS_DENOMINATOR) revert BadTax();
// A sniper window's premium is compounded into the pool, whatever the split.
if ((liquidityShareBps > 0 || sniperDuration > 0) && !hasPool) revert BadTax();
if (dividendShareBps > 0 && !hasVault) revert BadTax();
SniperRate.check(sniperDuration, uint16(uint256(sellBps) + STANDARD_FEE_BPS));
SniperRate.check(sniperDuration, uint16(uint256(buyBps) + STANDARD_FEE_BPS));
}
function taxConfig(PoolKey memory key)
external
view
returns (
uint16 buyBps,
uint16 sellBps,
uint16 creatorShareBps,
uint16 liquidityShareBps,
uint16 dividendShareBps,
uint16 burnShareBps,
bool dynamic,
address taxAdmin
)
{
bytes32 id = poolId(key);
Tax memory tax = taxOf[id];
_overlayPendingSplit(id, tax);
bool off = _isFailedOpen(id);
return (
off ? 0 : tax.buyBps,
off ? 0 : tax.sellBps,
tax.creatorShareBps,
tax.liquidityShareBps,
tax.dividendShareBps,
tax.burnShareBps,
tax.dynamic,
tax.taxAdmin
);
}
/// @dev The sniper schedule is expressed in what the trader pays in total,
/// so a launch opens at exactly 80% whatever the standard fee is.
function _effectiveCreatorBps(Tax memory tax, uint16 creatorBps) private view returns (uint16) {
if (tax.sniperDuration == 0) return creatorBps;
uint16 total = SniperRate.rateBps(
tax.startedAt,
tax.sniperDuration,
uint16(uint256(creatorBps) + STANDARD_FEE_BPS),
block.timestamp
);
return total - STANDARD_FEE_BPS;
}
/// @notice What a trader pays right now, standard fee included, and
/// when the sniper tax, if any, ends.
function currentRates(PoolKey memory key)
external
view
returns (uint16 buyTotalBps, uint16 sellTotalBps, uint40 sniperEndsAt)
{
bytes32 id = poolId(key);
Tax memory tax = taxOf[id];
if (!tax.configured) return (0, 0, 0);
if (_isFailedOpen(id)) return (0, 0, 0);
_overlayPendingSplit(id, tax);
buyTotalBps = _effectiveCreatorBps(tax, tax.buyBps) + STANDARD_FEE_BPS;
sellTotalBps = _effectiveCreatorBps(tax, tax.sellBps) + STANDARD_FEE_BPS;
sniperEndsAt = tax.sniperDuration == 0 ? 0 : tax.startedAt + tax.sniperDuration;
}
/// @dev The gross whose tax leaves exactly `net` behind. Rounds up, so the
/// take lands within two wei of the rate, in the trader's favour.
function _grossUp(uint256 net, uint16 creatorBps) private pure returns (uint256) {
uint256 keep = uint256(BPS_DENOMINATOR) - creatorBps - STANDARD_FEE_BPS;
// Unreachable today (sniper opens at 8000 bps, so keep >= 2000).
if (keep == 0) revert BadTax();
return (net * BPS_DENOMINATOR + keep - 1) / keep;
}
/// @dev Only the launch adapter opens pools on this hook. Anyone else
/// could read a pending launch's nonce, derive the token address and
/// open its pool first, reverting the launch. Also refuses a second
/// pool on a token this hook already taxes.
function beforeInitialize(address sender, PoolKey calldata key, uint160)
external
view
onlyPoolManager
returns (bytes4)
{
if (sender != ammAdapter || sender == address(0)) revert NotLaunchAdapter();
bytes32 id = poolId(key);
bytes32 c0 = canonicalPoolOf[key.currency0];
bytes32 c1 = canonicalPoolOf[key.currency1];
if ((c0 != bytes32(0) && c0 != id) || (c1 != bytes32(0) && c1 != id)) revert SiblingPool();
return this.beforeInitialize.selector;
}
/// @dev Three separate divisions, the same three `_charge` books, so the
/// two never disagree by a rounding wei.
function _taxOn(uint256 amount, uint16 creatorBps) private pure returns (uint256) {
return (amount * PLATFORM_BPS) / BPS_DENOMINATOR + (amount * CREATOR_BASE_BPS) / BPS_DENOMINATOR
+ (amount * creatorBps) / BPS_DENOMINATOR;
}
/// @dev `beforeSwap` taxed the whole specified quote amount; a partial
/// fill would charge for a trade that did not happen, so it is
/// refused. Exact-input buy: the pool must have taken amountIn - tax.
/// Exact-output sell: it must have produced net + tax.
function _requireFullFill(
Tax memory tax,
IPoolManagerMinimal.SwapParams calldata params,
int128 quoteDelta,
bool buying
) private view {
if (buying) {
uint256 amountIn = uint256(-params.amountSpecified);
uint256 expected = amountIn - _taxOn(amountIn, _effectiveCreatorBps(tax, tax.buyBps));
if (quoteDelta > 0 || uint256(uint128(-quoteDelta)) < expected) revert PartialFill();
} else {
uint16 creatorBps = _effectiveCreatorBps(tax, tax.sellBps);
uint256 gross = _grossUp(uint256(params.amountSpecified), creatorBps);
uint256 expected = uint256(params.amountSpecified) + _taxOn(gross, creatorBps);
if (quoteDelta < 0 || uint256(uint128(quoteDelta)) < expected) revert PartialFill();
}
}
/// @dev Must agree exactly with `_taxOn`. The creator takes the remainder
/// so rounding never leaves a wei booked to nobody. During a sniper
/// window only the settled rate is split; the premium above it is
/// booked to the liquidity leg.
function _charge(
bytes32 id,
Tax memory tax,
uint256 amount,
uint16 creatorBps,
bool isBuy
) private returns (uint256 total) {
uint256 platformCut = (amount * PLATFORM_BPS) / BPS_DENOMINATOR;
uint256 baseCut = (amount * CREATOR_BASE_BPS) / BPS_DENOMINATOR;
uint256 creatorCut = (amount * creatorBps) / BPS_DENOMINATOR;
total = platformCut + baseCut + creatorCut;
if (total == 0) return 0;
// The standard fee: the platform's half, and the creator's half straight
// to their payee. Only the creator's own rate below goes through the
// four-way split.
pendingPlatform[id] += platformCut;
pendingCreator[id] += baseCut;
uint256 settledCut = (amount * (isBuy ? tax.buyBps : tax.sellBps)) / BPS_DENOMINATOR;
uint256 premium = creatorCut - settledCut;
uint256 toLiquidity = premium + (settledCut * tax.liquidityShareBps) / BPS_DENOMINATOR;
uint256 toDividend = (settledCut * tax.dividendShareBps) / BPS_DENOMINATOR;
uint256 toBurn = (settledCut * tax.burnShareBps) / BPS_DENOMINATOR;
pendingLiquidity[id] += toLiquidity;
pendingDividend[id] += toDividend;
pendingBurn[id] += toBurn;
pendingCreator[id] += creatorCut - toLiquidity - toDividend - toBurn;
emit TaxCharged(id, isBuy, total);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/// @dev Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
bytes4 selector = IERC20Metadata.decimals.selector;
assembly ("memory-safe") {
mstore(0x00, selector)
success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
decimals := mul(success, mload(0x00))
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to approve
* @param bubble Behavior switch if the approve call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/interfaces/IUniswapV4Minimal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/**
* The slice of Uniswap V4 this project actually calls.
*
* Declared by hand rather than imported, for the same reason
* IUniswapV3Minimal.sol exists: v4-core and v4-periphery are written against
* solc ^0.8.26, and this project is pinned to 0.8.24. Importing their source
* would force a compiler bump across every contract here. Nothing needs that —
* V4 is deployed from Uniswap's own prebuilt artifacts (see UniswapV4Deployer),
* exactly as V3 already is, so only the call surface has to be described.
*
* `Currency` is V4's address-shaped value type for "a token, or native ETH as
* address(0)". Modelled as a plain address here because that is what it is on
* the wire, and this project never pairs against native ETH anyway — pools take
* WETH, matching the V3 path.
*/
/// @dev V4 identifies a pool by the hash of this struct rather than by a
/// deployed contract, which is why there is no per-pool address anywhere in V4.
struct PoolKey {
address currency0;
address currency1;
uint24 fee;
int24 tickSpacing;
address hooks;
}
interface IPoolManagerMinimal {
/// @notice Creates the pool. Reverts if it already exists, so callers that
/// tolerate an existing pool must catch that themselves.
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
/// @notice Enters the singleton's locked context and calls back into
/// `msg.sender.unlockCallback(data)`. Every balance-changing V4 operation
/// must happen inside this window and net to zero by the end of it.
function unlock(bytes calldata data) external returns (bytes memory);
struct SwapParams {
bool zeroForOne;
int256 amountSpecified;
uint160 sqrtPriceLimitX96;
}
/// @notice Only callable while unlocked. Returns the caller's balance delta
/// packed as two int128s: currency0 in the high half, currency1 in the low.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (int256 swapDelta);
/// @notice Records the singleton's current balance of `currency`, so a
/// following transfer-in can be credited by `settle`.
function sync(address currency) external;
/// @notice Pays what the caller owes, crediting whatever arrived since sync.
function settle() external payable returns (uint256 paid);
/// @notice Withdraws what the caller is owed.
function take(address currency, address to, uint256 amount) external;
/// @notice Credits the caller's positive delta as ERC-6909 claim tokens
/// instead of moving ERC20. `id` is `uint256(uint160(currency))`. Only
/// callable while unlocked; no balance leaves the singleton.
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Burns claim tokens, opening a positive delta the caller can
/// then `take`. Only callable while unlocked.
function burn(address from, uint256 id, uint256 amount) external;
/// @notice ERC-6909 claim balance of `owner` in currency `id`.
function balanceOf(address owner, uint256 id) external view returns (uint256);
/// @dev Adding or removing liquidity. Mirrors v4-core's ModifyLiquidityParams
/// field for field -- the launchpad itself goes through PositionManager,
/// so this is here for the tax tests, which need a pool with a hook and
/// cannot get one from an adapter that hardcodes "no hook".
struct ModifyLiquidityParams {
int24 tickLower;
int24 tickUpper;
int256 liquidityDelta;
bytes32 salt;
}
/// @notice Reads one of the singleton's storage slots directly. V4 keeps
/// every pool's state inside one contract and exposes no getter for
/// it, so the current price is read the way v4-core's own
/// StateLibrary reads it: compute the slot, load the word.
function extsload(bytes32 slot) external view returns (bytes32);
function modifyLiquidity(
PoolKey memory key,
ModifyLiquidityParams memory params,
bytes calldata hookData
) external returns (int256 callerDelta, int256 feesAccrued);
}
/// @dev v4-periphery's PositionManager. It is an ERC-721, which is what lets
/// LiquidityLocker hold a V4 position under exactly the same "lock the NFT
/// forever" guarantee it already gives V3 positions.
interface IPositionManagerMinimal {
/// @notice The one entry point for liquidity changes. `unlockData` is
/// abi.encode(bytes actions, bytes[] params) — a byte per action, and one
/// abi-encoded parameter blob per action. See Actions in v4-periphery.
function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;
/// @notice The id the next minted position will take. There is no mint()
/// returning an id in V4, so a caller reads this immediately after minting
/// and subtracts one.
function nextTokenId() external view returns (uint256);
function ownerOf(uint256 tokenId) external view returns (address);
function approve(address spender, uint256 tokenId) external;
/// @notice The pool a position belongs to. Needed to know which two
/// currencies a fee collection should pay out, since V4 positions are not
/// tied to a pool contract that could be asked.
function getPoolAndPositionInfo(uint256 tokenId) external view returns (PoolKey memory, uint256);
}
/// @dev PositionManager pulls ERC-20s through Permit2 rather than a direct
/// allowance, so a spender needs approval in two places: the token approves
/// Permit2, then Permit2 approves the PositionManager.
interface IPermit2Minimal {
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
}
src/libraries/BitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}
src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
src/libraries/SniperRate.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/**
* The sniper tax curve, and the unit conversion that sits under it.
*
* A launch may open with a high trade fee that decays to its normal rate over a
* window the creator picks. The point is to make the first seconds of a launch
* unprofitable for bots that buy in the same block and sell into the first real
* buyers. This library is the whole of that idea: three immutable numbers and
* the clock in, a rate out. No storage, no state, nothing that can be nudged
* after launch.
*
* WHY LINEAR. It is trivially bounded, trivially tested, and a creator can say
* what it does in one sentence. An exponential decays faster early -- which is
* when it matters -- but nobody can eyeball whether one is right.
*
* WHY THE START IS A CONSTANT. A creator-chosen start rate is a knob whose only
* use is making the tax worse. Eighty percent is what the reference platforms
* use and what the product promises.
*
* WHY THE DURATION IS CAPPED HERE, in the library, and not only at the
* factory. An unbounded window is a permanent 80% tax with a friendly label:
* buy in, never sell. The cap is the one guard that turns "sniper tax" back
* into a feature, so it lives where every caller has to go through it.
*
* TWO UNITS. This platform counts fees in basis points, ten thousand to the
* whole. Uniswap V4 counts LP fees in hundredths of a basis point, a million to
* the whole. Every value crosses that line exactly once, in `toPips`, and the
* test suite asserts what a real swap was charged rather than what this
* returned -- because a wrong factor here is a fee that is silently off by a
* hundred times, in whichever direction happens to be worse.
*/
library SniperRate {
/// @notice What a trader pays at the instant a sniper-taxed launch opens.
/// Eighty percent, in basis points.
uint16 internal constant START_BPS = 8_000;
/// @notice The longest window a creator may set, in seconds. Five minutes.
/// Long enough to outlast a bot's first block and the copy-traders
/// behind it; short enough that nobody who buys in is trapped.
uint32 internal constant MAX_DURATION = 300;
uint16 internal constant BPS_DENOMINATOR = 10_000;
/// @dev V4's `LPFeeLibrary`. A pool whose key carries DYNAMIC_FEE_FLAG as
/// its fee has no fixed fee; its hook says what the fee is, per swap,
/// by returning a value with OVERRIDE_FEE_FLAG set from `beforeSwap`.
/// A pool's LP fee may never exceed MAX_LP_FEE.
///
/// These are assumed from v4-core's source and asserted against the
/// real PoolManager bytecode in V4DynamicFee.t.sol. If that test
/// fails, fix these; do not fix the test.
uint24 internal constant DYNAMIC_FEE_FLAG = 0x800000;
uint24 internal constant OVERRIDE_FEE_FLAG = 0x400000;
uint24 internal constant MAX_LP_FEE = 1_000_000;
error DurationTooLong(uint32 duration, uint32 max);
error FloorAboveStart(uint16 floorBps);
/// @notice Refuses a schedule the platform will not run. Called once, at
/// launch, by whichever contract records the schedule.
function check(uint32 duration, uint16 floorBps) internal pure {
if (duration > MAX_DURATION) revert DurationTooLong(duration, MAX_DURATION);
if (floorBps > START_BPS) revert FloorAboveStart(floorBps);
}
/**
* The rate right now, in basis points.
*
* Falls in a straight line from START_BPS at `startedAt` to `floorBps` at
* `startedAt + duration`, and stays at the floor forever after. Both ends
* are clamped explicitly rather than trusted to the arithmetic, so no
* input can produce a rate below what was advertised or above eighty.
*
* A zero duration is "no sniper tax": the floor from the first second.
*/
function rateBps(
uint40 startedAt,
uint32 duration,
uint16 floorBps,
uint256 nowTs
) internal pure returns (uint16) {
if (floorBps >= START_BPS) return floorBps;
if (duration == 0 || nowTs >= uint256(startedAt) + duration) return floorBps;
if (nowTs <= startedAt) return START_BPS;
uint256 remaining = uint256(startedAt) + duration - nowTs;
// (START - floor) * remaining / duration, all comfortably inside
// uint256: the largest term is 8_000 * 2**32.
uint256 premium = (uint256(START_BPS - floorBps) * remaining) / duration;
uint256 rate = floorBps + premium;
if (rate > START_BPS) return START_BPS;
if (rate < floorBps) return floorBps;
return uint16(rate);
}
/// @notice Basis points to V4's hundredths of a basis point. The one place
/// the two units meet.
function toPips(uint16 bps) internal pure returns (uint24) {
return uint24(bps) * 100;
}
/// @notice What `beforeSwap` returns to make a dynamic-fee pool charge
/// `bps` for this swap. Reverts rather than returning something V4
/// would refuse, because the refusal would surface as every swap
/// on the pool failing.
function lpFeeOverride(uint16 bps) internal pure returns (uint24) {
uint24 pips = toPips(bps);
require(pips <= MAX_LP_FEE, "fee above V4 maximum");
return pips | OVERRIDE_FEE_FLAG;
}
}
src/libraries/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Vendored unmodified from @uniswap/v4-core (MIT-licensed, solidity ^0.8.0,
// zero external deps) — Uniswap's original v3-core TickMath targets
// `pragma solidity >=0.5.0 <0.8.0`, incompatible with this repo's 0.8.24.
// Used here for single-sided liquidity launches (TokenFactory.sol): finding
// the tick range that opens a Uniswap V3 position 100% in the new token,
// with zero USDC required from the creator.
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"erc4626-tests/=/Users/narwastunagoro/Projects/rh-launchpad/.claude/worktrees/tax-audit-r3/contracts/lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=/Users/narwastunagoro/Projects/rh-launchpad/.claude/worktrees/tax-audit-r3/contracts/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=/Users/narwastunagoro/Projects/rh-launchpad/.claude/worktrees/tax-audit-r3/contracts/lib/openzeppelin-contracts/contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.