Verified contractExactMIT
UpegDuelDrawV4
Address0x3554faf0bc3e0809ed94e4303029fbc1cf6b0aa1
- Balance
0.010377 ETH
- Transactions
230
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,528,755
- Creation transaction
- 0x5c5c40bbfd…44821ba8cb
22 files
- src/UpegDuelDrawV4.solmain29.71 KB
- lib/upeg-draw-deps/upeghook-src/upegs/IUpeg.sol3.24 KB
- lib/upeg-draw-deps/v4-core/src/interfaces/IExtsload.sol1.02 KB
- lib/upeg-draw-deps/v4-core/src/interfaces/IExttload.sol699 B
- lib/upeg-draw-deps/v4-core/src/interfaces/IHooks.sol8.23 KB
- lib/upeg-draw-deps/v4-core/src/interfaces/IPoolManager.sol12.84 KB
- lib/upeg-draw-deps/v4-core/src/interfaces/IProtocolFees.sol2.49 KB
- lib/upeg-draw-deps/v4-core/src/interfaces/external/IERC20Minimal.sol3.04 KB
- lib/upeg-draw-deps/v4-core/src/interfaces/external/IERC6909Claims.sol3.16 KB
- lib/upeg-draw-deps/v4-core/src/libraries/CustomRevert.sol5.17 KB
- lib/upeg-draw-deps/v4-core/src/libraries/FixedPoint128.sol297 B
- lib/upeg-draw-deps/v4-core/src/libraries/FullMath.sol5.46 KB
- lib/upeg-draw-deps/v4-core/src/libraries/LiquidityMath.sol742 B
- lib/upeg-draw-deps/v4-core/src/libraries/Position.sol4.81 KB
- lib/upeg-draw-deps/v4-core/src/libraries/SafeCast.sol2.27 KB
- lib/upeg-draw-deps/v4-core/src/libraries/StateLibrary.sol16.03 KB
- lib/upeg-draw-deps/v4-core/src/types/BalanceDelta.sol2.34 KB
- lib/upeg-draw-deps/v4-core/src/types/BeforeSwapDelta.sol1.47 KB
- lib/upeg-draw-deps/v4-core/src/types/Currency.sol5.46 KB
- lib/upeg-draw-deps/v4-core/src/types/PoolId.sol539 B
- lib/upeg-draw-deps/v4-core/src/types/PoolKey.sol805 B
- lib/upeg-draw-deps/v4-core/src/types/PoolOperation.sol907 B
src/UpegDuelDrawV4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
// UpegDuelDraw V2 (#430) — scoring upgrade over the verified v1
// 0x427429B88cA867Db3C56cfC893b9B6A24BdE9A46. The draw core (drawWithPermit,
// exact-1e18 stake, mandatory-able reseed, fieldGroups, rescue trio) is
// byte-for-byte v1; the ONLY delta is three new composite ScoreModes that
// order candidates by the GAME's player-visible stats:
//
// TtThenCt (6): score = ttGroup*256 + ctGroup*16 + partCount (max wins)
// CtThenTt (7): score = ctGroup*256 + ttGroup*16 + partCount (max wins)
// TtPlusCt (8): score = (ttGroup+ctGroup)*16 + partCount (max wins)
//
// Key definitions (aligned with the official TRAITS panel + game derivations):
// ttGroup = largest same-value group over the SEVEN variable id slots
// (horn, accessories, hair, wings, tail, legsFront, legsBack).
// EXCLUDES body/eyes — their id is a constant 1 on every uPEG,
// and counting them created v1 FewIds' phantom duplicates
// (score credited pairs the game's TT never counts).
// ctGroup = largest same-PALETTE-INDEX group over the rendered color
// slots (body, eyes + gated hair/horn/tail/accessories),
// after merging the palette's two duplicate-hex pairs
// (idx 21→1 #cbdbfc, idx 13→11 #306082). Background omitted:
// its 6-color palette shares no hex with the main 36 → it can
// only ever be a singleton and never changes the max.
// partCount = count of the seven variable id slots with value > 0 (2–7).
//
// Ranges keep the three keys nibble-separated in one uint16 (max 1911).
//
// v1 lineage: uPEGDuel draw variant of UpegFlashDraw — myupeg.art's verified
// 0x67e10bF231865CE1cc04A363c5b0ad2Bb9828B6A adapted for the game economy.
// Same guaranteed-hit lottery core (flash-mint qty, keep the best by score
// mode, LIFO-burn the rest + the player's 1-uPEG stake). Deltas:
//
// 1. NO ON-CHAIN FEE. The stake pull is EXACTLY 1e18 (one whole uPEG) — a
// whole-number transfer always moves exactly one NFT, so there is no
// fractional-boundary hazard (the #430 fork test proved a fractional
// fee could LIFO-burn a SECOND NFT). The draw fee is charged OFF-CHAIN
// from the player's in-game wallet and credited 100% to the ladder pool
// (owner decision 2026-07-07: fee → pool, no project cut) — via the
// existing in-game payment rail (#328/#342), NOT this contract. The ETH
// fee + DEAD-burn flush of the original are gone.
// 2. drawWithPermit — EIP-2612 (the Unipeg ERC-20 supports permit; see
// GameTreasury.depositWithPermit precedent): one signature covers the
// 1-uPEG stake allowance and the draw itself. No separate approve.
// 3. BUNDLED SEED RESHUFFLE. The mint RNG only reseeds on real token-
// pool swaps (UpegHook._afterSwap). A draw called with `reseed = true`
// first performs a dust uPEG→ETH swap (funded from an OWNER-seeded float
// held by this contract, NOT pulled from the player — a wallet-side dust
// pull could LIFO-burn a whole NFT), refreshing the batch before the
// flash-mint. The float is owner-topped-up (no fee to skim now); ~0.001
// uPEG per reseed, cheap. Accumulated reseed ETH + the float are owner-
// rescuable.
//
// Stuck-funds posture (dev/test question, #430): the draw is one atomic tx —
// any revert unwinds the stake pull, the permit and the mints; nothing can be
// half-in. Funds that legitimately rest here: the owner-seeded reseed float
// (uPEG) and reseed swap proceeds (ETH). Both — plus any stray NFT — are
// recoverable via the owner-only rescue trio (rescueUpeg / sweepERC20 /
// rescueETH), kept verbatim from v2.
//
// The pool is pinned to immutables in the constructor — no PoolKey is
// passed per-call (same closure as the original).
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {IUpeg, UpegSeedData} from "upeghook-src/upegs/IUpeg.sol";
interface IERC20 {
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function balanceOf(address) external view returns (uint256);
}
interface IERC20Permit {
function permit(address owner, address spender, uint256 value, uint256 deadline,
uint8 v, bytes32 r, bytes32 s) external;
}
interface IUnlockCallback {
function unlockCallback(bytes calldata data) external returns (bytes memory);
}
contract UpegDuelDrawV4 is IUnlockCallback {
using StateLibrary for IPoolManager;
using PoolIdLibrary for PoolKey;
// ----- errors --------------------------------------------------------
error NotOwner();
error NotPoolManager();
error InvalidQty();
error TokenTransferFailed();
error UnknownMode();
error PoolNotInitialized();
error InvalidSlippage();
error InvalidDust();
error InsufficientReseedFloat();
// ----- events --------------------------------------------------------
event Drawn(address indexed player, uint256 indexed tokenId, uint256 encoded, uint16 score);
event Missed(address indexed player);
/// Reseed dust swap executed: the batch RNG has been reshuffled.
event Reseeded(uint256 upegIn, uint256 ethOut);
event EthRescued(address indexed to, uint256 amount);
event MaxSlippageBpsSet(uint16 bps);
event ReseedDustSet(uint256 dustWei);
// ----- constants -----------------------------------------------------
uint256 public constant UNIT_PER_UPEG = 1e18;
uint256 public constant MAX_QTY = 100;
uint256 public constant MAX_RESEED_DUST = 1e16; // 0.01 uPEG hard cap on the dust dial
uint16 public constant MAX_SLIPPAGE_BPS_CAP = 1000; // 10% hard ceiling (reseed swap guardrail)
// ----- owner dials ---------------------------------------------------
uint256 public reseedDustUpeg; // spent from the owner-seeded float per reseed
uint16 public maxSlippageBps; // reseed swap guardrail; init 500 (5%)
// ----- immutables ----------------------------------------------------
IPoolManager public immutable poolManager;
IUpeg public immutable upegs;
address public immutable owner;
uint24 public immutable poolFee;
int24 public immutable poolTickSpacing;
address public immutable poolHooks;
// ----- structs / enums (verbatim from UpegFlashDraw v2) --------------
enum ScoreMode {
Weighted, // 0
FewColors, // 1 (v1 legacy — superseded by CtThenTt)
ManyColors, // 2
FewParts, // 3
ManyParts, // 4 → Duel 冲CRIT (parts↔OR verified)
FewIds, // 5 (v1 legacy — superseded by TtThenCt)
TtThenCt, // 6 → Duel 高ATK: TT, ties→CT, ties→parts (max wins)
CtThenTt, // 7 → Duel 強DEF: CT, ties→TT, ties→parts (max wins)
TtPlusCt, // 8 → Duel 攻守兼備: TT+CT, ties→parts (max wins)
ManyPartsBalanced // 9 → Duel 冲CRIT: partCount, ties→TT+CT (max wins)
}
struct TraitMask {
uint256 backGroundColor;
uint256 horn; uint256 hornColor;
uint256 accessories; uint256 accessoriesColor;
uint256 hair; uint256 hairColor;
uint256 wings;
uint256 tail; uint256 tailColor;
uint256 legsFront;
uint256 legsBack;
uint256 eyes; uint256 eyesColor;
uint256 body; uint256 bodyColor;
uint256 ground; uint256 groundColor;
}
struct TraitWeights {
uint256 backGroundColor;
uint256 horn; uint256 hornColor;
uint256 accessories; uint256 accessoriesColor;
uint256 hair; uint256 hairColor;
uint256 wings;
uint256 tail; uint256 tailColor;
uint256 legsFront;
uint256 legsBack;
uint256 eyes; uint256 eyesColor;
uint256 body; uint256 bodyColor;
uint256 ground; uint256 groundColor;
}
struct DrawArgs {
uint256 qty;
TraitMask mask;
uint256 fieldGroups;
ScoreMode mode;
TraitWeights weights;
uint16 minScore; // candidates scoring below this are non-matching (0 = off)
}
// ----- constructor ----------------------------------------------------
constructor(
address poolManager_,
address upegs_,
uint24 poolFee_,
int24 poolTickSpacing_,
address poolHooks_,
address owner_,
uint256 reseedDustUpeg_
) {
// owner decoupled from the deployer (GameTreasury pattern): broadcast
// from a throwaway key; the precious owner key never signs a deploy.
poolManager = IPoolManager(poolManager_);
upegs = IUpeg(upegs_);
owner = owner_;
poolFee = poolFee_;
poolTickSpacing = poolTickSpacing_;
poolHooks = poolHooks_;
maxSlippageBps = 500;
if (reseedDustUpeg_ == 0 || reseedDustUpeg_ > MAX_RESEED_DUST) revert InvalidDust();
reseedDustUpeg = reseedDustUpeg_;
}
function _poolKey() internal view returns (PoolKey memory) {
return PoolKey({
currency0: Currency.wrap(address(0)),
currency1: Currency.wrap(address(upegs)),
fee: poolFee,
tickSpacing: poolTickSpacing,
hooks: IHooks(poolHooks)
});
}
// ----- entry points ---------------------------------------------------
/// Draw against the current batch. `reseed` first reshuffles the mint RNG
/// via a dust swap (fresh batch). Requires a prior uPEG allowance of at
/// least UNIT_PER_UPEG (the 1-uPEG stake) — or use drawWithPermit below.
function draw(DrawArgs calldata args, bool reseed)
external
returns (uint256 tokenId, uint256 encoded, uint16 score, bool matched)
{
if (args.qty == 0 || args.qty > MAX_QTY) revert InvalidQty();
bytes memory ret = poolManager.unlock(abi.encode(args, msg.sender, reseed));
(tokenId, encoded, score, matched) = abi.decode(ret, (uint256, uint256, uint16, bool));
}
/// One-signature flow: EIP-2612 permit (1-uPEG stake) + draw in a single tx.
/// permit is try/catch'd so a front-run (someone submitting the same
/// signature first) cannot brick the draw — the resulting allowance is
/// what matters. `value` should be UNIT_PER_UPEG.
function drawWithPermit(
DrawArgs calldata args,
bool reseed,
uint256 value,
uint256 deadline,
uint8 v, bytes32 r, bytes32 s
)
external
returns (uint256 tokenId, uint256 encoded, uint16 score, bool matched)
{
try IERC20Permit(address(upegs)).permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
if (args.qty == 0 || args.qty > MAX_QTY) revert InvalidQty();
bytes memory ret = poolManager.unlock(abi.encode(args, msg.sender, reseed));
(tokenId, encoded, score, matched) = abi.decode(ret, (uint256, uint256, uint16, bool));
}
function unlockCallback(bytes calldata data) external returns (bytes memory) {
if (msg.sender != address(poolManager)) revert NotPoolManager();
(DrawArgs memory a, address player, bool reseed) = abi.decode(data, (DrawArgs, address, bool));
return _runDraw(a, player, reseed);
}
// ----- draw internals -------------------------------------------------
function _runDraw(DrawArgs memory a, address player, bool reseed) internal returns (bytes memory) {
uint256 pickedTokenId;
uint256 pickedEncoded;
uint16 pickedScore;
bool found;
// ----- Optional reseed: dust swap uPEG→ETH fires _afterSwap → new RNG -----
// Funded from the contract's own float — never from the player's wallet
// (a wallet-side dust pull could LIFO-burn a whole NFT at a boundary).
if (reseed) _reseedSwap();
{
uint256 totalAmount = a.qty * UNIT_PER_UPEG;
uint256 indexBefore = upegs.OwnerUpegsCount(address(this));
// ----- Flash-take qty uPEG -> mint qty fresh NFTs to self -----
poolManager.take(Currency.wrap(address(upegs)), address(this), totalAmount);
// ----- Scan the freshly-minted batch for the best mint -----
(pickedTokenId, pickedEncoded, pickedScore, found) = _scanBatch(
indexBefore,
upegs.OwnerUpegsCount(address(this)),
a
);
// ----- On hit: pull EXACTLY the 1-uPEG stake, route rare back -----
// A whole-number transfer moves exactly one NFT — no fractional
// boundary hazard. No fee here: the draw fee is an off-chain in-game
// wallet debit → 100% to the ladder pool (owner decision 2026-07-07).
if (found) {
if (!IERC20(address(upegs)).transferFrom(player, address(this), UNIT_PER_UPEG)) {
revert TokenTransferFailed();
}
upegs.transferUpeg(player, pickedTokenId);
emit Drawn(player, pickedTokenId, pickedEncoded, pickedScore);
}
// ----- Repay qty uPEG to pool -> LIFO burns stake + unwanted fresh -----
poolManager.sync(Currency.wrap(address(upegs)));
if (!IERC20(address(upegs)).transfer(address(poolManager), totalAmount)) {
revert TokenTransferFailed();
}
poolManager.settle();
}
if (!found) {
emit Missed(player);
return abi.encode(uint256(0), uint256(0), uint16(0), false);
}
return abi.encode(pickedTokenId, pickedEncoded, pickedScore, true);
}
/// Dust swap uPEG→ETH on the pinned pool. Its only purpose is firing the
/// hook's _afterSwap reseed; the ETH proceeds accumulate here (owner-
/// rescuable). Runs inside the active unlock.
function _reseedSwap() internal {
uint256 dust = reseedDustUpeg;
if (IERC20(address(upegs)).balanceOf(address(this)) < dust) revert InsufficientReseedFloat();
PoolKey memory key = _poolKey();
(uint160 sqrtPriceX96, , , ) = poolManager.getSlot0(key.toId());
if (sqrtPriceX96 == 0) revert PoolNotInitialized();
// zeroForOne = false (uPEG in, ETH out) → price moves UP; approx
// √(1 + x) ≈ (1 + x/2), mirror of the original flush guardrail.
uint160 sqrtLimit = uint160(
uint256(sqrtPriceX96) * (10000 + uint256(maxSlippageBps) / 2) / 10000
);
BalanceDelta delta = poolManager.swap(
key,
SwapParams({
zeroForOne: false,
amountSpecified: -int256(dust),
sqrtPriceLimitX96: sqrtLimit
}),
""
);
uint256 upegSpent = uint256(uint128(-delta.amount1()));
uint256 ethRecv = uint256(uint128( delta.amount0()));
poolManager.sync(Currency.wrap(address(upegs)));
if (!IERC20(address(upegs)).transfer(address(poolManager), upegSpent)) revert TokenTransferFailed();
poolManager.settle();
if (ethRecv > 0) poolManager.take(Currency.wrap(address(0)), address(this), ethRecv);
emit Reseeded(upegSpent, ethRecv);
}
// ----- scan / score / match helpers (verbatim from UpegFlashDraw v2) --
function _scanBatch(
uint256 indexBefore,
uint256 indexAfter,
DrawArgs memory a
)
internal view
returns (uint256 pickedTokenId, uint256 pickedEncoded, uint16 pickedScore, bool found)
{
bool minWins =
(a.mode == ScoreMode.FewColors ||
a.mode == ScoreMode.FewParts ||
a.mode == ScoreMode.FewIds);
for (uint256 i = indexBefore; i < indexAfter; i++) {
UpegSeedData memory u = upegs.OwnerUpeg(address(this), i);
if (!_matches(u.seed, a.mask, a.fieldGroups)) continue;
uint16 s = _score(u.seed, a.mode, a.weights);
if (s < a.minScore) continue; // stat floor: below-threshold candidates never match
bool better = !found || (minWins ? s < pickedScore : s > pickedScore);
if (better) {
pickedTokenId = u.id;
pickedEncoded = u.seed;
pickedScore = s;
found = true;
}
}
}
function _score(uint256 seed, ScoreMode mode, TraitWeights memory w)
internal pure returns (uint16)
{
if (mode == ScoreMode.Weighted) return _scoreWeighted(seed, w);
if (mode == ScoreMode.FewColors || mode == ScoreMode.ManyColors) return _countRenderingColors(seed);
if (mode == ScoreMode.FewParts || mode == ScoreMode.ManyParts) return _countRenderingParts(seed);
if (mode == ScoreMode.FewIds) return _countDistinctIds(seed);
if (mode == ScoreMode.TtThenCt) return _ttGroup(seed) * 256 + _ctGroup(seed) * 16 + _partCount7(seed);
if (mode == ScoreMode.CtThenTt) return _ctGroup(seed) * 256 + _ttGroup(seed) * 16 + _partCount7(seed);
if (mode == ScoreMode.TtPlusCt) return (_ttGroup(seed) + _ctGroup(seed)) * 16 + _partCount7(seed);
if (mode == ScoreMode.ManyPartsBalanced) return _countRenderingParts(seed) * 256 + (_ttGroup(seed) + _ctGroup(seed)) * 16;
revert UnknownMode();
}
function _scoreWeighted(uint256 seed, TraitWeights memory w)
internal pure returns (uint16 s)
{
s += _w(w.backGroundColor, uint8(seed));
s += _w(w.horn, uint8(seed >> 8));
s += _w(w.accessories, uint8(seed >> 16));
s += _w(w.hair, uint8(seed >> 24));
s += _w(w.wings, uint8(seed >> 32));
s += _w(w.tail, uint8(seed >> 40));
s += _w(w.legsFront, uint8(seed >> 48));
s += _w(w.legsBack, uint8(seed >> 56));
s += _w(w.eyes, uint8(seed >> 64));
s += _w(w.body, uint8(seed >> 72));
s += _w(w.ground, uint8(seed >> 80));
s += _w(w.bodyColor, uint8(seed >> 88));
s += _w(w.eyesColor, uint8(seed >> 96));
s += _w(w.hairColor, uint8(seed >> 104));
s += _w(w.hornColor, uint8(seed >> 112));
s += _w(w.groundColor, uint8(seed >> 120));
s += _w(w.accessoriesColor, uint8(seed >> 128));
s += _w(w.tailColor, uint8(seed >> 136));
}
function _w(uint256 weights, uint8 value) private pure returns (uint16) {
return uint16((weights >> (uint256(value) * 4)) & 0xF);
}
function _popcount(uint256 x) internal pure returns (uint16) {
x = x - ((x >> 1) & 0x5555555555555555555555555555555555555555555555555555555555555555);
x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333)
+ ((x >> 2) & 0x3333333333333333333333333333333333333333333333333333333333333333);
x = (x + (x >> 4)) & 0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F;
unchecked {
return uint16(
(x * 0x0101010101010101010101010101010101010101010101010101010101010101) >> 248
);
}
}
function _countRenderingColors(uint256 seed) internal pure returns (uint16) {
uint256 seen;
if (uint8(seed >> 72) != 0) seen |= 1 << uint8(seed >> 88); // body -> bodyColor
if (uint8(seed >> 64) != 0) seen |= 1 << uint8(seed >> 96); // eyes -> eyesColor
if (uint8(seed >> 24) != 0) seen |= 1 << uint8(seed >> 104); // hair -> hairColor
if (uint8(seed >> 8) != 0) seen |= 1 << uint8(seed >> 112); // horn -> hornColor
if (uint8(seed >> 40) != 0) seen |= 1 << uint8(seed >> 136); // tail -> tailColor
if (uint8(seed >> 16) != 0) seen |= 1 << uint8(seed >> 128); // acc. -> accColor
if (uint8(seed >> 80) != 0) seen |= 1 << uint8(seed >> 120); // grnd. -> groundColor
return _popcount(seen);
}
function _countRenderingParts(uint256 seed) internal pure returns (uint16 n) {
if (uint8(seed >> 72) != 0) n++; // body
if (uint8(seed >> 64) != 0) n++; // eyes
if (uint8(seed >> 24) != 0) n++; // hair
if (uint8(seed >> 8) != 0) n++; // horn
if (uint8(seed >> 32) != 0) n++; // wings
if (uint8(seed >> 40) != 0) n++; // tail
if (uint8(seed >> 48) != 0) n++; // legsFront
if (uint8(seed >> 56) != 0) n++; // legsBack
if (uint8(seed >> 16) != 0) n++; // accessories
if (uint8(seed >> 80) != 0) n++; // ground
}
function _countDistinctIds(uint256 seed) internal pure returns (uint16) {
uint256 seen;
uint8 v;
v = uint8(seed >> 72); if (v != 0) seen |= 1 << v;
v = uint8(seed >> 64); if (v != 0) seen |= 1 << v;
v = uint8(seed >> 24); if (v != 0) seen |= 1 << v;
v = uint8(seed >> 8); if (v != 0) seen |= 1 << v;
v = uint8(seed >> 32); if (v != 0) seen |= 1 << v;
v = uint8(seed >> 40); if (v != 0) seen |= 1 << v;
v = uint8(seed >> 48); if (v != 0) seen |= 1 << v;
v = uint8(seed >> 56); if (v != 0) seen |= 1 << v;
v = uint8(seed >> 16); if (v != 0) seen |= 1 << v;
v = uint8(seed >> 80); if (v != 0) seen |= 1 << v;
return _popcount(seen);
}
/// Largest same-value group over the seven VARIABLE id slots. body/eyes
/// (constant id) and ground (never rendered) are excluded — the game's TT
/// counts exactly these seven (TT_TRAIT_KEYS in js/shared.js).
function _ttGroup(uint256 seed) internal pure returns (uint16 best) {
uint8[7] memory v = [
uint8(seed >> 8), // horn
uint8(seed >> 16), // accessories
uint8(seed >> 24), // hair
uint8(seed >> 32), // wings
uint8(seed >> 40), // tail
uint8(seed >> 48), // legsFront
uint8(seed >> 56) // legsBack
];
best = 1;
for (uint256 i = 0; i < 7; i++) {
if (v[i] == 0) continue;
uint16 c = 0;
for (uint256 j = 0; j < 7; j++) {
if (v[j] == v[i]) c++;
}
if (c > best) best = c;
}
}
/// Palette index of a raw color byte, with the main palette's two
/// duplicate-hex pairs merged (21→1 #cbdbfc, 13→11 #306082) so hex-equal
/// colors group even across distinct indices.
function _palIdx(uint8 v) internal pure returns (uint8 i) {
i = v % 36;
if (i == 21) i = 1;
if (i == 13) i = 11;
}
/// Largest same-palette-index group over the rendered color slots the
/// game's colorTierHex counts: body + eyes (always present) + gated
/// hair/horn/tail/accessories. Background omitted (separate 6-color
/// palette, zero hex overlap with the main 36 → always a singleton).
function _ctGroup(uint256 seed) internal pure returns (uint16 best) {
uint8[6] memory col;
bool[6] memory on;
col[0] = _palIdx(uint8(seed >> 88)); on[0] = true; // bodyColor
col[1] = _palIdx(uint8(seed >> 96)); on[1] = true; // eyesColor
col[2] = _palIdx(uint8(seed >> 104)); on[2] = uint8(seed >> 24) != 0; // hairColor
col[3] = _palIdx(uint8(seed >> 112)); on[3] = uint8(seed >> 8) != 0; // hornColor
col[4] = _palIdx(uint8(seed >> 136)); on[4] = uint8(seed >> 40) != 0; // tailColor
col[5] = _palIdx(uint8(seed >> 128)); on[5] = uint8(seed >> 16) != 0; // accessoriesColor
best = 1;
for (uint256 i = 0; i < 6; i++) {
if (!on[i]) continue;
uint16 c = 0;
for (uint256 j = 0; j < 6; j++) {
if (on[j] && col[j] == col[i]) c++;
}
if (c > best) best = c;
}
}
/// Count of the seven variable id slots with value > 0 — the official
/// TRAITS-panel part count (range 2–7; both legs are always present).
function _partCount7(uint256 seed) internal pure returns (uint16 n) {
if (uint8(seed >> 8) != 0) n++; // horn
if (uint8(seed >> 16) != 0) n++; // accessories
if (uint8(seed >> 24) != 0) n++; // hair
if (uint8(seed >> 32) != 0) n++; // wings
if (uint8(seed >> 40) != 0) n++; // tail
if (uint8(seed >> 48) != 0) n++; // legsFront
if (uint8(seed >> 56) != 0) n++; // legsBack
}
function _matches(uint256 seed, TraitMask memory m, uint256 fieldGroups)
internal pure returns (bool)
{
if (!_bit(m.backGroundColor, uint8(seed))) return false;
if (!_bit(m.wings, uint8(seed >> 32))) return false;
if (!_bit(m.legsFront, uint8(seed >> 48))) return false;
if (!_bit(m.legsBack, uint8(seed >> 56))) return false;
if (!_pair(m.horn, m.hornColor, uint8(seed >> 8), uint8(seed >> 112))) return false;
if (!_pair(m.accessories, m.accessoriesColor, uint8(seed >> 16), uint8(seed >> 128))) return false;
if (!_pair(m.hair, m.hairColor, uint8(seed >> 24), uint8(seed >> 104))) return false;
if (!_pair(m.tail, m.tailColor, uint8(seed >> 40), uint8(seed >> 136))) return false;
if (!_pair(m.eyes, m.eyesColor, uint8(seed >> 64), uint8(seed >> 96))) return false;
if (!_pair(m.body, m.bodyColor, uint8(seed >> 72), uint8(seed >> 88))) return false;
if (!_pair(m.ground, m.groundColor, uint8(seed >> 80), uint8(seed >> 120))) return false;
return _checkGroups(seed, fieldGroups);
}
function _checkGroups(uint256 seed, uint256 fieldGroups)
internal pure returns (bool)
{
if (fieldGroups == 0) return true;
uint8[16] memory firstVal;
uint16 setMask;
for (uint256 i = 0; i < 18; i++) {
uint8 group = uint8(fieldGroups >> (i * 8));
if (group == 0) continue;
if (group >= 16) continue;
uint256 idBitOff = _pairedIdBitOffset(i);
if (idBitOff != type(uint256).max) {
if (uint8(seed >> idBitOff) == 0) continue;
}
uint8 value = uint8(seed >> (i * 8));
uint16 bit = uint16(1) << group;
if ((setMask & bit) == 0) {
firstVal[group] = value;
setMask |= bit;
} else if (firstVal[group] != value) {
return false;
}
}
return true;
}
function _pairedIdBitOffset(uint256 slotIdx) internal pure returns (uint256) {
if (slotIdx == 11) return 72;
if (slotIdx == 12) return 64;
if (slotIdx == 13) return 24;
if (slotIdx == 14) return 8;
if (slotIdx == 15) return 80;
if (slotIdx == 16) return 16;
if (slotIdx == 17) return 40;
return type(uint256).max;
}
function _bit(uint256 bitmap, uint8 pos) private pure returns (bool) {
return ((bitmap >> pos) & 1) == 1;
}
function _pair(
uint256 idBmp, uint256 colorBmp, uint8 id, uint8 color
) private pure returns (bool) {
if (!_bit(idBmp, id)) return false;
if (id == 0) return true;
return _bit(colorBmp, color);
}
// ----- housekeeping (rescue trio verbatim from v2 + fee dials) --------
function rescueUpeg(address to, uint256 upegId) external {
if (msg.sender != owner) revert NotOwner();
upegs.transferUpeg(to, upegId);
}
function sweepERC20(address token, uint256 amount) external {
if (msg.sender != owner) revert NotOwner();
if (!IERC20(token).transfer(owner, amount)) revert TokenTransferFailed();
}
function rescueETH(address to, uint256 amount) external {
if (msg.sender != owner) revert NotOwner();
(bool ok, ) = to.call{value: amount}("");
if (!ok) revert TokenTransferFailed();
emit EthRescued(to, amount);
}
function setMaxSlippageBps(uint16 bps) external {
if (msg.sender != owner) revert NotOwner();
if (bps == 0 || bps > MAX_SLIPPAGE_BPS_CAP) revert InvalidSlippage();
maxSlippageBps = bps;
emit MaxSlippageBpsSet(bps);
}
function setReseedDust(uint256 dustWei) external {
if (msg.sender != owner) revert NotOwner();
if (dustWei == 0 || dustWei > MAX_RESEED_DUST) revert InvalidDust();
reseedDustUpeg = dustWei;
emit ReseedDustSet(dustWei);
}
// Native receive so PoolManager can pay out the reseed swap's ETH side.
receive() external payable {}
}
lib/upeg-draw-deps/upeghook-src/upegs/IUpeg.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @dev Upeg data structure.
struct UpegSeedData {
/// @dev Upeg ID.
uint256 id;
/// @dev Upeg seed.
uint256 seed;
}
/// @dev Upeg collection interface.
/// Each owner has a list of Upegs with unique IDs and seed values.
interface IUpeg {
/// @dev Error when the caller doesn't own the Upeg.
error NotUpegOwner();
/// @dev Error when Upeg index is out of range.
error UpegIndexOutOfRange();
/// @dev Upeg mint event.
event OnUpegMinted(address indexed owner, uint upegId);
/// @dev Upeg burn event.
event OnUpegBurned(address indexed owner, uint upegId);
/// @dev Upeg transfer event.
event OnUpegTransfer(address indexed from, address indexed to, uint upegId);
/// @dev Total Upeg count.
function UpegsTotalCount() external view returns (uint);
/// @dev Total holder count.
function HoldersCount() external view returns (uint);
/// @dev Upeg count for an owner.
function OwnerUpegsCount(address owner) external view returns (uint);
/// @dev Returns a paginated list of Upegs.
/// @param owner Owner address
/// @param page Page number
/// @param pageSize Page size
function OwnerUpegsPage(address owner, uint page, uint pageSize) external view returns (UpegSeedData[] memory upegs);
/// @dev Upeg for an owner by index.
/// @param owner Owner address
/// @param index Upeg index
function OwnerUpeg(address owner, uint index) external view returns (UpegSeedData memory);
/// @dev Upeg index for an owner by ID.
/// @param owner Owner address
/// @param upegId Upeg ID
function OwnerUpegIndex(address owner, uint upegId) external view returns (uint index);
/// @dev Reorders a Upeg for an owner. Shifts all items left/right (may be gas-inefficient).
/// @param owner Owner address
/// @param upegId Upeg ID to reorder
/// @param newIndex New index
function ReorderUpeg(address owner, uint upegId, uint newIndex) external;
/// @dev Reorders a Upeg for an owner. Gas-optimized swap without shifting.
/// @param owner Owner address
/// @param upegId Upeg ID to reorder
/// @param newIndex New index or swap index
function ReorderUpegPair(address owner, uint upegId, uint newIndex) external;
/// @dev Checks if the owner owns a Upeg by ID.
function OwnerOwns(address owner, uint upegId) external view returns (bool);
/// @dev Checks if the owner is a holder.
function IsHolder(address owner) external view returns (bool);
/// @dev Holder by index.
function Holder(uint index) external view returns (address);
/// @dev Holder number by address.
function HolderNumber(address owner) external view returns (uint);
/// @dev Transfers a Upeg to an address. One token is transferred with the Upeg.
/// @param to Recipient address
/// @param upegId Upeg ID
function transferUpeg(address to, uint upegId) external;
/// @dev Transfers multiple Upegs. Transfers the same number of tokens.
/// @param to Recipient address
/// @param upegIds Array of Upeg IDs
function transferUpegsList(
address to,
uint[] calldata upegIds
) external;
}lib/upeg-draw-deps/v4-core/src/interfaces/IExtsload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
lib/upeg-draw-deps/v4-core/src/interfaces/IExttload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
lib/upeg-draw-deps/v4-core/src/interfaces/IHooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}
lib/upeg-draw-deps/v4-core/src/interfaces/IPoolManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
/// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
/// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
/// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}
lib/upeg-draw-deps/v4-core/src/interfaces/IProtocolFees.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}
lib/upeg-draw-deps/v4-core/src/interfaces/external/IERC20Minimal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
lib/upeg-draw-deps/v4-core/src/interfaces/external/IERC6909Claims.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}
lib/upeg-draw-deps/v4-core/src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
lib/upeg-draw-deps/v4-core/src/libraries/FixedPoint128.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
lib/upeg-draw-deps/v4-core/src/libraries/FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly ("memory-safe") {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly ("memory-safe") {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (0 - denominator) & denominator;
// Divide denominator by power of two
assembly ("memory-safe") {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly ("memory-safe") {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly ("memory-safe") {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the preconditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) != 0) {
require(++result > 0);
}
}
}
}
lib/upeg-draw-deps/v4-core/src/libraries/LiquidityMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math library for liquidity
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
assembly ("memory-safe") {
z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
if shr(128, z) {
// revert SafeCastOverflow()
mstore(0, 0x93dafdf1)
revert(0x1c, 0x04)
}
}
}
}
lib/upeg-draw-deps/v4-core/src/libraries/Position.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
using CustomRevert for bytes4;
/// @notice Cannot update a position with no liquidity
error CannotUpdateEmptyPosition();
// info stored for each user's position
struct State {
// the amount of liquidity owned by this position
uint128 liquidity;
// fee growth per unit of liquidity as of the last update to liquidity or fees owed
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
}
/// @notice Returns the State struct of a position, given an owner and position boundaries
/// @param self The mapping containing all user positions
/// @param owner The address of the position owner
/// @param tickLower The lower tick boundary of the position
/// @param tickUpper The upper tick boundary of the position
/// @param salt A unique value to differentiate between multiple positions in the same range
/// @return position The position info struct of the given owners' position
function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
internal
view
returns (State storage position)
{
bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
position = self[positionKey];
}
/// @notice A helper function to calculate the position key
/// @param owner The address of the position owner
/// @param tickLower the lower tick boundary of the position
/// @param tickUpper the upper tick boundary of the position
/// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
internal
pure
returns (bytes32 positionKey)
{
// positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
mstore(fmp, owner) // [0x0c, 0x20)
positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes
// now clean the memory we used
mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
mstore(fmp, 0) // fmp held owner
}
}
/// @notice Credits accumulated fees to a user's position
/// @param self The individual position to update
/// @param liquidityDelta The change in pool liquidity as a result of the position update
/// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
/// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
/// @return feesOwed0 The amount of currency0 owed to the position owner
/// @return feesOwed1 The amount of currency1 owed to the position owner
function update(
State storage self,
int128 liquidityDelta,
uint256 feeGrowthInside0X128,
uint256 feeGrowthInside1X128
) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
uint128 liquidity = self.liquidity;
if (liquidityDelta == 0) {
// disallow pokes for 0 liquidity positions
if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
} else {
self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
}
// calculate accumulated fees. overflow in the subtraction of fee growth is expected
unchecked {
feesOwed0 =
FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
feesOwed1 =
FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
}
// update the position
self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
}
}
lib/upeg-draw-deps/v4-core/src/libraries/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}
lib/upeg-draw-deps/v4-core/src/libraries/StateLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";
/// @notice A helper library to provide state getters that use extsload
library StateLibrary {
/// @notice index of pools mapping in the PoolManager
bytes32 public constant POOLS_SLOT = bytes32(uint256(6));
/// @notice index of feeGrowthGlobal0X128 in Pool.State
uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;
// feeGrowthGlobal1X128 offset in Pool.State = 2
/// @notice index of liquidity in Pool.State
uint256 public constant LIQUIDITY_OFFSET = 3;
/// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;
uint256 public constant TICKS_OFFSET = 4;
/// @notice index of tickBitmap mapping in Pool.State
uint256 public constant TICK_BITMAP_OFFSET = 5;
/// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;
uint256 public constant POSITIONS_OFFSET = 6;
/**
* @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee
* @dev Corresponds to pools[poolId].slot0
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.
* @return tick The current tick of the pool.
* @return protocolFee The protocol fee of the pool.
* @return lpFee The swap fee of the pool.
*/
function getSlot0(IPoolManager manager, PoolId poolId)
internal
view
returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
bytes32 data = manager.extsload(stateSlot);
// 24 bits |24bits|24bits |24 bits|160 bits
// 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7
// ---------- | fee |protocolfee | tick | sqrtPriceX96
assembly ("memory-safe") {
// bottom 160 bits of data
sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
// next 24 bits of data
tick := signextend(2, shr(160, data))
// next 24 bits of data
protocolFee := and(shr(184, data), 0xFFFFFF)
// last 24 bits of data
lpFee := and(shr(208, data), 0xFFFFFF)
}
}
/**
* @notice Retrieves the tick information of a pool at a specific tick.
* @dev Corresponds to pools[poolId].ticks[tick]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve information for.
* @return liquidityGross The total position liquidity that references this tick
* @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
* @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
* @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
*/
function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128
)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
// read all 3 words of the TickInfo struct
bytes32[] memory data = manager.extsload(slot, 3);
assembly ("memory-safe") {
let firstWord := mload(add(data, 32))
liquidityNet := sar(128, firstWord)
liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
feeGrowthOutside0X128 := mload(add(data, 64))
feeGrowthOutside1X128 := mload(add(data, 96))
}
}
/**
* @notice Retrieves the liquidity information of a pool at a specific tick.
* @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve liquidity for.
* @return liquidityGross The total position liquidity that references this tick
* @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
*/
function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (uint128 liquidityGross, int128 liquidityNet)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
bytes32 value = manager.extsload(slot);
assembly ("memory-safe") {
liquidityNet := sar(128, value)
liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
/**
* @notice Retrieves the fee growth outside a tick range of a pool
* @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve fee growth for.
* @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
* @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
*/
function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
// offset by 1 word, since the first word is liquidityGross + liquidityNet
bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);
assembly ("memory-safe") {
feeGrowthOutside0X128 := mload(add(data, 32))
feeGrowthOutside1X128 := mload(add(data, 64))
}
}
/**
* @notice Retrieves the global fee growth of a pool.
* @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return feeGrowthGlobal0 The global fee growth for token0.
* @return feeGrowthGlobal1 The global fee growth for token1.
* @dev Note that feeGrowthGlobal can be artificially inflated
* For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal
* atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
*/
function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
internal
view
returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State, `uint256 feeGrowthGlobal0X128`
bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);
// read the 2 words of feeGrowthGlobal
bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);
assembly ("memory-safe") {
feeGrowthGlobal0 := mload(add(data, 32))
feeGrowthGlobal1 := mload(add(data, 64))
}
}
/**
* @notice Retrieves total the liquidity of a pool.
* @dev Corresponds to pools[poolId].liquidity
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return liquidity The liquidity of the pool.
*/
function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `uint128 liquidity`
bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);
liquidity = uint128(uint256(manager.extsload(slot)));
}
/**
* @notice Retrieves the tick bitmap of a pool at a specific tick.
* @dev Corresponds to pools[poolId].tickBitmap[tick]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve the bitmap for.
* @return tickBitmap The bitmap of the tick.
*/
function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)
internal
view
returns (uint256 tickBitmap)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(int16 => uint256) tickBitmap;`
bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);
// slot id of the mapping key: `pools[poolId].tickBitmap[tick]
bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));
tickBitmap = uint256(manager.extsload(slot));
}
/**
* @notice Retrieves the position information of a pool without needing to calculate the `positionId`.
* @dev Corresponds to pools[poolId].positions[positionId]
* @param poolId The ID of the pool.
* @param owner The owner of the liquidity position.
* @param tickLower The lower tick of the liquidity range.
* @param tickUpper The upper tick of the liquidity range.
* @param salt The bytes32 randomness to further distinguish position state.
* @return liquidity The liquidity of the position.
* @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
* @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
*/
function getPositionInfo(
IPoolManager manager,
PoolId poolId,
address owner,
int24 tickLower,
int24 tickUpper,
bytes32 salt
) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {
// positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);
(liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);
}
/**
* @notice Retrieves the position information of a pool at a specific position ID.
* @dev Corresponds to pools[poolId].positions[positionId]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param positionId The ID of the position.
* @return liquidity The liquidity of the position.
* @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
* @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
*/
function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)
internal
view
returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)
{
bytes32 slot = _getPositionInfoSlot(poolId, positionId);
// read all 3 words of the Position.State struct
bytes32[] memory data = manager.extsload(slot, 3);
assembly ("memory-safe") {
liquidity := mload(add(data, 32))
feeGrowthInside0LastX128 := mload(add(data, 64))
feeGrowthInside1LastX128 := mload(add(data, 96))
}
}
/**
* @notice Retrieves the liquidity of a position.
* @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param positionId The ID of the position.
* @return liquidity The liquidity of the position.
*/
function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)
internal
view
returns (uint128 liquidity)
{
bytes32 slot = _getPositionInfoSlot(poolId, positionId);
liquidity = uint128(uint256(manager.extsload(slot)));
}
/**
* @notice Calculate the fee growth inside a tick range of a pool
* @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tickLower The lower tick of the range.
* @param tickUpper The upper tick of the range.
* @return feeGrowthInside0X128 The fee growth inside the tick range for token0.
* @return feeGrowthInside1X128 The fee growth inside the tick range for token1.
*/
function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)
internal
view
returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
{
(uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);
(uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =
getTickFeeGrowthOutside(manager, poolId, tickLower);
(uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =
getTickFeeGrowthOutside(manager, poolId, tickUpper);
(, int24 tickCurrent,,) = getSlot0(manager, poolId);
unchecked {
if (tickCurrent < tickLower) {
feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
} else if (tickCurrent >= tickUpper) {
feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;
feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;
} else {
feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
}
}
}
function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
}
function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(int24 => TickInfo) ticks`
bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);
// slot key of the tick key: `pools[poolId].ticks[tick]
return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));
}
function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(bytes32 => Position.State) positions;`
bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);
// slot of the mapping key: `pools[poolId].positions[positionId]
return keccak256(abi.encodePacked(positionId, positionMapping));
}
}
lib/upeg-draw-deps/v4-core/src/types/BalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
lib/upeg-draw-deps/v4-core/src/types/BeforeSwapDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}
lib/upeg-draw-deps/v4-core/src/types/Currency.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
lib/upeg-draw-deps/v4-core/src/types/PoolId.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}
lib/upeg-draw-deps/v4-core/src/types/PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}
lib/upeg-draw-deps/v4-core/src/types/PoolOperation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
"@uniswap/v4-core/=lib/upeg-draw-deps/v4-core/",
"upeghook-src/=lib/upeg-draw-deps/upeghook-src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"upeg-draw-deps/=lib/upeg-draw-deps/v4-core/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.