Verified contractExactMIT
HolderRewardsDistributor
Address0xfdb6a9b38f94d0cdddeb4131596f6ff9fecf125e
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.26
- Same code
1 more 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
- 26,458,268
- Creation transaction
- 0xb4508d45fe…1492789237
40 files
- src/HolderRewardsDistributor.solmain35.69 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol216 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13.96 KB
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol4.77 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.19 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.66 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.95 KB
- lib/v4-periphery/lib/v4-core/src/interfaces/IExtsload.sol1.02 KB
- lib/v4-periphery/lib/v4-core/src/interfaces/IExttload.sol699 B
- lib/v4-periphery/lib/v4-core/src/interfaces/IHooks.sol8.23 KB
- lib/v4-periphery/lib/v4-core/src/interfaces/IPoolManager.sol12.84 KB
- lib/v4-periphery/lib/v4-core/src/interfaces/IProtocolFees.sol2.49 KB
- lib/v4-periphery/lib/v4-core/src/interfaces/external/IERC20Minimal.sol3.04 KB
- lib/v4-periphery/lib/v4-core/src/interfaces/external/IERC6909Claims.sol3.16 KB
- lib/v4-periphery/lib/v4-core/src/libraries/CustomRevert.sol5.17 KB
- lib/v4-periphery/lib/v4-core/src/libraries/FullMath.sol5.46 KB
- lib/v4-periphery/lib/v4-core/src/libraries/SafeCast.sol2.27 KB
- lib/v4-periphery/lib/v4-core/src/types/BalanceDelta.sol2.34 KB
- lib/v4-periphery/lib/v4-core/src/types/BeforeSwapDelta.sol1.47 KB
- lib/v4-periphery/lib/v4-core/src/types/Currency.sol5.46 KB
- lib/v4-periphery/lib/v4-core/src/types/PoolId.sol539 B
- lib/v4-periphery/lib/v4-core/src/types/PoolKey.sol805 B
- lib/v4-periphery/lib/v4-core/src/types/PoolOperation.sol907 B
- src/HolderRewardsLedger.sol23.14 KB
- src/interfaces/IBankrFeeLedger.sol21.71 KB
- src/interfaces/IBankrLaunchFactory.sol16.77 KB
- src/interfaces/IBankrLaunchpadRegistry.sol10.6 KB
- src/interfaces/IBnkrEpochs.sol2.23 KB
- src/interfaces/ICreatorVestingEscrow.sol2.61 KB
- src/interfaces/IHolderRewards.sol9.32 KB
- src/libraries/BucketIds.sol1.19 KB
- src/libraries/FeeMath.sol8 KB
- src/libraries/LaunchConstants.sol8.31 KB
src/HolderRewardsDistributor.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {HolderRewardsLedger} from "./HolderRewardsLedger.sol";
import {IBankrFeeLedger} from "./interfaces/IBankrFeeLedger.sol";
import {IBankrLaunchFactory} from "./interfaces/IBankrLaunchFactory.sol";
import {IBnkrSource, IHolderRewardsDistributor} from "./interfaces/IHolderRewards.sol";
import {IBnkrEpochs} from "./interfaces/IBnkrEpochs.sol";
import {ICreatorVestingEscrow} from "./interfaces/ICreatorVestingEscrow.sol";
import {BucketIds} from "./libraries/BucketIds.sol";
import {LaunchConstants as K} from "./libraries/LaunchConstants.sol";
/// @dev The deployer's transient slots while a distributor is constructed: neither value is in the initcode, so the
/// predicted address depends on neither.
interface ILaunching {
function launchingTerms() external view returns (uint256);
function launchingLeg() external view returns (address);
}
/// @title HolderRewardsDistributor — one per launch, deployed before its token and bound into it as the token's reward
/// hook (spec §6): holders earn by holding, on three legs. Rewritten from Launch v3's distributor without its
/// conversion, anchor ring, bounty or pool binding. Keeperless (decision 1): the fee ledger accrues the
/// creator's holder share into the QUOTE leg in every swap (`accrue`, storage only) and claims pull it from the
/// ledger lazily; the vest-to-holders slice streams on its own schedule from the cliff; anyone's `reconcile`
/// streams the rest (BNKR or quote the chain's BnkrHolderLeg pushed, donations, what a stream ran to nobody). No
/// owner, no admin exclusion (D17): the set is fixed at construction, plus each account's own `excludeSelf`.
/// Its terms (stream length, restart share, the three activation floors) and its holder leg are fixed at
/// construction too: nothing it reads after that can move them.
contract HolderRewardsDistributor is HolderRewardsLedger, ReentrancyGuard, IBnkrEpochs {
using SafeERC20 for IERC20;
address internal constant DEAD = 0x000000000000000000000000000000000000dEaD;
/// @notice Gas a claimForMany element must have before it starts (Launch v3 CreatorFeeVault's batch floor): the
/// worst claim (walks on this coin and on a Bankr-launch quote, its lazy pull burning all of PULL_GAS) with
/// its last payout still handed all of PAYOUT_GAS. An element that runs out of gas, or short of a cap,
/// reverts the batch.
uint256 public constant MIN_GAS_PER_CLAIM = 2_400_000;
/// @dev Gas the BNKR leg's self-call is handed, whatever the BNKR does with it (R8-GAS-1): its worst path with every
/// BNKR read at READ_GAS uses ~0.57M. A skipped leg is then the BNKR's own failure (R7-01), never the gas limit.
uint256 internal constant BNKR_LEG_GAS = 1_000_000;
/// @dev Gas each payout of a three-leg claim is handed, as BankrFeeLedger.PAYOUT_GAS (R8-GAS-2): failing with all of
/// it is a refusal, withheld. claimLeg hands all the gas (an asset whose honest transfer needs more).
uint256 internal constant PAYOUT_GAS = 1_000_000;
/// @dev Gas the creator share's lazy pull is handed, or the call reverts InsufficientGas (R8REV-1): the quote's
/// transfer runs five frames down, so a quote burning all it gets would leave the caller ~7.6 % of its gas,
/// not 1/64. The worst honest pull uses ~0.18M.
uint256 internal constant PULL_GAS = 300_000;
/// @dev Gas a claim hands the holder leg's poke, equal to LaunchConstants.HOLDERS_WAKE_GAS so a batch the in-swap wake
/// converts a claim's poke converts too; with POKE_READ_GAS for the gate's three reads of the leg and the ledger.
uint256 internal constant POKE_GAS = 2_000_000;
uint256 internal constant POKE_READ_GAS = 30_000;
/// @dev A capped call's own cost (a cold callee, memory) and, with the 1/63 of the cap the call keeps, what follows a
/// callee that burned all of it (re-setting a claim's fresh rewards slot, 20k): the check is the only gas edge.
uint256 internal constant CALL_TAIL = 15_000;
/// @notice A leg goes live (and every transfer starts paying for it) only on a first notify of a material amount
/// (review C finding 7); smaller deposits wait as surplus and join the first one that clears it. TOKEN: the
/// coin's supply over this divisor; BNKR: BNKR's supply over its own; QUOTE: `quoteActivation`.
uint256 public immutable tokenActivationDivisor;
uint256 public immutable bnkrActivationDivisor;
/// @dev BNKR swaps followed at most (the leg's MAX_BNKR_SWAPS): past it the BNKR stays and the leg's push reverts,
/// so the walk a holder's first transfer in an epoch runs is bounded here, whatever the leg does.
uint256 internal constant MAX_BNKR_EPOCHS = 4;
/// @dev Gas an asset read may spend (R7-02): BNKR is not this suite's code, and every read is lenient anyway. Kept
/// under 144,900 (63 x the 2,300 SSTORE sentry), so a starved read can never let a nonReentrant call finish.
uint256 internal constant READ_GAS = 100_000;
uint256 private constant U32 = 0xffffffff; // a 32-bit field of the terms word
address public immutable token;
address public immutable quote;
IBankrFeeLedger public immutable feeLedger;
bytes32 public immutable poolId;
address public immutable holderLeg;
address public immutable escrow;
/// @notice The escrow holds a vest-to-holders push schedule for this contract (H9a); without one it is never deployed.
bool public immutable hasHolderVest;
/// @notice What the QUOTE leg's first notify must reach, in the quote's own units, named at this coin's launch
/// and fixed for its life (at least one raw unit, so dust never opens the leg).
uint256 public immutable quoteActivation;
address internal immutable _poolManager;
address internal immutable _factory;
/// @notice LEG_BNKR's asset, the open epoch's token: it follows the holder leg's BNKR (syncBnkr), so a chain that
/// lists BNKR later (FD-23) reaches coins launched before it, and a BNKR swap reaches every coin.
address public bnkr;
/// @dev The leg's BNKR this coin hands over to once its open epoch's last period ends (0 when steady).
address internal _nextBnkr;
mapping(uint256 => address) internal _pastBnkr; // a closed epoch's token
/// @dev The draining stream's rewardsAllocated at its finish had someone been eligible throughout: any shortfall
/// streamed to nobody, and a closed epoch could never re-stream it.
uint256 internal _drainTarget;
/// @dev Everything that holds launch supply or reward inventory never earns: the PoolManager (every pool's reserves),
/// the suite, the token, this contract, the predicted escrow, 0xdEaD, the holder leg and the buyback. The token does not exist
/// yet, so nothing is read from it. `quoteDistributor` is the quote's own distributor when the quote is a Bankr
/// launch: this contract's quote inventory would earn there and never claim, so it leaves that set.
/// The terms word and the holder leg come from the deployer's transient slots, not the arguments: the
/// constructor has no stack room for them and `predict` keeps its five arguments.
constructor(
address token_,
address factory_,
bytes32 poolId_,
address quote_,
address escrow_,
bool holderVest,
address quoteDistributor
) {
if (token_ == address(0) || factory_ == address(0) || quote_ == address(0)) revert ZeroAddress();
IBankrLaunchFactory f = IBankrLaunchFactory(factory_);
_factory = factory_;
IBankrFeeLedger l = IBankrFeeLedger(f.ledger());
(token, quote, feeLedger, poolId, escrow, hasHolderVest) = (token_, quote_, l, poolId_, escrow_, holderVest);
address pm = address(l.poolManager());
_poolManager = pm;
address leg = ILaunching(msg.sender).launchingLeg();
holderLeg = leg;
address[9] memory ex =
[pm, f.hook(), address(l), f.locker(), factory_, token_, address(this), escrow_, DEAD];
for (uint256 i; i < ex.length; ++i) {
rewardExcluded[ex[i]] = true;
}
rewardExcluded[leg] = true;
rewardExcluded[f.buyback()] = true;
// streamSecs | restartBps << 32 | tokenDivisor << 48 | bnkrDivisor << 80 | quoteActivation << 112
uint256 terms = _checkedTerms(ILaunching(msg.sender).launchingTerms());
(rewardStreamSecs, rewardRestartBps) = (terms & U32, terms >> 32 & 0xffff);
(tokenActivationDivisor, bnkrActivationDivisor) = (terms >> 48 & U32, terms >> 80 & U32);
terms >>= 112;
quoteActivation = terms != 0 ? terms : 1; // a floor of 0 would let an empty notify open the leg
address b = _legBnkr();
if (b != address(0)) {
bnkr = b;
emit BnkrLegEnabled(b);
}
if (quoteDistributor != address(0)) IHolderRewardsDistributor(quoteDistributor).excludeSelf();
}
/// @dev The terms word, held to its hard bounds. B7: no division by zero, and a divisor under the audited one is a
/// higher floor that holds rewards where nobody can release them. B4: a restart share of 0 lets dust stretch
/// every period. B21: the QUOTE floor fits the 112-bit buffer it is compared with.
function _checkedTerms(uint256 terms) private pure returns (uint256) {
if (terms & U32 == 0 || terms >> 48 & U32 < 10_000 || terms >> 80 & U32 < 10_000_000) revert HardBound(7);
if (terms >> 32 & 0xffff == 0 || terms >> 32 & 0xffff > 10_000) revert HardBound(4);
if (terms >> 224 != 0) revert HardBound(21);
return terms;
}
// ── token hook ───────────────────────────────────────────────────────────
/// @dev No lock: a TOKEN claim pays from inside the claim's lock and re-enters here (spec §6).
function onTransfer(address from, address to, uint256 value, uint256 fromBal, uint256 toBal) external {
if (msg.sender != token) revert NotToken();
_onTransfer(from, to, value, fromBal, toBal);
}
// ── intake ───────────────────────────────────────────────────────────────
/// @notice The fee ledger's call in every swap that credits this coin's creator holder share (decision 1): `h` of
/// the quote, already this contract's share in the ledger, joins the QUOTE leg's buffer and streams once it
/// clears the fold rule (_foldQuote). Storage only: no pull, no external call, so the swap's tokens never
/// move here and its stipend stays small. `bufferOnly` (a nested swap) only buffers; the next outer swap, a
/// claim's pull or reconcile folds it.
function accrue(uint256 h, bool bufferOnly) external {
if (msg.sender != address(feeLedger)) revert NotLedger();
uint256 p = _pendingQuote + h;
_setPending(bufferOnly ? p : _foldQuote(p, quoteActivation));
}
/// @inheritdoc IHolderRewardsDistributor
function onLegPush(uint256 quoteIn) external {
if (msg.sender != holderLeg) revert NotHolderLeg();
if (_reentrancyGuardEntered()) return;
if (quoteIn != 0) _setPending(_foldQuote(_pendingQuote + quoteIn, quoteActivation));
else if (_nextBnkr == address(0) && _due(LEG_BNKR, false)) _notifySurplus(LEG_BNKR);
}
/// @notice The factory only, once, at the launch that escrows this contract's vest-to-holders slice: the TOKEN leg
/// streams `total` from the cliff to the schedule's end (a stream length past the cliff at least), so no
/// one pushes the vest. The escrow has always vested at least what has streamed, whatever the cliff and
/// duration; a claim releases from the escrow what its TOKEN payout needs.
function openVest(uint256 total, uint64 cliff, uint64 duration) external {
if (msg.sender != _factory) revert NotFactory();
Stream storage s = _streams[LEG_TOKEN];
if (!hasHolderVest || s.periodFinish != 0) revert VestOpen();
uint256 start = block.timestamp + cliff;
uint256 finish = block.timestamp + Math.max(duration, uint256(cliff) + rewardStreamSecs);
// B5: both ends fit the stream's 40-bit clocks, or a wrapped finish would end the vest stream at once
if (finish >> 40 != 0) revert HardBound(5);
uint256 rate = total / (finish - start);
_liveLegs |= uint8(1 << LEG_TOKEN);
// casting is safe: the slice is part of a supply under 2^128, and both times were just held under 2^40
// forge-lint: disable-next-line(unsafe-typecast)
(s.rewardRate, s.lastUpdateTime, s.periodFinish) = (uint176(rate), uint40(start), uint40(finish));
emit RewardsNotified(LEG_TOKEN, rate * (finish - start), rate, finish);
}
/// @notice Anyone, any time: the backstop for what no swap folded. Pulls this contract's creatorId share (outside
/// an unlock; inside one it waits in the ledger), then streams the QUOTE leg's surplus with its buffer at the
/// live activation floor (a rounding remainder, a failed accrue, a quote the holder leg forwarded, a
/// donation, a stream that ran to nobody), the TOKEN leg's surplus once its vest stream has ended (what the
/// escrow still holds released first), and the BNKR the holder leg pushed. Never reverts for a missing
/// feature (I12). The BNKR leg's self-call is handed exactly BNKR_LEG_GAS or this reverts InsufficientGas
/// (R8-GAS-1); every call above it was handed its full need.
function reconcile() external nonReentrant returns (uint256 pulled, uint256[3] memory notified) {
pulled = _pull();
if (!_vesting()) {
if (hasHolderVest) _releaseVest();
if (_due(LEG_TOKEN, false)) notified[LEG_TOKEN] = _notifySurplus(LEG_TOKEN);
}
notified[LEG_QUOTE] = _reconcileQuote();
if (gasleft() < BNKR_LEG_GAS * 64 / 63 + CALL_TAIL) revert InsufficientGas();
try this.reconcileBnkrLeg{gas: BNKR_LEG_GAS}() returns (uint256 n) {
notified[LEG_BNKR] = n;
} catch {}
}
/// @dev Self-call target of reconcile only, which holds the lock (its selector leaves onTransfer's dispatch as it
/// was). A draining BNKR epoch is topped up only by what its last period streamed to nobody (_endDrain); this
/// reports the old token's final notify, or that one.
function reconcileBnkrLeg() external returns (uint256 notified) {
if (msg.sender != address(this)) revert NotSelf();
(, notified) = _syncBnkr();
if (_nextBnkr == address(0) && _due(LEG_BNKR, false)) notified = _notifySurplus(LEG_BNKR);
}
/// @dev The vest stream runs until the TOKEN leg's first period ends: openVest's, which nothing else notifies.
function _vesting() internal view returns (bool) {
return hasHolderVest && block.timestamp < _streams[LEG_TOKEN].periodFinish;
}
/// @dev The QUOTE leg's surplus joins its buffer, folded at the coin's activation floor. Returns what started
/// streaming.
function _reconcileQuote() internal returns (uint256) {
uint256 p = _pendingQuote + _surplus(LEG_QUOTE);
uint256 carry = _foldQuote(p, quoteActivation);
_setPending(carry);
return p > carry ? p - carry : 0;
}
/// @dev Permissionless and lenient: what the escrow has vested lands as TOKEN balance (both sides excluded, so the
/// hook moves no supply); a release that fails, or finds nothing, waits.
function _releaseVest() internal {
try ICreatorVestingEscrow(escrow).releaseFor(address(this)) returns (uint256 amount) {
emit VestPushed(amount);
} catch {}
}
function _due(uint8 leg, bool noFloor) internal view returns (bool) {
uint256 s = _surplus(leg);
return s >= rewardStreamSecs && (_liveLegs & (1 << leg) != 0 || s >= activationFloor(leg) || noFloor);
}
/// @notice What a leg's first notify must reach (see tokenActivationDivisor); supplies read leniently. The QUOTE
/// floor is the coin's own figure: no later change to the quote's row reaches it.
function activationFloor(uint8 leg) public view returns (uint256 floor_) {
if (leg == LEG_QUOTE) return quoteActivation;
floor_ = Math.min(_read(assetOf(leg), abi.encodeCall(IERC20.totalSupply, ())), K.MAX_QUOTE_SUPPLY)
/ (leg == LEG_TOKEN ? tokenActivationDivisor : bnkrActivationDivisor);
if (floor_ < rewardStreamSecs) floor_ = rewardStreamSecs;
}
/// @dev This contract's creatorId share, by the balance that landed. The pull is handed exactly PULL_GAS or this
/// reverts InsufficientGas, so a short gas limit never passes for a refused pull; inside someone's unlock the
/// ledger's own unlock is refused and the share waits there.
function _pull() internal returns (uint256 pulled) {
bytes32 b = BucketIds.creatorId(poolId);
(uint256 a0, uint256 a1) = feeLedger.claimable(b, address(this));
if (a0 + a1 == 0) return 0;
uint256 before = _balance(quote);
if (gasleft() < PULL_GAS * 64 / 63 + CALL_TAIL) revert InsufficientGas();
try feeLedger.collectFees{gas: PULL_GAS}(b) {}
catch {
return 0;
}
uint256 after_ = _balance(quote);
pulled = after_ > before ? after_ - before : 0;
emit FeesPulled(pulled);
}
/// @notice Anyone; the holder leg before every push, which it makes only in what this returns.
function syncBnkr() external nonReentrant returns (address intake) {
(intake,) = _syncBnkr();
}
/// @dev Never from the hook (I8). The old BNKR held is notified once more, then drains over that last period
/// before the next epoch opens; an epoch that never streamed takes the new BNKR in place. A BNKR equal to the
/// quote or the token is no leg of its own (_legStreams).
function _syncBnkr() internal returns (address intake, uint256 notified) {
address next = _nextBnkr;
if (next != address(0)) {
bool held;
(held, notified) = _endDrain();
if (held) return (next, notified);
_openEpoch(next);
}
intake = bnkr;
address cur = _legBnkr();
if (cur == address(0) || cur == intake || _bnkrEpoch >= MAX_BNKR_EPOCHS) return (intake, 0);
// with no floor once the leg is live (else it is owed to nobody); a leg never live keeps its floor, so dust
// cannot turn it on for every later transfer (review C finding 7)
uint256 s = _surplus(LEG_BNKR);
if (s >= rewardStreamSecs && (_liveLegs & (1 << LEG_BNKR) != 0 || s >= activationFloor(LEG_BNKR))) {
notified = _notifySurplus(LEG_BNKR);
}
Stream storage o = _bnkrStream(_bnkrEpoch);
uint256 finish = o.periodFinish;
if (finish == 0) {
bnkr = cur;
if (intake == address(0)) emit BnkrLegEnabled(cur);
else emit BnkrSwitched(intake, cur);
} else {
emit BnkrDraining(intake, cur);
if (block.timestamp < finish) {
_updateLeg(o, _eligible);
(_nextBnkr, _drainTarget) = (cur, o.rewardsAllocated + _remainingStream(LEG_BNKR));
} else {
_openEpoch(cur);
}
}
return (cur, notified);
}
/// @dev Holds the drain until its last period has streamed to someone: the part that ran while nobody was eligible
/// (owed to nobody) is notified once more as soon as someone is, so nothing strands. Donations alone never
/// extend it: only a shortfall in what was allocated does.
function _endDrain() internal returns (bool held, uint256 notified) {
Stream storage s = _bnkrStream(_bnkrEpoch);
if (block.timestamp < s.periodFinish) return (true, 0);
uint256 supply = _eligible;
_updateLeg(s, supply);
if (s.rewardsAllocated + rewardStreamSecs > _drainTarget) return (false, 0);
if (supply != 0) {
notified = _notifySurplus(LEG_BNKR);
_drainTarget = s.rewardsAllocated + _remainingStream(LEG_BNKR);
}
return (true, notified);
}
function _openEpoch(address next) internal {
_pastBnkr[_closeBnkrEpoch()] = bnkr;
(bnkr, _nextBnkr) = (next, address(0));
emit BnkrEpochOpened(_bnkrEpoch, next);
}
/// @dev Lenient: a leg that does not answer names no BNKR.
function _legBnkr() internal view returns (address b) {
uint256 w = _read(holderLeg, abi.encodeWithSelector(IBnkrSource.bnkr.selector));
// casting to 'uint160' is safe because the upper bits are checked zero
// forge-lint: disable-next-line(unsafe-typecast)
if (w >> 160 == 0) b = address(uint160(w));
}
/// @dev One word, 0 when the call fails or answers less (R7-02): capped gas and at most a word copied, so a
/// token that reverts, lies or return-bombs costs a bounded amount and never reverts this.
function _read(address a, bytes memory data) internal view returns (uint256 w) {
assembly ("memory-safe") {
let ok := staticcall(READ_GAS, a, add(data, 0x20), mload(data), 0x00, 0x20)
if and(ok, gt(returndatasize(), 0x1f)) { w := mload(0x00) }
}
}
/// @dev Clamped to TOKEN-3's bound (R7-01, R7-03): above it a lying or minted balance could overflow a notify or
/// a thin coin's accumulator; an honest leg never holds that much, so the clamp never binds for it.
function _balance(address a) internal view returns (uint256) {
return Math.min(_read(a, abi.encodeCall(IERC20.balanceOf, (address(this)))), K.MAX_QUOTE_SUPPLY);
}
// ── claims ───────────────────────────────────────────────────────────────
/// @inheritdoc IHolderRewardsDistributor
function claim() external returns (uint256[3] memory amounts) {
amounts = _claimSelf();
// after the payouts and outside the lock (R7), so the poke can never starve them and its pushes notify
if (!_pokeLeg() && amounts[0] | amounts[1] | amounts[2] == 0) revert NothingToClaim();
}
function _claimSelf() internal nonReentrant returns (uint256[3] memory) {
return _claim(msg.sender, 7, true);
}
/// @dev Only with POKE_GAS and its gate free, so a claim near its estimate never even reads the leg; then only when
/// this coin's pile, in the ledger or staged, is at the quote's floor. Lenient reads (I12): a leg that does not
/// answer reads a floor of 0 and is not poked. True when the poke call returned.
function _pokeLeg() internal returns (bool) {
address leg = holderLeg;
if (gasleft() < POKE_GAS * 64 / 63 + CALL_TAIL + POKE_READ_GAS) return false;
uint256 f = _read(leg, abi.encodeCall(IBnkrSource.minPile, (quote)));
if (f == 0) return false;
(uint256 a0, uint256 a1) = feeLedger.claimable(BucketIds.holdersId(poolId), leg);
if (a0 + a1 < f && _read(leg, abi.encodeCall(IBnkrSource.pending, (poolId))) < f) return false;
try IBnkrSource(leg).poke{gas: POKE_GAS}(poolId) {
return true;
} catch {}
return false;
}
function claimLeg(uint8 leg) external nonReentrant returns (uint256) {
if (leg >= LEGS) revert BadLeg();
return _claim(msg.sender, uint8(1 << leg), false)[leg];
}
function claimFor(address account) external nonReentrant returns (uint256[3] memory amounts) {
if (!_mayClaimFor(account)) revert ClaimerNotAllowed();
return _claim(account, 7, false);
}
/// @notice Batch: each account is authorised against the outer caller; one the policy refuses it, one with nothing
/// to claim or one that refuses a payout is skipped, never the whole batch. One that ran out of gas, or
/// could not hand a payout all of PAYOUT_GAS, reverts it.
function claimForMany(address[] calldata accounts) external nonReentrant returns (uint256 paid) {
for (uint256 i; i < accounts.length; ++i) {
address a = accounts[i];
if (!_mayClaimFor(a)) continue;
uint256 g = gasleft();
if (g < MIN_GAS_PER_CLAIM) revert InsufficientGas();
try this.claimForAuthorized(a) {
++paid;
} catch {
// an out-of-gas callee leaves only the 1/64 the call kept; a payout's own gas check names itself
if (gasleft() <= g / 64 || _gasShort()) revert InsufficientGas();
}
}
}
/// @dev The call that just failed reverted exactly InsufficientGas(): a payout's cap check, never the account's own.
function _gasShort() internal pure returns (bool short) {
bytes4 sel = InsufficientGas.selector;
assembly ("memory-safe") {
if eq(returndatasize(), 4) {
returndatacopy(0x00, 0x00, 4)
short := eq(and(mload(0x00), shl(224, 0xffffffff)), sel)
}
}
}
/// @dev Self-call target of claimForMany only, which holds the lock and authorised the account.
function claimForAuthorized(address account) external returns (uint256[3] memory amounts) {
if (msg.sender != address(this)) revert NotSelf();
return _claim(account, 7, false);
}
/// @dev A draining BNKR epoch's rewards are kept, not forfeited into a stream that is closing: the account claims
/// them with claimPastBnkr once the epoch closes.
function excludeSelf() external nonReentrant {
if (_excluded(msg.sender)) revert ExcludedAccount();
uint256 legs = _nextBnkr == address(0) ? 7 : 3;
emit RewardExcluded(msg.sender, _exclude(msg.sender, IERC20(token).balanceOf(msg.sender), legs));
}
/// @dev One closed epoch per call, in its own token; a token that refuses reverts and the rewards stay. Excluded
/// accounts claim what they earned before excluding (they are settled no further).
function claimPastBnkr(address account, uint256 epoch) external nonReentrant returns (uint256 amount) {
if (!_mayClaimFor(account)) revert ClaimerNotAllowed();
if (epoch >= _bnkrEpoch) revert BadEpoch();
if (!_excluded(account)) _settleAll(account, IERC20(token).balanceOf(account));
amount = _take(_bnkrStream(epoch), account);
if (amount == 0) revert NothingToClaim();
IERC20(_pastBnkr[epoch]).safeTransfer(account, amount);
emit PastBnkrClaimed(account, msg.sender, epoch, amount);
}
/// @dev Checks-effects-interactions: every leg settled and zeroed before anything is paid. A TOKEN payout re-enters
/// onTransfer from this excluded contract to an eligible holder, which makes the paid tokens earn from now on. A
/// leg whose asset refuses the payout (a paused or blocklisting quote, the TOKEN cap) keeps its rewards and the
/// other legs pay (H13 TOKEN-4); only when every owed leg refuses does the claim revert. `soft` (claim() alone):
/// nothing owed returns zeros, so a claim that only pokes the holder leg lands.
function _claim(address account, uint8 legs, bool soft) internal returns (uint256[3] memory amounts) {
if (_excluded(account)) revert ExcludedAccount();
_settleAll(account, IERC20(token).balanceOf(account));
bool any;
for (uint8 leg; leg < LEGS; ++leg) {
if (legs & (1 << leg) == 0) continue;
amounts[leg] = _take(_stream(leg), account);
any = any || amounts[leg] != 0;
}
if (!any) {
if (soft) return amounts;
revert NothingToClaim();
}
bool pulled = _fund(amounts[LEG_TOKEN], amounts[LEG_QUOTE]);
any = false;
for (uint8 leg; leg < LEGS; ++leg) {
uint256 a = amounts[leg];
if (a == 0) continue;
if (_pay(assetOf(leg), account, a, legs == 7)) {
any = true;
} else {
_untake(_stream(leg), account, a);
amounts[leg] = 0;
}
}
if (!any) revert PayoutRefused();
// what the pull brought past the swaps' accrues (their rounding, a failed accrue) streams now
if (pulled) _reconcileQuote();
emit RewardClaimed(account, msg.sender, amounts);
}
/// @dev Lazy funding (decision 1), between the takes and the payouts: the creatorId share is pulled only when the
/// QUOTE balance cannot pay this claim, and the escrow releases only when the TOKEN balance cannot (the vest
/// stream never runs ahead of the vest). A pull refused inside someone's unlock leaves that payout withheld.
function _fund(uint256 tokenOwed, uint256 quoteOwed) internal returns (bool pulled) {
if (tokenOwed != 0 && hasHolderVest && _balance(token) < tokenOwed) _releaseVest();
if (quoteOwed != 0 && _balance(quote) < quoteOwed) pulled = _pull() != 0;
}
/// @dev SafeERC20.trySafeTransfer, copying at most a word of return data. `capped`: handed exactly PAYOUT_GAS, and a
/// caller that cannot hand all of it reverts, so a short gas limit never passes for a refusal (R8-GAS-2); else
/// all the gas, for a single leg's claim, which any refusal reverts.
function _pay(address asset, address to, uint256 amount, bool capped) internal returns (bool ok) {
uint256 g = gasleft();
if (capped) {
if (g < PAYOUT_GAS * 64 / 63 + CALL_TAIL) revert InsufficientGas();
g = PAYOUT_GAS;
}
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, shl(224, 0xa9059cbb))
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, amount)
ok := call(g, asset, 0, 0x00, 0x44, 0x00, 0x20)
if iszero(and(ok, eq(mload(0x00), 1))) {
ok := and(ok, and(iszero(returndatasize()), gt(extcodesize(asset), 0)))
}
mstore(0x40, fmp)
}
}
/// @dev Q9: the ledger's one claim policy per account (open by default), shared by every distributor, for the
/// outer caller. A contract that keys off its balance and cannot restrict itself is open too (the accepted
/// residual).
function _mayClaimFor(address account) internal view returns (bool) {
return feeLedger.mayClaimFor(account, msg.sender);
}
// ── ledger binding and views ─────────────────────────────────────────────
function _excluded(address account) internal view override returns (bool) {
return account == _poolManager || rewardExcluded[account];
}
function _legStreams(uint8 leg) internal view override returns (bool) {
if (leg != LEG_BNKR) return true;
address b = bnkr;
return b != address(0) && b != quote && b != token;
}
/// @dev Lenient (review C 1): an asset that does not answer balanceOf (a BNKR named on a chain where it has no code)
/// reads 0, so its leg never notifies and reconcile() never reverts for it (I12).
function _rewardBalance(uint8 leg) internal view override returns (uint256) {
address a = assetOf(leg);
return a == address(0) ? 0 : _balance(a);
}
function assetOf(uint8 leg) public view returns (address) {
if (leg == LEG_TOKEN) return token;
if (leg == LEG_QUOTE) return quote;
if (leg == LEG_BNKR) return bnkr;
revert BadLeg();
}
/// @notice QUOTE taken in and not streaming yet (decision 1): under the activation floor, under one wei a second
/// while a period is open, or what a fold's floored rate left.
function pendingQuote() external view returns (uint256) {
return _pendingQuote;
}
/// @dev An excluded account shows what it still holds of the open stream: only BNKR kept by excluding during a
/// drain, which claimPastBnkr pays once the epoch closes (every other leg is forfeited, or never settled).
function earned(uint8 leg, address account) external view returns (uint256) {
if (leg >= LEGS) revert BadLeg();
if (_excluded(account)) return _settled(_stream(leg), account);
return _earned(leg, account, IERC20(token).balanceOf(account));
}
function surplus(uint8 leg) external view returns (uint256) {
if (leg >= LEGS) revert BadLeg();
return _surplus(leg);
}
function rewardsOwed(uint8 leg) external view returns (uint256) {
if (leg >= LEGS) revert BadLeg();
return _rewardsOwed(leg);
}
function remainingStream(uint8 leg) external view returns (uint256) {
if (leg >= LEGS) revert BadLeg();
return _remainingStream(leg);
}
function streamOf(uint8 leg) external view returns (bool, uint256, uint256, uint256, uint256, uint256) {
if (leg >= LEGS) revert BadLeg();
Stream storage s = _stream(leg);
return (
_legStreams(leg), s.periodFinish, s.rewardRate, s.rewardPerTokenStored, s.rewardsAllocated, s.rewardsClaimed
);
}
function rewardsOf(uint8 leg, address account) external view returns (uint256, uint256) {
if (leg >= LEGS) revert BadLeg();
Stream storage s = _stream(leg);
return (_settled(s, account), s.userRewardPerTokenPaid[account]);
}
function bnkrEpoch() external view returns (uint256 epoch, address next) {
return (_bnkrEpoch, _nextBnkr);
}
/// @dev `claimable` adds the walk the account's next checkpoint will run, stopping where it stops; an excluded
/// account (the PoolManager included) is settled no further, so it shows only what is stored.
function pastBnkr(uint256 epoch, address account)
external
view
returns (address epochToken, uint256 owed, uint256 claimable)
{
uint256 open = _bnkrEpoch;
if (epoch >= open) revert BadEpoch();
Stream storage s = _bnkrStream(epoch);
claimable = _settled(s, account);
uint256 bal = _excluded(account) || _bnkrStream(open).userRewardPerTokenPaid[account] != 0
? 0
: IERC20(token).balanceOf(account);
for (uint256 e = open; e > epoch && bal != 0;) {
--e;
(uint256 d, uint256 p) = _pastDue(e, account, bal);
if (e == epoch) claimable += d;
if (p != 0) break;
}
(epochToken, owed) = (_pastBnkr[epoch], _owed(s));
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/// @dev Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
bytes4 selector = IERC20Metadata.decimals.selector;
assembly ("memory-safe") {
mstore(0x00, selector)
success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
decimals := mul(success, mload(0x00))
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to approve
* @param bubble Behavior switch if the approve call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.sol.eta.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the 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.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// 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²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory buffer) private pure returns (bool) {
uint256 chunk;
for (uint256 i = 0; i < buffer.length; i += 0x20) {
// See _unsafeReadBytesOffset from utils/Bytes.sol
assembly ("memory-safe") {
chunk := mload(add(add(buffer, 0x20), i))
}
if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
/**
* @dev Counts the number of leading zero bits in a uint256.
*/
function clz(uint256 x) internal pure returns (uint256) {
return ternary(x == 0, 256, 255 - log2(x));
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.sol.eta.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev A uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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/v4-periphery/lib/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;
}
src/HolderRewardsLedger.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IHolderRewardsDistributor} from "./interfaces/IHolderRewards.sol";
/// @title HolderRewardsLedger — hold-to-earn accounting, ported from Launch v3's HolderRewardsLedger (live on Arbitrum
/// and Arc): the wallet balance is the reward-bearing position, Synthetix StakingRewards semantics driven by the
/// token's transfer hook, three reward legs (token, quote, BNKR) sharing one eligible supply (spec §6).
/// @dev Deposits stream linearly over the coin's `rewardStreamSecs`, so a deposit cannot be sniped by
/// buy-trigger-claim-sell.
/// Excluded accounts hold supply that never earns. Anything streamed while `eligibleSupply == 0` is never allocated:
/// it stays in the balance as surplus and the next notify re-streams it. Accumulators carry 1e36 precision so a
/// 6-decimal asset streaming a few wei a second still advances against a 1e29 supply. The BNKR leg is a sequence of
/// epochs, one stream per BNKR the holder leg names (founder 11-05: a swap, no migration); a closed epoch's rewards
/// are settled per holder at their first checkpoint in a later one, from storage alone.
abstract contract HolderRewardsLedger is IHolderRewardsDistributor {
uint8 public constant LEG_TOKEN = 0;
uint8 public constant LEG_QUOTE = 1;
uint8 public constant LEG_BNKR = 2;
uint256 internal constant LEGS = 3;
/// @notice Seconds a deposit streams over, fixed at this coin's launch (at least 1: B7).
uint256 public immutable rewardStreamSecs;
/// @notice A notify restarts a full period only when it adds at least this share (bps, 1 to 10,000: B4) of the open
/// period's remaining stream; smaller top-ups join the open period at its finish, so dust cannot keep
/// re-stretching delivery. Fixed at this coin's launch.
uint256 public immutable rewardRestartBps;
uint256 private constant PRECISION = 1e36;
/// @dev An account's `rewards` word: what it has settled in the low 136 bits (a reward balance reads at most
/// MAX_QUOTE_SUPPLY, under 2^120), and above them the part of a raw unit its checkpoints could not settle yet,
/// in PRECISION-ths (under 2^120).
uint256 private constant REM_SHIFT = 136;
uint256 private constant SETTLED_MASK = (1 << REM_SHIFT) - 1;
/// @dev Every BNKR epoch after the first starts its accumulator here, so each checkpoint in it is non-zero and a 0
/// reads "not seen since the epoch opened".
uint256 internal constant EPOCH_START = 1;
/// @dev The first slot is what every transfer reads; a leg never notified (`periodFinish == 0`) costs that one read.
struct Stream {
uint40 periodFinish;
uint40 lastUpdateTime;
uint176 rewardRate; // wei per second while the period is open
uint256 rewardPerTokenStored;
/// @dev Everything streamed while someone was eligible: an upper bound of the sum of all `earned`, never
/// balance-derived. Over that sum it holds only the remainder each account carries (under a raw unit, paid
/// as it completes) and what the accumulator's own floor leaves (under supply / 1e36 of a unit an update).
uint256 rewardsAllocated;
uint256 rewardsClaimed;
mapping(address => uint256) userRewardPerTokenPaid;
mapping(address => uint256) rewards; // settled but unclaimed, and the carried remainder (REM_SHIFT)
}
/// @dev The reward denominator (token supply held by accounts that earn, at most the token's: 1e36 raw), a bit per leg
/// ever notified, the open BNKR epoch and the QUOTE leg's buffer, in one slot: a transfer reads it once and
/// skips every leg not yet live.
uint128 internal _eligible;
uint8 internal _liveLegs;
uint8 internal _bnkrEpoch;
/// @dev Decision 1: QUOTE taken in (a swap's accrue, a reconcile) that is not streaming yet: under the leg's
/// activation floor, under one wei a second while a period is open, or what a fold's floored rate left.
/// Reserved like the stream, never surplus, so small accrues are late (an open period at most), never lost.
uint112 internal _pendingQuote;
mapping(address => bool) public rewardExcluded;
Stream[3] internal _streams; // _streams[LEG_BNKR] is BNKR epoch 0
mapping(uint256 => Stream) internal _bnkrStreams; // BNKR epochs from 1
/// @notice Below one wei per second a full period cannot move: smaller TOKEN and BNKR surplus waits until it has
/// accumulated, and the QUOTE leg streams it over a shorter period (audit F-16). Equals `rewardStreamSecs`.
function MIN_NOTIFY_AMOUNT() external view returns (uint256) {
return rewardStreamSecs;
}
function _rewardBalance(uint8 leg) internal view virtual returns (uint256);
function _legStreams(uint8 leg) internal view virtual returns (bool);
// ── views ────────────────────────────────────────────────────────────────
function eligibleSupply() public view returns (uint256) {
return _eligible;
}
function _bnkrStream(uint256 e) internal view returns (Stream storage) {
return e == 0 ? _streams[LEG_BNKR] : _bnkrStreams[e];
}
/// @dev A leg's open stream: the BNKR leg's is its open epoch's.
function _stream(uint8 leg) internal view returns (Stream storage) {
return leg == LEG_BNKR ? _bnkrStream(_bnkrEpoch) : _streams[leg];
}
function _earned(uint8 leg, address account, uint256 balance) internal view returns (uint256) {
if (rewardExcluded[account]) return 0;
Stream storage s = _stream(leg);
(uint256 d,) = _pendingStep(s);
uint256 paid = s.userRewardPerTokenPaid[account];
if (paid == 0 && leg == LEG_BNKR && _bnkrEpoch != 0) paid = EPOCH_START;
uint256 r = s.rewards[account];
(uint256 q,) = _accrued(balance, s.rewardPerTokenStored + d - paid, r >> REM_SHIFT);
return _credit(r & SETTLED_MASK, q);
}
function _settled(Stream storage s, address account) internal view returns (uint256) {
return s.rewards[account] & SETTLED_MASK;
}
/// @dev `balance * delta / PRECISION` with `rem`, the remainder the account's earlier checkpoints carried: the
/// whole units and the remainder to carry next. So a checkpoint floors nothing away, whoever forces it and
/// however often (audit F-04), and the carry is in reward units: a balance change leaves it right.
function _accrued(uint256 balance, uint256 delta, uint256 rem) private pure returns (uint256 q, uint256) {
q = Math.mulDiv(balance, delta, PRECISION);
unchecked {
rem += mulmod(balance, delta, PRECISION); // each under 2^120
return rem < PRECISION ? (q, rem) : (q + 1, rem - PRECISION);
}
}
/// @dev `r` with `q` more settled. Saturates: a settled amount past its 136 bits (no reward balance reads that
/// high) must neither carry into the remainder nor revert a transfer (I8).
function _credit(uint256 r, uint256 q) private pure returns (uint256) {
uint256 room = SETTLED_MASK - (r & SETTLED_MASK);
unchecked {
return r + (q < room ? q : room);
}
}
/// @dev Counted from the stream's start while that is still ahead: the vest stream opens at its cliff.
function _remainingStream(uint8 leg) internal view returns (uint256) {
Stream storage s = _stream(leg);
uint256 finish = s.periodFinish;
uint256 from = Math.max(block.timestamp, s.lastUpdateTime);
return from >= finish ? 0 : (finish - from) * s.rewardRate;
}
/// @dev Allocated (including the stream since the last checkpoint) but not yet claimed: an upper bound of all `earned`.
function _rewardsOwed(uint8 leg) internal view returns (uint256) {
return _owed(_stream(leg));
}
function _owed(Stream storage s) internal view returns (uint256) {
(, uint256 pending) = _pendingStep(s);
return s.rewardsAllocated + pending - s.rewardsClaimed;
}
/// @dev The leg's balance that is neither owed, scheduled nor (QUOTE) buffered: new deposits, stream that ran while
/// nobody was eligible, rounding dust. Zero for a leg that does not stream. Saturates instead of reverting: the
/// QUOTE leg's liabilities run ahead of its balance by what the ledger still holds for it until a pull.
function _surplus(uint8 leg) internal view returns (uint256) {
if (!_legStreams(leg)) return 0;
uint256 reserved = _rewardsOwed(leg) + _remainingStream(leg);
if (leg == LEG_QUOTE) reserved += _pendingQuote;
uint256 bal = _rewardBalance(leg);
return bal > reserved ? bal - reserved : 0;
}
/// @dev The step `_updateLeg` would apply now: `streamed` (not the truncated credit) is what gets allocated, so the
/// liability can never fall a wei short of what accounts will claim.
function _pendingStep(Stream storage s) internal view returns (uint256 deltaPerToken, uint256 streamed) {
uint256 supply = _eligible;
if (supply == 0) return (0, 0);
uint256 finish = s.periodFinish;
uint256 applicable = block.timestamp < finish ? block.timestamp : finish;
uint256 last = s.lastUpdateTime;
if (applicable <= last) return (0, 0);
return _step(s.rewardPerTokenStored, (applicable - last) * s.rewardRate, supply);
}
/// @dev (0, 0) for a step the accumulator cannot hold: it is left as surplus rather than revert the transfer hook
/// (I8), whatever figures an asset reports (R7-03).
function _step(uint256 rpt, uint256 streamed, uint256 supply) private pure returns (uint256 d, uint256) {
if (streamed > type(uint256).max / PRECISION) return (0, 0);
// the product fits (checked above) and max - rpt cannot underflow: unchecked keeps the hook at mulDiv's cost
unchecked {
d = streamed * PRECISION / supply;
return d > type(uint256).max - rpt ? (0, 0) : (d, streamed);
}
}
// ── accounting ───────────────────────────────────────────────────────────
/// @dev Advances a live leg to now against `supply` and returns its reward per token (0 while nothing was ever
/// allocated: then every checkpoint is still 0, so no settle is due). Advances even with nobody eligible: that
/// window's stream is never allocated (it becomes surplus), never lumped onto the next holder.
function _updateLeg(Stream storage s, uint256 supply) internal returns (uint256 rpt) {
uint256 finish = s.periodFinish;
rpt = s.rewardPerTokenStored;
uint256 last = s.lastUpdateTime;
uint256 applicable = block.timestamp < finish ? block.timestamp : finish;
if (applicable <= last) return rpt;
if (supply != 0) {
(uint256 d, uint256 streamed) = _step(rpt, (applicable - last) * s.rewardRate, supply);
s.rewardsAllocated += streamed;
rpt += d;
s.rewardPerTokenStored = rpt;
}
// casting to 'uint40' is safe because applicable <= periodFinish, itself a uint40
// forge-lint: disable-next-line(unsafe-typecast)
s.lastUpdateTime = uint40(applicable);
}
/// @dev Credits `account` what `balance` earned since its checkpoint on one leg; writes only what changed. `walk`:
/// a BNKR epoch after the first, where a 0 checkpoint is an account not seen since it opened, which first closes
/// the earlier epochs it never settled (the balance it holds now is the one it held through them).
function _settleLeg(Stream storage s, bool walk, address account, uint256 balance, uint256 rpt) internal {
uint256 paid = s.userRewardPerTokenPaid[account];
if (rpt == paid) return;
if (paid == 0 && walk) paid = _closePastEpochs(account, balance);
if (balance != 0) {
// _accrued and _credit, in line: as calls they cost every transfer ~430 gas a leg and account
uint256 r = s.rewards[account];
uint256 delta = rpt - paid;
uint256 q = Math.mulDiv(balance, delta, PRECISION);
unchecked {
uint256 rem = (r >> REM_SHIFT) + mulmod(balance, delta, PRECISION);
if (rem >= PRECISION) (q, rem) = (q + 1, rem - PRECISION);
r &= SETTLED_MASK;
uint256 room = SETTLED_MASK - r;
s.rewards[account] = r + (q < room ? q : room) | rem << REM_SHIFT;
}
}
s.userRewardPerTokenPaid[account] = rpt;
}
/// @dev Newest closed epoch first, down to the one the account last checkpointed in; their accumulators are final.
/// Writes only `rewards`: the open epoch's checkpoint written right after keeps this from running twice, and
/// the epoch count bounds it (storage only, I8).
function _closePastEpochs(address account, uint256 balance) internal returns (uint256) {
if (balance == 0) return EPOCH_START;
for (uint256 e = _bnkrEpoch; e != 0;) {
--e;
(uint256 d, uint256 p) = _pastDue(e, account, balance);
if (d != 0) {
Stream storage o = _bnkrStream(e);
o.rewards[account] = _credit(o.rewards[account], d);
}
if (p != 0) break;
}
return EPOCH_START;
}
/// @dev What `balance` held since its checkpoint `p` earned in closed epoch `e` (from its start when `p` is 0).
function _pastDue(uint256 e, address account, uint256 balance) internal view returns (uint256 d, uint256 p) {
Stream storage o = _bnkrStream(e);
p = o.userRewardPerTokenPaid[account];
uint256 delta = o.rewardPerTokenStored - (p == 0 && e != 0 ? EPOCH_START : p);
// only an account checkpointed in the epoch carries a remainder there
(d,) = _accrued(balance, delta, p == 0 ? 0 : o.rewards[account] >> REM_SHIFT);
}
/// @dev Updates every leg and settles `account` (eligible) at `balance` on each.
function _settleAll(address account, uint256 balance) internal {
(uint256 supply, uint256 live, uint256 epoch) = (_eligible, _liveLegs, _bnkrEpoch);
for (uint8 leg; leg < LEGS; ++leg) {
if (live & (1 << leg) == 0) continue;
Stream storage s = leg == LEG_BNKR ? _bnkrStream(epoch) : _streams[leg];
uint256 rpt = _updateLeg(s, supply);
if (rpt != 0) _settleLeg(s, leg == LEG_BNKR && epoch != 0, account, balance, rpt);
}
}
/// @dev The token's hook (v3 `_onTransfer`, with the balances passed in): settles both parties against the balances
/// that earned, and keeps `eligibleSupply` exact across eligible / excluded moves. It cannot revert on a transfer
/// the ERC-20 accepts: a sender's `value` is at most its counted balance, and nothing here calls out (I8).
function _onTransfer(address from, address to, uint256 value, uint256 fromBal, uint256 toBal) internal {
bool fromEligible = from != address(0) && !_excluded(from);
bool toEligible = to != address(0) && !_excluded(to);
if (!fromEligible && !toEligible) return;
if (fromEligible && value > fromBal) return; // the ERC-20 raises its own error
uint256 supply = _settleParties(fromEligible ? from : address(0), fromBal, toEligible ? to : address(0), toBal);
if (fromEligible == toEligible) return;
// casting to 'uint128' is safe because the eligible supply is part of the token's, at most 1e36 raw
// forge-lint: disable-next-line(unsafe-typecast)
_eligible = uint128(fromEligible ? supply - value : supply + value);
}
/// @dev Updates every live leg and settles each party given (0: not eligible); returns the eligible supply it read.
function _settleParties(address from, uint256 fromBal, address to, uint256 toBal)
internal
returns (uint256 supply)
{
uint256 live;
uint256 epoch;
(supply, live, epoch) = (_eligible, _liveLegs, _bnkrEpoch);
for (uint8 leg; leg < LEGS; ++leg) {
if (live & (1 << leg) == 0) continue;
Stream storage s = leg == LEG_BNKR ? _bnkrStream(epoch) : _streams[leg];
uint256 rpt = _updateLeg(s, supply);
if (rpt == 0) continue;
bool walk = leg == LEG_BNKR && epoch != 0;
if (from != address(0)) _settleLeg(s, walk, from, fromBal, rpt);
if (to != address(0)) _settleLeg(s, walk, to, toBal, rpt);
}
}
/// @dev Overridable so the distributor can answer its hottest exclusion (the PoolManager) from an immutable.
function _excluded(address account) internal view virtual returns (bool) {
return rewardExcluded[account];
}
/// @dev Stream the leg's surplus (_schedule); returns what it added to the stream, and what the floored rate left
/// stays surplus for the next notify.
function _notifySurplus(uint8 leg) internal returns (uint256) {
Stream storage s = _openLeg(leg);
uint256 amount = _surplus(leg);
uint256 carry = _schedule(leg, s, amount);
return amount > carry ? amount - carry : 0;
}
/// @dev Decision 1's QUOTE intake, storage only: `p` (the buffer and what just arrived) streams from a wei a
/// second over a period (before the leg is live, from `floor_`) and, between periods, from a lower `floor_`
/// (audit F-16). Returns the new buffer: all of `p` while it waits, else what the floored rate left.
function _foldQuote(uint256 p, uint256 floor_) internal returns (uint256) {
if (p < rewardStreamSecs) {
if (p < floor_ || block.timestamp < _streams[LEG_QUOTE].periodFinish) return p;
} else if (_liveLegs & (1 << LEG_QUOTE) == 0 && p < floor_) {
return p;
}
return _schedule(LEG_QUOTE, _openLeg(LEG_QUOTE), p);
}
/// @dev The leg's open stream, made live by its first notify or else advanced to now.
function _openLeg(uint8 leg) private returns (Stream storage s) {
s = _stream(leg);
if (_liveLegs & (1 << leg) == 0) _liveLegs |= uint8(1 << leg);
else _updateLeg(s, _eligible);
}
/// @dev A meaningful `amount` (>= rewardRestartBps of what is still streaming) restarts a full period with the
/// remainder folded in (a shorter one when that is under a wei a second); a small one joins the open period.
/// Returns the carry: what the rate, floored to a wei a second and capped at uint176, leaves of `amount` plus
/// the remainder. The event reports what the stream gained: a carry re-offered later is never counted twice.
function _schedule(uint8 leg, Stream storage s, uint256 amount) private returns (uint256 carry) {
uint256 remaining = _remainingStream(leg);
uint256 finish = s.periodFinish;
if (amount >= Math.ceilDiv(remaining * rewardRestartBps, 10_000)) {
finish = block.timestamp + rewardStreamSecs;
}
uint256 total = amount + remaining;
uint256 left = finish - block.timestamp;
// a full period would floor this to a rate of 0 and stream none of it (audit F-16)
if (total != 0 && total < left) (left, finish) = (total, block.timestamp + total);
// the rest of a rate past uint176 is carried too (R7-01)
uint256 rate = Math.min(total / left, type(uint176).max);
carry = total - rate * left;
// casting is safe: rate is capped above and finish a timestamp at most 2^32 seconds ahead
// forge-lint: disable-next-line(unsafe-typecast)
(s.rewardRate, s.lastUpdateTime, s.periodFinish) = (uint176(rate), uint40(block.timestamp), uint40(finish));
emit RewardsNotified(leg, amount > carry ? amount - carry : 0, rate, finish);
}
/// @dev The buffer's field: what lies past it stays in the balance or the ledger, where reconcile finds it again.
function _setPending(uint256 p) internal {
// casting is safe: clamped to the field
// forge-lint: disable-next-line(unsafe-typecast)
_pendingQuote = uint112(Math.min(p, type(uint112).max));
}
/// @dev Claim bookkeeping: zeroes the account's settled rewards on one stream before anything is paid.
function _take(Stream storage s, address account) internal returns (uint256 amount) {
uint256 r = s.rewards[account];
amount = r & SETTLED_MASK;
if (amount == 0) return 0;
s.rewards[account] = r - amount; // the carried remainder stays
s.rewardsClaimed += amount;
}
/// @dev A payout its asset refused: the rewards go back to the account, unclaimed.
function _untake(Stream storage s, address account, uint256 amount) internal {
s.rewards[account] = _credit(s.rewards[account], amount);
s.rewardsClaimed -= amount;
}
/// @dev One-way exclusion of an eligible account holding `balance`: settled, its unclaimed rewards on `legs` (a bit
/// mask) forfeited back to surplus, its balance out of the eligible supply. Closed BNKR epochs are never
/// forfeited: nothing can re-stream them, so the account keeps what it earned there.
function _exclude(address account, uint256 balance, uint256 legs) internal returns (uint256[3] memory forfeited) {
_settleAll(account, balance);
for (uint8 leg; leg < LEGS; ++leg) {
if (legs & (1 << leg) == 0) continue;
Stream storage s = _stream(leg);
uint256 f = s.rewards[account] & SETTLED_MASK;
if (f == 0) continue;
s.rewards[account] = 0;
s.rewardsAllocated -= f;
forfeited[leg] = f;
}
// casting to 'uint128' is safe because an eligible balance is counted in the uint128 eligible supply
// forge-lint: disable-next-line(unsafe-typecast)
_eligible -= uint128(balance);
rewardExcluded[account] = true;
}
/// @dev Closes the open BNKR epoch (its stream has ended: brought to its finish, the accumulator is final) and opens
/// the next at EPOCH_START. The BNKR live bit stays set, so transfers keep settling it, walk included.
function _closeBnkrEpoch() internal returns (uint256 closed) {
closed = _bnkrEpoch;
_updateLeg(_bnkrStream(closed), _eligible);
_bnkrStreams[closed + 1].rewardPerTokenStored = EPOCH_START;
// casting to 'uint8' is safe because the distributor opens at most MAX_BNKR_EPOCHS
// forge-lint: disable-next-line(unsafe-typecast)
_bnkrEpoch = uint8(closed + 1);
}
}
src/interfaces/IBankrFeeLedger.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
/// @notice Ledger surface: the FeesManager-compatible subset (bucketId plays "poolId") plus bucket extensions.
interface IBankrFeeLedger {
/// @dev `creatorShare` is the part of `shares` that is a launch fee recipient's own (design: several fee recipients):
/// the label that tells a creator entry from a pad payee, the holders, auto-LP and buyback, and what a community
/// takeover moves. An entry merged with a pad payee holds more than its creator part. Both fit: at most WAD.
struct Beneficiary {
uint128 shares;
uint64 creatorShare;
uint256 lastCumulatedFees0;
uint256 lastCumulatedFees1;
}
/// @dev A pool's fee terms, frozen at launch: its hook (the only caller of creditSwap), the flags below, the
/// referrer rate, Bankr's slice (its share of the fee, its floor in pips of volume, the holders' part of it)
/// and the holder leg the coin keeps for life. Slot 0 is full and is all a plain swap reads.
struct PoolTerms {
address hook;
// T_QUOTE_IS_0 1, T_WAIVED 2 (Bankr's own part stays in the remainder), T_DECAY_SPLIT 4, T_TREASURY_CUT 8
// (either treasury share below is set), T_HOLDER_INTAKE 16 (`distributor` is set: decision 1's accrue)
uint8 flags;
uint16 referrerBps;
uint16 bankrFeeBps;
uint24 bankrMinPips;
uint16 holdersShareBps;
uint16 legId;
// The treasury marker's shares of the steady part and decay surplus go to bankrId rounded up, since two
// remainder-bucket floors per release left its claim up to ~1.1 wei under the ruling.
uint64 treasuryWad;
uint64 treasuryDecayWad;
address distributor;
uint64 holderWad;
}
/// @dev A queued community takeover of a launch's creator share (spec §9): the new recipient, when it may execute,
/// and the CTO authority's epoch at queue time (any rotation of the authority voids it).
struct PendingCto {
address newRecipient;
uint64 executeAfter;
uint32 epoch;
}
event Collect(bytes32 indexed poolId, uint256 fees0, uint256 fees1);
event Release(bytes32 indexed poolId, address indexed beneficiary, uint256 fees0, uint256 fees1);
event UpdateBeneficiary(bytes32 poolId, address oldBeneficiary, address newBeneficiary);
event BucketRegistered(bytes32 indexed bucketId, bytes32 indexed poolId, address[] beneficiaries, uint256[] shares);
/// @dev `hook` is the only crediter of a pool bucket (0 = a currency bucket: any allowlisted hook); a locked
/// bucket's beneficiaries can never move.
event BucketBound(bytes32 indexed bucketId, address indexed hook, bool locked);
event ProtocolSinkSet(address indexed sink, bool allowed);
event HookSet(address indexed hook, bool allowed);
event ClaimsCollectorSet(address indexed who, bool allowed);
/// @dev The stored terms whole, so a coin's frozen split is known from its launch.
event PoolTermsRegistered(bytes32 indexed poolId, PoolTerms terms);
event LegAdded(uint16 indexed legId, address indexed leg);
/// @dev One per swap fee: `bankr` is what bankrId took (Bankr's own half, plus the treasury's cut of the remainder
/// on Bankr's pad), `holders` the coin's holders' half, `remainder` what the creator and decay buckets took.
event SwapFee(
bytes32 indexed poolId,
address indexed sender,
uint24 feePips,
uint256 fee,
uint256 bankr,
uint256 holders,
address indexed referrer,
uint256 referral,
uint256 remainder
);
// claim all: an earner's balance per currency holds its referral slices and the bucket shares settled into it
/// @dev A bucket share moved into the account's balance: an internal move, not a payout.
event Settled(bytes32 indexed bucketId, address indexed account, uint256 fees0, uint256 fees1);
/// @dev The account's balance in one currency was paid to it (a payout, as Release is).
event Withdraw(address indexed account, Currency indexed currency, uint256 amount);
/// @dev The currency refused the payout (frozen, halted, reverting, or it burned PAYOUT_GAS): nothing moved, the
/// balance stays.
event Withheld(address indexed account, Currency indexed currency, uint256 amount);
/// @dev Q9: the account's claim policy. Open (false, the default): anyone may settle, push and claim for it, paid
/// to it only. Restricted: only itself and the claim operators it names.
event ClaimRestrictedSet(address indexed account, bool restricted);
event ClaimOperatorSet(address indexed account, address indexed operator, bool allowed);
/// @dev Decision 1: the pool's distributor failed its accrue with all of its stipend. The share stays in the ledger
/// for the distributor's next pull (a claim's, or anyone's reconcile), so it streams late, never lost.
event HolderAccrueFailed(bytes32 indexed poolId, uint256 amount);
// community takeover (CTO, spec §9): ops surface; a takeover moves only the creator's own share of a bucket
/// @dev With BucketRegistered, entry by entry: each beneficiary's creator part (0: not a fee recipient), whether
/// the launch's creator entries can be taken over, and the notice and grace the coin keeps for life.
event CreatorShares(bytes32 indexed bucketId, uint256[] creatorShares, bool takeover, uint32 notice, uint32 grace);
event CtoAuthoritySet(address indexed authority, uint32 epoch);
event CtoQueued(bytes32 indexed creatorId, address indexed newRecipient, uint64 executeAfter, uint64 expiresAt);
event CtoCancelled(bytes32 indexed creatorId, address indexed by);
/// @dev One per entry whose creator part moved, creatorId's then decayId's: up to 64 in each (TooManyEntries). None
/// when the launch has no creator part: the execute still consumes its notice (NS-18 LEDGER-4).
event CtoExecuted(
bytes32 indexed bucketId, address indexed oldRecipient, address indexed newRecipient, uint256 shareWad
);
event CtoDisabledForever();
error NotFactory();
error NotHook();
error NotPoolManager();
error BucketExists();
error UnknownBucket();
error SharesMismatch();
error NotBeneficiary();
error BeneficiaryExists();
error NotProtocolSink();
error ZeroAddress();
error SentinelPayee();
error NotClaimsCollector();
error BeneficiaryLocked();
/// @dev A credit the ledger's ERC-6909 balance of that currency does not back (credited − released > balance).
error Insolvent();
error NotPoolHook();
error UnknownPool();
error PoolTermsExist();
error InvalidPoolTerms();
error NotFactoryOwner();
error NotCtoAuthority();
/// @dev Not a launch's creatorId, or registered without a takeover (the coin's pad had it off at launch).
error NotCtoEligible();
error NoPendingCto();
error CtoTimelockActive();
/// @dev A queued takeover unlocked more than the coin's grace ago: it is dead, and must be queued again.
error CtoExpired();
/// @dev A bucket with more entries than its header's uint8 count holds (255), or than one takeover transaction
/// settles (64) on a coin that can be taken over, its decay bucket included.
error TooManyEntries();
error CtoAuthorityRotated();
error CtoDisabled();
/// @dev Zero, a routing marker (LedgerOps.isSentinel), a holder of more than a creator part where the takeover
/// moves one, or a contract that could never collect the share (LedgerOps.strands, as InvalidBeneficiary).
error InvalidCtoRecipient();
/// @dev A beneficiary's move to a contract that could never collect: the coin's TOKEN or quote, the PoolManager, the
/// ledger or the factory's suite code (H13 ECON-I2). Also a bucket bound with one of its own currencies as a
/// payee (NS-18 LEDGER-1): a launch that names the quote token as a recipient reverts with it.
error InvalidBeneficiary();
/// @dev Under PAYOUT_GAS * 64 / 63 plus the call's own cost left for a payout: the whole call reverts, never a skip.
error InsufficientGas();
/// @dev withdrawFor an account the caller may not push: a claims collector, a protocol sink, a suite contract, or a
/// restricted account that did not name the caller its claim operator.
error NotPushable();
error NotLeg(); // setHoldersWake or drawWindow from an address the factory never registered as a holder leg
error LegExists(); // addLeg for a leg that has its id: an id is written once
/// @dev A conversion that spent more of a quote than its window had left for this leg's cap.
error WindowExceeded();
// factory / hook surface
/// @dev Binds the bucket to `key.hooks` (which must be allowlisted): only that hook may ever credit it. `cto`: bit 0
/// the launch's creator entries can be taken over, bits 8..39 the notice in seconds (at least 3,600), bits
/// 40..71 the grace (at least 1); 0 for a bucket no takeover is queued on (a decayId, any coin with it off).
function registerBucket(
bytes32 bucketId,
PoolKey calldata key,
address[] calldata beneficiaries,
uint256[] calldata sharesWad,
uint256[] calldata creatorShares,
uint256 cto
) external;
/// @dev A one-payee pool bucket: `payee` at 100 %, bound to `key.hooks`; `locked` pins the payee for good (a launch's
/// holdersId, so nothing can redirect the holders' half of Bankr's slice).
function registerSoleBucket(bytes32 bucketId, PoolKey calldata key, address payee, bool locked) external;
/// @dev Chain-wide bucket keyed by a currency, not a pool (bankrId, Bankr's own half and extension cut): poolId = 0,
/// currency0 = `currency`, currency1 = ADDRESS_ZERO; credited with isCurrency0 == true by any allowlisted hook.
function registerCurrencyBucket(
bytes32 bucketId,
Currency currency,
address[] calldata beneficiaries,
uint256[] calldata sharesWad
) external;
function credit(bytes32 bucketId, bool isCurrency0, uint256 amount) external;
/// @dev Binds a pool's terms once; every bucket creditSwap credits must already exist. Refused (InvalidPoolTerms)
/// where the split could underflow at `lowerSteadyPips`, the lower of the pool's two steady fees, or a share,
/// a flag or the leg id is out of range (LedgerCold.registerPoolTerms holds the checks).
function registerPoolTerms(bytes32 poolId, PoolKey calldata key, PoolTerms calldata t, uint24 lowerSteadyPips)
external;
/// @dev The pool's hook, once per swap, after minting `fee` of the quote to the ledger: splits it (FeeMath.swapSplit
/// at `f` with the swap direction's steady rate `s`) into its buckets and the referrer's balance, then accrues
/// the distributor's creatorId share of it into the holders' stream (decision 1). `wake`: 1 when the swap runs
/// inside an extension's post-swap frame or the buyback's fill (the hook's own flag), so its accrue only buffers
/// and no leg wakes; 0 for an outer swap whose sender did not ask for the holder wake; 2 + n when it did
/// (HookData.HOLDERS_WAKE) and keeps n gas for the rest of its route.
function creditSwap(bytes32 poolId, address sender, uint24 f, uint24 s, uint256 fee, address referrer, uint256 wake)
external;
/// @notice Accounting only: each account's share of each bucket into its balance (no token moves, so none can fail
/// it). Settles an account whose claim policy lets the caller (mayClaimFor: anyone while it is open), and
/// never a claims collector, protocol sink or suite contract; anything else is skipped.
function settle(bytes32[] calldata bucketIds, address[] calldata accounts) external;
/// @notice Settles the caller's listed buckets (none: the balance alone, a referrer's old claim), then pays its whole
/// balance in each named currency, ERC-20 through the ledger's own unlock (so never inside a swap). Each
/// payout gets exactly PAYOUT_GAS: a refusal is Withheld and the other currencies still pay.
function withdraw(bytes32[] calldata bucketIds, Currency[] calldata currencies) external;
/// @notice withdraw's payouts for `account`, paid to `account` only (NotPushable: whom the caller may not push; a
/// puller, never settled, is pushed by anyone when it holds a balance in a named currency: NS-18 LEDGER-2).
function withdrawFor(address account, Currency[] calldata currencies) external;
/// @notice The caller's balance in one currency with every unit of gas, reverting on refusal: the way out for a quote
/// whose honest transfer needs more than PAYOUT_GAS.
function withdrawUncapped(Currency currency) external;
/// @notice Q9: the caller's own policy, reversible. Restricted, only the caller and its claim operators may settle,
/// push or claim for it, on this ledger and on every holder distributor.
function setClaimRestricted(bool restricted) external;
/// @dev While the caller is restricted, the operator may settle it, push it its balance and claim its holder
/// rewards: the timing, never the destination. Revocable; it matters only while the caller is restricted.
function setClaimOperator(address operator, bool allowed) external;
function claimRestricted(address account) external view returns (bool);
function isClaimOperator(address account, address operator) external view returns (bool);
/// @notice The one claim policy (Q9) the ledger and every distributor apply: the account itself, anyone while it is
/// open, or an operator it named while it is restricted.
function mayClaimFor(address account, address caller) external view returns (bool);
function setProtocolSink(address sink, bool allowed) external;
function setHook(address hook, bool allowed) external;
function setClaimsCollector(address who, bool allowed) external;
// community takeover (spec §9). The factory's owner appoints the authority, cancels and can weld the
// feature off for good; the authority queues, cancels and, the coin's notice later under the same appointment,
// executes.
/// @dev Every call, a re-appointment included, starts a new epoch, so nothing queued before it can execute.
function setCtoAuthority(address authority) external;
/// @dev One-way: the authority is cleared and can never be set again.
function disableCtoForever() external;
/// @dev Replaces any earlier queue for the launch and restarts the clock. Not dismissable by a fee recipient: no
/// claim, beneficiary move or other recipient action stops it (a creator part is followed wherever it
/// moves). It unlocks the coin's own notice later and expires its grace after that (CtoExpired, ctoTermsOf).
function queueCto(bytes32 creatorId, address newRecipient) external;
function cancelCto(bytes32 creatorId) external;
/// @dev Settles every fee recipient into its own balance (Settled) and moves every creator part, in creatorId and
/// in decayId, to the one new recipient (a merged operator part stays with its address). No token moves, so
/// no recipient's code or token can stop or price it: each old one withdraws as ever. CtoExpired once stale.
function executeCto(bytes32 creatorId) external;
// claims-collector surface (the hook's LP backlog): same bookkeeping as collectFees, paid as
// ERC-6909 via poolManager.transfer — no unlock, so it works INSIDE a swap
function collectFeesAsClaims(bytes32 bucketId) external returns (uint256 fees0, uint256 fees1);
/// @notice A registered holder leg, for its own coins (decision 2): the holders' pile a swap wakes it at, in `quote`.
function setHoldersWake(Currency quote, uint96 floor) external;
/// @notice The wake a swap of one of `legId`'s coins checks: the leg in the low 160 bits, the pile it wakes at
/// above (0: unarmed).
function holdersWake(uint16 legId, Currency quote) external view returns (uint256);
/// @notice The factory only, once per leg: the next leg id, from 1. The id is never cleared, so the leg stays a
/// puller here for life (never settled, never a payee's move or a takeover's heir) whatever the factory
/// names later.
function addLeg(address leg) external returns (uint16 legId);
function legIdOf(address leg) external view returns (uint16);
/// @notice `quote`'s conversion window, one for every leg: open until `until`, with `left` of a cap still to draw.
function windowOf(Currency quote) external view returns (uint64 until, uint192 left);
/// @notice A registered leg, after converting `spent` of `quote`: its room is `left` capped at `cap` while the
/// window is open, else `cap` (WindowExceeded above it); the window keeps the rest and stays open at least
/// `interval` more. A leg can use a window up or keep it shut, never widen it for another leg.
function drawWindow(Currency quote, uint256 spent, uint256 cap, uint32 interval) external;
// FeesManager-compatible surface
function collectFees(bytes32 bucketId) external returns (uint128 fees0, uint128 fees1);
function collectFeesMany(bytes32[] calldata bucketIds)
external
returns (uint128[] memory fees0, uint128[] memory fees1);
function collectFeesFor(bytes32 bucketId, address beneficiary) external returns (uint128 fees0, uint128 fees1);
function updateBeneficiary(bytes32 bucketId, address newBeneficiary) external;
function updateBeneficiaryMany(bytes32[] calldata bucketIds, address newBeneficiary) external;
function getShares(bytes32 bucketId, address beneficiary) external view returns (uint256);
function getCumulatedFees0(bytes32 bucketId) external view returns (uint256);
function getCumulatedFees1(bytes32 bucketId) external view returns (uint256);
function getLastCumulatedFees0(bytes32 bucketId, address beneficiary) external view returns (uint256);
function getLastCumulatedFees1(bytes32 bucketId, address beneficiary) external view returns (uint256);
// extensions
/// @dev One currency of the caller's share, so a quote whose transfers revert cannot hold the other leg.
function collectFeesSide(bytes32 bucketId, bool isCurrency0) external returns (uint256 fees);
function claimable(bytes32 bucketId, address beneficiary) external view returns (uint256 fees0, uint256 fees1);
function bucketOf(bytes32 bucketId)
external
view
returns (bytes32 poolId, Currency currency0, Currency currency1, bool exists);
function bucketBinding(bytes32 bucketId) external view returns (address hook, bool locked);
function beneficiariesOf(bytes32 bucketId) external view returns (address[] memory);
function poolTerms(bytes32 poolId) external view returns (PoolTerms memory);
/// @dev An account's pull balance in one currency (referral slices and settled shares), counted in `outstanding`.
function balances(address account, Currency currency) external view returns (uint256);
function PAYOUT_GAS() external view returns (uint256);
/// @notice Gas the accrue is handed in an outer swap, and in a nested one (decision 1): short of it plus the call's
/// own cost, the swap reverts InsufficientGas, so an estimated gas limit always accrues.
function ACCRUE_GAS() external view returns (uint256);
function ACCRUE_BUFFER_GAS() external view returns (uint256);
/// @dev Credited minus released across every bucket; never above poolManager.balanceOf(ledger, currency).
function outstanding(Currency currency) external view returns (uint256);
function isProtocolSink(address sink) external view returns (bool);
function isHook(address hook) external view returns (bool);
function isClaimsCollector(address who) external view returns (bool);
function factory() external view returns (address);
function poolManager() external view returns (IPoolManager);
function ctoAuthority() external view returns (address);
function ctoAuthorityEpoch() external view returns (uint32);
function ctoDisabledForever() external view returns (bool);
function pendingCto(bytes32 creatorId)
external
view
returns (address newRecipient, uint64 executeAfter, uint32 epoch);
/// @dev The creator part of `beneficiary`'s entry in `bucketId` (0: not a fee recipient's entry). It follows the
/// entry through its own moves.
function creatorShareOf(bytes32 bucketId, address beneficiary) external view returns (uint256);
/// @dev How many entries of `bucketId` hold a creator part.
function creatorCount(bytes32 bucketId) external view returns (uint256);
function ctoEligible(bytes32 bucketId) external view returns (bool);
/// @dev A launch's takeover terms as frozen in its creator bucket: whether it can be taken over, the public notice
/// before an execute and how long after it the execute stays open, in seconds.
function ctoTermsOf(bytes32 creatorId) external view returns (bool eligible, uint32 notice, uint32 grace);
}
src/interfaces/IBankrLaunchFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {VestingAllocation} from "./ICreatorVestingEscrow.sol";
import {IBankrLaunchpadRegistry} from "./IBankrLaunchpadRegistry.sol";
import {FeeSchedule} from "../libraries/FeeMath.sol";
/// @dev How the factory prices a quote in USD to bound a launch's start tick (security finding 9; v2 PairRegistry).
/// NONE: the quote takes no launches. CHAINLINK: a USD feed behind the L2 sequencer gate. SIGNED: a
/// PriceAttestation from the factory's priceSigner, carried by the launch itself.
enum PricingMode {
NONE,
CHAINLINK,
SIGNED
}
/// @dev EIP-712 ("Bankr Launch Pricing", "1", chainId, factory) over PriceAttestation(address quote,uint256
/// priceUsdE18,uint64 observedAt,uint64 expiresAt). Empty for a CHAINLINK quote.
struct PriceAttestation {
uint256 priceUsdE18; // USD per whole quote token
uint64 observedAt;
uint64 expiresAt;
bytes signature;
}
/// @dev A launch's extension, bound for good. `id` != 0: a Bankr preset deployed in the launch from `params` (README
/// "Presets"). `id` 0 with `ext` set: the launcher's pre-deployed code, admitted by the hook at `codehash` with
/// these maxima, quote-only flag and sunset (README "Custom extensions", DYOR). Neither: none. `payee` 0 = the
/// effective fee recipient. A preset declares its own flag and sunset, so those fields stay 0 with an `id`.
struct LaunchExtension {
uint8 id;
bytes params;
address payee;
address ext;
bytes32 codehash;
uint24 maxBuyPips;
uint24 maxSellPips;
bool quoteOnly;
uint32 sunsetSecs;
uint24 quoteGas; // custom code only: 0 = EXT_QUOTE_GAS, else within [EXT_QUOTE_GAS, EXT_QUOTE_GAS_MAX]
uint24 afterGas; // custom code only: 0 = EXT_AFTER_GAS (unless quote-only), else within [.., EXT_AFTER_GAS_MAX]
}
/// @dev A launch's own economics (Launch SDK H3–H5, H8), checked against the protocol bounds by LaunchEconomics and its
/// pad's by the registry, and bound for good: one fee schedule per direction (a buy is quote in); the referrer's
/// slice of the fee, paid off the remainder to a referrer the trader names (0–500 bps, 0 = none); and the creator
/// side of the remainder after Bankr's slice, the referrer and the operators: `holdersBps` to the coin's
/// distributor, `autoLpBps` to the hook's band and `buybackBps` to BankrBuyback, in bps of that side (sum <=
/// 10,000; any may be 0). `vestToHoldersBps` of supply vests to the coin's holders (H9a): a push schedule to the
/// distributor in the launch's escrow, cliff <= duration <= 365 days, counted with `vestBps` against the pad's
/// vested total.
struct LaunchEconomics {
FeeSchedule buy;
FeeSchedule sell;
uint16 referrerBps;
uint16 holdersBps;
uint16 autoLpBps;
uint16 buybackBps;
uint16 vestToHoldersBps;
uint64 vestToHoldersCliff;
uint64 vestToHoldersDuration;
}
/// @dev One of a launch's fee recipients and its share of the creator's own take (what is left of the creator side
/// after the pad's payees and the launch's holders, auto-LP and buyback shares), in bps of that take.
struct FeeRecipient {
address recipient;
uint16 shareBps;
}
struct LaunchParams {
string name;
string symbol;
string metadataUri;
/// @dev May replace the token's metadata URI after launch; zero fixes it from the first block. Never defaulted.
address metadataAdmin;
bytes32 salt;
address quote;
uint256 totalSupply; // 0 => the pad's default supply
int24 expectedStartTick; // quote per token (token-as-currency0 orientation), spacing-aligned, in startTickBounds
uint256 deadline;
// 0 runner_v1, 1 degen, 2 thin topside (RunnerCurve tables, H10); any other value is the launch's own table
// (CurveTable): up to eight 32-bit rows from the top bits, each (width in 200-tick spacings << 16) | share in bps.
uint256 curveId;
LaunchEconomics econ; // forwarded undecoded: LaunchRegistry checks it and binds it on the hook
// The creator's take, split: at most the pad's limit of distinct recipients, each share above 0, summing to 10,000.
// None => the launcher alone. The first is the primary: it takes the rounding remainder, and alone it is the default
// extension payee (a list of two or more must name the payee). A recipient with code (not an EIP-7702 account) must
// have restricted its claims on the ledger, unless the launch waives that with `allowOpenCodeFeeRecipients`.
FeeRecipient[] feeRecipients;
bool allowOpenCodeFeeRecipients;
address vestingRecipient; // 0 => launcher
uint16 vestBps; // 0..5000
bool allowCodeVestingRecipient;
VestingAllocation[] extraAllocations; // builder lane; all schedules live in the launch's escrow clone
address[] capExclusions; // the token's 2 %/24 h wallet cap skips these (the chain's aggregator settlers)
uint256 devBuyAmountIn;
uint256 devBuyMinOut;
uint64 launchpadId; // 0 = Bankr's own pad (the spec §4 preset), always signed by the registry's bankrSigner (D10)
uint16 maxOperatorShareBps; // the most of the remainder the pad's payees may take, steady and decay (audit r1 F-2)
bytes32 operatorPayeesHash; // keccak256(abi.encode(PadTerms)) of the pad's terms the launcher expects; 0 = any (ADM-03)
IBankrLaunchpadRegistry.LaunchAuthorization authorization; // empty (0, 0, "") for an open pad
PriceAttestation priceAttestation; // SIGNED quotes only
LaunchExtension extension; // a preset, custom code or none; a signed launch commits to it (LaunchpadAuth.termsHash)
// Scheduled start: the second public trading opens. 0 = at launch; otherwise strictly after the launch's own block
// (StartPassed) and at most the pad's start delay ahead (StartTooFar).
// Fixed for good once the launch lands; inside the terms hash, so a signed launch commits to it.
uint64 startTime;
// "" (every option at its pad's default, no pin) or abi.encode(LaunchOptions): the launch's own picks of what
// LaunchParams has no field for, and its pins on the resolved terms and the token address.
bytes options;
}
/// @dev setSuite's wiring, as one struct (its ten addresses do not fit a frame's stack).
struct SuiteAddrs {
address hook;
address ledger;
address locker;
address holderRewardsDeployer;
address tokenDeployer;
address vestingEscrowImpl;
address holderLeg;
address buyback;
address launchpadRegistry;
address settings;
}
struct LaunchResult {
address token;
bytes32 poolId;
address distributor;
address vestingEscrow; // 0 when nothing vests
uint256 devBuyOut;
}
/// @notice Factory surface: single-pool launch through the chain's ITokenDeployer + one CreatorVestingEscrow clone,
/// every term of it taken from the settings contract's resolve and frozen per coin, the launch gate, the
/// treasury protocol sink and the holder leg, pause, hook rotation. Errors of the factory's own libraries are
/// declared HERE (`IBankrLaunchFactory.X`); a launch also bubbles IBankrLaunchSettings' own, unchanged.
interface IBankrLaunchFactory {
function launch(LaunchParams calldata p) external payable returns (LaunchResult memory);
function computeTokenAddress(address launcher, bytes32 salt, LaunchParams calldata p)
external
view
returns (address);
function computeVestingEscrow(address launcher, bytes32 salt) external view returns (address);
/// @notice The `pHash` a pad's signer signs for `p` sent by `launcher` with `nativeDevBuy` wei (LaunchpadAuth
/// .termsHash), payees resolved as launch() resolves them. Served here, not by the registry (EIP-170).
function hashLaunchTerms(LaunchParams calldata p, address launcher, uint256 nativeDevBuy)
external
view
returns (bytes32 pHash);
/// @notice One-shot (SuiteAlreadySet). Registers the leg with the ledger as leg 1 and records it, exactly as
/// setHolderLeg does later.
function setSuite(SuiteAddrs calldata a) external;
/// @notice Every owner setter below is one call with no wait (suite 4). Future launches only: the new hook joins
/// the generations list; pools on an earlier generation stay there.
function setHook(address newHook) external;
function setPaused(bool paused) external;
/// @notice On (the deploy default): only Bankr's id 0 may launch (plan Q15-B). Off: pads launch under their own
/// rules too. Id 0 always carries an authorization from the launchpad registry's bankrSigner (D10).
function setLaunchGated(bool gated) external;
/// @notice Bankr's own half of future quotes' buckets, the bond payee and the ledger's protocol sink (H13 GOV-1),
/// at once. The sink moves from the old Safe to the new one; the old Safe still collects its own.
function setTreasury(address treasurySafe) external;
/// @notice Suite code (every hook generation, a linked library) or a routing marker: never a
/// payee anything collects.
function isSuite(address a) external view returns (bool);
function paused() external view returns (bool);
function launchGated() external view returns (bool);
function weth() external view returns (address);
function treasury() external view returns (address);
/// @dev Sole, locked beneficiary of the holdersId bucket of every launch made while it is named here: the BNKR
/// holder leg in force (H17). A coin keeps the leg of its launch; setHolderLeg changes it for later ones.
function holderLeg() external view returns (address);
/// @notice Owner, instant: registers `leg` with the ledger and names it for every launch from now on. The leg and
/// its references are suite code for good.
function setHolderLeg(address leg) external;
/// @dev The chain's BankrBuyback (H8b): the `buyback` payee of every launch's creator bucket that opts in. Set once.
function buyback() external view returns (address);
function hook() external view returns (address);
function ledger() external view returns (address);
function locker() external view returns (address);
function holderRewardsDeployer() external view returns (address);
function tokenDeployer() external view returns (address);
function vestingEscrowImpl() external view returns (address);
function launchpadRegistry() external view returns (address);
/// @notice The settings contract: every launch's terms are its resolve's answer. Set once, in setSuite.
function settings() external view returns (address);
/// @notice keccak256 of the coin's CoinTerms as stored and logged (CoinTermsFrozen); 0 for any other address.
function termsHashOf(address token) external view returns (bytes32);
/// @notice Every hook generation this factory wired, oldest first; a launch registers on the newest.
function hookGenerations() external view returns (address[] memory);
function launcherOf(address token) external view returns (address);
function vestingEscrowOf(address token) external view returns (address);
function poolOf(address token) external view returns (bytes32 poolId, PoolKey memory key);
function FEES_TO_HOLDERS() external view returns (address);
event TokenLaunched(
address indexed token,
address indexed launcher,
address indexed quote,
bytes32 poolId,
int24 startTick,
string metadataUri,
uint64 launchpadId
);
/// @dev Only for a launch whose trading opens later than the launch itself: `startTime` is the second the hook
/// first lets a public swap through and the token first lets a wallet move it.
event TradingScheduled(address indexed token, bytes32 indexed poolId, uint64 startTime);
/// @dev The coin's record, once: `terms` is abi.encode(CoinTerms) with the words only the factory knows filled in
/// (the token, the trading start, a preset's binding), `termsHash` its hash (termsHashOf), `resolvedHash`
/// what resolve returned for the same launch (the launcher's pin). Logged before the pool is initialised.
event CoinTermsFrozen(
address indexed token, bytes32 indexed poolId, bytes32 termsHash, bytes32 resolvedHash, bytes terms
);
event LaunchResolved(
address indexed token,
uint256 curveId,
address distributor,
address vestingEscrow,
address vestingRecipient,
uint256 devBuyOut
);
event HookSet(address indexed hook);
event PausedSet(bool paused);
event TreasurySet(address indexed treasury);
event HolderLegSet(address indexed holderLeg, uint16 legId);
event LaunchGateSet(bool gated);
error Paused();
error Expired();
error InvalidTick();
error TokenSaltTaken();
error TokenAddressChanged(address actual); // the launch pinned another token address (LaunchOptions.expectedToken)
error MalformedLaunch(); // launch() calldata whose params offset is not the canonical one
error TermsMismatch(); // the split's auto-LP payees or the hook are not the ones the coin's record names
error InvalidCurve(); // neither a built-in curve id (0..2) nor a well-formed table of bands (CurveTable)
error SentinelPayee();
error InvalidVestingRecipient();
error InvalidFeeRecipient();
error InvalidFeeRecipients();
error OpenContractFeeRecipient(address recipient);
error DevBuyTooLarge();
error DevBuyerExcluded(); // a scheduled launch's dev buyer is on the token's cap exclusions: it could move before the start
error DevBuyTooLittle();
error AmbiguousDevBuy();
error DevBuyNativeOnlyForWeth();
error SuiteAlreadySet();
error SuiteUnset();
error OwnershipCannotBeRenounced();
error ZeroAddress();
error NotPoolManager();
error LaunchpadPayeeRejected(); // a pad payee is a sentinel, a suite contract, the token or the escrow
error LaunchGated(); // the gate is on and the launch names a pad other than Bankr's id 0
error InvalidExtensionPayee(); // a sentinel, a suite contract, the token or the escrow
error ExtensionPayeeUnnamed(); // several fee recipients and an extension: the payee must be named
error PresetBindingMismatch(); // the preset deployer returned a binding other than the launch asked for
error AmbiguousExtension(); // a preset id with custom fields, or custom code with preset params
error InvalidHook(); // setSuite's or setHook's hook is not this suite's, or names periphery that is not its own
error InvalidHolderLeg(); // a leg not built on this factory's ledger and distributor deployer, or with no oracle
error InvalidTreasury(); // suite code, a hook generation, a preset instance, a launched token, a quote or a marker
error InvalidSettings(); // setSuite's settings contract was not built for this factory and its pad registry
// Raised by LaunchEconomics' and LaunchPool's dependencies (OpenZeppelin Clones / SafeERC20, RunnerCurve) under the
// factory's delegatecall; declared here so the factory's ABI still decodes every revert a launch can bubble (H18).
error FailedDeployment();
error InsufficientBalance(uint256 balance, uint256 needed);
error SafeERC20FailedOperation(address token);
error UnknownCurve();
// A launch's curve (CurveTable), raised under LaunchPool's delegatecall. A table is held to its coin's own rules
// (CurveRules, from the pad's knobs and the owner's guard); a built-in curve to no liquidity (B8), its per-tick
// figure (B9) and its dust figure (B10) only.
error CurveTooThin(uint256 row); // the row's band holds no liquidity, or under 1 / minDepthDiv of the flat curve's
error CurveLiquidity(uint256 row); // the row's band puts a tick past half of v4's cap (a built-in: past its figure)
error CurveTooDense(uint256 row); // the row's band is over maxDensity times the sale as one band from its near edge
error CurveStep(uint256 row); // a pool that buys its own token: the row's band is over its step on those under it
error CurvePlacement(); // under placeBps of the sale is sold by placeTicks past the start
error CurveDust(uint256 unplaced); // the bands left more of the sale unplaced than the curve's ppm
// B12 at the start price, raised under LaunchPool's delegatecall: a pool with an auto-LP share starts where TOKEN's
// side of its own compound band is worth nothing to the hook's arithmetic: no compound could place until a rise.
error CompoundStartTooDeep();
}
src/interfaces/IBankrLaunchpadRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @dev An extension's kind (0 = none); a pad's flags F6 to F8 in the settings contract switch each kind on.
uint8 constant EXT_KIND_PRESET = 1;
uint8 constant EXT_KIND_QUOTE_ONLY = 2; // custom code bound quote-only: a read-only quote, no post-swap call
uint8 constant EXT_KIND_CALLS_OUT = 3; // custom code with the guarded post-swap call
/// @dev Id 0's suffix, the one suffix closed to launches on every other pad (D28).
uint24 constant BANKR_VANITY = 0xba3;
uint8 constant BANKR_VANITY_NIBBLES = 3;
/// @notice The identity of every launchpad on the Bankr launch suite. One registry per chain; `register()` (bond to the
/// treasury) mints a sequential `launchpadId` from 1 and gives the pad its own rows in the settings contract.
/// Id 0 is Bankr's own pad, operated by the registry owner and always signed by `bankrSigner`. The factory
/// calls `recordLaunch` for every launch: the registry verifies and consumes the signer's one-use EIP-712
/// LaunchAuthorization (domain `("Bankr Launchpads", "1")`, verifying contract = this registry), holds the
/// pad's pause and vanity and records `launchpadOf(token)`. A pad's knobs, flags, payees, quotes, curves and
/// the extension allowlist are the settings contract's.
interface IBankrLaunchpadRegistry {
/// @dev Empty `(0, 0, "")` for an open pad (`signer == address(0)`); id 0 always carries Bankr's.
struct LaunchAuthorization {
bytes32 nonce;
uint256 deadline;
bytes signature;
}
/// @dev The decay window's surplus above the steady fee (spec §3): off, it follows the steady split; on, each payee
/// takes its `sharesWad` of it, auto-LP `autoLpBps` of the rest and the creator what is left.
struct DecaySplit {
bool on;
uint16 autoLpBps;
uint256[] sharesWad;
}
/// @dev The token's last `nibbles` hex digits must be `suffix` (0 nibbles = none; otherwise 4–6, id 0's `ba3`
/// aside). Suffixes are prefix-free across pads, and only `…ba3` is closed to launches on other pads (D28).
struct Vanity {
uint24 suffix;
uint8 nibbles;
}
/// @dev A pad's identity; its settings are the settings contract's and its branding `metadataUriOf`.
struct Launchpad {
address operator; // id 0: the registry owner
address pendingOperator;
address signer; // address(0) = open pad; id 0: bankrSigner
bool paused;
bool verified; // an off-chain badge the registry owner sets; no on-chain effect
Vanity vanity;
}
/// @dev A pad's payees (distinct), each one's WAD share of the remainder and the decay split: what every launch
/// on the pad binds into its buckets. Held by the settings contract (`payeesOf`), which checks them.
struct PadTerms {
address[] payees;
uint256[] steadySharesWad;
DecaySplit decay;
}
// ── registration ─────────────────────────────────────────────────────────
/// @notice Registers a new launchpad; `msg.sender` becomes its operator, `msg.value` must equal the bond. The pad
/// copies the owner's template in the settings contract (`initPad`), with these payees, no decay split,
/// no vanity and takeover off.
function register(
address signer,
address[] calldata payees,
uint256[] calldata steadySharesWad,
string calldata metadataUri
) external payable returns (uint64 id);
// ── operator-only config (immediate; future launches only) ───────────────
/// @notice `address(0)` turns the pad open (no authorization required); on id 0 it is `bankrSigner`, and zero
/// refuses every id-0 launch.
function setSigner(uint64 id, address signer) external;
/// @notice `4 <= nibbles <= 6` (or 0, none) and `suffix < 16^nibbles`; reverts `VanityTaken` unless prefix-free with
/// every other pad's. Only `…ba3` (id 0's) binds launches from other pads.
function setVanity(uint64 id, Vanity calldata vanity) external;
/// @notice At most `maxPadUriBytes` bytes (`MetadataTooLong`).
function setMetadataUri(uint64 id, string calldata uri) external;
function setPaused(uint64 id, bool paused) external;
function transferOperator(uint64 id, address next) external;
function acceptOperator(uint64 id) external;
// ── factory-only ─────────────────────────────────────────────────────────
/// @notice Verifies + consumes the authorization over `paramsHash` (id 0: always `bankrSigner`'s), holds the
/// pad's pause and vanity, records `launchpadOf(token)`. The launch's terms are the settings contract's.
function recordLaunch(
uint64 id,
address launcher,
address token,
bytes32 paramsHash,
LaunchAuthorization calldata auth
) external;
// ── owner (Bankr): the bond, the pad link's size, its own signer and the verified badge ──
/// @notice Any amount, immediate: 0 is free registration. No pool's economics read it.
function setRegistrationBond(uint256 wei_) external;
/// @notice The longest link a pad may store, in bytes; 0 admits the empty link only. A stored link stands.
function setMaxPadUriBytes(uint32 bytes_) external;
/// @notice Id 0's signer (its `setSigner` slot): signs every id-0 launch; zero refuses them all.
function setBankrSigner(address signer) external;
function bankrSigner() external view returns (address);
function setVerified(uint64 id, bool verified) external;
/// @notice Permissionless; pays every accrued bond to the factory's treasury as it stands at the call.
function withdrawBonds() external;
// ── views ────────────────────────────────────────────────────────────────
function BANKR_LAUNCHPAD_ID() external view returns (uint64);
function maxPadUriBytes() external view returns (uint32);
function factory() external view returns (address);
/// @notice `factory.treasury()`, read live, so a rotated treasury takes the bonds too (audit r3 ADM-2).
function treasury() external view returns (address);
function registrationBondWei() external view returns (uint256);
function accruedBonds() external view returns (uint256);
function launchpadCount() external view returns (uint64);
/// @notice A pad's operator; id 0's is the registry's owner.
function operatorOf(uint64 id) external view returns (address);
function getLaunchpad(uint64 id) external view returns (Launchpad memory);
function metadataUriOf(uint64 id) external view returns (string memory);
/// @notice The pad owning a vanity suffix, and whether one does (id 0 owns `0xba3`/3); a revoked suffix is owned by
/// `type(uint64).max` (the registry owner's) until the pad it is assigned to takes it.
function vanityOwner(uint24 suffix, uint8 nibbles) external view returns (bool owned, uint64 id);
/// @notice Owner only: takes a pad's suffix away (squatting, abuse); future launches of that pad carry no vanity. The
/// suffix stays held, by the registry owner: neither that pad nor any other can claim it (review C 4) until
/// `assignVanity` names the pad that may.
function revokeVanity(uint64 id) external;
/// @notice Owner only: a revoked suffix becomes claimable by pad `id` alone, through its own `setVanity` (the operator
/// opts in; nothing changes a pad's launches without it). Re-assigning replaces the designee.
function assignVanity(uint24 suffix, uint8 nibbles, uint64 id) external;
/// @notice The pad `token` launched on; reverts UnknownLaunch for a token the suite never launched (H13 GOV info).
function launchpadOf(address token) external view returns (uint64);
function isNonceUsed(uint64 id, bytes32 nonce) external view returns (bool);
function domainSeparator() external view returns (bytes32);
/// @notice The EIP-712 digest an operator's signer signs for one launch.
function hashLaunchAuthorization(uint64 id, address launcher, bytes32 pHash, bytes32 nonce, uint256 deadline)
external
view
returns (bytes32 digest);
event LaunchpadRegistered(uint64 indexed id, address indexed operator, address signer, string metadataUri);
event LaunchpadSignerSet(uint64 indexed id, address signer);
event LaunchpadVanitySet(uint64 indexed id, uint24 suffix, uint8 nibbles);
event VanityRevoked(uint64 indexed id, uint24 suffix, uint8 nibbles);
event VanityAssigned(uint64 indexed id, uint24 suffix, uint8 nibbles);
event LaunchpadVerifiedSet(uint64 indexed id, bool verified);
event LaunchpadMetadataSet(uint64 indexed id, string metadataUri);
event LaunchpadPausedSet(uint64 indexed id, bool paused);
event LaunchpadOperatorTransferStarted(uint64 indexed id, address pendingOperator);
event LaunchpadOperatorTransferred(uint64 indexed id, address operator);
/// @dev The per-pad attribution event (D6): `TokenLaunched` keeps its three indexed slots for existing decoders.
event LaunchRecorded(uint64 indexed launchpadId, address indexed token, address indexed launcher);
event RegistrationBondSet(uint256 wei_);
event MaxPadUriBytesSet(uint32 bytes_);
event BankrSignerSet(address signer);
event BondsWithdrawn(address indexed treasury, uint256 amount);
error NotFactory();
error NotOperator();
error NotPendingOperator();
error UnknownLaunchpad();
error IncorrectBond();
error ZeroAddress();
error MetadataTooLong();
error InvalidVanity();
error LaunchpadPaused();
error VanityMismatch(); // the token does not end in the pad's suffix
error VanityTaken(); // a suffix that is not prefix-free, or a token ending in another pad's suffix
error AuthorizationExpired();
error NonceUsed();
error InvalidAuthorization();
error BankrSignerUnset();
error NoAccruedBonds();
error OwnershipCannotBeRenounced();
error BondTransferFailed();
error UnknownLaunch(); // launchpadOf: a token the suite never launched
}
src/interfaces/IBnkrEpochs.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice A distributor's BNKR leg across the holder leg's BNKR swaps (founder 11-05: nothing migrates): one epoch per
/// BNKR, each claimable in its own token by the holders who earned it, forever. Apart from IHolderRewards.sol so
/// the token, factory, fee ledger and hook build byte-identical.
interface IBnkrEpochs {
/// @notice The leg named `to`: what this contract holds of `from` streams out over one last period, and again only
/// for what that period streamed while nobody was eligible.
event BnkrDraining(address indexed from, address indexed to);
/// @notice `epoch` is open: the BNKR leg streams `bnkr`, and every earlier epoch is final.
event BnkrEpochOpened(uint256 indexed epoch, address indexed bnkr);
/// @notice The open epoch never streamed, so it simply takes the leg's new BNKR (no epoch opens).
event BnkrSwitched(address indexed from, address indexed to);
event PastBnkrClaimed(address indexed account, address indexed operator, uint256 indexed epoch, uint256 amount);
error BadEpoch(); // not a closed epoch
/// @notice Follows the holder leg's BNKR (permissionless; the leg calls it before every push) and returns what an
/// incoming BNKR push is booked as now: the open epoch's token, or the next one's while the old one drains.
function syncBnkr() external returns (address intake);
/// @notice A closed epoch's rewards, in that epoch's token, to `account` (authorised as claimFor). Excluded accounts
/// keep and claim what they earned before excluding: a closed epoch can never re-stream it to anyone else.
function claimPastBnkr(address account, uint256 epoch) external returns (uint256 amount);
/// @notice The open epoch, and the token it hands over to once its drain ends (0 when steady).
function bnkrEpoch() external view returns (uint256 epoch, address next);
/// @notice A closed epoch's token, what it still owes in all, and what `account` can claim of it now.
function pastBnkr(uint256 epoch, address account)
external
view
returns (address epochToken, uint256 owed, uint256 claimable);
}
src/interfaces/ICreatorVestingEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @dev One schedule. `push` (vest-to-holders, H9a): released by anyone to its recipient (the launch's distributor) with
/// releaseFor; only the factory adds one. Otherwise a pull schedule its recipient releases with release.
struct VestingAllocation { address recipient; uint256 amount; uint64 cliff; uint64 duration; bool push; }
/// @notice Per-launch vesting escrow exposing Doppler's ABI subset (spec v4.1 R5) so le4-03's vesting reader keeps its names,
/// plus Launch v3's push schedules (spec §9).
interface ICreatorVestingEscrow {
/// @dev `start`: the launch's scheduled trading start; every schedule's clock runs from the later of it and now.
function initialize(address token, VestingAllocation[] calldata schedules, uint64 start) external;
function factory() external view returns (address);
function token() external view returns (address);
function vestingStart() external view returns (uint256);
function getScheduleIdsOf(address beneficiary) external view returns (uint256[] memory);
function vestingSchedules(uint256 scheduleId) external view returns (uint64 cliff, uint64 duration);
function vestingOf(address beneficiary, uint256 scheduleId) external view returns (uint256 totalAmount, uint256 releasedAmount);
function scheduleCount() external view returns (uint256);
function scheduleOf(uint256 scheduleId)
external
view
returns (address beneficiary, uint256 total, uint256 released, uint64 cliff, uint64 duration, bool push);
/// @notice What `beneficiary` could release now across its schedules of both kinds.
function computeAvailableVestedAmount(address beneficiary) external view returns (uint256);
/// @notice What releaseFor(beneficiary) would push now (its push schedules only).
function computePushableAmount(address beneficiary) external view returns (uint256);
function release(uint256 amount) external;
function releaseFor(address beneficiary) external returns (uint256 amount);
event Initialized(address indexed token, uint256 vestingStart, uint256 total);
event VestingReleased(address indexed beneficiary, uint256 amount);
event VestingPushed(address indexed beneficiary, address indexed caller, uint256 amount);
error NotFactory(); error AlreadyInitialized(); error NotInitialized(); error InsufficientEscrowBalance(uint256 needed, uint256 held);
error NothingVested(); error ReleaseExceedsVested(uint256 requested, uint256 available); error InvalidSchedule();
error NotPushSchedule();
}
src/interfaces/IHolderRewards.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice What a BankrLaunchToken calls on its distributor before every balance change, with the PRE-transfer balances,
/// so the distributor never calls back into the token (or anything else) from inside a transfer (spec §6, D16).
interface IHolderHook {
function onTransfer(address from, address to, uint256 value, uint256 fromBalance, uint256 toBalance) external;
}
/// @notice The chain's BNKR as its holder leg (BnkrHolderLeg, H17) names it; 0 until BNKR is set there.
interface IBnkrSource {
function bnkr() external view returns (address);
function minPile(address quote) external view returns (uint96);
function pending(bytes32 poolId) external view returns (uint256);
function poke(bytes32 poolId) external;
}
/// @notice Hold-to-earn distributor of one launch (spec §6): holders earn by holding, pro rata to their wallet balance, on
/// three legs that share one eligible supply: the launch token (vest-to-holders, donations), the pool's quote (the
/// creator's holder share, accrued in every swap; Bankr's 5 % where it is paid in quote) and BNKR. No owner, no
/// staking, no keeper (decision 1).
interface IHolderRewardsDistributor is IHolderHook {
/// @dev `amount`: what the notify added to the leg's stream (its floored rate's remainder is carried, not counted).
event RewardsNotified(uint8 indexed leg, uint256 amount, uint256 rewardRate, uint256 periodFinish);
event RewardClaimed(address indexed account, address indexed operator, uint256[3] amounts);
event RewardExcluded(address indexed account, uint256[3] forfeited);
event FeesPulled(uint256 amount);
event VestPushed(uint256 amount);
event BnkrLegEnabled(address indexed bnkr);
error NotToken();
error NotSelf();
error ExcludedAccount();
error NothingToClaim();
error PayoutRefused(); // every owed leg's asset refused its payout (H13 TOKEN-4); the rewards stay claimable
/// @dev claimFor or claimPastBnkr for an account whose ledger claim policy (Q9) refuses the caller.
error ClaimerNotAllowed();
error BadLeg();
error ZeroAddress();
/// @dev accrue from anyone but the fee ledger.
error NotLedger();
/// @dev onLegPush from anyone but the chain's holder leg.
error NotHolderLeg();
/// @dev openVest from anyone but the factory.
error NotFactory();
/// @dev openVest on a launch without a vest-to-holders slice, or a second time.
error VestOpen();
/// @dev A capped call could not be handed its whole cap (a lazy pull, reconcile's BNKR leg, a full claim's payout),
/// or a claimForMany element started under MIN_GAS_PER_CLAIM or ran out of gas.
error InsufficientGas();
/// @dev A hard bound of the design's section 2, by number. At construction: 7, a stream of 0 seconds or an
/// activation divisor under 10,000 (TOKEN) or 10,000,000 (BNKR); 4, a restart share outside 1 to 10,000 bps;
/// 21, a QUOTE floor past 112 bits. In openVest: 5, a vest stream ending past the 40-bit clocks.
error HardBound(uint8 bound);
/// @notice The fee ledger only, inside every swap that credits this coin's creator holder share (decision 1):
/// storage only. `bufferOnly` for a nested swap, which only buffers.
function accrue(uint256 h, bool bufferOnly) external;
/// @notice The holder leg only, after each push (decisions 1-2 seam): a forward's `quoteIn` joins the QUOTE buffer; 0
/// streams the BNKR it pushed. Storage and capped reads only; a no-op inside this distributor's own call.
function onLegPush(uint256 quoteIn) external;
/// @notice The factory only, once, at a launch with a vest-to-holders slice: the TOKEN leg's stream from the cliff.
function openVest(uint256 total, uint64 cliff, uint64 duration) external;
/// @notice Permissionless backstop: pulls the creator's holder share from the ledger, then streams each leg's surplus
/// (QUOTE with its buffer; TOKEN once the vest stream has ended; BNKR). Never reverts for a missing feature
/// (I12). Needs 1,030,873 gas left at its BNKR leg or reverts InsufficientGas.
function reconcile() external returns (uint256 pulled, uint256[3] memory notified);
/// @notice QUOTE taken in and not streaming yet: under the activation floor, under one wei a second while a period
/// is open, or the remainder a fold's floored rate left.
function pendingQuote() external view returns (uint256);
/// @notice Every leg: pulls the creator's holder share from the ledger first when the QUOTE balance cannot pay it,
/// and releases the vest from the escrow when the TOKEN balance cannot.
/// @notice Pays every leg first; then, with the gas the payouts left (POKE_GAS and its gate), pokes the holder leg for
/// this coin's pile when it is due (decision 2's claim retry). Reverts NothingToClaim only when it neither
/// paid nor poked.
function claim() external returns (uint256[3] memory amounts);
/// @notice One leg only, its asset handed all the gas: the escape hatch for an asset whose honest transfer needs
/// more than the 1,000,000 a full claim hands each payout. An asset that refuses reverts PayoutRefused
/// here; claim() pays the other legs and keeps it.
function claimLeg(uint8 leg) external returns (uint256 amount);
/// @notice Pays `account`, never the caller, under the ledger's one claim policy (Q9, mayClaimFor): anyone while
/// the account is open (the default), else only the account or a claim operator it named there.
function claimFor(address account) external returns (uint256[3] memory amounts);
/// @notice claimFor for each account, skipping any the policy refuses the caller.
function claimForMany(address[] calldata accounts) external returns (uint256 paid);
function claimForAuthorized(address account) external returns (uint256[3] memory amounts);
/// @notice One-way: the caller stops earning and forfeits what it accrued to everyone else (a contract that can
/// never claim, such as another launch's distributor holding this token as its quote).
function excludeSelf() external;
function token() external view returns (address);
function quote() external view returns (address);
function bnkr() external view returns (address);
function poolId() external view returns (bytes32);
function escrow() external view returns (address);
function hasHolderVest() external view returns (bool);
function eligibleSupply() external view returns (uint256);
function rewardExcluded(address account) external view returns (bool);
function assetOf(uint8 leg) external view returns (address);
function earned(uint8 leg, address account) external view returns (uint256);
function surplus(uint8 leg) external view returns (uint256);
/// @notice What a leg's first notify must reach before it goes live (review C finding 7).
function activationFloor(uint8 leg) external view returns (uint256);
function rewardsOwed(uint8 leg) external view returns (uint256);
function remainingStream(uint8 leg) external view returns (uint256);
function streamOf(uint8 leg)
external
view
returns (
bool streams,
uint256 periodFinish,
uint256 rewardRate,
uint256 rewardPerTokenStored,
uint256 rewardsAllocated,
uint256 rewardsClaimed
);
function rewardsOf(uint8 leg, address account) external view returns (uint256 settled, uint256 paidCheckpoint);
}
/// @notice Deploys one HolderRewardsDistributor for a token the factory is about to create at `token`, before the token
/// (its constructor binds the distributor as its reward hook), and records it by pool and by token.
interface IHolderRewardsDeployer {
/// @dev Factory only; CREATE2 with salt bytes32(uint256(uint160(token))). `escrow` is the launch's predicted vesting
/// escrow, excluded from rewards whether or not anything vests; `holderVest` says it holds a vest-to-holders
/// schedule for the distributor to push. `holderLeg` and `terms` are the coin's for life (see launchingTerms).
function deploy(
address token,
bytes32 poolId,
address quote,
address escrow,
bool holderVest,
address holderLeg,
uint256 terms
) external returns (address distributor);
/// @notice The terms word of the distributor being constructed right now (transient, so `predict` ignores it):
/// streamSecs | restartBps << 32 | tokenDivisor << 48 | bnkrDivisor << 80 | quoteActivation << 112.
function launchingTerms() external view returns (uint256);
/// @notice Its holder leg, handed over the same way.
function launchingLeg() external view returns (address);
function predict(address token, bytes32 poolId, address quote, address escrow, bool holderVest)
external
view
returns (address);
function distributorOf(bytes32 poolId) external view returns (address);
function distributorOfToken(address token) external view returns (address);
}
src/libraries/BucketIds.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// Ledger bucket ids (spec v4.1 bucket table). The TypeScript mirror (le4-02 `bucketIds.ts`)
/// hashes the same raw concat via viem's encodePacked.
library BucketIds {
function creatorId(bytes32 poolId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(poolId, "creator"));
}
/// @dev The coin's holders' half of Bankr's slice (H4), sole beneficiary the chain's BNKR holder leg.
function holdersId(bytes32 poolId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(poolId, "holders"));
}
/// @dev The decay surplus above the steady rate, registered only when the launch's pad has a decay split (H4).
function decayId(bytes32 poolId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(poolId, "decay"));
}
/// @dev One bucket per quote currency per chain: Bankr's own half of every pool's slice and its cut of every extension
/// fee, sole beneficiary the treasury.
function bankrId(address quote) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(quote, "bankr"));
}
}
src/libraries/FeeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {LaunchConstants as K} from "./LaunchConstants.sol";
/// @dev One direction's fee schedule (Launch SDK H3): `startPips` falling linearly to `steadyPips` over `decaySecs` from
/// pool init, bound once at launch. A 0 s decay is flat at the steady rate.
struct FeeSchedule {
uint24 startPips;
uint24 steadyPips;
uint32 decaySecs;
}
/// @dev One direction of a pool as the hook stores it, one slot: the schedule and the pool's compound floor (the same
/// figure in both directions), so the swap's one read of its schedule brings the floor with it.
struct PoolSide {
uint24 startPips;
uint24 steadyPips;
uint32 decaySecs;
uint128 compoundFloor;
}
/// @dev One swap fee's legs (Launch SDK H4): the coin's holders, Bankr's own half, the referrer, then the remainder's
/// steady part (the creator bucket) and decay surplus (the decay bucket). They sum to the fee exactly.
struct SwapSplit {
uint256 holders;
uint256 bankr;
uint256 referral;
uint256 steady;
uint256 decay;
}
/// Per-launch fee schedule, Bankr's slice and the per-swap split (Launch SDK H3/H4), four-shape fee sizing.
library FeeMath {
/// @dev f(t) = t >= d ? s : a − (a − s)·t / d, the drop rounded down so the fee never undershoots the line.
/// `nowTs >= initTimestamp`: the hook refuses a swap before the trading start, and views clamp (HookState).
function feePipsAt(FeeSchedule memory s, uint256 initTimestamp, uint256 nowTs) internal pure returns (uint24) {
uint256 elapsed = nowTs - initTimestamp;
if (elapsed >= s.decaySecs) return s.steadyPips;
uint256 drop = uint256(s.startPips - s.steadyPips) * elapsed / s.decaySecs;
// casting to 'uint24' is safe because drop <= startPips - steadyPips
// forge-lint: disable-next-line(unsafe-typecast)
return uint24(s.startPips - drop);
}
/// @dev feePipsAt on a pool's stored side: the same line, read from the hook's own slot.
function sideFeeAt(PoolSide memory s, uint256 initTimestamp, uint256 nowTs) internal pure returns (uint24) {
uint256 elapsed = nowTs - initTimestamp;
if (elapsed >= s.decaySecs) return s.steadyPips;
uint256 drop = uint256(s.startPips - s.steadyPips) * elapsed / s.decaySecs;
// casting to 'uint24' is safe because drop <= startPips - steadyPips
// forge-lint: disable-next-line(unsafe-typecast)
return uint24(s.startPips - drop);
}
/// @dev Bankr's slice of fee F charged at f pips (D1): max(⌈F·feeBps/1e4⌉, ⌈F·minPips/f⌉), each term rounded up on
/// its own. The second is `minPips` of the basis F was sized on. Both numbers are the pool's own, frozen at
/// launch (suite 3: 1,000 and 250); the ledger holds them to what the pool's lowest fee can carry.
function bankrSlice(uint256 fee, uint24 feePips, uint256 feeBps, uint256 minPips)
internal
pure
returns (uint256 b)
{
if (fee == 0) return 0;
b = FullMath.mulDivRoundingUp(fee, feeBps, 10_000);
uint256 floor_ = FullMath.mulDivRoundingUp(fee, minPips, feePips);
if (floor_ > b) b = floor_;
}
// PoolTerms slot 0 as the ledger stores it: hook 160 | flags 8 | referrerBps 16 | bankrFeeBps 16 | bankrMinPips 24
// | holdersShareBps 16 | legId 16. BankrFeeLedger.layout.t.sol holds the shifts to the struct.
uint8 internal constant T_QUOTE_IS_0 = 1;
uint8 internal constant T_WAIVED = 2;
uint8 internal constant T_DECAY_SPLIT = 4;
uint8 internal constant T_TREASURY_CUT = 8;
uint8 internal constant T_HOLDER_INTAKE = 16;
uint256 internal constant T_FLAGS_SHIFT = 160;
uint256 internal constant T_REFERRER_SHIFT = 168;
uint256 internal constant T_BANKR_FEE_SHIFT = 184;
uint256 internal constant T_BANKR_MIN_SHIFT = 200;
uint256 internal constant T_HOLDERS_SHARE_SHIFT = 224;
uint256 internal constant T_LEG_SHIFT = 240;
/// @dev Spec §3, fee F at rate f, steady rate s, terms word `w` (PoolTerms slot 0): B = bankrSlice, the holders
/// ⌊B·holdersShareBps/1e4⌋, Bankr the rest of B (0 when waived, FD-25), a named referrer ⌊F·referrerBps/1e4⌋,
/// the remainder M ⌊M·s/f⌋ steady / the rest decay (decay split, f > s). Rounding favours Bankr; the sum is F.
function swapSplit(uint256 fee, uint24 f, uint24 s, uint256 w, bool named)
internal
pure
returns (SwapSplit memory x)
{
// forge-lint: disable-next-line(unsafe-typecast)
uint256 b = bankrSlice(fee, f, uint16(w >> T_BANKR_FEE_SHIFT), uint24(w >> T_BANKR_MIN_SHIFT));
// At 5,000 this is suite 3's ⌊B/2⌋. In a fee that splits the product is at most 10,000 times the fee, and a
// fee is a v4 amount (under 2^127): it cannot overflow there.
// forge-lint: disable-next-line(unsafe-typecast)
x.holders = b * uint16(w >> T_HOLDERS_SHARE_SHIFT) / 10_000;
if (w >> T_FLAGS_SHIFT & T_WAIVED == 0) x.bankr = b - x.holders;
// forge-lint: disable-next-line(unsafe-typecast)
if (named) x.referral = FullMath.mulDiv(fee, uint16(w >> T_REFERRER_SHIFT), 10_000);
uint256 m = fee - x.holders - x.bankr - x.referral;
x.steady = w >> T_FLAGS_SHIFT & T_DECAY_SPLIT != 0 && f > s ? FullMath.mulDiv(m, s, f) : m;
x.decay = m - x.steady;
}
/// @dev A pad that names the treasury marker: its WAD shares of the steady part and the decay surplus move into Bankr's leg, each
/// rounded up, so its claim is never under its share; the rest of each part stays for the other payees. The decay
/// cut takes one wei more, at most the whole part (review C finding 3): B rounding up shrinks M by under a wei of
/// which K gets only half, and at v2's 29/48 of the surplus that left the treasury up to ~0.1 wei short.
function treasuryCut(SwapSplit memory x, uint256 steadyWad, uint256 decayWad) internal pure {
uint256 a = FullMath.mulDivRoundingUp(x.steady, steadyWad, 1e18);
uint256 b;
if (decayWad != 0 && x.decay != 0) {
b = FullMath.mulDivRoundingUp(x.decay, decayWad, 1e18) + 1;
if (b > x.decay) b = x.decay;
}
x.steady -= a;
x.decay -= b;
x.bankr += a + b;
}
/// @dev Fee on the gross quote leg for the four swap shapes (spec §2), every one rounded up (H13 ECON-1: an exact-in
/// sell's too, so Bankr's legs never trail the volume ruling; the hook caps the pair at the output). Exact-out
/// shapes are grossed up r / (1 − r − o): the pool amount is the net the trader asked for, and `otherPips` the
/// swap's other fee (Bankr's for the extension's, the extension's for Bankr's), so each is sized on the whole
/// gross the trader pays, as on the exact-in shapes (H13 AMM-I2).
function feeFor(uint256 quoteAmount, uint24 feePips, uint24 otherPips, bool exactOut)
internal
pure
returns (uint256)
{
if (exactOut) return FullMath.mulDivRoundingUp(quoteAmount, feePips, K.PIPS - feePips - otherPips);
return FullMath.mulDivRoundingUp(quoteAmount, feePips, K.PIPS);
}
/// @dev A swap with no other fee (a pool without an extension). The quote's side no longer changes the rounding.
function feeFor(uint256 quoteAmount, uint24 feePips, bool exactOut, bool) internal pure returns (uint256) {
return feeFor(quoteAmount, feePips, 0, exactOut);
}
/// @dev Q4-C: Bankr takes num/den of every extension fee, rounded up; the payee the rest. No holders' part (D6).
/// Suite 3: 2/7 (28.57 %).
function extensionBankrCut(uint256 extFee, uint256 num, uint256 den) internal pure returns (uint256) {
return FullMath.mulDivRoundingUp(extFee, num, den);
}
}
src/libraries/LaunchConstants.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// What the launch suite compiles in (suite 4 design 3.1): units, pool plumbing, labels and the gas budgets sized to
/// the code. Every product figure is a setting of the settings contract, frozen per coin at its launch; suite 3's
/// figures, which this file held, are the defaults a chain's config names (config/<chain>.json, `.settings`).
library LaunchConstants {
uint24 internal constant PIPS = 1_000_000;
// The treasury as a pad payee: a marker, never an account. A launch cuts its shares into the quote's bankrId
// bucket, whose beneficiary is the treasury and moves with it (review B finding 4).
address internal constant PAD_TREASURY = address(uint160(uint256(keccak256("bankr.launch.pad-payee.treasury"))));
int24 internal constant TICK_SPACING = 200;
int24 internal constant MAX_USABLE_TICK = 887_200;
int24 internal constant MIN_USABLE_TICK = -887_200;
// At or above this pool tick both sides of any compound band (a spacing or more each way) are worth at least 1 to
// the hook's arithmetic, so LaunchPool asks the hook for a pool's band only below it (B12 at the start price).
int24 internal constant COMPOUND_VALUED_TICK = -600_000;
// A quote's raw supply ceiling (H13 TOKEN-3): a reward leg streaming more than ~1.16e41 wei per second per wei of
// eligible supply overflows the 1e36-precision accumulator inside every transfer; every listed quote is under 1e29.
uint256 internal constant MAX_QUOTE_SUPPLY = 1e36;
// The in-swap compound's gas cap: forwarded whole when the swap has it, else what is left, and a short compound that
// fails reverts the swap (audit r1 ADM-02). A pool's first compound uses ~476k, ~492k on id 0 (two buckets pulled).
uint32 internal constant COMPOUND_GAS_STIPEND = 600_000;
uint32 internal constant SIDE_EFFECT_GAS_TAIL = 20_000; // what afterSwap still needs after an in-swap side effect returns (audit L-4)
// Decision 3: a buyback pool's fill runs last in an outer swap, at most once per interval, handed exactly the stipend
// and only with the reserve free past it (the tail, the route's settlement, three reward legs going live), so a fill
// no estimate carried never starves what the estimate paid for; short, it is skipped. A refused fill retries sooner.
// D3-T6, audit F-09: a first fill across a tick after a donation, its trigger a sell that pays no fee and the pool's
// protocol fee on, every access cold: ~388k at worst (a pool with no auto-LP share)
uint32 internal constant BUYBACK_GAS_STIPEND = 460_000;
uint32 internal constant BUYBACK_GAS_RESERVE = 320_000;
uint256 internal constant BUYBACK_GAS_NEED = uint256(BUYBACK_GAS_STIPEND) * 64 / 63 + BUYBACK_GAS_RESERVE;
// Extension slot (plan "In-swap calls revision"): the fee ceiling each way and the quote's STATICCALL budget. An
// extension is asked from the first swap and fills only the room under the coin's fee ceiling: nothing while
// Bankr's decaying fee is at or above it, so a binding above the ceiling could never charge (Launch SDK H3).
uint24 internal constant EXT_CEILING_PIPS = 100_000;
// A launch names its two gas budgets in its binding, for life: these are the floors (and a preset's budgets), the
// _MAX the hard ceilings. Every swap of the pool carries the whole of both, so the ceilings bound every route.
uint32 internal constant EXT_QUOTE_GAS = 50_000;
uint32 internal constant EXT_QUOTE_GAS_MAX = 250_000;
uint32 internal constant EXT_AFTER_GAS_MAX = 1_000_000;
// The guarded post-swap CALL's floor (G_A, sized for an own-pool buyback), the guard frame's own snapshot / compare
// overhead around the call (plus 1/63 of what a binding adds over the floor), and the extra per router-pinned route
// currency. Constants: no setter can loosen the guard.
uint32 internal constant EXT_AFTER_GAS = 150_000;
uint32 internal constant EXT_FRAME_GAS = 40_000;
uint32 internal constant EXT_PIN_GAS = 1_000;
// Kept free past the tail at an extension pool's last gas check, framed or not, for the PoolManager's tail and the
// route's settlement after the hook: the heaviest fork-measured settlement (Universal Router, 69,023) with room for a
// cold Permit2 pull or an unwrap. An extension cannot then take what a wallet's estimate paid it for (audit r3 EXT-2).
uint32 internal constant EXT_ROUTE_RESERVE = 80_000;
// Ceiling on the work a quote's answer decides in afterSwap: the extension fee's two legs, cold, with the payee's
// claims and the treasury bucket going zero to nonzero. The check keeps what a swap did not spend of it free, so a
// fee charged only on inclusion cannot take what the estimate paid for (audit r4 EXT-1).
uint32 internal constant EXT_SETTLE_GAS = 75_000;
// Kept free on top while Bankr's own fee leaves the extension no room under 10 % (the first seconds of a decay), for
// what the launch second saves (no reference fold, 4,692 cold) and the fee turning on adds outside its measured
// legs: a second-0 estimate then lands once there is room (r5 ADM-1; test/design/AlwaysOn.t.sol under --isolate).
uint32 internal constant EXT_ROOM_RESERVE = 6_000;
// Kept free while the extension has room and charges nothing, for the integer rounding of the slack's 63/64 across
// the call frames (2 measured either way): an exact-in sell estimated at 0 pips lands once it charges, and one
// estimated charging lands at 0 pips with about this much more. Other shapes: README, "From the first swap".
uint32 internal constant EXT_IDLE_RESERVE = 16;
// Gas a sponsor, router or wallet adds to a swap's simulated limit for EACH Bankr pool on the route (audits r2 ADM-1,
// r3 ADM-3): a compound, quote or post-swap call can come due before inclusion on any hop, and short of its whole
// stipend a swap reverts. Each covers its stipends (x 64/63, tail, route and settle reserves) through six frames, and
// the token's transfer hook with all three reward legs gone live in the same window: measured end to end on id 0, a
// first compound pulling both buckets with the coin's three legs going live needs +828,273 cold (H13 AMM-2), and a
// creator holder share's accrue can go from buffer-only to a first join (+55,217): 883,490, 8.0 % under 960,000.
uint32 internal constant SWAP_GAS_HEADROOM = 960_000;
// What the extension path spends before its last gas check and no budget or reserve counts: the hook data's
// parse, the frame's calldata with the longest extData, and per pinned currency its copies. BankrHookLens adds
// them (six frames, a swap that settles nothing, --isolate: 3,430 for 2,048 bytes, 1,000 a pin; test/ns18 EXT-2).
uint32 internal constant EXT_PATH_GAS = 10_000;
uint32 internal constant EXT_PATH_PIN_GAS = 1_200;
// On top, per extension pool at the floor budgets (499,879; +2,440 per pin). A pool with larger budgets needs
// BankrHookLens.extSwapGasHeadroom: the same sum with the binding's quoteGas and afterGas.
uint32 internal constant EXT_SWAP_GAS_HEADROOM = 500_000;
// Decision 2: what the ledger hands the holder leg's in-swap wake, exactly. Only a sender that asks runs it
// (HookData.HOLDERS_WAKE), so no other swap's outcome depends on it. Sized ~1.2x a full batch of 8 first-time
// distributors draining over two hops, cold (~1.64M; round 9 raised it from 1.6M: only a capped batch fitted).
uint32 internal constant HOLDERS_WAKE_GAS = 2_000_000;
// The tail: the compound's stipend and tail and the extension frame with its _extNeed at both budget ceilings and 16
// pins (2,143,084), three reward legs going live (220k), the compound's reads (48k) and the fill last (480k):
// 2,891,084, 1.7 % under it. _extNeed is kept, not spent: in order the tail has 340,207 to spare (AlwaysOnWakeTail).
uint32 internal constant HOLDERS_WAKE_TAIL = 2_940_000;
address internal constant DEAD = 0x000000000000000000000000000000000000dEaD; // TOKEN burns: the locker's launch dust and BankrBuyback's fills; no BNKR ever goes here
uint160 internal constant HOOK_PERMISSION_MASK = 0x38CC;
uint24 internal constant DYNAMIC_FEE = 0x800000;
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
"v4-core/=lib/v4-periphery/lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"v4-periphery/=lib/v4-periphery/",
"v4-hooks-public/=lib/v4-hooks-public/",
"permit2/=lib/permit2/",
"solady/=lib/solady/",
"solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
"openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"@openzeppelin/=lib/openzeppelin-contracts/",
"forge-std/=lib/forge-std/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.