contract
RulesEngine
compiler
v0.8.26+commit.8a97fa7a
optimizer
on, 200 runs · via IR
evm version
cancun
license
MIT
match
full: bytecode and metadata hash equal
verified
2026-10-31 17:37:27 UTC
constructor arguments
source (26 files)
src/rules/RulesEngine.solmain566 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol"; import {EngineBase} from "../EngineBase.sol"; import {IRuleCoin, Script} from "../IRuleEngine.sol"; import {RuleId, Rules, RuleWords} from "./RuleWords.sol"; interface IERC20Balance { function balanceOf(address) external view returns (uint256); } /// @title eleos rules engine (Vows) /// @notice Vows: up to eight rules per coin, fixed at launch, checked on every transfer. No owner can change a /// coin's rules; a rule only ends at the time it carries. /// The creator is exempt from holding and buying caps; sell rules and the dev lock apply to the creator. /// Per trader counts (buy limit, no repeat) go by the wallet that signed (`tx.origin`): on Elysium that is the /// person for transactions signed on Elysium (also those the relayer forwards through the inbox) and the /// person's alias for a bridge and buy. Payouts go to the receiving wallet when it is a wallet. /// The buyer rewards and the jackpot are pots in HYPE held here, fed by anyone (`fundRewards`, `fundJackpot`). /// Price rules (dip only, taper, opening bell) read the pool's price: the sold share of the curve is /// 1 - sqrt(P) / sqrt(P_start). contract RulesEngine is EngineBase { error Bad(string what); error NotCreator(); error NotCoin(); error NothingOwed(); error PayFailed(); event JackpotWon(address indexed token, address indexed winner, uint256 amount); event RewardEarned(address indexed token, address indexed buyer, uint256 amount); event Claimed(address indexed token, address indexed who, uint256 amount); event PotFunded(address indexed token, bool jackpot, address indexed from, uint256 amount); event RewardsWithdrawn(address indexed token, uint256 amount); event Jailed(address indexed token, address indexed who, uint256 until); uint256 public constant MAX_RULES = 8; uint256 internal constant DAY = 86_400; uint256 internal constant SUPPLY = 1_000_000_000 ether; /// @dev What the rules of a coin remember. A field is only kept up when one of the coin's rules reads it, so a coin /// without such rules pays no storage on a trade (the indexer counts holders, volume and trades for the site). struct Stats { address lastBuyer; // no repeat uint40 lastBuyTime; // slow mode, raise, anti bundle uint16 buysInSecond; // anti bundle uint40 devLastSend; // dev lock uint32 holders; // the club uint32 buysSinceSell; // buys unlock sells uint32 qualifyingBuys; // buyer rewards uint16 partnerAtStart; // reactive: the partner's sold share when this coin launched bool entangledOpen; // entangled uint96 lastBuyAmount; // raise uint128 volume; // chapters uint160 peak; // dip only: the lowest sqrt price seen, the coin's highest price } struct Wallet { uint32 buys; uint40 lastBuy; uint40 lastTrade; uint40 jailUntil; } struct Pots { uint128 jackpot; uint128 rewards; address jackpotLast; uint40 jackpotTime; uint128 owedTotal; } /// @dev one transfer, as the rules see it struct T { address token; address from; address to; uint256 amount; uint256 fromBal; uint256 toBal; address creator; uint256 start; } mapping(address => Stats) internal _stats; mapping(address => mapping(address => Wallet)) internal _wallets; mapping(address => Pots) internal _pots; mapping(address => mapping(address => uint256)) public owed; constructor(IPoolManager pm, address hook_, int24 startTick_, address setter_) EngineBase(pm, hook_, startTick_, setter_) {} receive() external payable { revert Refused(); } // ---------------------------------------------------------------- views function stats(address token) external view returns (Stats memory) { return _stats[token]; } function wallet(address token, address a) external view returns (Wallet memory) { return _wallets[token][a]; } function pots(address token) external view returns (Pots memory) { return _pots[token]; } /// @notice A coin's rules, unpacked. function rulesOf(address token) public view returns (Rules memory) { Script memory sc = scriptOf(token); return RuleWords.decode(sc.rows, sc.n); } /// @notice Is a rule of the coin on right now. function isOn(address token, uint8 id) external view returns (bool) { return _isOn(rulesOf(token), id); } /// @notice The coin's max wallet right now (max wallet, rising max wallet, chapters); type(uint256).max when off. function maxWalletOf(address token) external view returns (uint256) { Script memory sc = scriptOf(token); return _maxWallet(token, RuleWords.decode(sc.rows, sc.n), sc.start); } function marketOpen(address token) external view returns (bool) { return _marketOpen(rulesOf(token)); } // ---------------------------------------------------------------- the launch check /// @notice The limits every coin lives with, checked on its rule words before launch. A rule never holds a /// wallet for longer than a day, the dev lock lasts at most 30 days, and no rule can brick a coin. function validate(uint256[] calldata w, uint32 release) external view { if (release != 0) revert Bad("release"); if (w.length > MAX_RULES) revert Bad("too many rules"); uint64 seen; for (uint256 i; i < w.length; i++) { uint256 x = w[i]; uint8 id = uint8(x); if (id >= 64 || RuleId.KNOWN & (uint64(1) << id) == 0) revert Bad("unknown rule"); if (seen & (uint64(1) << id) != 0) revert Bad("rule twice"); seen |= uint64(1) << id; if (x >> (40 + RuleId.bitsOf(id)) != 0) revert Bad("numbers"); uint32 u = uint32(x >> 8); if (u != 0 && u <= block.timestamp) revert Bad("until time"); } _check(RuleWords.decode(w)); } function _check(Rules memory r) internal view { uint64 m = r.mask; if (_on(m, RuleId.MAX_WALLET)) _bps(r.maxWalletBps, 10, "maxWallet"); if (_on(m, RuleId.RISING_MAX_WALLET)) { _bps(r.riseStartBps, 10, "riseStart"); if (r.riseStepBps > 10_000) revert Bad("riseStep"); _time(r.riseSeconds, 60, 7 * DAY, "riseSeconds"); } if (_on(m, RuleId.CHAPTERS)) { _bps(r.chapterStartBps, 10, "chapterStart"); if (r.chapterVolume < 1e6 ether) revert Bad("chapterVolume"); } if (_on(m, RuleId.THE_CLUB) && r.clubMax < 10) revert Bad("clubMax"); if (_on(m, RuleId.HOLDER_GATED)) { if (r.gateToken.code.length == 0) revert Bad("gateToken"); if (r.gateMin == 0 || r.gateMin == type(uint256).max) revert Bad("gateMin"); } if (_on(m, RuleId.MAX_TRADE)) _bps(r.maxTradeBps, 10, "maxTrade"); if (_on(m, RuleId.ANTI_BUNDLE) && r.buysPerSecond == 0) revert Bad("buysPerSecond"); if (_on(m, RuleId.RAISE)) { if (r.raiseBps == 0 || r.raiseBps > 10_000) revert Bad("raiseBps"); _time(r.raiseReset, 10, DAY, "raiseReset"); } if (_on(m, RuleId.MIN_BUY) && (r.minBuy == 0 || r.minBuy > 10_000_000 ether)) revert Bad("minBuy"); if (_on(m, RuleId.SLOW_MODE)) _time(r.slowSeconds, 1, 3600, "slowSeconds"); if (_on(m, RuleId.BUY_LIMIT) && r.buyLimit == 0) revert Bad("buyLimit"); if (_on(m, RuleId.ANTI_DUMP)) { _bps(r.dumpBuyBps, 10, "dumpBuy"); _bps(r.dumpSellBps, 10, "dumpSell"); } if (_on(m, RuleId.SELL_CURVE)) { _bps(r.curveFloorBps, 5, "curveFloor"); if (r.curveSmallBps < r.curveFloorBps || r.curveSmallBps > 10_000) revert Bad("curveSmall"); _bps(r.curveBigBagBps, 1, "curveBigBag"); } if (_on(m, RuleId.TAPER)) { _bps(r.taperEndBps, 5, "taperEnd"); if (r.taperStartBps < r.taperEndBps || r.taperStartBps > 10_000) revert Bad("taperStart"); _bps(r.taperSoldBps, 100, "taperSold"); } if (_on(m, RuleId.BUYS_UNLOCK_SELLS) && (r.unlockBuys == 0 || r.unlockBuys > 20)) revert Bad("unlockBuys"); if (_on(m, RuleId.DEV_LOCK)) { _time(r.devLockSeconds, 0, 30 * DAY, "devLock"); _bps(r.devCapBps, 1, "devCap"); _time(r.devGapSeconds, 0, DAY, "devGap"); } if (_on(m, RuleId.DIAMOND)) _time(r.diamondSeconds, 1, DAY, "diamond"); if (_on(m, RuleId.COOLDOWN)) _time(r.cooldownSeconds, 1, DAY, "cooldown"); if (_on(m, RuleId.SNIPER_JAIL)) { _time(r.jailWindow, 1, 3600, "jailWindow"); _time(r.jailSeconds, 1, DAY, "jailSeconds"); } if (_on(m, RuleId.MARKET_HOURS)) { if (r.openHour >= 24 || r.closeHour >= 24 || r.openHour == r.closeHour) revert Bad("hours"); if (r.weekdays == 0 || r.weekdays >= 128) revert Bad("weekdays"); } if (_on(m, RuleId.SELL_WINDOW)) { _time(r.sellPeriod, 60, DAY, "sellPeriod"); if (r.sellWindow < 60 || r.sellWindow >= r.sellPeriod) revert Bad("sellWindow"); } if (_on(m, RuleId.TICK_TOCK)) _time(r.tickSeconds, 60, DAY, "tickSeconds"); if (_on(m, RuleId.OPENING_BELL)) { _time(r.bellSeconds, 1, DAY, "bellSeconds"); if (r.bellSoldBps > 10_000) revert Bad("bellSold"); } if (_on(m, RuleId.POOL_ONLY) && _on(m, RuleId.P2P_ONLY)) revert Bad("pool only and p2p only"); if (_on(m, RuleId.BUYER_REWARDS) && r.rewardPerBuy == 0) revert Bad("rewardPerBuy"); if (_on(m, RuleId.JACKPOT)) { _time(r.jackpotSilence, 30, DAY, "jackpotSilence"); _bps(r.jackpotShareBps, 1, "jackpotShare"); } if (_on(m, RuleId.DIP_ONLY) && (r.dipBps == 0 || r.dipBps >= 10_000)) revert Bad("dipBps"); if (_on(m, RuleId.ENTANGLED) && _on(m, RuleId.REACTIVE)) revert Bad("one linked rule"); if (_on(m, RuleId.ENTANGLED)) { if (!_coin(r.beacon)) revert Bad("beacon"); _bps(r.beaconTargetBps, 1, "beaconTarget"); } if (_on(m, RuleId.REACTIVE)) { if (!_coin(r.partner)) revert Bad("partner"); _bps(r.reactBaseBps, 1, "reactBase"); } } // ---------------------------------------------------------------- transfers /// @notice At launch: the reactive rule measures the partner from here. function opened(address token) external { if (msg.sender != launcher) revert Refused(); Rules memory r = rulesOf(token); if (_has(r, RuleId.REACTIVE)) _stats[token].partnerAtStart = uint16(soldBpsOf(r.partner)); } function onMove(Move calldata m) external returns (uint256, uint256, uint256) { Script memory sc = scriptOf(msg.sender); T memory t = T(msg.sender, m.from, m.to, m.amount, m.fromBal, m.toBal, sc.creator, sc.start); Rules memory r = RuleWords.decode(sc.rows, sc.n); Stats storage s = _stats[t.token]; if (_has(r, RuleId.THE_CLUB)) _holders(t, r, s); if (t.from == address(poolManager)) _buy(t, r, s); else if (t.to == address(poolManager)) _sell(t, r, s); else if (t.to != DEAD) _send(t, r, s); return (0, 0, 0); } function _holders(T memory t, Rules memory r, Stats storage s) internal { if (_tracked(t.token, t.from) && t.fromBal == t.amount && s.holders > 0) s.holders--; if (_tracked(t.token, t.to) && t.toBal == 0) { s.holders++; if (_isOn(r, RuleId.THE_CLUB) && t.to != t.creator && s.holders > r.clubMax) revert Blocked(RuleId.THE_CLUB); } } function _buy(T memory t, Rules memory r, Stats storage s) internal { bool dev = tx.origin == t.creator || t.to == t.creator; uint256 now_ = block.timestamp; if (_isOn(r, RuleId.P2P_ONLY) && !dev) revert Blocked(RuleId.P2P_ONLY); if (_isOn(r, RuleId.MARKET_HOURS) && !_marketOpen(r)) revert Blocked(RuleId.MARKET_HOURS); if (_isOn(r, RuleId.TICK_TOCK) && ((now_ - t.start) / r.tickSeconds) % 2 == 1) revert Blocked(RuleId.TICK_TOCK); if (!dev) { if (_isOn(r, RuleId.ENTANGLED) && !s.entangledOpen) { if (soldBpsOf(r.beacon) < r.beaconTargetBps) revert Blocked(RuleId.ENTANGLED); s.entangledOpen = true; } _holdCaps(t, r); if (_isOn(r, RuleId.MAX_TRADE) && t.amount > _of(r.maxTradeBps)) revert Blocked(RuleId.MAX_TRADE); if (_isOn(r, RuleId.ANTI_DUMP) && t.amount > _of(r.dumpBuyBps)) revert Blocked(RuleId.ANTI_DUMP); if (_isOn(r, RuleId.REACTIVE) && t.amount > _of(_reactiveCapBps(r, s))) revert Blocked(RuleId.REACTIVE); if (_isOn(r, RuleId.MIN_BUY) && t.amount < r.minBuy) revert Blocked(RuleId.MIN_BUY); if (_isOn(r, RuleId.SLOW_MODE) && s.lastBuyTime != 0 && now_ < uint256(s.lastBuyTime) + r.slowSeconds) { revert Blocked(RuleId.SLOW_MODE); } if (_isOn(r, RuleId.NO_REPEAT) && s.lastBuyer == tx.origin) revert Blocked(RuleId.NO_REPEAT); if ( _isOn(r, RuleId.RAISE) && now_ < uint256(s.lastBuyTime) + r.raiseReset && t.amount < uint256(s.lastBuyAmount) * (10_000 + r.raiseBps) / 10_000 ) revert Blocked(RuleId.RAISE); if (_isOn(r, RuleId.BUY_LIMIT) && _wallets[t.token][tx.origin].buys >= r.buyLimit) revert Blocked(RuleId.BUY_LIMIT); } // buys per second: Elysium's block number is the parent chain's, so blocks would count nothing useful if (_has(r, RuleId.ANTI_BUNDLE)) { uint16 inSecond = s.lastBuyTime == now_ ? s.buysInSecond + 1 : 1; if (_isOn(r, RuleId.ANTI_BUNDLE) && !dev && inSecond > r.buysPerSecond) revert Blocked(RuleId.ANTI_BUNDLE); s.buysInSecond = inSecond; } if (_has(r, RuleId.DIP_ONLY)) { uint160 p = sqrtPriceOf(t.token); uint160 peak = s.peak; if (_isOn(r, RuleId.DIP_ONLY) && !dev && (peak == 0 || p < peak || _ratio(peak, p) > 10_000 - uint256(r.dipBps))) { revert Blocked(RuleId.DIP_ONLY); } if (peak == 0 || p < peak) s.peak = p; } // record what the rules read later if (_has(r, RuleId.BUY_LIMIT) || _has(r, RuleId.DIAMOND) || _has(r, RuleId.COOLDOWN) || _has(r, RuleId.SNIPER_JAIL)) { Wallet storage w = _wallets[t.token][tx.origin]; if (_has(r, RuleId.BUY_LIMIT)) w.buys++; if (_has(r, RuleId.DIAMOND)) w.lastBuy = uint40(now_); if (_has(r, RuleId.COOLDOWN)) w.lastTrade = uint40(now_); if (_isOn(r, RuleId.SNIPER_JAIL) && !dev && now_ < t.start + r.jailWindow) { uint40 free = uint40(now_ + r.jailSeconds); w.jailUntil = free; emit Jailed(t.token, tx.origin, free); if (t.to.code.length == 0 && t.to != tx.origin) { _wallets[t.token][t.to].jailUntil = free; emit Jailed(t.token, t.to, free); } } } if (_has(r, RuleId.JACKPOT)) _settleJackpot(t.token, r); if (_has(r, RuleId.BUYS_UNLOCK_SELLS)) s.buysSinceSell++; if (_has(r, RuleId.SLOW_MODE) || _has(r, RuleId.RAISE) || _has(r, RuleId.ANTI_BUNDLE)) s.lastBuyTime = uint40(now_); if (_has(r, RuleId.NO_REPEAT)) s.lastBuyer = tx.origin; if (_has(r, RuleId.RAISE)) s.lastBuyAmount = uint96(t.amount); if (_has(r, RuleId.CHAPTERS)) s.volume += uint128(t.amount); address payee = t.to.code.length == 0 ? t.to : tx.origin; if (_isOn(r, RuleId.BUYER_REWARDS) && t.amount >= r.rewardMinBuy) { s.qualifyingBuys++; uint256 n = r.rewardEveryN; uint256 pay = r.rewardPerBuy; Pots storage pt = _pots[t.token]; if ((n <= 1 || s.qualifyingBuys % n == 0) && pt.rewards >= pay) { pt.rewards -= uint128(pay); owed[t.token][payee] += pay; pt.owedTotal += uint128(pay); emit RewardEarned(t.token, payee, pay); } } if (_isOn(r, RuleId.JACKPOT) && t.amount >= r.jackpotMinBuy) { Pots storage pt = _pots[t.token]; pt.jackpotLast = payee; pt.jackpotTime = uint40(now_); } } function _sell(T memory t, Rules memory r, Stats storage s) internal { uint256 now_ = block.timestamp; // the person behind the sell: the holder, or the signer when a contract sells address who = t.from.code.length == 0 ? t.from : tx.origin; if (t.from == t.creator || tx.origin == t.creator) _devLock(t, r, s, t.amount); if (_isOn(r, RuleId.OPENING_BELL) && now_ < t.start + r.bellSeconds && soldBpsOf(t.token) < r.bellSoldBps) { revert Blocked(RuleId.OPENING_BELL); } if (_isOn(r, RuleId.SELL_WINDOW) && (now_ - t.start) % r.sellPeriod >= r.sellWindow) revert Blocked(RuleId.SELL_WINDOW); if (_isOn(r, RuleId.TICK_TOCK) && ((now_ - t.start) / r.tickSeconds) % 2 == 0) revert Blocked(RuleId.TICK_TOCK); if (_isOn(r, RuleId.MARKET_HOURS) && !r.sellsOpen && !_marketOpen(r)) revert Blocked(RuleId.MARKET_HOURS); if (_isOn(r, RuleId.ANTI_DUMP) && t.amount > _of(r.dumpSellBps)) revert Blocked(RuleId.ANTI_DUMP); if (_isOn(r, RuleId.SELL_CURVE)) { uint256 bag = who == t.from ? t.fromBal : IRuleCoin(t.token).balanceOf(who) + t.amount; uint256 big = _of(r.curveBigBagBps); uint256 cap = bag >= big ? _of(r.curveFloorBps) : _of(r.curveSmallBps) - (_of(r.curveSmallBps) - _of(r.curveFloorBps)) * bag / big; if (t.amount > cap) revert Blocked(RuleId.SELL_CURVE); } if (_isOn(r, RuleId.TAPER)) { uint256 sold = _min(soldBpsOf(t.token), r.taperSoldBps); uint256 capBps = r.taperStartBps - (uint256(r.taperStartBps) - r.taperEndBps) * sold / r.taperSoldBps; if (t.amount > _of(capBps)) revert Blocked(RuleId.TAPER); } if (_isOn(r, RuleId.BUYS_UNLOCK_SELLS) && s.buysSinceSell < r.unlockBuys) revert Blocked(RuleId.BUYS_UNLOCK_SELLS); Wallet storage w = _wallets[t.token][who]; if (_isOn(r, RuleId.DIAMOND) && now_ < uint256(w.lastBuy) + r.diamondSeconds) revert Blocked(RuleId.DIAMOND); if (_isOn(r, RuleId.COOLDOWN) && w.lastTrade != 0 && now_ < uint256(w.lastTrade) + r.cooldownSeconds) { revert Blocked(RuleId.COOLDOWN); } if (_jailed(t.token, r, t.from) || _jailed(t.token, r, tx.origin)) revert Blocked(RuleId.SNIPER_JAIL); if (_has(r, RuleId.DIP_ONLY)) { uint160 p = sqrtPriceOf(t.token); if (s.peak == 0 || p < s.peak) s.peak = p; } if (_has(r, RuleId.COOLDOWN)) w.lastTrade = uint40(now_); if (_has(r, RuleId.BUYS_UNLOCK_SELLS)) s.buysSinceSell = 0; if (_has(r, RuleId.CHAPTERS)) s.volume += uint128(t.amount); } function _send(T memory t, Rules memory r, Stats storage s) internal { if (!_tracked(t.token, t.from)) return; // coins out of the hook or the coin itself: the launch, never a holder if (_isOn(r, RuleId.POOL_ONLY)) revert Blocked(RuleId.POOL_ONLY); if (t.from == t.creator) _devLock(t, r, s, t.amount); // a send leaves the creator's wallet like a sell if (_jailed(t.token, r, t.from)) revert Blocked(RuleId.SNIPER_JAIL); if (t.to != t.creator) _holdCaps(t, r); } function _holdCaps(T memory t, Rules memory r) internal view { if (t.toBal + t.amount > _maxWallet(t.token, r, t.start)) { if (_isOn(r, RuleId.MAX_WALLET)) revert Blocked(RuleId.MAX_WALLET); if (_isOn(r, RuleId.RISING_MAX_WALLET)) revert Blocked(RuleId.RISING_MAX_WALLET); revert Blocked(RuleId.CHAPTERS); } if (_isOn(r, RuleId.HOLDER_GATED)) { address who = t.to.code.length == 0 ? t.to : tx.origin; if (IERC20Balance(r.gateToken).balanceOf(who) < r.gateMin) revert Blocked(RuleId.HOLDER_GATED); } } /// @dev Dev lock: nothing leaves the creator's wallet before the lock ends; after that pieces of at most the cap, /// spaced out by the gap, sells and sends alike (audit 30.10.: a send of the whole bag to a fresh wallet /// would have gone around the cap). Coins the creator sent on are free in the receiving wallet: the cap and /// the gap already bound how fast they could leave. function _devLock(T memory t, Rules memory r, Stats storage s, uint256 amount) internal { if (!_isOn(r, RuleId.DEV_LOCK)) return; uint256 now_ = block.timestamp; if (now_ < t.start + r.devLockSeconds) revert Blocked(RuleId.DEV_LOCK); if (amount > _of(r.devCapBps)) revert Blocked(RuleId.DEV_LOCK); if (s.devLastSend != 0 && now_ < uint256(s.devLastSend) + r.devGapSeconds) revert Blocked(RuleId.DEV_LOCK); s.devLastSend = uint40(now_); } function _jailed(address token, Rules memory r, address a) internal view returns (bool) { return _has(r, RuleId.SNIPER_JAIL) && block.timestamp < _wallets[token][a].jailUntil; } function _maxWallet(address token, Rules memory r, uint256 start) internal view returns (uint256 cap) { cap = type(uint256).max; if (_isOn(r, RuleId.MAX_WALLET)) cap = _min(cap, _of(r.maxWalletBps)); if (_isOn(r, RuleId.RISING_MAX_WALLET)) { uint256 steps = (block.timestamp - start) / r.riseSeconds; uint256 b = r.riseStepBps == 0 ? (steps >= 14 ? 10_000 : uint256(r.riseStartBps) << steps) : uint256(r.riseStartBps) + uint256(r.riseStepBps) * steps; cap = _min(cap, _of(_min(b, 10_000))); } if (_isOn(r, RuleId.CHAPTERS)) { uint256 ch = _stats[token].volume / r.chapterVolume; uint256 b = ch >= 14 ? 10_000 : uint256(r.chapterStartBps) << ch; cap = _min(cap, _of(_min(b, 10_000))); } } function _marketOpen(Rules memory r) internal view returns (bool) { uint256 day = (block.timestamp / 86_400 + 4) % 7; // 1970-01-01 was a Thursday if (r.weekdays & (1 << day) == 0) return false; uint256 h = (block.timestamp / 3600) % 24; return r.openHour < r.closeHour ? (h >= r.openHour && h < r.closeHour) : (h >= r.openHour || h < r.closeHour); } function _reactiveCapBps(Rules memory r, Stats storage s) internal view returns (uint256) { int256 diff = int256(soldBpsOf(r.partner)) - int256(uint256(s.partnerAtStart)); int256 cap = int256(uint256(r.reactBaseBps)) + diff * int256(uint256(r.reactSensitivity)) / 100; if (cap < 1) return 1; if (cap > 10_000) return 10_000; return uint256(cap); } // ---------------------------------------------------------------- pots (HYPE) /// @notice Anyone can feed a coin's jackpot. function fundJackpot(address token) external payable { _withRule(token, RuleId.JACKPOT); _pots[token].jackpot += uint128(msg.value); emit PotFunded(token, true, msg.sender, msg.value); } /// @notice Anyone can feed a coin's buyer rewards. Only the creator can take back what is not owed. function fundRewards(address token) external payable { _withRule(token, RuleId.BUYER_REWARDS); _pots[token].rewards += uint128(msg.value); emit PotFunded(token, false, msg.sender, msg.value); } function withdrawRewards(address token, uint256 amount) external { if (msg.sender != IRuleCoin(token).creator()) revert NotCreator(); Pots storage pt = _pots[token]; if (amount > pt.rewards) revert Bad("amount"); pt.rewards -= uint128(amount); emit RewardsWithdrawn(token, amount); _pay(msg.sender, amount); } /// @notice Pays the jackpot to the last buyer once nobody bought for the silence time. function settleJackpot(address token) external { _settleJackpot(token, rulesOf(token)); } function claim(address token) external { _claim(token, msg.sender); } /// @notice Pays `who` what this coin owes them (a won jackpot, buyer rewards). Anyone may trigger it (the eleos /// keeper does, so nobody has to come back for it); the HYPE only ever goes to `who`. function claimFor(address token, address who) external { _claim(token, who); } function _claim(address token, address who) internal { Rules memory r = rulesOf(token); if (_has(r, RuleId.JACKPOT)) _settleJackpot(token, r); uint256 a = owed[token][who]; if (a == 0) revert NothingOwed(); owed[token][who] = 0; _pots[token].owedTotal -= uint128(a); emit Claimed(token, who, a); _pay(who, a); } function _settleJackpot(address token, Rules memory r) internal { Pots storage pt = _pots[token]; address w = pt.jackpotLast; if (w == address(0) || block.timestamp < uint256(pt.jackpotTime) + r.jackpotSilence) return; uint256 win = uint256(pt.jackpot) * r.jackpotShareBps / 10_000; pt.jackpotLast = address(0); pt.jackpot -= uint128(win); owed[token][w] += win; pt.owedTotal += uint128(win); emit JackpotWon(token, w, win); } function _withRule(address token, uint8 id) internal view { if (!_coin(token)) revert NotCoin(); if (!_has(rulesOf(token), id)) revert Bad("no such pot"); } function _pay(address to, uint256 amount) internal { (bool ok,) = to.call{value: amount}(""); if (!ok) revert PayFailed(); } // ---------------------------------------------------------------- helpers function _isOn(Rules memory r, uint8 id) internal view returns (bool) { if (r.mask & (uint64(1) << id) == 0) return false; uint32 u = r.until[id]; return u == 0 || block.timestamp < u; } function _has(Rules memory r, uint8 id) internal pure returns (bool) { return r.mask & (uint64(1) << id) != 0; } function _on(uint64 m, uint8 id) internal pure returns (bool) { return m & (uint64(1) << id) != 0; } function _of(uint256 b) internal pure returns (uint256) { return SUPPLY * b / 10_000; } function _min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function _bps(uint256 v, uint256 min, string memory what) internal pure { if (v < min || v > 10_000) revert Bad(what); } function _time(uint256 v, uint256 min, uint256 max, string memory what) internal pure { if (v < min || v > max) revert Bad(what); } }
../../lib/v4-core/src/interfaces/IPoolManager.sol218 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {Currency} from "../types/Currency.sol"; import {PoolKey} from "../types/PoolKey.sol"; import {IHooks} from "./IHooks.sol"; import {IERC6909Claims} from "./external/IERC6909Claims.sol"; import {IProtocolFees} from "./IProtocolFees.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; import {PoolId} from "../types/PoolId.sol"; import {IExtsload} from "./IExtsload.sol"; import {IExttload} from "./IExttload.sol"; import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol"; /// @notice Interface for the PoolManager interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload { /// @notice Thrown when a currency is not netted out after the contract is unlocked error CurrencyNotSettled(); /// @notice Thrown when trying to interact with a non-initialized pool error PoolNotInitialized(); /// @notice Thrown when unlock is called, but the contract is already unlocked error AlreadyUnlocked(); /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not error ManagerLocked(); /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow error TickSpacingTooLarge(int24 tickSpacing); /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize error TickSpacingTooSmall(int24 tickSpacing); /// @notice PoolKey must have currencies where address(currency0) < address(currency1) error CurrenciesOutOfOrderOrEqual(address currency0, address currency1); /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook, /// or on a pool that does not have a dynamic swap fee. error UnauthorizedDynamicLPFeeUpdate(); /// @notice Thrown when trying to swap amount of 0 error SwapAmountCannotBeZero(); ///@notice Thrown when native currency is passed to a non native settlement error NonzeroNativeValue(); /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta. error MustClearExactPositiveDelta(); /// @notice Emitted when a new pool is initialized /// @param id The abi encoded hash of the pool key struct for the new pool /// @param currency0 The first currency of the pool by address sort order /// @param currency1 The second currency of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param hooks The hooks contract address for the pool, or address(0) if none /// @param sqrtPriceX96 The price of the pool on initialization /// @param tick The initial tick of the pool corresponding to the initialized price event Initialize( PoolId indexed id, Currency indexed currency0, Currency indexed currency1, uint24 fee, int24 tickSpacing, IHooks hooks, uint160 sqrtPriceX96, int24 tick ); /// @notice Emitted when a liquidity position is modified /// @param id The abi encoded hash of the pool key struct for the pool that was modified /// @param sender The address that modified the pool /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param liquidityDelta The amount of liquidity that was added or removed /// @param salt The extra data to make positions unique event ModifyLiquidity( PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt ); /// @notice Emitted for swaps between currency0 and currency1 /// @param id The abi encoded hash of the pool key struct for the pool that was modified /// @param sender The address that initiated the swap call, and that received the callback /// @param amount0 The delta of the currency0 balance of the pool /// @param amount1 The delta of the currency1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of the price of the pool after the swap /// @param fee The swap fee in hundredths of a bip event Swap( PoolId indexed id, address indexed sender, int128 amount0, int128 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint24 fee ); /// @notice Emitted for donations /// @param id The abi encoded hash of the pool key struct for the pool that was donated to /// @param sender The address that initiated the donate call /// @param amount0 The amount donated in currency0 /// @param amount1 The amount donated in currency1 event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1); /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract. /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee` /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)` /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)` function unlock(bytes calldata data) external returns (bytes memory); /// @notice Initialize the state for a given pool ID /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee /// @param key The pool key for the pool to initialize /// @param sqrtPriceX96 The initial square root price /// @return tick The initial tick of the pool function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick); /// @notice Modify the liquidity for the given pool /// @dev Poke by calling with a zero liquidityDelta /// @param key The pool to modify liquidity in /// @param params The parameters for modifying the liquidity /// @param hookData The data to pass through to the add/removeLiquidity hooks /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued) /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData) external returns (BalanceDelta callerDelta, BalanceDelta feesAccrued); /// @notice Swap against the given pool /// @param key The pool to swap in /// @param params The parameters for swapping /// @param hookData The data to pass through to the swap hooks /// @return swapDelta The balance delta of the address swapping /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified. /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta. function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData) external returns (BalanceDelta swapDelta); /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds. /// Donors should keep this in mind when designing donation mechanisms. /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)). /// Read the comments in `Pool.swap()` for more information about this. /// @param key The key of the pool to donate to /// @param amount0 The amount of currency0 to donate /// @param amount1 The amount of currency1 to donate /// @param hookData The data to pass through to the donate hooks /// @return BalanceDelta The delta of the caller after the donate function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) external returns (BalanceDelta); /// @notice Writes the current ERC20 balance of the specified currency to transient storage /// This is used to checkpoint balances for the manager and derive deltas for the caller. /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped /// for native tokens because the amount to settle is determined by the sent value. /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle /// native funds, this function can be called with the native currency to then be able to settle the native currency function sync(Currency currency) external; /// @notice Called by the user to net out some value owed to the user /// @dev Will revert if the requested amount is not available, consider using `mint` instead /// @dev Can also be used as a mechanism for free flash loans /// @param currency The currency to withdraw from the pool manager /// @param to The address to withdraw to /// @param amount The amount of currency to withdraw function take(Currency currency, address to, uint256 amount) external; /// @notice Called by the user to pay what is owed /// @return paid The amount of currency settled function settle() external payable returns (uint256 paid); /// @notice Called by the user to pay on behalf of another address /// @param recipient The address to credit for the payment /// @return paid The amount of currency settled function settleFor(address recipient) external payable returns (uint256 paid); /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently. /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer. /// @dev This could be used to clear a balance that is considered dust. /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared. function clear(Currency currency, uint256 amount) external; /// @notice Called by the user to move value into ERC6909 balance /// @param to The address to mint the tokens to /// @param id The currency address to mint to ERC6909s, as a uint256 /// @param amount The amount of currency to mint /// @dev The id is converted to a uint160 to correspond to a currency address /// If the upper 12 bytes are not 0, they will be 0-ed out function mint(address to, uint256 id, uint256 amount) external; /// @notice Called by the user to move value from ERC6909 balance /// @param from The address to burn the tokens from /// @param id The currency address to burn from ERC6909s, as a uint256 /// @param amount The amount of currency to burn /// @dev The id is converted to a uint160 to correspond to a currency address /// If the upper 12 bytes are not 0, they will be 0-ed out function burn(address from, uint256 id, uint256 amount) external; /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees. /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee /// @param key The key of the pool to update dynamic LP fees for /// @param newDynamicLPFee The new dynamic pool LP fee function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external; }
src/EngineBase.sol133 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol"; import {IHooks} from "v4-core/interfaces/IHooks.sol"; import {StateLibrary} from "v4-core/libraries/StateLibrary.sol"; import {TickMath} from "v4-core/libraries/TickMath.sol"; import {FullMath} from "v4-core/libraries/FullMath.sol"; import {PoolKey} from "v4-core/types/PoolKey.sol"; import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol"; import {Currency, CurrencyLibrary} from "v4-core/types/Currency.sol"; import {IRuleEngine, IRuleCoin, Script} from "./IRuleEngine.sol"; /// @notice What both engines share: the pool every coin of the mode trades in (native HYPE against the coin, fee 0, /// tick spacing 200, the eleos hook), prices read from the pool's tick, and the one launcher they serve. /// On Elysium `block.number` is the parent chain's block, so nothing here counts blocks: only seconds. /// The coin is currency1, so the pool's price P is coins per HYPE and the coin's price in HYPE is 1 / P. The /// whole supply starts as one position from the start price down, so the share of it sold at a price is /// 1 - sqrt(P) / sqrt(P_start). abstract contract EngineBase is IRuleEngine { using StateLibrary for IPoolManager; using PoolIdLibrary for PoolKey; error Blocked(uint8 rule); error Refused(); event Bound(address indexed launcher); int24 internal constant TICK_SPACING = 200; address internal constant DEAD = 0x000000000000000000000000000000000000dEaD; IPoolManager public immutable poolManager; address public immutable override hook; int24 public immutable override startTick; uint160 public immutable startSqrt; address internal immutable setter; /// @notice The launcher whose coins this engine serves (set once by the deployer). address public launcher; constructor(IPoolManager pm, address hook_, int24 startTick_, address setter_) { if (address(pm) == address(0) || hook_ == address(0) || setter_ == address(0)) revert Refused(); poolManager = pm; hook = hook_; startTick = startTick_; startSqrt = TickMath.getSqrtPriceAtTick(startTick_); setter = setter_; } /// @notice Names the launcher once. Its coins are the only ones the engine's pots and coin links accept. function bind(address l) external { if (msg.sender != setter || launcher != address(0) || l == address(0)) revert Refused(); launcher = l; emit Bound(l); } function poolIdOf(address token) public view returns (PoolId) { return PoolKey({ currency0: CurrencyLibrary.ADDRESS_ZERO, currency1: Currency.wrap(token), fee: 0, tickSpacing: TICK_SPACING, hooks: IHooks(hook) }).toId(); } function sqrtPriceOf(address token) public view returns (uint160 p) { (p,,,) = poolManager.getSlot0(poolIdOf(token)); } /// @notice Share of the coin's curve sold at today's price, in basis points. function soldBpsOf(address token) public view returns (uint256) { return _sold(sqrtPriceOf(token)); } function _sold(uint160 p) internal view returns (uint256) { uint256 s = startSqrt; if (p == 0 || p >= s) return 0; return 10_000 - uint256(p) * 10_000 / s; } /// @dev The coin's price at sqrt price `p` against its price at `ref`, in basis points: (ref / p)^2. function _ratio(uint160 ref, uint160 p) internal pure returns (uint256) { if (p == 0) return 0; uint256 a = FullMath.mulDiv(10_000, ref, p); if (a > type(uint128).max) return type(uint40).max; uint256 r = FullMath.mulDiv(a, ref, p); return r > type(uint40).max ? type(uint40).max : r; } /// @notice Where a coin keeps its rule words: the contract the coin created first (nonce 1). function dataOf(address token) public pure returns (address) { return address(uint160(uint256(keccak256(abi.encodePacked(bytes2(0xd694), token, bytes1(0x01)))))); } /// @notice A coin's rules as fixed at launch: its rule words, the release time of locked lots, the creator and the /// launch time. function scriptOf(address token) public view returns (Script memory sc) { address d = dataOf(token); uint256 size = d.code.length; if (size >= 33) { uint256 n = (size - 33) / 32; if (n > 8) n = 8; sc.n = n; uint256[8] memory rows; uint256 rel; assembly ("memory-safe") { let p := mload(0x40) extcodecopy(d, p, 1, 0x20) rel := mload(p) extcodecopy(d, rows, 33, mul(n, 0x20)) } sc.rows = rows; sc.release = rel; } sc.creator = IRuleCoin(token).creator(); sc.start = IRuleCoin(token).launchedAt(); } /// @dev Holders: everyone but the pool manager, the hook, the coin itself and the burn addresses. function _tracked(address token, address a) internal view returns (bool) { return a != address(poolManager) && a != hook && a != token && a != DEAD && a != address(0); } function _coin(address token) internal view returns (bool) { address l = launcher; return l != address(0) && ICoinListE(l).isCoin(token); } } interface ICoinListE { function isCoin(address) external view returns (bool); }
src/IRuleEngine.sol54 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; /// @notice The engine of a rule coin: the rule logic of a launch mode, deployed once and shared by every coin of that /// mode, so each coin stays small enough to launch in one transaction under Elysium's gas cap. A coin calls its /// engine on every transfer that is not between two excluded addresses (pool manager, hook, the coin itself, /// the burn addresses). The engine keeps each coin's state under the coin's own address, so a contract that /// calls it only ever touches its own state. interface IRuleEngine { struct Move { address from; address to; uint256 amount; uint256 fromBal; // balances before the transfer uint256 toBal; uint256 pot; // the coin's own balance before the transfer (coins whose rules keep coins as a prize) } /// @notice Runs the rules for one transfer of the calling coin and reverts with `Blocked(rule)` when one refuses. /// The engine reads the coin's rule words from the coin's data contract. /// Returns the coins of a buy that go to the dead address and into the coin's pot, and the coins the buyer /// gets out of the pot on top. function onMove(Move calldata m) external returns (uint256 burn, uint256 toPot, uint256 drop); /// @notice The launcher tells the engine about a new coin before its pool opens (what a rule measures from). function opened(address token) external; /// @notice Reverts with the reason when a coin with these rule words cannot launch. function validate(uint256[] calldata rows, uint32 release) external view; function hook() external view returns (address); function startTick() external view returns (int24); } /// @notice A coin's rules as fixed at launch. struct Script { uint256[8] rows; // the first `n` are the rule words uint256 n; uint256 release; // rules that lock coins: seconds a locked lot takes to unlock (0 for Vows) address creator; uint256 start; // launch time } /// @notice What the engines read from a coin (its rule words come from its data contract, see EngineBase). interface IRuleCoin { function creator() external view returns (address); function launchedAt() external view returns (uint64); function balanceOf(address) external view returns (uint256); } interface ICoinList { function isCoin(address) external view returns (bool); }
src/rules/RuleWords.sol236 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; /// @title rule words of Vows /// @notice Rule ids are fixed numbers the site shares with the contracts (gaps are rules that are not offered). A coin carries /// up to eight rules, one word each: /// /// bits 0..7 id /// bits 8..39 until: unix seconds after which the rule is off, 0 = forever /// bits 40..255 the rule's numbers, packed one after the other in the order of `RuleWords` below (unused bits 0) /// /// Shares are basis points of the total supply (1 = 0.01 %), times in seconds, coin amounts in whole coins, HYPE in wei. /// Not on Elysium: GAS_CAP (28). Elysium orders transactions by arrival and ignores priority tips, so every /// transaction pays the same gas price and a cap on it would refuse nobody. library RuleId { uint8 internal constant MAX_WALLET = 1; // maxWalletBps u16 uint8 internal constant MAX_TRADE = 2; // maxTradeBps u16 uint8 internal constant ANTI_DUMP = 3; // dumpBuyBps u16, dumpSellBps u16 uint8 internal constant SELL_CURVE = 4; // curveSmallBps u16, curveFloorBps u16, curveBigBagBps u16 uint8 internal constant ANTI_BUNDLE = 5; // buysPerSecond u16 (per second: Elysium has no block count of its own) uint8 internal constant CHAPTERS = 6; // chapterStartBps u16, chapterVolume u64 whole coins uint8 internal constant POOL_ONLY = 7; uint8 internal constant HOLDER_GATED = 8; // gateToken address, gateMin mantissa u48, gateMin exponent u8 (raw units) uint8 internal constant P2P_ONLY = 9; uint8 internal constant RISING_MAX_WALLET = 10; // riseStartBps u16, riseStepBps u16 (0 = doubling), riseSeconds u32 uint8 internal constant TAPER = 11; // taperStartBps u16, taperEndBps u16, taperSoldBps u16 uint8 internal constant RAISE = 12; // raiseBps u16, raiseReset u32 uint8 internal constant NO_REPEAT = 13; uint8 internal constant BUYS_UNLOCK_SELLS = 14; // unlockBuys u16 uint8 internal constant MARKET_HOURS = 15; // openHour u8, closeHour u8, weekdays u8 (bit 0 = Sunday), sellsOpen u8 uint8 internal constant SELL_WINDOW = 16; // sellWindow u32, sellPeriod u32 uint8 internal constant THE_CLUB = 17; // clubMax u32 uint8 internal constant MIN_BUY = 18; // minBuy u64 whole coins uint8 internal constant SLOW_MODE = 19; // slowSeconds u32 uint8 internal constant TICK_TOCK = 20; // tickSeconds u32 uint8 internal constant DEV_LOCK = 21; // devLockSeconds u32, devCapBps u16, devGapSeconds u32 uint8 internal constant COOLDOWN = 22; // cooldownSeconds u32 uint8 internal constant BUY_LIMIT = 23; // buyLimit u16 uint8 internal constant DIAMOND = 24; // diamondSeconds u32 uint8 internal constant SNIPER_JAIL = 25; // jailWindow u32, jailSeconds u32 uint8 internal constant BUYER_REWARDS = 31; // rewardPerBuy u96 wei, rewardMinBuy u64 whole coins, rewardEveryN u16 uint8 internal constant ENTANGLED = 34; // beacon address, beaconTargetBps u16 uint8 internal constant REACTIVE = 35; // partner address, reactBaseBps u16, reactSensitivity u16 (percent) uint8 internal constant JACKPOT = 36; // jackpotSilence u32, jackpotShareBps u16, jackpotMinBuy u64 whole coins uint8 internal constant DIP_ONLY = 37; // dipBps u16 uint8 internal constant OPENING_BELL = 38; // bellSeconds u32, bellSoldBps u16 uint256 internal constant COUNT = 39; uint64 internal constant KNOWN = (uint64(1) << 1) | (uint64(1) << 2) | (uint64(1) << 3) | (uint64(1) << 4) | (uint64(1) << 5) | (uint64(1) << 6) | (uint64(1) << 7) | (uint64(1) << 8) | (uint64(1) << 9) | (uint64(1) << 10) | (uint64(1) << 11) | (uint64(1) << 12) | (uint64(1) << 13) | (uint64(1) << 14) | (uint64(1) << 15) | (uint64(1) << 16) | (uint64(1) << 17) | (uint64(1) << 18) | (uint64(1) << 19) | (uint64(1) << 20) | (uint64(1) << 21) | (uint64(1) << 22) | (uint64(1) << 23) | (uint64(1) << 24) | (uint64(1) << 25) | (uint64(1) << 31) | (uint64(1) << 34) | (uint64(1) << 35) | (uint64(1) << 36) | (uint64(1) << 37) | (uint64(1) << 38); /// @notice Bits of numbers each rule packs from bit 40 on (the rest of the word must be 0). function bitsOf(uint8 id) internal pure returns (uint256) { if (id == MAX_WALLET || id == MAX_TRADE || id == ANTI_BUNDLE || id == BUYS_UNLOCK_SELLS) return 16; if (id == BUY_LIMIT || id == DIP_ONLY) return 16; if (id == ANTI_DUMP) return 32; if (id == SELL_CURVE || id == TAPER) return 48; if (id == CHAPTERS) return 80; if (id == POOL_ONLY || id == P2P_ONLY || id == NO_REPEAT) return 0; if (id == HOLDER_GATED) return 216; if (id == RISING_MAX_WALLET) return 64; if (id == RAISE || id == OPENING_BELL) return 48; if (id == MARKET_HOURS) return 32; if (id == SELL_WINDOW || id == SNIPER_JAIL) return 64; if (id == THE_CLUB || id == SLOW_MODE || id == TICK_TOCK || id == COOLDOWN || id == DIAMOND) return 32; if (id == MIN_BUY) return 64; if (id == DEV_LOCK) return 80; if (id == BUYER_REWARDS) return 176; if (id == ENTANGLED) return 176; if (id == REACTIVE) return 192; if (id == JACKPOT) return 112; return 0; } } /// @notice A coin's rules, unpacked from its words for one transfer. struct Rules { uint64 mask; uint32[39] until; // who can hold uint16 maxWalletBps; // 1 uint16 riseStartBps; // 10 uint16 riseStepBps; // 10, 0 = doubling uint32 riseSeconds; // 10 uint16 chapterStartBps; // 6 uint256 chapterVolume; // 6, raw units uint32 clubMax; // 17 address gateToken; // 8 uint256 gateMin; // 8, raw units of the gate token // how you buy uint16 maxTradeBps; // 2 uint16 buysPerSecond; // 5 uint16 raiseBps; // 12 uint32 raiseReset; // 12 uint256 minBuy; // 18, raw units uint32 slowSeconds; // 19 uint16 buyLimit; // 23 // how you sell uint16 dumpBuyBps; // 3 uint16 dumpSellBps; // 3 uint16 curveSmallBps; // 4 uint16 curveFloorBps; // 4 uint16 curveBigBagBps; // 4 uint16 taperStartBps; // 11 uint16 taperEndBps; // 11 uint16 taperSoldBps; // 11 uint16 unlockBuys; // 14 uint32 devLockSeconds; // 21 uint16 devCapBps; // 21 uint32 devGapSeconds; // 21 uint32 diamondSeconds; // 24 uint32 cooldownSeconds; // 22 uint32 jailWindow; // 25 uint32 jailSeconds; // 25 // when it trades uint8 openHour; // 15 uint8 closeHour; // 15 uint8 weekdays; // 15 bool sellsOpen; // 15 uint32 sellWindow; // 16 uint32 sellPeriod; // 16 uint32 tickSeconds; // 20 uint32 bellSeconds; // 38 uint16 bellSoldBps; // 38 // who gets paid (HYPE pots in the engine) uint256 rewardPerBuy; // 31, wei uint256 rewardMinBuy; // 31, raw units uint16 rewardEveryN; // 31 uint32 jackpotSilence; // 36 uint16 jackpotShareBps; // 36 uint256 jackpotMinBuy; // 36, raw units // links and games uint16 dipBps; // 37 address beacon; // 34 uint16 beaconTargetBps; // 34 address partner; // 35 uint16 reactBaseBps; // 35 uint16 reactSensitivity; // 35 } library RuleWords { function decode(uint256[] memory w) internal pure returns (Rules memory r) { uint256[8] memory f; uint256 n = w.length > 8 ? 8 : w.length; for (uint256 i; i < n; i++) { f[i] = w[i]; } return decode(f, n); } function decode(uint256[8] memory w, uint256 n) internal pure returns (Rules memory r) { if (n > 8) n = 8; for (uint256 i; i < n; i++) { uint256 x = w[i]; uint8 id = uint8(x); if (id >= RuleId.COUNT) continue; // never launches (the validator refuses it) r.mask |= uint64(1) << id; r.until[id] = uint32(x >> 8); _params(r, id, x >> 40); } } function _params(Rules memory r, uint8 id, uint256 p) private pure { if (id == RuleId.MAX_WALLET) { r.maxWalletBps = uint16(p); } else if (id == RuleId.MAX_TRADE) { r.maxTradeBps = uint16(p); } else if (id == RuleId.ANTI_DUMP) { (r.dumpBuyBps, r.dumpSellBps) = (uint16(p), uint16(p >> 16)); } else if (id == RuleId.SELL_CURVE) { (r.curveSmallBps, r.curveFloorBps, r.curveBigBagBps) = (uint16(p), uint16(p >> 16), uint16(p >> 32)); } else if (id == RuleId.ANTI_BUNDLE) { r.buysPerSecond = uint16(p); } else if (id == RuleId.CHAPTERS) { (r.chapterStartBps, r.chapterVolume) = (uint16(p), uint256(uint64(p >> 16)) * 1 ether); } else if (id == RuleId.HOLDER_GATED) { r.gateToken = address(uint160(p)); uint256 e = uint8(p >> 208); r.gateMin = e > 60 ? type(uint256).max : uint256(uint48(p >> 160)) * 10 ** e; } else if (id == RuleId.RISING_MAX_WALLET) { (r.riseStartBps, r.riseStepBps, r.riseSeconds) = (uint16(p), uint16(p >> 16), uint32(p >> 32)); } else if (id == RuleId.TAPER) { (r.taperStartBps, r.taperEndBps, r.taperSoldBps) = (uint16(p), uint16(p >> 16), uint16(p >> 32)); } else if (id == RuleId.RAISE) { (r.raiseBps, r.raiseReset) = (uint16(p), uint32(p >> 16)); } else if (id == RuleId.BUYS_UNLOCK_SELLS) { r.unlockBuys = uint16(p); } else if (id == RuleId.MARKET_HOURS) { (r.openHour, r.closeHour, r.weekdays, r.sellsOpen) = (uint8(p), uint8(p >> 8), uint8(p >> 16), uint8(p >> 24) != 0); } else if (id == RuleId.SELL_WINDOW) { (r.sellWindow, r.sellPeriod) = (uint32(p), uint32(p >> 32)); } else if (id == RuleId.THE_CLUB) { r.clubMax = uint32(p); } else if (id == RuleId.MIN_BUY) { r.minBuy = uint256(uint64(p)) * 1 ether; } else if (id == RuleId.SLOW_MODE) { r.slowSeconds = uint32(p); } else if (id == RuleId.TICK_TOCK) { r.tickSeconds = uint32(p); } else if (id == RuleId.DEV_LOCK) { (r.devLockSeconds, r.devCapBps, r.devGapSeconds) = (uint32(p), uint16(p >> 32), uint32(p >> 48)); } else if (id == RuleId.COOLDOWN) { r.cooldownSeconds = uint32(p); } else if (id == RuleId.BUY_LIMIT) { r.buyLimit = uint16(p); } else if (id == RuleId.DIAMOND) { r.diamondSeconds = uint32(p); } else if (id == RuleId.SNIPER_JAIL) { (r.jailWindow, r.jailSeconds) = (uint32(p), uint32(p >> 32)); } else if (id == RuleId.BUYER_REWARDS) { (r.rewardPerBuy, r.rewardMinBuy, r.rewardEveryN) = (uint96(p), uint256(uint64(p >> 96)) * 1 ether, uint16(p >> 160)); } else if (id == RuleId.ENTANGLED) { (r.beacon, r.beaconTargetBps) = (address(uint160(p)), uint16(p >> 160)); } else if (id == RuleId.REACTIVE) { (r.partner, r.reactBaseBps, r.reactSensitivity) = (address(uint160(p)), uint16(p >> 160), uint16(p >> 176)); } else if (id == RuleId.JACKPOT) { (r.jackpotSilence, r.jackpotShareBps, r.jackpotMinBuy) = (uint32(p), uint16(p >> 32), uint256(uint64(p >> 48)) * 1 ether); } else if (id == RuleId.DIP_ONLY) { r.dipBps = uint16(p); } else if (id == RuleId.OPENING_BELL) { (r.bellSeconds, r.bellSoldBps) = (uint32(p), uint16(p >> 32)); } } // ---- building words (the tests and the deploy checks use these; the site packs the same way) function word(uint8 id, uint32 until_, uint256 params) internal pure returns (uint256) { return uint256(id) | (uint256(until_) << 8) | (params << 40); } }
../../lib/v4-core/src/types/Currency.sol120 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol"; import {CustomRevert} from "../libraries/CustomRevert.sol"; type Currency is address; using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global; using CurrencyLibrary for Currency global; function equals(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) == Currency.unwrap(other); } function greaterThan(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) > Currency.unwrap(other); } function lessThan(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) < Currency.unwrap(other); } function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) >= Currency.unwrap(other); } /// @title CurrencyLibrary /// @dev This library allows for transferring and holding native tokens and ERC20 tokens library CurrencyLibrary { /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails error NativeTransferFailed(); /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails error ERC20TransferFailed(); /// @notice A constant to represent the native currency Currency public constant ADDRESS_ZERO = Currency.wrap(address(0)); function transfer(Currency currency, address to, uint256 amount) internal { // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol // modified custom error selectors bool success; if (currency.isAddressZero()) { assembly ("memory-safe") { // Transfer the ETH and revert if it fails. success := call(gas(), to, amount, 0, 0, 0, 0) } // revert with NativeTransferFailed, containing the bubbled up error as an argument if (!success) { CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector); } } else { assembly ("memory-safe") { // Get a pointer to some free memory. let fmp := mload(0x40) // Write the abi-encoded calldata into memory, beginning with the function selector. mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument. mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type. success := and( // Set success to whether the call reverted, if not we check it either // returned exactly 1 (can't just be non-zero data), or had no return data. or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())), // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2. // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. // Counterintuitively, this call must be positioned second to the or() call in the // surrounding and() call or else returndatasize() will be zero during the computation. call(gas(), currency, 0, fmp, 68, 0, 32) ) // Now clean the memory we used mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here } // revert with ERC20TransferFailed, containing the bubbled up error as an argument if (!success) { CustomRevert.bubbleUpAndRevertWith( Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector ); } } } function balanceOfSelf(Currency currency) internal view returns (uint256) { if (currency.isAddressZero()) { return address(this).balance; } else { return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this)); } } function balanceOf(Currency currency, address owner) internal view returns (uint256) { if (currency.isAddressZero()) { return owner.balance; } else { return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner); } } function isAddressZero(Currency currency) internal pure returns (bool) { return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO); } function toId(Currency currency) internal pure returns (uint256) { return uint160(Currency.unwrap(currency)); } // If the upper 12 bytes are non-zero, they will be zero-ed out // Therefore, fromId() and toId() are not inverses of each other function fromId(uint256 id) internal pure returns (Currency) { return Currency.wrap(address(uint160(id))); } }
../../lib/v4-core/src/types/PoolKey.sol23 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Currency} from "./Currency.sol"; import {IHooks} from "../interfaces/IHooks.sol"; import {PoolIdLibrary} from "./PoolId.sol"; using PoolIdLibrary for PoolKey global; /// @notice Returns the key for identifying a pool struct PoolKey { /// @notice The lower currency of the pool, sorted numerically Currency currency0; /// @notice The higher currency of the pool, sorted numerically Currency currency1; /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000 uint24 fee; /// @notice Ticks that involve positions must be a multiple of tick spacing int24 tickSpacing; /// @notice The hooks of the pool IHooks hooks; }
../../lib/v4-core/src/interfaces/IHooks.sol153 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolKey} from "../types/PoolKey.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol"; import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol"; /// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits /// of the address that the hooks contract is deployed to. /// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400 /// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used. /// See the Hooks library for the full spec. /// @dev Should only be callable by the v4 PoolManager. interface IHooks { /// @notice The hook called before the state of a pool is initialized /// @param sender The initial msg.sender for the initialize call /// @param key The key for the pool being initialized /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96 /// @return bytes4 The function selector for the hook function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4); /// @notice The hook called after the state of a pool is initialized /// @param sender The initial msg.sender for the initialize call /// @param key The key for the pool being initialized /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96 /// @param tick The current tick after the state of a pool is initialized /// @return bytes4 The function selector for the hook function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick) external returns (bytes4); /// @notice The hook called before liquidity is added /// @param sender The initial msg.sender for the add liquidity call /// @param key The key for the pool /// @param params The parameters for adding liquidity /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook /// @return bytes4 The function selector for the hook function beforeAddLiquidity( address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after liquidity is added /// @param sender The initial msg.sender for the add liquidity call /// @param key The key for the pool /// @param params The parameters for adding liquidity /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta /// @param feesAccrued The fees accrued since the last time fees were collected from this position /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook /// @return bytes4 The function selector for the hook /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency function afterAddLiquidity( address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, BalanceDelta delta, BalanceDelta feesAccrued, bytes calldata hookData ) external returns (bytes4, BalanceDelta); /// @notice The hook called before liquidity is removed /// @param sender The initial msg.sender for the remove liquidity call /// @param key The key for the pool /// @param params The parameters for removing liquidity /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeRemoveLiquidity( address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after liquidity is removed /// @param sender The initial msg.sender for the remove liquidity call /// @param key The key for the pool /// @param params The parameters for removing liquidity /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta /// @param feesAccrued The fees accrued since the last time fees were collected from this position /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook /// @return bytes4 The function selector for the hook /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency function afterRemoveLiquidity( address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, BalanceDelta delta, BalanceDelta feesAccrued, bytes calldata hookData ) external returns (bytes4, BalanceDelta); /// @notice The hook called before a swap /// @param sender The initial msg.sender for the swap call /// @param key The key for the pool /// @param params The parameters for the swap /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook /// @return bytes4 The function selector for the hook /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million) function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData) external returns (bytes4, BeforeSwapDelta, uint24); /// @notice The hook called after a swap /// @param sender The initial msg.sender for the swap call /// @param key The key for the pool /// @param params The parameters for the swap /// @param delta The amount owed to the caller (positive) or owed to the pool (negative) /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook /// @return bytes4 The function selector for the hook /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency function afterSwap( address sender, PoolKey calldata key, SwapParams calldata params, BalanceDelta delta, bytes calldata hookData ) external returns (bytes4, int128); /// @notice The hook called before donate /// @param sender The initial msg.sender for the donate call /// @param key The key for the pool /// @param amount0 The amount of token0 being donated /// @param amount1 The amount of token1 being donated /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeDonate( address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after donate /// @param sender The initial msg.sender for the donate call /// @param key The key for the pool /// @param amount0 The amount of token0 being donated /// @param amount1 The amount of token1 being donated /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook /// @return bytes4 The function selector for the hook function afterDonate( address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData ) external returns (bytes4); }
../../lib/v4-core/src/interfaces/external/IERC6909Claims.sol67 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice Interface for claims over a contract balance, wrapped as a ERC6909 interface IERC6909Claims { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event OperatorSet(address indexed owner, address indexed operator, bool approved); event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount); event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount); /*////////////////////////////////////////////////////////////// FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @notice Owner balance of an id. /// @param owner The address of the owner. /// @param id The id of the token. /// @return amount The balance of the token. function balanceOf(address owner, uint256 id) external view returns (uint256 amount); /// @notice Spender allowance of an id. /// @param owner The address of the owner. /// @param spender The address of the spender. /// @param id The id of the token. /// @return amount The allowance of the token. function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount); /// @notice Checks if a spender is approved by an owner as an operator /// @param owner The address of the owner. /// @param spender The address of the spender. /// @return approved The approval status. function isOperator(address owner, address spender) external view returns (bool approved); /// @notice Transfers an amount of an id from the caller to a receiver. /// @param receiver The address of the receiver. /// @param id The id of the token. /// @param amount The amount of the token. /// @return bool True, always, unless the function reverts function transfer(address receiver, uint256 id, uint256 amount) external returns (bool); /// @notice Transfers an amount of an id from a sender to a receiver. /// @param sender The address of the sender. /// @param receiver The address of the receiver. /// @param id The id of the token. /// @param amount The amount of the token. /// @return bool True, always, unless the function reverts function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool); /// @notice Approves an amount of an id to a spender. /// @param spender The address of the spender. /// @param id The id of the token. /// @param amount The amount of the token. /// @return bool True, always function approve(address spender, uint256 id, uint256 amount) external returns (bool); /// @notice Sets or removes an operator for the caller. /// @param operator The address of the operator. /// @param approved The approval status. /// @return bool True, always function setOperator(address operator, bool approved) external returns (bool); }
../../lib/v4-core/src/interfaces/IProtocolFees.sol53 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Currency} from "../types/Currency.sol"; import {PoolId} from "../types/PoolId.sol"; import {PoolKey} from "../types/PoolKey.sol"; /// @notice Interface for all protocol-fee related functions in the pool manager interface IProtocolFees { /// @notice Thrown when protocol fee is set too high error ProtocolFeeTooLarge(uint24 fee); /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller. error InvalidCaller(); /// @notice Thrown when collectProtocolFees is attempted on a token that is synced. error ProtocolFeeCurrencySynced(); /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController. event ProtocolFeeControllerUpdated(address indexed protocolFeeController); /// @notice Emitted when the protocol fee is updated for a pool. event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee); /// @notice Given a currency address, returns the protocol fees accrued in that currency /// @param currency The currency to check /// @return amount The amount of protocol fees accrued in the currency function protocolFeesAccrued(Currency currency) external view returns (uint256 amount); /// @notice Sets the protocol fee for the given pool /// @param key The key of the pool to set a protocol fee for /// @param newProtocolFee The fee to set function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external; /// @notice Sets the protocol fee controller /// @param controller The new protocol fee controller function setProtocolFeeController(address controller) external; /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected /// @dev This will revert if the contract is unlocked /// @param recipient The address to receive the protocol fees /// @param currency The currency to withdraw /// @param amount The amount of currency to withdraw /// @return amountCollected The amount of currency successfully withdrawn function collectProtocolFees(address recipient, Currency currency, uint256 amount) external returns (uint256 amountCollected); /// @notice Returns the current protocol fee controller address /// @return address The current protocol fee controller address function protocolFeeController() external view returns (address); }
../../lib/v4-core/src/types/BalanceDelta.sol73 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeCast} from "../libraries/SafeCast.sol"; /// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0 /// and the lower 128 bits represent the amount1. type BalanceDelta is int256; using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global; using BalanceDeltaLibrary for BalanceDelta global; using SafeCast for int256; function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) { assembly ("memory-safe") { balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1)) } } function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) { int256 res0; int256 res1; assembly ("memory-safe") { let a0 := sar(128, a) let a1 := signextend(15, a) let b0 := sar(128, b) let b1 := signextend(15, b) res0 := add(a0, b0) res1 := add(a1, b1) } return toBalanceDelta(res0.toInt128(), res1.toInt128()); } function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) { int256 res0; int256 res1; assembly ("memory-safe") { let a0 := sar(128, a) let a1 := signextend(15, a) let b0 := sar(128, b) let b1 := signextend(15, b) res0 := sub(a0, b0) res1 := sub(a1, b1) } return toBalanceDelta(res0.toInt128(), res1.toInt128()); } function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) { return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b); } function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) { return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b); } /// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type library BalanceDeltaLibrary { /// @notice A BalanceDelta of 0 BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0); function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) { assembly ("memory-safe") { _amount0 := sar(128, balanceDelta) } } function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) { assembly ("memory-safe") { _amount1 := signextend(15, balanceDelta) } } }
../../lib/v4-core/src/types/PoolId.sol18 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolKey} from "./PoolKey.sol"; type PoolId is bytes32; /// @notice Library for computing the ID of a pool library PoolIdLibrary { /// @notice Returns value equal to keccak256(abi.encode(poolKey)) function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) { assembly ("memory-safe") { // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes) poolId := keccak256(poolKey, 0xa0) } } }
../../lib/v4-core/src/interfaces/IExtsload.sol22 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice Interface for functions to access any storage slot in a contract interface IExtsload { /// @notice Called by external contracts to access granular pool state /// @param slot Key of slot to sload /// @return value The value of the slot as bytes32 function extsload(bytes32 slot) external view returns (bytes32 value); /// @notice Called by external contracts to access granular pool state /// @param startSlot Key of slot to start sloading from /// @param nSlots Number of slots to load into return value /// @return values List of loaded values. function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values); /// @notice Called by external contracts to access sparse pool state /// @param slots List of slots to SLOAD from. /// @return values List of loaded values. function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values); }
../../lib/v4-core/src/interfaces/IExttload.sol16 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; /// @notice Interface for functions to access any transient storage slot in a contract interface IExttload { /// @notice Called by external contracts to access transient storage of the contract /// @param slot Key of slot to tload /// @return value The value of the slot as bytes32 function exttload(bytes32 slot) external view returns (bytes32 value); /// @notice Called by external contracts to access sparse transient pool state /// @param slots List of slots to tload /// @return values List of loaded values function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values); }
../../lib/v4-core/src/types/PoolOperation.sol27 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {PoolKey} from "../types/PoolKey.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; /// @notice Parameter struct for `ModifyLiquidity` pool operations struct ModifyLiquidityParams { // the lower and upper tick of the position int24 tickLower; int24 tickUpper; // how to modify the liquidity int256 liquidityDelta; // a value to set if you want unique liquidity positions at the same range bytes32 salt; } /// @notice Parameter struct for `Swap` pool operations struct SwapParams { /// Whether to swap token0 for token1 or vice versa bool zeroForOne; /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut) int256 amountSpecified; /// The sqrt price at which, if reached, the swap will stop executing uint160 sqrtPriceLimitX96; }
../../lib/v4-core/src/libraries/StateLibrary.sol350 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolId} from "../types/PoolId.sol"; import {IPoolManager} from "../interfaces/IPoolManager.sol"; import {Position} from "./Position.sol"; /// @notice A helper library to provide state getters that use extsload library StateLibrary { /// @notice index of pools mapping in the PoolManager bytes32 public constant POOLS_SLOT = bytes32(uint256(6)); /// @notice index of feeGrowthGlobal0X128 in Pool.State uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1; // feeGrowthGlobal1X128 offset in Pool.State = 2 /// @notice index of liquidity in Pool.State uint256 public constant LIQUIDITY_OFFSET = 3; /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks; uint256 public constant TICKS_OFFSET = 4; /// @notice index of tickBitmap mapping in Pool.State uint256 public constant TICK_BITMAP_OFFSET = 5; /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions; uint256 public constant POSITIONS_OFFSET = 6; /** * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee * @dev Corresponds to pools[poolId].slot0 * @param manager The pool manager contract. * @param poolId The ID of the pool. * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision. * @return tick The current tick of the pool. * @return protocolFee The protocol fee of the pool. * @return lpFee The swap fee of the pool. */ function getSlot0(IPoolManager manager, PoolId poolId) internal view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); bytes32 data = manager.extsload(stateSlot); // 24 bits |24bits|24bits |24 bits|160 bits // 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7 // ---------- | fee |protocolfee | tick | sqrtPriceX96 assembly ("memory-safe") { // bottom 160 bits of data sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) // next 24 bits of data tick := signextend(2, shr(160, data)) // next 24 bits of data protocolFee := and(shr(184, data), 0xFFFFFF) // last 24 bits of data lpFee := and(shr(208, data), 0xFFFFFF) } } /** * @notice Retrieves the tick information of a pool at a specific tick. * @dev Corresponds to pools[poolId].ticks[tick] * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tick The tick to retrieve information for. * @return liquidityGross The total position liquidity that references this tick * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left) * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) */ function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick) internal view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128 ) { bytes32 slot = _getTickInfoSlot(poolId, tick); // read all 3 words of the TickInfo struct bytes32[] memory data = manager.extsload(slot, 3); assembly ("memory-safe") { let firstWord := mload(add(data, 32)) liquidityNet := sar(128, firstWord) liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) feeGrowthOutside0X128 := mload(add(data, 64)) feeGrowthOutside1X128 := mload(add(data, 96)) } } /** * @notice Retrieves the liquidity information of a pool at a specific tick. * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tick The tick to retrieve liquidity for. * @return liquidityGross The total position liquidity that references this tick * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left) */ function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick) internal view returns (uint128 liquidityGross, int128 liquidityNet) { bytes32 slot = _getTickInfoSlot(poolId, tick); bytes32 value = manager.extsload(slot); assembly ("memory-safe") { liquidityNet := sar(128, value) liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) } } /** * @notice Retrieves the fee growth outside a tick range of a pool * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tick The tick to retrieve fee growth for. * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) */ function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick) internal view returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128) { bytes32 slot = _getTickInfoSlot(poolId, tick); // offset by 1 word, since the first word is liquidityGross + liquidityNet bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2); assembly ("memory-safe") { feeGrowthOutside0X128 := mload(add(data, 32)) feeGrowthOutside1X128 := mload(add(data, 64)) } } /** * @notice Retrieves the global fee growth of a pool. * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128 * @param manager The pool manager contract. * @param poolId The ID of the pool. * @return feeGrowthGlobal0 The global fee growth for token0. * @return feeGrowthGlobal1 The global fee growth for token1. * @dev Note that feeGrowthGlobal can be artificially inflated * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme */ function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId) internal view returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State, `uint256 feeGrowthGlobal0X128` bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET); // read the 2 words of feeGrowthGlobal bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2); assembly ("memory-safe") { feeGrowthGlobal0 := mload(add(data, 32)) feeGrowthGlobal1 := mload(add(data, 64)) } } /** * @notice Retrieves total the liquidity of a pool. * @dev Corresponds to pools[poolId].liquidity * @param manager The pool manager contract. * @param poolId The ID of the pool. * @return liquidity The liquidity of the pool. */ function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State: `uint128 liquidity` bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET); liquidity = uint128(uint256(manager.extsload(slot))); } /** * @notice Retrieves the tick bitmap of a pool at a specific tick. * @dev Corresponds to pools[poolId].tickBitmap[tick] * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tick The tick to retrieve the bitmap for. * @return tickBitmap The bitmap of the tick. */ function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick) internal view returns (uint256 tickBitmap) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State: `mapping(int16 => uint256) tickBitmap;` bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET); // slot id of the mapping key: `pools[poolId].tickBitmap[tick] bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping)); tickBitmap = uint256(manager.extsload(slot)); } /** * @notice Retrieves the position information of a pool without needing to calculate the `positionId`. * @dev Corresponds to pools[poolId].positions[positionId] * @param poolId The ID of the pool. * @param owner The owner of the liquidity position. * @param tickLower The lower tick of the liquidity range. * @param tickUpper The upper tick of the liquidity range. * @param salt The bytes32 randomness to further distinguish position state. * @return liquidity The liquidity of the position. * @return feeGrowthInside0LastX128 The fee growth inside the position for token0. * @return feeGrowthInside1LastX128 The fee growth inside the position for token1. */ function getPositionInfo( IPoolManager manager, PoolId poolId, address owner, int24 tickLower, int24 tickUpper, bytes32 salt ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) { // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt)) bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt); (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey); } /** * @notice Retrieves the position information of a pool at a specific position ID. * @dev Corresponds to pools[poolId].positions[positionId] * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param positionId The ID of the position. * @return liquidity The liquidity of the position. * @return feeGrowthInside0LastX128 The fee growth inside the position for token0. * @return feeGrowthInside1LastX128 The fee growth inside the position for token1. */ function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) { bytes32 slot = _getPositionInfoSlot(poolId, positionId); // read all 3 words of the Position.State struct bytes32[] memory data = manager.extsload(slot, 3); assembly ("memory-safe") { liquidity := mload(add(data, 32)) feeGrowthInside0LastX128 := mload(add(data, 64)) feeGrowthInside1LastX128 := mload(add(data, 96)) } } /** * @notice Retrieves the liquidity of a position. * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param positionId The ID of the position. * @return liquidity The liquidity of the position. */ function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId) internal view returns (uint128 liquidity) { bytes32 slot = _getPositionInfoSlot(poolId, positionId); liquidity = uint128(uint256(manager.extsload(slot))); } /** * @notice Calculate the fee growth inside a tick range of a pool * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tickLower The lower tick of the range. * @param tickUpper The upper tick of the range. * @return feeGrowthInside0X128 The fee growth inside the tick range for token0. * @return feeGrowthInside1X128 The fee growth inside the tick range for token1. */ function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId); (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) = getTickFeeGrowthOutside(manager, poolId, tickLower); (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) = getTickFeeGrowthOutside(manager, poolId, tickUpper); (, int24 tickCurrent,,) = getSlot0(manager, poolId); unchecked { if (tickCurrent < tickLower) { feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128; feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128; } else if (tickCurrent >= tickUpper) { feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128; feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128; } else { feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128; } } } function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) { return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT)); } function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State: `mapping(int24 => TickInfo) ticks` bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET); // slot key of the tick key: `pools[poolId].ticks[tick] return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot)); } function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State: `mapping(bytes32 => Position.State) positions;` bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET); // slot of the mapping key: `pools[poolId].positions[positionId] return keccak256(abi.encodePacked(positionId, positionMapping)); } }
../../lib/v4-core/src/libraries/TickMath.sol239 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; } } }
../../lib/v4-core/src/libraries/FullMath.sol118 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0 = a * b; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly ("memory-safe") { let mm := mulmod(a, b, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { assembly ("memory-safe") { result := div(prod0, denominator) } return result; } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly ("memory-safe") { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly ("memory-safe") { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (0 - denominator) & denominator; // Divide denominator by power of two assembly ("memory-safe") { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly ("memory-safe") { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly ("memory-safe") { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the preconditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) { unchecked { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) != 0) { require(++result > 0); } } } }
../../lib/v4-core/src/interfaces/external/IERC20Minimal.sol49 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Minimal ERC20 interface for Uniswap /// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3 interface IERC20Minimal { /// @notice Returns an account's balance in the token /// @param account The account for which to look up the number of tokens it has, i.e. its balance /// @return The number of tokens held by the account function balanceOf(address account) external view returns (uint256); /// @notice Transfers the amount of token from the `msg.sender` to the recipient /// @param recipient The account that will receive the amount transferred /// @param amount The number of tokens to send from the sender to the recipient /// @return Returns true for a successful transfer, false for an unsuccessful transfer function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Returns the current allowance given to a spender by an owner /// @param owner The account of the token owner /// @param spender The account of the token spender /// @return The current allowance granted by `owner` to `spender` function allowance(address owner, address spender) external view returns (uint256); /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount` /// @param spender The account which will be allowed to spend a given amount of the owners tokens /// @param amount The amount of tokens allowed to be used by `spender` /// @return Returns true for a successful approval, false for unsuccessful function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender` /// @param sender The account from which the transfer will be initiated /// @param recipient The recipient of the transfer /// @param amount The amount of the transfer /// @return Returns true for a successful transfer, false for unsuccessful function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`. /// @param from The account from which the tokens were sent, i.e. the balance decreased /// @param to The account to which the tokens were sent, i.e. the balance increased /// @param value The amount of tokens that were transferred event Transfer(address indexed from, address indexed to, uint256 value); /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes. /// @param owner The account that approved spending of its tokens /// @param spender The account for which the spending allowance was modified /// @param value The new allowance from the owner to the spender event Approval(address indexed owner, address indexed spender, uint256 value); }
../../lib/v4-core/src/libraries/CustomRevert.sol121 lines
// 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)) } } }
../../lib/v4-core/src/types/BeforeSwapDelta.sol39 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Return type of the beforeSwap hook. // Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook) type BeforeSwapDelta is int256; // Creates a BeforeSwapDelta from specified and unspecified function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified) pure returns (BeforeSwapDelta beforeSwapDelta) { assembly ("memory-safe") { beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified)) } } /// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type library BeforeSwapDeltaLibrary { /// @notice A BeforeSwapDelta of 0 BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0); /// extracts int128 from the upper 128 bits of the BeforeSwapDelta /// returned by beforeSwap function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) { assembly ("memory-safe") { deltaSpecified := sar(128, delta) } } /// extracts int128 from the lower 128 bits of the BeforeSwapDelta /// returned by beforeSwap and afterSwap function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) { assembly ("memory-safe") { deltaUnspecified := signextend(15, delta) } } }
../../lib/v4-core/src/libraries/SafeCast.sol61 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {CustomRevert} from "./CustomRevert.sol"; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { using CustomRevert for bytes4; error SafeCastOverflow(); /// @notice Cast a uint256 to a uint160, revert on overflow /// @param x The uint256 to be downcasted /// @return y The downcasted integer, now type uint160 function toUint160(uint256 x) internal pure returns (uint160 y) { y = uint160(x); if (y != x) SafeCastOverflow.selector.revertWith(); } /// @notice Cast a uint256 to a uint128, revert on overflow /// @param x The uint256 to be downcasted /// @return y The downcasted integer, now type uint128 function toUint128(uint256 x) internal pure returns (uint128 y) { y = uint128(x); if (x != y) SafeCastOverflow.selector.revertWith(); } /// @notice Cast a int128 to a uint128, revert on overflow or underflow /// @param x The int128 to be casted /// @return y The casted integer, now type uint128 function toUint128(int128 x) internal pure returns (uint128 y) { if (x < 0) SafeCastOverflow.selector.revertWith(); y = uint128(x); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param x The int256 to be downcasted /// @return y The downcasted integer, now type int128 function toInt128(int256 x) internal pure returns (int128 y) { y = int128(x); if (y != x) SafeCastOverflow.selector.revertWith(); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param x The uint256 to be casted /// @return y The casted integer, now type int256 function toInt256(uint256 x) internal pure returns (int256 y) { y = int256(x); if (y < 0) SafeCastOverflow.selector.revertWith(); } /// @notice Cast a uint256 to a int128, revert on overflow /// @param x The uint256 to be downcasted /// @return The downcasted integer, now type int128 function toInt128(uint256 x) internal pure returns (int128) { if (x >= 1 << 127) SafeCastOverflow.selector.revertWith(); return int128(int256(x)); } }
../../lib/v4-core/src/libraries/Position.sol104 lines
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import {FullMath} from "./FullMath.sol"; import {FixedPoint128} from "./FixedPoint128.sol"; import {LiquidityMath} from "./LiquidityMath.sol"; import {CustomRevert} from "./CustomRevert.sol"; /// @title Position /// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary /// @dev Positions store additional state for tracking fees owed to the position library Position { using CustomRevert for bytes4; /// @notice Cannot update a position with no liquidity error CannotUpdateEmptyPosition(); // info stored for each user's position struct State { // the amount of liquidity owned by this position uint128 liquidity; // fee growth per unit of liquidity as of the last update to liquidity or fees owed uint256 feeGrowthInside0LastX128; uint256 feeGrowthInside1LastX128; } /// @notice Returns the State struct of a position, given an owner and position boundaries /// @param self The mapping containing all user positions /// @param owner The address of the position owner /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @param salt A unique value to differentiate between multiple positions in the same range /// @return position The position info struct of the given owners' position function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt) internal view returns (State storage position) { bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt); position = self[positionKey]; } /// @notice A helper function to calculate the position key /// @param owner The address of the position owner /// @param tickLower the lower tick boundary of the position /// @param tickUpper the upper tick boundary of the position /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller. function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt) internal pure returns (bytes32 positionKey) { // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt)) assembly ("memory-safe") { let fmp := mload(0x40) mstore(add(fmp, 0x26), salt) // [0x26, 0x46) mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26) mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23) mstore(fmp, owner) // [0x0c, 0x20) positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes // now clean the memory we used mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt mstore(fmp, 0) // fmp held owner } } /// @notice Credits accumulated fees to a user's position /// @param self The individual position to update /// @param liquidityDelta The change in pool liquidity as a result of the position update /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries /// @return feesOwed0 The amount of currency0 owed to the position owner /// @return feesOwed1 The amount of currency1 owed to the position owner function update( State storage self, int128 liquidityDelta, uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128 ) internal returns (uint256 feesOwed0, uint256 feesOwed1) { uint128 liquidity = self.liquidity; if (liquidityDelta == 0) { // disallow pokes for 0 liquidity positions if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith(); } else { self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta); } // calculate accumulated fees. overflow in the subtraction of fee growth is expected unchecked { feesOwed0 = FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128); feesOwed1 = FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128); } // update the position self.feeGrowthInside0LastX128 = feeGrowthInside0X128; self.feeGrowthInside1LastX128 = feeGrowthInside1X128; } }
../../lib/v4-core/src/libraries/BitMath.sol50 lines
// 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)) } } }
../../lib/v4-core/src/libraries/FixedPoint128.sol9 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; }
../../lib/v4-core/src/libraries/LiquidityMath.sol21 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Math library for liquidity library LiquidityMath { /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows /// @param x The liquidity before change /// @param y The delta by which liquidity should be changed /// @return z The liquidity delta function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) { assembly ("memory-safe") { z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y)) if shr(128, z) { // revert SafeCastOverflow() mstore(0, 0x93dafdf1) revert(0x1c, 0x04) } } } }