Verified contractExactMIT
SniperFeeHook
Address0x78ba6c9d023790e2a953ef3aae2d73145c5b60cc
- Balance
0 ETH
- Transactions
1
- 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,069
- Creation transaction
- 0x8a9a8cd574…1ec25e8614
4 files
src/SniperFeeHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {PoolKey, IPoolManagerMinimal} from "./interfaces/IUniswapV4Minimal.sol";
import {SniperRate} from "./libraries/SniperRate.sol";
/**
* The fee on a Quick launch: 80% at the open, falling to 1% over the sniper
* window, then 1% for good. Charged by this hook on every swap, in the quote
* currency, and split 75% to the creator's payee and 25% to the platform --
* the same split FeeSplitter applies to an ordinary Quick launch's pool fee.
*
* WHY THE HOOK CHARGES IT AND NOT THE POOL.
*
* This used to be a dynamic LP fee. An LP fee is paid to whatever liquidity a
* swap trades through, so anyone could put a thin position just ahead of the
* price and take most of a sniper's 80% from the lock (audit R3 M1). The pool
* is now opened at a zero LP fee and the fee is taken out of the trade itself,
* so it is the same whoever's liquidity fills it, and outside liquidity earns
* nothing from it.
*
* Every one of the four swap kinds is charged in exactly one callback, as in
* TaxHook: where the quote is the specified currency in `beforeSwap`, where it
* is the unspecified one in `afterSwap`. Nothing is paid during a swap; the
* hook books counters and `distribute` pays, so a payee that cannot receive
* can never fail a trade.
*
* Only the V4 launch adapter can open a pool naming this hook. Anyone else
* could read a pending launch's nonce, derive the token address and open its
* pool first, reverting the launch (see `beforeInitialize`).
*
* A schedule is written once, by the factory, at launch, and never again. A
* creator who could restart an 80% fee after people had bought would hold a
* rug button, and the point of the cap on duration is that nobody holds one.
*/
interface IFactoryConfig {
function launchConfig() external view returns (address);
function feeSplitter() external view returns (address);
}
interface ILaunchConfigAdapters {
function ammAdapter(uint8 venue) external view returns (address);
function guardian() external view returns (address);
function platformTreasury() external view returns (address);
}
interface ICreatorRecipient {
function creatorRecipient(address token) external view returns (address);
}
contract SniperFeeHook {
/// @notice The fee a Quick launch decays to and keeps: one percent.
uint16 public constant FLOOR_BPS = 100;
/// @notice The creator's share of every fee; the platform gets the rest.
uint16 public constant CREATOR_SHARE_BPS = 7_500;
uint16 internal constant BPS_DENOMINATOR = 10_000;
/// @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;
IPoolManagerMinimal public immutable poolManager;
/// @dev Set once by `admin`, for the same reason TaxHook's is: the hook's
/// address is mined from its constructor arguments, so the factory --
/// which needs the hook's address -- cannot be one of them.
address public immutable admin;
address public tokenFactory;
struct Schedule {
uint40 startedAt;
uint32 duration;
bool configured;
address token;
address quote;
}
mapping(bytes32 poolId => Schedule) public scheduleOf;
mapping(bytes32 poolId => uint256) public pendingCreator;
mapping(bytes32 poolId => uint256) public pendingPlatform;
mapping(address token => bytes32 poolId) public canonicalPoolOf;
mapping(bytes32 poolId => bool) public failedOpen;
bool public allFailedOpen;
bool private _redeeming;
event SniperScheduled(bytes32 indexed poolId, uint40 startedAt, uint32 duration);
event FeeCharged(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 FailedOpen(bytes32 indexed poolId);
event AllFailedOpen();
error NotPoolManager();
error NotTokenFactory();
error AlreadyConfigured();
error BadHook();
error NotLaunchAdapter();
error PoolNotInitialized();
/// @dev A second pool wearing this hook on a token it already charges.
error SiblingPool();
error NotConfigured();
error NotRedeeming();
error PartialFill();
error DeltaOverflow();
error NotGuardian();
error LaunchesStopped();
modifier onlyPoolManager() {
if (msg.sender != address(poolManager)) revert NotPoolManager();
_;
}
constructor(IPoolManagerMinimal poolManager_, address admin_) {
if (address(poolManager_) == address(0) || admin_ == address(0)) revert BadHook();
poolManager = poolManager_;
admin = admin_;
}
function setTokenFactory(address factory) external {
if (msg.sender != admin) revert NotTokenFactory();
if (tokenFactory != address(0)) revert AlreadyConfigured();
if (factory == address(0)) revert BadHook();
tokenFactory = factory;
}
function poolId(PoolKey memory key) public pure returns (bytes32) {
return keccak256(abi.encode(key));
}
/**
* Records a pool's schedule. Once, at launch, by the factory.
*
* The clock starts now rather than at a caller-supplied time, so a schedule
* cannot be back- or forward-dated. `SniperRate.check` is what enforces the
* duration cap; it is the honeypot guard and it cannot be bypassed by a
* caller, including the factory.
*/
function configure(PoolKey memory key, address token, uint32 duration) external {
if (msg.sender != tokenFactory) revert NotTokenFactory();
// A launch would promise a fee this hook will never charge.
if (allFailedOpen) revert LaunchesStopped();
bytes32 id = poolId(key);
if (scheduleOf[id].configured) revert AlreadyConfigured();
// Any LP fee would be paid to whoever's liquidity a swap crosses,
// which is the leak this hook exists to close.
if (key.fee != 0 || key.hooks != address(this)) revert BadHook();
if (token != key.currency0 && token != key.currency1) revert BadHook();
address quote = token == key.currency0 ? key.currency1 : key.currency0;
if (quote == address(0)) revert BadHook();
// A key that drifted from the adapter's would charge a pool nobody trades.
if (uint160(uint256(poolManager.extsload(keccak256(abi.encodePacked(id, POOLS_SLOT))))) == 0) {
revert PoolNotInitialized();
}
SniperRate.check(duration, FLOOR_BPS);
canonicalPoolOf[token] = id;
uint40 startedAt = uint40(block.timestamp);
scheduleOf[id] = Schedule({
startedAt: startedAt,
duration: duration,
configured: true,
token: token,
quote: quote
});
emit SniperScheduled(id, startedAt, duration);
}
/// @dev The V4 adapter LaunchConfig names; enum index 2 is UniswapV4. Also
/// refuses a second pool on a token this hook already charges.
function beforeInitialize(address sender, PoolKey calldata key, uint160)
external
view
onlyPoolManager
returns (bytes4)
{
address factory = tokenFactory;
if (factory == address(0)) revert NotLaunchAdapter();
address adapter = ILaunchConfigAdapters(IFactoryConfig(factory).launchConfig()).ammAdapter(2);
if (sender != adapter || adapter == 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;
}
/// @notice The fee a swap on `key` pays right now, in basis points of the
/// quote side. Zero until the factory configures the pool, which
/// is after the creator's dev buy.
function currentRateBps(PoolKey memory key) public view returns (uint16) {
bytes32 id = poolId(key);
Schedule memory s = scheduleOf[id];
if (!s.configured || _isFailedOpen(id)) return 0;
return SniperRate.rateBps(s.startedAt, s.duration, FLOOR_BPS, block.timestamp);
}
/// @notice When `key`'s fee reaches the floor, as a timestamp. Zero for a
/// pool with no schedule.
function decayEndsAt(PoolKey memory key) external view returns (uint40) {
Schedule memory s = scheduleOf[poolId(key)];
if (!s.configured) return 0;
return s.startedAt + s.duration;
}
/**
* Charges where the quote is the specified currency: an exact-input BUY
* (quote in) and an exact-output SELL (quote out). A positive specified
* delta 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);
Schedule memory s = scheduleOf[id];
if (!s.configured || _isFailedOpen(id)) return (this.beforeSwap.selector, 0, 0);
bool buying = params.zeroForOne != (key.currency0 == s.token);
bool exactInput = params.amountSpecified < 0;
uint16 rate = currentRateBps(key);
uint256 amount;
if (buying && exactInput) {
amount = _charge(id, _feeOn(uint256(-params.amountSpecified), rate), true);
} else if (!buying && !exactInput) {
amount = _charge(id, _feeOn(_grossUp(uint256(params.amountSpecified), rate), rate), false);
} else {
return (this.beforeSwap.selector, 0, 0);
}
if (amount == 0) return (this.beforeSwap.selector, 0, 0);
_collect(s.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: 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);
Schedule memory s = scheduleOf[id];
if (!s.configured || _isFailedOpen(id)) return (this.afterSwap.selector, 0);
bool tokenIsCurrency0 = key.currency0 == s.token;
bool buying = params.zeroForOne != tokenIsCurrency0;
bool exactInput = params.amountSpecified < 0;
uint16 rate = currentRateBps(key);
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, _feeOn(uint128(quoteDelta), rate), false);
} else if (buying && !exactInput) {
if (quoteDelta >= 0) return (this.afterSwap.selector, 0);
amount = _charge(id, _feeOn(_grossUp(uint128(-quoteDelta), rate), rate), true);
} else {
_requireFullFill(params, quoteDelta, buying, rate);
return (this.afterSwap.selector, 0);
}
if (amount == 0) return (this.afterSwap.selector, 0);
_collect(s.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));
}
/**
* Pays both legs, in quote. Permissionless. A leg that cannot receive, or
* whose payee cannot be read, is re-booked rather than reverted on, so it
* cannot hold the other hostage.
*/
function distribute(PoolKey memory key) external {
bytes32 id = poolId(key);
Schedule memory s = scheduleOf[id];
if (!s.configured) revert NotConfigured();
IERC20 quote = IERC20(s.quote);
if (quote.balanceOf(address(this)) < pendingCreator[id] + pendingPlatform[id]) _redeem(s.quote);
address factory = tokenFactory;
address config = _addressFrom(factory, abi.encodeCall(IFactoryConfig.launchConfig, ()));
address splitter = _addressFrom(factory, abi.encodeCall(IFactoryConfig.feeSplitter, ()));
_pay(id, pendingPlatform, quote, _addressFrom(config, abi.encodeCall(ILaunchConfigAdapters.platformTreasury, ())));
_pay(id, pendingCreator, quote, _addressFrom(splitter, abi.encodeCall(ICreatorRecipient.creatorRecipient, (s.token))));
}
/// @dev Zero when the read fails.
function _addressFrom(address target, bytes memory data) private view returns (address out) {
(bool ok, bytes memory ret) = target.staticcall(data);
if (ok && ret.length == 32) out = address(uint160(uint256(bytes32(ret))));
}
/// @notice Stops charging one pool, for good; what was booked can still be
/// paid out. The way out if a V4 change ever made the swap
/// callbacks revert and froze trading.
/// @dev LaunchConfig's guardian, at once: it can only take a fee away.
/// One-way, because switching back would be an instant raise.
function failOpen(PoolKey memory key) external {
_requireGuardian();
bytes32 id = poolId(key);
if (!scheduleOf[id].configured) revert NotConfigured();
if (failedOpen[id]) return;
failedOpen[id] = true;
emit FailedOpen(id);
}
/// @notice `failOpen` for every pool on this hook, and no launch on it again.
function failOpenAll() external {
_requireGuardian();
if (allFailedOpen) return;
allFailedOpen = true;
emit AllFailedOpen();
}
function unlockCallback(bytes calldata data) external onlyPoolManager returns (bytes memory) {
if (!_redeeming) revert NotRedeeming();
(address currency, uint256 amount) = abi.decode(data, (address, uint256));
poolManager.burn(address(this), uint256(uint160(currency)), amount);
poolManager.take(currency, address(this), amount);
return "";
}
function _requireGuardian() private view {
if (msg.sender != ILaunchConfigAdapters(IFactoryConfig(tokenFactory).launchConfig()).guardian()) {
revert NotGuardian();
}
}
function _isFailedOpen(bytes32 id) private view returns (bool) {
return allFailedOpen || failedOpen[id];
}
/// @dev The fee on a quote amount, rounded down, in the trader's favour.
function _feeOn(uint256 amount, uint16 rate) private pure returns (uint256) {
return (amount * rate) / BPS_DENOMINATOR;
}
/// @dev The gross whose fee leaves exactly `net` behind. Rounds up; the
/// rate never passes SniperRate's 80% start, so `keep` is never zero.
function _grossUp(uint256 net, uint16 rate) private pure returns (uint256) {
uint256 keep = uint256(BPS_DENOMINATOR) - rate;
return (net * BPS_DENOMINATOR + keep - 1) / keep;
}
/// @dev The platform takes the remainder, so rounding never books a wei
/// to nobody.
function _charge(bytes32 id, uint256 amount, bool isBuy) private returns (uint256) {
if (amount == 0) return 0;
uint256 toCreator = (amount * CREATOR_SHARE_BPS) / BPS_DENOMINATOR;
pendingCreator[id] += toCreator;
pendingPlatform[id] += amount - toCreator;
emit FeeCharged(id, isBuy, amount);
return amount;
}
/// @dev `beforeSwap` charged on the whole specified quote amount; a
/// partial fill would charge for a trade that did not happen.
function _requireFullFill(
IPoolManagerMinimal.SwapParams calldata params,
int128 quoteDelta,
bool buying,
uint16 rate
) private pure {
if (buying) {
uint256 amountIn = uint256(-params.amountSpecified);
uint256 expected = amountIn - _feeOn(amountIn, rate);
if (quoteDelta > 0 || uint256(uint128(-quoteDelta)) < expected) revert PartialFill();
} else {
uint256 net = uint256(params.amountSpecified);
uint256 expected = net + _feeOn(_grossUp(net, rate), rate);
if (quoteDelta < 0 || uint256(uint128(quoteDelta)) < expected) revert PartialFill();
}
}
/// @dev Never `take` mid-swap: the trader has not settled yet. A claim
/// moves no balance and is redeemed by `distribute`.
function _collect(address currency, uint256 amount) private {
poolManager.mint(address(this), uint256(uint160(currency)), amount);
}
function _redeem(address currency) private {
uint256 claims = poolManager.balanceOf(address(this), uint256(uint160(currency)));
if (claims == 0) return;
_redeeming = true;
poolManager.unlock(abi.encode(currency, claims));
_redeeming = false;
}
/// @dev 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;
bool ok;
if (to != address(0) && to != address(this) && to != address(poolManager)) {
bytes memory ret;
(ok, ret) = address(erc20).call(abi.encodeCall(IERC20.transfer, (to, amount)));
ok = ok && (ret.length == 0 ? address(erc20).code.length > 0 : abi.decode(ret, (bool)));
}
if (ok) {
emit Distributed(id, to, amount);
} else {
pending[id] += amount;
emit PayoutFailed(id, to, amount);
}
}
}
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);
}
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/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;
}
}
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.