// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.19;
import {LibMulticaller} from "multicaller/LibMulticaller.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import {IAmAmm} from "./interfaces/IAmAmm.sol";
/// @title AmAmm
/// @author zefram.eth
/// @notice Implements the auction mechanism from the am-AMM paper (https://arxiv.org/abs/2403.03367)
abstract contract AmAmm is IAmAmm {
/// -----------------------------------------------------------------------
/// Library usage
/// -----------------------------------------------------------------------
using SafeCastLib for *;
using FixedPointMathLib for *;
/// -----------------------------------------------------------------------
/// Constants
/// -----------------------------------------------------------------------
function K(PoolId) internal view virtual returns (uint48) {
return 7200;
}
function MIN_BID_MULTIPLIER(PoolId) internal view virtual returns (uint256) {
return 1.1e18;
}
function MIN_RENT(PoolId) internal view virtual returns (uint128) {
return 0;
}
/// -----------------------------------------------------------------------
/// Immutable args
/// -----------------------------------------------------------------------
/// @dev The block number at which the contract was deployed
uint256 internal immutable _deploymentBlockNumber;
/// -----------------------------------------------------------------------
/// Storage variables
/// -----------------------------------------------------------------------
mapping(PoolId id => Bid) internal _topBids;
mapping(PoolId id => Bid) internal _nextBids;
mapping(PoolId id => uint48) internal _lastUpdatedBlockIdx;
mapping(Currency currency => uint256) internal _totalFees;
mapping(address manager => mapping(PoolId id => uint256)) internal _refunds;
mapping(address manager => mapping(Currency currency => uint256)) internal _fees;
/// -----------------------------------------------------------------------
/// Constructor
/// -----------------------------------------------------------------------
constructor() {
_deploymentBlockNumber = block.number;
}
/// -----------------------------------------------------------------------
/// Bidder actions
/// -----------------------------------------------------------------------
/// @inheritdoc IAmAmm
function bid(PoolId id, address manager, bytes6 payload, uint128 rent, uint128 deposit) external virtual override {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
address msgSender = LibMulticaller.senderOrSigner();
if (!_amAmmEnabled(id)) {
revert AmAmm__NotEnabled();
}
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// update state machine
_updateAmAmmWrite(id);
// ensure bid is valid
// - manager can't be zero address
// - bid needs to be greater than the next bid by >10%
// - deposit needs to cover the rent for K blocks
// - deposit needs to be a multiple of rent
// - payload needs to be valid
// - rent needs to be at least MIN_RENT
if (
manager == address(0) || rent <= _nextBids[id].rent.mulWad(MIN_BID_MULTIPLIER(id)) || deposit < rent * K(id)
|| deposit % rent != 0 || !_payloadIsValid(id, payload) || rent < MIN_RENT(id)
) {
revert AmAmm__InvalidBid();
}
// refund deposit of the previous next bid
_refunds[_nextBids[id].manager][id] += _nextBids[id].deposit;
// update next bid
uint48 blockIdx = uint48(block.number - _deploymentBlockNumber);
_nextBids[id] = Bid(manager, blockIdx, payload, rent, deposit);
/// -----------------------------------------------------------------------
/// External calls
/// -----------------------------------------------------------------------
// transfer deposit from msg.sender to this contract
_pullBidToken(id, msgSender, deposit);
emit SubmitBid(id, manager, blockIdx, payload, rent, deposit);
}
/// @inheritdoc IAmAmm
function depositIntoTopBid(PoolId id, uint128 amount) external virtual override {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
address msgSender = LibMulticaller.senderOrSigner();
if (!_amAmmEnabled(id)) {
revert AmAmm__NotEnabled();
}
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// update state machine
_updateAmAmmWrite(id);
Bid memory topBid = _topBids[id];
// only the top bid manager can deposit into the top bid
if (msgSender != topBid.manager) {
revert AmAmm__Unauthorized();
}
// ensure amount is a multiple of rent
if (amount % topBid.rent != 0) {
revert AmAmm__InvalidDepositAmount();
}
// add amount to top bid deposit
_topBids[id].deposit = topBid.deposit + amount;
/// -----------------------------------------------------------------------
/// External calls
/// -----------------------------------------------------------------------
// transfer amount from msg.sender to this contract
_pullBidToken(id, msgSender, amount);
emit DepositIntoTopBid(id, msgSender, amount);
}
/// @inheritdoc IAmAmm
function withdrawFromTopBid(PoolId id, uint128 amount, address recipient) external virtual override {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
address msgSender = LibMulticaller.senderOrSigner();
if (!_amAmmEnabled(id)) {
revert AmAmm__NotEnabled();
}
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// update state machine
_updateAmAmmWrite(id);
Bid memory topBid = _topBids[id];
// only the top bid manager can withdraw from the top bid
if (msgSender != topBid.manager) {
revert AmAmm__Unauthorized();
}
// ensure amount is a multiple of rent
if (amount % topBid.rent != 0) {
revert AmAmm__InvalidDepositAmount();
}
// require D_top / R_top >= K
if ((topBid.deposit - amount) / topBid.rent < K(id)) {
revert AmAmm__BidLocked();
}
// deduct amount from top bid deposit
_topBids[id].deposit = topBid.deposit - amount;
/// -----------------------------------------------------------------------
/// External calls
/// -----------------------------------------------------------------------
// transfer amount to recipient
_pushBidToken(id, recipient, amount);
emit WithdrawFromTopBid(id, msgSender, recipient, amount);
}
/// @inheritdoc IAmAmm
function depositIntoNextBid(PoolId id, uint128 amount) external virtual override {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
address msgSender = LibMulticaller.senderOrSigner();
if (!_amAmmEnabled(id)) {
revert AmAmm__NotEnabled();
}
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// update state machine
_updateAmAmmWrite(id);
Bid memory nextBid = _nextBids[id];
// only the next bid manager can deposit into the next bid
if (msgSender != nextBid.manager) {
revert AmAmm__Unauthorized();
}
// ensure amount is a multiple of rent
if (amount % nextBid.rent != 0) {
revert AmAmm__InvalidDepositAmount();
}
// add amount to next bid deposit
_nextBids[id].deposit = nextBid.deposit + amount;
/// -----------------------------------------------------------------------
/// External calls
/// -----------------------------------------------------------------------
// transfer amount from msg.sender to this contract
_pullBidToken(id, msgSender, amount);
emit DepositIntoNextBid(id, msgSender, amount);
}
/// @inheritdoc IAmAmm
function withdrawFromNextBid(PoolId id, uint128 amount, address recipient) external virtual override {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
address msgSender = LibMulticaller.senderOrSigner();
if (!_amAmmEnabled(id)) {
revert AmAmm__NotEnabled();
}
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// update state machine
_updateAmAmmWrite(id);
Bid memory nextBid = _nextBids[id];
// only the next bid manager can withdraw from the next bid
if (msgSender != nextBid.manager) {
revert AmAmm__Unauthorized();
}
// ensure amount is a multiple of rent
if (amount % nextBid.rent != 0) {
revert AmAmm__InvalidDepositAmount();
}
// require D_next / R_next >= K
if ((nextBid.deposit - amount) / nextBid.rent < K(id)) {
revert AmAmm__BidLocked();
}
// deduct amount from next bid deposit
_nextBids[id].deposit = nextBid.deposit - amount;
/// -----------------------------------------------------------------------
/// External calls
/// -----------------------------------------------------------------------
// transfer amount to recipient
_pushBidToken(id, recipient, amount);
emit WithdrawFromNextBid(id, msgSender, recipient, amount);
}
/// @inheritdoc IAmAmm
function claimRefund(PoolId id, address recipient) external virtual override returns (uint256 refund) {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
address msgSender = LibMulticaller.senderOrSigner();
if (!_amAmmEnabled(id)) {
revert AmAmm__NotEnabled();
}
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// update state machine
_updateAmAmmWrite(id);
refund = _refunds[msgSender][id];
if (refund == 0) {
return 0;
}
delete _refunds[msgSender][id];
/// -----------------------------------------------------------------------
/// External calls
/// -----------------------------------------------------------------------
// transfer refund to recipient
_pushBidToken(id, recipient, refund);
emit ClaimRefund(id, msgSender, recipient, refund);
}
/// @inheritdoc IAmAmm
function claimFees(Currency currency, address recipient) external virtual override returns (uint256 fees) {
address msgSender = LibMulticaller.senderOrSigner();
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// update manager fees
fees = _fees[msgSender][currency];
if (fees == 0) {
return 0;
}
delete _fees[msgSender][currency];
// update total fees
unchecked {
// safe because _totalFees[currency] is the sum of all managers' fees
_totalFees[currency] -= fees;
}
/// -----------------------------------------------------------------------
/// External calls
/// -----------------------------------------------------------------------
// transfer fees to recipient
_transferFeeToken(currency, recipient, fees);
emit ClaimFees(currency, msgSender, recipient, fees);
}
/// @inheritdoc IAmAmm
function increaseBidRent(
PoolId id,
uint128 additionalRent,
uint128 updatedDeposit,
bool topBid,
address withdrawRecipient
) external virtual override returns (uint128 amountDeposited, uint128 amountWithdrawn) {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
address msgSender = LibMulticaller.senderOrSigner();
if (!_amAmmEnabled(id)) {
revert AmAmm__NotEnabled();
}
// noop if additionalRent is 0
if (additionalRent == 0) return (0, 0);
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// update state machine
_updateAmAmmWrite(id);
Bid storage relevantBidStorage = topBid ? _topBids[id] : _nextBids[id];
Bid memory relevantBid = relevantBidStorage;
// must be the manager of the relevant bid
if (msgSender != relevantBid.manager) {
revert AmAmm__Unauthorized();
}
uint128 newRent = relevantBid.rent + additionalRent;
// ensure that:
// - updatedDeposit is a multiple of newRent
// - newRent is >= MIN_RENT(id)
if (updatedDeposit % newRent != 0 || newRent < MIN_RENT(id)) {
revert AmAmm__InvalidBid();
}
// require D / R >= K
if (updatedDeposit / newRent < K(id)) {
revert AmAmm__BidLocked();
}
// update relevant bid
relevantBidStorage.rent = newRent;
relevantBidStorage.deposit = updatedDeposit;
/// -----------------------------------------------------------------------
/// External calls
/// -----------------------------------------------------------------------
unchecked {
// explicitly comparing updatedDeposit and relevantBid.deposit so subtractions are always safe
if (updatedDeposit > relevantBid.deposit) {
// transfer amount from msg.sender to this contract
amountDeposited = updatedDeposit - relevantBid.deposit;
_pullBidToken(id, msgSender, amountDeposited);
} else if (updatedDeposit < relevantBid.deposit) {
// transfer amount from this contract to withdrawRecipient
amountWithdrawn = relevantBid.deposit - updatedDeposit;
_pushBidToken(id, withdrawRecipient, amountWithdrawn);
}
}
emit IncreaseBidRent(
id, msgSender, additionalRent, updatedDeposit, topBid, withdrawRecipient, amountDeposited, amountWithdrawn
);
}
/// @inheritdoc IAmAmm
function setBidPayload(PoolId id, bytes6 payload, bool topBid) external virtual override {
address msgSender = LibMulticaller.senderOrSigner();
if (!_amAmmEnabled(id)) {
revert AmAmm__NotEnabled();
}
// update state machine
_updateAmAmmWrite(id);
Bid storage relevantBid = topBid ? _topBids[id] : _nextBids[id];
if (msgSender != relevantBid.manager) {
revert AmAmm__Unauthorized();
}
if (!_payloadIsValid(id, payload)) {
revert AmAmm__InvalidBid();
}
relevantBid.payload = payload;
emit SetBidPayload(id, msgSender, payload, topBid);
}
/// @inheritdoc IAmAmm
function updateStateMachine(PoolId id) external override {
_updateAmAmmWrite(id);
}
/// -----------------------------------------------------------------------
/// Getters
/// -----------------------------------------------------------------------
/// @inheritdoc IAmAmm
function getTopBid(PoolId id) external view override returns (Bid memory topBid) {
(topBid,) = _updateAmAmmView(id);
}
/// @inheritdoc IAmAmm
function getTopBidWrite(PoolId id) external override returns (Bid memory) {
_updateAmAmmWrite(id);
return _topBids[id];
}
/// @inheritdoc IAmAmm
function getNextBid(PoolId id) external view override returns (Bid memory nextBid) {
(, nextBid) = _updateAmAmmView(id);
}
/// @inheritdoc IAmAmm
function getNextBidWrite(PoolId id) external override returns (Bid memory) {
_updateAmAmmWrite(id);
return _nextBids[id];
}
/// @inheritdoc IAmAmm
function getRefund(address manager, PoolId id) external view override returns (uint256) {
return _refunds[manager][id];
}
/// @inheritdoc IAmAmm
function getRefundWrite(address manager, PoolId id) external override returns (uint256) {
_updateAmAmmWrite(id);
return _refunds[manager][id];
}
/// @inheritdoc IAmAmm
function getFees(address manager, Currency currency) external view override returns (uint256) {
return _fees[manager][currency];
}
/// -----------------------------------------------------------------------
/// Virtual functions
/// -----------------------------------------------------------------------
/// @dev Returns whether the am-AMM is enabled for a given pool
function _amAmmEnabled(PoolId id) internal view virtual returns (bool);
/// @dev Validates a bid payload, e.g. ensure the swap fee is below a certain threshold
function _payloadIsValid(PoolId id, bytes6 payload) internal view virtual returns (bool);
/// @dev Burns bid tokens from address(this)
function _burnBidToken(PoolId id, uint256 amount) internal virtual;
/// @dev Transfers bid tokens from an address that's not address(this) to address(this)
function _pullBidToken(PoolId id, address from, uint256 amount) internal virtual;
/// @dev Transfers bid tokens from address(this) to an address that's not address(this)
function _pushBidToken(PoolId id, address to, uint256 amount) internal virtual;
/// @dev Transfers accrued fees from address(this)
function _transferFeeToken(Currency currency, address to, uint256 amount) internal virtual;
/// @dev Accrues swap fees to the manager
function _accrueFees(address manager, Currency currency, uint256 amount) internal virtual {
_fees[manager][currency] += amount;
_totalFees[currency] += amount;
}
/// -----------------------------------------------------------------------
/// Internal helpers
/// -----------------------------------------------------------------------
/// @dev Charges rent and updates the top and next bids for a given pool
function _updateAmAmmWrite(PoolId id) internal virtual returns (address manager, bytes6 payload) {
uint48 currentBlockIdx = uint48(block.number - _deploymentBlockNumber);
// early return if the pool has already been updated in this block
// condition is also true if no update has occurred for type(uint48).max blocks
// which is extremely unlikely
if (_lastUpdatedBlockIdx[id] == currentBlockIdx) {
return (_topBids[id].manager, _topBids[id].payload);
}
Bid memory topBid = _topBids[id];
Bid memory nextBid = _nextBids[id];
bool updatedTopBid;
bool updatedNextBid;
uint256 rentCharged;
// run state machine
{
bool stepHasUpdatedTopBid;
bool stepHasUpdatedNextBid;
uint256 stepRentCharged;
address stepRefundManager;
uint256 stepRefundAmount;
while (true) {
(
topBid,
nextBid,
stepHasUpdatedTopBid,
stepHasUpdatedNextBid,
stepRentCharged,
stepRefundManager,
stepRefundAmount
) = _stateTransition(currentBlockIdx, id, topBid, nextBid);
if (!stepHasUpdatedTopBid && !stepHasUpdatedNextBid) {
break;
}
updatedTopBid = updatedTopBid || stepHasUpdatedTopBid;
updatedNextBid = updatedNextBid || stepHasUpdatedNextBid;
rentCharged += stepRentCharged;
if (stepRefundManager != address(0)) {
_refunds[stepRefundManager][id] += stepRefundAmount;
}
}
}
// update top and next bids
if (updatedTopBid) {
_topBids[id] = topBid;
}
if (updatedNextBid) {
_nextBids[id] = nextBid;
}
// update last updated blockIdx
_lastUpdatedBlockIdx[id] = currentBlockIdx;
// burn rent charged
if (rentCharged != 0) {
_burnBidToken(id, rentCharged);
}
return (topBid.manager, topBid.payload);
}
/// @dev View version of _updateAmAmmWrite()
function _updateAmAmmView(PoolId id) internal view virtual returns (Bid memory topBid, Bid memory nextBid) {
uint48 currentBlockIdx = uint48(block.number - _deploymentBlockNumber);
topBid = _topBids[id];
nextBid = _nextBids[id];
// run state machine
{
bool stepHasUpdatedTopBid;
bool stepHasUpdatedNextBid;
while (true) {
(topBid, nextBid, stepHasUpdatedTopBid, stepHasUpdatedNextBid,,,) =
_stateTransition(currentBlockIdx, id, topBid, nextBid);
if (!stepHasUpdatedTopBid && !stepHasUpdatedNextBid) {
break;
}
}
}
}
/// @dev Returns the updated top and next bids after a single state transition
/// State diagram is as follows:
/// after
/// ┌───────────────────────deposit ───────────────────┐
/// │ depletes │
/// ▼ │
/// ┌────────────────────────┐ ┌────────────────────────┐
/// │ │ │ │
/// │ State A │ │ State B │
/// │ Manager: nil │ ┌───────────▶│ Manager: r0 │◀─┐
/// │ Next: nil │ │ │ Next: nil │ │
/// │ │ │ │ │ │
/// └────────────────────────┘ │ └────────────────────────┘ │
/// │ │ │ │
/// │ │ │ │
/// │ │ │ │
/// │ │ │ │
/// bid(r) after K bid(r) after K
/// │ blocks │ blocks
/// │ │ │ │
/// │ │ │ │
/// │ │ after │ │
/// ├────────────────────────┼──deposit ───────────────┼──────────────┤
/// │ │ depletes │ │
/// ▼ │ ▼ │
/// ┌────────────────────────┐ │ ┌────────────────────────┐ │
/// │ │ │ │ │ │
/// │ State C │ │ │ State D │ │
/// ┌─▶│ Manager: nil │────────────┘ ┌─▶│ Manager: r0 │──┘
/// │ │ Next: r │ │ │ Next: r │
/// │ │ │ │ │ │
/// │ └────────────────────────┘ │ └────────────────────────┘
/// │ │ │ │
/// │ │ │ │
/// └─────bid(r)────┘ └─────bid(r)────┘
function _stateTransition(uint48 currentBlockIdx, PoolId id, Bid memory topBid, Bid memory nextBid)
internal
view
virtual
returns (
Bid memory,
Bid memory,
bool updatedTopBid,
bool updatedNextBid,
uint256 rentCharged,
address refundManager,
uint256 refundAmount
)
{
uint48 k = K(id);
if (nextBid.manager == address(0)) {
if (topBid.manager != address(0)) {
// State B
// charge rent from top bid
uint48 blocksPassed;
unchecked {
// unchecked so that if blockIdx ever overflows, we simply wrap around
// could be 0 if no update has occurred for type(uint48).max blocks
// which is extremely unlikely
blocksPassed = currentBlockIdx - topBid.blockIdx;
}
uint256 rentOwed = blocksPassed * topBid.rent;
if (rentOwed >= topBid.deposit) {
// State B -> State A
// the top bid's deposit has been depleted
rentCharged = topBid.deposit;
topBid = Bid(address(0), 0, 0, 0, 0);
updatedTopBid = true;
} else if (rentOwed != 0) {
// State B
// charge rent from top bid
rentCharged = rentOwed;
topBid.deposit -= rentOwed.toUint128();
topBid.blockIdx = currentBlockIdx;
updatedTopBid = true;
}
}
} else {
if (topBid.manager == address(0)) {
// State C
// check if K blocks have passed since the next bid was submitted
// if so, promote next bid to top bid
uint48 nextBidStartBlockIdx;
unchecked {
// unchecked so that if blockIdx ever overflows, we simply wrap around
nextBidStartBlockIdx = nextBid.blockIdx + k;
}
if (currentBlockIdx >= nextBidStartBlockIdx) {
// State C -> State B
// promote next bid to top bid
topBid = nextBid;
topBid.blockIdx = nextBidStartBlockIdx;
nextBid = Bid(address(0), 0, 0, 0, 0);
updatedTopBid = true;
updatedNextBid = true;
}
} else {
// State D
// we charge rent from the top bid only until K blocks after the next bid was submitted
// assuming the next bid's rent is greater than the top bid's rent + 10%, otherwise we don't care about
// the next bid
bool nextBidIsBetter = nextBid.rent > topBid.rent.mulWad(MIN_BID_MULTIPLIER(id));
uint48 blocksPassed;
unchecked {
// unchecked so that if blockIdx ever overflows, we simply wrap around
blocksPassed = nextBidIsBetter
? uint48(
FixedPointMathLib.min(currentBlockIdx - topBid.blockIdx, nextBid.blockIdx + k - topBid.blockIdx)
)
: currentBlockIdx - topBid.blockIdx;
}
uint256 rentOwed = blocksPassed * topBid.rent;
if (rentOwed >= topBid.deposit) {
// State D -> State C
// top bid has insufficient deposit
// clear the top bid and make sure the next bid starts >= the latest processed blockIdx
rentCharged = topBid.deposit;
topBid = Bid(address(0), 0, 0, 0, 0);
unchecked {
// unchecked so that if blockIdx ever underflows, we simply wrap around
uint48 latestProcessedBlockIdx = nextBidIsBetter
? uint48(FixedPointMathLib.min(currentBlockIdx, nextBid.blockIdx + k))
: currentBlockIdx;
nextBid.blockIdx = uint48(FixedPointMathLib.max(nextBid.blockIdx, latestProcessedBlockIdx - k));
}
updatedTopBid = true;
updatedNextBid = true;
} else {
// State D
// top bid has sufficient deposit
// charge rent from top bid
if (rentOwed != 0) {
rentCharged = rentOwed;
topBid.deposit -= rentOwed.toUint128();
topBid.blockIdx = currentBlockIdx;
updatedTopBid = true;
}
// check if K blocks have passed since the next bid was submitted
// and that the next bid's rent is greater than the top bid's rent + 10%
// if so, promote next bid to top bid
uint48 nextBidStartBlockIdx;
unchecked {
// unchecked so that if blockIdx ever overflows, we simply wrap around
nextBidStartBlockIdx = nextBid.blockIdx + k;
}
if (currentBlockIdx >= nextBidStartBlockIdx && nextBidIsBetter) {
// State D -> State B
// refund remaining deposit to top bid manager
(refundManager, refundAmount) = (topBid.manager, topBid.deposit);
// promote next bid to top bid
topBid = nextBid;
topBid.blockIdx = nextBidStartBlockIdx;
nextBid = Bid(address(0), 0, 0, 0, 0);
updatedTopBid = true;
updatedNextBid = true;
}
}
}
}
return (topBid, nextBid, updatedTopBid, updatedNextBid, rentCharged, refundManager, refundAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
/// @dev Decodes the payload specified by the am-AMM manager.
/// Format:
/// | swapFee0For1 - 3 bytes | swapFee1For0 - 3 bytes |
/// @return swapFee0For1 The swap fee for token0 -> token1 swaps
/// @return swapFee1For0 The swap fee for token1 -> token0 swaps
function decodeAmAmmPayload(bytes6 payload) pure returns (uint24 swapFee0For1, uint24 swapFee1For0) {
swapFee0For1 = uint24(bytes3(payload));
swapFee1For0 = uint24(bytes3(payload << 24));
}
// 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)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {BeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import "../interfaces/IBaseHook.sol";
abstract contract BaseHook is IBaseHook {
/// @notice The address of the pool manager
IPoolManager public immutable override poolManager;
constructor(IPoolManager _poolManager) {
poolManager = _poolManager;
}
/// @dev Only the pool manager may call this function
modifier poolManagerOnly() {
if (msg.sender != address(poolManager)) revert NotPoolManager();
_;
}
function afterInitialize(address, PoolKey calldata, uint160, int24) external virtual override returns (bytes4);
function beforeSwap(address, PoolKey calldata, IPoolManager.SwapParams calldata, bytes calldata)
external
virtual
override
returns (bytes4, BeforeSwapDelta, uint24);
}
// 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)
}
}
}
// 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))
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;
import "@uniswap/v4-core/src/types/PoolId.sol";
import "@uniswap/v4-core/src/types/Currency.sol";
import "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {AmAmm} from "biddog/AmAmm.sol";
import "flood-contracts/src/interfaces/IZone.sol";
import "flood-contracts/src/interfaces/IFloodPlain.sol";
import {IERC1271} from "permit2/src/interfaces/IERC1271.sol";
import {WETH} from "solady/tokens/WETH.sol";
import {ERC20} from "solady/tokens/ERC20.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import "./lib/Math.sol";
import "./base/Errors.sol";
import "./base/Constants.sol";
import "./lib/AmAmmPayload.sol";
import "./types/IdleBalance.sol";
import "./base/SharedStructs.sol";
import "./interfaces/IBunniHook.sol";
import {Oracle} from "./lib/Oracle.sol";
import {Ownable} from "./base/Ownable.sol";
import {BaseHook} from "./base/BaseHook.sol";
import {IBunniHub} from "./interfaces/IBunniHub.sol";
import {BunniSwapMath} from "./lib/BunniSwapMath.sol";
import {BunniHookLogic} from "./lib/BunniHookLogic.sol";
import {ReentrancyGuard} from "./base/ReentrancyGuard.sol";
/// @title BunniHook
/// @author zefram.eth
/// @notice Uniswap v4 hook responsible for handling swaps on Bunni. Implements auto-rebalancing
/// executed via FloodPlain. Uses am-AMM to recapture LVR & MEV.
contract BunniHook is BaseHook, Ownable, IBunniHook, ReentrancyGuard, AmAmm {
/// -----------------------------------------------------------------------
/// Library usage
/// -----------------------------------------------------------------------
using SafeTransferLib for *;
using FixedPointMathLib for *;
using IdleBalanceLibrary for *;
using PoolIdLibrary for PoolKey;
using CurrencyLibrary for Currency;
using Oracle for Oracle.Observation[MAX_CARDINALITY];
/// -----------------------------------------------------------------------
/// Immutable args
/// -----------------------------------------------------------------------
uint48 internal immutable _K;
WETH internal immutable weth;
IBunniHub internal immutable hub;
address internal immutable permit2;
IFloodPlain internal immutable floodPlain;
/// -----------------------------------------------------------------------
/// Transient storage variables
/// -----------------------------------------------------------------------
/// @dev Equal to uint256(keccak256("REBALANCE_OUTPUT_BALANCE_SLOT")) - 1
uint256 internal constant REBALANCE_OUTPUT_BALANCE_SLOT =
0x07bd55ea91cddb9c2c27beeba6deadeb8f557caeb242f82d756cf1d33154a78c;
/// -----------------------------------------------------------------------
/// Storage variables
/// -----------------------------------------------------------------------
/// @dev Contains mappings used by both BunniHook and BunniLogic. Makes passing
/// mappings to BunniHookLogic easier & cheaper.
HookStorage internal s;
/// @dev The address that receives the hook protocol fees
address internal hookFeeRecipient;
/// @notice Used for computing the hook fee amount. Fee taken is `amount * swapFee / 1e6 * hookFeesModifier / 1e6`.
uint32 internal hookFeeModifier;
/// @notice Used for computing the referral reward amount. Reward is `hookFee * referralRewardModifier / 1e6`.
uint32 internal referralRewardModifier;
/// @notice The FloodZone contract used in rebalance orders.
IZone internal floodZone;
/// @dev canWithdraw() returns false when a rebalance order is active. If rebalance orders don't get filled, withdrawals
/// will continue to be blocked until the rebalance order is fulfilled since there is order resubmission. This allows
/// the hook owner to manually unblock withdrawals for a pool.
mapping(PoolId => bool) internal withdrawalUnblocked;
/// -----------------------------------------------------------------------
/// Constructor
/// -----------------------------------------------------------------------
constructor(
IPoolManager poolManager_,
IBunniHub hub_,
IFloodPlain floodPlain_,
WETH weth_,
IZone floodZone_,
address owner_,
address hookFeeRecipient_,
uint32 hookFeeModifier_,
uint32 referralRewardModifier_,
uint48 k_
) BaseHook(poolManager_) {
if (hookFeeModifier_ > MODIFIER_BASE || referralRewardModifier_ > MODIFIER_BASE) {
revert BunniHook__InvalidModifier();
}
hub = hub_;
floodPlain = floodPlain_;
permit2 = address(floodPlain_.PERMIT2());
weth = weth_;
_K = k_;
require(
address(hub_) != address(0) && address(floodPlain_) != address(0) && address(permit2) != address(0)
&& address(weth_) != address(0) && owner_ != address(0) && k_ != 0
);
hookFeeRecipient = hookFeeRecipient_;
hookFeeModifier = hookFeeModifier_;
referralRewardModifier = referralRewardModifier_;
floodZone = floodZone_;
_initializeOwner(owner_);
poolManager_.setOperator(address(hub_), true);
emit SetModifiers(hookFeeModifier_, referralRewardModifier_);
}
/// -----------------------------------------------------------------------
/// EIP-1271 compliance
/// -----------------------------------------------------------------------
/// @inheritdoc IERC1271
function isValidSignature(bytes32 hash, bytes memory signature)
external
view
override
returns (bytes4 magicValue)
{
// verify rebalance order
PoolId id = abi.decode(signature, (PoolId)); // we use the signature field to store the pool id
if (s.rebalanceOrderPermit2Hash[id] == hash) {
return this.isValidSignature.selector;
}
}
/// -----------------------------------------------------------------------
/// External functions
/// -----------------------------------------------------------------------
/// @inheritdoc IBunniHook
function increaseCardinalityNext(PoolKey calldata key, uint32 cardinalityNext)
public
override
returns (uint32 cardinalityNextOld, uint32 cardinalityNextNew)
{
PoolId id = key.toId();
ObservationState storage state = s.states[id];
cardinalityNextOld = state.cardinalityNext;
cardinalityNextNew = s.observations[id].grow(cardinalityNextOld, cardinalityNext);
state.cardinalityNext = cardinalityNextNew;
}
/// @inheritdoc IBunniHook
function claimProtocolFees(Currency[] calldata currencyList) external override nonReentrant {
poolManager.unlock(abi.encode(HookUnlockCallbackType.CLAIM_FEES, abi.encode(currencyList)));
}
receive() external payable {}
/// -----------------------------------------------------------------------
/// Uniswap lock callback
/// -----------------------------------------------------------------------
enum HookUnlockCallbackType {
REBALANCE_PREHOOK,
REBALANCE_POSTHOOK,
CLAIM_FEES
}
/// @inheritdoc IUnlockCallback
function unlockCallback(bytes calldata data) external override poolManagerOnly returns (bytes memory) {
// decode input
(HookUnlockCallbackType t, bytes memory callbackData) = abi.decode(data, (HookUnlockCallbackType, bytes));
if (t == HookUnlockCallbackType.REBALANCE_PREHOOK) {
_rebalancePrehookCallback(callbackData);
} else if (t == HookUnlockCallbackType.REBALANCE_POSTHOOK) {
_rebalancePosthookCallback(callbackData);
} else if (t == HookUnlockCallbackType.CLAIM_FEES) {
_claimFees(callbackData);
}
return bytes("");
}
/// @dev Calls hub.hookHandleSwap to pull the rebalance swap input tokens from BunniHub.
/// Then burns PoolManager claim tokens and takes the underlying tokens from PoolManager.
/// Used while executing rebalance orders.
function _rebalancePrehookCallback(bytes memory callbackData) internal {
// decode data
(Currency currency, uint256 amount, PoolKey memory key, bool zeroForOne) =
abi.decode(callbackData, (Currency, uint256, PoolKey, bool));
// pull claim tokens from BunniHub
hub.hookHandleSwap({key: key, zeroForOne: zeroForOne, inputAmount: 0, outputAmount: amount});
// lock BunniHub to prevent reentrancy
hub.lockForRebalance(key);
// burn and take
poolManager.burn(address(this), currency.toId(), amount);
poolManager.take(currency, address(this), amount);
}
/// @dev Settles tokens sent to PoolManager and mints the corresponding claim tokens.
/// Then calls hub.hookHandleSwap to update pool balances with rebalance swap output.
/// Used while executing rebalance orders.
function _rebalancePosthookCallback(bytes memory callbackData) internal {
// decode data
(Currency currency, uint256 amount, PoolKey memory key, bool zeroForOne) =
abi.decode(callbackData, (Currency, uint256, PoolKey, bool));
// sync poolManager balance and transfer the output tokens to poolManager
poolManager.sync(currency);
if (!currency.isAddressZero()) {
Currency.unwrap(currency).safeTransfer(address(poolManager), amount);
}
// settle the transferred tokens and mint claim tokens
uint256 paid = poolManager.settle{value: currency.isAddressZero() ? amount : 0}();
poolManager.mint(address(this), currency.toId(), paid);
// unlock BunniHub
hub.unlockForRebalance(key);
// push claim tokens to BunniHub
hub.hookHandleSwap({key: key, zeroForOne: zeroForOne, inputAmount: paid, outputAmount: 0});
}
/// @dev Claims protocol fees earned and sends it to the recipient.
function _claimFees(bytes memory callbackData) internal {
// decode data
Currency[] memory currencyList = abi.decode(callbackData, (Currency[]));
address recipient = hookFeeRecipient;
// claim protocol fees
for (uint256 i; i < currencyList.length; i++) {
Currency currency = currencyList[i];
// can claim balance - am-AMM accrued fees
uint256 balance = poolManager.balanceOf(address(this), currency.toId()) - _totalFees[currency];
if (balance != 0) {
poolManager.burn(address(this), currency.toId(), balance);
if (currency.isAddressZero()) {
// convert ETH to WETH and send to recipient
poolManager.take(currency, address(this), balance);
weth.deposit{value: balance}();
weth.transfer(recipient, balance);
} else {
// take tokens directly to recipient
poolManager.take(currency, recipient, balance);
}
}
}
emit ClaimProtocolFees(currencyList, recipient);
}
/// -----------------------------------------------------------------------
/// BunniHub functions
/// -----------------------------------------------------------------------
/// @inheritdoc IBunniHook
function updateLdfState(PoolId id, bytes32 newState) external override {
if (msg.sender != address(hub)) revert BunniHook__Unauthorized();
s.ldfStates[id] = newState;
}
/// -----------------------------------------------------------------------
/// Owner functions
/// -----------------------------------------------------------------------
/// @inheritdoc IBunniHook
function setZone(IZone zone) external onlyOwner {
floodZone = zone;
emit SetZone(zone);
}
function setHookFeeRecipient(address newHookFeeRecipient) external onlyOwner {
hookFeeRecipient = newHookFeeRecipient;
emit SetHookFeeRecipient(newHookFeeRecipient);
}
/// @inheritdoc IBunniHook
function setModifiers(uint32 newHookFeeModifier, uint32 newReferralRewardModifier) external onlyOwner {
if (newHookFeeModifier > MODIFIER_BASE || newReferralRewardModifier > MODIFIER_BASE) {
revert BunniHook__InvalidModifier();
}
hookFeeModifier = newHookFeeModifier;
referralRewardModifier = newReferralRewardModifier;
emit SetModifiers(newHookFeeModifier, newReferralRewardModifier);
}
/// @inheritdoc IBunniHook
function setWithdrawalUnblocked(PoolId id, bool unblocked) external onlyOwner {
withdrawalUnblocked[id] = unblocked;
emit SetWithdrawalUnblocked(id, unblocked);
}
/// -----------------------------------------------------------------------
/// View functions
/// -----------------------------------------------------------------------
/// @inheritdoc IBunniHook
function getObservation(PoolKey calldata key, uint256 index)
external
view
override
returns (Oracle.Observation memory observation)
{
observation = s.observations[key.toId()][index];
}
/// @inheritdoc IBunniHook
function getState(PoolKey calldata key) external view override returns (ObservationState memory state) {
state = s.states[key.toId()];
}
/// @inheritdoc IBunniHook
function observe(PoolKey calldata key, uint32[] calldata secondsAgos)
external
view
override
returns (int56[] memory tickCumulatives)
{
return BunniHookLogic.observe(s, key, secondsAgos);
}
/// @inheritdoc IBunniHook
function isValidParams(bytes calldata hookParams) external pure override returns (bool) {
return BunniHookLogic.isValidParams(hookParams);
}
/// @inheritdoc IBunniHook
function getAmAmmEnabled(PoolId id) external view override returns (bool) {
return _amAmmEnabled(id);
}
/// @inheritdoc IBunniHook
function ldfStates(PoolId id) external view returns (bytes32) {
return s.ldfStates[id];
}
/// @inheritdoc IBunniHook
function slot0s(PoolId id)
external
view
returns (uint160 sqrtPriceX96, int24 tick, uint32 lastSwapTimestamp, uint32 lastSurgeTimestamp)
{
Slot0 memory slot0 = s.slot0s[id];
return (slot0.sqrtPriceX96, slot0.tick, slot0.lastSwapTimestamp, slot0.lastSurgeTimestamp);
}
/// @inheritdoc IBunniHook
function vaultSharePricesAtLastSwap(PoolId id)
external
view
returns (bool initialized, uint120 sharePrice0, uint120 sharePrice1)
{
VaultSharePrices memory prices = s.vaultSharePricesAtLastSwap[id];
return (prices.initialized, prices.sharePrice0, prices.sharePrice1);
}
/// @inheritdoc IBunniHook
function canWithdraw(PoolId id) external view returns (bool) {
return block.timestamp > s.rebalanceOrderDeadline[id] || withdrawalUnblocked[id];
}
/// @inheritdoc IBunniHook
function getHookFeeRecipient() external view returns (address) {
return hookFeeRecipient;
}
/// @inheritdoc IBunniHook
function getModifiers() external view returns (uint32 hookFeeModifier_, uint32 referralRewardModifier_) {
return (hookFeeModifier, referralRewardModifier);
}
/// @inheritdoc IBunniHook
function getClaimableHookFees(Currency[] calldata currencyList)
external
view
returns (uint256[] memory feeAmounts)
{
feeAmounts = new uint256[](currencyList.length);
for (uint256 i; i < currencyList.length; i++) {
// can claim balance - am-AMM accrued fees
Currency currency = currencyList[i];
feeAmounts[i] = poolManager.balanceOf(address(this), currency.toId()) - _totalFees[currency];
}
}
/// -----------------------------------------------------------------------
/// Hooks
/// -----------------------------------------------------------------------
/// @inheritdoc IBaseHook
function afterInitialize(address caller, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
override(BaseHook, IBaseHook)
poolManagerOnly
returns (bytes4)
{
BunniHookLogic.afterInitialize(s, caller, key, sqrtPriceX96, tick, hub);
return BunniHook.afterInitialize.selector;
}
/// @inheritdoc IBaseHook
function beforeSwap(address sender, PoolKey calldata key, IPoolManager.SwapParams calldata params, bytes calldata)
external
override(BaseHook, IBaseHook)
poolManagerOnly
nonReentrant
returns (bytes4, BeforeSwapDelta, uint24)
{
(
bool useAmAmmFee,
address amAmmManager,
Currency amAmmFeeCurrency,
uint256 amAmmFeeAmount,
BeforeSwapDelta beforeSwapDelta
) = BunniHookLogic.beforeSwap(
s,
BunniHookLogic.Env({
hookFeeModifier: hookFeeModifier,
referralRewardModifier: referralRewardModifier,
floodZone: floodZone,
hub: hub,
poolManager: poolManager,
floodPlain: floodPlain,
weth: weth,
permit2: permit2
}),
sender,
key,
params
);
// accrue swap fee to the am-AMM manager if present
if (useAmAmmFee) {
_accrueFees(amAmmManager, amAmmFeeCurrency, amAmmFeeAmount);
}
return (BunniHook.beforeSwap.selector, beforeSwapDelta, 0);
}
/// -----------------------------------------------------------------------
/// Rebalancing functions
/// -----------------------------------------------------------------------
/// @inheritdoc IBunniHook
function rebalanceOrderPreHook(RebalanceOrderHookArgs calldata hookArgs) external override nonReentrant {
// verify call came from Flood
if (msg.sender != address(floodPlain)) {
revert BunniHook__Unauthorized();
}
PoolId id = hookArgs.key.toId();
// verify the order hash originated from BunniHook
// this also verifies hookArgs is valid since it's hashed into the order hash
bytes32 orderHash;
// orderHash = bytes32(msg.data[msg.data.length - 32:msg.data.length]);
assembly ("memory-safe") {
orderHash := calldataload(sub(calldatasize(), 32))
}
if (s.rebalanceOrderHash[id] != orderHash) {
revert BunniHook__InvalidRebalanceOrderHash();
}
RebalanceOrderPreHookArgs calldata args = hookArgs.preHookArgs;
// store the order output balance before the order execution in transient storage
// this is used to compute the order output amount
uint256 outputBalanceBefore = hookArgs.postHookArgs.currency.isAddressZero()
? weth.balanceOf(address(this))
: hookArgs.postHookArgs.currency.balanceOfSelf();
assembly ("memory-safe") {
tstore(REBALANCE_OUTPUT_BALANCE_SLOT, outputBalanceBefore)
}
// pull input tokens from BunniHub to BunniHook
// received in the form of PoolManager claim tokens
// then unwrap claim tokens
poolManager.unlock(
abi.encode(
HookUnlockCallbackType.REBALANCE_PREHOOK,
abi.encode(args.currency, args.amount, hookArgs.key, hookArgs.key.currency1 == args.currency)
)
);
// ensure we have at least args.amount tokens so that there is enough input for the order
if (args.currency.balanceOfSelf() < args.amount) {
revert BunniHook__PrehookPostConditionFailed();
}
// wrap native ETH input to WETH
// we're implicitly trusting the WETH contract won't charge a fee which is OK in practice
if (args.currency.isAddressZero()) {
weth.deposit{value: args.amount}();
}
}
/// @inheritdoc IBunniHook
function rebalanceOrderPostHook(RebalanceOrderHookArgs calldata hookArgs) external override nonReentrant {
// verify call came from Flood
if (msg.sender != address(floodPlain)) {
revert BunniHook__Unauthorized();
}
PoolId id = hookArgs.key.toId();
// verify the order hash originated from BunniHook
// this also verifies hookArgs is valid since it's hashed into the order hash
bytes32 orderHash;
// orderHash = bytes32(msg.data[msg.data.length - 32:msg.data.length]);
assembly ("memory-safe") {
orderHash := calldataload(sub(calldatasize(), 32))
}
if (s.rebalanceOrderHash[id] != orderHash) {
revert BunniHook__InvalidRebalanceOrderHash();
}
// invalidate the rebalance order
delete s.rebalanceOrderHash[id];
delete s.rebalanceOrderPermit2Hash[id];
delete s.rebalanceOrderDeadline[id];
// surge fee should be applied after the rebalance has been executed
// since totalLiquidity will be increased
// no need to check surgeFeeAutostartThreshold since we just increased the liquidity in this tx
// so block.timestamp is the exact time when the surge should occur
s.slot0s[id].lastSwapTimestamp = uint32(block.timestamp);
s.slot0s[id].lastSurgeTimestamp = uint32(block.timestamp);
RebalanceOrderPostHookArgs calldata args = hookArgs.postHookArgs;
// compute order output amount by computing the difference in the output token balance
uint256 orderOutputAmount;
uint256 outputBalanceBefore;
assembly ("memory-safe") {
outputBalanceBefore := tload(REBALANCE_OUTPUT_BALANCE_SLOT)
}
if (args.currency.isAddressZero()) {
// unwrap WETH output to native ETH
orderOutputAmount = weth.balanceOf(address(this));
weth.withdraw(orderOutputAmount);
} else {
orderOutputAmount = args.currency.balanceOfSelf();
}
orderOutputAmount -= outputBalanceBefore;
// posthook should wrap output tokens as claim tokens and push it from BunniHook to BunniHub and update pool balances
poolManager.unlock(
abi.encode(
HookUnlockCallbackType.REBALANCE_POSTHOOK,
abi.encode(args.currency, orderOutputAmount, hookArgs.key, hookArgs.key.currency0 == args.currency)
)
);
// recompute idle balance
BunniHookLogic.recomputeIdleBalance(s, hub, hookArgs.key);
}
/// -----------------------------------------------------------------------
/// AmAmm support
/// -----------------------------------------------------------------------
function K(PoolId) internal view virtual override returns (uint48) {
return _K;
}
function MIN_RENT(PoolId id) internal view virtual override returns (uint128) {
// minimum rent should be propotional to the pool's BunniToken total supply
bytes memory hookParams = hub.hookParams(id);
bytes32 secondWord;
/// @solidity memory-safe-assembly
assembly {
secondWord := mload(add(hookParams, 64))
}
uint48 minRentMultiplier = uint48(bytes6(secondWord << 32));
uint256 minRent = hub.bunniTokenOfPool(id).totalSupply().mulWadUp(minRentMultiplier);
// if the min rent value is somehow more than uint128.max, cap it to uint128.max
return minRent > type(uint128).max ? type(uint128).max : uint128(minRent);
}
/// @dev precedence is poolOverride > globalOverride > poolEnabled
function _amAmmEnabled(PoolId id) internal view virtual override returns (bool) {
bytes memory hookParams = hub.hookParams(id);
bytes32 firstWord;
/// @solidity memory-safe-assembly
assembly {
firstWord := mload(add(hookParams, 32))
}
bool poolEnabled = uint8(bytes1(firstWord << 248)) != 0;
return poolEnabled;
}
function _payloadIsValid(PoolId id, bytes6 payload) internal view virtual override returns (bool) {
// use feeMax from hookParams
bytes memory hookParams = hub.hookParams(id);
bytes32 firstWord;
/// @solidity memory-safe-assembly
assembly {
firstWord := mload(add(hookParams, 32))
}
uint24 maxAmAmmFee = uint24(bytes3(firstWord << 96));
// payload is valid if swapFee0For1 and swapFee1For0 are at most maxAmAmmFee
(uint24 swapFee0For1, uint24 swapFee1For0) = decodeAmAmmPayload(payload);
return swapFee0For1 <= maxAmAmmFee && swapFee1For0 <= maxAmAmmFee;
}
function _burnBidToken(PoolId id, uint256 amount) internal virtual override {
hub.bunniTokenOfPool(id).burn(amount);
}
function _pullBidToken(PoolId id, address from, uint256 amount) internal virtual override {
hub.bunniTokenOfPool(id).transferFrom(from, address(this), amount);
}
function _pushBidToken(PoolId id, address to, uint256 amount) internal virtual override {
hub.bunniTokenOfPool(id).transfer(to, amount);
}
function _transferFeeToken(Currency currency, address to, uint256 amount) internal virtual override {
poolManager.transfer(to, currency.toId(), amount);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;
import "@uniswap/v4-core/src/types/PoolId.sol";
import "@uniswap/v4-core/src/types/Currency.sol";
import "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {SqrtPriceMath} from "@uniswap/v4-core/src/libraries/SqrtPriceMath.sol";
import {WETH} from "solady/tokens/WETH.sol";
import {ERC20} from "solady/tokens/ERC20.sol";
import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import "./Math.sol";
import "./FeeMath.sol";
import "./VaultMath.sol";
import "./AmAmmPayload.sol";
import "../base/Errors.sol";
import "../types/LDFType.sol";
import "../base/Constants.sol";
import "../types/PoolState.sol";
import "../types/IdleBalance.sol";
import "../base/SharedStructs.sol";
import {Oracle} from "./Oracle.sol";
import "../interfaces/IBunniHook.sol";
import {queryLDF} from "./QueryLDF.sol";
import {BunniHook} from "../BunniHook.sol";
import {HookletLib} from "./HookletLib.sol";
import {BunniSwapMath} from "./BunniSwapMath.sol";
import {RebalanceLogic} from "./RebalanceLogic.sol";
import {IHooklet} from "../interfaces/IHooklet.sol";
import {IBunniHub} from "../interfaces/IBunniHub.sol";
import {LiquidityAmounts} from "./LiquidityAmounts.sol";
/// @title BunniHookLogic
/// @notice Split from BunniHook to reduce contract size below the Spurious Dragon limit
library BunniHookLogic {
using TickMath for *;
using SafeCastLib for *;
using SafeTransferLib for *;
using FixedPointMathLib for *;
using HookletLib for IHooklet;
using IdleBalanceLibrary for *;
using PoolIdLibrary for PoolKey;
using CurrencyLibrary for Currency;
using Oracle for Oracle.Observation[MAX_CARDINALITY];
/// -----------------------------------------------------------------------
/// Structs
/// -----------------------------------------------------------------------
struct Env {
uint32 hookFeeModifier;
uint32 referralRewardModifier;
IBunniHub hub;
IPoolManager poolManager;
IFloodPlain floodPlain;
IZone floodZone;
WETH weth;
address permit2;
}
struct RebalanceInput {
PoolId id;
PoolKey key;
int24 updatedTick;
uint160 updatedSqrtPriceX96;
int24 arithmeticMeanTick;
bytes32 newLdfState;
DecodedHookParams hookParams;
Oracle.Observation updatedIntermediate;
uint32 updatedIndex;
uint32 updatedCardinality;
}
/// -----------------------------------------------------------------------
/// External functions
/// -----------------------------------------------------------------------
function afterInitialize(
HookStorage storage s,
address caller,
PoolKey calldata key,
uint160 sqrtPriceX96,
int24 tick,
IBunniHub hub
) external {
if (caller != address(hub)) revert BunniHook__Unauthorized(); // prevents non-BunniHub contracts from initializing a pool using this hook
PoolId id = key.toId();
// initialize slot0
s.slot0s[id] = Slot0({
sqrtPriceX96: sqrtPriceX96,
tick: tick,
lastSwapTimestamp: uint32(block.timestamp),
lastSurgeTimestamp: 0
});
// read hook data from hub
bytes memory hookData = hub.poolInitData();
// initialize first observation to be dated in the past
// so that we can immediately start querying the oracle
(uint24 twapSecondsAgo, bytes memory hookParams) = abi.decode(hookData, (uint24, bytes));
DecodedHookParams memory hookParamsDecoded = _decodeParams(hookParams);
uint32 maxTwapSecondsAgo = uint32(
FixedPointMathLib.max(
FixedPointMathLib.max(twapSecondsAgo, hookParamsDecoded.feeTwapSecondsAgo),
hookParamsDecoded.rebalanceTwapSecondsAgo
)
);
(s.states[id].intermediateObservation, s.states[id].cardinality, s.states[id].cardinalityNext) =
s.observations[id].initialize(uint32(block.timestamp - maxTwapSecondsAgo), tick);
// increase cardinality target based on maxTwapSecondsAgo
uint32 cardinalityNext =
(maxTwapSecondsAgo + (hookParamsDecoded.oracleMinInterval >> 1)) / hookParamsDecoded.oracleMinInterval + 1; // round up + 1
if (cardinalityNext > 1) {
uint32 cardinalityNextNew = s.observations[id].grow(1, cardinalityNext);
s.states[id].cardinalityNext = cardinalityNextNew;
}
}
function beforeSwap(
HookStorage storage s,
Env calldata env,
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params
)
external
returns (
bool useAmAmmFee,
address amAmmManager,
Currency amAmmFeeCurrency,
uint256 amAmmFeeAmount,
BeforeSwapDelta beforeSwapDelta
)
{
// skip 0 amount swaps
if (params.amountSpecified == 0) {
return (false, address(0), Currency.wrap(address(0)), 0, BeforeSwapDeltaLibrary.ZERO_DELTA);
}
// get pool state
PoolId id = key.toId();
Slot0 memory slot0 = s.slot0s[id];
PoolState memory bunniState = env.hub.poolState(id);
// hooklet call
bool feeOverridden;
uint24 feeOverride;
{
bool priceOverridden;
uint160 sqrtPriceX96Override;
(feeOverridden, feeOverride, priceOverridden, sqrtPriceX96Override) =
bunniState.hooklet.hookletBeforeSwap(sender, key, params);
// override price if needed
if (priceOverridden) {
slot0.sqrtPriceX96 = sqrtPriceX96Override;
slot0.tick = sqrtPriceX96Override.getTickAtSqrtPrice();
}
}
// ensure swap makes sense
if (
slot0.sqrtPriceX96 == 0
|| (
params.zeroForOne
&& (
params.sqrtPriceLimitX96 >= slot0.sqrtPriceX96
|| params.sqrtPriceLimitX96 <= TickMath.MIN_SQRT_PRICE
)
)
|| (
!params.zeroForOne
&& (
params.sqrtPriceLimitX96 <= slot0.sqrtPriceX96
|| params.sqrtPriceLimitX96 >= TickMath.MAX_SQRT_PRICE
)
) || params.amountSpecified > type(int128).max || params.amountSpecified < type(int128).min
) {
revert BunniHook__InvalidSwap();
}
// compute total token balances
(uint256 reserveBalance0, uint256 reserveBalance1) = (
getReservesInUnderlying(bunniState.reserve0, bunniState.vault0),
getReservesInUnderlying(bunniState.reserve1, bunniState.vault1)
);
(uint256 balance0, uint256 balance1) =
(bunniState.rawBalance0 + reserveBalance0, bunniState.rawBalance1 + reserveBalance1);
// decode hook params
DecodedHookParams memory hookParams = _decodeParams(bunniState.hookParams);
// update TWAP oracle
// do it before we fetch the arithmeticMeanTick
// which doesn't change the result but gives us updated index and cardinality
(Oracle.Observation memory updatedIntermediate, uint32 updatedIndex, uint32 updatedCardinality) =
_updateOracle(s, id, slot0.tick, hookParams.oracleMinInterval);
// get TWAP values
int24 arithmeticMeanTick;
int24 feeMeanTick;
bool useLDFTwap = bunniState.twapSecondsAgo != 0;
bool useFeeTwap = !feeOverridden && hookParams.feeTwapSecondsAgo != 0;
if (useLDFTwap && useFeeTwap) {
(int56 tickCumulatives0, int56 tickCumulatives1, int56 tickCumulatives2) = s.observations[id].observeTriple(
updatedIntermediate,
uint32(block.timestamp),
0,
bunniState.twapSecondsAgo,
hookParams.feeTwapSecondsAgo,
slot0.tick,
updatedIndex,
updatedCardinality
);
arithmeticMeanTick = int24((tickCumulatives0 - tickCumulatives1) / int56(uint56(bunniState.twapSecondsAgo)));
feeMeanTick = int24((tickCumulatives0 - tickCumulatives2) / int56(uint56(hookParams.feeTwapSecondsAgo)));
} else if (useLDFTwap) {
arithmeticMeanTick = _getTwap(
s, id, slot0.tick, bunniState.twapSecondsAgo, updatedIntermediate, updatedIndex, updatedCardinality
);
} else if (useFeeTwap) {
feeMeanTick = _getTwap(
s, id, slot0.tick, hookParams.feeTwapSecondsAgo, updatedIntermediate, updatedIndex, updatedCardinality
);
}
// query the LDF to get total liquidity and token densities
bytes32 ldfState = bunniState.ldfType == LDFType.DYNAMIC_AND_STATEFUL ? s.ldfStates[id] : bytes32(0);
(
uint256 totalLiquidity,
,
,
uint256 liquidityDensityOfRoundedTickX96,
uint256 currentActiveBalance0,
uint256 currentActiveBalance1,
bytes32 newLdfState,
bool shouldSurge
) = queryLDF({
key: key,
sqrtPriceX96: slot0.sqrtPriceX96,
tick: slot0.tick,
arithmeticMeanTick: arithmeticMeanTick,
ldf: bunniState.liquidityDensityFunction,
ldfParams: bunniState.ldfParams,
ldfState: ldfState,
balance0: balance0,
balance1: balance1,
idleBalance: bunniState.idleBalance
});
// ensure the current active balance of the requested output token is not zero
// or less than the requested output if it's an exact output swap
bool exactIn = params.amountSpecified < 0;
if (
params.zeroForOne && currentActiveBalance1 == 0 || !params.zeroForOne && currentActiveBalance0 == 0
|| totalLiquidity == 0
|| (
!exactIn
&& uint256(params.amountSpecified) > (params.zeroForOne ? currentActiveBalance1 : currentActiveBalance0)
)
) {
revert BunniHook__RequestedOutputExceedsBalance();
}
shouldSurge = shouldSurge && bunniState.ldfType != LDFType.STATIC; // only surge from LDF if LDF type is not static
if (bunniState.ldfType == LDFType.DYNAMIC_AND_STATEFUL) s.ldfStates[id] = newLdfState;
if (shouldSurge) {
// the LDF has been updated, so we need to update the idle balance
env.hub.hookSetIdleBalance(
key,
IdleBalanceLibrary.computeIdleBalance(currentActiveBalance0, currentActiveBalance1, balance0, balance1)
);
}
// check surge based on vault share prices
shouldSurge =
shouldSurge || _shouldSurgeFromVaults(s, id, bunniState, hookParams, reserveBalance0, reserveBalance1);
// compute swap result
(uint160 updatedSqrtPriceX96, int24 updatedTick, uint256 inputAmount, uint256 outputAmount) = BunniSwapMath
.computeSwap({
input: BunniSwapMath.BunniComputeSwapInput({
key: key,
totalLiquidity: totalLiquidity,
liquidityDensityOfRoundedTickX96: liquidityDensityOfRoundedTickX96,
currentActiveBalance0: currentActiveBalance0,
currentActiveBalance1: currentActiveBalance1,
sqrtPriceX96: slot0.sqrtPriceX96,
currentTick: slot0.tick,
liquidityDensityFunction: bunniState.liquidityDensityFunction,
arithmeticMeanTick: arithmeticMeanTick,
ldfParams: bunniState.ldfParams,
ldfState: ldfState,
swapParams: params
})
});
// revert if it's an exact output swap and outputAmount < params.amountSpecified
if (!exactIn && outputAmount < uint256(params.amountSpecified)) {
revert BunniHook__InsufficientOutput();
}
// ensure swap never moves price in the opposite direction
// ensure the inputAmount and outputAmount are non-zero
if (
(params.zeroForOne && updatedSqrtPriceX96 > slot0.sqrtPriceX96)
|| (!params.zeroForOne && updatedSqrtPriceX96 < slot0.sqrtPriceX96)
|| (outputAmount == 0 || inputAmount == 0)
) {
revert BunniHook__InvalidSwap();
}
// update slot0
uint32 lastSurgeTimestamp = slot0.lastSurgeTimestamp;
{
uint32 blockTimestamp32 = uint32(block.timestamp);
if (shouldSurge) {
// use unchecked so that if uint32 overflows we wrap around
// overflows are ok since we only look at differences
unchecked {
uint32 timeSinceLastSwap = blockTimestamp32 - slot0.lastSwapTimestamp;
// if more than `surgeFeeAutostartThreshold` seconds has passed since the last swap,
// we pretend that the surge started at `slot0.lastSwapTimestamp + surgeFeeAutostartThreshold`
// so that the pool never gets stuck with a high fee
lastSurgeTimestamp = timeSinceLastSwap >= hookParams.surgeFeeAutostartThreshold
? slot0.lastSwapTimestamp + hookParams.surgeFeeAutostartThreshold
: blockTimestamp32;
}
}
s.slot0s[id] = Slot0({
sqrtPriceX96: updatedSqrtPriceX96,
tick: updatedTick,
lastSwapTimestamp: blockTimestamp32,
lastSurgeTimestamp: lastSurgeTimestamp
});
}
// update am-AMM state
uint24 amAmmSwapFee;
if (hookParams.amAmmEnabled) {
bytes6 payload;
IAmAmm.Bid memory topBid = IAmAmm(address(this)).getTopBidWrite(id);
(amAmmManager, payload) = (topBid.manager, topBid.payload);
(uint24 swapFee0For1, uint24 swapFee1For0) = decodeAmAmmPayload(payload);
amAmmSwapFee = params.zeroForOne ? swapFee0For1 : swapFee1For0;
}
// charge swap fee
// precedence:
// 1) am-AMM fee
// 2) hooklet override fee
// 3) dynamic fee
(Currency inputToken, Currency outputToken) =
params.zeroForOne ? (key.currency0, key.currency1) : (key.currency1, key.currency0);
uint24 swapFee;
uint256 swapFeeAmount;
useAmAmmFee = hookParams.amAmmEnabled && amAmmManager != address(0);
// swap fee used as the basis for computing hookFees when useAmAmmFee == true
// this is to avoid a malicious am-AMM manager bypassing hookFees
// by setting the swap fee to max and offering a proxy swap contract
// that sets the Bunni swap fee to 0 during such swaps and charging swap fees
// independently
uint24 hookFeesBaseSwapFee = feeOverridden
? feeOverride
: computeDynamicSwapFee(
updatedSqrtPriceX96,
feeMeanTick,
lastSurgeTimestamp,
hookParams.feeMin,
hookParams.feeMax,
hookParams.feeQuadraticMultiplier,
hookParams.surgeFeeHalfLife
);
swapFee = useAmAmmFee
? uint24(FixedPointMathLib.max(amAmmSwapFee, computeSurgeFee(lastSurgeTimestamp, hookParams.surgeFeeHalfLife)))
: hookFeesBaseSwapFee;
uint256 hookFeesAmount;
uint256 hookHandleSwapInputAmount;
uint256 hookHandleSwapOutoutAmount;
if (exactIn) {
// compute the swap fee and the hook fee (i.e. protocol fee)
// swap fee is taken by decreasing the output amount
swapFeeAmount = outputAmount.mulDivUp(swapFee, SWAP_FEE_BASE);
if (useAmAmmFee) {
// instead of computing hook fees as a portion of the swap fee
// and deducting it, we compute hook fees separately using hookFeesBaseSwapFee
// and charge it as an extra fee on the swap
hookFeesAmount = outputAmount.mulDivUp(hookFeesBaseSwapFee, SWAP_FEE_BASE).mulDivUp(
env.hookFeeModifier, MODIFIER_BASE
);
} else {
hookFeesAmount = swapFeeAmount.mulDivUp(env.hookFeeModifier, MODIFIER_BASE);
swapFeeAmount -= hookFeesAmount;
}
// set the am-AMM fee to be the swap fee amount
// don't need to check if am-AMM is enabled since if it isn't
// BunniHook.beforeSwap() simply ignores the returned values
// this saves gas by avoiding an if statement
(amAmmFeeCurrency, amAmmFeeAmount) = (outputToken, swapFeeAmount);
// modify output amount with fees
outputAmount -= swapFeeAmount + hookFeesAmount;
// return beforeSwapDelta
// take in max(amountSpecified, inputAmount) such that if amountSpecified is greater we just happily accept it
int256 actualInputAmount = FixedPointMathLib.max(-params.amountSpecified, inputAmount.toInt256());
inputAmount = uint256(actualInputAmount);
beforeSwapDelta = toBeforeSwapDelta({
deltaSpecified: actualInputAmount.toInt128(),
deltaUnspecified: -outputAmount.toInt256().toInt128()
});
// if am-AMM is used, the swap fee needs to be taken from BunniHub, else it stays in BunniHub with the LPs
(hookHandleSwapInputAmount, hookHandleSwapOutoutAmount) = (
inputAmount, useAmAmmFee ? outputAmount + swapFeeAmount + hookFeesAmount : outputAmount + hookFeesAmount
);
} else {
// compute the swap fee and the hook fee (i.e. protocol fee)
// swap fee is taken by increasing the input amount
// need to modify fee rate to maintain the same average price as exactIn case
// in / (out * (1 - fee)) = in * (1 + fee') / out => fee' = fee / (1 - fee)
swapFeeAmount = inputAmount.mulDivUp(swapFee, SWAP_FEE_BASE - swapFee);
if (useAmAmmFee) {
// instead of computing hook fees as a portion of the swap fee
// and deducting it, we compute hook fees separately using hookFeesBaseSwapFee
// and charge it as an extra fee on the swap
hookFeesAmount = inputAmount.mulDivUp(hookFeesBaseSwapFee, SWAP_FEE_BASE - hookFeesBaseSwapFee).mulDivUp(
env.hookFeeModifier, MODIFIER_BASE
);
} else {
hookFeesAmount = swapFeeAmount.mulDivUp(env.hookFeeModifier, MODIFIER_BASE);
swapFeeAmount -= hookFeesAmount;
}
// set the am-AMM fee to be the swap fee amount
// don't need to check if am-AMM is enabled since if it isn't
// BunniHook.beforeSwap() simply ignores the returned values
// this saves gas by avoiding an if statement
(amAmmFeeCurrency, amAmmFeeAmount) = (inputToken, swapFeeAmount);
// modify input amount with fees
inputAmount += swapFeeAmount + hookFeesAmount;
// return beforeSwapDelta
// give out min(amountSpecified, outputAmount) such that we only give out as much as requested
int256 actualOutputAmount = FixedPointMathLib.min(params.amountSpecified, outputAmount.toInt256());
outputAmount = uint256(actualOutputAmount);
beforeSwapDelta = toBeforeSwapDelta({
deltaSpecified: -actualOutputAmount.toInt128(),
deltaUnspecified: inputAmount.toInt256().toInt128()
});
// if am-AMM is not used, the swap fee needs to be sent to BunniHub to the LPs, else it stays in BunniHook with the am-AMM manager
(hookHandleSwapInputAmount, hookHandleSwapOutoutAmount) = (
useAmAmmFee ? inputAmount - swapFeeAmount - hookFeesAmount : inputAmount - hookFeesAmount, outputAmount
);
}
// take input by minting claim tokens to hook
env.poolManager.mint(address(this), inputToken.toId(), inputAmount);
// call hub to handle swap
// - pull input claim tokens from hook
// - push output tokens to pool manager and mint claim tokens to hook
// - update raw token balances
env.hub.hookHandleSwap(key, params.zeroForOne, hookHandleSwapInputAmount, hookHandleSwapOutoutAmount);
// burn output claim tokens
env.poolManager.burn(address(this), outputToken.toId(), outputAmount);
// distribute part of hookFees to referrers
if (hookFeesAmount != 0) {
uint256 referrerRewardAmount = hookFeesAmount.mulDiv(env.referralRewardModifier, MODIFIER_BASE);
if (referrerRewardAmount != 0) {
if (!env.poolManager.isOperator(address(this), address(bunniState.bunniToken))) {
env.poolManager.setOperator(address(bunniState.bunniToken), true);
}
bool isToken0 = exactIn != params.zeroForOne;
bunniState.bunniToken.distributeReferralRewards(isToken0, referrerRewardAmount);
}
}
// emit swap event
emit IBunniHook.Swap(
id,
sender,
exactIn,
params.zeroForOne,
inputAmount,
outputAmount,
updatedSqrtPriceX96,
updatedTick,
swapFee,
totalLiquidity
);
// we should attempt to rebalance if:
// 1) rebalanceThreshold != 0, i.e. rebalancing is enabled
// 2.a) either shouldSurge == true, since tokens can only go out of balance due to shifting or vault returns, or:
// 2.b) the deadline of the last rebalance order has passed and the order wasn't executed, in which case we should reattempt to rebalance
uint256 rebalanceOrderDeadline = shouldSurge ? 0 : s.rebalanceOrderDeadline[id]; // gas: only do SLOAD if shouldSurge == false
if (
hookParams.rebalanceThreshold != 0
&& (shouldSurge || (block.timestamp > rebalanceOrderDeadline && rebalanceOrderDeadline != 0))
) {
if (shouldSurge) {
// surging makes any existing rebalance order meaningless
// since the desired token ratio will be different
// clear the existing rebalance order
delete s.rebalanceOrderHash[id];
delete s.rebalanceOrderPermit2Hash[id];
delete s.rebalanceOrderDeadline[id];
}
RebalanceLogic.rebalance(
s,
env,
RebalanceInput({
id: id,
key: key,
updatedTick: updatedTick,
updatedSqrtPriceX96: updatedSqrtPriceX96,
arithmeticMeanTick: arithmeticMeanTick,
newLdfState: newLdfState,
hookParams: hookParams,
updatedIntermediate: updatedIntermediate,
updatedIndex: updatedIndex,
updatedCardinality: updatedCardinality
})
);
}
// hooklet call
if (bunniState.hooklet.hasPermission(HookletLib.AFTER_SWAP_FLAG)) {
bunniState.hooklet.hookletAfterSwap(
sender,
key,
params,
IHooklet.SwapReturnData({
updatedSqrtPriceX96: updatedSqrtPriceX96,
updatedTick: updatedTick,
inputAmount: inputAmount,
outputAmount: outputAmount,
swapFee: swapFee,
totalLiquidity: totalLiquidity
})
);
}
}
function recomputeIdleBalance(HookStorage storage s, IBunniHub hub, PoolKey calldata key) external {
PoolId id = key.toId();
PoolState memory bunniState = hub.poolState(id);
Slot0 memory slot0 = s.slot0s[id];
(uint256 balance0, uint256 balance1) = (
bunniState.rawBalance0 + getReservesInUnderlying(bunniState.reserve0, bunniState.vault0),
bunniState.rawBalance1 + getReservesInUnderlying(bunniState.reserve1, bunniState.vault1)
);
int24 arithmeticMeanTick = bunniState.twapSecondsAgo == 0
? int24(0)
: _getTwap(
s,
id,
slot0.tick,
bunniState.twapSecondsAgo,
s.states[id].intermediateObservation,
s.states[id].index,
s.states[id].cardinality
);
bytes32 ldfState = bunniState.ldfType == LDFType.DYNAMIC_AND_STATEFUL ? s.ldfStates[id] : bytes32(0);
(,,,, uint256 currentActiveBalance0, uint256 currentActiveBalance1,,) = queryLDF({
key: key,
sqrtPriceX96: slot0.sqrtPriceX96,
tick: slot0.tick,
arithmeticMeanTick: arithmeticMeanTick,
ldf: bunniState.liquidityDensityFunction,
ldfParams: bunniState.ldfParams,
ldfState: ldfState,
balance0: balance0,
balance1: balance1,
idleBalance: IdleBalanceLibrary.ZERO // set to zero since we're recomputing the idle balance and shouldSurge isn't necessarily true
});
hub.hookSetIdleBalance(
key, IdleBalanceLibrary.computeIdleBalance(currentActiveBalance0, currentActiveBalance1, balance0, balance1)
);
}
function isValidParams(bytes calldata hookParams) external pure returns (bool) {
DecodedHookParams memory p = _decodeParams(hookParams);
unchecked {
return (p.feeMin <= p.feeMax) && (p.feeMax < SWAP_FEE_BASE)
&& (p.feeQuadraticMultiplier == 0 || p.feeMin == p.feeMax || p.feeTwapSecondsAgo != 0)
&& (uint256(p.surgeFeeHalfLife) * uint256(p.vaultSurgeThreshold0) * uint256(p.vaultSurgeThreshold1) != 0)
&& (p.surgeFeeHalfLife < MAX_SURGE_HALFLIFE && p.surgeFeeAutostartThreshold < MAX_SURGE_AUTOSTART_TIME)
&& (
(
p.rebalanceThreshold == 0 && p.rebalanceMaxSlippage == 0 && p.rebalanceTwapSecondsAgo == 0
&& p.rebalanceOrderTTL == 0
)
|| (
p.rebalanceThreshold != 0 && p.rebalanceMaxSlippage != 0
&& p.rebalanceMaxSlippage < REBALANCE_MAX_SLIPPAGE_BASE && p.rebalanceTwapSecondsAgo != 0
&& p.rebalanceTwapSecondsAgo < MAX_REBALANCE_TWAP_SECONDS_AGO && p.rebalanceOrderTTL != 0
&& p.rebalanceOrderTTL < MAX_REBALANCE_ORDER_TTL
)
) && (p.oracleMinInterval != 0)
&& (!p.amAmmEnabled || (p.maxAmAmmFee != 0 && p.maxAmAmmFee <= MAX_AMAMM_FEE && p.minRentMultiplier != 0));
}
}
function decodeHookParams(bytes calldata hookParams) external pure returns (DecodedHookParams memory p) {
return _decodeParams(hookParams);
}
function observe(HookStorage storage s, PoolKey calldata key, uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives)
{
PoolId id = key.toId();
IBunniHook.ObservationState memory state = s.states[id];
Slot0 memory slot0 = s.slot0s[id];
return s.observations[id].observe(
state.intermediateObservation,
uint32(block.timestamp),
secondsAgos,
slot0.tick,
state.index,
state.cardinality
);
}
/// -----------------------------------------------------------------------
/// Internal utility functions
/// -----------------------------------------------------------------------
/// @dev Checks if the pool should surge based on the vault share price changes since the last swap.
/// Also updates vaultSharePricesAtLastSwap.
function _shouldSurgeFromVaults(
HookStorage storage s,
PoolId id,
PoolState memory bunniState,
DecodedHookParams memory hookParams,
uint256 reserveBalance0,
uint256 reserveBalance1
) private returns (bool shouldSurge) {
if (address(bunniState.vault0) != address(0) || address(bunniState.vault1) != address(0)) {
// only surge if at least one vault is set because otherwise total liquidity won't automatically increase
// so there's no risk of being sandwiched
// load share prices at last swap
VaultSharePrices memory prevSharePrices = s.vaultSharePricesAtLastSwap[id];
// compute current share prices
uint120 sharePrice0 =
bunniState.reserve0 == 0 ? 0 : reserveBalance0.divWadUp(bunniState.reserve0).toUint120();
uint120 sharePrice1 =
bunniState.reserve1 == 0 ? 0 : reserveBalance1.divWadUp(bunniState.reserve1).toUint120();
// compare with share prices at last swap to see if we need to apply the surge fee
// surge fee is applied if the share price has increased by more than 1 / vaultSurgeThreshold
shouldSurge = prevSharePrices.initialized
&& (
dist(sharePrice0, prevSharePrices.sharePrice0)
> prevSharePrices.sharePrice0 / hookParams.vaultSurgeThreshold0
|| dist(sharePrice1, prevSharePrices.sharePrice1)
> prevSharePrices.sharePrice1 / hookParams.vaultSurgeThreshold1
);
// update share prices at last swap
if (
!prevSharePrices.initialized || sharePrice0 != prevSharePrices.sharePrice0
|| sharePrice1 != prevSharePrices.sharePrice1
) {
s.vaultSharePricesAtLastSwap[id] =
VaultSharePrices({initialized: true, sharePrice0: sharePrice0, sharePrice1: sharePrice1});
}
}
}
function _getTwap(
HookStorage storage s,
PoolId id,
int24 currentTick,
uint32 twapSecondsAgo,
Oracle.Observation memory updatedIntermediate,
uint32 updatedIndex,
uint32 updatedCardinality
) internal view returns (int24 arithmeticMeanTick) {
(int56 tickCumulative0, int56 tickCumulative1) = s.observations[id].observeDouble(
updatedIntermediate,
uint32(block.timestamp),
twapSecondsAgo,
0,
currentTick,
updatedIndex,
updatedCardinality
);
int56 tickCumulativesDelta = tickCumulative1 - tickCumulative0;
arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(twapSecondsAgo)));
}
function _updateOracle(HookStorage storage s, PoolId id, int24 tick, uint32 oracleMinInterval)
internal
returns (Oracle.Observation memory updatedIntermediate, uint32 updatedIndex, uint32 updatedCardinality)
{
IBunniHook.ObservationState memory state = s.states[id];
(updatedIntermediate, updatedIndex, updatedCardinality) = s.observations[id].write(
state.intermediateObservation,
state.index,
uint32(block.timestamp),
tick,
state.cardinality,
state.cardinalityNext,
oracleMinInterval
);
(s.states[id].intermediateObservation, s.states[id].index, s.states[id].cardinality) =
(updatedIntermediate, updatedIndex, updatedCardinality);
}
/// @dev Decodes hookParams into params used by this hook
/// @param hookParams The hook params raw bytes
/// @return p The decoded params struct
function _decodeParams(bytes memory hookParams) internal pure returns (DecodedHookParams memory p) {
// | feeMin - 3 bytes | feeMax - 3 bytes | feeQuadraticMultiplier - 3 bytes | feeTwapSecondsAgo - 3 bytes | maxAmAmmFee - 3 bytes | surgeFeeHalfLife - 2 bytes | surgeFeeAutostartThreshold - 2 bytes | vaultSurgeThreshold0 - 2 bytes | vaultSurgeThreshold1 - 2 bytes | rebalanceThreshold - 2 bytes | rebalanceMaxSlippage - 2 bytes | rebalanceTwapSecondsAgo - 2 bytes | rebalanceOrderTTL - 2 bytes | amAmmEnabled - 1 byte |
bytes32 firstWord;
// | oracleMinInterval - 4 bytes | minRentMultiplier - 6 bytes |
bytes32 secondWord;
/// @solidity memory-safe-assembly
assembly {
firstWord := mload(add(hookParams, 32))
secondWord := mload(add(hookParams, 64))
}
p.feeMin = uint24(bytes3(firstWord));
p.feeMax = uint24(bytes3(firstWord << 24));
p.feeQuadraticMultiplier = uint24(bytes3(firstWord << 48));
p.feeTwapSecondsAgo = uint24(bytes3(firstWord << 72));
p.maxAmAmmFee = uint24(bytes3(firstWord << 96));
p.surgeFeeHalfLife = uint16(bytes2(firstWord << 120));
p.surgeFeeAutostartThreshold = uint16(bytes2(firstWord << 136));
p.vaultSurgeThreshold0 = uint16(bytes2(firstWord << 152));
p.vaultSurgeThreshold1 = uint16(bytes2(firstWord << 168));
p.rebalanceThreshold = uint16(bytes2(firstWord << 184));
p.rebalanceMaxSlippage = uint16(bytes2(firstWord << 200));
p.rebalanceTwapSecondsAgo = uint16(bytes2(firstWord << 216));
p.rebalanceOrderTTL = uint16(bytes2(firstWord << 232));
p.amAmmEnabled = uint8(bytes1(firstWord << 248)) != 0;
p.oracleMinInterval = uint32(bytes4(secondWord));
p.minRentMultiplier = uint48(bytes6(secondWord << 32));
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {IPoolManager, PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import "./Math.sol";
import "../base/Errors.sol";
import "../base/Constants.sol";
import "../types/IdleBalance.sol";
import {SwapMath} from "./SwapMath.sol";
import {queryLDF} from "./QueryLDF.sol";
import {FullMathX96} from "./FullMathX96.sol";
import {SqrtPriceMath} from "./SqrtPriceMath.sol";
import {LiquidityAmounts} from "./LiquidityAmounts.sol";
import {ILiquidityDensityFunction} from "../interfaces/ILiquidityDensityFunction.sol";
library BunniSwapMath {
using TickMath for *;
using FullMathX96 for *;
using SafeCastLib for uint256;
using FixedPointMathLib for uint256;
/// @dev An infinitesimal fee rate is applied to naive swaps to protect against exact input vs exact output rate mismatches when swap amounts/liquidity are small.
/// The current value corresponds to 0.003%.
uint24 private constant EPSILON_FEE = 30;
struct BunniComputeSwapInput {
PoolKey key;
uint256 totalLiquidity;
uint256 liquidityDensityOfRoundedTickX96;
uint256 currentActiveBalance0;
uint256 currentActiveBalance1;
uint160 sqrtPriceX96;
int24 currentTick;
ILiquidityDensityFunction liquidityDensityFunction;
int24 arithmeticMeanTick;
bytes32 ldfParams;
bytes32 ldfState;
IPoolManager.SwapParams swapParams;
}
/// @notice Computes the result of a swap given the input parameters
/// @param input The input parameters for the swap
/// @return updatedSqrtPriceX96 The updated sqrt price after the swap
/// @return updatedTick The updated tick after the swap
/// @return inputAmount The input amount of the swap
/// @return outputAmount The output amount of the swap
function computeSwap(BunniComputeSwapInput calldata input)
external
view
returns (uint160 updatedSqrtPriceX96, int24 updatedTick, uint256 inputAmount, uint256 outputAmount)
{
bool zeroForOne = input.swapParams.zeroForOne;
bool exactIn = input.swapParams.amountSpecified < 0;
// initialize input and output amounts based on initial info
inputAmount = exactIn ? uint256(-input.swapParams.amountSpecified) : 0;
outputAmount = exactIn ? 0 : uint256(input.swapParams.amountSpecified);
// compute updated rounded tick liquidity
uint256 updatedRoundedTickLiquidity = (input.totalLiquidity * input.liquidityDensityOfRoundedTickX96) >> 96;
// initialize updatedTick to the current tick
updatedTick = input.currentTick;
// bound sqrtPriceLimitX96 by min/max possible values
uint160 sqrtPriceLimitX96 = input.swapParams.sqrtPriceLimitX96;
{
(uint160 minSqrtPrice, uint160 maxSqrtPrice) = (
TickMath.minUsableTick(input.key.tickSpacing).getSqrtPriceAtTick(),
TickMath.maxUsableTick(input.key.tickSpacing).getSqrtPriceAtTick()
);
// bound sqrtPriceLimit so that we never end up at an invalid rounded tick
if ((zeroForOne && sqrtPriceLimitX96 <= minSqrtPrice) || (!zeroForOne && sqrtPriceLimitX96 >= maxSqrtPrice))
{
sqrtPriceLimitX96 = zeroForOne ? minSqrtPrice + 1 : maxSqrtPrice - 1;
}
}
{
(int24 roundedTick, int24 nextRoundedTick) = roundTick(input.currentTick, input.key.tickSpacing);
uint160 naiveSwapResultSqrtPriceX96;
uint256 naiveSwapAmountIn;
uint256 naiveSwapAmountOut;
{
// handle the special case when we don't cross rounded ticks
if (updatedRoundedTickLiquidity != 0) {
// compute the resulting sqrt price using Uniswap math
int24 tickNext = zeroForOne ? roundedTick : nextRoundedTick;
uint160 sqrtPriceNextX96 = TickMath.getSqrtPriceAtTick(tickNext);
(naiveSwapResultSqrtPriceX96, naiveSwapAmountIn, naiveSwapAmountOut) = SwapMath.computeSwapStep({
sqrtPriceCurrentX96: input.sqrtPriceX96,
sqrtPriceTargetX96: SwapMath.getSqrtPriceTarget(zeroForOne, sqrtPriceNextX96, sqrtPriceLimitX96),
liquidity: updatedRoundedTickLiquidity,
amountRemaining: input.swapParams.amountSpecified,
feePips: 0
});
// check if naive swap exhausted the specified amount
if (
exactIn
? naiveSwapAmountIn == uint256(-input.swapParams.amountSpecified)
: naiveSwapAmountOut == uint256(input.swapParams.amountSpecified)
) {
// swap doesn't cross rounded tick
// compute the updated tick
// was initialized earlier as input.currentTick
if (naiveSwapResultSqrtPriceX96 == sqrtPriceNextX96) {
// Equivalent to `updatedTick = zeroForOne ? tickNext - 1 : tickNext;`
unchecked {
// cannot cast a bool to an int24 in Solidity
int24 _zeroForOne;
assembly {
_zeroForOne := zeroForOne
}
updatedTick = tickNext - _zeroForOne;
}
} else if (naiveSwapResultSqrtPriceX96 != input.sqrtPriceX96) {
// recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
updatedTick = TickMath.getTickAtSqrtPrice(naiveSwapResultSqrtPriceX96);
}
// naiveSwapAmountOut should be at most the corresponding active balance
// this may be violated due to precision loss
naiveSwapAmountOut = FixedPointMathLib.min(
naiveSwapAmountOut, zeroForOne ? input.currentActiveBalance1 : input.currentActiveBalance0
);
// early return
return (naiveSwapResultSqrtPriceX96, updatedTick, naiveSwapAmountIn, naiveSwapAmountOut);
}
}
}
// swap crosses rounded tick
// need to use LDF to compute the swap
// compute updated sqrt ratio & tick
uint256 inverseCumulativeAmountFnInput;
if (exactIn) {
// exact input swap
inverseCumulativeAmountFnInput =
zeroForOne ? input.currentActiveBalance0 + inputAmount : input.currentActiveBalance1 + inputAmount;
} else {
// exact output swap
inverseCumulativeAmountFnInput =
zeroForOne ? input.currentActiveBalance1 - outputAmount : input.currentActiveBalance0 - outputAmount;
}
(
bool success,
int24 updatedRoundedTick,
uint256 cumulativeAmount0,
uint256 cumulativeAmount1,
uint256 swapLiquidity
) = input.liquidityDensityFunction.computeSwap(
input.key,
inverseCumulativeAmountFnInput,
input.totalLiquidity,
zeroForOne,
exactIn,
input.arithmeticMeanTick,
input.currentTick,
input.ldfParams,
input.ldfState
);
if (success) {
// edge case: LDF says we're still in the same rounded tick
// or in a rounded tick in the opposite direction as the swap
// meaning first naive swap was insufficient but it should have been
// use the result from the first naive swap
if (zeroForOne ? updatedRoundedTick >= roundedTick : updatedRoundedTick <= roundedTick) {
if (updatedRoundedTickLiquidity == 0) {
// no liquidity, return trivial swap
return (input.sqrtPriceX96, input.currentTick, 0, 0);
}
// compute the updated tick
// was initialized earlier as input.currentTick
int24 _tickNext = zeroForOne ? roundedTick : nextRoundedTick;
if (naiveSwapResultSqrtPriceX96 == TickMath.getSqrtPriceAtTick(_tickNext)) {
// Equivalent to `updatedTick = zeroForOne ? _tickNext - 1 : _tickNext;`
unchecked {
// cannot cast a bool to an int24 in Solidity
int24 _zeroForOne;
assembly {
_zeroForOne := zeroForOne
}
updatedTick = _tickNext - _zeroForOne;
}
} else if (naiveSwapResultSqrtPriceX96 != input.sqrtPriceX96) {
// recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
updatedTick = TickMath.getTickAtSqrtPrice(naiveSwapResultSqrtPriceX96);
}
// naiveSwapAmountOut should be at most the corresponding active balance
// this may be violated due to precision loss
naiveSwapAmountOut = FixedPointMathLib.min(
naiveSwapAmountOut, zeroForOne ? input.currentActiveBalance1 : input.currentActiveBalance0
);
// early return
return (naiveSwapResultSqrtPriceX96, updatedTick, naiveSwapAmountIn, naiveSwapAmountOut);
}
// use Uniswap math to compute updated sqrt price
// the swap is called "partial swap"
// which always has the same exactIn and zeroForOne as the overall swap
(int24 tickStart, int24 tickNext) = zeroForOne
? (updatedRoundedTick + input.key.tickSpacing, updatedRoundedTick)
: (updatedRoundedTick, updatedRoundedTick + input.key.tickSpacing);
uint160 startSqrtPriceX96 = tickStart.getSqrtPriceAtTick();
// make sure the price limit is not reached
if (
(zeroForOne && sqrtPriceLimitX96 <= startSqrtPriceX96)
|| (!zeroForOne && sqrtPriceLimitX96 >= startSqrtPriceX96)
) {
uint160 sqrtPriceNextX96 = tickNext.getSqrtPriceAtTick();
// adjust the cumulativeAmount of the input token to be at least the corresponding currentActiveBalance
// we know that we're swapping in a different rounded tick as the starting one (based on the first naive swap)
// so this should be true but sometimes isn't due to precision error which is why the adjustment is necessary
if (zeroForOne) {
cumulativeAmount0 = FixedPointMathLib.max(cumulativeAmount0, input.currentActiveBalance0);
} else {
cumulativeAmount1 = FixedPointMathLib.max(cumulativeAmount1, input.currentActiveBalance1);
}
// perform naive swap within the updated rounded tick
bool hitSqrtPriceLimit;
if (swapLiquidity == 0 || sqrtPriceLimitX96 == startSqrtPriceX96) {
// don't move from the starting price
(naiveSwapResultSqrtPriceX96, naiveSwapAmountIn, naiveSwapAmountOut) = (startSqrtPriceX96, 0, 0);
} else {
// has swap liquidity, use Uniswap math to compute updated sqrt price and input/output amounts
int256 amountSpecifiedRemaining = exactIn
? -(inverseCumulativeAmountFnInput - (zeroForOne ? cumulativeAmount0 : cumulativeAmount1)).toInt256(
)
: ((zeroForOne ? cumulativeAmount1 : cumulativeAmount0) - inverseCumulativeAmountFnInput)
.toInt256();
(naiveSwapResultSqrtPriceX96, naiveSwapAmountIn, naiveSwapAmountOut) = SwapMath.computeSwapStep({
sqrtPriceCurrentX96: startSqrtPriceX96,
sqrtPriceTargetX96: SwapMath.getSqrtPriceTarget(zeroForOne, sqrtPriceNextX96, sqrtPriceLimitX96),
liquidity: swapLiquidity,
amountRemaining: amountSpecifiedRemaining,
feePips: EPSILON_FEE
});
if (naiveSwapResultSqrtPriceX96 == sqrtPriceLimitX96 && sqrtPriceLimitX96 != sqrtPriceNextX96) {
// give up if the swap hits the sqrt price limit
hitSqrtPriceLimit = true;
}
}
if (!hitSqrtPriceLimit) {
// initialize updatedTick to tickStart
updatedTick = tickStart;
// compute updatedTick
if (naiveSwapResultSqrtPriceX96 == sqrtPriceNextX96) {
// Equivalent to `updatedTick = zeroForOne ? tickNext - 1 : tickNext;`
unchecked {
// cannot cast a bool to an int24 in Solidity
int24 _zeroForOne;
assembly {
_zeroForOne := zeroForOne
}
updatedTick = tickNext - _zeroForOne;
}
} else if (naiveSwapResultSqrtPriceX96 != startSqrtPriceX96) {
// recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
updatedTick = TickMath.getTickAtSqrtPrice(naiveSwapResultSqrtPriceX96);
}
// set updatedSqrtPriceX96
updatedSqrtPriceX96 = naiveSwapResultSqrtPriceX96;
if (
exactIn
? naiveSwapAmountIn == uint256(-input.swapParams.amountSpecified)
: naiveSwapAmountOut == uint256(input.swapParams.amountSpecified)
) {
// edge case: the partial swap consumed the entire amount specified
// return the result of the partial swap directly
// naiveSwapAmountOut should be at most the corresponding active balance
// this may be violated due to precision loss
naiveSwapAmountOut = FixedPointMathLib.min(
naiveSwapAmountOut,
zeroForOne ? input.currentActiveBalance1 : input.currentActiveBalance0
);
return (naiveSwapResultSqrtPriceX96, updatedTick, naiveSwapAmountIn, naiveSwapAmountOut);
}
if (
(zeroForOne && cumulativeAmount1 < naiveSwapAmountOut)
|| (!zeroForOne && cumulativeAmount0 < naiveSwapAmountOut)
) {
// in rare cases the rounding error can cause one of the active balances to be negative
// revert in such cases to avoid leaking value
revert BunniSwapMath__SwapFailed();
}
(uint256 updatedActiveBalance0, uint256 updatedActiveBalance1) = zeroForOne
? (cumulativeAmount0 + naiveSwapAmountIn, cumulativeAmount1 - naiveSwapAmountOut)
: (cumulativeAmount0 - naiveSwapAmountOut, cumulativeAmount1 + naiveSwapAmountIn);
// compute input and output token amounts
// NOTE: The rounding direction of all the values involved are correct:
// - cumulative amounts are rounded up
// - naiveSwapAmountIn is rounded up
// - naiveSwapAmountOut is rounded down
// - currentActiveBalance0 and currentActiveBalance1 are rounded down
// Overall this leads to inputAmount being rounded up and outputAmount being rounded down
// which is safe.
// Use subReLU so that when the computed output is somehow negative (most likely due to precision loss)
// we output 0 instead of reverting.
(inputAmount, outputAmount) = zeroForOne
? (
updatedActiveBalance0 - input.currentActiveBalance0,
subReLU(input.currentActiveBalance1, updatedActiveBalance1)
)
: (
updatedActiveBalance1 - input.currentActiveBalance1,
subReLU(input.currentActiveBalance0, updatedActiveBalance0)
);
return (updatedSqrtPriceX96, updatedTick, inputAmount, outputAmount);
}
}
}
}
// the sqrt price limit has been reached
(updatedSqrtPriceX96, updatedTick) = (
sqrtPriceLimitX96,
sqrtPriceLimitX96 == input.sqrtPriceX96 ? input.currentTick : sqrtPriceLimitX96.getTickAtSqrtPrice() // recompute tick unless we haven't moved
);
// Rounding directions:
// currentActiveBalance: down
// totalDensity: up
// updatedActiveBalance: up
(, uint256 totalDensity0X96, uint256 totalDensity1X96,,,,,) = queryLDF({
key: input.key,
sqrtPriceX96: updatedSqrtPriceX96,
tick: updatedTick,
arithmeticMeanTick: input.arithmeticMeanTick,
ldf: input.liquidityDensityFunction,
ldfParams: input.ldfParams,
ldfState: input.ldfState,
balance0: 0,
balance1: 0,
idleBalance: IdleBalanceLibrary.ZERO
});
(uint256 _updatedActiveBalance0, uint256 _updatedActiveBalance1) =
(totalDensity0X96.fullMulX96Up(input.totalLiquidity), totalDensity1X96.fullMulX96Up(input.totalLiquidity));
// Use subReLU so that when the computed output is somehow negative (most likely due to precision loss)
// we output 0 instead of reverting.
if (zeroForOne) {
(inputAmount, outputAmount) = (
_updatedActiveBalance0 - input.currentActiveBalance0,
subReLU(input.currentActiveBalance1, _updatedActiveBalance1)
);
} else {
(inputAmount, outputAmount) = (
_updatedActiveBalance1 - input.currentActiveBalance1,
subReLU(input.currentActiveBalance0, _updatedActiveBalance0)
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
pragma abicoder v2;
uint256 constant WAD = 1e18;
uint256 constant Q96 = 0x1000000000000000000000000;
uint256 constant MAX_NONCE = 1e6;
uint256 constant MIN_INITIAL_SHARES = 1e12;
uint256 constant MAX_SWAP_FEE_RATIO = 2.88e20; // max ratio that avoids overflow in swap fee calculation, roughly sqrt(SWAP_FEE_BASE) * sqrt(sqrt((type(uint256).max - SWAP_FEE_BASE) / type(uint24).max) - 1)
uint256 constant SWAP_FEE_BASE = 1e6;
uint256 constant SWAP_FEE_BASE_SQUARED = 1e12;
uint256 constant RAW_TOKEN_RATIO_BASE = 1e6;
uint256 constant LN2_WAD = 693147180559945309;
uint256 constant MAX_VAULT_FEE_ERROR = 1e6;
uint256 constant MAX_CARDINALITY = 2 ** 24 - 1;
uint56 constant WITHDRAW_DELAY = 1 minutes;
uint56 constant WITHDRAW_GRACE_PERIOD = 3 minutes;
uint256 constant REFERRAL_REWARD_PER_TOKEN_PRECISION = 1e30;
uint256 constant MODIFIER_BASE = 1e6;
uint256 constant MIN_DEPOSIT_BALANCE_INCREASE = 1e6;
uint24 constant MAX_AMAMM_FEE = 0.1e6;
uint256 constant REBALANCE_MAX_SLIPPAGE_BASE = 1e5;
uint16 constant MAX_SURGE_HALFLIFE = 1 hours;
uint16 constant MAX_SURGE_AUTOSTART_TIME = 1 hours;
uint16 constant MAX_REBALANCE_MAX_SLIPPAGE = 0.25e5; // max value for rebalanceMaxSlippage is 25%
uint16 constant MAX_REBALANCE_TWAP_SECONDS_AGO = 3 hours;
uint16 constant MAX_REBALANCE_ORDER_TTL = 1 hours;
// 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)));
}
}
// 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))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC20 + EIP-2612 implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)
///
/// @dev Note:
/// - The ERC20 standard allows minting and transferring to and from the zero address,
/// minting and transferring zero tokens, as well as self-approvals.
/// For performance, this implementation WILL NOT revert for such actions.
/// Please add any checks with overrides if desired.
/// - The `permit` function uses the ecrecover precompile (0x1).
///
/// If you are overriding:
/// - NEVER violate the ERC20 invariant:
/// the total sum of all balances must be equal to `totalSupply()`.
/// - Check that the overridden function is actually used in the function you want to
/// change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC20 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The total supply has overflowed.
error TotalSupplyOverflow();
/// @dev The allowance has overflowed.
error AllowanceOverflow();
/// @dev The allowance has underflowed.
error AllowanceUnderflow();
/// @dev Insufficient balance.
error InsufficientBalance();
/// @dev Insufficient allowance.
error InsufficientAllowance();
/// @dev The permit is invalid.
error InvalidPermit();
/// @dev The permit has expired.
error PermitExpired();
/// @dev The allowance of Permit2 is fixed at infinity.
error Permit2AllowanceIsFixedAtInfinity();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted when `amount` tokens is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
uint256 private constant _TRANSFER_EVENT_SIGNATURE =
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
/// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
uint256 private constant _APPROVAL_EVENT_SIGNATURE =
0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The storage slot for the total supply.
uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;
/// @dev The balance slot of `owner` is given by:
/// ```
/// mstore(0x0c, _BALANCE_SLOT_SEED)
/// mstore(0x00, owner)
/// let balanceSlot := keccak256(0x0c, 0x20)
/// ```
uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;
/// @dev The allowance slot of (`owner`, `spender`) is given by:
/// ```
/// mstore(0x20, spender)
/// mstore(0x0c, _ALLOWANCE_SLOT_SEED)
/// mstore(0x00, owner)
/// let allowanceSlot := keccak256(0x0c, 0x34)
/// ```
uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;
/// @dev The nonce slot of `owner` is given by:
/// ```
/// mstore(0x0c, _NONCES_SLOT_SEED)
/// mstore(0x00, owner)
/// let nonceSlot := keccak256(0x0c, 0x20)
/// ```
uint256 private constant _NONCES_SLOT_SEED = 0x38377508;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`.
uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901;
/// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
bytes32 private constant _DOMAIN_TYPEHASH =
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev `keccak256("1")`.
/// If you need to use a different version, override `_versionHash`.
bytes32 private constant _DEFAULT_VERSION_HASH =
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
/// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`.
bytes32 private constant _PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @dev The canonical Permit2 address.
/// For signature-based allowance granting for single transaction ERC20 `transferFrom`.
/// To enable, override `_givePermit2InfiniteAllowance()`.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 METADATA */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the name of the token.
function name() public view virtual returns (string memory);
/// @dev Returns the symbol of the token.
function symbol() public view virtual returns (string memory);
/// @dev Returns the decimals places of the token.
function decimals() public view virtual returns (uint8) {
return 18;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the amount of tokens in existence.
function totalSupply() public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_TOTAL_SUPPLY_SLOT)
}
}
/// @dev Returns the amount of tokens owned by `owner`.
function balanceOf(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.
function allowance(address owner, address spender)
public
view
virtual
returns (uint256 result)
{
if (_givePermit2InfiniteAllowance()) {
if (spender == _PERMIT2) return type(uint256).max;
}
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x34))
}
}
/// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
///
/// Emits a {Approval} event.
function approve(address spender, uint256 amount) public virtual returns (bool) {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && amount != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
/// @solidity memory-safe-assembly
assembly {
// Compute the allowance slot and store the amount.
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x34), amount)
// Emit the {Approval} event.
mstore(0x00, amount)
log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
}
return true;
}
/// @dev Transfer `amount` tokens from the caller to `to`.
///
/// Requirements:
/// - `from` must at least have `amount`.
///
/// Emits a {Transfer} event.
function transfer(address to, uint256 amount) public virtual returns (bool) {
_beforeTokenTransfer(msg.sender, to, amount);
/// @solidity memory-safe-assembly
assembly {
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, caller())
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
}
_afterTokenTransfer(msg.sender, to, amount);
return true;
}
/// @dev Transfers `amount` tokens from `from` to `to`.
///
/// Note: Does not update the allowance if it is the maximum uint256 value.
///
/// Requirements:
/// - `from` must at least have `amount`.
/// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.
///
/// Emits a {Transfer} event.
function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
_beforeTokenTransfer(from, to, amount);
// Code duplication is for zero-cost abstraction if possible.
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
if iszero(eq(caller(), _PERMIT2)) {
// Compute the allowance slot and load its value.
mstore(0x20, caller())
mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
}
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
// Compute the allowance slot and load its value.
mstore(0x20, caller())
mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
}
_afterTokenTransfer(from, to, amount);
return true;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EIP-2612 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev For more performance, override to return the constant value
/// of `keccak256(bytes(name()))` if `name()` will never change.
function _constantNameHash() internal view virtual returns (bytes32 result) {}
/// @dev If you need a different value, override this function.
function _versionHash() internal view virtual returns (bytes32 result) {
result = _DEFAULT_VERSION_HASH;
}
/// @dev For inheriting contracts to increment the nonce.
function _incrementNonce(address owner) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _NONCES_SLOT_SEED)
mstore(0x00, owner)
let nonceSlot := keccak256(0x0c, 0x20)
sstore(nonceSlot, add(1, sload(nonceSlot)))
}
}
/// @dev Returns the current nonce for `owner`.
/// This value is used to compute the signature for EIP-2612 permit.
function nonces(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
// Compute the nonce slot and load its value.
mstore(0x0c, _NONCES_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`,
/// authorized by a signed approval by `owner`.
///
/// Emits a {Approval} event.
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && value != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(value)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
bytes32 nameHash = _constantNameHash();
// We simply calculate it on-the-fly to allow for cases where the `name` may change.
if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
bytes32 versionHash = _versionHash();
/// @solidity memory-safe-assembly
assembly {
// Revert if the block timestamp is greater than `deadline`.
if gt(timestamp(), deadline) {
mstore(0x00, 0x1a15a3cc) // `PermitExpired()`.
revert(0x1c, 0x04)
}
let m := mload(0x40) // Grab the free memory pointer.
// Clean the upper 96 bits.
owner := shr(96, shl(96, owner))
spender := shr(96, shl(96, spender))
// Compute the nonce slot and load its value.
mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX)
mstore(0x00, owner)
let nonceSlot := keccak256(0x0c, 0x20)
let nonceValue := sload(nonceSlot)
// Prepare the domain separator.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
mstore(0x2e, keccak256(m, 0xa0))
// Prepare the struct hash.
mstore(m, _PERMIT_TYPEHASH)
mstore(add(m, 0x20), owner)
mstore(add(m, 0x40), spender)
mstore(add(m, 0x60), value)
mstore(add(m, 0x80), nonceValue)
mstore(add(m, 0xa0), deadline)
mstore(0x4e, keccak256(m, 0xc0))
// Prepare the ecrecover calldata.
mstore(0x00, keccak256(0x2c, 0x42))
mstore(0x20, and(0xff, v))
mstore(0x40, r)
mstore(0x60, s)
let t := staticcall(gas(), 1, 0x00, 0x80, 0x20, 0x20)
// If the ecrecover fails, the returndatasize will be 0x00,
// `owner` will be checked if it equals the hash at 0x00,
// which evaluates to false (i.e. 0), and we will revert.
// If the ecrecover succeeds, the returndatasize will be 0x20,
// `owner` will be compared against the returned address at 0x20.
if iszero(eq(mload(returndatasize()), owner)) {
mstore(0x00, 0xddafbaef) // `InvalidPermit()`.
revert(0x1c, 0x04)
}
// Increment and store the updated nonce.
sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds.
// Compute the allowance slot and store the value.
// The `owner` is already at slot 0x20.
mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender))
sstore(keccak256(0x2c, 0x34), value)
// Emit the {Approval} event.
log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/// @dev Returns the EIP-712 domain separator for the EIP-2612 permit.
function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) {
bytes32 nameHash = _constantNameHash();
// We simply calculate it on-the-fly to allow for cases where the `name` may change.
if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
bytes32 versionHash = _versionHash();
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Grab the free memory pointer.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
result := keccak256(m, 0xa0)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL MINT FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Mints `amount` tokens to `to`, increasing the total supply.
///
/// Emits a {Transfer} event.
function _mint(address to, uint256 amount) internal virtual {
_beforeTokenTransfer(address(0), to, amount);
/// @solidity memory-safe-assembly
assembly {
let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)
let totalSupplyAfter := add(totalSupplyBefore, amount)
// Revert if the total supply overflows.
if lt(totalSupplyAfter, totalSupplyBefore) {
mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.
revert(0x1c, 0x04)
}
// Store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))
}
_afterTokenTransfer(address(0), to, amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL BURN FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Burns `amount` tokens from `from`, reducing the total supply.
///
/// Emits a {Transfer} event.
function _burn(address from, uint256 amount) internal virtual {
_beforeTokenTransfer(from, address(0), amount);
/// @solidity memory-safe-assembly
assembly {
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, from)
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Subtract and store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
// Emit the {Transfer} event.
mstore(0x00, amount)
log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)
}
_afterTokenTransfer(from, address(0), amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL TRANSFER FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Moves `amount` of tokens from `from` to `to`.
function _transfer(address from, address to, uint256 amount) internal virtual {
_beforeTokenTransfer(from, to, amount);
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
_afterTokenTransfer(from, to, amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL ALLOWANCE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
if (_givePermit2InfiniteAllowance()) {
if (spender == _PERMIT2) return; // Do nothing, as allowance is infinite.
}
/// @solidity memory-safe-assembly
assembly {
// Compute the allowance slot and load its value.
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
}
}
/// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.
///
/// Emits a {Approval} event.
function _approve(address owner, address spender, uint256 amount) internal virtual {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && amount != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
/// @solidity memory-safe-assembly
assembly {
let owner_ := shl(96, owner)
// Compute the allowance slot and store the amount.
mstore(0x20, spender)
mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))
sstore(keccak256(0x0c, 0x34), amount)
// Emit the {Approval} event.
mstore(0x00, amount)
log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOKS TO OVERRIDE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Hook that is called before any transfer of tokens.
/// This includes minting and burning.
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/// @dev Hook that is called after any transfer of tokens.
/// This includes minting and burning.
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PERMIT2 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether to fix the Permit2 contract's allowance at infinity.
///
/// This value should be kept constant after contract initialization,
/// or else the actual allowance values may not match with the {Approval} events.
/// For best performance, return a compile-time constant for zero-cost abstraction.
function _givePermit2InfiniteAllowance() internal view virtual returns (bool) {
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {ERC20} from "./ERC20.sol";
import {FixedPointMathLib} from "../utils/FixedPointMathLib.sol";
import {SafeTransferLib} from "../utils/SafeTransferLib.sol";
/// @notice Simple ERC4626 tokenized Vault implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC4626.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/mixins/ERC4626.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC4626.sol)
abstract contract ERC4626 is ERC20 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The default underlying decimals.
uint8 internal constant _DEFAULT_UNDERLYING_DECIMALS = 18;
/// @dev The default decimals offset.
uint8 internal constant _DEFAULT_DECIMALS_OFFSET = 0;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Cannot deposit more than the max limit.
error DepositMoreThanMax();
/// @dev Cannot mint more than the max limit.
error MintMoreThanMax();
/// @dev Cannot withdraw more than the max limit.
error WithdrawMoreThanMax();
/// @dev Cannot redeem more than the max limit.
error RedeemMoreThanMax();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted during a mint call or deposit call.
event Deposit(address indexed by, address indexed owner, uint256 assets, uint256 shares);
/// @dev Emitted during a withdraw call or redeem call.
event Withdraw(
address indexed by,
address indexed to,
address indexed owner,
uint256 assets,
uint256 shares
);
/// @dev `keccak256(bytes("Deposit(address,address,uint256,uint256)"))`.
uint256 private constant _DEPOSIT_EVENT_SIGNATURE =
0xdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7;
/// @dev `keccak256(bytes("Withdraw(address,address,address,uint256,uint256)"))`.
uint256 private constant _WITHDRAW_EVENT_SIGNATURE =
0xfbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC4626 CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev To be overridden to return the address of the underlying asset.
///
/// - MUST be an ERC20 token contract.
/// - MUST NOT revert.
function asset() public view virtual returns (address);
/// @dev To be overridden to return the number of decimals of the underlying asset.
/// Default: 18.
///
/// - MUST NOT revert.
function _underlyingDecimals() internal view virtual returns (uint8) {
return _DEFAULT_UNDERLYING_DECIMALS;
}
/// @dev Override to return a non-zero value to make the inflation attack even more unfeasible.
/// Only used when {_useVirtualShares} returns true.
/// Default: 0.
///
/// - MUST NOT revert.
function _decimalsOffset() internal view virtual returns (uint8) {
return _DEFAULT_DECIMALS_OFFSET;
}
/// @dev Returns whether virtual shares will be used to mitigate the inflation attack.
/// See: https://github.com/OpenZeppelin/openzeppelin-contracts/issues/3706
/// Override to return true or false.
/// Default: true.
///
/// - MUST NOT revert.
function _useVirtualShares() internal view virtual returns (bool) {
return true;
}
/// @dev Returns the decimals places of the token.
///
/// - MUST NOT revert.
function decimals() public view virtual override(ERC20) returns (uint8) {
if (!_useVirtualShares()) return _underlyingDecimals();
return _underlyingDecimals() + _decimalsOffset();
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ASSET DECIMALS GETTER HELPER */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Helper function to get the decimals of the underlying asset.
/// Useful for setting the return value of `_underlyingDecimals` during initialization.
/// If the retrieval succeeds, `success` will be true, and `result` will hold the result.
/// Otherwise, `success` will be false, and `result` will be zero.
///
/// Example usage:
/// ```
/// (bool success, uint8 result) = _tryGetAssetDecimals(underlying);
/// _decimals = success ? result : _DEFAULT_UNDERLYING_DECIMALS;
/// ```
function _tryGetAssetDecimals(address underlying)
internal
view
returns (bool success, uint8 result)
{
/// @solidity memory-safe-assembly
assembly {
// Store the function selector of `decimals()`.
mstore(0x00, 0x313ce567)
// Arguments are evaluated last to first.
success :=
and(
// Returned value is less than 256, at left-padded to 32 bytes.
and(lt(mload(0x00), 0x100), gt(returndatasize(), 0x1f)),
// The staticcall succeeds.
staticcall(gas(), underlying, 0x1c, 0x04, 0x00, 0x20)
)
result := mul(mload(0x00), success)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ACCOUNTING LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the total amount of the underlying asset managed by the Vault.
///
/// - SHOULD include any compounding that occurs from the yield.
/// - MUST be inclusive of any fees that are charged against assets in the Vault.
/// - MUST NOT revert.
function totalAssets() public view virtual returns (uint256 assets) {
assets = SafeTransferLib.balanceOf(asset(), address(this));
}
/// @dev Returns the amount of shares that the Vault will exchange for the amount of
/// assets provided, in an ideal scenario where all conditions are met.
///
/// - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
/// - MUST NOT show any variations depending on the caller.
/// - MUST NOT reflect slippage or other on-chain conditions, during the actual exchange.
/// - MUST NOT revert.
///
/// Note: This calculation MAY NOT reflect the "per-user" price-per-share, and instead
/// should reflect the "average-user's" price-per-share, i.e. what the average user should
/// expect to see when exchanging to and from.
function convertToShares(uint256 assets) public view virtual returns (uint256 shares) {
if (!_useVirtualShares()) {
uint256 supply = totalSupply();
return _eitherIsZero(assets, supply)
? _initialConvertToShares(assets)
: FixedPointMathLib.fullMulDiv(assets, supply, totalAssets());
}
uint256 o = _decimalsOffset();
if (o == uint256(0)) {
return FixedPointMathLib.fullMulDiv(assets, totalSupply() + 1, _inc(totalAssets()));
}
return FixedPointMathLib.fullMulDiv(assets, totalSupply() + 10 ** o, _inc(totalAssets()));
}
/// @dev Returns the amount of assets that the Vault will exchange for the amount of
/// shares provided, in an ideal scenario where all conditions are met.
///
/// - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
/// - MUST NOT show any variations depending on the caller.
/// - MUST NOT reflect slippage or other on-chain conditions, during the actual exchange.
/// - MUST NOT revert.
///
/// Note: This calculation MAY NOT reflect the "per-user" price-per-share, and instead
/// should reflect the "average-user's" price-per-share, i.e. what the average user should
/// expect to see when exchanging to and from.
function convertToAssets(uint256 shares) public view virtual returns (uint256 assets) {
if (!_useVirtualShares()) {
uint256 supply = totalSupply();
return supply == uint256(0)
? _initialConvertToAssets(shares)
: FixedPointMathLib.fullMulDiv(shares, totalAssets(), supply);
}
uint256 o = _decimalsOffset();
if (o == uint256(0)) {
return FixedPointMathLib.fullMulDiv(shares, totalAssets() + 1, _inc(totalSupply()));
}
return FixedPointMathLib.fullMulDiv(shares, totalAssets() + 1, totalSupply() + 10 ** o);
}
/// @dev Allows an on-chain or off-chain user to simulate the effects of their deposit
/// at the current block, given current on-chain conditions.
///
/// - MUST return as close to and no more than the exact amount of Vault shares that
/// will be minted in a deposit call in the same transaction, i.e. deposit should
/// return the same or more shares as `previewDeposit` if call in the same transaction.
/// - MUST NOT account for deposit limits like those returned from `maxDeposit` and should
/// always act as if the deposit will be accepted, regardless of approvals, etc.
/// - MUST be inclusive of deposit fees. Integrators should be aware of this.
/// - MUST not revert.
///
/// Note: Any unfavorable discrepancy between `convertToShares` and `previewDeposit` SHOULD
/// be considered slippage in share price or some other type of condition, meaning
/// the depositor will lose assets by depositing.
function previewDeposit(uint256 assets) public view virtual returns (uint256 shares) {
shares = convertToShares(assets);
}
/// @dev Allows an on-chain or off-chain user to simulate the effects of their mint
/// at the current block, given current on-chain conditions.
///
/// - MUST return as close to and no fewer than the exact amount of assets that
/// will be deposited in a mint call in the same transaction, i.e. mint should
/// return the same or fewer assets as `previewMint` if called in the same transaction.
/// - MUST NOT account for mint limits like those returned from `maxMint` and should
/// always act as if the mint will be accepted, regardless of approvals, etc.
/// - MUST be inclusive of deposit fees. Integrators should be aware of this.
/// - MUST not revert.
///
/// Note: Any unfavorable discrepancy between `convertToAssets` and `previewMint` SHOULD
/// be considered slippage in share price or some other type of condition,
/// meaning the depositor will lose assets by minting.
function previewMint(uint256 shares) public view virtual returns (uint256 assets) {
if (!_useVirtualShares()) {
uint256 supply = totalSupply();
return supply == uint256(0)
? _initialConvertToAssets(shares)
: FixedPointMathLib.fullMulDivUp(shares, totalAssets(), supply);
}
uint256 o = _decimalsOffset();
if (o == uint256(0)) {
return FixedPointMathLib.fullMulDivUp(shares, totalAssets() + 1, _inc(totalSupply()));
}
return FixedPointMathLib.fullMulDivUp(shares, totalAssets() + 1, totalSupply() + 10 ** o);
}
/// @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal
/// at the current block, given the current on-chain conditions.
///
/// - MUST return as close to and no fewer than the exact amount of Vault shares that
/// will be burned in a withdraw call in the same transaction, i.e. withdraw should
/// return the same or fewer shares as `previewWithdraw` if call in the same transaction.
/// - MUST NOT account for withdrawal limits like those returned from `maxWithdraw` and should
/// always act as if the withdrawal will be accepted, regardless of share balance, etc.
/// - MUST be inclusive of withdrawal fees. Integrators should be aware of this.
/// - MUST not revert.
///
/// Note: Any unfavorable discrepancy between `convertToShares` and `previewWithdraw` SHOULD
/// be considered slippage in share price or some other type of condition,
/// meaning the depositor will lose assets by depositing.
function previewWithdraw(uint256 assets) public view virtual returns (uint256 shares) {
if (!_useVirtualShares()) {
uint256 supply = totalSupply();
return _eitherIsZero(assets, supply)
? _initialConvertToShares(assets)
: FixedPointMathLib.fullMulDivUp(assets, supply, totalAssets());
}
uint256 o = _decimalsOffset();
if (o == uint256(0)) {
return FixedPointMathLib.fullMulDivUp(assets, totalSupply() + 1, _inc(totalAssets()));
}
return FixedPointMathLib.fullMulDivUp(assets, totalSupply() + 10 ** o, _inc(totalAssets()));
}
/// @dev Allows an on-chain or off-chain user to simulate the effects of their redemption
/// at the current block, given current on-chain conditions.
///
/// - MUST return as close to and no more than the exact amount of assets that
/// will be withdrawn in a redeem call in the same transaction, i.e. redeem should
/// return the same or more assets as `previewRedeem` if called in the same transaction.
/// - MUST NOT account for redemption limits like those returned from `maxRedeem` and should
/// always act as if the redemption will be accepted, regardless of approvals, etc.
/// - MUST be inclusive of withdrawal fees. Integrators should be aware of this.
/// - MUST NOT revert.
///
/// Note: Any unfavorable discrepancy between `convertToAssets` and `previewRedeem` SHOULD
/// be considered slippage in share price or some other type of condition,
/// meaning the depositor will lose assets by depositing.
function previewRedeem(uint256 shares) public view virtual returns (uint256 assets) {
assets = convertToAssets(shares);
}
/// @dev Private helper to return if either value is zero.
function _eitherIsZero(uint256 a, uint256 b) private pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := or(iszero(a), iszero(b))
}
}
/// @dev Private helper to return `x + 1` without the overflow check.
/// Used for computing the denominator input to `FixedPointMathLib.fullMulDiv(a, b, x + 1)`.
/// When `x == type(uint256).max`, we get `x + 1 == 0` (mod 2**256 - 1),
/// and `FixedPointMathLib.fullMulDiv` will revert as the denominator is zero.
function _inc(uint256 x) private pure returns (uint256) {
unchecked {
return x + 1;
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DEPOSIT / WITHDRAWAL LIMIT LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the maximum amount of the underlying asset that can be deposited
/// into the Vault for `to`, via a deposit call.
///
/// - MUST return a limited value if `to` is subject to some deposit limit.
/// - MUST return `2**256-1` if there is no maximum limit.
/// - MUST NOT revert.
function maxDeposit(address to) public view virtual returns (uint256 maxAssets) {
to = to; // Silence unused variable warning.
maxAssets = type(uint256).max;
}
/// @dev Returns the maximum amount of the Vault shares that can be minter for `to`,
/// via a mint call.
///
/// - MUST return a limited value if `to` is subject to some mint limit.
/// - MUST return `2**256-1` if there is no maximum limit.
/// - MUST NOT revert.
function maxMint(address to) public view virtual returns (uint256 maxShares) {
to = to; // Silence unused variable warning.
maxShares = type(uint256).max;
}
/// @dev Returns the maximum amount of the underlying asset that can be withdrawn
/// from the `owner`'s balance in the Vault, via a withdraw call.
///
/// - MUST return a limited value if `owner` is subject to some withdrawal limit or timelock.
/// - MUST NOT revert.
function maxWithdraw(address owner) public view virtual returns (uint256 maxAssets) {
maxAssets = convertToAssets(balanceOf(owner));
}
/// @dev Returns the maximum amount of Vault shares that can be redeemed
/// from the `owner`'s balance in the Vault, via a redeem call.
///
/// - MUST return a limited value if `owner` is subject to some withdrawal limit or timelock.
/// - MUST return `balanceOf(owner)` otherwise.
/// - MUST NOT revert.
function maxRedeem(address owner) public view virtual returns (uint256 maxShares) {
maxShares = balanceOf(owner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DEPOSIT / WITHDRAWAL LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Mints `shares` Vault shares to `to` by depositing exactly `assets`
/// of underlying tokens.
///
/// - MUST emit the {Deposit} event.
/// - MAY support an additional flow in which the underlying tokens are owned by the Vault
/// contract before the deposit execution, and are accounted for during deposit.
/// - MUST revert if all of `assets` cannot be deposited, such as due to deposit limit,
/// slippage, insufficient approval, etc.
///
/// Note: Most implementations will require pre-approval of the Vault with the
/// Vault's underlying `asset` token.
function deposit(uint256 assets, address to) public virtual returns (uint256 shares) {
if (assets > maxDeposit(to)) _revert(0xb3c61a83); // `DepositMoreThanMax()`.
shares = previewDeposit(assets);
_deposit(msg.sender, to, assets, shares);
}
/// @dev Mints exactly `shares` Vault shares to `to` by depositing `assets`
/// of underlying tokens.
///
/// - MUST emit the {Deposit} event.
/// - MAY support an additional flow in which the underlying tokens are owned by the Vault
/// contract before the mint execution, and are accounted for during mint.
/// - MUST revert if all of `shares` cannot be deposited, such as due to deposit limit,
/// slippage, insufficient approval, etc.
///
/// Note: Most implementations will require pre-approval of the Vault with the
/// Vault's underlying `asset` token.
function mint(uint256 shares, address to) public virtual returns (uint256 assets) {
if (shares > maxMint(to)) _revert(0x6a695959); // `MintMoreThanMax()`.
assets = previewMint(shares);
_deposit(msg.sender, to, assets, shares);
}
/// @dev Burns `shares` from `owner` and sends exactly `assets` of underlying tokens to `to`.
///
/// - MUST emit the {Withdraw} event.
/// - MAY support an additional flow in which the underlying tokens are owned by the Vault
/// contract before the withdraw execution, and are accounted for during withdraw.
/// - MUST revert if all of `assets` cannot be withdrawn, such as due to withdrawal limit,
/// slippage, insufficient balance, etc.
///
/// Note: Some implementations will require pre-requesting to the Vault before a withdrawal
/// may be performed. Those methods should be performed separately.
function withdraw(uint256 assets, address to, address owner)
public
virtual
returns (uint256 shares)
{
if (assets > maxWithdraw(owner)) _revert(0x936941fc); // `WithdrawMoreThanMax()`.
shares = previewWithdraw(assets);
_withdraw(msg.sender, to, owner, assets, shares);
}
/// @dev Burns exactly `shares` from `owner` and sends `assets` of underlying tokens to `to`.
///
/// - MUST emit the {Withdraw} event.
/// - MAY support an additional flow in which the underlying tokens are owned by the Vault
/// contract before the redeem execution, and are accounted for during redeem.
/// - MUST revert if all of shares cannot be redeemed, such as due to withdrawal limit,
/// slippage, insufficient balance, etc.
///
/// Note: Some implementations will require pre-requesting to the Vault before a redeem
/// may be performed. Those methods should be performed separately.
function redeem(uint256 shares, address to, address owner)
public
virtual
returns (uint256 assets)
{
if (shares > maxRedeem(owner)) _revert(0x4656425a); // `RedeemMoreThanMax()`.
assets = previewRedeem(shares);
_withdraw(msg.sender, to, owner, assets, shares);
}
/// @dev Internal helper for reverting efficiently.
function _revert(uint256 s) private pure {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, s)
revert(0x1c, 0x04)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev For deposits and mints.
///
/// Emits a {Deposit} event.
function _deposit(address by, address to, uint256 assets, uint256 shares) internal virtual {
SafeTransferLib.safeTransferFrom(asset(), by, address(this), assets);
_mint(to, shares);
/// @solidity memory-safe-assembly
assembly {
// Emit the {Deposit} event.
mstore(0x00, assets)
mstore(0x20, shares)
let m := shr(96, not(0))
log3(0x00, 0x40, _DEPOSIT_EVENT_SIGNATURE, and(m, by), and(m, to))
}
_afterDeposit(assets, shares);
}
/// @dev For withdrawals and redemptions.
///
/// Emits a {Withdraw} event.
function _withdraw(address by, address to, address owner, uint256 assets, uint256 shares)
internal
virtual
{
if (by != owner) _spendAllowance(owner, by, shares);
_beforeWithdraw(assets, shares);
_burn(owner, shares);
SafeTransferLib.safeTransfer(asset(), to, assets);
/// @solidity memory-safe-assembly
assembly {
// Emit the {Withdraw} event.
mstore(0x00, assets)
mstore(0x20, shares)
let m := shr(96, not(0))
log4(0x00, 0x40, _WITHDRAW_EVENT_SIGNATURE, and(m, by), and(m, to), and(m, owner))
}
}
/// @dev Internal conversion function (from assets to shares) to apply when the Vault is empty.
/// Only used when {_useVirtualShares} returns false.
///
/// Note: Make sure to keep this function consistent with {_initialConvertToAssets}
/// when overriding it.
function _initialConvertToShares(uint256 assets)
internal
view
virtual
returns (uint256 shares)
{
shares = assets;
}
/// @dev Internal conversion function (from shares to assets) to apply when the Vault is empty.
/// Only used when {_useVirtualShares} returns false.
///
/// Note: Make sure to keep this function consistent with {_initialConvertToShares}
/// when overriding it.
function _initialConvertToAssets(uint256 shares)
internal
view
virtual
returns (uint256 assets)
{
assets = shares;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOKS TO OVERRIDE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Hook that is called before any withdrawal or redemption.
function _beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}
/// @dev Hook that is called after any deposit or mint.
function _afterDeposit(uint256 assets, uint256 shares) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
pragma abicoder v2;
error BunniHub__Paused();
error BunniHub__ZeroInput();
error BunniHub__PastDeadline();
error BunniHub__Unauthorized();
error BunniHub__InvalidReferrer();
error BunniHub__LDFCannotBeZero();
error BunniHub__MaxNonceReached();
error BunniHub__SlippageTooHigh();
error BunniHub__WithdrawalPaused();
error BunniHub__HookCannotBeZero();
error BunniHub__ZeroSharesMinted();
error BunniHub__InvalidLDFParams();
error BunniHub__InvalidHookParams();
error BunniHub__VaultFeeIncorrect();
error BunniHub__VaultAssetMismatch();
error BunniHub__GracePeriodExpired();
error BunniHub__NoExpiredWithdrawal();
error BunniHub__MsgValueInsufficient();
error BunniHub__DepositAmountTooSmall();
error BunniHub__QueuedWithdrawalNotReady();
error BunniHub__BunniTokenNotInitialized();
error BunniHub__NeedToUseQueuedWithdrawal();
error BunniHub__InvalidRawTokenRatioBounds();
error BunniHub__QueuedWithdrawalNonexistent();
error BunniHub__MsgValueNotZeroWhenPoolKeyHasNoNativeToken();
error BunniToken__NotBunniHub();
error BunniToken__NotPoolManager();
error BunniToken__ReferrerAddressIsZero();
error BunniHook__InvalidSwap();
error BunniHook__Unauthorized();
error BunniHook__InvalidModifier();
error BunniHook__InsufficientOutput();
error BunniHook__InvalidRebalanceOrderHash();
error BunniHook__PrehookPostConditionFailed();
error BunniHook__RequestedOutputExceedsBalance();
error BunniSwapMath__SwapFailed();
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import "./Math.sol";
import "../base/Constants.sol";
using FixedPointMathLib for int256;
using FixedPointMathLib for uint256;
function computeSurgeFee(uint32 lastSurgeTimestamp, uint16 surgeFeeHalfLife) view returns (uint24 fee) {
// compute surge fee
// surge fee gets applied after the LDF shifts (if it's dynamic)
unchecked {
uint256 timeSinceLastSurge = uint32(block.timestamp) - lastSurgeTimestamp;
// max surge fee is hardcoded to 100% (SWAP_FEE_BASE)
fee = uint24(
SWAP_FEE_BASE.mulWadUp(uint256((-int256(timeSinceLastSurge.mulDiv(LN2_WAD, surgeFeeHalfLife))).expWad()))
);
}
}
function computeDynamicSwapFee(
uint160 postSwapSqrtPriceX96,
int24 arithmeticMeanTick,
uint32 lastSurgeTimestamp,
uint24 feeMin,
uint24 feeMax,
uint24 feeQuadraticMultiplier,
uint16 surgeFeeHalfLife
) view returns (uint24 fee) {
// compute surge fee
// surge fee gets applied after the LDF shifts (if it's dynamic)
fee = computeSurgeFee(lastSurgeTimestamp, surgeFeeHalfLife);
// special case for fixed fee pools
if (feeQuadraticMultiplier == 0 || feeMin == feeMax) return uint24(FixedPointMathLib.max(feeMin, fee));
uint256 ratio = uint256(postSwapSqrtPriceX96).mulDiv(SWAP_FEE_BASE, TickMath.getSqrtPriceAtTick(arithmeticMeanTick));
if (ratio > MAX_SWAP_FEE_RATIO) ratio = MAX_SWAP_FEE_RATIO;
ratio = ratio.mulDiv(ratio, SWAP_FEE_BASE); // square the sqrtPrice ratio to get the price ratio
uint256 delta = dist(ratio, SWAP_FEE_BASE);
// unchecked is safe since we're using uint256 to store the result and the return value is bounded in the range [feeMin, feeMax]
unchecked {
uint256 quadraticTerm = uint256(feeQuadraticMultiplier).mulDivUp(delta * delta, SWAP_FEE_BASE_SQUARED);
return uint24(FixedPointMathLib.max(fee, FixedPointMathLib.min(feeMin + quadraticTerm, feeMax)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
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))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(int256 x) internal pure returns (int256 w) {
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `a * b == x * y`, with full precision.
function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// 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 = p1 * 2**256 + p0`.
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure `z` is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// 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 := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
z :=
mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
z := div(z, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
z :=
mul(
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
z = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let k := and(n, 0xff) // `n`, cleaned.
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(k, p1)) {
z := add(shl(sub(256, k), p1), shr(k, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(and(n, 0xff), z)
break
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
/// @solidity memory-safe-assembly
assembly {
let g := n
let r := mod(a, n)
for { let y := 1 } 1 {} {
let q := div(g, r)
let t := g
g := r
r := sub(t, mul(r, q))
let u := x
x := y
y := sub(u, mul(y, q))
if iszero(r) { break }
}
x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let 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))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { z := mul(z, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
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)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
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(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
internal
pure
returns (uint256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
internal
pure
returns (int256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(uint256 x) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}
// 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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
library FullMathX96 {
uint256 internal constant Q96 = 0x1000000000000000000000000;
/// @dev Calculates `floor(x * y / 2 ** 96)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulX96(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(96, p1)) {
z := add(shl(160, p1), shr(96, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(96, z)
break
}
}
}
function fullMulX96Up(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = fullMulX96(x, y);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, Q96) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {CustomRevert} from "@uniswap/v4-core/src/libraries/CustomRevert.sol";
import {IPoolManager, PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import "../base/Constants.sol";
import {IHooklet} from "../interfaces/IHooklet.sol";
import {IBunniHub} from "../interfaces/IBunniHub.sol";
import {IBunniToken} from "../interfaces/IBunniToken.sol";
/// @dev Adapted from Uniswap v4's Hooks.sol
library HookletLib {
using CustomRevert for bytes4;
using HookletLib for IHooklet;
using FixedPointMathLib for *;
uint160 internal constant ALL_FLAGS_MASK = 0xFFF;
uint160 internal constant BEFORE_TRANSFER_FLAG = 1 << 11;
uint160 internal constant AFTER_TRANSFER_FLAG = 1 << 10;
uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 9;
uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 8;
uint160 internal constant BEFORE_DEPOSIT_FLAG = 1 << 7;
uint160 internal constant AFTER_DEPOSIT_FLAG = 1 << 6;
uint160 internal constant BEFORE_WITHDRAW_FLAG = 1 << 5;
uint160 internal constant AFTER_WITHDRAW_FLAG = 1 << 4;
uint160 internal constant BEFORE_SWAP_FLAG = 1 << 3;
uint160 internal constant BEFORE_SWAP_OVERRIDE_FEE_FLAG = 1 << 2;
uint160 internal constant BEFORE_SWAP_OVERRIDE_PRICE_FLAG = 1 << 1;
uint160 internal constant AFTER_SWAP_FLAG = 1;
error HookletLib__FailedHookletCall();
error HookletLib__InvalidHookletResponse();
function callHooklet(IHooklet self, bytes4 selector, bytes memory data) internal returns (bytes memory result) {
bytes4 decodedSelector;
assembly ("memory-safe") {
if iszero(call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)) {
if iszero(returndatasize()) {
// if the call failed without a revert reason, revert with `HookletLib__FailedHookletCall()`
mstore(0, 0x855e32e7)
revert(0x1c, 0x04)
}
// bubble up revert
let fmp := mload(0x40)
returndatacopy(fmp, 0, returndatasize())
revert(fmp, returndatasize())
}
// allocate result byte array from the free memory pointer
result := mload(0x40)
// store new free memory pointer at the end of the array padded to 32 bytes
mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
// store length in memory
mstore(result, returndatasize())
// copy return data to result
returndatacopy(add(result, 0x20), 0, returndatasize())
// get the selector from the return data
decodedSelector := mload(add(result, 0x20))
}
if (decodedSelector != selector) HookletLib__InvalidHookletResponse.selector.revertWith();
}
function staticcallHooklet(IHooklet self, bytes4 selector, bytes memory data)
internal
view
returns (bool success, bytes memory result)
{
bytes4 decodedSelector;
assembly ("memory-safe") {
switch staticcall(gas(), self, add(data, 0x20), mload(data), 0, 0)
case 0 {
// call reverted, set success to false
success := 0
}
default {
// call succeeded, set success to true
success := 1
// allocate result byte array from the free memory pointer
result := mload(0x40)
// store new free memory pointer at the end of the array padded to 32 bytes
mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
// store length in memory
mstore(result, returndatasize())
// copy return data to result
returndatacopy(add(result, 0x20), 0, returndatasize())
// get the selector from the return data
decodedSelector := mload(add(result, 0x20))
}
}
if (decodedSelector != selector) return (false, bytes(""));
}
modifier noSelfCall(IHooklet self, address sender) {
if (sender != address(self)) {
_;
}
}
/// @dev The hasPermission check is done outside of this function in order to avoid unnecessarily constructing `key`
function hookletBeforeTransfer(
IHooklet self,
address sender,
PoolKey memory key,
IBunniToken bunniToken,
address from,
address to,
uint256 amount
) internal noSelfCall(self, sender) {
self.callHooklet(
IHooklet.beforeTransfer.selector,
abi.encodeCall(IHooklet.beforeTransfer, (sender, key, bunniToken, from, to, amount))
);
}
/// @dev The hasPermission check is done outside of this function in order to avoid unnecessarily constructing `key`
function hookletAfterTransfer(
IHooklet self,
address sender,
PoolKey memory key,
IBunniToken bunniToken,
address from,
address to,
uint256 amount
) internal noSelfCall(self, sender) {
self.callHooklet(
IHooklet.afterTransfer.selector,
abi.encodeCall(IHooklet.afterTransfer, (sender, key, bunniToken, from, to, amount))
);
}
function hookletBeforeInitialize(IHooklet self, address sender, IBunniHub.DeployBunniTokenParams calldata params)
internal
noSelfCall(self, sender)
{
if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
self.callHooklet(
IHooklet.beforeInitialize.selector, abi.encodeCall(IHooklet.beforeInitialize, (sender, params))
);
}
}
function hookletAfterInitialize(
IHooklet self,
address sender,
IBunniHub.DeployBunniTokenParams calldata params,
IHooklet.InitializeReturnData memory returnData
) internal noSelfCall(self, sender) {
if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
self.callHooklet(
IHooklet.afterInitialize.selector,
abi.encodeCall(IHooklet.afterInitialize, (sender, params, returnData))
);
}
}
function hookletBeforeDeposit(IHooklet self, address sender, IBunniHub.DepositParams calldata params)
internal
noSelfCall(self, sender)
{
if (self.hasPermission(BEFORE_DEPOSIT_FLAG)) {
self.callHooklet(IHooklet.beforeDeposit.selector, abi.encodeCall(IHooklet.beforeDeposit, (sender, params)));
}
}
function hookletBeforeDepositView(IHooklet self, address sender, IBunniHub.DepositParams calldata params)
internal
view
noSelfCall(self, sender)
returns (bool success)
{
if (self.hasPermission(BEFORE_DEPOSIT_FLAG)) {
(success,) = self.staticcallHooklet(
IHooklet.beforeDepositView.selector, abi.encodeCall(IHooklet.beforeDepositView, (sender, params))
);
} else {
success = true;
}
}
function hookletAfterDeposit(
IHooklet self,
address sender,
IBunniHub.DepositParams calldata params,
IHooklet.DepositReturnData memory returnData
) internal noSelfCall(self, sender) {
if (self.hasPermission(AFTER_DEPOSIT_FLAG)) {
self.callHooklet(
IHooklet.afterDeposit.selector, abi.encodeCall(IHooklet.afterDeposit, (sender, params, returnData))
);
}
}
function hookletAfterDepositView(
IHooklet self,
address sender,
IBunniHub.DepositParams calldata params,
IHooklet.DepositReturnData memory returnData
) internal view noSelfCall(self, sender) returns (bool success) {
if (self.hasPermission(AFTER_DEPOSIT_FLAG)) {
(success,) = self.staticcallHooklet(
IHooklet.afterDepositView.selector,
abi.encodeCall(IHooklet.afterDepositView, (sender, params, returnData))
);
} else {
success = true;
}
}
function hookletBeforeWithdraw(IHooklet self, address sender, IBunniHub.WithdrawParams calldata params)
internal
noSelfCall(self, sender)
{
if (self.hasPermission(BEFORE_WITHDRAW_FLAG)) {
self.callHooklet(
IHooklet.beforeWithdraw.selector, abi.encodeCall(IHooklet.beforeWithdraw, (sender, params))
);
}
}
function hookletBeforeWithdrawView(IHooklet self, address sender, IBunniHub.WithdrawParams calldata params)
internal
view
noSelfCall(self, sender)
returns (bool success)
{
if (self.hasPermission(BEFORE_WITHDRAW_FLAG)) {
(success,) = self.staticcallHooklet(
IHooklet.beforeWithdrawView.selector, abi.encodeCall(IHooklet.beforeWithdrawView, (sender, params))
);
} else {
success = true;
}
}
function hookletAfterWithdraw(
IHooklet self,
address sender,
IBunniHub.WithdrawParams calldata params,
IHooklet.WithdrawReturnData memory returnData
) internal noSelfCall(self, sender) {
if (self.hasPermission(AFTER_WITHDRAW_FLAG)) {
self.callHooklet(
IHooklet.afterWithdraw.selector, abi.encodeCall(IHooklet.afterWithdraw, (sender, params, returnData))
);
}
}
function hookletAfterWithdrawView(
IHooklet self,
address sender,
IBunniHub.WithdrawParams calldata params,
IHooklet.WithdrawReturnData memory returnData
) internal view noSelfCall(self, sender) returns (bool success) {
if (self.hasPermission(AFTER_WITHDRAW_FLAG)) {
(success,) = self.staticcallHooklet(
IHooklet.afterWithdrawView.selector,
abi.encodeCall(IHooklet.afterWithdrawView, (sender, params, returnData))
);
} else {
success = true;
}
}
function hookletBeforeSwap(
IHooklet self,
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params
)
internal
noSelfCall(self, sender)
returns (bool feeOverridden, uint24 fee, bool priceOverridden, uint160 sqrtPriceX96)
{
if (self.hasPermission(BEFORE_SWAP_FLAG)) {
bytes memory result = self.callHooklet(
IHooklet.beforeSwap.selector, abi.encodeCall(IHooklet.beforeSwap, (sender, key, params))
);
(bool canOverrideFee, bool canOverridePrice) =
(self.hasPermission(BEFORE_SWAP_OVERRIDE_FEE_FLAG), self.hasPermission(BEFORE_SWAP_OVERRIDE_PRICE_FLAG));
if (canOverrideFee || canOverridePrice) {
// parse override data
// equivalent to the following Solidity code:
// (,feeOverridden, fee, priceOverridden, sqrtPriceX96) = abi.decode(result, (bytes4, bool, uint24, bool, uint160));
/// @solidity memory-safe-assembly
assembly {
feeOverridden := mload(add(result, 0x40))
fee := mload(add(result, 0x60))
priceOverridden := mload(add(result, 0x80))
sqrtPriceX96 := mload(add(result, 0xA0))
}
// ensure that the hooklet is allowed to override the fee and/or price
// if the hooklet doesn't have a permission but the override is set, the override is ignored
feeOverridden = canOverrideFee && feeOverridden;
priceOverridden = canOverridePrice && priceOverridden;
// clamp the override values to the valid range
fee = feeOverridden ? uint24(fee.clamp(0, SWAP_FEE_BASE)) : 0;
sqrtPriceX96 =
priceOverridden ? uint160(sqrtPriceX96.clamp(TickMath.MIN_SQRT_PRICE, TickMath.MAX_SQRT_PRICE)) : 0;
}
}
}
function hookletBeforeSwapView(
IHooklet self,
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params
)
internal
view
noSelfCall(self, sender)
returns (bool success, bool feeOverridden, uint24 fee, bool priceOverridden, uint160 sqrtPriceX96)
{
if (
self.hasPermission(BEFORE_SWAP_FLAG)
&& (
self.hasPermission(BEFORE_SWAP_OVERRIDE_FEE_FLAG) || self.hasPermission(BEFORE_SWAP_OVERRIDE_PRICE_FLAG)
)
) {
bytes memory result;
(success, result) = self.staticcallHooklet(
IHooklet.beforeSwapView.selector, abi.encodeCall(IHooklet.beforeSwapView, (sender, key, params))
);
if (!success) return (false, false, 0, false, 0);
(bool canOverrideFee, bool canOverridePrice) =
(self.hasPermission(BEFORE_SWAP_OVERRIDE_FEE_FLAG), self.hasPermission(BEFORE_SWAP_OVERRIDE_PRICE_FLAG));
// parse override data
// equivalent to the following Solidity code:
// (,feeOverridden, fee, priceOverridden, sqrtPriceX96) = abi.decode(result, (bytes4, bool, uint24, bool, uint160));
/// @solidity memory-safe-assembly
assembly {
feeOverridden := mload(add(result, 0x40))
fee := mload(add(result, 0x60))
priceOverridden := mload(add(result, 0x80))
sqrtPriceX96 := mload(add(result, 0xA0))
}
// ensure that the hooklet is allowed to override the fee and/or price
// if the hooklet doesn't have a permission but the override is set, the override is ignored
feeOverridden = canOverrideFee && feeOverridden;
priceOverridden = canOverridePrice && priceOverridden;
// clamp the override values to the valid range
fee = feeOverridden ? uint24(fee.clamp(0, SWAP_FEE_BASE)) : 0;
sqrtPriceX96 =
priceOverridden ? uint160(sqrtPriceX96.clamp(TickMath.MIN_SQRT_PRICE, TickMath.MAX_SQRT_PRICE)) : 0;
} else {
return (true, false, 0, false, 0);
}
}
/// @dev The hasPermission check is done outside of this function in order to avoid unnecessarily constructing returnData
/// when calling it.
function hookletAfterSwap(
IHooklet self,
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
IHooklet.SwapReturnData memory returnData
) internal noSelfCall(self, sender) {
self.callHooklet(
IHooklet.afterSwap.selector, abi.encodeCall(IHooklet.afterSwap, (sender, key, params, returnData))
);
}
function hookletAfterSwapView(
IHooklet self,
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
IHooklet.SwapReturnData memory returnData
) internal view noSelfCall(self, sender) returns (bool success) {
if (self.hasPermission(AFTER_SWAP_FLAG)) {
(success,) = self.staticcallHooklet(
IHooklet.afterSwapView.selector,
abi.encodeCall(IHooklet.afterSwapView, (sender, key, params, returnData))
);
} else {
success = true;
}
}
function hasPermission(IHooklet self, uint160 flag) internal pure returns (bool) {
return uint160(address(self)) & flag != 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.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.
library Hooks {
using LPFeeLibrary for uint24;
using Hooks for IHooks;
using SafeCast for int256;
using BeforeSwapDeltaLibrary for BeforeSwapDelta;
using ParseBytes for bytes;
using CustomRevert for bytes4;
uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);
uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;
uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;
uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;
uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;
uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;
uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;
struct Permissions {
bool beforeInitialize;
bool afterInitialize;
bool beforeAddLiquidity;
bool afterAddLiquidity;
bool beforeRemoveLiquidity;
bool afterRemoveLiquidity;
bool beforeSwap;
bool afterSwap;
bool beforeDonate;
bool afterDonate;
bool beforeSwapReturnDelta;
bool afterSwapReturnDelta;
bool afterAddLiquidityReturnDelta;
bool afterRemoveLiquidityReturnDelta;
}
/// @notice Thrown if the address will not lead to the specified hook calls being called
/// @param hooks The address of the hooks contract
error HookAddressNotValid(address hooks);
/// @notice Hook did not return its selector
error InvalidHookResponse();
/// @notice Additional context for ERC-7751 wrapped error when a hook call fails
error HookCallFailed();
/// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
error HookDeltaExceedsSwapAmount();
/// @notice Utility function intended to be used in hook constructors to ensure
/// the deployed hooks address causes the intended hooks to be called
/// @param permissions The hooks that are intended to be called
/// @dev permissions param is memory as the function will be called from constructors
function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
if (
permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
|| permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
|| permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
|| permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
|| permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
|| permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
|| permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
|| permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
|| permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
|| permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
|| permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
|| permissions.afterRemoveLiquidityReturnDelta
!= self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) {
HookAddressNotValid.selector.revertWith(address(self));
}
}
/// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
/// @param self The hook to verify
/// @param fee The fee of the pool the hook is used with
/// @return bool True if the hook address is valid
function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
// The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
{
return false;
}
if (
!self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
&& self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) return false;
// If there is no hook contract set, then fee cannot be dynamic
// If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
return address(self) == address(0)
? !fee.isDynamicFee()
: (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
}
/// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
/// @return result The complete data returned by the hook
function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
bool success;
assembly ("memory-safe") {
success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
}
// Revert with FailedHookCall, containing any error message to bubble up
if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);
// The call was successful, fetch the returned data
assembly ("memory-safe") {
// allocate result byte array from the free memory pointer
result := mload(0x40)
// store new free memory pointer at the end of the array padded to 32 bytes
mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
// store length in memory
mstore(result, returndatasize())
// copy return data to result
returndatacopy(add(result, 0x20), 0, returndatasize())
}
// Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
InvalidHookResponse.selector.revertWith();
}
}
/// @notice performs a hook call using the given calldata on the given hook
/// @return int256 The delta returned by the hook
function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
bytes memory result = callHook(self, data);
// If this hook wasn't meant to return something, default to 0 delta
if (!parseReturn) return 0;
// A length of 64 bytes is required to return a bytes4, and a 32 byte delta
if (result.length != 64) InvalidHookResponse.selector.revertWith();
return result.parseReturnDelta();
}
/// @notice modifier to prevent calling a hook if they initiated the action
modifier noSelfCall(IHooks self) {
if (msg.sender != address(self)) {
_;
}
}
/// @notice calls beforeInitialize hook if permissioned and validates return value
function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
}
}
/// @notice calls afterInitialize hook if permissioned and validates return value
function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
}
}
/// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
function beforeModifyLiquidity(
IHooks self,
PoolKey memory key,
IPoolManager.ModifyLiquidityParams memory params,
bytes calldata hookData
) internal noSelfCall(self) {
if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
} else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
}
}
/// @notice calls afterModifyLiquidity hook if permissioned and validates return value
function afterModifyLiquidity(
IHooks self,
PoolKey memory key,
IPoolManager.ModifyLiquidityParams memory params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);
callerDelta = delta;
if (params.liquidityDelta > 0) {
if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
} else {
if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
}
}
/// @notice calls beforeSwap hook if permissioned and validates return value
function beforeSwap(IHooks self, PoolKey memory key, IPoolManager.SwapParams memory params, bytes calldata hookData)
internal
returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
{
amountToSwap = params.amountSpecified;
if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);
if (self.hasPermission(BEFORE_SWAP_FLAG)) {
bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));
// A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
if (result.length != 96) InvalidHookResponse.selector.revertWith();
// dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
// is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();
// skip this logic for the case where the hook return is 0
if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());
// any return in unspecified is passed to the afterSwap hook for handling
int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();
// Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
if (hookDeltaSpecified != 0) {
bool exactInput = amountToSwap < 0;
amountToSwap += hookDeltaSpecified;
if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
HookDeltaExceedsSwapAmount.selector.revertWith();
}
}
}
}
}
/// @notice calls afterSwap hook if permissioned and validates return value
function afterSwap(
IHooks self,
PoolKey memory key,
IPoolManager.SwapParams memory params,
BalanceDelta swapDelta,
bytes calldata hookData,
BeforeSwapDelta beforeSwapHookReturn
) internal returns (BalanceDelta, BalanceDelta) {
if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);
int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();
if (self.hasPermission(AFTER_SWAP_FLAG)) {
hookDeltaUnspecified += self.callHookWithReturnDelta(
abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
).toInt128();
}
BalanceDelta hookDelta;
if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
: toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);
// the caller has to pay for (or receive) the hook's delta
swapDelta = swapDelta - hookDelta;
}
return (swapDelta, hookDelta);
}
/// @notice calls beforeDonate hook if permissioned and validates return value
function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(BEFORE_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
/// @notice calls afterDonate hook if permissioned and validates return value
function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
return uint160(address(self)) & flag != 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IEIP712} from "./IEIP712.sol";
/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
/// @notice Thrown when an allowance on a token has expired.
/// @param deadline The timestamp at which the allowed amount is no longer valid
error AllowanceExpired(uint256 deadline);
/// @notice Thrown when an allowance on a token has been depleted.
/// @param amount The maximum amount allowed
error InsufficientAllowance(uint256 amount);
/// @notice Thrown when too many nonces are invalidated.
error ExcessiveInvalidation();
/// @notice Emits an event when the owner successfully invalidates an ordered nonce.
event NonceInvalidation(
address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
);
/// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
event Approval(
address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
);
/// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
event Permit(
address indexed owner,
address indexed token,
address indexed spender,
uint160 amount,
uint48 expiration,
uint48 nonce
);
/// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
event Lockdown(address indexed owner, address token, address spender);
/// @notice The permit data for a token
struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice The permit message signed for a single token allowance
struct PermitSingle {
// the permit data for a single token alownce
PermitDetails details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The permit message signed for multiple token allowances
struct PermitBatch {
// the permit data for multiple token allowances
PermitDetails[] details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The saved permissions
/// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
/// @dev Setting amount to type(uint160).max sets an unlimited approval
struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice A token spender pair.
struct TokenSpenderPair {
// the token the spender is approved
address token;
// the spender address
address spender;
}
/// @notice Details for a token transfer.
struct AllowanceTransferDetails {
// the owner of the token
address from;
// the recipient of the token
address to;
// the amount of the token
uint160 amount;
// the token to be transferred
address token;
}
/// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
/// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
/// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
function allowance(address user, address token, address spender)
external
view
returns (uint160 amount, uint48 expiration, uint48 nonce);
/// @notice Approves the spender to use up to amount of the specified token up until the expiration
/// @param token The token to approve
/// @param spender The spender address to approve
/// @param amount The approved amount of the token
/// @param expiration The timestamp at which the approval is no longer valid
/// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
/// @dev Setting amount to type(uint160).max sets an unlimited approval
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
/// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitSingle Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;
/// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitBatch Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;
/// @notice Transfer approved tokens from one address to another
/// @param from The address to transfer from
/// @param to The address of the recipient
/// @param amount The amount of the token to transfer
/// @param token The token address to transfer
/// @dev Requires the from address to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(address from, address to, uint160 amount, address token) external;
/// @notice Transfer approved tokens in a batch
/// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
/// @dev Requires the from addresses to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;
/// @notice Enables performing a "lockdown" of the sender's Permit2 identity
/// by batch revoking approvals
/// @param approvals Array of approvals to revoke.
function lockdown(TokenSpenderPair[] calldata approvals) external;
/// @notice Invalidate nonces for a given (token, spender) pair
/// @param token The token to invalidate nonces for
/// @param spender The spender to invalidate nonces for
/// @param newNonce The new nonce to set. Invalidates all nonces less than it.
/// @dev Can't invalidate more than 2**16 nonces per transaction.
function invalidateNonces(address token, address spender, uint48 newNonce) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
interface IAmAmm {
error AmAmm__BidLocked();
error AmAmm__InvalidBid();
error AmAmm__NotEnabled();
error AmAmm__Unauthorized();
error AmAmm__InvalidDepositAmount();
event SubmitBid(
PoolId indexed id,
address indexed manager,
uint48 indexed blockIdx,
bytes6 payload,
uint128 rent,
uint128 deposit
);
event DepositIntoTopBid(PoolId indexed id, address indexed manager, uint128 amount);
event WithdrawFromTopBid(PoolId indexed id, address indexed manager, address indexed recipient, uint128 amount);
event DepositIntoNextBid(PoolId indexed id, address indexed manager, uint128 amount);
event WithdrawFromNextBid(PoolId indexed id, address indexed manager, address indexed recipient, uint128 amount);
event ClaimRefund(PoolId indexed id, address indexed manager, address indexed recipient, uint256 refund);
event ClaimFees(Currency indexed currency, address indexed manager, address indexed recipient, uint256 fees);
event SetBidPayload(PoolId indexed id, address indexed manager, bytes6 payload, bool topBid);
event IncreaseBidRent(
PoolId indexed id,
address indexed manager,
uint128 additionalRent,
uint128 updatedDeposit,
bool topBid,
address indexed withdrawRecipient,
uint128 amountDeposited,
uint128 amountWithdrawn
);
struct Bid {
address manager;
uint48 blockIdx; // block number (minus contract deployment block) when the bid was created / last charged rent
bytes6 payload; // payload specifying what parames the manager wants, e.g. swap fee
uint128 rent; // rent per block
uint128 deposit; // rent deposit amount
}
/// @notice Places a bid to become the manager of a pool
/// @param id The pool id
/// @param manager The address of the manager
/// @param payload The payload specifying what parameters the manager wants, e.g. swap fee
/// @param rent The rent per block
/// @param deposit The deposit amount, must be a multiple of rent and cover rent for >=K blocks
function bid(PoolId id, address manager, bytes6 payload, uint128 rent, uint128 deposit) external;
/// @notice Adds deposit to the top bid. Only callable by topBids[id].manager.
/// @param id The pool id
/// @param amount The amount to deposit, must be a multiple of rent
function depositIntoTopBid(PoolId id, uint128 amount) external;
/// @notice Withdraws from the deposit of the top bid. Only callable by topBids[id].manager. Reverts if D_top / R_top < K.
/// @param id The pool id
/// @param amount The amount to withdraw, must be a multiple of rent and leave D_top / R_top >= K
/// @param recipient The address of the recipient
function withdrawFromTopBid(PoolId id, uint128 amount, address recipient) external;
/// @notice Adds deposit to the next bid. Only callable by nextBids[id].manager.
/// @param id The pool id
/// @param amount The amount to deposit, must be a multiple of rent
function depositIntoNextBid(PoolId id, uint128 amount) external;
/// @notice Withdraws from the deposit of the next bid. Only callable by nextBids[id].manager. Reverts if D_next / R_next < K.
/// @param id The pool id
/// @param amount The amount to withdraw, must be a multiple of rent and leave D_next / R_next >= K
/// @param recipient The address of the recipient
function withdrawFromNextBid(PoolId id, uint128 amount, address recipient) external;
/// @notice Claims the refundable deposit of a pool owed to msg.sender.
/// @param id The pool id
/// @param recipient The address of the manager
/// @return refund The amount of refund claimed
function claimRefund(PoolId id, address recipient) external returns (uint256 refund);
/// @notice Claims the accrued fees of msg.sender.
/// @param currency The currency of the fees
/// @param recipient The address of the recipient
/// @return fees The amount of fees claimed
function claimFees(Currency currency, address recipient) external returns (uint256 fees);
/// @notice Increases the rent of a bid. Only callable by the manager of the relevant bid. Reverts if D / R < K after the update.
/// Reverts if updated deposit is not a multiple of the new rent. Noop if additionalRent is 0. Will take/send the difference between the old and new deposits.
/// @param id The pool id
/// @param additionalRent The additional rent to add
/// @param updatedDeposit The updated deposit amount of the bid
/// @param topBid True if the top bid manager is increasing the rent and deposit, false if the next bid manager is increasing the rent and deposit
/// @param withdrawRecipient The address to withdraw the difference between the old and new deposits to
/// @return amountDeposited The amount of deposit added, if any
/// @return amountWithdrawn The amount of deposit withdrawn, if any
function increaseBidRent(
PoolId id,
uint128 additionalRent,
uint128 updatedDeposit,
bool topBid,
address withdrawRecipient
) external returns (uint128 amountDeposited, uint128 amountWithdrawn);
/// @notice Sets the payload of a pool. Only callable by the manager of either the top bid or the next bid.
/// @param id The pool id
/// @param payload The payload specifying e.g. the swap fee
/// @param topBid True if the top bid manager is setting the fee, false if the next bid manager is setting the fee
function setBidPayload(PoolId id, bytes6 payload, bool topBid) external;
/// @notice Gets the top bid of a pool
function getTopBid(PoolId id) external view returns (Bid memory);
/// @notice Updates the am-AMM state of a pool and then gets the top bid
function getTopBidWrite(PoolId id) external returns (Bid memory);
/// @notice Gets the next bid of a pool
function getNextBid(PoolId id) external view returns (Bid memory);
/// @notice Updates the am-AMM state of a pool and then gets the next bid
function getNextBidWrite(PoolId id) external returns (Bid memory);
/// @notice Gets the refundable deposit of a pool
/// @param manager The address of the manager
/// @param id The pool id
function getRefund(address manager, PoolId id) external view returns (uint256);
/// @notice Updates the am-AMM state of a pool and then gets the refundable deposit owed to a manager in that pool
/// @param manager The address of the manager
/// @param id The pool id
function getRefundWrite(address manager, PoolId id) external returns (uint256);
/// @notice Gets the fees accrued by a manager
/// @param manager The address of the manager
/// @param currency The currency of the fees
function getFees(address manager, Currency currency) external view returns (uint256);
/// @notice Triggers a state machine update for the given pool
/// @param id The pool id
function updateStateMachine(PoolId id) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {BeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
interface IBaseHook {
error NotPoolManager();
function poolManager() external view returns (IPoolManager);
/// @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 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,
IPoolManager.SwapParams calldata params,
bytes calldata hookData
) external returns (bytes4, BeforeSwapDelta, uint24);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {IAmAmm} from "biddog/interfaces/IAmAmm.sol";
import "flood-contracts/src/interfaces/IZone.sol";
import "flood-contracts/src/interfaces/IFloodPlain.sol";
import {IERC1271} from "permit2/src/interfaces/IERC1271.sol";
import "../base/Constants.sol";
import "../base/SharedStructs.sol";
import {IOwnable} from "./IOwnable.sol";
import {Oracle} from "../lib/Oracle.sol";
import {IBunniHub} from "./IBunniHub.sol";
import {IBaseHook} from "./IBaseHook.sol";
/// @title BunniHook
/// @author zefram.eth
/// @notice Uniswap v4 hook responsible for handling swaps on Bunni. Implements auto-rebalancing
/// executed via FloodPlain. Uses am-AMM to recapture LVR & MEV.
interface IBunniHook is IBaseHook, IOwnable, IUnlockCallback, IERC1271, IAmAmm {
/// -----------------------------------------------------------------------
/// Events
/// -----------------------------------------------------------------------
/// @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 zeroForOne True if swapping token0 for token1, false otherwise
/// @param inputAmount The input token amount
/// @param outputAmount The output token amount
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee rate charged, 6 decimals
/// @param totalLiquidity The total virtual liquidity of the pool during and after the swap
event Swap(
PoolId indexed id,
address indexed sender,
bool exactIn,
bool zeroForOne,
uint256 inputAmount,
uint256 outputAmount,
uint160 sqrtPriceX96,
int24 tick,
uint24 fee,
uint256 totalLiquidity
);
event SetZone(IZone zone);
event SetHookFeeRecipient(address hookFeeRecipient);
event SetModifiers(uint32 indexed hookFeeModifier, uint32 indexed referrerRewardModifier);
event SetWithdrawalUnblocked(PoolId indexed id, bool unblocked);
event ClaimProtocolFees(Currency[] currencyList, address indexed recipient);
/// -----------------------------------------------------------------------
/// Structs and enums
/// -----------------------------------------------------------------------
/// @notice The state of a TWAP oracle for a given pool
/// @member index The index of the last written observation for the pool
/// @member cardinality The cardinality of the observations array for the pool
/// @member cardinalityNext The cardinality target of the observations array for the pool, which will replace cardinality when enough observations are written
/// @member intermediateObservation Used to maintain a min interval between observations
struct ObservationState {
uint32 index;
uint32 cardinality;
uint32 cardinalityNext;
Oracle.Observation intermediateObservation;
}
/// @notice The arguments passed to the rebalance order prehook and posthook.
/// @dev The hash of the hook args is used for validation in the prehook and posthook.
/// @member key The pool key of the pool being rebalanced
/// @member preHookArgs The prehook arguments
/// @member postHookArgs The posthook arguments
struct RebalanceOrderHookArgs {
PoolKey key;
RebalanceOrderPreHookArgs preHookArgs;
RebalanceOrderPostHookArgs postHookArgs;
}
/// @notice The arguments passed to the rebalance order prehook.
/// @member currency The currency to take from BunniHub and sell via the rebalance order
/// @member amount The amount of currency to take from BunniHub and sell via the rebalance order
struct RebalanceOrderPreHookArgs {
Currency currency;
uint256 amount;
}
/// @notice The arguments passed to the rebalance order posthook.
/// @member currency The currency to receive from the rebalance order and give to BunniHub
struct RebalanceOrderPostHookArgs {
Currency currency;
}
/// -----------------------------------------------------------------------
/// View functions
/// -----------------------------------------------------------------------
/// @notice Returns the observation for the given pool key and observation index
/// @param key The pool key
/// @param index The observation index
/// @return observation The observation struct
function getObservation(PoolKey calldata key, uint256 index)
external
view
returns (Oracle.Observation memory observation);
/// @notice Returns the TWAP oracle observation state for the given pool key
/// @param key The pool key
/// @return state The state struct
function getState(PoolKey calldata key) external view returns (ObservationState memory state);
/// @notice Observe the given pool for the timestamps
/// @param key The pool key
/// @param secondsAgos The timestamps to observe
/// @return tickCumulatives The tick cumulatives for the given timestamps
function observe(PoolKey calldata key, uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives);
/// @notice Validates if the given hook params are valid
/// @param hookParams The hook params
/// @return isValid True if the hook params are valid
function isValidParams(bytes calldata hookParams) external view returns (bool);
/// @notice The LDF state of a given pool. Used for evaluating the LDF.
/// @param id The pool id
/// @return The LDF state
function ldfStates(PoolId id) external view returns (bytes32);
/// @notice The slot0 state of a given pool
/// @param id The pool id
/// @return sqrtPriceX96
/// @return tick The tick of the pool
/// @return lastSwapTimestamp The timestamp of the last swap
/// @return lastSurgeTimestamp The timestamp of the last surge
function slot0s(PoolId id)
external
view
returns (uint160 sqrtPriceX96, int24 tick, uint32 lastSwapTimestamp, uint32 lastSurgeTimestamp);
/// @notice The share prices of the vaults used by the pool at the last swap
/// @param id The pool id
/// @return initialized True if the share prices have been initialized
/// @return sharePrice0 The underlying assets each share of vault0 represents, scaled by 1e18
/// @return sharePrice1 The underlying assets each share of vault1 represents, scaled by 1e18
function vaultSharePricesAtLastSwap(PoolId id)
external
view
returns (bool initialized, uint120 sharePrice0, uint120 sharePrice1);
/// @notice Whether am-AMM is enabled for the given pool.
function getAmAmmEnabled(PoolId id) external view returns (bool);
/// @notice Whether liquidity can be withdrawn from the given pool.
/// Currently used for pausing withdrawals when there is an active rebalance order.
/// @param id The pool id
/// @return Whether liquidity can be withdrawn from the given pool.
function canWithdraw(PoolId id) external view returns (bool);
/// @notice Returns the hook protocol fee recipient
function getHookFeeRecipient() external view returns (address);
/// @notice Returns the modifiers for computing hook fee and referral reward
function getModifiers() external view returns (uint32 hookFeeModifier_, uint32 referralRewardModifier_);
/// @notice Returns the claimable hook fees for the given currencies
/// @param currencyList The list of currencies to claim fees for
/// @return feeAmounts The list of claimable fees for each currency
function getClaimableHookFees(Currency[] calldata currencyList)
external
view
returns (uint256[] memory feeAmounts);
/// -----------------------------------------------------------------------
/// External functions
/// -----------------------------------------------------------------------
/// @notice Increase the cardinality target for the given pool
/// @param key The pool key
/// @param cardinalityNext The new cardinality target
/// @return cardinalityNextOld The old cardinality target
/// @return cardinalityNextNew The new cardinality target
function increaseCardinalityNext(PoolKey calldata key, uint32 cardinalityNext)
external
returns (uint32 cardinalityNextOld, uint32 cardinalityNextNew);
/// @notice Claim protocol fees for the given currency list.
/// @param currencyList The list of currencies to claim fees for
function claimProtocolFees(Currency[] calldata currencyList) external;
/// -----------------------------------------------------------------------
/// BunniHub functions
/// -----------------------------------------------------------------------
/// @notice Update the LDF state of the given pool. Only callable by BunniHub.
/// @param id The pool id
/// @param newState The new LDF state
function updateLdfState(PoolId id, bytes32 newState) external;
/// -----------------------------------------------------------------------
/// Owner functions
/// -----------------------------------------------------------------------
/// @notice Set the FloodZone contract address. Only callable by the owner.
/// @param zone The new FloodZone contract address
function setZone(IZone zone) external;
/// @notice Set the hook protocol fee recipient. Only callable by the owner.
/// @param newProtocolFeeRecipient The new protocol fee recipient address
function setHookFeeRecipient(address newProtocolFeeRecipient) external;
/// @notice Set the hook fee & referral reward params. Only callable by the owner.
/// @param newHookFeeModifier The new hook fee modifier. 6 decimals.
/// @param newReferralRewardModifier The new referral reward modifier. 6 decimals.
function setModifiers(uint32 newHookFeeModifier, uint32 newReferralRewardModifier) external;
/// @notice Set whether withdrawals are unblocked for the given pool. Only callable by the owner.
/// @param id The pool id
/// @param unblocked Whether withdrawals are unblocked for the given pool when a rebalance order is active
function setWithdrawalUnblocked(PoolId id, bool unblocked) external;
/// -----------------------------------------------------------------------
/// Rebalance functions
/// -----------------------------------------------------------------------
/// @notice Called by the FloodPlain contract prior to executing a rebalance order.
/// Should ensure the hook has exactly `hookArgs.preHookArgs.amount` tokens of `hookArgs.preHookArgs.currency` upon return.
/// @param hookArgs The rebalance order hook arguments
function rebalanceOrderPreHook(RebalanceOrderHookArgs calldata hookArgs) external;
/// @notice Called by the FloodPlain contract after executing a rebalance order.
/// Should transfer any output tokens from the order to BunniHub and update pool balances.
/// @param hookArgs The rebalance order hook arguments
function rebalanceOrderPostHook(RebalanceOrderHookArgs calldata hookArgs) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
pragma abicoder v2;
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {IPoolManager, PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {WETH} from "solady/tokens/WETH.sol";
import {ERC4626} from "solady/tokens/ERC4626.sol";
import "../types/LDFType.sol";
import "../types/IdleBalance.sol";
import "../base/SharedStructs.sol";
import {IERC20} from "./IERC20.sol";
import {IHooklet} from "./IHooklet.sol";
import {IOwnable} from "./IOwnable.sol";
import {IBunniHook} from "./IBunniHook.sol";
import {IBunniToken} from "./IBunniToken.sol";
import {PoolState} from "../types/PoolState.sol";
import {ILiquidityDensityFunction} from "./ILiquidityDensityFunction.sol";
/// @title BunniHub
/// @author zefram.eth
/// @notice The main contract LPs interact with. Each BunniKey corresponds to a BunniToken,
/// which is the ERC20 LP token for the Uniswap V3 position specified by the BunniKey.
/// Use deposit()/withdraw() to mint/burn LP tokens, and use compound() to compound the swap fees
/// back into the LP position.
interface IBunniHub is IUnlockCallback, IOwnable {
/// @notice Emitted when liquidity is increased via deposit
/// @param sender The msg.sender address
/// @param recipient The address of the account that received the share tokens
/// @param poolId The Uniswap V4 pool's ID
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
/// @param shares The amount of share tokens minted to the recipient
event Deposit(
address indexed sender,
address indexed recipient,
PoolId indexed poolId,
uint256 amount0,
uint256 amount1,
uint256 shares
);
/// @notice Emitted when a withdrawal is queued
/// @param sender The msg.sender address
/// @param poolId The Uniswap V4 pool's ID
/// @param shares The amount of share tokens queued for withdrawal
event QueueWithdraw(address indexed sender, PoolId indexed poolId, uint256 shares);
/// @notice Emitted when liquidity is decreased via withdrawal
/// @param sender The msg.sender address
/// @param recipient The address of the account that received the collected tokens
/// @param poolId The Uniswap V4 pool's ID
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
/// @param shares The amount of share tokens burnt from the sender
event Withdraw(
address indexed sender,
address indexed recipient,
PoolId indexed poolId,
uint256 amount0,
uint256 amount1,
uint256 shares
);
/// @notice Emitted when a new IBunniToken is created
/// @param bunniToken The BunniToken associated with the call
/// @param poolId The Uniswap V4 pool's ID
event NewBunni(IBunniToken indexed bunniToken, PoolId indexed poolId);
/// @notice Emitted when the recipient of referral rewards of the default referrer address(0) is set
/// @param newReferralRewardRecipient The new recipient of referral rewards of the default referrer address(0)
event SetReferralRewardRecipient(address indexed newReferralRewardRecipient);
/// @notice Emitted when a new address is added to or removed from the pauser set
/// @param guy The address that was added or removed from the pauser set
/// @param isPauser True if the address was added to the pauser set, false if it was removed
event SetPauser(address indexed guy, bool indexed isPauser);
/// @notice Emitted when the pause flags are set
/// @param pauseFlags The new pause flags, each bit corresponds to a function in BunniHub and is set to 1 if the function is paused
event SetPauseFlags(uint8 indexed pauseFlags);
/// @notice Emitted when the pause fuse is burned
event BurnPauseFuse();
/// @param poolKey The PoolKey of the Uniswap V4 pool
/// @param recipient The recipient of the minted share tokens
/// @param refundRecipient The recipient of the refunded ETH
/// @param amount0Desired The desired amount of token0 to be spent,
/// @param amount1Desired The desired amount of token1 to be spent,
/// @param amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// @param amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// @param vaultFee0 When we deposit token0 into vault0, the deposit amount is multiplied by WAD / (WAD - vaultFee0),
/// @param vaultFee1 When we deposit token1 into vault1, the deposit amount is multiplied by WAD / (WAD - vaultFee1),
/// @param deadline The time by which the transaction must be included to effect the change
/// @param referrer The referrer of the liquidity provider. Used for fee sharing.
struct DepositParams {
PoolKey poolKey;
address recipient;
address refundRecipient;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 vaultFee0;
uint256 vaultFee1;
uint256 deadline;
address referrer;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @dev Must be called after the corresponding BunniToken has been deployed via deployBunniToken()
/// @param params The input parameters
/// poolKey The PoolKey of the Uniswap V4 pool
/// recipient The recipient of the minted share tokens
/// refundRecipient The recipient of the refunded ETH
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// vaultFee0 When we deposit token0 into vault0, the deposit amount is multiplied by WAD / (WAD - vaultFee0),
/// vaultFee1 When we deposit token1 into vault1, the deposit amount is multiplied by WAD / (WAD - vaultFee1),
/// deadline The time by which the transaction must be included to effect the change
/// @return shares The new share tokens minted to the sender
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function deposit(DepositParams calldata params)
external
payable
returns (uint256 shares, uint256 amount0, uint256 amount1);
/// @param poolKey The PoolKey of the Uniswap V4 pool
/// @param shares The amount of share tokens to burn. Ignored if an expired queued withdrawal exists.
struct QueueWithdrawParams {
PoolKey poolKey;
uint200 shares;
}
/// @notice Queues a withdrawal of liquidity. Need to use this before calling withdraw() if am-AMM is enabled
/// and a manager exists for the pool. A queued withdrawal is unlocked after WITHDRAW_DELAY (1 minutes) has passed,
/// and before WITHDRAW_GRACE_PERIOD (15 minutes) has passed after it's been unlocked. This ensures the am-AMM manager
/// has an opportunity to execute any arbitrage trades before a withdrawal is processed.
/// @param params The input parameters
/// poolKey The PoolKey of the Uniswap V4 pool
/// shares The amount of share tokens to burn
function queueWithdraw(QueueWithdrawParams calldata params) external;
/// @param poolKey The PoolKey of the Uniswap V4 pool
/// @param recipient The recipient of the withdrawn tokens
/// @param shares The amount of share tokens to burn
/// @param amount0Min The minimum amount of token0 that should be accounted for the burned liquidity
/// @param amount1Min The minimum amount of token1 that should be accounted for the burned liquidity
/// @param deadline The time by which the transaction must be included to effect the change
/// @param useQueuedWithdrawal If true, queued withdrawal share tokens will be used
struct WithdrawParams {
PoolKey poolKey;
address recipient;
uint256 shares;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
bool useQueuedWithdrawal;
}
/// @notice Decreases the amount of liquidity in the position and sends the tokens to the sender.
/// If withdrawing ETH, need to follow up with unwrapWETH9() and sweepToken()
/// @dev Must be called after the corresponding BunniToken has been deployed via deployBunniToken()
/// @param params The input parameters
/// poolKey The Uniswap v4 pool's key
/// recipient The recipient of the withdrawn tokens
/// shares The amount of share tokens to burn,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 withdrawn to the recipient
/// @return amount1 The amount of token1 withdrawn to the recipient
function withdraw(WithdrawParams calldata params) external returns (uint256 amount0, uint256 amount1);
/// @param currency0 The token0 of the Uniswap V4 pool
/// @param currency1 The token1 of the Uniswap V4 pool
/// @param tickSpacing The tick spacing of the Uniswap V4 pool
/// @param twapSecondsAgo The TWAP time period to use for the liquidity density function
/// @param liquidityDensityFunction The liquidity density function to use
/// @param ldfType The type of LDF. See LDFType.sol for details.
/// @param hooklet The hooklet to use for the Bunni pool. If it's address(0), then a hooklet is not used.
/// @param ldfParams The parameters for the liquidity density function
/// @param hooks The hooks to use for the Uniswap V4 pool
/// @param hookParams The parameters for the hooks
/// @param vault0 The vault for token0. If address(0), then a vault is not used.
/// @param vault1 The vault for token1. If address(0), then a vault is not used.
/// @param minRawTokenRatio0 The minimum (rawBalance / balance) ratio for token0
/// @param targetRawTokenRatio0 The target (rawBalance / balance) ratio for token0
/// @param maxRawTokenRatio0 The maximum (rawBalance / balance) ratio for token0
/// @param minRawTokenRatio1 The minimum (rawBalance / balance) ratio for token1
/// @param targetRawTokenRatio1 The target (rawBalance / balance) ratio for token1
/// @param maxRawTokenRatio1 The maximum (rawBalance / balance) ratio for token1
/// @param sqrtPriceX96 The initial sqrt price of the Uniswap V4 pool
/// @param name The name of the BunniToken
/// @param symbol The symbol of the BunniToken
/// @param owner The owner of the BunniToken. Only has the power to set the metadata URI.
/// @param metadataURI The initial metadata URI of the BunniToken, containing info like description, image, etc.
/// @param salt The salt for deploying the BunniToken via CREATE3.
struct DeployBunniTokenParams {
Currency currency0;
Currency currency1;
int24 tickSpacing;
uint24 twapSecondsAgo;
ILiquidityDensityFunction liquidityDensityFunction;
IHooklet hooklet;
LDFType ldfType;
bytes32 ldfParams;
IBunniHook hooks;
bytes hookParams;
ERC4626 vault0;
ERC4626 vault1;
uint24 minRawTokenRatio0;
uint24 targetRawTokenRatio0;
uint24 maxRawTokenRatio0;
uint24 minRawTokenRatio1;
uint24 targetRawTokenRatio1;
uint24 maxRawTokenRatio1;
uint160 sqrtPriceX96;
bytes32 name;
bytes32 symbol;
address owner;
string metadataURI;
bytes32 salt;
}
/// @notice Deploys the BunniToken contract for a Bunni position. This token
/// represents a user's share in the Uniswap V4 LP position.
/// @dev The BunniToken is deployed via CREATE3, which allows for a deterministic address.
/// @param params The input parameters
/// currency0 The token0 of the Uniswap V4 pool
/// currency1 The token1 of the Uniswap V4 pool
/// tickSpacing The tick spacing of the Uniswap V4 pool
/// twapSecondsAgo The TWAP time period to use for the liquidity density function
/// liquidityDensityFunction The liquidity density function to use
/// hooklet The hooklet to use for the Bunni pool. If it's address(0), then a hooklet is not used.
/// ldfParams The parameters for the liquidity density function
/// hooks The hooks to use for the Uniswap V4 pool
/// hookParams The parameters for the hooks
/// vault0 The vault for token0. If address(0), then a vault is not used.
/// vault1 The vault for token1. If address(0), then a vault is not used.
/// minRawTokenRatio0 The minimum (rawBalance / balance) ratio for token0
/// targetRawTokenRatio0 The target (rawBalance / balance) ratio for token0
/// maxRawTokenRatio0 The maximum (rawBalance / balance) ratio for token0
/// minRawTokenRatio1 The minimum (rawBalance / balance) ratio for token1
/// targetRawTokenRatio1 The target (rawBalance / balance) ratio for token1
/// maxRawTokenRatio1 The maximum (rawBalance / balance) ratio for token1
/// sqrtPriceX96 The initial sqrt price of the Uniswap V4 pool
/// name The name of the BunniToken
/// symbol The symbol of the BunniToken
/// owner The owner of the BunniToken. Only has the power to set the metadata URI.
/// metadataURI The initial metadata URI of the BunniToken, containing info like description, image, etc.
/// salt The salt for deploying the BunniToken via CREATE3.
/// @return token The deployed BunniToken
/// @return key The PoolKey of the Uniswap V4 pool
function deployBunniToken(DeployBunniTokenParams calldata params)
external
returns (IBunniToken token, PoolKey memory key);
/// @notice Called by the hook to execute a generalized swap from one token to the other. Also used during rebalancing.
/// @dev If the raw balance is insufficient, vault reserves will be automatically used.
/// Will update vault reserves if the raw/reserve ratio is outside of the bounds.
/// @param key The PoolKey of the Uniswap V4 pool
/// @param zeroForOne True if the swap is for token0->token1, false if token1->token0
/// @param inputAmount The amount of the input token to pull from the hook
/// @param outputAmount The amount of the output token to push to the hook
function hookHandleSwap(PoolKey calldata key, bool zeroForOne, uint256 inputAmount, uint256 outputAmount)
external;
/// @notice Called by the hook to set the idle balance of a Bunni pool.
/// @param key The PoolKey of the Uniswap V4 pool
/// @param newIdleBalance The new idle balance of the pool
function hookSetIdleBalance(PoolKey calldata key, IdleBalance newIdleBalance) external;
/// @notice Sets the address of the recipient of referral rewards belonging to the default referrer address(0). Only callable by the owner.
/// @param newReferralRewardRecipient The new address of the recipient of referral rewards
function setReferralRewardRecipient(address newReferralRewardRecipient) external;
/// @notice Adds or removes an address from the pauser set. Only callable by the owner.
/// @param guy The address to add or remove from the pauser set
/// @param isPauser True if the address should be added to the pauser set, false if it should be removed
function setPauser(address guy, bool isPauser) external;
/// @notice Sets the pause flags. Only callable by the owner.
/// @param pauseFlags The new pause flags, each bit corresponds to a function in BunniHub and is set to 1 if the function is paused
function setPauseFlags(uint8 pauseFlags) external;
/// @notice Burns the pause fuse. Only callable by the owner.
/// All functions are permanently unpaused after this function is called.
function burnPauseFuse() external;
/// @notice Called by key.hooks to lock BunniHub before a rebalance order's execution.
/// @param key The PoolKey of the Uniswap v4 pool
function lockForRebalance(PoolKey calldata key) external;
/// @notice Called by key.hooks to unlock BunniHub after a rebalance order's execution.
/// @param key The PoolKey of the Uniswap v4 pool
function unlockForRebalance(PoolKey calldata key) external;
/// @notice The state of a Bunni pool.
function poolState(PoolId poolId) external view returns (PoolState memory);
/// @notice The PoolState struct of a given pool with only the immutable params filled out.
function poolParams(PoolId poolId) external view returns (PoolState memory);
/// @notice The BunniToken of a given pool. address(0) if the pool is not a Bunni pool.
function bunniTokenOfPool(PoolId poolId) external view returns (IBunniToken);
/// @notice The params of the given Bunni pool's hook. bytes("") if the pool is not a Bunni pool.
function hookParams(PoolId poolId) external view returns (bytes memory);
/// @notice The next available nonce of the given Bunni subspace.
function nonce(bytes32 bunniSubspace) external view returns (uint24);
/// @notice The PoolId of a given BunniToken.
function poolIdOfBunniToken(IBunniToken bunniToken) external view returns (PoolId);
/// @notice The token balances of a Bunni pool. Reserves in vaults are converted to raw token balances via ERC4626.previewRedeem().
function poolBalances(PoolId poolId) external view returns (uint256 balance0, uint256 balance1);
/// @notice The idle balance of a Bunni pool.
function idleBalance(PoolId poolId) external view returns (IdleBalance);
/// @notice The address of the recipient of referral rewards belonging to the default referrer address(0).
function getReferralRewardRecipient() external view returns (address);
/// @notice Returns true if the given address is a pauser who can pause/unpause external functions.
function isPauser(address guy) external view returns (bool);
/// @notice The pause flags and pause fuse status.
/// @return pauseFlags The pause flags, each bit corresponds to a function in BunniHub and is set to 1 if the function is paused
/// @return unpauseFuse The pause fuse status. If true, all functions are permanently unpaused
function getPauseStatus() external view returns (uint8 pauseFlags, bool unpauseFuse);
/// @notice The init data of a Bunni pool. Stored in transient storage and used
/// during the IHooks.afterInitialize() call.
function poolInitData() external view returns (bytes memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import "@uniswap/v4-core/src/types/Currency.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {IERC20} from "./IERC20.sol";
import {IOwnable} from "./IOwnable.sol";
import {IHooklet} from "./IHooklet.sol";
import {IBunniHub} from "./IBunniHub.sol";
import {IERC20Referrer} from "./IERC20Referrer.sol";
import {IERC20Lockable} from "./IERC20Lockable.sol";
/// @title BunniToken
/// @author zefram.eth
/// @notice ERC20 token that represents a user's LP position
interface IBunniToken is IERC20, IERC20Referrer, IERC20Lockable, IOwnable, IUnlockCallback {
event ClaimReferralRewards(address indexed referrer, uint256 reward0, uint256 reward1);
event SetMetadataURI(string newURI);
function hub() external view returns (IBunniHub);
function token0() external view returns (Currency);
function token1() external view returns (Currency);
function poolManager() external view returns (IPoolManager);
function poolKey() external view returns (PoolKey memory);
function hooklet() external view returns (IHooklet);
function mint(address to, uint256 amount) external;
function mint(address to, uint256 amount, address referrer) external;
function burn(address from, uint256 amount) external;
function burn(uint256 amount) external;
function initialize(address owner_, string calldata metadataURI_) external;
function metadataURI() external view returns (string memory);
function setMetadataURI(string calldata metadataURI_) external;
/// @notice Distributes referral rewards to all referrers. Usually called by the hook but can be called by anyone.
/// The referral rewards should be in the form of PoolManager ERC6909 claim tokens.
/// @dev Does not early return if the reward amount is 0, so the caller is responsible for not calling this function
/// if amount is indeed 0.
/// @param isToken0 Whether the rewards are in token0 or token1
/// @param amount The amount of rewards to distribute.
function distributeReferralRewards(bool isToken0, uint256 amount) external;
/// @notice Claims referral rewards for a given referrer ID. Can be called by anyone.
/// @param referrer The referrer to claim rewards for
/// @return reward0 The amount of token0 rewards claimed
/// @return reward1 The amount of token1 rewards claimed
function claimReferralRewards(address referrer) external returns (uint256 reward0, uint256 reward1);
/// @notice Returns the amount of referral rewards claimable by a given referrer ID.
/// @param referrer The referrer to check rewards for
/// @return reward0 The amount of token0 rewards claimable
/// @return reward1 The amount of token1 rewards claimable
function getClaimableReferralRewards(address referrer) external view returns (uint256 reward0, uint256 reward1);
/// @notice Increments the EIP-2612 permit nonce of the caller to invalidate permit signatures.
function incrementNonce() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IEIP712 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC1271 {
/// @dev Should return whether the signature provided is valid for the provided data
/// @param hash Hash of the data to be signed
/// @param signature Signature byte array associated with _data
/// @return magicValue The bytes4 magic value 0x1626ba7e
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
* Modified from OpenZeppelin's IERC20 contract
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @return The name of the token
*/
function name() external view returns (string memory);
/**
* @return The symbol of the token
*/
function symbol() external view returns (string memory);
/**
* @return The number of decimal places the token has
*/
function decimals() external view returns (uint8);
function nonces(address account) external view returns (uint256);
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
external;
function DOMAIN_SEPARATOR() external view returns (bytes32);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "./IERC20Unlocker.sol";
/// @title IERC20Lockable - Interface for a lockable token account.
/// @notice A token holder can lock their account, preventing any transfers from the account.
/// An unlocker contract is able to unlock the account. The unlocker contract is expected to
/// implement the `IERC20Unlocker` interface.
/// Used mainly for staking contracts that don't require transferring the token into the contract.
interface IERC20Lockable {
event Lock(address indexed account, IERC20Unlocker indexed unlocker);
event Unlock(address indexed account, IERC20Unlocker indexed unlocker);
/// @dev Error when calling lock() and the account is already locked.
error AlreadyLocked();
/// @dev Error when calling unlock() and the account is already unlocked.
error AlreadyUnlocked();
/// @dev Error when the caller is not the unlocker of the account.
error NotUnlocker();
/// @dev Error when trasferring tokens from a locked account.
error AccountLocked();
/// @notice Called by a token holder to lock their account. Once locked an account
/// can no longer transfer tokens until it's been unlocked. Only `unlocker` has the
/// ability to unlock the account. Reverts if the account is already locked.
/// @dev `unlocker` will receive the data via a `lockCallback()` call from this contract.
/// @param unlocker The address that will be able to unlock the account.
/// @param data Additional data with no specified format.
function lock(IERC20Unlocker unlocker, bytes calldata data) external;
/// @notice Called by an unlocker contract to unlock an account.
/// Reverts if the caller is not the unlocker of the account, or if
/// the account is not locked.
/// @param account The account to unlock.
function unlock(address account) external;
/// @notice Returns true if the account is locked, false otherwise.
/// @param account The account to check.
/// @return True if the account is locked, false otherwise.
function isLocked(address account) external view returns (bool);
/// @notice Returns the unlocker of the account. Be aware that the unlocker
/// is not set to 0 after the account has been unlocked, so the caller should
/// use this function in combination with `isLocked()`.
/// @param account The account whose unlocker is to be returned.
/// @return unlocker The unlocker of the account.
function unlockerOf(address account) external view returns (IERC20Unlocker unlocker);
}
// 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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IERC20Referrer {
/// @notice Returns the score of a referrer. The score is the sum of all
/// balances of accounts that have the referrer as their referrer.
/// @param referrer The referrer whose score is to be returned.
/// @return score The score of the referrer.
function scoreOf(address referrer) external view returns (uint256 score);
/// @notice Returns the referrer of an account. Default referrer is 0.
/// @param account The account whose referrer is to be returned.
/// @return referrer The referrer of the account.
function referrerOf(address account) external view returns (address referrer);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
/// @title IERC20Unlocker - Interface for an unlocker contract for `IERC20Lockable`.
/// @notice An unlocker contract is able to unlock accounts that have been locked by a `IERC20Lockable` contract.
/// The unlocker contract is expected to implement the `IERC20Unlocker` interface.
interface IERC20Unlocker {
/// @notice Called when an account calls `IERC20Lockable.lock()` and specifies this contract as the unlocker.
/// @param account The account that called `IERC20Lockable.lock()`.
/// @param balance The balance of the account after the lock.
/// @param data The data passed to `IERC20Lockable.lock()`.
function lockCallback(address account, uint256 balance, bytes calldata data) external;
/// @notice Called when a locked account with this contract as the unlocker receives tokens.
/// @param account The account that received tokens.
/// @param receiveAmount The amount of tokens received.
function lockedUserReceiveCallback(address account, uint256 receiveAmount) external;
}
// 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);
}
// 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);
}
// 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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {ISignatureTransfer} from "permit2/src/interfaces/ISignatureTransfer.sol";
interface IFloodPlain {
error InsufficientAmountReceived();
error NotAContract();
error ZoneDenied();
error DuplicateItems();
error ArrayLengthMismatch();
event OrderFulfilled(bytes32 indexed orderHash, address indexed zone, address indexed fulfiller, uint256 amountOut);
struct SignedOrder {
Order order;
bytes signature;
}
struct Order {
address offerer;
address zone;
address recipient;
Item[] offer;
Item consideration;
uint256 deadline;
uint256 nonce;
Hook[] preHooks;
Hook[] postHooks;
}
struct Item {
address token;
uint256 amount;
}
struct Hook {
address target;
bytes data;
}
/**
* @notice Get Permit2 SignatureTransfer contract that is used in verifying orders.
*/
function PERMIT2() external view returns (ISignatureTransfer);
/**
* @notice Retrieve the permit2 hash for a given order.
*
* @param order The components of the order.
*
* @return permitHash The permit2 hash as order as the witness.
*/
function getPermitHash(Order calldata order) external view returns (bytes32 permitHash);
/**
* @notice Retrieve the order hash for a given order.
*
* @param order The components of the order.
*
* @return orderHash The order hash.
*/
function getOrderHash(Order calldata order) external view returns (bytes32 orderHash);
/**
* @notice Check if the order deadline has passed or its nonce has been cancelled or used.
*
* @param order The components of the order.
*
* @return isValid A boolean guaranteeing the order cannot be fulfilled if false.
*/
function getOrderStatus(Order calldata order) external view returns (bool isValid);
/**
* @notice Check if the nonce of a user is available.
*
* @param user The address of the user to check the nonce of.
* @param nonce The nonce of the user to check.
*
* @return isValid A boolean returning true if the nonce is not flipped.
*/
function getNonceStatus(address user, uint256 nonce) external view returns (bool isValid);
/**
* @notice Allow receiving ether from Fulfiller. No checks are made to ensure the ether is
* sent from a Fulfiller. If ether is sent directly, it can be stolen.
*/
receive() external payable;
/**
* @notice Fulfill an order directly by transferring consideration from caller to offerer.
*
* @param package The order to fulfill and the permit2 signature with the order as the witness.
* Note that the offerer must first approve Permit2 contract to transfer any
* relevant tokens on their behalf.
*/
function fulfillOrder(SignedOrder calldata package) external payable;
/**
* @notice Fulfill single order.
*
* @param package The order to fulfill and its signatures. The offerer must first approve
* Permit2 contract to transfer any relevant tokens on their behalf.
* @param fulfiller The address that will receive offer items, then source consideration for
* the offerer.
* @param swapData Extra bytes passed to the Fulfiller.
*/
function fulfillOrder(SignedOrder calldata package, address fulfiller, bytes calldata swapData) external;
/**
* @notice Fulfill series of orders.
*
* @param packages The orders to fulfill and their signatures. The offerer must first approve
* Permit2 contract to transfer any relevant tokens on their behalf.
* @param fulfiller The address that will receive offer items, then source consideration items
* for the offerer.
* @param swapData Extra bytes passed to the Fulfiller.
*/
function fulfillOrders(SignedOrder[] calldata packages, address fulfiller, bytes calldata swapData) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IPoolManager, PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IBunniHub} from "./IBunniHub.sol";
import {IBunniToken} from "./IBunniToken.sol";
/// @title Hooklet
/// @notice Hooklets let developers execute custom logic before/after Bunni operations.
/// Each Bunni pool can have one hooklet attached to it. The least significant bits of the hooklet's
/// address is used to flag which hooklet functions should be callled.
interface IHooklet {
/// @notice Return data of an initialize operation.
/// @member bunniToken The BunniToken deployed.
/// @member key The Uniswap v4 pool's key.
struct InitializeReturnData {
IBunniToken bunniToken;
PoolKey key;
}
/// @notice Return data of a deposit operation.
/// @member shares The amount of shares minted.
/// @member amount0 The amount of token0 deposited.
/// @member amount1 The amount of token1 deposited.
struct DepositReturnData {
uint256 shares;
uint256 amount0;
uint256 amount1;
}
/// @notice Return data of a withdraw operation.
/// @member amount0 The amount of token0 withdrawn.
/// @member amount1 The amount of token1 withdrawn.
struct WithdrawReturnData {
uint256 amount0;
uint256 amount1;
}
/// @notice Return data of a swap operation.
/// @member updatedSqrtPriceX96 The pool's updated sqrt price after the swap.
/// @member updatedTick The pool's updated tick after the swap.
/// @member inputAmount The amount of input tokens swapped.
/// @member outputAmount The amount of output tokens received.
/// @member swapFee The swap fee used for the swap. 6 decimals.
/// @member totalLiquidity The pool's total liquidity after the swap.
struct SwapReturnData {
uint160 updatedSqrtPriceX96;
int24 updatedTick;
uint256 inputAmount;
uint256 outputAmount;
uint24 swapFee;
uint256 totalLiquidity;
}
/// @notice Overrides the swap fee of a pool before the swap is executed.
/// Ignored if the pool has an am-AMM manager.
/// @member overridden If true, the swap fee is overridden.
/// @member fee The swap fee to use for the swap. 6 decimals.
struct BeforeSwapFeeOverride {
bool overridden;
uint24 fee;
}
/// @notice Overrides the pool's spot price before the swap is executed.
/// @member overridden If true, the pool's spot price is overridden.
/// @member sqrtPriceX96 The spot price to use for the swap. Q96 value.
struct BeforeSwapPriceOverride {
bool overridden;
uint160 sqrtPriceX96;
}
/// @notice Called before a BunniToken transfer operation.
/// @param sender The address that initiated the transfer.
/// @param key The Uniswap v4 pool's key.
/// @param bunniToken The BunniToken being transferred.
/// @param from The address that is sending the tokens.
/// @param to The address that is receiving the tokens.
/// @param amount The amount of tokens being transferred.
/// @return selector IHooklet.beforeTransfer.selector if the call was successful.
function beforeTransfer(
address sender,
PoolKey calldata key,
IBunniToken bunniToken,
address from,
address to,
uint256 amount
) external returns (bytes4 selector);
/// @notice Called after a BunniToken transfer operation.
/// @param sender The address that initiated the transfer.
/// @param key The Uniswap v4 pool's key.
/// @param bunniToken The BunniToken being transferred.
/// @param from The address that is sending the tokens.
/// @param to The address that is receiving the tokens.
/// @param amount The amount of tokens being transferred.
/// @return selector IHooklet.afterTransfer.selector if the call was successful.
function afterTransfer(
address sender,
PoolKey calldata key,
IBunniToken bunniToken,
address from,
address to,
uint256 amount
) external returns (bytes4 selector);
/// @notice Called before a pool is initialized.
/// @param sender The address of the account that initiated the initialization.
/// @param params The initialization's input parameters.
/// @return selector IHooklet.beforeInitialize.selector if the call was successful.
function beforeInitialize(address sender, IBunniHub.DeployBunniTokenParams calldata params)
external
returns (bytes4 selector);
/// @notice Called after a pool is initialized.
/// @param sender The address of the account that initiated the initialization.
/// @param params The initialization's input parameters.
/// @param returnData The initialization operation's return data.
/// @return selector IHooklet.afterInitialize.selector if the call was successful.
function afterInitialize(
address sender,
IBunniHub.DeployBunniTokenParams calldata params,
InitializeReturnData calldata returnData
) external returns (bytes4 selector);
/// @notice Called before a deposit operation.
/// @param sender The address of the account that initiated the deposit.
/// @param params The deposit's input parameters.
/// @return selector IHooklet.beforeDeposit.selector if the call was successful.
function beforeDeposit(address sender, IBunniHub.DepositParams calldata params)
external
returns (bytes4 selector);
/// @notice View version of beforeDeposit(), used when computing deposit quotes like in BunniQuoter.
/// Should always have the same behavior as beforeDeposit().
/// @param sender The address of the account that initiated the deposit.
/// @param params The deposit's input parameters.
/// @return selector IHooklet.beforeDeposit.selector if the call was successful.
function beforeDepositView(address sender, IBunniHub.DepositParams calldata params)
external
view
returns (bytes4 selector);
/// @notice Called after a deposit operation.
/// @param sender The address of the account that initiated the deposit.
/// @param params The deposit's input parameters.
/// @param returnData The deposit operation's return data.
/// @return selector IHooklet.afterDeposit.selector if the call was successful.
function afterDeposit(
address sender,
IBunniHub.DepositParams calldata params,
DepositReturnData calldata returnData
) external returns (bytes4 selector);
/// @notice View version of afterDeposit(), used when computing deposit quotes like in BunniQuoter.
/// Should always have the same behavior as afterDeposit().
/// @param sender The address of the account that initiated the deposit.
/// @param params The deposit's input parameters.
/// @param returnData The deposit operation's return data.
/// @return selector IHooklet.afterDeposit.selector if the call was successful.
function afterDepositView(
address sender,
IBunniHub.DepositParams calldata params,
DepositReturnData calldata returnData
) external view returns (bytes4 selector);
/// @notice Called before a withdraw operation.
/// @param sender The address of the account that initiated the withdraw.
/// @param params The withdraw's input parameters.
/// @return selector IHooklet.beforeWithdraw.selector if the call was successful.
function beforeWithdraw(address sender, IBunniHub.WithdrawParams calldata params)
external
returns (bytes4 selector);
/// @notice View version of beforeWithdraw(), used when computing withdraw quotes like in BunniQuoter.
/// Should always have the same behavior as beforeWithdraw().
/// @param sender The address of the account that initiated the withdraw.
/// @param params The withdraw's input parameters.
/// @return selector IHooklet.beforeWithdraw.selector if the call was successful.
function beforeWithdrawView(address sender, IBunniHub.WithdrawParams calldata params)
external
view
returns (bytes4 selector);
/// @notice Called after a withdraw operation.
/// @param sender The address of the account that initiated the withdraw.
/// @param params The withdraw's input parameters.
/// @param returnData The withdraw operation's return data.
/// @return selector IHooklet.afterWithdraw.selector if the call was successful.
function afterWithdraw(
address sender,
IBunniHub.WithdrawParams calldata params,
WithdrawReturnData calldata returnData
) external returns (bytes4 selector);
/// @notice View version of afterWithdraw(), used when computing withdraw quotes like in BunniQuoter.
/// Should always have the same behavior as afterWithdraw().
/// @param sender The address of the account that initiated the withdraw.
/// @param params The withdraw's input parameters.
/// @param returnData The withdraw operation's return data.
/// @return selector IHooklet.afterWithdraw.selector if the call was successful.
function afterWithdrawView(
address sender,
IBunniHub.WithdrawParams calldata params,
WithdrawReturnData calldata returnData
) external view returns (bytes4 selector);
/// @notice Called before a swap operation. Allows the hooklet to override the swap fee & price
/// of the pool before the swap is executed.
/// @param sender The address of the account that initiated the swap.
/// @param key The Uniswap v4 pool's key.
/// @param params The swap's input parameters.
/// @return selector IHooklet.beforeSwap.selector if the call was successful.
/// @return feeOverriden If true, the swap fee is overridden. If the pool has an am-AMM manager
/// then the fee override is ignored.
/// @return fee The swap fee to use for the swap. 6 decimals.
/// @return priceOverridden If true, the pool's spot price is overridden.
/// @return sqrtPriceX96 The spot price to use for the swap. Q96 value.
function beforeSwap(address sender, PoolKey calldata key, IPoolManager.SwapParams calldata params)
external
returns (bytes4 selector, bool feeOverriden, uint24 fee, bool priceOverridden, uint160 sqrtPriceX96);
/// @notice View version of beforeSwap(), used when computing swap quotes like in BunniQuoter.
/// Should always return the same values as beforeSwap().
/// @param sender The address of the account that initiated the swap.
/// @param key The Uniswap v4 pool's key.
/// @param params The swap's input parameters.
/// @return selector IHooklet.beforeSwap.selector if the call was successful.
/// @return feeOverriden If true, the swap fee is overridden. If the pool has an am-AMM manager
/// then the fee override is ignored.
/// @return fee The swap fee to use for the swap. 6 decimals.
/// @return priceOverridden If true, the pool's spot price is overridden.
/// @return sqrtPriceX96 The spot price to use for the swap. Q96 value.
function beforeSwapView(address sender, PoolKey calldata key, IPoolManager.SwapParams calldata params)
external
view
returns (bytes4 selector, bool feeOverriden, uint24 fee, bool priceOverridden, uint160 sqrtPriceX96);
/// @notice Called after a swap operation.
/// @param sender The address of the account that initiated the swap.
/// @param key The Uniswap v4 pool's key.
/// @param params The swap's input parameters.
/// @param returnData The swap operation's return data.
function afterSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
SwapReturnData calldata returnData
) external returns (bytes4 selector);
/// @notice View version of afterSwap(), used when computing swap quotes like in BunniQuoter.
/// Should always have the same behavior as afterSwap().
/// @param sender The address of the account that initiated the swap.
/// @param key The Uniswap v4 pool's key.
/// @param params The swap's input parameters.
/// @param returnData The swap operation's return data.
/// @return selector IHooklet.afterSwap.selector if the call was successful.
function afterSwapView(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
SwapReturnData calldata returnData
) external view returns (bytes4 selector);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IPoolManager} from "./IPoolManager.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,
IPoolManager.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,
IPoolManager.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,
IPoolManager.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,
IPoolManager.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,
IPoolManager.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,
IPoolManager.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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
pragma abicoder v2;
import {PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
/// @title ILiquidityDensityFunction
/// @author zefram.eth
/// @notice Interface for liquidity density functions (LDFs) that dictate how liquidity is distributed over a pool's rounded ticks (each with `tickSpacing` ticks).
/// Each rounded tick is identified by its leftmost tick, which is a multiple of `tickSpacing`. The liquidity density of all rounded ticks should add up to 1, similar to probability density functions (PDFs).
/// Also contains functions for efficiently computing the cumulative amount of tokens in a consecutive range of rounded ticks, as well as their inverse functions. These are essential for computing swaps.
/// Enables arbitrary liquidity shapes, shifting liquidity across ticks, and switching from one liquidity shape to another.
interface ILiquidityDensityFunction {
/// @notice Queries the liquidity density function for the given pool and rounded tick.
/// Returns the density of the rounded tick, cumulative token densities at adjacent ticks, and state relevant info.
/// @param key The key of the Uniswap v4 pool
/// @param roundedTick The rounded tick to query
/// @param twapTick The TWAP tick. Is 0 if `twapSecondsAgo` is 0. It's up to `isValidParams` to ensure `twapSecondsAgo != 0` if the LDF uses the TWAP.
/// @param spotPriceTick The spot price tick.
/// @param ldfParams The parameters for the liquidity density function
/// @param ldfState The current state of the liquidity density function
/// @return liquidityDensityX96 The density of the rounded tick, scaled by Q96
/// @return cumulativeAmount0DensityX96 The cumulative token0 density in rounded ticks [roundedTick + tickSpacing, maxUsableTick], scaled by Q96
/// @return cumulativeAmount1DensityX96 The cumulative token1 density in rounded ticks [minUsableTick, roundedTick - tickSpacing], scaled by Q96
/// @return newLdfState The new state of the liquidity density function
/// @return shouldSurge Whether the pool should surge. Usually corresponds to whether the LDF has shifted / changed shape.
function query(
PoolKey calldata key,
int24 roundedTick,
int24 twapTick,
int24 spotPriceTick,
bytes32 ldfParams,
bytes32 ldfState
)
external
view
returns (
uint256 liquidityDensityX96,
uint256 cumulativeAmount0DensityX96,
uint256 cumulativeAmount1DensityX96,
bytes32 newLdfState,
bool shouldSurge
);
/// @notice Aggregates LDF queries used during a swap.
/// @dev A Bunni swap uses the inverseCumulativeAmount function to compute the rounded tick for which the cumulativeAmount is the closest to `inverseCumulativeAmountInput`
/// and <= `inverseCumulativeAmountInput`. This rounded tick is the starting point for swapping the remaining tokens, which is done via Uniswap math (not done in this function though).
/// @param key The key of the Uniswap v4 pool
/// @param inverseCumulativeAmountInput The input to the inverseCumulativeAmount function
/// @param totalLiquidity The total liquidity in the pool
/// @param zeroForOne Whether the input token is token0
/// @param exactIn Whether it's an exact input swap or an exact output swap
/// @param twapTick The TWAP tick. Is 0 if `twapSecondsAgo` is 0. It's up to `isValidParams` to ensure `twapSecondsAgo != 0` if the LDF uses the TWAP.
/// @param spotPriceTick The spot price tick.
/// @param ldfParams The parameters for the liquidity density function
/// @param ldfState The current state of the liquidity density function
/// @return success Whether the swap computation was successful
/// @return roundedTick The rounded tick to start the remainder swap from
/// @return cumulativeAmount0_ The cumulative amount of token0 to the right of the starting tick of the Uniswap swap
/// @return cumulativeAmount1_ The cumulative amount of token1 to the left of the starting tick of the Uniswap swap
/// @return swapLiquidity The liquidity used for the remainder swap
function computeSwap(
PoolKey calldata key,
uint256 inverseCumulativeAmountInput,
uint256 totalLiquidity,
bool zeroForOne,
bool exactIn,
int24 twapTick,
int24 spotPriceTick,
bytes32 ldfParams,
bytes32 ldfState
)
external
view
returns (
bool success,
int24 roundedTick,
uint256 cumulativeAmount0_,
uint256 cumulativeAmount1_,
uint256 swapLiquidity
);
/// @notice Computes the cumulative amount of token0 in the rounded ticks [roundedTick, maxUsableTick].
/// @param key The key of the Uniswap v4 pool
/// @param roundedTick The rounded tick to query
/// @param totalLiquidity The total liquidity in the pool
/// @param twapTick The TWAP tick. Is 0 if `twapSecondsAgo` is 0. It's up to `isValidParams` to ensure `twapSecondsAgo != 0` if the LDF uses the TWAP.
/// @param spotPriceTick The spot price tick.
/// @param ldfParams The parameters for the liquidity density function
/// @param ldfState The current state of the liquidity density function
/// @return The cumulative amount of token0 in the rounded ticks [roundedTick, maxUsableTick]
function cumulativeAmount0(
PoolKey calldata key,
int24 roundedTick,
uint256 totalLiquidity,
int24 twapTick,
int24 spotPriceTick,
bytes32 ldfParams,
bytes32 ldfState
) external view returns (uint256);
/// @notice Computes the cumulative amount of token1 in the rounded ticks [minUsableTick, roundedTick].
/// @param key The key of the Uniswap v4 pool
/// @param roundedTick The rounded tick to query
/// @param totalLiquidity The total liquidity in the pool
/// @param twapTick The TWAP tick. Is 0 if `twapSecondsAgo` is 0. It's up to `isValidParams` to ensure `twapSecondsAgo != 0` if the LDF uses the TWAP.
/// @param spotPriceTick The spot price tick.
/// @param ldfParams The parameters for the liquidity density function
/// @param ldfState The current state of the liquidity density function
/// @return The cumulative amount of token1 in the rounded ticks [minUsableTick, roundedTick]
function cumulativeAmount1(
PoolKey calldata key,
int24 roundedTick,
uint256 totalLiquidity,
int24 twapTick,
int24 spotPriceTick,
bytes32 ldfParams,
bytes32 ldfState
) external view returns (uint256);
/// @notice Checks if the given LDF parameters are valid.
/// @param key The key of the Uniswap v4 pool
/// @param twapSecondsAgo The time window for the TWAP
/// @param ldfParams The parameters for the liquidity density function
/// @return Whether the parameters are valid
function isValidParams(PoolKey calldata key, uint24 twapSecondsAgo, bytes32 ldfParams)
external
view
returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {IFloodPlain} from "./IFloodPlain.sol";
interface IOnChainOrders {
event OrderEtched(bytes32 indexed orderHash, IFloodPlain.SignedOrder signedOrder);
/**
* @notice Record an order on-chain for ease of use by other contracts.
*
* @param signedOrder The order and its signature to record.
*/
function etchOrder(IFloodPlain.SignedOrder calldata signedOrder) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IOwnable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The caller is not authorized to call the function.
error Unauthorized();
/// @dev The `newOwner` cannot be the zero address.
error NewOwnerIsZeroAddress();
/// @dev The `pendingOwner` does not have a valid handover request.
error NoHandoverRequest();
/// @dev Cannot double-initialize.
error AlreadyInitialized();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership is transferred from `oldOwner` to `newOwner`.
/// This event is intentionally kept the same as OpenZeppelin's Ownable to be
/// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
/// despite it not being as lightweight as a single argument event.
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
/// @dev An ownership handover to `pendingOwner` has been requested.
event OwnershipHandoverRequested(address indexed pendingOwner);
/// @dev The ownership handover to `pendingOwner` has been canceled.
event OwnershipHandoverCanceled(address indexed pendingOwner);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* external UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to transfer the ownership to `newOwner`.
function transferOwnership(address newOwner) external payable;
/// @dev Allows the owner to renounce their ownership.
function renounceOwnership() external payable;
/// @dev Request a two-step ownership handover to the caller.
/// The request will automatically expire in 48 hours (172800 seconds) by default.
function requestOwnershipHandover() external payable;
/// @dev Cancels the two-step ownership handover to the caller, if any.
function cancelOwnershipHandover() external payable;
/// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
/// Reverts if there is no existing ownership handover requested by `pendingOwner`.
function completeOwnershipHandover(address pendingOwner) external payable;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* external READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of the contract.
function owner() external view returns (address result);
/// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
function ownershipHandoverExpiresAt(address pendingOwner) external view returns (uint256 result);
}
// 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";
/// @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);
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 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);
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;
}
/// @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;
}
// 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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IEIP712} from "./IEIP712.sol";
/// @title SignatureTransfer
/// @notice Handles ERC20 token transfers through signature based actions
/// @dev Requires user's token approval on the Permit2 contract
interface ISignatureTransfer is IEIP712 {
/// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount
/// @param maxAmount The maximum amount a spender can request to transfer
error InvalidAmount(uint256 maxAmount);
/// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred
/// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred
error LengthMismatch();
/// @notice Emits an event when the owner successfully invalidates an unordered nonce.
event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask);
/// @notice The token and amount details for a transfer signed in the permit transfer signature
struct TokenPermissions {
// ERC20 token address
address token;
// the maximum amount that can be spent
uint256 amount;
}
/// @notice The signed permit message for a single token transfer
struct PermitTransferFrom {
TokenPermissions permitted;
// a unique value for every token owner's signature to prevent signature replays
uint256 nonce;
// deadline on the permit signature
uint256 deadline;
}
/// @notice Specifies the recipient address and amount for batched transfers.
/// @dev Recipients and amounts correspond to the index of the signed token permissions array.
/// @dev Reverts if the requested amount is greater than the permitted signed amount.
struct SignatureTransferDetails {
// recipient address
address to;
// spender requested amount
uint256 requestedAmount;
}
/// @notice Used to reconstruct the signed permit message for multiple token transfers
/// @dev Do not need to pass in spender address as it is required that it is msg.sender
/// @dev Note that a user still signs over a spender address
struct PermitBatchTransferFrom {
// the tokens and corresponding amounts permitted for a transfer
TokenPermissions[] permitted;
// a unique value for every token owner's signature to prevent signature replays
uint256 nonce;
// deadline on the permit signature
uint256 deadline;
}
/// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection
/// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order
/// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce
/// @dev It returns a uint256 bitmap
/// @dev The index, or wordPosition is capped at type(uint248).max
function nonceBitmap(address, uint256) external view returns (uint256);
/// @notice Transfers a token using a signed permit message
/// @dev Reverts if the requested amount is greater than the permitted signed amount
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails The spender's requested transfer details for the permitted token
/// @param signature The signature to verify
function permitTransferFrom(
PermitTransferFrom memory permit,
SignatureTransferDetails calldata transferDetails,
address owner,
bytes calldata signature
) external;
/// @notice Transfers a token using a signed permit message
/// @notice Includes extra data provided by the caller to verify signature over
/// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
/// @dev Reverts if the requested amount is greater than the permitted signed amount
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails The spender's requested transfer details for the permitted token
/// @param witness Extra data to include when checking the user signature
/// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
/// @param signature The signature to verify
function permitWitnessTransferFrom(
PermitTransferFrom memory permit,
SignatureTransferDetails calldata transferDetails,
address owner,
bytes32 witness,
string calldata witnessTypeString,
bytes calldata signature
) external;
/// @notice Transfers multiple tokens using a signed permit message
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails Specifies the recipient and requested amount for the token transfer
/// @param signature The signature to verify
function permitTransferFrom(
PermitBatchTransferFrom memory permit,
SignatureTransferDetails[] calldata transferDetails,
address owner,
bytes calldata signature
) external;
/// @notice Transfers multiple tokens using a signed permit message
/// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
/// @notice Includes extra data provided by the caller to verify signature over
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails Specifies the recipient and requested amount for the token transfer
/// @param witness Extra data to include when checking the user signature
/// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
/// @param signature The signature to verify
function permitWitnessTransferFrom(
PermitBatchTransferFrom memory permit,
SignatureTransferDetails[] calldata transferDetails,
address owner,
bytes32 witness,
string calldata witnessTypeString,
bytes calldata signature
) external;
/// @notice Invalidates the bits specified in mask for the bitmap at the word position
/// @dev The wordPos is maxed at type(uint248).max
/// @param wordPos A number to index the nonceBitmap at
/// @param mask A bitmap masked against msg.sender's current bitmap at the word position
function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
/// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
/// @param data The data that was passed to the call to unlock
/// @return Any data that you want to be returned from the unlock call
function unlockCallback(bytes calldata data) external returns (bytes memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {IFloodPlain} from "./IFloodPlain.sol";
interface IZone {
struct FeeInfo {
address recipient;
uint64 bps;
}
/**
* @notice Check if a fulfiller belongs to the zone.
*
* @dev Fulfiller must still ensure that
* - msg.sender is a the BOOK.
* - Book caller is authorized.
*
* @param order Order being fulfilled.
* @param fulfiller The address that will fulfill the order by supplying consideration items.
*
* @return True if fulfiller is enabled, false if fulfiller is not enabled.
*/
function validate(IFloodPlain.Order calldata order, address fulfiller) external view returns (bool);
/**
* @notice Get the fee information.
*
* @dev It is up to Fulfiller to respect the fees set in a zone.
*
* @return The address of the fee recipient who should receive the fees.
* The fee cut in BPS that should be taken from the output tokens.
*/
function fee(IFloodPlain.Order calldata order, address fulfiller) external view returns (FeeInfo memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import {subReLU} from "../lib/Math.sol";
type IdleBalance is bytes32;
using {equals as ==, notEqual as !=} for IdleBalance global;
using IdleBalanceLibrary for IdleBalance global;
function equals(IdleBalance bal, IdleBalance other) pure returns (bool) {
return IdleBalance.unwrap(bal) == IdleBalance.unwrap(other);
}
function notEqual(IdleBalance bal, IdleBalance other) pure returns (bool) {
return IdleBalance.unwrap(bal) != IdleBalance.unwrap(other);
}
library IdleBalanceLibrary {
using FixedPointMathLib for uint256;
using IdleBalanceLibrary for uint256;
uint256 private constant _BALANCE_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/// @dev Set isToken0 to true in ZERO to keep storage slots dirty
IdleBalance internal constant ZERO =
IdleBalance.wrap(bytes32(0x8000000000000000000000000000000000000000000000000000000000000000));
error IdleBalanceLibrary__BalanceOverflow();
function fromIdleBalance(IdleBalance idleBalance) internal pure returns (uint256 rawBalance, bool isToken0) {
uint256 mask = _BALANCE_MASK;
assembly ("memory-safe") {
isToken0 := shr(255, idleBalance)
rawBalance := and(mask, idleBalance)
}
}
function toIdleBalance(uint256 rawBalance, bool isToken0) internal pure returns (IdleBalance) {
// revert if balance overflows 255 bits
if (rawBalance > _BALANCE_MASK) revert IdleBalanceLibrary__BalanceOverflow();
// pack isToken0 and balance into a single uint256
bytes32 packed;
assembly ("memory-safe") {
packed := or(shl(255, isToken0), rawBalance)
}
return IdleBalance.wrap(packed);
}
function computeIdleBalance(uint256 activeBalance0, uint256 activeBalance1, uint256 balance0, uint256 balance1)
internal
pure
returns (IdleBalance)
{
(uint256 extraBalance0, uint256 extraBalance1) =
(subReLU(balance0, activeBalance0), subReLU(balance1, activeBalance1));
(uint256 extraBalanceProportion0, uint256 extraBalanceProportion1) =
(balance0 == 0 ? 0 : extraBalance0.divWad(balance0), balance1 == 0 ? 0 : extraBalance1.divWad(balance1));
bool isToken0 = extraBalanceProportion0 >= extraBalanceProportion1;
return (isToken0 ? extraBalance0 : extraBalance1).toIdleBalance(isToken0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
enum LDFType {
STATIC, // LDF does not change ever
DYNAMIC_NOT_STATEFUL, // LDF can change, does not use ldfState
DYNAMIC_AND_STATEFUL // LDF can change, uses ldfState
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
using LPFeeLibrary for uint24;
using CustomRevert for bytes4;
/// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
error LPFeeTooLarge(uint24 fee);
/// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;
/// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
// only dynamic-fee pools can return a fee via the beforeSwap hook
uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;
/// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;
/// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
uint24 public constant MAX_LP_FEE = 1000000;
/// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
/// @param self The fee to check
/// @return bool True of the fee is dynamic
function isDynamicFee(uint24 self) internal pure returns (bool) {
return self == DYNAMIC_FEE_FLAG;
}
/// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
/// @param self The fee to check
/// @return bool True of the fee is valid
function isValid(uint24 self) internal pure returns (bool) {
return self <= MAX_LP_FEE;
}
/// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
/// @param self The fee to validate
function validate(uint24 self) internal pure {
if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
}
/// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
/// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
/// @param self The fee to get the initial LP from
/// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
function getInitialLPFee(uint24 self) internal pure returns (uint24) {
// the initial fee for a dynamic fee pool is 0
if (self.isDynamicFee()) return 0;
self.validate();
return self;
}
/// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
/// @param self The fee to check
/// @return bool True of the fee has the override flag set
function isOverride(uint24 self) internal pure returns (bool) {
return self & OVERRIDE_FEE_FLAG != 0;
}
/// @notice returns a fee with the override flag removed
/// @param self The fee to remove the override flag from
/// @return fee The fee without the override flag set
function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
return self & REMOVE_OVERRIDE_MASK;
}
/// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
/// @param self The fee to remove the override flag from, and then validate
/// @return fee The fee without the override flag set (if valid)
function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
fee = self.removeOverrideFlag();
fee.validate();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/**
* @title LibMulticaller
* @author vectorized.eth
* @notice Library to read the `msg.sender` of the multicaller with sender contract.
*
* @dev Note:
* The functions in this library do NOT guard against reentrancy.
* A single transaction can recurse through different Multicallers
* (e.g. `MulticallerWithSender -> contract -> MulticallerWithSigner -> contract`).
*
* Think of these functions like `msg.sender`.
*
* If your contract `C` can handle reentrancy safely with plain old `msg.sender`
* for any `A -> C -> B -> C`, you should be fine substituting `msg.sender` with these functions.
*/
library LibMulticaller {
/**
* @dev The address of the multicaller contract.
*/
address internal constant MULTICALLER = 0x0000000000002Bdbf1Bf3279983603Ec279CC6dF;
/**
* @dev The address of the multicaller with sender contract.
*/
address internal constant MULTICALLER_WITH_SENDER = 0x00000000002Fd5Aeb385D324B580FCa7c83823A0;
/**
* @dev The address of the multicaller with signer contract.
*/
address internal constant MULTICALLER_WITH_SIGNER = 0x000000000000D9ECebf3C23529de49815Dac1c4c;
/**
* @dev Returns the caller of `aggregateWithSender` on `MULTICALLER_WITH_SENDER`.
*/
function multicallerSender() internal view returns (address result) {
return at(MULTICALLER_WITH_SENDER);
}
/**
* @dev Returns the signer of `aggregateWithSigner` on `MULTICALLER_WITH_SIGNER`.
*/
function multicallerSigner() internal view returns (address result) {
return at(MULTICALLER_WITH_SIGNER);
}
/**
* @dev Returns the caller of `aggregateWithSender` on `MULTICALLER_WITH_SENDER`,
* if the current context's `msg.sender` is `MULTICALLER_WITH_SENDER`.
* Otherwise, returns `msg.sender`.
*/
function sender() internal view returns (address result) {
return resolve(MULTICALLER_WITH_SENDER);
}
/**
* @dev Returns the caller of `aggregateWithSigner` on `MULTICALLER_WITH_SIGNER`,
* if the current context's `msg.sender` is `MULTICALLER_WITH_SIGNER`.
* Otherwise, returns `msg.sender`.
*/
function signer() internal view returns (address) {
return resolve(MULTICALLER_WITH_SIGNER);
}
/**
* @dev Returns the caller or signer at `a`.
* @param a The multicaller with sender / signer.
*/
function at(address a) internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x00)
if iszero(staticcall(gas(), a, codesize(), 0x00, 0x00, 0x20)) {
revert(codesize(), codesize()) // For better gas estimation.
}
result := mload(0x00)
}
}
/**
* @dev Returns the caller or signer at `a`, if the caller is `a`.
* @param a The multicaller with sender / signer.
*/
function resolve(address a) internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, caller())
if eq(caller(), a) {
if iszero(staticcall(gas(), a, codesize(), 0x00, 0x00, 0x20)) {
revert(codesize(), codesize()) // For better gas estimation.
}
}
result := mload(0x00)
}
}
/**
* @dev Returns the caller of `aggregateWithSender` on `MULTICALLER_WITH_SENDER`,
* if the current context's `msg.sender` is `MULTICALLER_WITH_SENDER`.
* Returns the signer of `aggregateWithSigner` on `MULTICALLER_WITH_SIGNER`,
* if the current context's `msg.sender` is `MULTICALLER_WITH_SIGNER`.
* Otherwise, returns `msg.sender`.
*/
function senderOrSigner() internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, caller())
let withSender := MULTICALLER_WITH_SENDER
if eq(caller(), withSender) {
if iszero(staticcall(gas(), withSender, codesize(), 0x00, 0x00, 0x20)) {
revert(codesize(), codesize()) // For better gas estimation.
}
}
let withSigner := MULTICALLER_WITH_SIGNER
if eq(caller(), withSigner) {
if iszero(staticcall(gas(), withSigner, codesize(), 0x00, 0x00, 0x20)) {
revert(codesize(), codesize()) // For better gas estimation.
}
}
result := mload(0x00)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "@uniswap/v4-core/src/libraries/SqrtPriceMath.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundingUp
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = SqrtPriceMath.getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundingUp);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = SqrtPriceMath.getAmount0Delta(sqrtRatioX96, sqrtRatioBX96, liquidity, roundingUp);
amount1 = SqrtPriceMath.getAmount1Delta(sqrtRatioAX96, sqrtRatioX96, liquidity, roundingUp);
} else {
amount1 = SqrtPriceMath.getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundingUp);
}
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0)
internal
pure
returns (uint128 liquidity)
{
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1)
internal
pure
returns (uint128 liquidity)
{
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import "../base/Constants.sol";
using FixedPointMathLib for int256;
using FixedPointMathLib for uint256;
/// @dev modified from solady
function dist(uint256 x, uint256 y) pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(mul(xor(sub(y, x), sub(x, y)), gt(x, y)), sub(y, x))
}
}
/// @dev modified from solady
function absDiff(uint256 x, uint256 y) pure returns (bool positive, uint256 diff) {
/// @solidity memory-safe-assembly
assembly {
positive := gt(x, y)
diff := xor(mul(xor(sub(y, x), sub(x, y)), gt(x, y)), sub(y, x))
}
}
function roundTick(int24 currentTick, int24 tickSpacing) pure returns (int24 roundedTick, int24 nextRoundedTick) {
int24 compressed = currentTick / tickSpacing;
if (currentTick < 0 && currentTick % tickSpacing != 0) compressed--; // round towards negative infinity
roundedTick = compressed * tickSpacing;
nextRoundedTick = roundedTick + tickSpacing;
}
function roundTickSingle(int24 currentTick, int24 tickSpacing) pure returns (int24 roundedTick) {
int24 compressed = currentTick / tickSpacing;
if (currentTick < 0 && currentTick % tickSpacing != 0) compressed--; // round towards negative infinity
roundedTick = compressed * tickSpacing;
}
function boundTick(int24 tick, int24 tickSpacing) pure returns (int24 boundedTick) {
(int24 minTick, int24 maxTick) = (TickMath.minUsableTick(tickSpacing), TickMath.maxUsableTick(tickSpacing));
return int24(FixedPointMathLib.clamp(tick, minTick, maxTick));
}
function weightedSum(uint256 value0, uint256 weight0, uint256 value1, uint256 weight1) pure returns (uint256) {
return (value0 * weight0 + value1 * weight1) / (weight0 + weight1);
}
/// @dev Converts xWad, the decimal index of a rounded tick scaled by WAD, to the corresponding rounded tick.
function xWadToRoundedTick(int256 xWad, int24 mu, int24 tickSpacing, bool roundUp) pure returns (int24) {
int24 x = SafeCastLib.toInt24(xWad / int256(WAD));
if (roundUp) {
if (xWad > 0 && xWad % int256(WAD) != 0) x++; // round towards positive infinity
} else {
if (xWad < 0 && xWad % int256(WAD) != 0) x--; // round towards negative infinity
}
return x * tickSpacing + mu;
}
function percentDelta(uint256 a, uint256 b) pure returns (uint256) {
uint256 absDelta = dist(a, b);
return FixedPointMathLib.divWad(absDelta, b);
}
/// @dev Returns ReLU(x - y) = max(x - y, 0)
function subReLU(uint256 x, uint256 y) pure returns (uint256) {
unchecked {
return x > y ? x - y : 0;
}
}
function divQ96RoundUp(uint256 value) pure returns (uint256) {
return (value + ((1 << 96) - 1)) >> 96;
}
function roundUpFullMulDivResult(uint256 x, uint256 y, uint256 d, uint256 resultRoundedDown)
pure
returns (uint256 result)
{
result = resultRoundedDown;
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
result := add(resultRoundedDown, 1)
if iszero(result) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {MAX_CARDINALITY} from "../base/Constants.sol";
/// @title Oracle
/// @notice Provides price data useful for a wide variety of system designs. Based on Uniswap's
/// truncated oracle.
/// @dev Instances of stored oracle data, "observations", are collected in the oracle array
/// Every pool is initialized with an oracle array length of 1. Anyone can pay the SSTOREs to increase the
/// maximum length of the oracle array. New slots will be added when the array is fully populated.
/// Observations are overwritten when the full length of the oracle array is populated.
/// The most recent observation is available, independent of the length of the oracle array, by passing 0 to observe()
/// A minimum observation interval is enforced to make the choice of cardinality more meaningful. This is done by
/// only recording an observation if the time elapsed since the last observation is >= minInterval, and recording the data
/// into a separate "intermediate" observation slot otherwise to ensure tickCumulative is accurate.
library Oracle {
/// @notice Thrown when trying to interact with an Oracle of a non-initialized pool
error OracleCardinalityCannotBeZero();
/// @notice Thrown when trying to observe a price that is older than the oldest recorded price
/// @param oldestTimestamp Timestamp of the oldest remaining observation
/// @param targetTimestamp Invalid timestamp targeted to be observed
error TargetPredatesOldestObservation(uint32 oldestTimestamp, uint32 targetTimestamp);
/// @notice This is the max amount of ticks in either direction that the pool is allowed to move at one time
int24 constant MAX_ABS_TICK_MOVE = 9116;
struct Observation {
// the block timestamp of the observation
uint32 blockTimestamp;
// the previous printed tick to calculate the change from time to time
int24 prevTick;
// the tick accumulator, i.e. tick * time elapsed since the pool was first initialized
int56 tickCumulative;
// whether or not the observation is initialized
bool initialized;
}
/// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick values
/// @dev blockTimestamp _must_ be chronologically equal to or greater than last.blockTimestamp, safe for 0 or 1 overflows
/// @param last The specified observation to be transformed
/// @param blockTimestamp The timestamp of the new observation
/// @param tick The active tick at the time of the new observation
/// @return Observation The newly populated observation
function transform(Observation memory last, uint32 blockTimestamp, int24 tick)
private
pure
returns (Observation memory)
{
unchecked {
uint32 delta = blockTimestamp - last.blockTimestamp;
// if the current tick moves more than the max abs tick movement
// then we truncate it down
if ((tick - last.prevTick) > MAX_ABS_TICK_MOVE) {
tick = last.prevTick + MAX_ABS_TICK_MOVE;
} else if ((tick - last.prevTick) < -MAX_ABS_TICK_MOVE) {
tick = last.prevTick - MAX_ABS_TICK_MOVE;
}
return Observation({
blockTimestamp: blockTimestamp,
prevTick: tick,
tickCumulative: last.tickCumulative + int56(tick) * int56(uint56(delta)),
initialized: true
});
}
}
/// @notice Initialize the oracle array by writing the first slot. Called once for the lifecycle of the observations array
/// @param self The stored oracle array
/// @param time The time of the oracle initialization, via block.timestamp truncated to uint32
/// @return intermediate The intermediate observation in between min intervals
/// @return cardinality The number of populated elements in the oracle array
/// @return cardinalityNext The new length of the oracle array, independent of population
function initialize(Observation[MAX_CARDINALITY] storage self, uint32 time, int24 tick)
internal
returns (Observation memory intermediate, uint32 cardinality, uint32 cardinalityNext)
{
intermediate = Observation({blockTimestamp: time, prevTick: tick, tickCumulative: 0, initialized: true});
self[0] = intermediate;
return (intermediate, 1, 1);
}
/// @notice Writes an oracle observation to the array
/// @dev Writable at most once per block. Index represents the most recently written element. cardinality and index must be tracked externally.
/// If the index is at the end of the allowable array length (according to cardinality), and the next cardinality
/// is greater than the current one, cardinality may be increased. This restriction is created to preserve ordering.
/// @param self The stored oracle array
/// @param intermediate The intermediate observation in between min intervals. Always the most recent observation.
/// @param index The index of the observation that was most recently written to the observations array
/// @param blockTimestamp The timestamp of the new observation
/// @param tick The active tick at the time of the new observation
/// @param cardinality The number of populated elements in the oracle array
/// @param cardinalityNext The new length of the oracle array, independent of population
/// @param minInterval The minimum interval between observations.
/// @return intermediateUpdated The updated intermediate observation
/// @return indexUpdated The new index of the most recently written element in the oracle array
/// @return cardinalityUpdated The new cardinality of the oracle array
function write(
Observation[MAX_CARDINALITY] storage self,
Observation memory intermediate,
uint32 index,
uint32 blockTimestamp,
int24 tick,
uint32 cardinality,
uint32 cardinalityNext,
uint32 minInterval
) internal returns (Observation memory intermediateUpdated, uint32 indexUpdated, uint32 cardinalityUpdated) {
unchecked {
// early return if we've already written an observation this block
if (intermediate.blockTimestamp == blockTimestamp) {
return (intermediate, index, cardinality);
}
// update the intermediate observation using the most recent observation
// which is always the current intermediate observation
intermediateUpdated = transform(intermediate, blockTimestamp, tick);
// if the time since the last recorded observation is less than the minimum interval, we store the observation in the intermediate observation
if (blockTimestamp - self[index].blockTimestamp < minInterval) {
return (intermediateUpdated, index, cardinality);
}
// if the conditions are right, we can bump the cardinality
if (cardinalityNext > cardinality && index == (cardinality - 1)) {
cardinalityUpdated = cardinalityNext;
} else {
cardinalityUpdated = cardinality;
}
indexUpdated = (index + 1) % cardinalityUpdated;
self[indexUpdated] = intermediateUpdated;
}
}
/// @notice Prepares the oracle array to store up to `next` observations
/// @param self The stored oracle array
/// @param current The current next cardinality of the oracle array
/// @param next The proposed next cardinality which will be populated in the oracle array
/// @return next The next cardinality which will be populated in the oracle array
function grow(Observation[MAX_CARDINALITY] storage self, uint32 current, uint32 next) internal returns (uint32) {
unchecked {
if (current == 0) revert OracleCardinalityCannotBeZero();
// no-op if the passed next value isn't greater than the current next value
if (next <= current) return current;
// store in each slot to prevent fresh SSTOREs in swaps
// this data will not be used because the initialized boolean is still false
for (uint32 i = current; i < next; i++) {
self[i].blockTimestamp = 1;
}
return next;
}
}
/// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied.
/// The result may be the same observation, or adjacent observations.
/// @dev The answer must be contained in the array, used when the target is located within the stored observation
/// boundaries: older than the most recent observation and younger, or the same age as, the oldest observation
/// @param self The stored oracle array
/// @param time The current block.timestamp
/// @param target The timestamp at which the reserved observation should be for
/// @param index The index of the observation that was most recently written to the observations array
/// @param cardinality The number of populated elements in the oracle array
/// @return beforeOrAt The observation recorded before, or at, the target
/// @return atOrAfter The observation recorded at, or after, the target
function binarySearch(
Observation[MAX_CARDINALITY] storage self,
uint32 time,
uint32 target,
uint32 index,
uint32 cardinality
) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
unchecked {
uint256 l = (index + 1) % cardinality; // oldest observation
uint256 r = l + cardinality - 1; // newest observation
uint256 i;
while (true) {
i = (l + r) / 2;
beforeOrAt = self[i % cardinality];
// we've landed on an uninitialized tick, keep searching higher (more recently)
if (!beforeOrAt.initialized) {
l = i + 1;
continue;
}
atOrAfter = self[(i + 1) % cardinality];
bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target);
// check if we've found the answer!
if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) break;
if (!targetAtOrAfter) r = i - 1;
else l = i + 1;
}
}
}
/// @notice Fetches the observations beforeOrAt and atOrAfter a given target, i.e. where [beforeOrAt, atOrAfter] is satisfied
/// @dev Assumes there is at least 1 initialized observation.
/// Used by observeSingle() to compute the counterfactual accumulator values as of a given block timestamp.
/// @param self The stored oracle array
/// @param intermediate The intermediate observation in between min intervals. Always the most recent observation.
/// @param time The current block.timestamp
/// @param target The timestamp at which the reserved observation should be for
/// @param tick The active tick at the time of the returned or simulated observation
/// @param index The index of the observation that was most recently written to the observations array
/// @param cardinality The number of populated elements in the oracle array
/// @return beforeOrAt The observation which occurred at, or before, the given timestamp
/// @return atOrAfter The observation which occurred at, or after, the given timestamp
function getSurroundingObservations(
Observation[MAX_CARDINALITY] storage self,
Observation memory intermediate,
uint32 time,
uint32 target,
int24 tick,
uint32 index,
uint32 cardinality
) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
unchecked {
// optimistically set before to the newest observation
beforeOrAt = intermediate;
// if the target is chronologically at or after the newest observation, we can early return
if (lte(time, beforeOrAt.blockTimestamp, target)) {
if (beforeOrAt.blockTimestamp == target) {
// if newest observation equals target, we're in the same block, so we can ignore atOrAfter
return (beforeOrAt, atOrAfter);
} else {
// otherwise, we need to transform
return (beforeOrAt, transform(beforeOrAt, target, tick));
}
}
// now, set before to the newest *recorded* Observation
beforeOrAt = self[index];
atOrAfter = intermediate;
// if the target is chronologically at or after the newest recorded observation, we can early return
// beforeAt would be self[index] and atOrAfter would be intermediate
if (lte(time, beforeOrAt.blockTimestamp, target)) {
return (beforeOrAt, atOrAfter);
}
// now, set before to the oldest observation
beforeOrAt = self[(index + 1) % cardinality];
if (!beforeOrAt.initialized) beforeOrAt = self[0];
// ensure that the target is chronologically at or after the oldest observation
if (!lte(time, beforeOrAt.blockTimestamp, target)) {
revert TargetPredatesOldestObservation(beforeOrAt.blockTimestamp, target);
}
// if we've reached this point, we have to binary search
return binarySearch(self, time, target, index, cardinality);
}
}
/// @dev Reverts if an observation at or before the desired observation timestamp does not exist.
/// 0 may be passed as `secondsAgo' to return the current cumulative values.
/// If called with a timestamp falling between two observations, returns the counterfactual accumulator values
/// at exactly the timestamp between the two observations.
/// @param self The stored oracle array
/// @param intermediate The intermediate observation in between min intervals. Always the most recent observation.
/// @param time The current block timestamp
/// @param secondsAgo The amount of time to look back, in seconds, at which point to return an observation
/// @param tick The current tick
/// @param index The index of the observation that was most recently written to the observations array
/// @param cardinality The number of populated elements in the oracle array
/// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo`
function observeSingle(
Observation[MAX_CARDINALITY] storage self,
Observation memory intermediate,
uint32 time,
uint32 secondsAgo,
int24 tick,
uint32 index,
uint32 cardinality
) internal view returns (int56 tickCumulative) {
unchecked {
if (secondsAgo == 0) {
if (intermediate.blockTimestamp != time) intermediate = transform(intermediate, time, tick);
return intermediate.tickCumulative;
}
uint32 target = time - secondsAgo;
(Observation memory beforeOrAt, Observation memory atOrAfter) =
getSurroundingObservations(self, intermediate, time, target, tick, index, cardinality);
if (target == beforeOrAt.blockTimestamp) {
// we're at the left boundary
return beforeOrAt.tickCumulative;
} else if (target == atOrAfter.blockTimestamp) {
// we're at the right boundary
return atOrAfter.tickCumulative;
} else {
// we're in the middle
uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;
uint32 targetDelta = target - beforeOrAt.blockTimestamp;
return beforeOrAt.tickCumulative
+ ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / int56(uint56(observationTimeDelta)))
* int56(uint56(targetDelta));
}
}
}
/// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
/// @dev Reverts if `secondsAgos` > oldest observation
/// @param self The stored oracle array
/// @param intermediate The intermediate observation in between min intervals. Always the most recent observation.
/// @param time The current block.timestamp
/// @param secondsAgo0 Amount of time to look back, in seconds, at which point to return an observation
/// @param secondsAgo1 Amount of time to look back, in seconds, at which point to return an observation
/// @param tick The current tick
/// @param index The index of the observation that was most recently written to the observations array
/// @param cardinality The number of populated elements in the oracle array
/// @return tickCumulative0 The first tick * time elapsed since the pool was first initialized, as of `secondsAgo0`
/// @return tickCumulative1 The second tick * time elapsed since the pool was first initialized, as of `secondsAgo1`
function observeDouble(
Observation[MAX_CARDINALITY] storage self,
Observation memory intermediate,
uint32 time,
uint32 secondsAgo0,
uint32 secondsAgo1,
int24 tick,
uint32 index,
uint32 cardinality
) internal view returns (int56 tickCumulative0, int56 tickCumulative1) {
unchecked {
if (cardinality == 0) revert OracleCardinalityCannotBeZero();
tickCumulative0 = observeSingle(self, intermediate, time, secondsAgo0, tick, index, cardinality);
tickCumulative1 = observeSingle(self, intermediate, time, secondsAgo1, tick, index, cardinality);
}
}
function observeTriple(
Oracle.Observation[MAX_CARDINALITY] storage self,
Oracle.Observation memory intermediate,
uint32 time,
uint32 secondsAgo0,
uint32 secondsAgo1,
uint32 secondsAgo2,
int24 tick,
uint32 index,
uint32 cardinality
) internal view returns (int56 tickCumulative0, int56 tickCumulative1, int56 tickCumulative2) {
unchecked {
if (cardinality == 0) revert OracleCardinalityCannotBeZero();
tickCumulative0 = observeSingle(self, intermediate, time, secondsAgo0, tick, index, cardinality);
tickCumulative1 = observeSingle(self, intermediate, time, secondsAgo1, tick, index, cardinality);
tickCumulative2 = observeSingle(self, intermediate, time, secondsAgo2, tick, index, cardinality);
}
}
/// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
/// @dev Reverts if `secondsAgos` > oldest observation
/// @param self The stored oracle array
/// @param intermediate The intermediate observation in between min intervals. Always the most recent observation.
/// @param time The current block.timestamp
/// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation
/// @param tick The current tick
/// @param index The index of the observation that was most recently written to the observations array
/// @param cardinality The number of populated elements in the oracle array
/// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo`
function observe(
Observation[MAX_CARDINALITY] storage self,
Observation memory intermediate,
uint32 time,
uint32[] memory secondsAgos,
int24 tick,
uint32 index,
uint32 cardinality
) internal view returns (int56[] memory tickCumulatives) {
unchecked {
if (cardinality == 0) revert OracleCardinalityCannotBeZero();
tickCumulatives = new int56[](secondsAgos.length);
for (uint256 i = 0; i < secondsAgos.length; i++) {
tickCumulatives[i] = observeSingle(self, intermediate, time, secondsAgos[i], tick, index, cardinality);
}
}
}
/// @notice comparator for 32-bit timestamps
/// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time
/// @param time A timestamp truncated to 32 bits
/// @param a A comparison timestamp from which to determine the relative position of `time`
/// @param b From which to determine the relative position of `time`
/// @return Whether `a` is chronologically <= `b`
function lte(uint32 time, uint32 a, uint32 b) private pure returns (bool) {
unchecked {
// if there hasn't been overflow, no need to adjust
if (a <= time && b <= time) return a <= b;
uint256 aAdjusted = a > time ? a : a + 2 ** 32;
uint256 bAdjusted = b > time ? b : b + 2 ** 32;
return aAdjusted <= bAdjusted;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {IFloodPlain} from "flood-contracts/src/interfaces/IFloodPlain.sol";
import {ISignatureTransfer, PermitHash} from "permit2/src/libraries/PermitHash.sol";
library OrderHashMemory {
string internal constant _HOOK_STRING = "Hook(address target,bytes data)";
string internal constant _ITEM_STRING = "Item(address token,uint256 amount)";
string internal constant _ORDER_STRING =
"Order(address offerer,address zone,address recipient,Item[] offer,Item consideration,uint256 deadline,uint256 nonce,Hook[] preHooks,Hook[] postHooks)";
string internal constant _PERMIT_STRING =
"PermitBatchWitnessTransferFrom(TokenPermissions[] permitted,address spender,uint256 nonce,uint256 deadline,Order witness)";
string internal constant _TOKEN_PERMISSIONS_STRING = "TokenPermissions(address token,uint256 amount)";
string internal constant _PERMIT_STRING_VARIABLE_END = "Order witness)";
bytes32 public constant _ITEM_TYPEHASH = keccak256(bytes(_ITEM_STRING));
bytes32 public constant _HOOK_TYPEHASH = keccak256(bytes(_HOOK_STRING));
bytes32 public constant _ORDER_TYPEHASH = keccak256(abi.encodePacked(_ORDER_STRING, _HOOK_STRING, _ITEM_STRING));
bytes32 public constant _PERMIT_TYPEHASH = keccak256(
abi.encodePacked(_PERMIT_STRING, _HOOK_STRING, _ITEM_STRING, _ORDER_STRING, _TOKEN_PERMISSIONS_STRING)
);
string public constant _WITNESS_TYPESTRING = string(
abi.encodePacked(
_PERMIT_STRING_VARIABLE_END, _HOOK_STRING, _ITEM_STRING, _ORDER_STRING, _TOKEN_PERMISSIONS_STRING
)
);
function hash(IFloodPlain.Hook memory hook) internal pure returns (bytes32) {
return keccak256(abi.encode(_HOOK_TYPEHASH, hook.target, keccak256(hook.data)));
}
function hash(IFloodPlain.Item memory item) internal pure returns (bytes32) {
return keccak256(abi.encode(_ITEM_TYPEHASH, item.token, item.amount));
}
function hash(IFloodPlain.Order memory order) internal pure returns (bytes32) {
// Hash offer array.
uint256 length = order.offer.length;
bytes32[] memory offerHashes = new bytes32[](length);
for (uint256 i; i < length; ++i) {
offerHashes[i] = hash(order.offer[i]);
}
// Hash preHooks array.
length = order.preHooks.length;
bytes32[] memory preHooksHashes = new bytes32[](length);
for (uint256 i; i < length; ++i) {
preHooksHashes[i] = hash(order.preHooks[i]);
}
// Hash postHooks array.
length = order.postHooks.length;
bytes32[] memory postHooksHashes = new bytes32[](length);
for (uint256 i; i < length; ++i) {
postHooksHashes[i] = hash(order.postHooks[i]);
}
// Derive and return the order hash as specified by EIP-712.
return keccak256(
abi.encode(
_ORDER_TYPEHASH,
order.offerer,
order.zone,
order.recipient,
keccak256(abi.encodePacked(offerHashes)),
hash(order.consideration),
order.deadline,
order.nonce,
keccak256(abi.encodePacked(preHooksHashes)),
keccak256(abi.encodePacked(postHooksHashes))
)
);
}
function hashAsWitness(IFloodPlain.Order memory order, address spender)
internal
pure
returns (bytes32 orderHash, bytes32 hashWithWitness)
{
IFloodPlain.Item[] memory offer = order.offer;
bytes32[] memory tokenPermissionHashes = new bytes32[](offer.length);
bytes32[] memory offerHashes = new bytes32[](offer.length);
for (uint256 i; i < offer.length; ++i) {
IFloodPlain.Item memory item = offer[i];
offerHashes[i] = hash(item);
tokenPermissionHashes[i] = keccak256(
abi.encode(
PermitHash._TOKEN_PERMISSIONS_TYPEHASH, ISignatureTransfer.TokenPermissions(item.token, item.amount)
)
);
}
orderHash = hash(order);
hashWithWitness = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
keccak256(abi.encodePacked(tokenPermissionHashes)),
spender,
order.nonce,
order.deadline,
orderHash
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {IOwnable} from "../interfaces/IOwnable.sol";
/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable is IOwnable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
/// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
/// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The owner slot is given by:
/// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
/// It is intentionally chosen to be a high value
/// to avoid collision with lower slots.
/// The choice of manual storage layout is to enable compatibility
/// with both regular and upgradeable contracts.
bytes32 internal constant _OWNER_SLOT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
/// The ownership handover slot of `newOwner` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
/// let handoverSlot := keccak256(0x00, 0x20)
/// ```
/// It stores the expiry timestamp of the two-step ownership handover.
uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Initializes the owner directly without authorization guard.
/// This function must be called upon initialization,
/// regardless of whether the contract is upgradeable or not.
/// This is to enable generalization to both regular and upgradeable contracts,
/// and to save gas in case the initial owner is not the caller.
/// For performance reasons, this function will not check if there
/// is an existing owner.
function _initializeOwner(address newOwner) internal virtual {
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(_OWNER_SLOT, newOwner)
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
}
/// @dev Sets the owner directly without authorization guard.
function _setOwner(address newOwner) internal virtual {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, newOwner)
}
}
/// @dev Throws if the sender is not the owner.
function _checkOwner() internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner, revert.
if iszero(eq(caller(), sload(_OWNER_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns how long a two-step ownership handover is valid for in seconds.
/// Override to return a different value if needed.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
return 48 * 3600;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to transfer the ownership to `newOwner`.
function transferOwnership(address newOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
if iszero(shl(96, newOwner)) {
mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
revert(0x1c, 0x04)
}
}
_setOwner(newOwner);
}
/// @dev Allows the owner to renounce their ownership.
function renounceOwnership() public payable virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Request a two-step ownership handover to the caller.
/// The request will automatically expire in 48 hours (172800 seconds) by default.
function requestOwnershipHandover() public payable virtual {
unchecked {
uint256 expires = block.timestamp + _ownershipHandoverValidFor();
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to `expires`.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
// Emit the {OwnershipHandoverRequested} event.
log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
}
}
}
/// @dev Cancels the two-step ownership handover to the caller, if any.
function cancelOwnershipHandover() public payable virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), 0)
// Emit the {OwnershipHandoverCanceled} event.
log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
}
}
/// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
/// Reverts if there is no existing ownership handover requested by `pendingOwner`.
function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
let handoverSlot := keccak256(0x0c, 0x20)
// If the handover does not exist, or has expired.
if gt(timestamp(), sload(handoverSlot)) {
mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
revert(0x1c, 0x04)
}
// Set the handover slot to 0.
sstore(handoverSlot, 0)
}
_setOwner(pendingOwner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of the contract.
function owner() public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_OWNER_SLOT)
}
}
/// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
function ownershipHandoverExpiresAt(address pendingOwner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
// Compute the handover slot.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
// Load the handover slot.
result := sload(keccak256(0x0c, 0x20))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by the owner.
modifier onlyOwner() virtual {
_checkOwner();
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
// equivalent: (selector,) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
selector := mload(add(result, 0x20))
}
}
function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
// equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
assembly ("memory-safe") {
lpFee := mload(add(result, 0x60))
}
}
function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
// equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
hookReturn := mload(add(result, 0x40))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {IAllowanceTransfer} from "../interfaces/IAllowanceTransfer.sol";
import {ISignatureTransfer} from "../interfaces/ISignatureTransfer.sol";
library PermitHash {
bytes32 public constant _PERMIT_DETAILS_TYPEHASH =
keccak256("PermitDetails(address token,uint160 amount,uint48 expiration,uint48 nonce)");
bytes32 public constant _PERMIT_SINGLE_TYPEHASH = keccak256(
"PermitSingle(PermitDetails details,address spender,uint256 sigDeadline)PermitDetails(address token,uint160 amount,uint48 expiration,uint48 nonce)"
);
bytes32 public constant _PERMIT_BATCH_TYPEHASH = keccak256(
"PermitBatch(PermitDetails[] details,address spender,uint256 sigDeadline)PermitDetails(address token,uint160 amount,uint48 expiration,uint48 nonce)"
);
bytes32 public constant _TOKEN_PERMISSIONS_TYPEHASH = keccak256("TokenPermissions(address token,uint256 amount)");
bytes32 public constant _PERMIT_TRANSFER_FROM_TYPEHASH = keccak256(
"PermitTransferFrom(TokenPermissions permitted,address spender,uint256 nonce,uint256 deadline)TokenPermissions(address token,uint256 amount)"
);
bytes32 public constant _PERMIT_BATCH_TRANSFER_FROM_TYPEHASH = keccak256(
"PermitBatchTransferFrom(TokenPermissions[] permitted,address spender,uint256 nonce,uint256 deadline)TokenPermissions(address token,uint256 amount)"
);
string public constant _TOKEN_PERMISSIONS_TYPESTRING = "TokenPermissions(address token,uint256 amount)";
string public constant _PERMIT_TRANSFER_FROM_WITNESS_TYPEHASH_STUB =
"PermitWitnessTransferFrom(TokenPermissions permitted,address spender,uint256 nonce,uint256 deadline,";
string public constant _PERMIT_BATCH_WITNESS_TRANSFER_FROM_TYPEHASH_STUB =
"PermitBatchWitnessTransferFrom(TokenPermissions[] permitted,address spender,uint256 nonce,uint256 deadline,";
function hash(IAllowanceTransfer.PermitSingle memory permitSingle) internal pure returns (bytes32) {
bytes32 permitHash = _hashPermitDetails(permitSingle.details);
return
keccak256(abi.encode(_PERMIT_SINGLE_TYPEHASH, permitHash, permitSingle.spender, permitSingle.sigDeadline));
}
function hash(IAllowanceTransfer.PermitBatch memory permitBatch) internal pure returns (bytes32) {
uint256 numPermits = permitBatch.details.length;
bytes32[] memory permitHashes = new bytes32[](numPermits);
for (uint256 i = 0; i < numPermits; ++i) {
permitHashes[i] = _hashPermitDetails(permitBatch.details[i]);
}
return keccak256(
abi.encode(
_PERMIT_BATCH_TYPEHASH,
keccak256(abi.encodePacked(permitHashes)),
permitBatch.spender,
permitBatch.sigDeadline
)
);
}
function hash(ISignatureTransfer.PermitTransferFrom memory permit) internal view returns (bytes32) {
bytes32 tokenPermissionsHash = _hashTokenPermissions(permit.permitted);
return keccak256(
abi.encode(_PERMIT_TRANSFER_FROM_TYPEHASH, tokenPermissionsHash, msg.sender, permit.nonce, permit.deadline)
);
}
function hash(ISignatureTransfer.PermitBatchTransferFrom memory permit) internal view returns (bytes32) {
uint256 numPermitted = permit.permitted.length;
bytes32[] memory tokenPermissionHashes = new bytes32[](numPermitted);
for (uint256 i = 0; i < numPermitted; ++i) {
tokenPermissionHashes[i] = _hashTokenPermissions(permit.permitted[i]);
}
return keccak256(
abi.encode(
_PERMIT_BATCH_TRANSFER_FROM_TYPEHASH,
keccak256(abi.encodePacked(tokenPermissionHashes)),
msg.sender,
permit.nonce,
permit.deadline
)
);
}
function hashWithWitness(
ISignatureTransfer.PermitTransferFrom memory permit,
bytes32 witness,
string calldata witnessTypeString
) internal view returns (bytes32) {
bytes32 typeHash = keccak256(abi.encodePacked(_PERMIT_TRANSFER_FROM_WITNESS_TYPEHASH_STUB, witnessTypeString));
bytes32 tokenPermissionsHash = _hashTokenPermissions(permit.permitted);
return keccak256(abi.encode(typeHash, tokenPermissionsHash, msg.sender, permit.nonce, permit.deadline, witness));
}
function hashWithWitness(
ISignatureTransfer.PermitBatchTransferFrom memory permit,
bytes32 witness,
string calldata witnessTypeString
) internal view returns (bytes32) {
bytes32 typeHash =
keccak256(abi.encodePacked(_PERMIT_BATCH_WITNESS_TRANSFER_FROM_TYPEHASH_STUB, witnessTypeString));
uint256 numPermitted = permit.permitted.length;
bytes32[] memory tokenPermissionHashes = new bytes32[](numPermitted);
for (uint256 i = 0; i < numPermitted; ++i) {
tokenPermissionHashes[i] = _hashTokenPermissions(permit.permitted[i]);
}
return keccak256(
abi.encode(
typeHash,
keccak256(abi.encodePacked(tokenPermissionHashes)),
msg.sender,
permit.nonce,
permit.deadline,
witness
)
);
}
function _hashPermitDetails(IAllowanceTransfer.PermitDetails memory details) private pure returns (bytes32) {
return keccak256(abi.encode(_PERMIT_DETAILS_TYPEHASH, details));
}
function _hashTokenPermissions(ISignatureTransfer.TokenPermissions memory permitted)
private
pure
returns (bytes32)
{
return keccak256(abi.encode(_TOKEN_PERMISSIONS_TYPEHASH, permitted));
}
}
// 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)
}
}
}
// 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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {PoolId, PoolKey, Currency} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {SSTORE2} from "solady/utils/SSTORE2.sol";
import {ERC4626} from "solady/tokens/ERC4626.sol";
import "./LDFType.sol";
import "./IdleBalance.sol";
import "../base/Errors.sol";
import {IHooklet} from "../interfaces/IHooklet.sol";
import {HubStorage} from "../base/SharedStructs.sol";
import {IBunniToken} from "../interfaces/IBunniToken.sol";
import {ILiquidityDensityFunction} from "../interfaces/ILiquidityDensityFunction.sol";
using SSTORE2 for address;
/// @notice The state of a Bunni pool
/// @member liquidityDensityFunction The LDF that dictates how liquidity is distributed
/// @member bunniToken The BunniToken for this pool
/// @member hooklet The hooklet for this pool. Set to address(0) if the pool does not have a hooklet.
/// @member twapSecondsAgo The time window for the TWAP used by the LDF. Set to 0 if the LDF does not use the TWAP.
/// @member ldfParams The parameters for the LDF
/// @member hookParams The hook parameters for the pool
/// @member vault0 The ERC4626 vault used for currency0
/// @member vault1 The ERC4626 vault used for currency1
/// @member ldfType The type of LDF. See LDFType.sol for details.
/// @member minRawTokenRatio0 The minimum (rawBalance / balance) ratio for currency0
/// @member targetRawTokenRatio0 The target (rawBalance / balance) ratio for currency0
/// @member maxRawTokenRatio0 The maximum (rawBalance / balance) ratio for currency0
/// @member minRawTokenRatio1 The minimum (rawBalance / balance) ratio for currency1
/// @member targetRawTokenRatio1 The target (rawBalance / balance) ratio for currency1
/// @member maxRawTokenRatio1 The maximum (rawBalance / balance) ratio for currency1
/// @member rawBalance0 The raw token balance of currency0. Raw just means it's not stored in a ERC4626 vault.
/// @member rawBalance1 The raw token balance of currency1. Raw just means it's not stored in a ERC4626 vault.
/// @member reserve0 The vault share tokens owned in vault0
/// @member reserve1 The vault share tokens owned in vault1
/// @member idleBalance The balance of the token that's in excess. Used when computing the total liquidity.
struct PoolState {
ILiquidityDensityFunction liquidityDensityFunction;
IBunniToken bunniToken;
IHooklet hooklet;
uint24 twapSecondsAgo;
bytes32 ldfParams;
bytes hookParams;
ERC4626 vault0;
ERC4626 vault1;
LDFType ldfType;
uint24 minRawTokenRatio0;
uint24 targetRawTokenRatio0;
uint24 maxRawTokenRatio0;
uint24 minRawTokenRatio1;
uint24 targetRawTokenRatio1;
uint24 maxRawTokenRatio1;
uint256 rawBalance0;
uint256 rawBalance1;
uint256 reserve0;
uint256 reserve1;
IdleBalance idleBalance;
}
/// @notice The raw state of a given pool
/// @dev Since a pool's parameters are immutable, we use SSTORE2 to store them cheaply and store the pointer here.
/// @member immutableParamsPointer The SSTORE2 pointer to the immutable parameters of the pool
/// @member rawBalance0 The raw token balance of currency0. Raw just means it's not stored in a ERC4626 vault.
/// @member rawBalance1 The raw token balance of currency1. Raw just means it's not stored in a ERC4626 vault.
struct RawPoolState {
address immutableParamsPointer;
uint256 rawBalance0;
uint256 rawBalance1;
}
function getPoolParams(address ptr) view returns (PoolState memory state) {
// read params via SSLOAD2
bytes memory immutableParams = ptr.read();
{
ILiquidityDensityFunction liquidityDensityFunction;
/// @solidity memory-safe-assembly
assembly {
liquidityDensityFunction := shr(96, mload(add(immutableParams, 32)))
}
state.liquidityDensityFunction = liquidityDensityFunction;
}
{
IBunniToken bunniToken;
/// @solidity memory-safe-assembly
assembly {
bunniToken := shr(96, mload(add(immutableParams, 52)))
}
state.bunniToken = bunniToken;
}
{
uint24 twapSecondsAgo;
/// @solidity memory-safe-assembly
assembly {
twapSecondsAgo := shr(232, mload(add(immutableParams, 72)))
}
state.twapSecondsAgo = twapSecondsAgo;
}
{
bytes32 ldfParams;
/// @solidity memory-safe-assembly
assembly {
ldfParams := mload(add(immutableParams, 75))
}
state.ldfParams = ldfParams;
}
{
ERC4626 vault0;
/// @solidity memory-safe-assembly
assembly {
vault0 := shr(96, mload(add(immutableParams, 107)))
}
state.vault0 = vault0;
}
{
ERC4626 vault1;
/// @solidity memory-safe-assembly
assembly {
vault1 := shr(96, mload(add(immutableParams, 127)))
}
state.vault1 = vault1;
}
{
LDFType ldfType;
/// @solidity memory-safe-assembly
assembly {
ldfType := shr(248, mload(add(immutableParams, 147)))
}
state.ldfType = ldfType;
}
{
uint24 minRawTokenRatio0;
/// @solidity memory-safe-assembly
assembly {
minRawTokenRatio0 := shr(232, mload(add(immutableParams, 148)))
}
state.minRawTokenRatio0 = minRawTokenRatio0;
}
{
uint24 targetRawTokenRatio0;
/// @solidity memory-safe-assembly
assembly {
targetRawTokenRatio0 := shr(232, mload(add(immutableParams, 151)))
}
state.targetRawTokenRatio0 = targetRawTokenRatio0;
}
{
uint24 maxRawTokenRatio0;
/// @solidity memory-safe-assembly
assembly {
maxRawTokenRatio0 := shr(232, mload(add(immutableParams, 154)))
}
state.maxRawTokenRatio0 = maxRawTokenRatio0;
}
{
uint24 minRawTokenRatio1;
/// @solidity memory-safe-assembly
assembly {
minRawTokenRatio1 := shr(232, mload(add(immutableParams, 157)))
}
state.minRawTokenRatio1 = minRawTokenRatio1;
}
{
uint24 targetRawTokenRatio1;
/// @solidity memory-safe-assembly
assembly {
targetRawTokenRatio1 := shr(232, mload(add(immutableParams, 160)))
}
state.targetRawTokenRatio1 = targetRawTokenRatio1;
}
{
uint24 maxRawTokenRatio1;
/// @solidity memory-safe-assembly
assembly {
maxRawTokenRatio1 := shr(232, mload(add(immutableParams, 163)))
}
state.maxRawTokenRatio1 = maxRawTokenRatio1;
}
{
IHooklet hooklet;
/// @solidity memory-safe-assembly
assembly {
hooklet := shr(96, mload(add(immutableParams, 166)))
}
state.hooklet = hooklet;
}
{
bytes memory hookParams;
/// @solidity memory-safe-assembly
assembly {
let hookParamsLen := shr(240, mload(add(immutableParams, 186))) // uint16
hookParams := add(immutableParams, 156) // 156 = 186 (hookParamsLen location) + 2 (hookParamsLen is uint16) - 32 (expand hookParamsLen to 32 bytes)
mstore(hookParams, hookParamsLen) // overwrite length field of `bytes memory hookParams`
}
state.hookParams = hookParams;
}
}
function getPoolState(HubStorage storage s, PoolId poolId) view returns (PoolState memory state) {
RawPoolState memory rawState = s.poolState[poolId];
if (rawState.immutableParamsPointer == address(0)) revert BunniHub__BunniTokenNotInitialized();
state = getPoolParams(rawState.immutableParamsPointer);
state.rawBalance0 = rawState.rawBalance0;
state.rawBalance1 = rawState.rawBalance1;
state.reserve0 = address(state.vault0) != address(0) ? s.reserve0[poolId] : 0;
state.reserve1 = address(state.vault1) != address(0) ? s.reserve1[poolId] : 0;
// idle balance is only needed when the LDF is not static since static LDFs
// can never become imbalanced
state.idleBalance = state.ldfType == LDFType.STATIC ? IdleBalanceLibrary.ZERO : s.idleBalance[poolId];
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import "../types/IdleBalance.sol";
import {Q96} from "../base/Constants.sol";
import {FullMathX96} from "./FullMathX96.sol";
import {LiquidityAmounts} from "./LiquidityAmounts.sol";
import {roundTick, roundUpFullMulDivResult} from "./Math.sol";
import {ILiquidityDensityFunction} from "../interfaces/ILiquidityDensityFunction.sol";
using FullMathX96 for uint256;
using FixedPointMathLib for uint256;
/// @notice Queries the liquidity density function for the given pool and tick
/// @param key The pool key
/// @param sqrtPriceX96 The current sqrt price of the pool
/// @param tick The current tick of the pool
/// @param arithmeticMeanTick The TWAP oracle value
/// @param ldf The liquidity density function
/// @param ldfParams The parameters for the liquidity density function
/// @param ldfState The current state of the liquidity density function
/// @param balance0 The balance of token0 in the pool
/// @param balance1 The balance of token1 in the pool
/// @return totalLiquidity The total liquidity in the pool
/// @return totalDensity0X96 The total density of token0 in the pool, scaled by Q96
/// @return totalDensity1X96 The total density of token1 in the pool, scaled by Q96
/// @return liquidityDensityOfRoundedTickX96 The liquidity density of the rounded tick, scaled by Q96
/// @return activeBalance0 The active balance of token0 in the pool, which is the amount used by swap liquidity
/// @return activeBalance1 The active balance of token1 in the pool, which is the amount used by swap liquidity
/// @return newLdfState The new state of the liquidity density function
/// @return shouldSurge Whether the pool should surge
function queryLDF(
PoolKey memory key,
uint160 sqrtPriceX96,
int24 tick,
int24 arithmeticMeanTick,
ILiquidityDensityFunction ldf,
bytes32 ldfParams,
bytes32 ldfState,
uint256 balance0,
uint256 balance1,
IdleBalance idleBalance
)
view
returns (
uint256 totalLiquidity,
uint256 totalDensity0X96,
uint256 totalDensity1X96,
uint256 liquidityDensityOfRoundedTickX96,
uint256 activeBalance0,
uint256 activeBalance1,
bytes32 newLdfState,
bool shouldSurge
)
{
(int24 roundedTick, int24 nextRoundedTick) = roundTick(tick, key.tickSpacing);
(uint160 roundedTickSqrtRatio, uint160 nextRoundedTickSqrtRatio) =
(TickMath.getSqrtPriceAtTick(roundedTick), TickMath.getSqrtPriceAtTick(nextRoundedTick));
uint256 density0RightOfRoundedTickX96;
uint256 density1LeftOfRoundedTickX96;
(
liquidityDensityOfRoundedTickX96,
density0RightOfRoundedTickX96,
density1LeftOfRoundedTickX96,
newLdfState,
shouldSurge
) = ldf.query(key, roundedTick, arithmeticMeanTick, tick, ldfParams, ldfState);
(uint256 density0OfRoundedTickX96, uint256 density1OfRoundedTickX96) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96, roundedTickSqrtRatio, nextRoundedTickSqrtRatio, uint128(liquidityDensityOfRoundedTickX96), true
);
totalDensity0X96 = density0RightOfRoundedTickX96 + density0OfRoundedTickX96;
totalDensity1X96 = density1LeftOfRoundedTickX96 + density1OfRoundedTickX96;
// modify balance0/balance1 to deduct the idle balance
// skip this if a surge happens since the idle balance will need to be recalculated
if (!shouldSurge) {
(uint256 balance, bool isToken0) = IdleBalanceLibrary.fromIdleBalance(idleBalance);
if (isToken0) {
balance0 = subReLU(balance0, balance);
} else {
balance1 = subReLU(balance1, balance);
}
}
if (balance0 != 0 || balance1 != 0) {
bool noToken0 = balance0 == 0 || totalDensity0X96 == 0;
bool noToken1 = balance1 == 0 || totalDensity1X96 == 0;
uint256 totalLiquidityEstimate0 = noToken0 ? 0 : balance0.fullMulDiv(Q96, totalDensity0X96);
uint256 totalLiquidityEstimate1 = noToken1 ? 0 : balance1.fullMulDiv(Q96, totalDensity1X96);
bool useLiquidityEstimate0 =
(totalLiquidityEstimate0 < totalLiquidityEstimate1 || totalDensity1X96 == 0) && totalDensity0X96 != 0;
if (useLiquidityEstimate0) {
totalLiquidity =
noToken0 ? 0 : roundUpFullMulDivResult(balance0, Q96, totalDensity0X96, totalLiquidityEstimate0);
(activeBalance0, activeBalance1) = (
noToken0 ? 0 : FixedPointMathLib.min(balance0, totalLiquidityEstimate0.fullMulX96(totalDensity0X96)),
noToken1 ? 0 : FixedPointMathLib.min(balance1, totalLiquidityEstimate0.fullMulX96(totalDensity1X96))
);
} else {
totalLiquidity =
noToken1 ? 0 : roundUpFullMulDivResult(balance1, Q96, totalDensity1X96, totalLiquidityEstimate1);
(activeBalance0, activeBalance1) = (
noToken0 ? 0 : FixedPointMathLib.min(balance0, totalLiquidityEstimate1.fullMulX96(totalDensity0X96)),
noToken1 ? 0 : FixedPointMathLib.min(balance1, totalLiquidityEstimate1.fullMulX96(totalDensity1X96))
);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;
import "@uniswap/v4-core/src/types/Currency.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import "flood-contracts/src/interfaces/IZone.sol";
import "flood-contracts/src/interfaces/IFloodPlain.sol";
import "flood-contracts/src/interfaces/IOnChainOrders.sol";
import {IEIP712} from "permit2/src/interfaces/IEIP712.sol";
import {ERC20} from "solady/tokens/ERC20.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import "./VaultMath.sol";
import "../types/PoolState.sol";
import "../types/IdleBalance.sol";
import "../base/SharedStructs.sol";
import {Oracle} from "./Oracle.sol";
import {queryLDF} from "./QueryLDF.sol";
import {FullMathX96} from "./FullMathX96.sol";
import {BunniHookLogic} from "./BunniHookLogic.sol";
import {OrderHashMemory} from "./OrderHashMemory.sol";
library RebalanceLogic {
using FullMathX96 for *;
using SafeTransferLib for *;
using FixedPointMathLib for *;
using IdleBalanceLibrary for *;
using Oracle for Oracle.Observation[MAX_CARDINALITY];
/// @dev Creates a rebalance order on FloodPlain.
function rebalance(
HookStorage storage s,
BunniHookLogic.Env calldata env,
BunniHookLogic.RebalanceInput calldata input
) external {
// compute rebalance params
(bool success, Currency inputToken, Currency outputToken, uint256 inputAmount, uint256 outputAmount) =
_computeRebalanceParams(s, env, input);
if (!success) return;
// create rebalance order
_createRebalanceOrder(
s,
env,
input.id,
input.key,
input.hookParams.rebalanceOrderTTL,
inputToken,
outputToken,
inputAmount,
outputAmount
);
}
function _computeRebalanceParams(
HookStorage storage s,
BunniHookLogic.Env calldata env,
BunniHookLogic.RebalanceInput calldata input
)
private
view
returns (bool success, Currency inputToken, Currency outputToken, uint256 inputAmount, uint256 outputAmount)
{
// compute the ratio (excessLiquidity / totalLiquidity)
// excessLiquidity is the minimum amount of liquidity that can be supported by the excess tokens
// load fresh state
PoolState memory bunniState = env.hub.poolState(input.id);
// get fresh token balances
(uint256 balance0, uint256 balance1) = (
bunniState.rawBalance0 + getReservesInUnderlying(bunniState.reserve0, bunniState.vault0),
bunniState.rawBalance1 + getReservesInUnderlying(bunniState.reserve1, bunniState.vault1)
);
// compute total liquidity at spot price
(uint256 totalLiquidity,,,,,,,) = queryLDF({
key: input.key,
sqrtPriceX96: input.updatedSqrtPriceX96,
tick: input.updatedTick,
arithmeticMeanTick: input.arithmeticMeanTick,
ldf: bunniState.liquidityDensityFunction,
ldfParams: bunniState.ldfParams,
ldfState: input.newLdfState,
balance0: balance0,
balance1: balance1,
idleBalance: bunniState.idleBalance
});
// compute target token densities of the excess liquidity after rebalancing
// this is done by querying the LDF using a TWAP as the spot price to prevent manipulation
int24 rebalanceSpotPriceTick = _getTwap(
s,
input.id,
input.updatedTick,
input.hookParams.rebalanceTwapSecondsAgo,
input.updatedIntermediate,
input.updatedIndex,
input.updatedCardinality
);
uint160 rebalanceSpotPriceSqrtRatioX96 = TickMath.getSqrtPriceAtTick(rebalanceSpotPriceTick);
// totalDensity0X96 and totalDensity1X96 are the token densities of the excess liquidity
// after rebalancing
(, uint256 totalDensity0X96, uint256 totalDensity1X96,,,,,) = queryLDF({
key: input.key,
sqrtPriceX96: rebalanceSpotPriceSqrtRatioX96,
tick: rebalanceSpotPriceTick,
arithmeticMeanTick: input.arithmeticMeanTick,
ldf: bunniState.liquidityDensityFunction,
ldfParams: bunniState.ldfParams,
ldfState: input.newLdfState,
balance0: 0,
balance1: 0,
idleBalance: IdleBalanceLibrary.ZERO
});
// should rebalance if idleBalance / (totalLiquidity * totalDensityX96 / Q96) >= 1 / rebalanceThreshold
(uint256 idleBalance, bool willRebalanceToken0) = bunniState.idleBalance.fromIdleBalance();
bool shouldRebalance = idleBalance != 0
&& idleBalance
>= totalLiquidity.fullMulX96(willRebalanceToken0 ? totalDensity0X96 : totalDensity1X96)
/ input.hookParams.rebalanceThreshold;
if (!shouldRebalance) return (false, inputToken, outputToken, inputAmount, outputAmount);
// Let x be the idle balance, d be the input amount, and y be the output amount.
// We want the resulting ratio (x - d) / y = r = totalDensityX / totalDensityY.
// Given the price of the output token in terms of the input token, p, we have the following relationship:
// (x - d) / (d / p) = r
// => d = px / (p + r), y = d/p = x / (p + r)
uint256 p; // price of output token in terms of the input token
uint256 r; // desired ratio of the resulting input token amount to the output token amount
if (willRebalanceToken0) {
// zero for one
uint256 rebalanceSpotPriceInvSqrtRatioX96 = TickMath.getSqrtPriceAtTick(-rebalanceSpotPriceTick);
p = rebalanceSpotPriceInvSqrtRatioX96.fullMulX96(rebalanceSpotPriceInvSqrtRatioX96);
if (totalDensity1X96 == 0) {
// should never happen
return (false, inputToken, outputToken, inputAmount, outputAmount);
}
r = totalDensity0X96.fullMulDiv(Q96, totalDensity1X96);
(inputToken, outputToken) = (input.key.currency0, input.key.currency1);
} else {
// one for zero
p = rebalanceSpotPriceSqrtRatioX96.fullMulX96(rebalanceSpotPriceSqrtRatioX96);
if (totalDensity0X96 == 0) {
// should never happen
return (false, inputToken, outputToken, inputAmount, outputAmount);
}
r = totalDensity1X96.fullMulDiv(Q96, totalDensity0X96);
(inputToken, outputToken) = (input.key.currency1, input.key.currency0);
}
// apply slippage to price
// normally slippage is applied to the price of the input token in terms of the output token, but here we use the inverse
// so p := p / (1 - slippage)
p = p.mulDiv(REBALANCE_MAX_SLIPPAGE_BASE, REBALANCE_MAX_SLIPPAGE_BASE - input.hookParams.rebalanceMaxSlippage);
// determine input & output
uint256 pPlusR = p + r;
inputAmount = idleBalance.mulDiv(p, pPlusR);
outputAmount = idleBalance.mulDivUp(Q96, pPlusR);
success = true;
}
function _createRebalanceOrder(
HookStorage storage s,
BunniHookLogic.Env calldata env,
PoolId id,
PoolKey calldata key,
uint16 rebalanceOrderTTL,
Currency inputToken,
Currency outputToken,
uint256 inputAmount,
uint256 outputAmount
) private {
// create Flood order
ERC20 inputERC20Token = inputToken.isAddressZero() ? env.weth : ERC20(Currency.unwrap(inputToken));
ERC20 outputERC20Token = outputToken.isAddressZero() ? env.weth : ERC20(Currency.unwrap(outputToken));
IFloodPlain.Item[] memory offer = new IFloodPlain.Item[](1);
offer[0] = IFloodPlain.Item({token: address(inputERC20Token), amount: inputAmount});
IFloodPlain.Item memory consideration =
IFloodPlain.Item({token: address(outputERC20Token), amount: outputAmount});
IBunniHook.RebalanceOrderHookArgs memory hookArgs = IBunniHook.RebalanceOrderHookArgs({
key: key,
preHookArgs: IBunniHook.RebalanceOrderPreHookArgs({currency: inputToken, amount: inputAmount}),
postHookArgs: IBunniHook.RebalanceOrderPostHookArgs({currency: outputToken})
});
// prehook should pull input tokens from BunniHub to BunniHook and update pool balances
IFloodPlain.Hook[] memory preHooks = new IFloodPlain.Hook[](1);
preHooks[0] = IFloodPlain.Hook({
target: address(this),
data: abi.encodeCall(IBunniHook.rebalanceOrderPreHook, (hookArgs))
});
// posthook should push output tokens from BunniHook to BunniHub and update pool balances
IFloodPlain.Hook[] memory postHooks = new IFloodPlain.Hook[](1);
postHooks[0] = IFloodPlain.Hook({
target: address(this),
data: abi.encodeCall(IBunniHook.rebalanceOrderPostHook, (hookArgs))
});
IFloodPlain.Order memory order = IFloodPlain.Order({
offerer: address(this),
zone: address(env.floodZone),
recipient: address(this),
offer: offer,
consideration: consideration,
deadline: block.timestamp + rebalanceOrderTTL,
nonce: uint256(keccak256(abi.encode(block.number, id))), // combine block.number and pool id to avoid nonce collisions between pools
preHooks: preHooks,
postHooks: postHooks
});
// record order for verification later
(s.rebalanceOrderHash[id], s.rebalanceOrderPermit2Hash[id]) = _hashFloodOrder(order, env);
s.rebalanceOrderDeadline[id] = order.deadline;
// approve input token to permit2
if (inputERC20Token.allowance(address(this), env.permit2) < inputAmount) {
address(inputERC20Token).safeApproveWithRetry(env.permit2, type(uint256).max);
}
// etch order so fillers can pick it up
// use PoolId as signature to enable isValidSignature() to find the correct order hash
IOnChainOrders(address(env.floodPlain)).etchOrder(
IFloodPlain.SignedOrder({order: order, signature: abi.encode(id)})
);
}
function _getTwap(
HookStorage storage s,
PoolId id,
int24 currentTick,
uint32 twapSecondsAgo,
Oracle.Observation calldata updatedIntermediate,
uint32 updatedIndex,
uint32 updatedCardinality
) private view returns (int24 arithmeticMeanTick) {
(int56 tickCumulative0, int56 tickCumulative1) = s.observations[id].observeDouble(
updatedIntermediate,
uint32(block.timestamp),
twapSecondsAgo,
0,
currentTick,
updatedIndex,
updatedCardinality
);
int56 tickCumulativesDelta = tickCumulative1 - tickCumulative0;
arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(twapSecondsAgo)));
}
/// @dev The hash that Permit2 uses when verifying the order's signature.
/// See https://github.com/Uniswap/permit2/blob/cc56ad0f3439c502c246fc5cfcc3db92bb8b7219/src/SignatureTransfer.sol#L65
/// Always calls permit2 for the domain separator to maintain cross-chain replay protection in the event of a fork
/// Also returns the Flood order hash
function _hashFloodOrder(IFloodPlain.Order memory order, BunniHookLogic.Env calldata env)
private
view
returns (bytes32 orderHash, bytes32 permit2Hash)
{
(orderHash, permit2Hash) = OrderHashMemory.hashAsWitness(order, address(env.floodPlain));
permit2Hash = keccak256(abi.encodePacked("\x19\x01", IEIP712(env.permit2).DOMAIN_SEPARATOR(), permit2Hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
abstract contract ReentrancyGuard {
error ReentrancyGuard__ReentrantCall();
/// @dev Equal to uint256(keccak256("STATUS")) - 1
uint256 private constant STATUS_SLOT = 0x99d6ee9363d15a40a5ab48bebc5e3e7dd2c4e190c950f55fe724fad94b380d7e;
uint256 private constant NOT_ENTERED = 0;
uint256 private constant ENTERED = 1;
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() internal {
uint256 statusSlot = STATUS_SLOT;
uint256 status;
/// @solidity memory-safe-assembly
assembly {
status := tload(statusSlot)
}
if (status == ENTERED) revert ReentrancyGuard__ReentrantCall();
uint256 entered = ENTERED;
/// @solidity memory-safe-assembly
assembly {
tstore(statusSlot, entered)
}
}
function _nonReentrantAfter() internal {
uint256 statusSlot = STATUS_SLOT;
uint256 notEntered = NOT_ENTERED;
/// @solidity memory-safe-assembly
assembly {
tstore(statusSlot, notEntered)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Read and write to persistent storage at a fraction of the cost.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SSTORE2.sol)
/// @author Saw-mon-and-Natalie (https://github.com/Saw-mon-and-Natalie)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SSTORE2.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol)
/// @author Modified from SSTORE3 (https://github.com/Philogy/sstore3)
library SSTORE2 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The proxy initialization code.
uint256 private constant _CREATE3_PROXY_INITCODE = 0x67363d3d37363d34f03d5260086018f3;
/// @dev Hash of the `_CREATE3_PROXY_INITCODE`.
/// Equivalent to `keccak256(abi.encodePacked(hex"67363d3d37363d34f03d5260086018f3"))`.
bytes32 internal constant CREATE3_PROXY_INITCODE_HASH =
0x21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unable to deploy the storage contract.
error DeploymentFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* WRITE LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Writes `data` into the bytecode of a storage contract and returns its address.
function write(bytes memory data) internal returns (address pointer) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(data) // Let `l` be `n + 1`. +1 as we prefix a STOP opcode.
/**
* ---------------------------------------------------+
* Opcode | Mnemonic | Stack | Memory |
* ---------------------------------------------------|
* 61 l | PUSH2 l | l | |
* 80 | DUP1 | l l | |
* 60 0xa | PUSH1 0xa | 0xa l l | |
* 3D | RETURNDATASIZE | 0 0xa l l | |
* 39 | CODECOPY | l | [0..l): code |
* 3D | RETURNDATASIZE | 0 l | [0..l): code |
* F3 | RETURN | | [0..l): code |
* 00 | STOP | | |
* ---------------------------------------------------+
* @dev Prefix the bytecode with a STOP opcode to ensure it cannot be called.
* Also PUSH2 is used since max contract size cap is 24,576 bytes which is less than 2 ** 16.
*/
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
// Deploy a new contract with the generated creation code.
pointer := create(0, add(data, 0x15), add(n, 0xb))
if iszero(pointer) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(data, n) // Restore the length of `data`.
}
}
/// @dev Writes `data` into the bytecode of a storage contract with `salt`
/// and returns its normal CREATE2 deterministic address.
function writeCounterfactual(bytes memory data, bytes32 salt)
internal
returns (address pointer)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(data)
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
// Deploy a new contract with the generated creation code.
pointer := create2(0, add(data, 0x15), add(n, 0xb), salt)
if iszero(pointer) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(data, n) // Restore the length of `data`.
}
}
/// @dev Writes `data` into the bytecode of a storage contract and returns its address.
/// This uses the so-called "CREATE3" workflow,
/// which means that `pointer` is agnostic to `data, and only depends on `salt`.
function writeDeterministic(bytes memory data, bytes32 salt)
internal
returns (address pointer)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(data)
mstore(0x00, _CREATE3_PROXY_INITCODE) // Store the `_PROXY_INITCODE`.
let proxy := create2(0, 0x10, 0x10, salt)
if iszero(proxy) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, proxy) // Store the proxy's address.
// 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
// 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
mstore(0x00, 0xd694)
mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
pointer := keccak256(0x1e, 0x17)
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
if iszero(
mul( // The arguments of `mul` are evaluated last to first.
extcodesize(pointer),
call(gas(), proxy, 0, add(data, 0x15), add(n, 0xb), codesize(), 0x00)
)
) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(data, n) // Restore the length of `data`.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ADDRESS CALCULATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the initialization code hash of the storage contract for `data`.
/// Used for mining vanity addresses with create2crunch.
function initCodeHash(bytes memory data) internal pure returns (bytes32 hash) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(data)
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
returndatacopy(returndatasize(), returndatasize(), gt(n, 0xfffe))
mstore(data, add(0x61000180600a3d393df300, shl(0x40, n)))
hash := keccak256(add(data, 0x15), add(n, 0xb))
mstore(data, n) // Restore the length of `data`.
}
}
/// @dev Equivalent to `predictCounterfactualAddress(data, salt, address(this))`
function predictCounterfactualAddress(bytes memory data, bytes32 salt)
internal
view
returns (address pointer)
{
pointer = predictCounterfactualAddress(data, salt, address(this));
}
/// @dev Returns the CREATE2 address of the storage contract for `data`
/// deployed with `salt` by `deployer`.
/// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
function predictCounterfactualAddress(bytes memory data, bytes32 salt, address deployer)
internal
pure
returns (address predicted)
{
bytes32 hash = initCodeHash(data);
/// @solidity memory-safe-assembly
assembly {
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, hash)
mstore(0x01, shl(96, deployer))
mstore(0x15, salt)
predicted := keccak256(0x00, 0x55)
// Restore the part of the free memory pointer that has been overwritten.
mstore(0x35, 0)
}
}
/// @dev Equivalent to `predictDeterministicAddress(salt, address(this))`.
function predictDeterministicAddress(bytes32 salt) internal view returns (address pointer) {
pointer = predictDeterministicAddress(salt, address(this));
}
/// @dev Returns the "CREATE3" deterministic address for `salt` with `deployer`.
function predictDeterministicAddress(bytes32 salt, address deployer)
internal
pure
returns (address pointer)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, deployer) // Store `deployer`.
mstore8(0x0b, 0xff) // Store the prefix.
mstore(0x20, salt) // Store the salt.
mstore(0x40, CREATE3_PROXY_INITCODE_HASH) // Store the bytecode hash.
mstore(0x14, keccak256(0x0b, 0x55)) // Store the proxy's address.
mstore(0x40, m) // Restore the free memory pointer.
// 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
// 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
mstore(0x00, 0xd694)
mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
pointer := keccak256(0x1e, 0x17)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* READ LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `read(pointer, 0, 2 ** 256 - 1)`.
function read(address pointer) internal view returns (bytes memory data) {
/// @solidity memory-safe-assembly
assembly {
data := mload(0x40)
let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01))
extcodecopy(pointer, add(data, 0x1f), 0x00, add(n, 0x21))
mstore(data, n) // Store the length.
mstore(0x40, add(n, add(data, 0x40))) // Allocate memory.
}
}
/// @dev Equivalent to `read(pointer, start, 2 ** 256 - 1)`.
function read(address pointer, uint256 start) internal view returns (bytes memory data) {
/// @solidity memory-safe-assembly
assembly {
data := mload(0x40)
let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01))
let l := sub(n, and(0xffffff, mul(lt(start, n), start)))
extcodecopy(pointer, add(data, 0x1f), start, add(l, 0x21))
mstore(data, mul(sub(n, start), lt(start, n))) // Store the length.
mstore(0x40, add(data, add(0x40, mload(data)))) // Allocate memory.
}
}
/// @dev Returns a slice of the data on `pointer` from `start` to `end`.
/// `start` and `end` will be clamped to the range `[0, args.length]`.
/// The `pointer` MUST be deployed via the SSTORE2 write functions.
/// Otherwise, the behavior is undefined.
/// Out-of-gas reverts if `pointer` does not have any code.
function read(address pointer, uint256 start, uint256 end)
internal
view
returns (bytes memory data)
{
/// @solidity memory-safe-assembly
assembly {
data := mload(0x40)
if iszero(lt(end, 0xffff)) { end := 0xffff }
let d := mul(sub(end, start), lt(start, end))
extcodecopy(pointer, add(data, 0x1f), start, add(d, 0x01))
if iszero(and(0xff, mload(add(data, d)))) {
let n := sub(extcodesize(pointer), 0x01)
returndatacopy(returndatasize(), returndatasize(), shr(40, n))
d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n))))
}
mstore(data, d) // Store the length.
mstore(add(add(data, 0x20), d), 0) // Zeroize the slot after the bytes.
mstore(0x40, add(add(data, 0x40), d)) // Allocate memory.
}
}
}
// 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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe integer casting library that reverts on overflow.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeCastLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)
/// @dev Optimized for runtime gas for very high number of optimizer runs (i.e. >= 1000000).
library SafeCastLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unable to cast to the target type due to overflow.
error Overflow();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* UNSIGNED INTEGER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Casts `x` to a uint8. Reverts on overflow.
function toUint8(uint256 x) internal pure returns (uint8) {
if (x >= 1 << 8) _revertOverflow();
return uint8(x);
}
/// @dev Casts `x` to a uint16. Reverts on overflow.
function toUint16(uint256 x) internal pure returns (uint16) {
if (x >= 1 << 16) _revertOverflow();
return uint16(x);
}
/// @dev Casts `x` to a uint24. Reverts on overflow.
function toUint24(uint256 x) internal pure returns (uint24) {
if (x >= 1 << 24) _revertOverflow();
return uint24(x);
}
/// @dev Casts `x` to a uint32. Reverts on overflow.
function toUint32(uint256 x) internal pure returns (uint32) {
if (x >= 1 << 32) _revertOverflow();
return uint32(x);
}
/// @dev Casts `x` to a uint40. Reverts on overflow.
function toUint40(uint256 x) internal pure returns (uint40) {
if (x >= 1 << 40) _revertOverflow();
return uint40(x);
}
/// @dev Casts `x` to a uint48. Reverts on overflow.
function toUint48(uint256 x) internal pure returns (uint48) {
if (x >= 1 << 48) _revertOverflow();
return uint48(x);
}
/// @dev Casts `x` to a uint56. Reverts on overflow.
function toUint56(uint256 x) internal pure returns (uint56) {
if (x >= 1 << 56) _revertOverflow();
return uint56(x);
}
/// @dev Casts `x` to a uint64. Reverts on overflow.
function toUint64(uint256 x) internal pure returns (uint64) {
if (x >= 1 << 64) _revertOverflow();
return uint64(x);
}
/// @dev Casts `x` to a uint72. Reverts on overflow.
function toUint72(uint256 x) internal pure returns (uint72) {
if (x >= 1 << 72) _revertOverflow();
return uint72(x);
}
/// @dev Casts `x` to a uint80. Reverts on overflow.
function toUint80(uint256 x) internal pure returns (uint80) {
if (x >= 1 << 80) _revertOverflow();
return uint80(x);
}
/// @dev Casts `x` to a uint88. Reverts on overflow.
function toUint88(uint256 x) internal pure returns (uint88) {
if (x >= 1 << 88) _revertOverflow();
return uint88(x);
}
/// @dev Casts `x` to a uint96. Reverts on overflow.
function toUint96(uint256 x) internal pure returns (uint96) {
if (x >= 1 << 96) _revertOverflow();
return uint96(x);
}
/// @dev Casts `x` to a uint104. Reverts on overflow.
function toUint104(uint256 x) internal pure returns (uint104) {
if (x >= 1 << 104) _revertOverflow();
return uint104(x);
}
/// @dev Casts `x` to a uint112. Reverts on overflow.
function toUint112(uint256 x) internal pure returns (uint112) {
if (x >= 1 << 112) _revertOverflow();
return uint112(x);
}
/// @dev Casts `x` to a uint120. Reverts on overflow.
function toUint120(uint256 x) internal pure returns (uint120) {
if (x >= 1 << 120) _revertOverflow();
return uint120(x);
}
/// @dev Casts `x` to a uint128. Reverts on overflow.
function toUint128(uint256 x) internal pure returns (uint128) {
if (x >= 1 << 128) _revertOverflow();
return uint128(x);
}
/// @dev Casts `x` to a uint136. Reverts on overflow.
function toUint136(uint256 x) internal pure returns (uint136) {
if (x >= 1 << 136) _revertOverflow();
return uint136(x);
}
/// @dev Casts `x` to a uint144. Reverts on overflow.
function toUint144(uint256 x) internal pure returns (uint144) {
if (x >= 1 << 144) _revertOverflow();
return uint144(x);
}
/// @dev Casts `x` to a uint152. Reverts on overflow.
function toUint152(uint256 x) internal pure returns (uint152) {
if (x >= 1 << 152) _revertOverflow();
return uint152(x);
}
/// @dev Casts `x` to a uint160. Reverts on overflow.
function toUint160(uint256 x) internal pure returns (uint160) {
if (x >= 1 << 160) _revertOverflow();
return uint160(x);
}
/// @dev Casts `x` to a uint168. Reverts on overflow.
function toUint168(uint256 x) internal pure returns (uint168) {
if (x >= 1 << 168) _revertOverflow();
return uint168(x);
}
/// @dev Casts `x` to a uint176. Reverts on overflow.
function toUint176(uint256 x) internal pure returns (uint176) {
if (x >= 1 << 176) _revertOverflow();
return uint176(x);
}
/// @dev Casts `x` to a uint184. Reverts on overflow.
function toUint184(uint256 x) internal pure returns (uint184) {
if (x >= 1 << 184) _revertOverflow();
return uint184(x);
}
/// @dev Casts `x` to a uint192. Reverts on overflow.
function toUint192(uint256 x) internal pure returns (uint192) {
if (x >= 1 << 192) _revertOverflow();
return uint192(x);
}
/// @dev Casts `x` to a uint200. Reverts on overflow.
function toUint200(uint256 x) internal pure returns (uint200) {
if (x >= 1 << 200) _revertOverflow();
return uint200(x);
}
/// @dev Casts `x` to a uint208. Reverts on overflow.
function toUint208(uint256 x) internal pure returns (uint208) {
if (x >= 1 << 208) _revertOverflow();
return uint208(x);
}
/// @dev Casts `x` to a uint216. Reverts on overflow.
function toUint216(uint256 x) internal pure returns (uint216) {
if (x >= 1 << 216) _revertOverflow();
return uint216(x);
}
/// @dev Casts `x` to a uint224. Reverts on overflow.
function toUint224(uint256 x) internal pure returns (uint224) {
if (x >= 1 << 224) _revertOverflow();
return uint224(x);
}
/// @dev Casts `x` to a uint232. Reverts on overflow.
function toUint232(uint256 x) internal pure returns (uint232) {
if (x >= 1 << 232) _revertOverflow();
return uint232(x);
}
/// @dev Casts `x` to a uint240. Reverts on overflow.
function toUint240(uint256 x) internal pure returns (uint240) {
if (x >= 1 << 240) _revertOverflow();
return uint240(x);
}
/// @dev Casts `x` to a uint248. Reverts on overflow.
function toUint248(uint256 x) internal pure returns (uint248) {
if (x >= 1 << 248) _revertOverflow();
return uint248(x);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIGNED INTEGER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Casts `x` to a int8. Reverts on overflow.
function toInt8(int256 x) internal pure returns (int8) {
unchecked {
if (((1 << 7) + uint256(x)) >> 8 == uint256(0)) return int8(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int16. Reverts on overflow.
function toInt16(int256 x) internal pure returns (int16) {
unchecked {
if (((1 << 15) + uint256(x)) >> 16 == uint256(0)) return int16(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int24. Reverts on overflow.
function toInt24(int256 x) internal pure returns (int24) {
unchecked {
if (((1 << 23) + uint256(x)) >> 24 == uint256(0)) return int24(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int32. Reverts on overflow.
function toInt32(int256 x) internal pure returns (int32) {
unchecked {
if (((1 << 31) + uint256(x)) >> 32 == uint256(0)) return int32(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int40. Reverts on overflow.
function toInt40(int256 x) internal pure returns (int40) {
unchecked {
if (((1 << 39) + uint256(x)) >> 40 == uint256(0)) return int40(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int48. Reverts on overflow.
function toInt48(int256 x) internal pure returns (int48) {
unchecked {
if (((1 << 47) + uint256(x)) >> 48 == uint256(0)) return int48(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int56. Reverts on overflow.
function toInt56(int256 x) internal pure returns (int56) {
unchecked {
if (((1 << 55) + uint256(x)) >> 56 == uint256(0)) return int56(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int64. Reverts on overflow.
function toInt64(int256 x) internal pure returns (int64) {
unchecked {
if (((1 << 63) + uint256(x)) >> 64 == uint256(0)) return int64(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int72. Reverts on overflow.
function toInt72(int256 x) internal pure returns (int72) {
unchecked {
if (((1 << 71) + uint256(x)) >> 72 == uint256(0)) return int72(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int80. Reverts on overflow.
function toInt80(int256 x) internal pure returns (int80) {
unchecked {
if (((1 << 79) + uint256(x)) >> 80 == uint256(0)) return int80(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int88. Reverts on overflow.
function toInt88(int256 x) internal pure returns (int88) {
unchecked {
if (((1 << 87) + uint256(x)) >> 88 == uint256(0)) return int88(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int96. Reverts on overflow.
function toInt96(int256 x) internal pure returns (int96) {
unchecked {
if (((1 << 95) + uint256(x)) >> 96 == uint256(0)) return int96(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int104. Reverts on overflow.
function toInt104(int256 x) internal pure returns (int104) {
unchecked {
if (((1 << 103) + uint256(x)) >> 104 == uint256(0)) return int104(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int112. Reverts on overflow.
function toInt112(int256 x) internal pure returns (int112) {
unchecked {
if (((1 << 111) + uint256(x)) >> 112 == uint256(0)) return int112(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int120. Reverts on overflow.
function toInt120(int256 x) internal pure returns (int120) {
unchecked {
if (((1 << 119) + uint256(x)) >> 120 == uint256(0)) return int120(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int128. Reverts on overflow.
function toInt128(int256 x) internal pure returns (int128) {
unchecked {
if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int136. Reverts on overflow.
function toInt136(int256 x) internal pure returns (int136) {
unchecked {
if (((1 << 135) + uint256(x)) >> 136 == uint256(0)) return int136(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int144. Reverts on overflow.
function toInt144(int256 x) internal pure returns (int144) {
unchecked {
if (((1 << 143) + uint256(x)) >> 144 == uint256(0)) return int144(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int152. Reverts on overflow.
function toInt152(int256 x) internal pure returns (int152) {
unchecked {
if (((1 << 151) + uint256(x)) >> 152 == uint256(0)) return int152(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int160. Reverts on overflow.
function toInt160(int256 x) internal pure returns (int160) {
unchecked {
if (((1 << 159) + uint256(x)) >> 160 == uint256(0)) return int160(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int168. Reverts on overflow.
function toInt168(int256 x) internal pure returns (int168) {
unchecked {
if (((1 << 167) + uint256(x)) >> 168 == uint256(0)) return int168(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int176. Reverts on overflow.
function toInt176(int256 x) internal pure returns (int176) {
unchecked {
if (((1 << 175) + uint256(x)) >> 176 == uint256(0)) return int176(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int184. Reverts on overflow.
function toInt184(int256 x) internal pure returns (int184) {
unchecked {
if (((1 << 183) + uint256(x)) >> 184 == uint256(0)) return int184(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int192. Reverts on overflow.
function toInt192(int256 x) internal pure returns (int192) {
unchecked {
if (((1 << 191) + uint256(x)) >> 192 == uint256(0)) return int192(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int200. Reverts on overflow.
function toInt200(int256 x) internal pure returns (int200) {
unchecked {
if (((1 << 199) + uint256(x)) >> 200 == uint256(0)) return int200(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int208. Reverts on overflow.
function toInt208(int256 x) internal pure returns (int208) {
unchecked {
if (((1 << 207) + uint256(x)) >> 208 == uint256(0)) return int208(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int216. Reverts on overflow.
function toInt216(int256 x) internal pure returns (int216) {
unchecked {
if (((1 << 215) + uint256(x)) >> 216 == uint256(0)) return int216(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int224. Reverts on overflow.
function toInt224(int256 x) internal pure returns (int224) {
unchecked {
if (((1 << 223) + uint256(x)) >> 224 == uint256(0)) return int224(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int232. Reverts on overflow.
function toInt232(int256 x) internal pure returns (int232) {
unchecked {
if (((1 << 231) + uint256(x)) >> 232 == uint256(0)) return int232(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int240. Reverts on overflow.
function toInt240(int256 x) internal pure returns (int240) {
unchecked {
if (((1 << 239) + uint256(x)) >> 240 == uint256(0)) return int240(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int248. Reverts on overflow.
function toInt248(int256 x) internal pure returns (int248) {
unchecked {
if (((1 << 247) + uint256(x)) >> 248 == uint256(0)) return int248(x);
_revertOverflow();
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* OTHER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Casts `x` to a int8. Reverts on overflow.
function toInt8(uint256 x) internal pure returns (int8) {
if (x >= 1 << 7) _revertOverflow();
return int8(int256(x));
}
/// @dev Casts `x` to a int16. Reverts on overflow.
function toInt16(uint256 x) internal pure returns (int16) {
if (x >= 1 << 15) _revertOverflow();
return int16(int256(x));
}
/// @dev Casts `x` to a int24. Reverts on overflow.
function toInt24(uint256 x) internal pure returns (int24) {
if (x >= 1 << 23) _revertOverflow();
return int24(int256(x));
}
/// @dev Casts `x` to a int32. Reverts on overflow.
function toInt32(uint256 x) internal pure returns (int32) {
if (x >= 1 << 31) _revertOverflow();
return int32(int256(x));
}
/// @dev Casts `x` to a int40. Reverts on overflow.
function toInt40(uint256 x) internal pure returns (int40) {
if (x >= 1 << 39) _revertOverflow();
return int40(int256(x));
}
/// @dev Casts `x` to a int48. Reverts on overflow.
function toInt48(uint256 x) internal pure returns (int48) {
if (x >= 1 << 47) _revertOverflow();
return int48(int256(x));
}
/// @dev Casts `x` to a int56. Reverts on overflow.
function toInt56(uint256 x) internal pure returns (int56) {
if (x >= 1 << 55) _revertOverflow();
return int56(int256(x));
}
/// @dev Casts `x` to a int64. Reverts on overflow.
function toInt64(uint256 x) internal pure returns (int64) {
if (x >= 1 << 63) _revertOverflow();
return int64(int256(x));
}
/// @dev Casts `x` to a int72. Reverts on overflow.
function toInt72(uint256 x) internal pure returns (int72) {
if (x >= 1 << 71) _revertOverflow();
return int72(int256(x));
}
/// @dev Casts `x` to a int80. Reverts on overflow.
function toInt80(uint256 x) internal pure returns (int80) {
if (x >= 1 << 79) _revertOverflow();
return int80(int256(x));
}
/// @dev Casts `x` to a int88. Reverts on overflow.
function toInt88(uint256 x) internal pure returns (int88) {
if (x >= 1 << 87) _revertOverflow();
return int88(int256(x));
}
/// @dev Casts `x` to a int96. Reverts on overflow.
function toInt96(uint256 x) internal pure returns (int96) {
if (x >= 1 << 95) _revertOverflow();
return int96(int256(x));
}
/// @dev Casts `x` to a int104. Reverts on overflow.
function toInt104(uint256 x) internal pure returns (int104) {
if (x >= 1 << 103) _revertOverflow();
return int104(int256(x));
}
/// @dev Casts `x` to a int112. Reverts on overflow.
function toInt112(uint256 x) internal pure returns (int112) {
if (x >= 1 << 111) _revertOverflow();
return int112(int256(x));
}
/// @dev Casts `x` to a int120. Reverts on overflow.
function toInt120(uint256 x) internal pure returns (int120) {
if (x >= 1 << 119) _revertOverflow();
return int120(int256(x));
}
/// @dev Casts `x` to a int128. Reverts on overflow.
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) _revertOverflow();
return int128(int256(x));
}
/// @dev Casts `x` to a int136. Reverts on overflow.
function toInt136(uint256 x) internal pure returns (int136) {
if (x >= 1 << 135) _revertOverflow();
return int136(int256(x));
}
/// @dev Casts `x` to a int144. Reverts on overflow.
function toInt144(uint256 x) internal pure returns (int144) {
if (x >= 1 << 143) _revertOverflow();
return int144(int256(x));
}
/// @dev Casts `x` to a int152. Reverts on overflow.
function toInt152(uint256 x) internal pure returns (int152) {
if (x >= 1 << 151) _revertOverflow();
return int152(int256(x));
}
/// @dev Casts `x` to a int160. Reverts on overflow.
function toInt160(uint256 x) internal pure returns (int160) {
if (x >= 1 << 159) _revertOverflow();
return int160(int256(x));
}
/// @dev Casts `x` to a int168. Reverts on overflow.
function toInt168(uint256 x) internal pure returns (int168) {
if (x >= 1 << 167) _revertOverflow();
return int168(int256(x));
}
/// @dev Casts `x` to a int176. Reverts on overflow.
function toInt176(uint256 x) internal pure returns (int176) {
if (x >= 1 << 175) _revertOverflow();
return int176(int256(x));
}
/// @dev Casts `x` to a int184. Reverts on overflow.
function toInt184(uint256 x) internal pure returns (int184) {
if (x >= 1 << 183) _revertOverflow();
return int184(int256(x));
}
/// @dev Casts `x` to a int192. Reverts on overflow.
function toInt192(uint256 x) internal pure returns (int192) {
if (x >= 1 << 191) _revertOverflow();
return int192(int256(x));
}
/// @dev Casts `x` to a int200. Reverts on overflow.
function toInt200(uint256 x) internal pure returns (int200) {
if (x >= 1 << 199) _revertOverflow();
return int200(int256(x));
}
/// @dev Casts `x` to a int208. Reverts on overflow.
function toInt208(uint256 x) internal pure returns (int208) {
if (x >= 1 << 207) _revertOverflow();
return int208(int256(x));
}
/// @dev Casts `x` to a int216. Reverts on overflow.
function toInt216(uint256 x) internal pure returns (int216) {
if (x >= 1 << 215) _revertOverflow();
return int216(int256(x));
}
/// @dev Casts `x` to a int224. Reverts on overflow.
function toInt224(uint256 x) internal pure returns (int224) {
if (x >= 1 << 223) _revertOverflow();
return int224(int256(x));
}
/// @dev Casts `x` to a int232. Reverts on overflow.
function toInt232(uint256 x) internal pure returns (int232) {
if (x >= 1 << 231) _revertOverflow();
return int232(int256(x));
}
/// @dev Casts `x` to a int240. Reverts on overflow.
function toInt240(uint256 x) internal pure returns (int240) {
if (x >= 1 << 239) _revertOverflow();
return int240(int256(x));
}
/// @dev Casts `x` to a int248. Reverts on overflow.
function toInt248(uint256 x) internal pure returns (int248) {
if (x >= 1 << 247) _revertOverflow();
return int248(int256(x));
}
/// @dev Casts `x` to a int256. Reverts on overflow.
function toInt256(uint256 x) internal pure returns (int256) {
if (int256(x) >= 0) return int256(x);
_revertOverflow();
}
/// @dev Casts `x` to a uint256. Reverts on overflow.
function toUint256(int256 x) internal pure returns (uint256) {
if (x >= 0) return uint256(x);
_revertOverflow();
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function _revertOverflow() private pure {
/// @solidity memory-safe-assembly
assembly {
// Store the function selector of `Overflow()`.
mstore(0x00, 0x35278d12)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount :=
mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount)
internal
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
pragma abicoder v2;
import {PoolId, PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {ERC4626} from "solady/tokens/ERC4626.sol";
import "./Constants.sol";
import "../types/IdleBalance.sol";
import {Oracle} from "../lib/Oracle.sol";
import {RawPoolState} from "../types/PoolState.sol";
import {IBunniHook} from "../interfaces/IBunniHook.sol";
import {IBunniToken} from "../interfaces/IBunniToken.sol";
import {ILiquidityDensityFunction} from "../interfaces/ILiquidityDensityFunction.sol";
/// @title Contains structs shared between multiple contracts
struct QueuedWithdrawal {
uint200 shareAmount;
uint56 unlockTimestamp;
}
/// @notice The storage of BunniHub
/// @member poolState The state of a given pool
/// @member reserve0 The vault share tokens owned in vault0
/// @member reserve1 The vault share tokens owned in vault1
/// @member idleBalance The balance of the token that's in excess. Used when computing the total liquidity.
/// @member nonce The nonce for a given bunniSubspace
/// @member poolIdOfBunniToken The pool ID of a given BunniToken
/// @member queuedWithdrawals The queued withdrawals for a given pool & user
/// @member isPauser The set of addresses that can pause external functions
/// @member referralRewardRecipient The address of the recipient of referral rewards belonging to the default referrer address(0)
/// @member pauseFlags Bit flags for pausing external functions
/// @member unpauseFuse Can be permanently set to true to unpause all external functions
struct HubStorage {
mapping(PoolId poolId => RawPoolState) poolState;
mapping(PoolId poolId => uint256) reserve0;
mapping(PoolId poolId => uint256) reserve1;
mapping(PoolId poolId => IdleBalance) idleBalance;
mapping(bytes32 bunniSubspace => uint24) nonce;
mapping(IBunniToken bunniToken => PoolId) poolIdOfBunniToken;
mapping(PoolId poolId => mapping(address => QueuedWithdrawal)) queuedWithdrawals;
mapping(address guy => bool) isPauser;
address referralRewardRecipient;
uint8 pauseFlags;
bool unpauseFuse;
}
/// @notice The decoded hook params for a given pool
/// @member feeMin The minimum swap fee, 6 decimals
/// @member feeMax The maximum swap fee (may be exceeded if surge fee is active), 6 decimals
/// @member feeQuadraticMultiplier The quadratic multiplier for the dynamic swap fee formula, 6 decimals
/// @member feeTwapSecondsAgo The time window for the TWAP used by the dynamic swap fee formula
/// @member maxAmAmmFee The maximum swap fee that can be set by the am-AMM manager. Must <= MAX_AMAMM_FEE.
/// @member surgeFeeHalfLife The half-life of the surge fee in seconds. The surge fee decays exponentially, and the half-life is the time it takes for the surge fee to decay to half its value.
/// @member surgeFeeAutostartThreshold Time after a swap when the surge fee exponential decay autostarts, in seconds. The autostart avoids the pool being stuck on a high fee.
/// @member vaultSurgeThreshold0 The threshold for the vault0 share price change to trigger the surge fee. Only used if both vaults are set.
/// 1 / vaultSurgeThreshold is the minimum percentage change in the vault share price to trigger the surge fee.
/// @member vaultSurgeThreshold1 The threshold for the vault1 share price change to trigger the surge fee. Only used if both vaults are set.
/// 1 / vaultSurgeThreshold is the minimum percentage change in the vault share price to trigger the surge fee.
/// @member rebalanceThreshold The threshold for triggering a rebalance from excess liquidity.
/// 1 / rebalanceThreshold is the minimum ratio of excess tokens to the target token amount (when the spot price is at TWAP) to trigger a rebalance.
/// When set to 0, rebalancing is disabled.
/// @member rebalanceMaxSlippage The maximum slippage (vs TWAP) allowed during rebalancing, 5 decimals. At most MAX_REBALANCE_MAX_SLIPPAGE.
/// @member rebalanceTwapSecondsAgo The time window for the TWAP used during rebalancing. At most MAX_REBALANCE_TWAP_SECONDS_AGO.
/// @member rebalanceOrderTTL The time-to-live for a rebalance order, in seconds. At most MAX_REBALANCE_ORDER_TTL.
/// @member amAmmEnabled Whether the am-AMM is enabled for this pool
/// @member oracleMinInterval The minimum interval between TWAP oracle updates, in seconds
/// @member minRentMultiplier The multiplier applied to the BunniToken total supply to compute the minimum rent. 18 decimals. Must be > 0 unless amAmmEnabled == false.
struct DecodedHookParams {
uint24 feeMin;
uint24 feeMax;
uint24 feeQuadraticMultiplier;
uint24 feeTwapSecondsAgo;
uint24 maxAmAmmFee;
uint16 surgeFeeHalfLife;
uint16 surgeFeeAutostartThreshold;
uint16 vaultSurgeThreshold0;
uint16 vaultSurgeThreshold1;
uint16 rebalanceThreshold;
uint16 rebalanceMaxSlippage;
uint16 rebalanceTwapSecondsAgo;
uint16 rebalanceOrderTTL;
bool amAmmEnabled;
uint32 oracleMinInterval;
uint48 minRentMultiplier;
}
/// @notice Contains mappings used by both BunniHook and BunniLogic. Makes passing
/// mappings to BunniHookLogic easier & cheaper.
/// @member observations The list of observations for a given pool ID
/// @member states The current TWAP oracle state for a given pool ID
/// @member rebalanceOrderHash The hash of the currently active rebalance order
/// @member rebalanceOrderPermit2Hash The Permit2 hash that's verified when BunniHook.isValidSignature() is called
/// @member rebalanceOrderDeadline The deadline for the currently active rebalance order
/// @member vaultSharePricesAtLastSwap The share prices of the vaults used by the pool at the last swap
/// @member ldfStates The LDF state for a given pool ID
/// @member slot0s The slot0 state for a given pool ID
struct HookStorage {
mapping(PoolId => Oracle.Observation[MAX_CARDINALITY]) observations;
mapping(PoolId => IBunniHook.ObservationState) states;
mapping(PoolId id => bytes32) rebalanceOrderHash;
mapping(PoolId id => bytes32) rebalanceOrderPermit2Hash;
mapping(PoolId id => uint256) rebalanceOrderDeadline;
mapping(PoolId => VaultSharePrices) vaultSharePricesAtLastSwap;
mapping(PoolId => bytes32) ldfStates;
mapping(PoolId => Slot0) slot0s;
}
/// @notice The slot0 state of a given pool
/// @member sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (currency1/currency0)
/// @member tick The log base 1.0001 of the ratio of the two assets (currency1/currency0)
/// @member lastSwapTimestamp The timestamp of the last swap (or rebalance execution)
/// @member lastSurgeTimestamp The timestamp of the last surge
struct Slot0 {
uint160 sqrtPriceX96;
int24 tick;
uint32 lastSwapTimestamp;
uint32 lastSurgeTimestamp;
}
/// @notice Tracks the share prices of vaults used by a pool using vaults for both currencies. Used for computing surges.
/// @member initialized True if the share prices have been initialized
/// @member sharePrice0 The underlying assets each share of vault0 represents, scaled by 1e18
/// @member sharePrice1 The underlying assets each share of vault1 represents, scaled by 1e18
struct VaultSharePrices {
bool initialized;
uint120 sharePrice0;
uint120 sharePrice1;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "./SafeCast.sol";
import {FullMath} from "./FullMath.sol";
import {UnsafeMath} from "./UnsafeMath.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
using SafeCast for uint256;
error InvalidPriceOrLiquidity();
error InvalidPrice();
error NotEnoughLiquidity();
error PriceOverflow();
/// @notice Gets the next sqrt price given a delta of currency0
/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
/// price less in order to not send too much output.
/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
/// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of currency0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of currency0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
internal
pure
returns (uint160)
{
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96;
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
if (add) {
unchecked {
uint256 product = amount * sqrtPX96;
if (product / amount == sqrtPX96) {
uint256 denominator = numerator1 + product;
if (denominator >= numerator1) {
// always fits in 160 bits
return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
}
}
}
// denominator is checked for overflow
return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));
} else {
unchecked {
uint256 product = amount * sqrtPX96;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
// equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow();
assembly ("memory-safe") {
if iszero(
and(
eq(div(product, amount), and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
gt(numerator1, product)
)
) {
mstore(0, 0xf5c787f1) // selector for PriceOverflow()
revert(0x1c, 0x04)
}
}
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
}
/// @notice Gets the next sqrt price given a delta of currency1
/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
/// price less in order to not send too much output.
/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
/// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of currency1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of currency1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
internal
pure
returns (uint160)
{
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (add) {
uint256 quotient = (
amount <= type(uint160).max
? (amount << FixedPoint96.RESOLUTION) / liquidity
: FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
);
return (uint256(sqrtPX96) + quotient).toUint160();
} else {
uint256 quotient = (
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
: FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
);
// equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity();
assembly ("memory-safe") {
if iszero(gt(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff), quotient)) {
mstore(0, 0x4323a555) // selector for NotEnoughLiquidity()
revert(0x1c, 0x04)
}
}
// always fits 160 bits
unchecked {
return uint160(sqrtPX96 - quotient);
}
}
}
/// @notice Gets the next sqrt price given an input amount of currency0 or currency1
/// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
/// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
/// @param liquidity The amount of usable liquidity
/// @param amountIn How much of currency0, or currency1, is being swapped in
/// @param zeroForOne Whether the amount in is currency0 or currency1
/// @return uint160 The price after adding the input amount to currency0 or currency1
function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne)
internal
pure
returns (uint160)
{
// equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
assembly ("memory-safe") {
if or(
iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
) {
mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
revert(0x1c, 0x04)
}
}
// round to make sure that we don't pass the target price
return zeroForOne
? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
: getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
}
/// @notice Gets the next sqrt price given an output amount of currency0 or currency1
/// @dev Throws if price or liquidity are 0 or the next price is out of bounds
/// @param sqrtPX96 The starting price before accounting for the output amount
/// @param liquidity The amount of usable liquidity
/// @param amountOut How much of currency0, or currency1, is being swapped out
/// @param zeroForOne Whether the amount out is currency1 or currency0
/// @return uint160 The price after removing the output amount of currency0 or currency1
function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne)
internal
pure
returns (uint160)
{
// equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
assembly ("memory-safe") {
if or(
iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
) {
mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
revert(0x1c, 0x04)
}
}
// round to make sure that we pass the target price
return zeroForOne
? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
: getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
}
/// @notice Gets the amount0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return uint256 Amount of currency0 required to cover a position of size liquidity between the two passed prices
function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
internal
pure
returns (uint256)
{
unchecked {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
// equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice();
assembly ("memory-safe") {
if iszero(and(sqrtPriceAX96, 0xffffffffffffffffffffffffffffffffffffffff)) {
mstore(0, 0x00bfc921) // selector for InvalidPrice()
revert(0x1c, 0x04)
}
}
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96;
return roundUp
? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96)
: FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96;
}
}
/// @notice Equivalent to: `a >= b ? a - b : b - a`
function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {
assembly ("memory-safe") {
let diff :=
sub(and(a, 0xffffffffffffffffffffffffffffffffffffffff), and(b, 0xffffffffffffffffffffffffffffffffffffffff))
// mask = 0 if a >= b else -1 (all 1s)
let mask := sar(255, diff)
// if a >= b, res = a - b = 0 ^ (a - b)
// if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)
// either way, res = mask ^ (a - b + mask)
res := xor(mask, add(mask, diff))
}
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices
function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
internal
pure
returns (uint256 amount1)
{
uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96);
uint256 denominator = FixedPoint96.Q96;
uint256 _liquidity = uint256(liquidity);
/**
* Equivalent to:
* amount1 = roundUp
* ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96)
* : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
* Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
*/
amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);
assembly ("memory-safe") {
amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))
}
}
/// @notice Helper that gets signed currency0 delta
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount0 delta
/// @return int256 Amount of currency0 corresponding to the passed liquidityDelta between the two prices
function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
internal
pure
returns (int256)
{
unchecked {
return liquidity < 0
? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
: -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
}
}
/// @notice Helper that gets signed currency1 delta
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount1 delta
/// @return int256 Amount of currency1 corresponding to the passed liquidityDelta between the two prices
function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
internal
pure
returns (int256)
{
unchecked {
return liquidity < 0
? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
: -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import {subReLU} from "./Math.sol";
import {SqrtPriceMath} from "./SqrtPriceMath.sol";
/// @title Computes the result of a swap within ticks
/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
library SwapMath {
uint24 internal constant MAX_SWAP_FEE = 1e6;
/// @dev A minimum fee amount is applied to protect against exact input vs exact output rate mismatches when swap amounts/liquidity are small.
uint256 internal constant MIN_FEE_AMOUNT = 1e3;
/// @notice Computes the sqrt price target for the next swap step
/// @param zeroForOne The direction of the swap, true for currency0 to currency1, false for currency1 to currency0
/// @param sqrtPriceNextX96 The Q64.96 sqrt price for the next initialized tick
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value
/// after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @return sqrtPriceTargetX96 The price target for the next swap step
function getSqrtPriceTarget(bool zeroForOne, uint160 sqrtPriceNextX96, uint160 sqrtPriceLimitX96)
internal
pure
returns (uint160 sqrtPriceTargetX96)
{
assembly ("memory-safe") {
// a flag to toggle between sqrtPriceNextX96 and sqrtPriceLimitX96
// when zeroForOne == true, nextOrLimit reduces to sqrtPriceNextX96 >= sqrtPriceLimitX96
// sqrtPriceTargetX96 = max(sqrtPriceNextX96, sqrtPriceLimitX96)
// when zeroForOne == false, nextOrLimit reduces to sqrtPriceNextX96 < sqrtPriceLimitX96
// sqrtPriceTargetX96 = min(sqrtPriceNextX96, sqrtPriceLimitX96)
sqrtPriceNextX96 := and(sqrtPriceNextX96, 0xffffffffffffffffffffffffffffffffffffffff)
sqrtPriceLimitX96 := and(sqrtPriceLimitX96, 0xffffffffffffffffffffffffffffffffffffffff)
let nextOrLimit := xor(lt(sqrtPriceNextX96, sqrtPriceLimitX96), and(zeroForOne, 0x1))
let symDiff := xor(sqrtPriceNextX96, sqrtPriceLimitX96)
sqrtPriceTargetX96 := xor(sqrtPriceLimitX96, mul(symDiff, nextOrLimit))
}
}
/// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
/// @dev If the swap's amountSpecified is negative, the combined fee and input amount will never exceed the absolute value of the remaining amount.
/// @param sqrtPriceCurrentX96 The current sqrt price of the pool
/// @param sqrtPriceTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
/// @param liquidity The usable liquidity
/// @param amountRemaining How much input or output amount is remaining to be swapped in/out
/// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
/// @return sqrtPriceNextX96 The price after swapping the amount in/out, not to exceed the price target
/// @return amountIn The amount to be swapped in, of either currency0 or currency1, based on the direction of the swap
/// @return amountOut The amount to be received, of either currency0 or currency1, based on the direction of the swap
/// @dev feePips must be no larger than MAX_SWAP_FEE for this function. We ensure that before setting a fee using LPFeeLibrary.isValid.
function computeSwapStep(
uint160 sqrtPriceCurrentX96,
uint160 sqrtPriceTargetX96,
uint256 liquidity,
int256 amountRemaining,
uint24 feePips
) internal pure returns (uint160 sqrtPriceNextX96, uint256 amountIn, uint256 amountOut) {
bool exactIn = amountRemaining < 0;
uint256 feeAmount;
unchecked {
uint256 _feePips = feePips; // upcast once and cache
bool zeroForOne = sqrtPriceCurrentX96 >= sqrtPriceTargetX96;
if (exactIn) {
uint256 amountRemainingLessFee = FixedPointMathLib.min(
FullMath.mulDiv(uint256(-amountRemaining), MAX_SWAP_FEE - _feePips, MAX_SWAP_FEE),
subReLU(uint256(-amountRemaining), MIN_FEE_AMOUNT)
);
amountIn = zeroForOne
? SqrtPriceMath.getAmount0Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, true)
: SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, true);
if (amountRemainingLessFee >= amountIn) {
// `amountIn` is capped by the target price
sqrtPriceNextX96 = sqrtPriceTargetX96;
feeAmount = _feePips == MAX_SWAP_FEE
? amountIn // amountIn is always 0 here, as amountRemainingLessFee == 0 and amountRemainingLessFee >= amountIn
: FixedPointMathLib.max(
FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_SWAP_FEE - _feePips), MIN_FEE_AMOUNT
);
} else {
// exhaust the remaining amount
amountIn = amountRemainingLessFee;
sqrtPriceNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
sqrtPriceCurrentX96, liquidity, amountRemainingLessFee, zeroForOne
);
// we didn't reach the target, so take the remainder of the maximum input as fee
feeAmount = FixedPointMathLib.max(uint256(-amountRemaining) - amountIn, MIN_FEE_AMOUNT);
}
amountOut = zeroForOne
? SqrtPriceMath.getAmount1Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, false)
: SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, false);
} else {
amountOut = zeroForOne
? SqrtPriceMath.getAmount1Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, false)
: SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, false);
if (uint256(amountRemaining) >= amountOut) {
// `amountOut` is capped by the target price
sqrtPriceNextX96 = sqrtPriceTargetX96;
} else {
// cap the output amount to not exceed the remaining output amount
amountOut = uint256(amountRemaining);
sqrtPriceNextX96 =
SqrtPriceMath.getNextSqrtPriceFromOutput(sqrtPriceCurrentX96, liquidity, amountOut, zeroForOne);
}
amountIn = zeroForOne
? SqrtPriceMath.getAmount0Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, true)
: SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, true);
// `feePips` cannot be `MAX_SWAP_FEE` for exact out
feeAmount = FixedPointMathLib.max(
FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_SWAP_FEE - _feePips), MIN_FEE_AMOUNT
);
}
}
// add fee back into amountIn
// ensure that amountIn <= |amountRemaining| if exactIn
if (exactIn) amountIn = FixedPointMathLib.min(amountIn + feeAmount, uint256(-amountRemaining));
else amountIn += feeAmount;
}
}
// 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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 will return 0, and should be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly ("memory-safe") {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
/// @notice Calculates floor(a×b÷denominator)
/// @dev division by 0 will return 0, and should be checked externally
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result, floor(a×b÷denominator)
function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
assembly ("memory-safe") {
result := div(mul(a, b), denominator)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {ERC4626} from "solady/tokens/ERC4626.sol";
function getReservesInUnderlying(uint256 reserveAmount, ERC4626 vault) view returns (uint256) {
return address(vault) == address(0) ? reserveAmount : vault.previewRedeem(reserveAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {ERC20} from "./ERC20.sol";
/// @notice Simple Wrapped Ether implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/WETH.sol)
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/WETH.sol)
/// @author Inspired by WETH9 (https://github.com/dapphub/ds-weth/blob/master/src/weth9.sol)
contract WETH is ERC20 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 METADATA */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the name of the token.
function name() public view virtual override returns (string memory) {
return "Wrapped Ether";
}
/// @dev Returns the symbol of the token.
function symbol() public view virtual override returns (string memory) {
return "WETH";
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* WETH */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Deposits `amount` ETH of the caller and mints `amount` WETH to the caller.
function deposit() public payable virtual {
_mint(msg.sender, msg.value);
}
/// @dev Burns `amount` WETH of the caller and sends `amount` ETH to the caller.
function withdraw(uint256 amount) public virtual {
_burn(msg.sender, amount);
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and check if it succeeded or not.
if iszero(call(gas(), caller(), amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Equivalent to `deposit()`.
receive() external payable virtual {
deposit();
}
}
{
"compilationTarget": {
"src/BunniHook.sol": "BunniHook"
},
"evmVersion": "cancun",
"libraries": {
"src/lib/BunniHookLogic.sol:BunniHookLogic": "0x11f2ee6b0fc6367efae53e0a33ee6216974a0f81",
"src/lib/BunniSwapMath.sol:BunniSwapMath": "0x00000000af7929ae27a7aa6e9eb68fe0f10bba88",
"src/lib/RebalanceLogic.sol:RebalanceLogic": "0x000000005bea54b06ba1376474cf0df55f608200"
},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 7500
},
"remappings": [
":@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
":@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
":@uniswap/v4-core/=lib/v4-core/",
":biddog/=lib/biddog/src/",
":clones-with-immutable-args/=lib/clones-with-immutable-args/src/",
":create3-factory/=lib/create3-factory/",
":ds-test/=lib/clones-with-immutable-args/lib/ds-test/src/",
":erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
":flood-contracts/=lib/flood-contracts/",
":forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
":forge-std/=lib/forge-std/src/",
":hardhat/=lib/v4-core/node_modules/hardhat/",
":leb128-nooffset/=lib/flood-contracts/lib/leb128-nooffset/src/",
":leb128/=lib/flood-contracts/lib/leb128-nooffset/src/",
":multicaller/=lib/multicaller/src/",
":openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
":permit2/=lib/permit2/",
":solady/=lib/solady/src/",
":solmate/src/=lib/solmate/src/",
":solmate/utils/=lib/solmate/src/utils/",
":v4-core/=lib/v4-core/src/"
],
"viaIR": true
}
[{"inputs":[{"internalType":"contract IPoolManager","name":"poolManager_","type":"address"},{"internalType":"contract IBunniHub","name":"hub_","type":"address"},{"internalType":"contract IFloodPlain","name":"floodPlain_","type":"address"},{"internalType":"contract WETH","name":"weth_","type":"address"},{"internalType":"contract IZone","name":"floodZone_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"address","name":"hookFeeRecipient_","type":"address"},{"internalType":"uint32","name":"hookFeeModifier_","type":"uint32"},{"internalType":"uint32","name":"referralRewardModifier_","type":"uint32"},{"internalType":"uint48","name":"k_","type":"uint48"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AlreadyInitialized","type":"error"},{"inputs":[],"name":"AmAmm__BidLocked","type":"error"},{"inputs":[],"name":"AmAmm__InvalidBid","type":"error"},{"inputs":[],"name":"AmAmm__InvalidDepositAmount","type":"error"},{"inputs":[],"name":"AmAmm__NotEnabled","type":"error"},{"inputs":[],"name":"AmAmm__Unauthorized","type":"error"},{"inputs":[],"name":"BunniHook__InvalidModifier","type":"error"},{"inputs":[],"name":"BunniHook__InvalidRebalanceOrderHash","type":"error"},{"inputs":[],"name":"BunniHook__PrehookPostConditionFailed","type":"error"},{"inputs":[],"name":"BunniHook__Unauthorized","type":"error"},{"inputs":[],"name":"NewOwnerIsZeroAddress","type":"error"},{"inputs":[],"name":"NoHandoverRequest","type":"error"},{"inputs":[],"name":"NotPoolManager","type":"error"},{"inputs":[],"name":"OracleCardinalityCannotBeZero","type":"error"},{"inputs":[],"name":"ReentrancyGuard__ReentrantCall","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"Currency","name":"currency","type":"address"},{"indexed":true,"internalType":"address","name":"manager","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"fees","type":"uint256"}],"name":"ClaimFees","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"Currency[]","name":"currencyList","type":"address[]"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"}],"name":"ClaimProtocolFees","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"manager","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"refund","type":"uint256"}],"name":"ClaimRefund","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"manager","type":"address"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"DepositIntoNextBid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"manager","type":"address"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"DepositIntoTopBid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"manager","type":"address"},{"indexed":false,"internalType":"uint128","name":"additionalRent","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"updatedDeposit","type":"uint128"},{"indexed":false,"internalType":"bool","name":"topBid","type":"bool"},{"indexed":true,"internalType":"address","name":"withdrawRecipient","type":"address"},{"indexed":false,"internalType":"uint128","name":"amountDeposited","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"amountWithdrawn","type":"uint128"}],"name":"IncreaseBidRent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipHandoverCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipHandoverRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"manager","type":"address"},{"indexed":false,"internalType":"bytes6","name":"payload","type":"bytes6"},{"indexed":false,"internalType":"bool","name":"topBid","type":"bool"}],"name":"SetBidPayload","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"hookFeeRecipient","type":"address"}],"name":"SetHookFeeRecipient","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint32","name":"hookFeeModifier","type":"uint32"},{"indexed":true,"internalType":"uint32","name":"referrerRewardModifier","type":"uint32"}],"name":"SetModifiers","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":false,"internalType":"bool","name":"unblocked","type":"bool"}],"name":"SetWithdrawalUnblocked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract IZone","name":"zone","type":"address"}],"name":"SetZone","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"manager","type":"address"},{"indexed":true,"internalType":"uint48","name":"blockIdx","type":"uint48"},{"indexed":false,"internalType":"bytes6","name":"payload","type":"bytes6"},{"indexed":false,"internalType":"uint128","name":"rent","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"deposit","type":"uint128"}],"name":"SubmitBid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"bool","name":"exactIn","type":"bool"},{"indexed":false,"internalType":"bool","name":"zeroForOne","type":"bool"},{"indexed":false,"internalType":"uint256","name":"inputAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"outputAmount","type":"uint256"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"indexed":false,"internalType":"int24","name":"tick","type":"int24"},{"indexed":false,"internalType":"uint24","name":"fee","type":"uint24"},{"indexed":false,"internalType":"uint256","name":"totalLiquidity","type":"uint256"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"manager","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"WithdrawFromNextBid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"manager","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"WithdrawFromTopBid","type":"event"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"int24","name":"tick","type":"int24"}],"name":"afterInitialize","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IPoolManager.SwapParams","name":"params","type":"tuple"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"beforeSwap","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"},{"internalType":"BeforeSwapDelta","name":"","type":"int256"},{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"},{"internalType":"address","name":"manager","type":"address"},{"internalType":"bytes6","name":"payload","type":"bytes6"},{"internalType":"uint128","name":"rent","type":"uint128"},{"internalType":"uint128","name":"deposit","type":"uint128"}],"name":"bid","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"}],"name":"canWithdraw","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"cancelOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"},{"internalType":"address","name":"recipient","type":"address"}],"name":"claimFees","outputs":[{"internalType":"uint256","name":"fees","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"Currency[]","name":"currencyList","type":"address[]"}],"name":"claimProtocolFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"},{"internalType":"address","name":"recipient","type":"address"}],"name":"claimRefund","outputs":[{"internalType":"uint256","name":"refund","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"pendingOwner","type":"address"}],"name":"completeOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"},{"internalType":"uint128","name":"amount","type":"uint128"}],"name":"depositIntoNextBid","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"},{"internalType":"uint128","name":"amount","type":"uint128"}],"name":"depositIntoTopBid","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"}],"name":"getAmAmmEnabled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"Currency[]","name":"currencyList","type":"address[]"}],"name":"getClaimableHookFees","outputs":[{"internalType":"uint256[]","name":"feeAmounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"manager","type":"address"},{"internalType":"Currency","name":"currency","type":"address"}],"name":"getFees","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getHookFeeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getModifiers","outputs":[{"internalType":"uint32","name":"hookFeeModifier_","type":"uint32"},{"internalType":"uint32","name":"referralRewardModifier_","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"}],"name":"getNextBid","outputs":[{"components":[{"internalType":"address","name":"manager","type":"address"},{"internalType":"uint48","name":"blockIdx","type":"uint48"},{"internalType":"bytes6","name":"payload","type":"bytes6"},{"internalType":"uint128","name":"rent","type":"uint128"},{"internalType":"uint128","name":"deposit","type":"uint128"}],"internalType":"struct IAmAmm.Bid","name":"nextBid","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"}],"name":"getNextBidWrite","outputs":[{"components":[{"internalType":"address","name":"manager","type":"address"},{"internalType":"uint48","name":"blockIdx","type":"uint48"},{"internalType":"bytes6","name":"payload","type":"bytes6"},{"internalType":"uint128","name":"rent","type":"uint128"},{"internalType":"uint128","name":"deposit","type":"uint128"}],"internalType":"struct IAmAmm.Bid","name":"","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getObservation","outputs":[{"components":[{"internalType":"uint32","name":"blockTimestamp","type":"uint32"},{"internalType":"int24","name":"prevTick","type":"int24"},{"internalType":"int56","name":"tickCumulative","type":"int56"},{"internalType":"bool","name":"initialized","type":"bool"}],"internalType":"struct Oracle.Observation","name":"observation","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"manager","type":"address"},{"internalType":"PoolId","name":"id","type":"bytes32"}],"name":"getRefund","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"manager","type":"address"},{"internalType":"PoolId","name":"id","type":"bytes32"}],"name":"getRefundWrite","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"getState","outputs":[{"components":[{"internalType":"uint32","name":"index","type":"uint32"},{"internalType":"uint32","name":"cardinality","type":"uint32"},{"internalType":"uint32","name":"cardinalityNext","type":"uint32"},{"components":[{"internalType":"uint32","name":"blockTimestamp","type":"uint32"},{"internalType":"int24","name":"prevTick","type":"int24"},{"internalType":"int56","name":"tickCumulative","type":"int56"},{"internalType":"bool","name":"initialized","type":"bool"}],"internalType":"struct Oracle.Observation","name":"intermediateObservation","type":"tuple"}],"internalType":"struct IBunniHook.ObservationState","name":"state","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"}],"name":"getTopBid","outputs":[{"components":[{"internalType":"address","name":"manager","type":"address"},{"internalType":"uint48","name":"blockIdx","type":"uint48"},{"internalType":"bytes6","name":"payload","type":"bytes6"},{"internalType":"uint128","name":"rent","type":"uint128"},{"internalType":"uint128","name":"deposit","type":"uint128"}],"internalType":"struct IAmAmm.Bid","name":"topBid","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"}],"name":"getTopBidWrite","outputs":[{"components":[{"internalType":"address","name":"manager","type":"address"},{"internalType":"uint48","name":"blockIdx","type":"uint48"},{"internalType":"bytes6","name":"payload","type":"bytes6"},{"internalType":"uint128","name":"rent","type":"uint128"},{"internalType":"uint128","name":"deposit","type":"uint128"}],"internalType":"struct IAmAmm.Bid","name":"","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"},{"internalType":"uint128","name":"additionalRent","type":"uint128"},{"internalType":"uint128","name":"updatedDeposit","type":"uint128"},{"internalType":"bool","name":"topBid","type":"bool"},{"internalType":"address","name":"withdrawRecipient","type":"address"}],"name":"increaseBidRent","outputs":[{"internalType":"uint128","name":"amountDeposited","type":"uint128"},{"internalType":"uint128","name":"amountWithdrawn","type":"uint128"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint32","name":"cardinalityNext","type":"uint32"}],"name":"increaseCardinalityNext","outputs":[{"internalType":"uint32","name":"cardinalityNextOld","type":"uint32"},{"internalType":"uint32","name":"cardinalityNextNew","type":"uint32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"hookParams","type":"bytes"}],"name":"isValidParams","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes32","name":"hash","type":"bytes32"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"isValidSignature","outputs":[{"internalType":"bytes4","name":"magicValue","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"}],"name":"ldfStates","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint32[]","name":"secondsAgos","type":"uint32[]"}],"name":"observe","outputs":[{"internalType":"int56[]","name":"tickCumulatives","type":"int56[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"result","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pendingOwner","type":"address"}],"name":"ownershipHandoverExpiresAt","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"Currency","name":"currency","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"internalType":"struct IBunniHook.RebalanceOrderPreHookArgs","name":"preHookArgs","type":"tuple"},{"components":[{"internalType":"Currency","name":"currency","type":"address"}],"internalType":"struct IBunniHook.RebalanceOrderPostHookArgs","name":"postHookArgs","type":"tuple"}],"internalType":"struct IBunniHook.RebalanceOrderHookArgs","name":"hookArgs","type":"tuple"}],"name":"rebalanceOrderPostHook","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"Currency","name":"currency","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"internalType":"struct IBunniHook.RebalanceOrderPreHookArgs","name":"preHookArgs","type":"tuple"},{"components":[{"internalType":"Currency","name":"currency","type":"address"}],"internalType":"struct IBunniHook.RebalanceOrderPostHookArgs","name":"postHookArgs","type":"tuple"}],"internalType":"struct IBunniHook.RebalanceOrderHookArgs","name":"hookArgs","type":"tuple"}],"name":"rebalanceOrderPreHook","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"requestOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"},{"internalType":"bytes6","name":"payload","type":"bytes6"},{"internalType":"bool","name":"topBid","type":"bool"}],"name":"setBidPayload","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newHookFeeRecipient","type":"address"}],"name":"setHookFeeRecipient","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"newHookFeeModifier","type":"uint32"},{"internalType":"uint32","name":"newReferralRewardModifier","type":"uint32"}],"name":"setModifiers","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"},{"internalType":"bool","name":"unblocked","type":"bool"}],"name":"setWithdrawalUnblocked","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IZone","name":"zone","type":"address"}],"name":"setZone","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"}],"name":"slot0s","outputs":[{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"int24","name":"tick","type":"int24"},{"internalType":"uint32","name":"lastSwapTimestamp","type":"uint32"},{"internalType":"uint32","name":"lastSurgeTimestamp","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"unlockCallback","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"},{"internalType":"bytes32","name":"newState","type":"bytes32"}],"name":"updateLdfState","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"}],"name":"updateStateMachine","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"}],"name":"vaultSharePricesAtLastSwap","outputs":[{"internalType":"bool","name":"initialized","type":"bool"},{"internalType":"uint120","name":"sharePrice0","type":"uint120"},{"internalType":"uint120","name":"sharePrice1","type":"uint120"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"},{"internalType":"uint128","name":"amount","type":"uint128"},{"internalType":"address","name":"recipient","type":"address"}],"name":"withdrawFromNextBid","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"id","type":"bytes32"},{"internalType":"uint128","name":"amount","type":"uint128"},{"internalType":"address","name":"recipient","type":"address"}],"name":"withdrawFromTopBid","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]