Verified contractExactMIT
EurekaBexFixedTriangleCatalogUnion
Address0x852d6bb46309bf54a2ef87d7eb18c56b93354292
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 1,000 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,111,798
- Creation transaction
- 0xf950abb809…eae7d0b662
28 files
- src/bex/EurekaBexFixedTriangleCatalogUnion.solmain44.24 KB
- src/bex/BexBatchQuoter.sol7.99 KB
- src/bex/BexCycleData.sol458 B
- src/bex/BexCycleQuoter.sol17.21 KB
- src/bex/BexCycleSizing.sol1.99 KB
- src/bex/BexSelectedCatalogValidator.sol3.71 KB
- src/bex/EurekaBexBatch.sol12.86 KB
- src/interfaces/uniswapv3/IUniswapV3Pool.sol777 B
- src/interfaces/uniswapv3/IUniswapV3PoolActions.sol5.95 KB
- src/interfaces/uniswapv3/IUniswapV3PoolDerivedState.sol2.46 KB
- src/interfaces/uniswapv3/IUniswapV3PoolEvents.sol5.54 KB
- src/interfaces/uniswapv3/IUniswapV3PoolImmutables.sol1.74 KB
- src/interfaces/uniswapv3/IUniswapV3PoolOwnerActions.sol1.13 KB
- src/interfaces/uniswapv3/IUniswapV3PoolState.sol6.03 KB
- src/libraries/uniswapv3/BitMath.sol2.78 KB
- src/libraries/uniswapv3/FixedPoint96.sol375 B
- src/libraries/uniswapv3/FullMath.sol5.32 KB
- src/libraries/uniswapv3/LiquidityMath.sol609 B
- src/libraries/uniswapv3/LowGasSafeMath.sol1.68 KB
- src/libraries/uniswapv3/SafeCast.sol1.04 KB
- src/libraries/uniswapv3/SqrtPriceMath.sol12.52 KB
- src/libraries/uniswapv3/SwapMath.sol5.61 KB
- src/libraries/uniswapv3/Tick.sol9.37 KB
- src/libraries/uniswapv3/TickBitmap.sol4.85 KB
- src/libraries/uniswapv3/TickMath.sol8.63 KB
- src/libraries/uniswapv3/UnsafeMath.sol647 B
- src/liquidations/compoundv2/common/IUniswapV3Quoter.sol1.93 KB
- src/liquidations/compoundv2/common/quoters/UniswapV3Quoter/UniswapV3QuoterBase.sol11.29 KB
src/bex/EurekaBexFixedTriangleCatalogUnion.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {BexCycleData} from "./BexCycleData.sol";
import {BexCycleQuoter} from "./BexCycleQuoter.sol";
import {BexSelectedCatalogValidator} from "./BexSelectedCatalogValidator.sol";
import {BexCycleSizing} from "./BexCycleSizing.sol";
import {IBatchToken, IBatchIdentity, IBatchFactory, IBatchSwapV3} from "./EurekaBexBatch.sol";
import {IUniswapV3Pool} from "src/interfaces/uniswapv3/IUniswapV3Pool.sol";
import {FullMath} from "src/libraries/uniswapv3/FullMath.sol";
import {BitMath} from "src/libraries/uniswapv3/BitMath.sol";
import {SqrtPriceMath} from "src/libraries/uniswapv3/SqrtPriceMath.sol";
import {TickMath} from "src/libraries/uniswapv3/TickMath.sol";
interface IFixedTriangleCatalogBitmapV3Pool { function tickBitmap(int16 wordPosition) external view returns (uint256); }
/// @notice BEX executor for an immutable, reviewed catalogue of V3 triangles.
/// @dev Compute snapshots each admitted pool once and evaluates only the
/// predeclared directions. It never discovers pools, traverses a graph, or
/// reads an adjacent bitmap word. Execute reloads only its chosen triangle.
contract EurekaBexFixedTriangleCatalogUnion {
address private constant UNISWAP_V3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
address private constant SUSHISWAP_V3_FACTORY = 0xbACEB8eC6b9355Dfc0269C18bac9d6E2Bdc29C4F;
// Retained profit must also clear this share of gross (1000 bps = 10%) so
// the flat gas reimbursement cannot drain thin arbs at high basefee.
uint256 private constant MIN_RETAINED_SHARE_BPS = 1_000;
uint16 public constant MAX_POOLS = 64;
uint16 public constant MAX_ROUTES = 255;
uint256 private constant MAX_REPAYMENT = 50 ether;
uint256 private constant FEE_DENOMINATOR = 1_000_000;
// Compute is intentionally tolerant of live pool state changing after the
// immutable catalogue was reviewed. Each call is bounded so one malformed
// pool or route cannot consume the whole BEX compute allowance.
uint256 private constant SNAPSHOT_GAS = 31_000;
uint256 private constant ROUTE_SOLVE_GAS = 36_000;
// The 10M BEX compute limit must also hold if every isolated call uses
// its entire allowance. Leave 900k for ABI encoding, catalogue reads,
// loop work and EIP-150 call overhead outside child call budgets.
uint256 private constant MAX_CHILD_COMPUTE_GAS = 9_100_000;
struct Policy {
address recipient;
address weth;
uint256 minimumRetained;
uint256 builderShareBps;
uint256 maximumPayment;
}
struct Identity { address factory; uint24 fee; bytes32 codeHash; }
struct State {
BexCycleQuoter.Pool pool;
Identity identity;
uint160 price;
int24 tick;
int24 spacing;
uint128 liquidity;
uint160 zeroForOneLimit;
uint160 oneForZeroLimit;
}
struct Solution {
State buy;
State middle;
State sell;
uint112 amount;
uint256 repayment;
uint256 gross;
uint160 buyLimit;
uint160 middleLimit;
uint160 sellLimit;
}
struct Winner { uint16 route; uint112 amount; uint256 gross; }
address private immutable WETH;
BexSelectedCatalogValidator public immutable catalogValidator;
bytes32 public immutable validatorCodeHash;
address public immutable catalogData;
bytes32 public immutable catalogCodeHash;
uint16 public immutable poolCount;
uint16 public immutable routeCount;
uint256 private immutable catalogSize;
address private immutable RECIPIENT;
uint256 private immutable MINIMUM_RETAINED;
uint256 private immutable BUILDER_SHARE_BPS;
uint256 private immutable MAXIMUM_PAYMENT;
bytes32 public immutable policyHash;
address public immutable owner;
bool public paused = true;
/// @dev Stores the last completed block plus one, so the default zero
/// cannot collide with a valid block number.
uint256 private lastExecutionMarker = 1;
uint8 transient private phase;
uint16 transient private activeRoute;
uint112 transient private activeAmount;
uint256 transient private activeRepayment;
address transient private activeBuyPool;
address transient private activeBuyToken0;
address transient private activeToken;
address transient private activeSecondToken;
address transient private activeMiddlePool;
address transient private activeMiddleToken0;
address transient private activeMiddleToken1;
uint160 transient private activeMiddleLimit;
address transient private activeSellPool;
address transient private activeSellToken0;
address transient private activeSellToken1;
uint160 transient private activeSellLimit;
bool transient private innerCallback;
uint256 transient private saleAmount;
address transient private saleToken;
address transient private salePool;
address transient private saleToken0;
event CyclesExecuted(bytes32 indexed requestId, uint256 indexed targetBlock,
uint256 result, uint256 grossProfit, uint256 builderPayment, uint256 retainedProfit);
event RouteExecuted(uint16 indexed route, uint112 amount, uint256 grossProfit);
event Paused(bool value);
constructor(Policy memory p, bytes memory data, Identity[] memory ids, BexSelectedCatalogValidator validator) {
require(p.recipient != address(0) && p.recipient != address(this), "IDENTITY");
require(p.weth.code.length > 0 && p.minimumRetained > 0, "POLICY");
require(p.builderShareBps == 6_000 && p.maximumPayment > 0, "PAYMENT");
require(address(validator).code.length > 0 && validator.WETH() == p.weth, "VALIDATOR");
(BexCycleQuoter.Pool[] memory catalogPools, BexCycleQuoter.Route[] memory catalogRoutes) = validator._catalog(data);
require(catalogPools.length > 0 && catalogPools.length <= MAX_POOLS, "POOL_COUNT");
// The multi-plan result uses one byte per route. Zero remains the
// sentinel for an absent second family winner.
require(catalogRoutes.length > 0 && catalogRoutes.length <= MAX_ROUTES && ids.length == catalogPools.length, "ROUTE_COUNT");
require(
catalogPools.length * SNAPSHOT_GAS + catalogRoutes.length * ROUTE_SOLVE_GAS <= MAX_CHILD_COMPUTE_GAS,
"COMPUTE_BUDGET"
);
bool[] memory used = new bool[](catalogPools.length);
uint256 previousRoute;
for (uint256 i; i < catalogPools.length; ++i) {
if (i != 0) require(catalogPools[i - 1].pool < catalogPools[i].pool, "POOL_ORDER");
require(catalogPools[i].token0 != catalogPools[i].token1, "POOL_TOKENS");
require(catalogPools[i].kind == 3 && (ids[i].factory == UNISWAP_V3_FACTORY || ids[i].factory == SUSHISWAP_V3_FACTORY), "FAMILY_V3");
_validatePool(catalogPools[i], ids[i]);
}
for (uint256 i; i < catalogRoutes.length; ++i) {
BexCycleQuoter.Route memory route = catalogRoutes[i];
require(_closed(catalogPools, route, p.weth), "ROUTE");
uint256 key = _routeKey(route);
if (i != 0) require(key > previousRoute, "ROUTE_ORDER");
previousRoute = key;
used[route.first] = true; used[route.second] = true; used[route.third] = true;
require(_containsInverse(catalogRoutes, route), "INVERSE");
}
for (uint256 i; i < used.length; ++i) require(used[i], "POOL_UNUSED");
bytes memory packed = new bytes(data.length + 55 * ids.length);
assembly { mcopy(add(packed, 32), add(data, 32), mload(data)) }
for (uint256 i; i < ids.length; ++i) {
uint256 at = data.length + 55 * i;
Identity memory id = ids[i];
assembly {
mstore(add(add(packed, 32), at), shl(96, mload(id)))
mstore(add(add(packed, 52), at), shl(232, mload(add(id, 32))))
mstore(add(add(packed, 55), at), mload(add(id, 64)))
}
}
address store = address(new BexCycleData(packed));
WETH = p.weth;
catalogValidator = validator;
validatorCodeHash = address(validator).codehash;
catalogData = store;
catalogCodeHash = store.codehash;
poolCount = uint16(catalogPools.length);
routeCount = uint16(catalogRoutes.length);
catalogSize = data.length;
RECIPIENT = p.recipient;
MINIMUM_RETAINED = p.minimumRetained;
BUILDER_SHARE_BPS = p.builderShareBps;
MAXIMUM_PAYMENT = p.maximumPayment;
policyHash = keccak256(abi.encode("ETH58_FIXED_TRIANGLE_CATALOG_MULTIPLAN_60PCT_V1", p, data, ids, validatorCodeHash, catalogCodeHash));
owner = msg.sender;
}
/// @dev The reviewed catalog only admits the canonical V3 fee tiers below.
/// Their tick spacing is immutable and verified at construction, so compute
/// and execute need not make a separate spacing call per V3 pool.
function _spacingForFee(uint24 fee) private pure returns (int24) {
if (fee == 100) return 1;
if (fee == 500) return 10;
if (fee == 3000) return 60;
if (fee == 10000) return 200;
revert("V3_TIER");
}
function _routeKey(BexCycleQuoter.Route memory route) private pure returns (uint256) {
return (uint256(route.first) << 32) | (uint256(route.second) << 16) | route.third;
}
function _containsInverse(BexCycleQuoter.Route[] memory routes, BexCycleQuoter.Route memory route) private pure returns (bool) {
uint256 wanted = (uint256(route.third) << 32) | (uint256(route.second) << 16) | route.first;
uint256 low;
uint256 high = routes.length;
while (low < high) {
uint256 middle = low + (high - low) / 2;
uint256 key = _routeKey(routes[middle]);
if (key == wanted) return true;
if (key < wanted) low = middle + 1;
else high = middle;
}
return false;
}
function _closed(BexCycleQuoter.Pool[] memory pools, BexCycleQuoter.Route memory route, address weth) private pure returns (bool) {
if (
route.first >= pools.length || route.second >= pools.length || route.third >= pools.length
|| route.first == route.second || route.second == route.third || route.first == route.third
) return false;
address token = _other(pools[route.first], weth);
if (token == address(0)) return false;
token = _other(pools[route.second], token);
return token != address(0) && (pools[route.third].token0 == token || pools[route.third].token1 == token)
&& _other(pools[route.third], token) == weth;
}
function _validatePool(BexCycleQuoter.Pool memory p, Identity memory id) private view {
require(p.pool.code.length > 0 && p.token0.code.length > 0 && p.token1.code.length > 0, "POOL");
IBatchIdentity pool = IBatchIdentity(p.pool);
require(pool.token0() == p.token0 && pool.token1() == p.token1, "TOKENS");
require(id.factory.code.length > 0 && pool.factory() == id.factory && p.pool.codehash == id.codeHash, "POOL_IDENTITY");
require(id.fee < FEE_DENOMINATOR && pool.fee() == id.fee && IBatchFactory(id.factory).getPool(p.token0, p.token1, id.fee) == p.pool, "V3_IDENTITY");
require(IUniswapV3Pool(p.pool).tickSpacing() == _spacingForFee(id.fee), "V3_SPACING");
}
function setPaused(bool value) external {
require(msg.sender == owner && phase == 0, "OWNER");
paused = value;
emit Paused(value);
}
/// @notice Immutable execution policy, exposed with the historical public-getter ABI.
function policy() external view returns (address recipient, address weth, uint256 minimumRetained, uint256 builderShareBps, uint256 maximumPayment) {
return (RECIPIENT, WETH, MINIMUM_RETAINED, BUILDER_SHARE_BPS, MAXIMUM_PAYMENT);
}
/// @notice Legacy fixed-cycle request identity; direction is packed into the result.
function requestIdentity(uint256 targetBlock, bytes32 parentHash) public view returns (bytes32) {
return keccak256(abi.encode(block.chainid, address(this), policyHash, targetBlock, parentHash));
}
function lastExecutionBlock() public view returns (uint256) { return lastExecutionMarker - 1; }
function _read(uint256 offset, uint256 size) private view returns (bytes memory data) {
data = new bytes(size);
address source = catalogData;
assembly { extcodecopy(source, add(data, 32), offset, size) }
}
function _checkCatalog() private view { require(catalogData.codehash == catalogCodeHash, "CATALOG_CHANGED"); }
function _pool(uint256 index) private view returns (BexCycleQuoter.Pool memory p) {
require(index < poolCount, "POOL_INDEX");
bytes memory data = _read(5 + 61 * index, 61);
assembly {
mstore(p, shr(96, mload(add(data, 32))))
mstore(add(p, 32), shr(96, mload(add(data, 52))))
mstore(add(p, 64), shr(96, mload(add(data, 72))))
mstore(add(p, 96), byte(0, mload(add(data, 92))))
}
}
function _identity(uint256 index) private view returns (Identity memory id) {
bytes memory data = _read(1 + catalogSize + 55 * index, 55);
assembly {
mstore(id, shr(96, mload(add(data, 32))))
mstore(add(id, 32), shr(232, mload(add(data, 52))))
mstore(add(id, 64), mload(add(data, 55)))
}
}
/// @notice The immutable reviewed pool and route catalogue.
function catalog() external view returns (bytes memory) {
_checkCatalog();
return _read(1, catalogSize);
}
function _direction(uint16 direction) private view returns (uint16 buy, uint16 middle, uint16 sell) {
require(direction > 0 && direction <= routeCount, "ROUTE");
bytes memory data = _read(5 + 61 * uint256(poolCount) + 6 * uint256(direction - 1), 6);
assembly {
buy := shr(240, mload(add(data, 32)))
middle := shr(240, mload(add(data, 34)))
sell := shr(240, mload(add(data, 36)))
}
}
function _other(BexCycleQuoter.Pool memory p, address token) private pure returns (address) {
require(token == p.token0 || token == p.token1, "TOKEN");
return token == p.token0 ? p.token1 : p.token0;
}
function _state(uint256 index) private view returns (State memory s) {
s.pool = _pool(index); s.identity = _identity(index);
require(s.pool.pool.codehash == s.identity.codeHash, "CODE_CHANGED");
// Decode the shared slot0 prefix. UniV3's ABI is fixed, and this
// executor rejects every non-canonical factory at construction.
(bool ok, bytes memory data) = s.pool.pool.staticcall(abi.encodeWithSignature("slot0()"));
require(ok && data.length == 224, "SLOT0");
uint256 rawPrice; int256 rawTick;
assembly { rawPrice := mload(add(data, 32)) rawTick := mload(add(data, 64)) }
require(rawPrice > 0 && rawPrice <= type(uint160).max && rawTick >= type(int24).min && rawTick <= type(int24).max, "SLOT0");
s.price = uint160(rawPrice); s.tick = int24(rawTick);
s.liquidity = IUniswapV3Pool(s.pool.pool).liquidity();
s.spacing = _spacingForFee(s.identity.fee);
require(s.liquidity > 0 && s.spacing > 0, "STATE");
int24 compressed = s.tick / s.spacing;
if (s.tick < 0 && s.tick % s.spacing != 0) --compressed;
uint256 word = IFixedTriangleCatalogBitmapV3Pool(s.pool.pool).tickBitmap(int16(compressed >> 8));
s.zeroForOneLimit = _limitFromWord(s, true, word);
s.oneForZeroLimit = _limitFromWord(s, false, word);
}
/// @notice Isolated snapshot entry point used only by `compute`.
/// @dev Pool state is live and can become unavailable after construction.
/// A failed snapshot is an explicit skip of every route that uses it; it
/// never weakens the construction-time identity or execute-time checks.
function snapshotPool(uint16 index) external view returns (State memory state) {
require(msg.sender == address(this), "SELF");
return _state(index);
}
function _oriented(State memory s, address input) private pure returns (BexCycleSizing.Reserves memory r) {
(uint256 reserve0, uint256 reserve1) = BexCycleSizing.virtualReserves(s.liquidity, s.price);
(r.x, r.y) = input == s.pool.token0 ? (reserve0, reserve1) : (reserve1, reserve0);
r.fee = FEE_DENOMINATOR - s.identity.fee;
}
/// @dev Read one directional bitmap word. The boundary is the nearest
/// initialized tick in that word, or the word edge when none is present.
/// No adjacent word or individual tick storage is read.
function _bitmapBoundary(State memory s, bool zeroForOne, uint256 word) private pure returns (int24 boundaryTick) {
int24 compressed = s.tick / s.spacing;
if (s.tick < 0 && s.tick % s.spacing != 0) --compressed;
int16 wordPosition = int16(compressed >> 8);
uint8 bitPosition = uint8(uint24(compressed) & 255);
int256 boundaryCompressed;
if (zeroForOne) {
uint256 mask = bitPosition == 255 ? type(uint256).max : (uint256(1) << (bitPosition + 1)) - 1;
uint256 masked = word & mask;
boundaryCompressed = int256(wordPosition) * 256 + (masked == 0 ? int256(0) : int256(uint256(BitMath.mostSignificantBit(masked))));
} else {
uint256 mask = bitPosition == 255 ? 0 : type(uint256).max << (bitPosition + 1);
uint256 masked = word & mask;
// `nextInitializedTickWithinOneWord` advances through an empty
// current word to its last compressed tick before continuing in
// the next step. Keep the price limit inside that uninitialized
// word edge. At bit 255 there is no current-word space left, so
// use the first tick of the next word without reading it.
int256 emptyBoundary = bitPosition == 255 ? int256(256) : int256(255);
boundaryCompressed = int256(wordPosition) * 256 + (masked == 0 ? emptyBoundary : int256(uint256(BitMath.leastSignificantBit(masked))));
}
int256 rawTick = boundaryCompressed * int256(s.spacing);
if (rawTick < TickMath.MIN_TICK) return TickMath.MIN_TICK;
if (rawTick > TickMath.MAX_TICK) return TickMath.MAX_TICK;
return int24(rawTick);
}
/// @dev `limit` is one sqrt-price unit inside a boundary selected from one
/// bitmap word, so a successful swap never reaches an initialized tick.
function _limitFromWord(State memory s, bool zeroForOne, uint256 word) private pure returns (uint160 limit) {
uint160 boundary = TickMath.getSqrtRatioAtTick(_bitmapBoundary(s, zeroForOne, word));
if (zeroForOne) {
if (boundary == type(uint160).max) return 0;
limit = boundary + 1;
if (s.price <= limit) return 0;
} else {
if (boundary <= TickMath.MIN_SQRT_RATIO) return 0;
limit = boundary - 1;
if (s.price >= limit) return 0;
}
}
function _limit(State memory s, bool zeroForOne) private pure returns (uint160) {
return zeroForOne ? s.zeroForOneLimit : s.oneForZeroLimit;
}
function _capOutputAtLimit(State memory s, bool zeroForOne, uint160 limit) private pure returns (uint256 cap) {
cap = zeroForOne
? SqrtPriceMath.getAmount1Delta(limit, s.price, s.liquidity, false)
: SqrtPriceMath.getAmount0Delta(s.price, limit, s.liquidity, false);
// Leave one raw unit inside the boundary so fixed-point rounding cannot
// land execution exactly on a usable tick.
return cap > 1 ? cap - 1 : 0;
}
function _capOutput(State memory s, bool zeroForOne) private pure returns (uint256) {
return _capOutputAtLimit(s, zeroForOne, _limit(s, zeroForOne));
}
function _v3ExactOutput(State memory s, address output, uint256 amount, uint160 limit) private pure returns (uint256 repayment) {
bool zeroForOne = s.pool.token0 != output;
require(amount > 0 && amount <= _capOutputAtLimit(s, zeroForOne, limit), "V3_OUTPUT_CAP");
uint160 q = SqrtPriceMath.getNextSqrtPriceFromOutput(s.price, s.liquidity, amount, zeroForOne);
require(zeroForOne ? q > limit : q < limit, "V3_CROSS");
uint256 noFee = zeroForOne
? SqrtPriceMath.getAmount0Delta(q, s.price, s.liquidity, true)
: SqrtPriceMath.getAmount1Delta(s.price, q, s.liquidity, true);
repayment = FullMath.mulDivRoundingUp(noFee, FEE_DENOMINATOR, FEE_DENOMINATOR - s.identity.fee);
}
function _v3ExactInput(State memory s, address input, uint256 amount, uint160 limit) private pure returns (uint256 output) {
bool zeroForOne = s.pool.token0 == input;
uint256 effective = FullMath.mulDiv(amount, FEE_DENOMINATOR - s.identity.fee, FEE_DENOMINATOR);
// A route-local exact-input leg can be fed one raw unit after a prior
// amount delta rounds down. That has no executable output; returning
// zero keeps the candidate ineligible without aborting the catalog scan.
if (effective == 0) return 0;
uint160 q = SqrtPriceMath.getNextSqrtPriceFromInput(s.price, s.liquidity, effective, zeroForOne);
require(zeroForOne ? q > limit : q < limit, "V3_CROSS");
output = zeroForOne
? SqrtPriceMath.getAmount1Delta(q, s.price, s.liquidity, false)
: SqrtPriceMath.getAmount0Delta(s.price, q, s.liquidity, false);
}
/// @dev Largest raw input whose fee-adjusted input stays strictly before
/// `limit`. The subtraction makes the equality case inadmissible.
function _v3InputCap(State memory s, address input, uint160 limit) private pure returns (uint256 cap) {
bool zeroForOne = s.pool.token0 == input;
uint256 netToLimit = zeroForOne
? SqrtPriceMath.getAmount0Delta(limit, s.price, s.liquidity, true)
: SqrtPriceMath.getAmount1Delta(s.price, limit, s.liquidity, true);
if (netToLimit == 0) return 0;
cap = (netToLimit * FEE_DENOMINATOR - 1) / (FEE_DENOMINATOR - s.identity.fee);
// A raw cap can round down to a zero fee-adjusted input (for example,
// netToLimit=1 at 3000 fee gives raw cap=1). It is not executable and
// must make the route ineligible rather than letting quote revert.
if (FullMath.mulDiv(cap, FEE_DENOMINATOR - s.identity.fee, FEE_DENOMINATOR) == 0) return 0;
}
/// @dev Bound an exact-input V3 leg by both its own tick interval and the
/// downstream output it is allowed to create. No inverse search is used.
function _v3InputCapForOutput(State memory s, address input, uint256 outputCap, uint160 ownLimit) private pure returns (uint256) {
bool zeroForOne = s.pool.token0 == input;
uint256 inTickOutput = _capOutputAtLimit(s, zeroForOne, ownLimit);
uint256 allowedOutput = outputCap < inTickOutput ? outputCap : inTickOutput;
if (allowedOutput == 0) return 0;
uint160 outputLimit = SqrtPriceMath.getNextSqrtPriceFromOutput(s.price, s.liquidity, allowedOutput, zeroForOne);
uint160 limit = zeroForOne
? (outputLimit > ownLimit ? outputLimit : ownLimit)
: (outputLimit < ownLimit ? outputLimit : ownLimit);
return _v3InputCap(s, input, limit);
}
/// @dev Intersect the three fixed V3 in-tick capacities without searching.
function _routeCap(State memory buy, State memory middle, State memory sell)
private view returns (uint256 cap, uint160 buyLimit, uint160 middleLimit, uint160 sellLimit)
{
address token = _other(buy.pool, WETH);
bool buyZeroForOne = buy.pool.token0 != token;
buyLimit = _limit(buy, buyZeroForOne);
if (buyLimit == 0) return (0, 0, 0, 0);
cap = _capOutputAtLimit(buy, buyZeroForOne, buyLimit);
uint256 maxInput = _v3InputCap(buy, WETH, buyLimit);
if (maxInput > MAX_REPAYMENT) maxInput = MAX_REPAYMENT;
if (maxInput == 0) return (0, 0, 0, 0);
uint256 repaymentCap = _v3ExactInput(buy, WETH, maxInput, buyLimit);
if (repaymentCap < cap) cap = repaymentCap;
address secondToken = _other(middle.pool, token);
sellLimit = _limit(sell, sell.pool.token0 == secondToken);
if (sellLimit == 0) return (0, 0, 0, 0);
uint256 finalInputCap = _v3InputCap(sell, secondToken, sellLimit);
middleLimit = _limit(middle, middle.pool.token0 == token);
if (middleLimit == 0) return (0, 0, 0, 0);
uint256 middleInputCap = _v3InputCapForOutput(middle, token, finalInputCap, middleLimit);
if (middleInputCap < cap) cap = middleInputCap;
}
function _repayment(State memory buy, address token, uint256 amount, uint160 limit) private pure returns (uint256) {
return _v3ExactOutput(buy, token, amount, limit);
}
function _sellQuote(State memory sell, address input, uint256 amount, uint160 limit) private pure returns (uint256) {
return _v3ExactInput(sell, input, amount, limit);
}
function _quote(State memory buy, State memory middle, State memory sell, uint256 amount, uint160 buyLimit, uint160 middleLimit, uint160 sellLimit)
private view returns (uint256 repayment, uint256 gross)
{
address token = _other(buy.pool, WETH);
repayment = _repayment(buy, token, amount, buyLimit);
if (repayment == 0 || repayment > MAX_REPAYMENT) return (repayment, 0);
uint256 received = _sellQuote(middle, token, amount, middleLimit);
token = _other(middle.pool, token);
received = _sellQuote(sell, token, received, sellLimit);
if (received > repayment) gross = received - repayment;
}
function _economics(uint256 gross) private view returns (uint256 payment, uint256 retained) {
uint256 gasCost = 500000 * block.basefee;
if (gross <= gasCost) return (gasCost, 0);
payment = gasCost + (gross - gasCost) * BUILDER_SHARE_BPS / 10_000;
retained = gross - payment;
}
function _admissible(uint256 gross) private view returns (bool) {
(uint256 payment, uint256 retained) = _economics(gross);
return payment > 0 && payment <= MAXIMUM_PAYMENT && retained >= MINIMUM_RETAINED && retained * 10_000 >= gross * MIN_RETAINED_SHARE_BPS;
}
/// @notice Solve a preselected route from already-read state.
/// @dev The analytic seed is clipped by every downstream in-tick capacity,
/// then one exact quote validates that candidate. This is deliberately
/// a route-local solve, not a build-time grid or graph search.
/// @dev The caller chooses a predeclared direction. This has no graph discovery.
function _solveStates(State memory buy, State memory middle, State memory sell) private view returns (Solution memory solution) {
solution.buy = buy; solution.middle = middle; solution.sell = sell;
address token = _other(solution.buy.pool, WETH);
address next = _other(solution.middle.pool, token);
(uint256 initial,) = BexCycleSizing.seed(
_oriented(solution.buy, WETH), _oriented(solution.middle, token), _oriented(solution.sell, next), true
);
if (initial == 0) return solution;
uint256 cap;
(cap, solution.buyLimit, solution.middleLimit, solution.sellLimit) = _routeCap(solution.buy, solution.middle, solution.sell);
if (cap == 0) return solution;
if (initial > cap) initial = cap;
if (initial > type(uint112).max) return solution;
(uint256 repayment, uint256 gross) = _quote(
solution.buy, solution.middle, solution.sell, initial,
solution.buyLimit, solution.middleLimit, solution.sellLimit
);
if (_admissible(gross)) { solution.amount = uint112(initial); solution.repayment = repayment; solution.gross = gross; }
}
function _solve(uint16 direction) private view returns (Solution memory solution) {
if (paused || phase != 0 || direction == 0 || direction > routeCount) return solution;
_checkCatalog();
(uint16 buyIndex, uint16 middleIndex, uint16 sellIndex) = _direction(direction);
return _solveStates(_state(buyIndex), _state(middleIndex), _state(sellIndex));
}
function _solveCached(uint16 direction, State[] memory states) private view returns (Solution memory) {
(uint16 buyIndex, uint16 middleIndex, uint16 sellIndex) = _direction(direction);
return _solveStates(states[buyIndex], states[middleIndex], states[sellIndex]);
}
function _isSushi(uint16 buyIndex, uint16 middleIndex, uint16 sellIndex, State[] memory states) private pure returns (bool) {
return states[buyIndex].identity.factory == SUSHISWAP_V3_FACTORY
|| states[middleIndex].identity.factory == SUSHISWAP_V3_FACTORY
|| states[sellIndex].identity.factory == SUSHISWAP_V3_FACTORY;
}
function _isSushi(uint16 direction) private view returns (bool) {
(uint16 buyIndex, uint16 middleIndex, uint16 sellIndex) = _direction(direction);
return _identity(buyIndex).factory == SUSHISWAP_V3_FACTORY
|| _identity(middleIndex).factory == SUSHISWAP_V3_FACTORY
|| _identity(sellIndex).factory == SUSHISWAP_V3_FACTORY;
}
/// @notice Isolated route quote entry point used only by `compute`.
/// @dev This makes arithmetic/quote faults route-local while preserving a
/// single immutable snapshot per pool for the whole catalogue scan.
function solveSnapshot(bytes calldata packed) external view returns (uint112 amount, uint256 gross) {
require(msg.sender == address(this), "SELF");
require(packed.length == 357, "SNAPSHOT");
Solution memory solution = _solveStates(_unpackState(packed, 0), _unpackState(packed, 119), _unpackState(packed, 238));
return (solution.amount, solution.gross);
}
/// @dev A compact quote state is 119 bytes: token0/token1 (20/20), fee
/// (3), price (20), liquidity (16), and the cached directional limits
/// (20/20). Pool identity and raw tick data were already checked while
/// snapshotting and are not consumed by the pure route solve. Omitting
/// them keeps every isolated route quote inside its bounded allowance.
function _packState(bytes memory packed, uint256 offset, State memory state) private pure {
BexCycleQuoter.Pool memory pool = state.pool;
Identity memory identity = state.identity;
address token0 = pool.token0;
address token1 = pool.token1;
uint24 fee = identity.fee;
uint160 price = state.price;
uint128 liquidity = state.liquidity;
uint160 zeroForOneLimit = state.zeroForOneLimit;
uint160 oneForZeroLimit = state.oneForZeroLimit;
assembly ("memory-safe") {
let target := add(add(packed, 32), offset)
mstore(target, shl(96, token0))
mstore(add(target, 20), shl(96, token1))
mstore(add(target, 40), shl(232, fee))
mstore(add(target, 43), shl(96, price))
mstore(add(target, 63), shl(128, liquidity))
mstore(add(target, 79), shl(96, zeroForOneLimit))
mstore(add(target, 99), shl(96, oneForZeroLimit))
}
}
function _unpackState(bytes calldata packed, uint256 offset) private pure returns (State memory state) {
address token0;
address token1;
uint24 fee;
uint160 price;
uint128 liquidity;
uint160 zeroForOneLimit;
uint160 oneForZeroLimit;
assembly ("memory-safe") {
let source := add(packed.offset, offset)
token0 := shr(96, calldataload(source))
token1 := shr(96, calldataload(add(source, 20)))
fee := shr(232, calldataload(add(source, 40)))
price := shr(96, calldataload(add(source, 43)))
liquidity := shr(128, calldataload(add(source, 63)))
zeroForOneLimit := shr(96, calldataload(add(source, 79)))
oneForZeroLimit := shr(96, calldataload(add(source, 99)))
}
state.pool = BexCycleQuoter.Pool(address(0), token0, token1, 3);
state.identity.fee = fee;
state.price = price;
state.liquidity = liquidity;
state.zeroForOneLimit = zeroForOneLimit;
state.oneForZeroLimit = oneForZeroLimit;
}
function _packRoute(bytes memory packed, State memory buy, State memory middle, State memory sell) private pure {
_packState(packed, 0, buy);
_packState(packed, 119, middle);
_packState(packed, 238, sell);
}
/// @notice Snapshot each reviewed pool once and solve only declared directions.
function compute() external view returns (uint256) {
// Execute consumes this request for the current block. Stop quoting
// once it has landed instead of returning another unexecutable result.
if (paused || phase != 0 || lastExecutionBlock() == block.number) return 0;
_checkCatalog();
State[] memory states = new State[](poolCount);
bool[] memory available = new bool[](poolCount);
for (uint16 i; i < poolCount; ++i) {
try this.snapshotPool{gas: SNAPSHOT_GAS}(i) returns (State memory state) {
states[i] = state;
available[i] = true;
} catch {}
}
// Each self-call consumes its calldata before the next iteration.
// Reuse one buffer, including padding for the final compact value,
// rather than expanding memory for every direction in the catalogue.
bytes memory packed = new bytes(384);
assembly ("memory-safe") { mstore(packed, 357) }
// Copy immutable route indexes once per scan. Keep a full word of
// padding so the last six-byte route's word loads stay in this buffer.
bytes memory directions = _read(5 + 61 * uint256(poolCount), 6 * uint256(routeCount) + 32);
Winner memory uni;
Winner memory sushi;
for (uint16 direction = 1; direction <= routeCount; ++direction) {
uint16 buyIndex;
uint16 middleIndex;
uint16 sellIndex;
assembly ("memory-safe") {
let route := add(add(directions, 32), mul(sub(direction, 1), 6))
buyIndex := shr(240, mload(route))
middleIndex := shr(240, mload(add(route, 2)))
sellIndex := shr(240, mload(add(route, 4)))
}
if (!available[buyIndex] || !available[middleIndex] || !available[sellIndex]) continue;
_packRoute(packed, states[buyIndex], states[middleIndex], states[sellIndex]);
try this.solveSnapshot{gas: ROUTE_SOLVE_GAS}(packed)
returns (uint112 amount, uint256 gross)
{
if (amount == 0) continue;
bool isSushi = _isSushi(buyIndex, middleIndex, sellIndex, states);
Winner memory winner = isSushi ? sushi : uni;
if (winner.amount == 0 || gross > winner.gross) {
winner = Winner(direction, amount, gross);
if (isSushi) sushi = winner;
else uni = winner;
}
} catch {}
}
if (uni.amount == 0) uni = sushi;
else if (sushi.amount != 0 && sushi.gross > uni.gross) (uni, sushi) = (sushi, uni);
if (uni.amount == 0) return 0;
uint16 second = sushi.amount == 0 || sushi.route == uni.route ? 0 : sushi.route;
return (uint256(uni.route) << 120) | (uint256(uni.amount) << 8) | second;
}
function execute(uint256 targetBlock, bytes32 parentHash, bytes32 requestId, uint256 result) external {
require(!paused && phase == 0, "INACTIVE");
// Eureka documents that the execute transaction is signed by the
// builder's live fee-recipient key. Bind execution to that rotating
// identity without pinning a builder address in the deployment.
require(msg.sender == block.coinbase, "BUILDER");
require(block.number == targetBlock && blockhash(block.number - 1) == parentHash, "TARGET");
require(requestId == requestIdentity(targetBlock, parentHash), "REQUEST");
require(lastExecutionBlock() != block.number, "DUPLICATE");
uint16 direction = uint8(result >> 120);
uint112 amount = uint112(result >> 8);
uint16 secondDirection = uint8(result);
require(result >> 128 == 0 && direction != 0 && direction <= routeCount && amount > 0, "RESULT");
require(secondDirection == 0 || (secondDirection <= routeCount && _isSushi(direction) != _isSushi(secondDirection)), "SECOND_RESULT");
Solution memory solution = _solve(direction);
require(amount == solution.amount, "AMOUNT");
uint256 beforeCoinbase = block.coinbase.balance;
uint256 beforeWeth = IBatchToken(WETH).balanceOf(address(this));
uint256 gross = _executeSolution(direction, solution);
(uint256 payment, uint256 retained) = _economics(gross);
// The second amount is deliberately not trusted from compute. Re-read
// its three pools after the first route and use that live optimum. If
// the opportunity disappeared, the first route can still land.
if (secondDirection != 0) {
solution = _solve(secondDirection);
if (solution.amount != 0) {
(uint256 secondPayment, uint256 secondRetained) = _economics(solution.gross);
if (payment + secondPayment <= MAXIMUM_PAYMENT) {
uint256 secondGross = _executeSolution(secondDirection, solution);
(secondPayment, secondRetained) = _economics(secondGross);
gross += secondGross; payment += secondPayment; retained += secondRetained;
}
}
}
require(payment > 0 && payment <= MAXIMUM_PAYMENT && retained >= MINIMUM_RETAINED, "PROFIT_FLOOR");
// Lock both execute and owner mutation across every external settlement
// call. The marker is written first and rolls back with any failure.
lastExecutionMarker = block.number + 1;
phase = 4;
IBatchToken(WETH).withdraw(payment);
(bool paid,) = payable(block.coinbase).call{value: payment}("");
require(paid, "COINBASE_PAYMENT");
_pay(WETH, RECIPIENT, retained);
require(IBatchToken(WETH).balanceOf(address(this)) == beforeWeth, "INVENTORY");
require(block.coinbase.balance > beforeCoinbase, "COINBASE_NOT_RICHER");
emit CyclesExecuted(requestId, targetBlock, result, gross, payment, retained);
phase = 0;
}
function _executeSolution(uint16 direction, Solution memory solution) private returns (uint256 gross) {
State memory buy = solution.buy;
address token = _other(buy.pool, WETH);
address secondToken = _other(solution.middle.pool, token);
uint256 beforeWeth = IBatchToken(WETH).balanceOf(address(this));
uint256 beforeToken = IBatchToken(token).balanceOf(address(this));
uint256 beforeSecond = IBatchToken(secondToken).balanceOf(address(this));
activeRoute = direction; activeAmount = solution.amount; activeRepayment = solution.repayment;
activeBuyPool = buy.pool.pool; activeBuyToken0 = buy.pool.token0; activeToken = token;
activeSecondToken = secondToken;
activeMiddlePool = solution.middle.pool.pool; activeMiddleToken0 = solution.middle.pool.token0; activeMiddleToken1 = solution.middle.pool.token1;
activeSellPool = solution.sell.pool.pool; activeSellToken0 = solution.sell.pool.token0; activeSellToken1 = solution.sell.pool.token1;
activeMiddleLimit = solution.middleLimit;
activeSellLimit = solution.sellLimit;
phase = 1;
bool zeroForOne = buy.pool.token0 != token;
IBatchSwapV3(buy.pool.pool).swap(address(this), zeroForOne, -int256(uint256(solution.amount)), solution.buyLimit, hex"01");
require(phase == 3, "MISSING_FLASH"); phase = 4;
uint256 afterWeth = IBatchToken(WETH).balanceOf(address(this));
require(afterWeth > beforeWeth, "PROFIT");
gross = afterWeth - beforeWeth;
require(IBatchToken(token).balanceOf(address(this)) == beforeToken, "TOKEN_INVENTORY");
require(IBatchToken(secondToken).balanceOf(address(this)) == beforeSecond, "SECOND_INVENTORY");
emit RouteExecuted(direction, solution.amount, gross);
activeAmount = 0; activeRoute = 0; activeRepayment = 0; saleAmount = 0; saleToken = address(0); salePool = address(0); saleToken0 = address(0); phase = 0;
}
function uniswapV3SwapCallback(int256 a, int256 b, bytes calldata data) external { _callback(a, b, data); }
function _callback(int256 a, int256 b, bytes calldata data) private {
if (phase == 1) {
bool token0 = activeBuyToken0 == activeToken;
require(msg.sender == activeBuyPool && data.length == 1 && data[0] == 0x01, "CALLBACK");
require((token0 ? a : b) == -int256(uint256(activeAmount)) && (token0 ? b : a) > 0, "BORROW_DELTAS");
require(uint256(token0 ? b : a) == activeRepayment, "REPAYMENT");
_finish();
} else {
require(phase == 2 && innerCallback, "INNER_CALLBACK");
bool zeroForOne = saleToken == saleToken0;
require(msg.sender == salePool && data.length == 0, "INNER_CALLBACK");
require((zeroForOne ? a : b) == int256(saleAmount) && (zeroForOne ? b : a) < 0, "SELL_DELTAS");
innerCallback = false; _pay(saleToken, salePool, saleAmount);
}
}
function _sell(address pool, address token0, address token1, address input, uint256 amount, uint160 limit) private returns (uint256 received) {
require(
(input == token0 || input == token1) && amount > 0 && amount <= type(uint256).max / 2 && limit > 0,
"INPUT"
);
bool zeroForOne = token0 == input;
saleAmount = amount; saleToken = input; salePool = pool; saleToken0 = token0; innerCallback = true;
(int256 amount0, int256 amount1) = IBatchSwapV3(pool).swap(address(this), zeroForOne, int256(amount), limit, "");
require(!innerCallback, "MISSING_INNER");
int256 outputDelta = zeroForOne ? amount1 : amount0;
require(outputDelta < 0, "OUTPUT");
return uint256(-outputDelta);
}
function _finish() private {
require(activeRepayment > 0 && activeRepayment <= MAX_REPAYMENT, "REPAYMENT"); phase = 2;
address token = activeToken; uint256 amount = activeAmount;
amount = _sell(activeMiddlePool, activeMiddleToken0, activeMiddleToken1, token, amount, activeMiddleLimit);
_sell(activeSellPool, activeSellToken0, activeSellToken1, activeSecondToken, amount, activeSellLimit);
phase = 3; _pay(WETH, activeBuyPool, activeRepayment);
}
function _pay(address token, address to, uint256 amount) private {
// ERC-20 allows either empty returndata or one ABI-encoded true. Keep
// the check strict while avoiding dynamic ABI/bytes allocation on each
// callback repayment and route leg.
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, shl(224, 0xa9059cbb))
mstore(add(ptr, 4), to)
mstore(add(ptr, 36), amount)
let ok := call(gas(), token, 0, ptr, 68, 0, 32)
switch returndatasize()
case 0 {
if iszero(ok) { revert(0, 0) }
}
case 32 {
returndatacopy(ptr, 0, 32)
if iszero(and(ok, eq(mload(ptr), 1))) { revert(0, 0) }
}
default { revert(0, 0) }
}
}
receive() external payable { require(msg.sender == WETH, "WETH_ONLY"); }
}
src/bex/BexBatchQuoter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {UniswapV3QuoterBase} from "src/liquidations/compoundv2/common/quoters/UniswapV3Quoter/UniswapV3QuoterBase.sol";
import {IUniswapV3Pool} from "src/interfaces/uniswapv3/IUniswapV3Pool.sol";
import {TickMath} from "src/libraries/uniswapv3/TickMath.sol";
import {FullMath} from "src/libraries/uniswapv3/FullMath.sol";
import {BitMath} from "src/libraries/uniswapv3/BitMath.sol";
interface IBatchV2 { function getReserves() external view returns (uint112,uint112,uint32); }
/// @notice Fixed-grid, bounded two-pool search. Snapshot each pool once and
/// exactly quote seven sizes on at most eight ranked routes.
abstract contract BexBatchQuoter is UniswapV3QuoterBase {
address internal immutable WETH;
constructor(address weth) { WETH = weth; }
function _admissible(uint256 gross) internal view virtual returns (bool);
struct Pool { address pool; address token; uint8 kind; }
struct Route { uint16 buy; uint16 sell; }
struct Snapshot { Pool identity; uint256 token; uint256 weth; PoolState v3; }
struct Candidate { uint256 route; uint256 amount; uint256 repayment; uint256 gross; uint256 gridGross; uint256 quotes; }
struct Report { Candidate best; uint256 marginal; uint256 shortlisted; uint256 unavailable; uint256 quotes; }
uint256 constant MAX_REPAYMENT = 50 ether;
uint256 constant MAX_STEPS = 32;
function _sqrt(uint256 value) private pure returns (uint256 result) {
if (value == 0) return 0;
result = uint256(1) << (BitMath.mostSignificantBit(value)/2);
for (uint256 i; i < 7; ++i) result = (result+value/result)/2;
uint256 other = value/result;
return result < other ? result : other;
}
function _snapshot(Pool memory p) internal view returns (Snapshot memory s) {
require(p.pool != address(0) && p.token != address(0) && p.token != WETH && (p.kind == 2 || p.kind == 3), "POOL");
s.identity = p;
uint256 a; uint256 b;
if (p.kind == 2) {
(a,b,) = IBatchV2(p.pool).getReserves();
} else {
s.v3 = fetchState(p.pool,0);
require(s.v3.sqrtPriceX96 > 0 && s.v3.fee < 1e6, "STATE");
a = FullMath.mulDiv(s.v3.liquidity,2**96,s.v3.sqrtPriceX96);
b = FullMath.mulDiv(s.v3.liquidity,s.v3.sqrtPriceX96,2**96);
}
(s.token,s.weth) = p.token < WETH ? (a,b) : (b,a);
// The seed's products are bounded; larger virtual balances are outside
// this research universe, not silently truncated.
require(a <= type(uint112).max && b <= type(uint112).max,"RESERVE_BOUND");
}
function _seed(Snapshot memory buy, Snapshot memory sell) internal pure returns (uint256 amount, uint256 score) {
if (buy.token == 0 || buy.weth == 0 || sell.token == 0 || sell.weth == 0) return (0,0);
uint256 fb = buy.identity.kind == 2 ? 997000 : 1000000-buy.v3.fee;
uint256 fs = sell.identity.kind == 2 ? 997000 : 1000000-sell.v3.fee;
uint256 a = _sqrt(FullMath.mulDiv(sell.weth*sell.token,fb*fs,1e12));
uint256 b = _sqrt(buy.weth*buy.token);
if (a*buy.token <= b*sell.token) return (0,0);
amount = (a*buy.token-b*sell.token)/(a+b*fs/1e6);
if (amount == 0 || amount >= buy.token) return (0,0);
uint256 repay = FullMath.mulDiv(buy.weth*amount,1e6,(buy.token-amount)*fb)+1;
uint256 received = FullMath.mulDiv(sell.weth,amount*fs,sell.token*1e6+amount*fs);
if (repay >= received) return (0,0);
score = received-repay;
}
function _v3(Snapshot memory s,uint256 amount,bool borrow) private view returns (uint256 value) {
require(amount > 0 && amount <= uint256(type(int256).max), "AMOUNT");
bool z = borrow ? WETH < s.identity.token : s.identity.token < WETH;
int256 specified = borrow ? -int256(amount) : int256(amount);
uint160 limit = z ? TickMath.MIN_SQRT_RATIO+1 : TickMath.MAX_SQRT_RATIO-1;
(SwapState memory state,uint128 liquidity,uint160 price) = setInitialState(s.v3,specified,limit,z);
uint256 steps;
while (state.amountSpecifiedRemaining != 0 && price != limit) {
require(steps++ < MAX_STEPS,"TICK_BUDGET");
(,price,liquidity) = processSwapWithinTick(IUniswapV3Pool(s.identity.pool),s.v3,state,price,liquidity,limit,z,!borrow);
}
require(state.amountSpecifiedRemaining == 0,"PARTIAL_QUOTE");
value = borrow ? uint256(state.amountCalculated) : uint256(-state.amountCalculated);
}
function _quote(Snapshot memory buy,Snapshot memory sell,uint256 amount) private view returns (Candidate memory c) {
c.amount = amount; c.quotes = 1;
if (amount == 0 || (buy.identity.kind == 2 && amount >= buy.token)) return c;
c.repayment = buy.identity.kind == 2
? FullMath.mulDiv(buy.weth*amount,1000,(buy.token-amount)*997)+1 : _v3(buy,amount,true);
if (c.repayment == 0 || c.repayment > MAX_REPAYMENT) return c;
uint256 received = sell.identity.kind == 2
? FullMath.mulDiv(sell.weth,amount*997,sell.token*1000+amount*997) : _v3(sell,amount,false);
if (received > c.repayment) c.gross = received-c.repayment;
}
// Self-call isolates a tick-budget failure to its shortlisted route. The
// diagnostic report retains the failure count; there is no approximate quote.
function evaluate(Snapshot calldata buy, Snapshot calldata sell, uint256 initial)
external view returns (Candidate memory best)
{
require(msg.sender == address(this), "SELF");
uint256[7] memory factors = [uint256(1),2,3,4,5,6,8];
uint256 count;
for (uint256 i; i < factors.length; ++i) {
uint256 amount = initial*factors[i]/4;
if (amount == 0 || amount > type(uint112).max) continue;
Candidate memory c = _quote(buy,sell,amount);
count += c.quotes;
if (c.gross > best.gross && _admissible(c.gross)) best = c;
}
best.gridGross = best.gross; best.quotes = count;
}
function _search(Pool[] memory pools,Route[] memory routes) internal view returns (Report memory report) {
uint256 budget = 8;
Snapshot[] memory states = new Snapshot[](pools.length);
for (uint256 i; i < pools.length; ++i) {
states[i] = _snapshot(pools[i]);
}
uint256[] memory indices = new uint256[](budget);
uint256[] memory seeds = new uint256[](budget);
uint256[] memory scores = new uint256[](budget);
for (uint256 i; i < routes.length; ++i) {
Route memory r = routes[i];
require(r.buy < pools.length && r.sell < pools.length && r.buy != r.sell,"ROUTE");
require(pools[r.buy].token == pools[r.sell].token,"TOKEN");
(uint256 amount,uint256 score) = _seed(states[r.buy],states[r.sell]);
if (score == 0) continue;
++report.marginal;
if (score <= 500000*block.basefee) continue;
for (uint256 j; j < budget; ++j) if (score > scores[j]) {
for (uint256 k = budget-1; k > j; --k) { scores[k]=scores[k-1]; seeds[k]=seeds[k-1]; indices[k]=indices[k-1]; }
scores[j]=score; seeds[j]=amount; indices[j]=i;
break;
}
}
for (uint256 i; i < budget && scores[i] > 0; ++i) {
Route memory r = routes[indices[i]];
++report.shortlisted;
try this.evaluate{gas:1000000}(states[r.buy],states[r.sell],seeds[i]) returns (Candidate memory c) {
report.quotes += c.quotes;
c.route = indices[i]+1;
if (c.gross > report.best.gross) report.best = c;
} catch { ++report.unavailable; }
}
// Unavailable routes remain explicit even when another route succeeds.
// The caller must not label a partial search as a complete no-op.
}
}
src/bex/BexCycleData.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
/// @notice Immutable cycle catalog bytes, stored after a STOP instruction.
/// The deployed account has no executable mutator or destruction path.
contract BexCycleData {
constructor(bytes memory data) {
require(data.length>0 && data.length<=24575,"DATA_SIZE");
bytes memory runtime=bytes.concat(hex"00",data);
assembly { return(add(runtime,32),mload(runtime)) }
}
}
src/bex/BexCycleQuoter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {UniswapV3QuoterBase} from "src/liquidations/compoundv2/common/quoters/UniswapV3Quoter/UniswapV3QuoterBase.sol";
import {IUniswapV3Pool} from "src/interfaces/uniswapv3/IUniswapV3Pool.sol";
import {TickMath} from "src/libraries/uniswapv3/TickMath.sol";
import {FullMath} from "src/libraries/uniswapv3/FullMath.sol";
import {BexCycleSizing} from "./BexCycleSizing.sol";
interface ICycleV2 { function getReserves() external view returns (uint112,uint112,uint32); }
interface ICycleV3Identity { function factory() external view returns(address); function lmPool() external view returns(address); }
/// @notice Bounded two-swap and standard V2/V3 triangle quoting for an immutable executor.
/// Packed catalog: u16 pool count, u16 route count, 61 bytes/pool (three
/// addresses and kind), six bytes/route (three u16 indices), all big endian.
contract BexCycleQuoter is UniswapV3QuoterBase {
address public immutable WETH;
constructor(address weth) { WETH=weth; }
struct Economics { uint256 minimumRetained; uint256 builderShareBps; uint256 maximumPayment; }
// Qualified envelope for this executor, catalog and standard token behavior.
// Eight thousand gas remain outside the admission ceiling. These are
// conservative admission costs, not a universal EVM gas estimator.
uint256 private constant TRIANGLE_BASE_GAS=446000;
uint256 private constant QUOTE_STEP_GAS=4000;
uint256 private constant INITIALIZED_CROSS_GAS=30000;
uint256 private constant NEW_STORAGE_GAS=20000;
uint256 private constant PANCAKE_REWARD_GAS=30000;
address constant PANCAKE_FACTORY=0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865;
uint256 private constant EXECUTION_ADMISSION_GAS=492000;
uint16 constant DIRECT=type(uint16).max;
struct Pool { address pool; address token0; address token1; uint8 kind; }
struct Route { uint16 first; uint16 second; uint16 third; }
struct Snapshot { Pool identity; uint256 r0; uint256 r1; PoolState v3; bool available; uint256 storageGas; }
struct Candidate { uint256 route; uint256 amount; uint256 repayment; uint256 gross; }
struct Report { Candidate best; uint256 marginal; uint256 shortlisted; uint256 unavailable; uint256 quotes; uint256 unavailablePools; uint256 poolReads; uint256 budgetSkipped; uint256 gasRejected; uint256 executionGas; uint256 unavailableQuotes; uint256 budgetSkippedQuotes; uint256 refinementQuotes; }
function _u16(bytes calldata data,uint256 at) private pure returns(uint16 value) {
assembly { value := shr(240,calldataload(add(data.offset,at))) }
}
function _address(bytes calldata data,uint256 at) private pure returns(address value) {
assembly { value := shr(96,calldataload(add(data.offset,at))) }
}
function _catalog(bytes calldata data) public view returns(Pool[] memory pools,Route[] memory routes) {
(pools,routes)=_decodeCatalog(data);uint256 np=pools.length;uint256 nr=routes.length;
for(uint256 i;i<np;++i) {
Pool memory p=pools[i];
require(p.pool!=address(0) && p.token0!=address(0) && p.token0<p.token1 && (p.kind==2 || p.kind==3),"POOL");
if(i>0)require(pools[i-1].pool<p.pool,"POOL_ORDER");pools[i]=p;
}
uint256 previous;
for(uint256 i;i<nr;++i) {
Route memory r=routes[i];
require(r.first<np && r.third<np && r.first!=r.third,"ROUTE");
uint256 key=(uint256(r.first)<<32)|(uint256(r.second)<<16)|r.third;
if(i>0)require(key>previous,"ROUTE_ORDER");previous=key;
address a=_other(pools[r.first],WETH);
if(r.second==DIRECT) require(_other(pools[r.third],a)==WETH,"CYCLE");
else {
require(r.second<np && r.first!=r.second && r.second!=r.third,"MIDDLE");
address b=_other(pools[r.second],a);
require(b!=WETH && _other(pools[r.third],b)==WETH,"TRIANGLE");
}
routes[i]=r;
}
}
// Executor construction validates every identity and route once. Its
// immutable catalog hash protects those bytes on every compute. Decode
// them without repeating graph validation inside the quote gas budget.
function _decodeCatalog(bytes calldata data) private pure returns(Pool[] memory pools,Route[] memory routes) {
require(data.length>=4,"CATALOG");uint256 np=_u16(data,0);uint256 nr=_u16(data,2);
require(np>0 && np<=64 && nr>0 && nr<=512 && data.length==4+61*np+6*nr,"BOUNDS");
pools=new Pool[](np);routes=new Route[](nr);
for(uint256 i;i<np;++i) {
uint256 at=4+61*i;
pools[i]=Pool(_address(data,at),_address(data,at+20),_address(data,at+40),uint8(data[at+60]));
}
for(uint256 i;i<nr;++i) {
uint256 at=4+61*np+6*i;
routes[i]=Route(_u16(data,at),_u16(data,at+2),_u16(data,at+4));
}
}
function _other(Pool memory p,address token) private pure returns(address) {
require(token==p.token0 || token==p.token1,"TOKEN");return token==p.token0?p.token1:p.token0;
}
function snapshot(Pool calldata p) external view returns(Snapshot memory s) {
require(msg.sender==address(this),"SELF");s.identity=p;
if(p.kind==2) (s.r0,s.r1,)=ICycleV2(p.pool).getReserves();
else {
s.v3=fetchState(p.pool,0);require(s.v3.sqrtPriceX96>0 && s.v3.fee<1e6,"STATE");
// One extra slot0 read supplies oracle metadata; do not decode its
// protocol-fee tail as uint8 (Pancake uses a wider field).
(bool ok,bytes memory data)=p.pool.staticcall(abi.encodeWithSignature("slot0()"));
require(ok && data.length==224,"SLOT0");
uint256 index;uint256 cardinality;uint256 next;uint256 protocol;
assembly{index:=mload(add(data,96)) cardinality:=mload(add(data,128)) next:=mload(add(data,160)) protocol:=mload(add(data,192))}
require(cardinality>0 && cardinality<=type(uint16).max && index<cardinality && next>=cardinality && next<=type(uint16).max,"ORACLE");
uint256 updated=next>cardinality && index==cardinality-1?next:cardinality;
IUniswapV3Pool v=IUniswapV3Pool(p.pool);
(uint32 timestamp,,,)=v.observations((index+1)%updated);
if(timestamp==0)s.storageGas+=NEW_STORAGE_GAS;
if(v.feeGrowthGlobal0X128()==0)s.storageGas+=NEW_STORAGE_GAS;
if(v.feeGrowthGlobal1X128()==0)s.storageGas+=NEW_STORAGE_GAS;
(uint128 fee0,uint128 fee1)=v.protocolFees();
if(protocol!=0 && fee0==0 && fee1==0)s.storageGas+=NEW_STORAGE_GAS;
// Pancake's enabled liquidity-mining module accrues rewards even
// without a tick crossing. It is additional execution work.
if(ICycleV3Identity(p.pool).factory()==PANCAKE_FACTORY && ICycleV3Identity(p.pool).lmPool()!=address(0))s.storageGas+=PANCAKE_REWARD_GAS;
s.r0=FullMath.mulDiv(s.v3.liquidity,2**96,s.v3.sqrtPriceX96);
s.r1=FullMath.mulDiv(s.v3.liquidity,s.v3.sqrtPriceX96,2**96);
}
require(s.r0<=type(uint112).max && s.r1<=type(uint112).max,"RESERVES");s.available=true;
}
function _reserves(Snapshot memory s,address input) private pure returns(uint256 x,uint256 y,uint256 fee) {
(x,y)=input==s.identity.token0?(s.r0,s.r1):(s.r1,s.r0);
fee=s.identity.kind==2?997000:1000000-s.v3.fee;
}
function oriented(Snapshot memory s,address input) private pure returns(BexCycleSizing.Reserves memory r){
(r.x,r.y,r.fee)=_reserves(s,input);
}
function seed(Snapshot memory buy,Snapshot memory middle,Snapshot memory sell) private view returns(uint256 amount,uint256 score){
if(!buy.available || !middle.available || !sell.available)return(0,0);
address token=_other(buy.identity,WETH);address next=_other(middle.identity,token);
return BexCycleSizing.seed(oriented(buy,WETH),oriented(middle,token),oriented(sell,next),true);
}
function _v3(Snapshot memory s,address input,uint256 amount,bool borrow,bool measure) private view returns(uint256 value,uint256 workGas) {
require(amount>0 && amount<=uint256(type(int256).max),"AMOUNT");
bool z=input==s.identity.token0;int256 specified=borrow?-int256(amount):int256(amount);
uint160 limit=z?TickMath.MIN_SQRT_RATIO+1:TickMath.MAX_SQRT_RATIO-1;
(SwapState memory state,uint128 liquidity,uint160 price)=setInitialState(s.v3,specified,limit,z);
uint256 steps;
while(state.amountSpecifiedRemaining!=0 && price!=limit) {
require(steps++<32,"TICK_BUDGET");
int24 nextTick;bool initialized;uint160 next;
if(measure)(nextTick,initialized,next)=getNextTickAndPrice(s.v3.tickSpacing,state.tick,IUniswapV3Pool(s.identity.pool),z);
(,price,liquidity)=processSwapWithinTick(IUniswapV3Pool(s.identity.pool),s.v3,state,price,liquidity,limit,z,!borrow);
if(measure){
workGas+=QUOTE_STEP_GAS;
if(initialized && price==next){
workGas+=INITIALIZED_CROSS_GAS;
(,,uint256 outside0,uint256 outside1,int56 cumulative,uint160 secondsPerLiquidity,uint32 secondsOutside,)=IUniswapV3Pool(s.identity.pool).ticks(nextTick);
if(outside0==0)workGas+=NEW_STORAGE_GAS;
if(outside1==0)workGas+=NEW_STORAGE_GAS;
if(cumulative==0 && secondsPerLiquidity==0 && secondsOutside==0)workGas+=NEW_STORAGE_GAS;
}
}
}
if(measure)workGas+=s.storageGas;
require(state.amountSpecifiedRemaining==0,"PARTIAL_QUOTE");
return(borrow?uint256(state.amountCalculated):uint256(-state.amountCalculated),workGas);
}
function _out(Snapshot memory s,address token,uint256 amount,bool measure) private view returns(uint256,uint256) {
if(amount==0)return(0,0);
if(s.identity.kind==3)return _v3(s,token,amount,false,measure);
(uint256 x,uint256 y,)=_reserves(s,token);
return(FullMath.mulDiv(y,amount*997,x*1000+amount*997),0);
}
function seedDirect(Snapshot memory buy,Snapshot memory sell) private view returns(uint256 amount,uint256 score){
if(!buy.available || !sell.available)return(0,0);
BexCycleSizing.Reserves memory middle;
return BexCycleSizing.seed(oriented(buy,WETH),middle,oriented(sell,_other(buy.identity,WETH)),false);
}
struct Evaluation {Candidate best;uint256 quotes;uint256 gasRejected;uint256 executionGas;uint256 unavailableQuotes;uint256 budgetSkippedQuotes;uint256 bestEighths;}
function _better(Candidate memory c,Candidate memory best,Economics calldata e) private view returns(bool){
uint256 reserve=500000*block.basefee;
if(c.gross<=reserve)return false;
uint256 payment=reserve+(c.gross-reserve)*e.builderShareBps/10000;
return c.gross-payment>=e.minimumRetained && payment<=e.maximumPayment &&
(c.gross>best.gross || (c.gross==best.gross && c.amount<best.amount));
}
function quoteSize(Snapshot calldata buy,Snapshot calldata middle,Snapshot calldata sell,bool triangle,uint256 amount)
external view returns(Candidate memory c,uint256 estimate){
require(msg.sender==address(this),"SELF");
c.amount=amount;
(uint256 bw,uint256 bt,)=_reserves(buy,WETH);
if(buy.identity.kind==2 && amount>=bt)return(c,0);
uint256 work;
if(buy.identity.kind==2)c.repayment=FullMath.mulDiv(bw*amount,1000,(bt-amount)*997)+1;
else(c.repayment,work)=_v3(buy,WETH,amount,true,triangle);
if(c.repayment==0 || c.repayment>50 ether)return(c,0);
address token=_other(buy.identity,WETH);uint256 received=amount;uint256 legGas;
if(triangle){
(received,legGas)=_out(middle,token,received,true);work+=legGas;
token=_other(middle.identity,token);
}
(received,legGas)=_out(sell,token,received,triangle);work+=legGas;
if(received>c.repayment)c.gross=received-c.repayment;
estimate=triangle?TRIANGLE_BASE_GAS+work:0;
}
function evaluate(Snapshot calldata buy,Snapshot calldata middle,Snapshot calldata sell,bool triangle,uint256 initial,Economics calldata e)
external view returns(Evaluation memory result) {
require(msg.sender==address(this),"SELF");
// Start near the analytic optimum. Every size remains an exact quote;
// a failed large size cannot erase an earlier successful candidate.
uint256[7] memory factors=[uint256(4),1,2,3,5,6,8];
for(uint256 i;i<7;++i) {
uint256 amount=initial*factors[i]/4;
if(amount==0 || amount>type(uint112).max)continue;
if(gasleft()<205000){result.budgetSkippedQuotes=7-i;break;}
++result.quotes;
try this.quoteSize{gas:180000}(buy,middle,sell,triangle,amount) returns(Candidate memory c,uint256 estimate){
if(triangle && estimate>EXECUTION_ADMISSION_GAS){++result.gasRejected;continue;}
if(_better(c,result.best,e)){
result.best=c;result.executionGas=estimate;result.bestEighths=factors[i]*2;
}
}catch{++result.unavailableQuotes;}
}
}
function inspect(bytes calldata catalog,Economics calldata e) external view returns(Report memory report) {
require(e.minimumRetained>0 && e.builderShareBps<=10000 && e.maximumPayment>0,"ECONOMICS");
(Pool[] memory pools,Route[] memory routes)=_decodeCatalog(catalog);
Snapshot[] memory states=new Snapshot[](pools.length);
for(uint256 i;i<pools.length;++i) {
++report.poolReads;
try this.snapshot{gas:60000}(pools[i]) returns(Snapshot memory s){states[i]=s;}
catch{++report.unavailablePools;}
}
// Separate 8/6 candidate quotas retain both families' search breadth.
uint256[14] memory indices;uint256[14] memory seeds;uint256[14] memory scores;
for(uint256 i;i<routes.length;++i) {
Route memory r=routes[i];bool triangle=r.second!=DIRECT;
if(!states[r.first].available || !states[r.third].available || (triangle && !states[r.second].available))continue;
uint256 amount;uint256 score;
if(triangle)(amount,score)=seed(states[r.first],states[r.second],states[r.third]);
else (amount,score)=seedDirect(states[r.first],states[r.third]);
if(score==0)continue;++report.marginal;
if(score<=500000*block.basefee)continue;
uint256 start=triangle?8:0;uint256 end=triangle?14:8;
for(uint256 j=start;j<end;++j)if(score>scores[j]){
for(uint256 k=end-1;k>j;--k){scores[k]=scores[k-1];seeds[k]=seeds[k-1];indices[k]=indices[k-1];}
scores[j]=score;seeds[j]=amount;indices[j]=i;break;
}
}
uint256 winningSeed;uint256 winningEighths;
for(uint256 i;i<14;++i){
if(scores[i]==0)continue;
// Leave room to encode diagnostics and return through the executor.
// A skipped quote is explicit; it is never an approximate result.
if(gasleft()<1150000){++report.budgetSkipped;continue;}
Route memory r=routes[indices[i]];bool triangle=r.second!=DIRECT;
++report.shortlisted;
try this.evaluate{gas:1000000}(states[r.first],states[triangle?r.second:r.third],states[r.third],triangle,seeds[i],e) returns(Evaluation memory v){
report.quotes+=v.quotes;report.gasRejected+=v.gasRejected;v.best.route=indices[i]+1;
if(v.best.gross>report.best.gross){report.best=v.best;report.executionGas=v.executionGas;winningSeed=seeds[i];winningEighths=v.bestEighths;}
report.unavailableQuotes+=v.unavailableQuotes;report.budgetSkippedQuotes+=v.budgetSkippedQuotes;
}catch{++report.unavailable;}
}
if(report.best.gross==0)return report;
Route memory winner=routes[report.best.route-1];bool winnerTriangle=winner.second!=DIRECT;
// Spend only spare budget on the two eighth-grid neighbors of the
// coarse winner. The original exact candidate remains available.
for(uint256 i;i<2;++i){
uint256 factor=i==0?winningEighths-1:winningEighths+1;
if(factor>16)continue;
uint256 amount=winningSeed*factor/8;
if(amount==0 || amount>type(uint112).max)continue;
if(gasleft()<225000){++report.budgetSkippedQuotes;continue;}
++report.refinementQuotes;++report.quotes;
try this.quoteSize{gas:180000}(states[winner.first],states[winnerTriangle?winner.second:winner.third],states[winner.third],winnerTriangle,amount) returns(Candidate memory c,uint256 estimate){
if(winnerTriangle && estimate>EXECUTION_ADMISSION_GAS){++report.gasRejected;continue;}
if(_better(c,report.best,e)){c.route=report.best.route;report.best=c;report.executionGas=estimate;}
}catch{++report.unavailableQuotes;}
}
}
}
src/bex/BexCycleSizing.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {FullMath} from "src/libraries/uniswapv3/FullMath.sol";
import {BitMath} from "src/libraries/uniswapv3/BitMath.sol";
/// @notice Shared analytic seed for quoting and execution admission. The
/// approximated reserves never establish realized profit or replace tick quotes.
library BexCycleSizing {
struct Reserves {uint256 x;uint256 y;uint256 fee;}
function virtualReserves(uint128 liquidity,uint160 price) internal pure returns(uint256 a,uint256 b){
require(price>0,"STATE");
a=FullMath.mulDiv(liquidity,2**96,price);b=FullMath.mulDiv(liquidity,price,2**96);
require(a<=type(uint112).max && b<=type(uint112).max,"RESERVES");
}
function sqrt(uint256 n) private pure returns(uint256 x){
if(n==0)return 0;x=uint256(1)<<(BitMath.mostSignificantBit(n)/2);
for(uint256 i;i<7;++i)x=(x+n/x)/2;return x<n/x?x:n/x;
}
function seed(Reserves memory buy,Reserves memory middle,Reserves memory sell,bool triangle) internal pure returns(uint256 amount,uint256 score){
uint256 bw=buy.x;uint256 bt=buy.y;uint256 fb=buy.fee;
uint256 st=sell.x;uint256 sw=sell.y;uint256 fs=sell.fee;
if(bw==0 || bt==0 || st==0 || sw==0)return(0,0);
if(triangle){
if(middle.x==0 || middle.y==0)return(0,0);
uint256 divisor=sell.x*1e6+middle.y*sell.fee;
st=FullMath.mulDiv(middle.x,sell.x*1e6,divisor);
sw=FullMath.mulDiv(middle.y*sell.fee,sell.y,divisor);fs=middle.fee;
if(st==0 || sw==0)return(0,0);
}
uint256 a=sqrt(FullMath.mulDiv(sw*st,fb*fs,1e12));uint256 b=sqrt(bw*bt);
if(a*bt<=b*st)return(0,0);
amount=(a*bt-b*st)/(a+b*fs/1e6);
if(amount==0 || amount>=bt)return(0,0);
uint256 repay=FullMath.mulDiv(bw*amount,1e6,(bt-amount)*fb)+1;
uint256 out=FullMath.mulDiv(sw,amount*fs,st*1e6+amount*fs);
if(out>repay)score=out-repay;
}
}
src/bex/BexSelectedCatalogValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {BexCycleQuoter} from "./BexCycleQuoter.sol";
/// @notice Constructor-only catalogue validator for the selected-route executor.
/// @dev This deliberately exposes the same two-call ABI surface used by
/// EurekaBexSelectedCycles, without the quotation, snapshot, or sizing
/// code in BexCycleQuoter. Keep validation behavior byte-for-byte
/// compatible at the semantic level with BexCycleQuoter._catalog.
contract BexSelectedCatalogValidator {
address public immutable WETH;
uint16 private constant DIRECT = type(uint16).max;
constructor(address weth) {
WETH = weth;
}
function _u16(bytes calldata data, uint256 at) private pure returns (uint16 value) {
assembly {
value := shr(240, calldataload(add(data.offset, at)))
}
}
function _address(bytes calldata data, uint256 at) private pure returns (address value) {
assembly {
value := shr(96, calldataload(add(data.offset, at)))
}
}
function _other(BexCycleQuoter.Pool memory p, address token) private pure returns (address) {
require(token == p.token0 || token == p.token1, "TOKEN");
return token == p.token0 ? p.token1 : p.token0;
}
/// @notice Decode and validate the reviewed packed catalogue.
/// @dev ABI-compatible with BexCycleQuoter._catalog for the selected
/// executor's constructor call.
function _catalog(bytes calldata data)
external
view
returns (BexCycleQuoter.Pool[] memory pools, BexCycleQuoter.Route[] memory routes)
{
require(data.length >= 4, "CATALOG");
uint256 np = _u16(data, 0);
uint256 nr = _u16(data, 2);
require(np > 0 && np <= 64 && nr > 0 && nr <= 512 && data.length == 4 + 61 * np + 6 * nr, "BOUNDS");
pools = new BexCycleQuoter.Pool[](np);
routes = new BexCycleQuoter.Route[](nr);
for (uint256 i; i < np; ++i) {
uint256 at = 4 + 61 * i;
BexCycleQuoter.Pool memory p = BexCycleQuoter.Pool({
pool: _address(data, at),
token0: _address(data, at + 20),
token1: _address(data, at + 40),
kind: uint8(data[at + 60])
});
require(p.pool != address(0) && p.token0 != address(0) && p.token0 < p.token1 && (p.kind == 2 || p.kind == 3), "POOL");
if (i > 0) require(pools[i - 1].pool < p.pool, "POOL_ORDER");
pools[i] = p;
}
uint256 previous;
for (uint256 i; i < nr; ++i) {
uint256 at = 4 + 61 * np + 6 * i;
BexCycleQuoter.Route memory r = BexCycleQuoter.Route({
first: _u16(data, at), second: _u16(data, at + 2), third: _u16(data, at + 4)
});
require(r.first < np && r.third < np && r.first != r.third, "ROUTE");
uint256 key = (uint256(r.first) << 32) | (uint256(r.second) << 16) | r.third;
if (i > 0) require(key > previous, "ROUTE_ORDER");
previous = key;
address a = _other(pools[r.first], WETH);
if (r.second == DIRECT) {
require(_other(pools[r.third], a) == WETH, "CYCLE");
} else {
require(r.second < np && r.first != r.second && r.second != r.third, "MIDDLE");
require(pools[r.first].kind == 3 && pools[r.second].kind == 3 && pools[r.third].kind == 3, "TRIANGLE_KIND");
address b = _other(pools[r.second], a);
require(b != WETH && _other(pools[r.third], b) == WETH, "TRIANGLE");
}
routes[i] = r;
}
}
}
src/bex/EurekaBexBatch.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {BexBatchQuoter, IBatchV2} from "./BexBatchQuoter.sol";
import {TickMath} from "src/libraries/uniswapv3/TickMath.sol";
interface IBatchToken {
function balanceOf(address) external view returns (uint256);
function withdraw(uint256) external;
}
interface IBatchIdentity {
function token0() external view returns (address);
function token1() external view returns (address);
function factory() external view returns (address);
function fee() external view returns (uint24);
}
interface IBatchFactory {
function getPair(address,address) external view returns (address);
function getPool(address,address,uint24) external view returns (address);
}
interface IBatchSwapV2 {
function swap(uint256,uint256,address,bytes calldata) external;
}
interface IBatchSwapV3 {
function swap(address,bool,int256,uint160,bytes calldata) external returns (int256,int256);
}
/// @notice Immutable, reviewed standard V2 (0.3%) and fixed-fee V3 WETH cycles.
/// Packed result: bits 0..111 amount, bits 112..127 one-based route, rest zero.
/// All economics use newly earned WETH; existing inventory cannot fund a trade.
contract EurekaBexBatch is BexBatchQuoter {
struct Policy {
address recipient;
address weth;
uint256 minimumRetained;
uint256 builderShareBps;
uint256 maximumPayment;
}
struct Identity { address factory; uint24 fee; bytes32 codeHash; }
Policy public policy;
Pool[] public pools;
Route[] public routes;
Identity[] public identities;
bytes32 public immutable policyHash;
address public immutable owner;
bool public paused = true;
uint256 public lastExecutionBlock;
// Callback state belongs to this transaction; avoid persistent writes/refunds.
uint8 transient private phase; // 0 idle, 1 flash callback, 2 sale, 3 repaid, 4 settlement
uint256 transient private activeRoute;
uint256 transient private activeAmount;
bool transient private innerCallback;
event BatchExecuted(bytes32 indexed requestId, uint256 indexed targetBlock,
uint256 result, uint256 grossProfit, uint256 builderPayment, uint256 retainedProfit);
event Paused(bool value);
constructor(Policy memory p, Pool[] memory ps, Route[] memory rs, Identity[] memory ids)
BexBatchQuoter(p.weth)
{
require(p.recipient != address(0) && p.recipient != address(this), "IDENTITY");
require(p.weth.code.length > 0 && p.minimumRetained > 0, "POLICY");
require(p.builderShareBps <= 10000 && p.maximumPayment > 0, "PAYMENT");
// Bounds deliberately limited to the measured 38-pool / 158-route batch.
require(ps.length > 0 && ps.length <= 38 && rs.length > 0 && rs.length <= 158 && ids.length == ps.length, "BUDGET");
for (uint256 i; i < ps.length; ++i) {
Pool memory pool = ps[i]; Identity memory id = ids[i];
require(pool.pool.code.length > 0 && pool.token.code.length > 0 && pool.token != p.weth, "POOL");
require(pool.kind == 2 || pool.kind == 3, "KIND");
for (uint256 j; j < i; ++j) require(ps[j].pool != pool.pool, "DUPLICATE_POOL");
IBatchIdentity v = IBatchIdentity(pool.pool);
(address t0,address t1) = pool.token < p.weth ? (pool.token,p.weth) : (p.weth,pool.token);
require(v.token0() == t0 && v.token1() == t1, "TOKENS");
require(id.factory.code.length > 0 && v.factory() == id.factory && pool.pool.codehash == id.codeHash, "POOL_IDENTITY");
if (pool.kind == 2) {
require(id.fee == 3000 && IBatchFactory(id.factory).getPair(t0,t1) == pool.pool, "V2_IDENTITY");
} else {
require(id.fee < 1000000 && v.fee() == id.fee && IBatchFactory(id.factory).getPool(t0,t1,id.fee) == pool.pool, "V3_IDENTITY");
}
pools.push(pool); identities.push(id);
}
uint256[] memory seen = new uint256[](ps.length);
for (uint256 i; i < rs.length; ++i) {
Route memory r = rs[i];
require(r.buy < ps.length && r.sell < ps.length && r.buy != r.sell, "ROUTE");
require(ps[r.buy].token == ps[r.sell].token, "ROUTE_TOKEN");
uint256 bit = uint256(1) << r.sell;
require(seen[r.buy] & bit == 0, "DUPLICATE_ROUTE");
seen[r.buy] |= bit;
routes.push(r);
}
policy = p; owner = msg.sender;
policyHash = keccak256(abi.encode("ETH58_BATCH_COINBASE_V2",p,ps,rs,ids));
}
function setPaused(bool value) external {
require(msg.sender == owner && phase == 0, "OWNER");
paused = value; emit Paused(value);
}
function requestIdentity(uint256 targetBlock, bytes32 parentHash) public view returns (bytes32) {
return keccak256(abi.encode(block.chainid,address(this),policyHash,targetBlock,parentHash));
}
function _economics(uint256 gross) private view returns (uint256 payment, uint256 retained) {
uint256 gasCost = 500000*block.basefee;
if (gross <= gasCost) return (gasCost,0);
payment = gasCost+(gross-gasCost)*policy.builderShareBps/10000;
retained = gross-payment;
}
function _admissible(uint256 gross) internal view override returns (bool) {
(uint256 payment,uint256 retained) = _economics(gross);
return retained >= policy.minimumRetained && payment <= policy.maximumPayment;
}
/// @notice Diagnostics expose unavailable shortlisted routes. A zero result
/// means no executable winner was found, not an exhaustive absence of arbs.
function inspect() public view returns (Report memory report) {
if (paused || phase != 0 || lastExecutionBlock == block.number) return report;
for (uint256 i; i < pools.length; ++i) _checkIdentity(i);
return _search(pools,routes);
}
function compute() external view returns (uint256 result) {
Report memory report = inspect();
if (report.best.gross == 0) return 0;
return (report.best.route << 112) | report.best.amount;
}
function _checkIdentity(uint256 index) private view {
Pool memory p = pools[index];
require(p.pool.codehash == identities[index].codeHash, "CODE_CHANGED");
if (p.kind == 3) require(IBatchIdentity(p.pool).fee() == identities[index].fee, "FEE_CHANGED");
}
function execute(uint256 targetBlock, bytes32 parentHash, bytes32 requestId, uint256 result) external {
require(!paused && phase == 0, "INACTIVE");
require(msg.sender == block.coinbase, "BUILDER");
require(block.number == targetBlock && blockhash(block.number-1) == parentHash, "TARGET");
require(requestId == requestIdentity(targetBlock,parentHash), "REQUEST");
require(lastExecutionBlock != block.number, "DUPLICATE");
uint256 route = result >> 112; uint256 amount = uint112(result);
require(result >> 128 == 0 && route > 0 && route <= routes.length && amount > 0, "RESULT");
Route memory r = routes[route-1];
_checkIdentity(r.buy); _checkIdentity(r.sell);
Pool memory buy = pools[r.buy]; Pool memory sell = pools[r.sell];
(uint256 initial,) = _seed(_snapshot(buy),_snapshot(sell));
uint256[7] memory factors = [uint256(1),2,3,4,5,6,8];
bool allowed;
for (uint256 i; i < 7; ++i) if (amount == initial*factors[i]/4) allowed = true;
require(allowed, "GRID");
uint256 beforeWeth = IBatchToken(WETH).balanceOf(address(this));
uint256 beforeToken = IBatchToken(buy.token).balanceOf(address(this));
activeRoute = route-1; activeAmount = amount; phase = 1; lastExecutionBlock = block.number;
if (buy.kind == 2) {
bool t0 = buy.token < WETH;
IBatchSwapV2(buy.pool).swap(t0?amount:0,t0?0:amount,address(this),hex"01");
} else {
bool z = WETH < buy.token;
IBatchSwapV3(buy.pool).swap(address(this),z,-int256(amount),_limit(z),hex"01");
}
require(phase == 3, "MISSING_FLASH"); phase = 4;
uint256 afterWeth = IBatchToken(WETH).balanceOf(address(this));
require(afterWeth > beforeWeth, "PROFIT");
uint256 gross = afterWeth-beforeWeth;
(uint256 payment,uint256 retained) = _economics(gross);
require(retained >= policy.minimumRetained && payment <= policy.maximumPayment, "PROFIT_FLOOR");
if (payment != 0) {
uint256 beforeCoinbase = block.coinbase.balance;
IBatchToken(WETH).withdraw(payment);
(bool ok,) = payable(block.coinbase).call{value:payment}("");
require(ok && block.coinbase.balance >= beforeCoinbase + payment,"BID");
}
_pay(WETH,policy.recipient,retained);
require(IBatchToken(WETH).balanceOf(address(this)) == beforeWeth, "INVENTORY");
require(IBatchToken(buy.token).balanceOf(address(this)) == beforeToken, "TOKEN_INVENTORY");
emit BatchExecuted(requestId,targetBlock,result,gross,payment,retained);
activeAmount = 0; activeRoute = 0; phase = 0;
}
function uniswapV2Call(address sender,uint256 a,uint256 b,bytes calldata data) external {
Pool memory buy = pools[routes[activeRoute].buy];
require(phase == 1 && buy.kind == 2 && msg.sender == buy.pool && sender == address(this), "CALLBACK");
require(data.length == 1 && data[0] == 0x01, "DATA");
bool t0 = buy.token < WETH;
require(a == (t0?activeAmount:0) && b == (t0?0:activeAmount), "BORROW_AMOUNT");
(uint112 r0,uint112 r1,) = IBatchV2(buy.pool).getReserves();
(uint256 token,uint256 weth) = t0?(r0,r1):(r1,r0);
require(activeAmount < token, "SIZE");
_finish(weth*activeAmount*1000/((token-activeAmount)*997)+1);
}
function uniswapV3SwapCallback(int256 a,int256 b,bytes calldata data) external { _callback(a,b,data); }
function pancakeV3SwapCallback(int256 a,int256 b,bytes calldata data) external { _callback(a,b,data); }
function _callback(int256 a,int256 b,bytes calldata data) private {
Route memory r = routes[activeRoute];
if (phase == 1) {
Pool memory buy = pools[r.buy]; bool t0 = buy.token < WETH;
require(buy.kind == 3 && msg.sender == buy.pool, "CALLBACK");
require(data.length == 1 && data[0] == 0x01, "DATA");
require((t0?a:b) == -int256(activeAmount) && (t0?b:a) > 0, "BORROW_DELTAS");
_finish(uint256(t0?b:a));
} else {
Pool memory sell = pools[r.sell]; bool t0 = sell.token < WETH;
require(phase == 2 && innerCallback && sell.kind == 3 && msg.sender == sell.pool && data.length == 0, "INNER_CALLBACK");
require((t0?a:b) == int256(activeAmount) && (t0?b:a) < 0, "SELL_DELTAS");
innerCallback = false; _pay(sell.token,sell.pool,activeAmount);
}
}
function _finish(uint256 repayment) private {
require(repayment > 0 && repayment <= MAX_REPAYMENT, "REPAYMENT"); phase = 2;
Route memory r = routes[activeRoute]; Pool memory sell = pools[r.sell];
uint256 beforeWeth = IBatchToken(WETH).balanceOf(address(this));
uint256 beforeToken = IBatchToken(sell.token).balanceOf(address(this));
require(beforeToken >= activeAmount, "INPUT");
bool z = sell.token < WETH;
if (sell.kind == 2) {
(uint112 a,uint112 b,) = IBatchV2(sell.pool).getReserves();
(uint256 token,uint256 weth) = z?(a,b):(b,a);
uint256 adjusted = activeAmount*997;
uint256 out = adjusted*weth/(token*1000+adjusted);
require(out > 0, "OUTPUT");
_pay(sell.token,sell.pool,activeAmount);
IBatchSwapV2(sell.pool).swap(z?0:out,z?out:0,address(this),"");
} else {
innerCallback = true;
IBatchSwapV3(sell.pool).swap(address(this),z,int256(activeAmount),_limit(z),"");
require(!innerCallback, "MISSING_INNER");
}
require(IBatchToken(sell.token).balanceOf(address(this)) == beforeToken-activeAmount, "PARTIAL_INPUT");
require(IBatchToken(WETH).balanceOf(address(this)) > beforeWeth+repayment, "PROFIT");
phase = 3; _pay(WETH,pools[r.buy].pool,repayment);
}
function _limit(bool z) private pure returns (uint160) {
return z?TickMath.MIN_SQRT_RATIO+1:TickMath.MAX_SQRT_RATIO-1;
}
function _pay(address token,address to,uint256 amount) private {
(bool ok,bytes memory data) = token.call(abi.encodeWithSignature("transfer(address,uint256)",to,amount));
require(ok && (data.length == 0 || (data.length == 32 && abi.decode(data,(bool)))), "TRANSFER");
}
receive() external payable { require(msg.sender == WETH, "WETH_ONLY"); }
}
src/interfaces/uniswapv3/IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "./IUniswapV3PoolImmutables.sol";
import "./IUniswapV3PoolState.sol";
import "./IUniswapV3PoolDerivedState.sol";
import "./IUniswapV3PoolActions.sol";
import "./IUniswapV3PoolOwnerActions.sol";
import "./IUniswapV3PoolEvents.sol";
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{}
src/interfaces/uniswapv3/IUniswapV3PoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(int24 tickLower, int24 tickUpper, uint128 amount) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @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
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
src/interfaces/uniswapv3/IUniswapV3PoolDerivedState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(
uint32[] calldata secondsAgos
) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(
int24 tickLower,
int24 tickUpper
) external view returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside);
}
src/interfaces/uniswapv3/IUniswapV3PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 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 price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
src/interfaces/uniswapv3/IUniswapV3PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
src/interfaces/uniswapv3/IUniswapV3PoolOwnerActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
src/interfaces/uniswapv3/IUniswapV3PoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(
int24 tick
)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(
bytes32 key
)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(
uint256 index
)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
src/libraries/uniswapv3/BitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
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
/// @dev The function satisfies the property:
/// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)
/// @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);
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
/// @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
/// @dev The function satisfies the property:
/// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)
/// @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);
r = 255;
if (x & type(uint128).max > 0) {
r -= 128;
} else {
x >>= 128;
}
if (x & type(uint64).max > 0) {
r -= 64;
} else {
x >>= 64;
}
if (x & type(uint32).max > 0) {
r -= 32;
} else {
x >>= 32;
}
if (x & type(uint16).max > 0) {
r -= 16;
} else {
x >>= 16;
}
if (x & type(uint8).max > 0) {
r -= 8;
} else {
x >>= 8;
}
if (x & 0xf > 0) {
r -= 4;
} else {
x >>= 4;
}
if (x & 0x3 > 0) {
r -= 2;
} else {
x >>= 2;
}
if (x & 0x1 > 0) r -= 1;
}
}
src/libraries/uniswapv3/FixedPoint96.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.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; // 2^96
}
src/libraries/uniswapv3/FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.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) {
// The inverse and limb recombination operate modulo 2**256.
// Solidity 0.8 checked arithmetic would reject valid wide products.
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; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
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 = (type(uint256).max - denominator + 1) & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
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 {
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 precoditions 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) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
src/libraries/uniswapv3/LiquidityMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
/// @title Math library for liquidity
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
if (y < 0) {
require((z = x - uint128(-y)) < x, "LS");
} else {
require((z = x + uint128(y)) >= x, "LA");
}
}
}
src/libraries/uniswapv3/LowGasSafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
src/libraries/uniswapv3/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
src/libraries/uniswapv3/SqrtPriceMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "./LowGasSafeMath.sol";
import "./SafeCast.sol";
import "./FullMath.sol";
import "./UnsafeMath.sol";
import "./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 LowGasSafeMath for uint256;
using SafeCast for uint256;
/// @notice Gets the next sqrt price given a delta of token0
/// @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 token0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of token0
/// @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) {
uint256 product;
unchecked { product = amount * sqrtPX96; }
if (product / amount == sqrtPX96) {
uint256 denominator;
unchecked { denominator = numerator1 + product; }
if (denominator >= numerator1) {
// always fits in 160 bits
return
uint160(
FullMath.mulDivRoundingUp(
numerator1,
sqrtPX96,
denominator
)
);
}
}
return
uint160(
UnsafeMath.divRoundingUp(
numerator1,
(numerator1 / sqrtPX96).add(amount)
)
);
} else {
uint256 product;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
unchecked { product = amount * sqrtPX96; }
require(
product / amount == sqrtPX96 &&
numerator1 > product
);
uint256 denominator = numerator1 - product;
return
FullMath
.mulDivRoundingUp(numerator1, sqrtPX96, denominator)
.toUint160();
}
}
/// @notice Gets the next sqrt price given a delta of token1
/// @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 token1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of token1
/// @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).add(quotient).toUint160();
} else {
uint256 quotient = (
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(
amount << FixedPoint96.RESOLUTION,
liquidity
)
: FullMath.mulDivRoundingUp(
amount,
FixedPoint96.Q96,
liquidity
)
);
require(sqrtPX96 > quotient);
// always fits 160 bits
return uint160(sqrtPX96 - quotient);
}
}
/// @notice Gets the next sqrt price given an input amount of token0 or token1
/// @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 token0, or token1, is being swapped in
/// @param zeroForOne Whether the amount in is token0 or token1
/// @return sqrtQX96 The price after adding the input amount to token0 or token1
function getNextSqrtPriceFromInput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountIn,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96) {
require(sqrtPX96 > 0);
require(liquidity > 0);
// 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 token0 or token1
/// @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 token0, or token1, is being swapped out
/// @param zeroForOne Whether the amount out is token0 or token1
/// @return sqrtQX96 The price after removing the output amount of token0 or token1
function getNextSqrtPriceFromOutput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountOut,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96) {
require(sqrtPX96 > 0);
require(liquidity > 0);
// 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 sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;
require(sqrtRatioAX96 > 0);
// Keep the canonical division order. Dividing liquidity before Q96
// multiplication loses precision even when the final result fits.
return roundUp
? UnsafeMath.divRoundingUp(
FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
sqrtRatioAX96
)
: FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
roundUp
? FullMath.mulDivRoundingUp(
liquidity,
sqrtRatioBX96 - sqrtRatioAX96,
FixedPoint96.Q96
)
: FullMath.mulDiv(
liquidity,
sqrtRatioBX96 - sqrtRatioAX96,
FixedPoint96.Q96
);
}
/// @notice Helper that gets signed token0 delta
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount0 delta
/// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount0) {
return
liquidity < 0
? -getAmount0Delta(
sqrtRatioAX96,
sqrtRatioBX96,
uint128(-liquidity),
false
).toInt256()
: getAmount0Delta(
sqrtRatioAX96,
sqrtRatioBX96,
uint128(liquidity),
true
).toInt256();
}
/// @notice Helper that gets signed token1 delta
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount1 delta
/// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount1) {
return
liquidity < 0
? -getAmount1Delta(
sqrtRatioAX96,
sqrtRatioBX96,
uint128(-liquidity),
false
).toInt256()
: getAmount1Delta(
sqrtRatioAX96,
sqrtRatioBX96,
uint128(liquidity),
true
).toInt256();
}
}
src/libraries/uniswapv3/SwapMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "./FullMath.sol";
import "./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 {
/// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
/// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
/// @param sqrtRatioCurrentX96 The current sqrt price of the pool
/// @param sqrtRatioTargetX96 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 sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target
/// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
/// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
/// @return feeAmount The amount of input that will be taken as a fee
function computeSwapStep(
uint160 sqrtRatioCurrentX96,
uint160 sqrtRatioTargetX96,
uint128 liquidity,
int256 amountRemaining,
uint24 feePips,
bool zeroForOne
)
internal
pure
returns (
uint160 sqrtRatioNextX96,
uint256 amountIn,
uint256 amountOut,
uint256 feeAmount
)
{
require(zeroForOne == sqrtRatioCurrentX96 >= sqrtRatioTargetX96, "SPD");
bool exactIn = amountRemaining >= 0;
if (exactIn) {
uint256 amountRemainingLessFee = FullMath.mulDiv(
uint256(amountRemaining),
1e6 - feePips,
1e6
);
amountIn = zeroForOne
? SqrtPriceMath.getAmount0Delta(
sqrtRatioTargetX96,
sqrtRatioCurrentX96,
liquidity,
true
)
: SqrtPriceMath.getAmount1Delta(
sqrtRatioCurrentX96,
sqrtRatioTargetX96,
liquidity,
true
);
if (amountRemainingLessFee >= amountIn)
sqrtRatioNextX96 = sqrtRatioTargetX96;
else
sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
sqrtRatioCurrentX96,
liquidity,
amountRemainingLessFee,
zeroForOne
);
} else {
amountOut = zeroForOne
? SqrtPriceMath.getAmount1Delta(
sqrtRatioTargetX96,
sqrtRatioCurrentX96,
liquidity,
false
)
: SqrtPriceMath.getAmount0Delta(
sqrtRatioCurrentX96,
sqrtRatioTargetX96,
liquidity,
false
);
if (uint256(-amountRemaining) >= amountOut)
sqrtRatioNextX96 = sqrtRatioTargetX96;
else
sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(
sqrtRatioCurrentX96,
liquidity,
uint256(-amountRemaining),
zeroForOne
);
}
bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;
// get the input/output amounts
if (zeroForOne) {
amountIn = max && exactIn
? amountIn
: SqrtPriceMath.getAmount0Delta(
sqrtRatioNextX96,
sqrtRatioCurrentX96,
liquidity,
true
);
amountOut = max && !exactIn
? amountOut
: SqrtPriceMath.getAmount1Delta(
sqrtRatioNextX96,
sqrtRatioCurrentX96,
liquidity,
false
);
} else {
amountIn = max && exactIn
? amountIn
: SqrtPriceMath.getAmount1Delta(
sqrtRatioCurrentX96,
sqrtRatioNextX96,
liquidity,
true
);
amountOut = max && !exactIn
? amountOut
: SqrtPriceMath.getAmount0Delta(
sqrtRatioCurrentX96,
sqrtRatioNextX96,
liquidity,
false
);
}
// cap the output amount to not exceed the remaining output amount
if (!exactIn && amountOut > uint256(-amountRemaining)) {
amountOut = uint256(-amountRemaining);
}
if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {
// we didn't reach the target, so take the remainder of the maximum input as fee
feeAmount = uint256(amountRemaining) - amountIn;
} else {
feeAmount = FullMath.mulDivRoundingUp(
amountIn,
feePips,
1e6 - feePips
);
}
}
}
src/libraries/uniswapv3/Tick.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "./LowGasSafeMath.sol";
import "./SafeCast.sol";
import "./TickMath.sol";
import "./LiquidityMath.sol";
/// @title Tick
/// @notice Contains functions for managing tick processes and relevant calculations
/// Ithil to modify it, since it does not have access to storage arrays
library Tick {
using LowGasSafeMath for int256;
using SafeCast for int256;
// info stored for each initialized individual tick
struct Info {
// the total position liquidity that references this tick
uint128 liquidityGross;
// amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),
int128 liquidityNet;
// fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
// only has relative meaning, not absolute — the value depends on when the tick is initialized
uint256 feeGrowthOutside0X128;
uint256 feeGrowthOutside1X128;
// the cumulative tick value on the other side of the tick
int56 tickCumulativeOutside;
// the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick)
// only has relative meaning, not absolute — the value depends on when the tick is initialized
uint160 secondsPerLiquidityOutsideX128;
// the seconds spent on the other side of the tick (relative to the current tick)
// only has relative meaning, not absolute — the value depends on when the tick is initialized
uint32 secondsOutside;
// true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0
// these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks
bool initialized;
}
/// @notice Derives max liquidity per tick from given tick spacing
/// @dev Executed within the pool constructor
/// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing`
/// e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ...
/// @return The max liquidity per tick
function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128) {
int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing;
int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing;
uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1;
return type(uint128).max / numTicks;
}
/// @notice Retrieves fee growth data
/// Ithil: only use it with lower = self[tickLower] and upper = self[tickUpper]
/// @param lower The info of the lower tick boundary of the position
/// @param upper The info of the upper tick boundary of the position
/// @param tickLower The lower tick boundary of the position
/// @param tickUpper The upper tick boundary of the position
/// @param tickCurrent The current tick
/// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
/// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
/// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries
/// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries
function getFeeGrowthInside(
Tick.Info memory lower,
Tick.Info memory upper,
int24 tickLower,
int24 tickUpper,
int24 tickCurrent,
uint256 feeGrowthGlobal0X128,
uint256 feeGrowthGlobal1X128
) internal pure returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {
// calculate fee growth below
uint256 feeGrowthBelow0X128;
uint256 feeGrowthBelow1X128;
if (tickCurrent >= tickLower) {
feeGrowthBelow0X128 = lower.feeGrowthOutside0X128;
feeGrowthBelow1X128 = lower.feeGrowthOutside1X128;
} else {
feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128;
feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128;
}
// calculate fee growth above
uint256 feeGrowthAbove0X128;
uint256 feeGrowthAbove1X128;
if (tickCurrent < tickUpper) {
feeGrowthAbove0X128 = upper.feeGrowthOutside0X128;
feeGrowthAbove1X128 = upper.feeGrowthOutside1X128;
} else {
feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upper.feeGrowthOutside0X128;
feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upper.feeGrowthOutside1X128;
}
feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;
feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;
}
/// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa
/// Ithil: always use with info = self[tick]
/// @param info The info tick that will be updated
/// @param tick The tick that will be updated
/// @param tickCurrent The current tick
/// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)
/// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
/// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
/// @param secondsPerLiquidityCumulativeX128 The all-time seconds per max(1, liquidity) of the pool
/// @param tickCumulative The tick * time elapsed since the pool was first initialized
/// @param time The current block timestamp cast to a uint32
/// @param upper true for updating a position's upper tick, or false for updating a position's lower tick
/// @param maxLiquidity The maximum liquidity allocation for a single tick
/// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa
function update(
Tick.Info memory info,
int24 tick,
int24 tickCurrent,
int128 liquidityDelta,
uint256 feeGrowthGlobal0X128,
uint256 feeGrowthGlobal1X128,
uint160 secondsPerLiquidityCumulativeX128,
int56 tickCumulative,
uint32 time,
bool upper,
uint128 maxLiquidity
) internal pure returns (bool flipped) {
uint128 liquidityGrossBefore = info.liquidityGross;
uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta);
require(liquidityGrossAfter <= maxLiquidity, "LO");
flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);
if (liquidityGrossBefore == 0) {
// by convention, we assume that all growth before a tick was initialized happened _below_ the tick
if (tick <= tickCurrent) {
info.feeGrowthOutside0X128 = feeGrowthGlobal0X128;
info.feeGrowthOutside1X128 = feeGrowthGlobal1X128;
info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128;
info.tickCumulativeOutside = tickCumulative;
info.secondsOutside = time;
}
info.initialized = true;
}
info.liquidityGross = liquidityGrossAfter;
// when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)
info.liquidityNet = upper
? int256(info.liquidityNet).sub(liquidityDelta).toInt128()
: int256(info.liquidityNet).add(liquidityDelta).toInt128();
}
/// @notice Transitions to next tick as needed by price movement
/// @param info The result of the mapping containing all tick information for initialized ticks
/// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
/// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
/// @param secondsPerLiquidityCumulativeX128 The current seconds per liquidity
/// @param tickCumulative The tick * time elapsed since the pool was first initialized
/// @param time The current block.timestamp
/// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)
function cross(
Tick.Info memory info,
uint256 feeGrowthGlobal0X128,
uint256 feeGrowthGlobal1X128,
uint160 secondsPerLiquidityCumulativeX128,
int56 tickCumulative,
uint32 time
) internal pure returns (int128 liquidityNet) {
info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128;
info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128;
info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128 - info.secondsPerLiquidityOutsideX128;
info.tickCumulativeOutside = tickCumulative - info.tickCumulativeOutside;
info.secondsOutside = time - info.secondsOutside;
liquidityNet = info.liquidityNet;
}
}
src/libraries/uniswapv3/TickBitmap.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "./BitMath.sol";
/// @title Packed tick initialized state library
/// @notice Stores a packed mapping of tick index to its initialized state
/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
library TickBitmap {
/// @notice Computes the position in the mapping where the initialized bit for a tick lives
/// @param tick The tick for which to compute the position
/// @return wordPos The key in the mapping containing the word in which the bit is stored
/// @return bitPos The bit position in the word where the flag is stored
/// @dev simply divides @param tick by 256 with remainder: tick = wordPos * 256 + bitPos
function position(
int24 tick
) internal pure returns (int16 wordPos, uint8 bitPos) {
wordPos = int16(tick >> 8);
bitPos = uint8(int8(tick % 256));
}
/// Written by Ithil
function computeWordPos(
int24 tick,
int24 tickSpacing,
bool lte
) internal pure returns (int16 wordPos) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity
(wordPos, ) = lte ? position(compressed) : position(compressed + 1);
}
/// @notice Flips the initialized state for a given tick from false to true, or vice versa
/// @param selfResult The result of the mapping in which to flip the tick (Ithil modified)
/// @param tick The tick to flip
/// @param tickSpacing The spacing between usable ticks
function flipTick(
uint256 selfResult,
int24 tick,
int24 tickSpacing
) internal pure {
require(tick % tickSpacing == 0); // ensure that the tick is spaced
(, uint8 bitPos) = position(tick / tickSpacing);
uint256 mask = 1 << bitPos;
selfResult ^= mask;
}
/// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
/// to the left (less than or equal to) or right (greater than) of the given tick
/// @param selfResult The result of the mapping in which to compute the next initialized tick (Ithil modified)
/// @param tick The starting tick
/// @param tickSpacing The spacing between usable ticks
/// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
/// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
/// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
function nextInitializedTickWithinOneWord(
uint256 selfResult,
int24 tick,
int24 tickSpacing,
bool lte
) internal pure returns (int24 next, bool initialized) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity
if (lte) {
(, uint8 bitPos) = position(compressed);
// all the 1s at or to the right of the current bitPos
uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);
uint256 masked = selfResult & mask;
// if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
initialized = masked != 0;
// overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
next = initialized
? (compressed -
int24(
uint24(bitPos) -
uint24(BitMath.mostSignificantBit(masked))
)) * tickSpacing
: (compressed - int24(uint24(bitPos))) * tickSpacing;
} else {
// start from the word of the next tick, since the current tick state doesn't matter
(, uint8 bitPos) = position(compressed + 1);
// all the 1s at or to the left of the bitPos
uint256 mask = ~((1 << bitPos) - 1);
uint256 masked = selfResult & mask;
// if there are no initialized ticks to the left of the current tick, return leftmost in the word
initialized = masked != 0;
// overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
next = initialized
? (compressed +
1 +
int24(
uint24(BitMath.leastSignificantBit(masked) - bitPos)
)) * tickSpacing
: (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) *
tickSpacing;
}
}
}
src/libraries/uniswapv3/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
/// @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 {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @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 ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(int256(MAX_TICK)), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// 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 getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
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; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
src/libraries/uniswapv3/UnsafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.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 has unspecified behavior, and must 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 {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}
src/liquidations/compoundv2/common/IUniswapV3Quoter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
interface IUniswapV3Quoter {
struct PoolState {
// the current price
uint160 sqrtPriceX96;
// the current tick
int24 tick;
// the tick spacing
int24 tickSpacing;
// the pool's fee
uint24 fee;
// the pool's liquidity
uint128 liquidity;
}
// accumulated protocol fees in token0/token1 units
struct ProtocolFees {
uint128 token0;
uint128 token1;
}
// the top level state of the swap, the results of which are recorded in storage at the end
struct SwapState {
// the amount remaining to be swapped in/out of the input/output asset
int256 amountSpecifiedRemaining;
// the amount already swapped out/in of the output/input asset
int256 amountCalculated;
// current sqrt(price)
uint160 sqrtPriceX96;
// the tick associated with the current price
int24 tick;
// the current liquidity in range
uint128 liquidity;
}
struct StepComputations {
// the price at the beginning of the step
uint160 sqrtPriceStartX96;
// the next tick to swap to from the current tick in the swap direction
int24 tickNext;
// whether tickNext is initialized or not
bool initialized;
// sqrt(price) for the next tick (1/0)
uint160 sqrtPriceNextX96;
// how much is being swapped in in this step
uint256 amountIn;
// how much is being swapped out
uint256 amountOut;
// how much fee is being paid in
uint256 feeAmount;
}
struct InitialState {
address poolAddress;
PoolState poolState;
uint256 feeGrowthGlobal0X128;
uint256 feeGrowthGlobal1X128;
}
struct NextTickPassage {
int24 tick;
int24 tickSpacing;
}
}
src/liquidations/compoundv2/common/quoters/UniswapV3Quoter/UniswapV3QuoterBase.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.6;
import "src/libraries/uniswapv3/LowGasSafeMath.sol";
import "src/libraries/uniswapv3/SafeCast.sol";
import "src/libraries/uniswapv3/Tick.sol";
import "src/libraries/uniswapv3/TickBitmap.sol";
import "src/libraries/uniswapv3/FullMath.sol";
import "src/libraries/uniswapv3/TickMath.sol";
import "src/libraries/uniswapv3/LiquidityMath.sol";
import "src/libraries/uniswapv3/SqrtPriceMath.sol";
import "src/libraries/uniswapv3/SwapMath.sol";
import "../../IUniswapV3Quoter.sol";
import "src/interfaces/uniswapv3/IUniswapV3Pool.sol";
import "src/interfaces/uniswapv3/IUniswapV3PoolImmutables.sol";
contract UniswapV3QuoterBase is IUniswapV3Quoter {
using LowGasSafeMath for int256;
using SafeCast for uint256;
using Tick for mapping(int24 => Tick.Info);
function fetchState(
address _pool,
uint32 secondsAgo
) internal view returns (PoolState memory poolState) {
uint160 sqrtPriceX96;
int24 tick;
uint128 liquidity;
IUniswapV3Pool pool = IUniswapV3Pool(_pool);
int24 tickSpacing = IUniswapV3PoolImmutables(_pool).tickSpacing();
uint24 fee = IUniswapV3PoolImmutables(_pool).fee();
if (secondsAgo == 0) {
(sqrtPriceX96, tick) = _readSlot0(_pool);
liquidity = pool.liquidity();
} else {
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
secondsAgos[1] = 0;
(
int56[] memory tickCumulatives,
uint160[] memory secondsPerLiquidityCumulativeX128s
) = IUniswapV3Pool(pool).observe(secondsAgos);
int56 tickCumulativesDelta = tickCumulatives[1] -
tickCumulatives[0];
uint160 secondsPerLiquidityCumulativesDelta = secondsPerLiquidityCumulativeX128s[
1
] - secondsPerLiquidityCumulativeX128s[0];
tick = int24(tickCumulativesDelta / int32(secondsAgo));
if (
tickCumulativesDelta < 0 &&
(tickCumulativesDelta % int32(secondsAgo) != 0)
) tick--;
sqrtPriceX96 = TickMath.getSqrtRatioAtTick(tick);
uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
liquidity = uint128(
secondsAgoX160 /
(uint192(secondsPerLiquidityCumulativesDelta) << 32)
);
}
poolState = PoolState(sqrtPriceX96, tick, tickSpacing, fee, liquidity);
}
function _readSlot0(
address pool
) private view returns (uint160 sqrtPriceX96, int24 tick) {
(bool ok, bytes memory data) = pool.staticcall(
abi.encodeWithSignature("slot0()")
);
require(ok && data.length >= 64, "SLOT0");
uint256 sqrtPriceRaw;
int256 tickRaw;
assembly {
sqrtPriceRaw := mload(add(data, 32))
tickRaw := mload(add(data, 64))
}
require(sqrtPriceRaw <= type(uint160).max, "SLOT0_SQRT");
require(
tickRaw >= int256(type(int24).min) &&
tickRaw <= int256(type(int24).max),
"SLOT0_TICK"
);
sqrtPriceX96 = uint160(sqrtPriceRaw);
tick = int24(tickRaw);
}
function setInitialState(
PoolState memory initialPoolState,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bool zeroForOne
)
internal
pure
returns (
SwapState memory state,
uint128 liquidity,
uint160 sqrtPriceX96
)
{
liquidity = initialPoolState.liquidity;
sqrtPriceX96 = initialPoolState.sqrtPriceX96;
require(
zeroForOne
? sqrtPriceLimitX96 < initialPoolState.sqrtPriceX96 &&
sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO
: sqrtPriceLimitX96 > initialPoolState.sqrtPriceX96 &&
sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO,
"SPL"
);
state = SwapState({
amountSpecifiedRemaining: amountSpecified,
amountCalculated: 0,
sqrtPriceX96: initialPoolState.sqrtPriceX96,
tick: initialPoolState.tick,
liquidity: 0
});
}
function getNextTickAndPrice(
int24 tickSpacing,
int24 currentTick,
IUniswapV3Pool pool,
bool zeroForOne
)
internal
view
returns (int24 tickNext, bool initialized, uint160 sqrtPriceNextX96)
{
int24 compressed = currentTick / tickSpacing;
if (!zeroForOne) compressed++;
if (currentTick < 0 && currentTick % tickSpacing != 0) compressed--;
uint256 selfResult = pool.tickBitmap(int16(compressed >> 8));
(tickNext, initialized) = TickBitmap.nextInitializedTickWithinOneWord(
selfResult,
currentTick,
tickSpacing,
zeroForOne
);
if (tickNext < TickMath.MIN_TICK) {
tickNext = TickMath.MIN_TICK;
} else if (tickNext > TickMath.MAX_TICK) {
tickNext = TickMath.MAX_TICK;
}
sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(tickNext);
}
function processSwapWithinTick(
IUniswapV3Pool pool,
PoolState memory initialPoolState,
SwapState memory state,
uint160 firstSqrtPriceX96,
uint128 firstLiquidity,
uint160 sqrtPriceLimitX96,
bool zeroForOne,
bool exactAmount
)
internal
view
returns (
uint160 sqrtPriceNextX96,
uint160 finalSqrtPriceX96,
uint128 finalLiquidity
)
{
StepComputations memory step;
finalLiquidity = firstLiquidity;
step.sqrtPriceStartX96 = firstSqrtPriceX96;
(
step.tickNext,
step.initialized,
sqrtPriceNextX96
) = getNextTickAndPrice(
initialPoolState.tickSpacing,
state.tick,
pool,
zeroForOne
);
(
finalSqrtPriceX96,
step.amountIn,
step.amountOut,
step.feeAmount
) = SwapMath.computeSwapStep(
firstSqrtPriceX96,
(
zeroForOne
? sqrtPriceNextX96 < sqrtPriceLimitX96
: sqrtPriceNextX96 > sqrtPriceLimitX96
)
? sqrtPriceLimitX96
: sqrtPriceNextX96,
firstLiquidity,
state.amountSpecifiedRemaining,
initialPoolState.fee,
zeroForOne
);
if (exactAmount) {
state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount)
.toInt256();
state.amountCalculated = state.amountCalculated.sub(
step.amountOut.toInt256()
);
} else {
state.amountSpecifiedRemaining += step.amountOut.toInt256();
state.amountCalculated = state.amountCalculated.add(
(step.amountIn + step.feeAmount).toInt256()
);
}
if (finalSqrtPriceX96 == sqrtPriceNextX96) {
if (step.initialized) {
(, int128 liquidityNet, , , , , , ) = pool.ticks(step.tickNext);
if (zeroForOne) liquidityNet = -liquidityNet;
finalLiquidity = LiquidityMath.addDelta(
firstLiquidity,
liquidityNet
);
}
state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
} else if (finalSqrtPriceX96 != step.sqrtPriceStartX96) {
state.tick = TickMath.getTickAtSqrtRatio(finalSqrtPriceX96);
}
}
function returnedAmount(
SwapState memory state,
int256 amountSpecified,
bool zeroForOne
) internal pure returns (int256 amount0, int256 amount1) {
if (amountSpecified > 0) {
(amount0, amount1) = zeroForOne
? (
amountSpecified - state.amountSpecifiedRemaining,
state.amountCalculated
)
: (
state.amountCalculated,
amountSpecified - state.amountSpecifiedRemaining
);
} else {
(amount0, amount1) = zeroForOne
? (
state.amountCalculated,
amountSpecified - state.amountSpecifiedRemaining
)
: (
amountSpecified - state.amountSpecifiedRemaining,
state.amountCalculated
);
}
}
function quoteSwap(
address poolAddress,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bool zeroForOne,
uint32 secondsAgo
) internal view returns (int256 amount0, int256 amount1) {
require(amountSpecified < 0, "QSEA");
PoolState memory initialPoolState = fetchState(poolAddress, secondsAgo);
uint160 sqrtPriceNextX96;
(
SwapState memory state,
uint128 liquidity,
uint160 sqrtPriceX96
) = setInitialState(
initialPoolState,
amountSpecified,
sqrtPriceLimitX96,
zeroForOne
);
while (
state.amountSpecifiedRemaining != 0 &&
sqrtPriceX96 != sqrtPriceLimitX96
)
(sqrtPriceNextX96, sqrtPriceX96, liquidity) = processSwapWithinTick(
IUniswapV3Pool(poolAddress),
initialPoolState,
state,
sqrtPriceX96,
liquidity,
sqrtPriceLimitX96,
zeroForOne,
false
);
(amount0, amount1) = returnedAmount(state, amountSpecified, zeroForOne);
}
function quoteSwapExactAmount(
address poolAddress,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bool zeroForOne,
uint32 secondsAgo
) internal view returns (int256 amount0, int256 amount1) {
require(amountSpecified > 0, "QSEA");
PoolState memory initialPoolState = fetchState(poolAddress, secondsAgo);
uint160 sqrtPriceNextX96;
(
SwapState memory state,
uint128 liquidity,
uint160 sqrtPriceX96
) = setInitialState(
initialPoolState,
amountSpecified,
sqrtPriceLimitX96,
zeroForOne
);
while (
state.amountSpecifiedRemaining != 0 &&
sqrtPriceX96 != sqrtPriceLimitX96
)
(sqrtPriceNextX96, sqrtPriceX96, liquidity) = processSwapWithinTick(
IUniswapV3Pool(poolAddress),
initialPoolState,
state,
sqrtPriceX96,
liquidity,
sqrtPriceLimitX96,
zeroForOne,
true
);
(amount0, amount1) = returnedAmount(state, amountSpecified, zeroForOne);
}
}
Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 1000,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.