Verified contractPartialMIT
Favus
Address0x33ca3f8d225faa35109e18d4312395bfdb315e96
- Balance
0 ETH
- Transactions
165
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 1,000,000 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,429,842
- Creation transaction
- 0x5d639fb156…1ef3c98ed2
3 files
- src/Favus.solmain19.96 KB
- lib/solady/src/utils/FixedPointMathLib.sol55.65 KB
- src/lib/HoneyMath.sol5.62 KB
src/Favus.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import {HoneyMath} from "./lib/HoneyMath.sol";
// FAVUS — the honeycomb.
// Site: https://favus.fun · X: https://x.com/FavusFun · TG: (see SITE / X / TG below)
//
// Buyers build the walls, sellers feed the veterans.
// This contract is the token and the veterans' honey. It has no owner, no admin, no setter, no pause,
// no upgrade path and no mint after construction. Nothing here can be changed by anyone, ever.
/// @title Favus ($FAVUS) — ERC-20 with Veterans' honey
/// @notice A fixed-supply ERC-20 whose balances grow on their own. $FAVUS fed into the honey pot
/// (`feedHoney`, in practice the sell tax taken by the pool hook) is shared between holders in
/// proportion to `balance x ripeness`, where ripeness is `1 - 2^(-age / 7 days)`.
///
/// - `balanceOf` = settled balance + honey accrued since the account was last touched. Nobody claims.
/// - Sending tokens out (transfer, burn, feedHoney) settles your honey and makes the rest of your
/// bag a recruit again (age 0). Receiving never resets you: every lot you receive ripens on its own.
/// - Accounts with contract code earn nothing (EIP-7702 delegated EOAs do earn). So do 0xdEaD and 0x0.
///
/// @dev O(1) accounting, no loops over holders. Full derivation and the rounding argument:
/// favus/docs/honey-math.md. Reference model: contracts/model/honey_model.py.
///
/// Per holder: b_i (settled balance) and d_i = sum over lots of lot * 2^(start / 7d).
/// Weight w_i(t) = b_i - 2^(-t/7d) * d_i. Totals B = sum b_i, D = sum d_i, W = B - 2^(-t/7d) * D.
/// A drop `a` at time t adds A0 += a / W and A2 += a * 2^(-t/7d) / W.
/// Honey owed to a holder since its snapshot = b_i * dA0 - d_i * dA2.
///
/// 2^(t/7d) grows without bound, so time is cut into frames of 64 weeks and every d / A2 increment
/// is stored relative to the start of its frame (so 2^x < 2^64 inside a frame). A2 is the plain sum
/// of frame-relative increments; `_a2AtFrameStart` lets a holder split dA2 by frame.
///
/// Every rounding goes against the holder: d_i up, D down (so W up), a/W down, A2 increments up,
/// the deduction up, the credit down. On top of that `_owed` hard-caps credits at what was allocated.
contract Favus {
using FixedPointMathLib for uint256;
// ------------------------------------------------------------------ constants
string public constant name = "Favus";
string public constant symbol = "FAVUS";
uint8 public constant decimals = 18;
/// @notice Project links. They are part of the bytecode. X and TG are filled in by the operator as
/// the last source edit before deployment (then the hook salt is mined again).
string public constant SITE = "https://favus.fun";
string public constant X = "https://x.com/FavusFun";
string public constant TG = "";
uint256 internal constant SUPPLY = 1_000_000_000e18;
address internal constant DEAD = 0x000000000000000000000000000000000000dEaD;
/// @dev One frame = 64 half-lives. Inside a frame 2^(x) < 2^64.
uint256 internal constant EPOCH = 64 * 7 days;
/// @dev Fractional bits carried by d_i and D (unripe mass in wei * 2^32).
uint256 internal constant F = 32;
/// @dev A0 is Q128; A2 is Q192.
uint256 internal constant Q0 = 1 << 128;
/// @dev Divisor for d (Q32) * dA2 (Q192).
uint256 internal constant QD = 1 << 224;
/// @dev Below one whole ripe token of total weight a drop is carried forward, not distributed.
uint256 internal constant MIN_W = 1e18;
/// @notice Timestamp of deployment. Ripening and frames are measured from here.
uint256 public immutable LAUNCH_TS;
// ------------------------------------------------------------------ storage
struct Account {
uint128 bal; // settled balance
uint120 honey; // lifetime honey credited (saturating; informational)
bool excluded; // permanently outside the hive
uint192 d; // sum lot * 2^(start/7d), relative to the start of frame `epoch`, Q32, rounded up
uint32 epoch; // frame of the snapshot below
uint256 a0; // A0 at the last settle
uint256 a2; // A2 at the last settle
}
mapping(address => Account) internal _acct;
mapping(address => mapping(address => uint256)) public allowance;
uint256 public totalSupply;
uint128 internal _eligible; // B: sum of settled balances of non-excluded accounts
uint32 internal _epoch; // current frame
uint256 internal _unripe; // D: lower bound of sum d_i, relative to the start of `_epoch`, Q32
uint256 internal _a0; // sum a / W, Q128, rounded down
uint256 internal _a2; // sum a * 2^(-(t - frameStart)/7d) / W, Q192, rounded up
mapping(uint256 => uint256) internal _a2AtFrameStart;
uint128 internal _fed; // all honey ever fed (including what is still pending)
uint128 internal _pending; // fed but not yet distributed (no ripe weight at the time)
uint128 internal _paid; // all honey ever credited to balances
uint128 internal _owed; // distributed but not yet credited: the hard cap on credits
// ------------------------------------------------------------------ events / errors
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @param W total ripe weight (wei) the drop was measured against.
event HoneyFed(address indexed from, uint256 amount, uint256 W);
/// @param amount honey now waiting for the next drop (total ripe weight was under one token).
event HoneyCarried(uint256 amount);
event Excluded(address indexed account);
error ZeroAddress();
error InsufficientBalance();
error InsufficientAllowance();
/// @dev Position inside the current frame, computed once per call.
struct Clock {
uint256 cur; // frame index
uint256 dt; // seconds since the frame started (< EPOCH)
}
// ------------------------------------------------------------------ construction
/// @param recipient receives the whole fixed supply (the launcher, which seeds the pool with it).
constructor(address recipient) {
if (recipient == address(0)) revert ZeroAddress();
LAUNCH_TS = block.timestamp;
totalSupply = SUPPLY;
Clock memory c = Clock(0, 0);
bool eligible = _touch(recipient, c);
_credit(recipient, SUPPLY, eligible, c);
emit Transfer(address(0), recipient, SUPPLY);
}
// ------------------------------------------------------------------ ERC-20
/// @notice Settled balance plus honey accrued since the account was last touched.
function balanceOf(address account) public view returns (uint256) {
Account storage h = _acct[account];
if (h.excluded) return h.bal;
(uint256 honey,) = _accrued(h, _frameNow());
return h.bal + honey;
}
function approve(address spender, uint256 amount) external returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) external returns (bool) {
_transfer(msg.sender, to, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount) external returns (bool) {
uint256 allowed = allowance[from][msg.sender];
if (allowed != type(uint256).max) {
if (allowed < amount) revert InsufficientAllowance();
unchecked {
allowance[from][msg.sender] = allowed - amount;
}
}
_transfer(from, to, amount);
return true;
}
/// @notice Destroy `amount` of your own tokens. The only way supply ever changes.
function burn(uint256 amount) external {
Clock memory c = _roll();
bool eligible = _touch(msg.sender, c);
if (amount != 0) {
_debit(msg.sender, amount, eligible, c);
unchecked {
totalSupply -= amount; // amount <= balance <= totalSupply
}
}
emit Transfer(msg.sender, address(0), amount);
}
// ------------------------------------------------------------------ honey
/// @notice Give `amount` of your own $FAVUS to the veterans. Anyone can call it; the pool hook calls it
/// with the sell tax. The honey (plus anything carried from earlier) is shared by ripe weight
/// as of this moment. If total ripe weight is under one token it is carried to the next drop.
/// `feedHoney(0)` just retries a carried drop.
function feedHoney(uint256 amount) external {
Clock memory c = _roll();
bool eligible = _touch(msg.sender, c);
if (amount != 0) {
_debit(msg.sender, amount, eligible, c);
_fed += uint128(amount); // checked add; amount <= balance < 2^128
emit Transfer(msg.sender, address(this), amount);
}
uint256 total = uint256(_pending) + amount;
if (total == 0) return;
uint256 pd = HoneyMath.powFracDown(c.dt % HoneyMath.HALF_LIFE);
uint256 n = c.dt / HoneyMath.HALF_LIFE; // < 64
// W = B - 2^(-x) D, in Q32 wei. D is a lower bound and it is decayed downwards, so W is an upper bound.
uint256 w = (uint256(_eligible) << F).zeroFloorSub(_unripe.fullMulDiv(pd, HoneyMath.ONE) >> n);
emit HoneyFed(msg.sender, amount, w >> F);
if (w >= MIN_W << F) {
uint256 c0 = total.fullMulDiv(1 << (128 + F), w); // a / W, rounded down
// a * 2^(-x) / W in Q192, rounded up (and using the upper bound of the power)
uint256 inc = (c0 << 64).fullMulDivUp(pd + HoneyMath.POW_ERR, HoneyMath.ONE << n);
uint256 a2 = _a2;
if (inc <= type(uint256).max - a2) {
_a0 += c0;
_a2 = a2 + inc;
_owed += uint128(total);
_pending = 0;
return;
}
// A2 is full. Not reachable (needs sum a/W >= 2^64); if it ever were, honey is carried and
// transfers keep working instead of reverting.
}
_pending = uint128(total);
emit HoneyCarried(total);
}
/// @notice Ripe share of an account's settled balance. 1e18 = fully ripe, 0.5e18 after one week.
function ripeness(address account) external view returns (uint256) {
Account storage h = _acct[account];
uint256 bal = h.bal;
if (bal == 0 || isExcluded(account)) return 0;
uint256 elapsed = block.timestamp - LAUNCH_TS;
uint256 cur = elapsed / EPOCH;
uint256 d = HoneyMath.ceilShr(h.d, 64 * (cur - h.epoch));
uint256 unripe = HoneyMath.decayUp(d, elapsed - cur * EPOCH);
bal <<= F;
return unripe >= bal ? 0 : ((bal - unripe) * 1e18) / bal;
}
/// @notice Lifetime honey credited to an account's settled balance (excludes honey not yet settled).
function honeyOf(address account) external view returns (uint256) {
return _acct[account].honey;
}
/// @notice All $FAVUS ever fed to the honey pot.
function totalHoneyFed() external view returns (uint256) {
return _fed;
}
/// @notice All honey credited to balances so far. Never more than `totalHoneyFed`.
function totalHoneyPaid() external view returns (uint256) {
return _paid;
}
/// @notice Honey fed while there was no ripe weight, waiting for the next drop.
function pendingHoney() external view returns (uint256) {
return _pending;
}
/// @notice True if the account earns no honey: it holds contract code (other than an EIP-7702
/// delegation), or is 0xdEaD / 0x0, or was ever seen in that state. Exclusion is permanent.
/// @dev An account that only just gained code reads true here, but its weight leaves the hive at its
/// next touch (any transfer to or from it, even of 0 tokens, by anyone).
function isExcluded(address account) public view returns (bool) {
return _acct[account].excluded || _hasForeignCode(account);
}
// ------------------------------------------------------------------ internals: transfers
function _transfer(address from, address to, uint256 amount) internal {
if (to == address(0)) revert ZeroAddress();
Clock memory c = _roll();
// settle the sender, then the receiver, then move the tokens
bool fromEligible = _touch(from, c);
bool toEligible = to == from ? fromEligible : _touch(to, c);
if (amount != 0) {
// a zero-amount transfer settles but must never reset anyone's age:
// transferFrom(victim, x, 0) needs no allowance
_debit(from, amount, fromEligible, c);
_credit(to, amount, toEligible, c);
}
emit Transfer(from, to, amount);
}
/// @dev Take `amount` out of `from`. For an eligible account everything left becomes one fresh lot.
function _debit(address from, uint256 amount, bool eligible, Clock memory c) internal {
Account storage h = _acct[from];
uint256 bal = h.bal;
if (bal < amount) revert InsufficientBalance();
unchecked {
bal -= amount;
}
h.bal = uint128(bal);
if (eligible) {
// remove the old lots exactly as stored (d_i is an upper bound, so D stays a lower bound)
uint256 unripe = _unripe.zeroFloorSub(h.d);
(uint256 down, uint256 up) = HoneyMath.grow(bal << F, c.dt);
h.d = uint192(up);
_unripe = unripe + down;
unchecked {
_eligible -= uint128(amount); // B >= bal >= amount
}
}
}
/// @dev Add `amount` to `to` as a new lot starting now.
function _credit(address to, uint256 amount, bool eligible, Clock memory c) internal {
Account storage h = _acct[to];
unchecked {
h.bal += uint128(amount); // sum of balances <= totalSupply < 2^128
}
if (eligible) {
(uint256 down, uint256 up) = HoneyMath.grow(amount << F, c.dt);
h.d = uint192(h.d + up); // <= bal * 2^96 * (1 + 2^-120) + lots: far below 2^192
_unripe += down;
unchecked {
_eligible += uint128(amount);
}
}
}
// ------------------------------------------------------------------ internals: honey
function _frameNow() internal view returns (uint256) {
return (block.timestamp - LAUNCH_TS) / EPOCH;
}
/// @dev Move the global state into the current frame. Runs first in every state-changing entry point.
function _roll() internal returns (Clock memory c) {
uint256 elapsed = block.timestamp - LAUNCH_TS;
c.cur = elapsed / EPOCH;
c.dt = elapsed - c.cur * EPOCH;
uint256 e = _epoch;
if (c.cur > e) {
// Nothing happened between the last touch and now, so A2 at the start of the next two frames
// is today's A2. Holders last seen in frame `e` need exactly these two values (see _accrued).
uint256 a2 = _a2;
_a2AtFrameStart[e + 1] = a2;
if (c.cur > e + 1) _a2AtFrameStart[e + 2] = a2;
uint256 shift = 64 * (c.cur - e);
_unripe = shift >= 256 ? 0 : _unripe >> shift; // re-base D, rounding down
_epoch = uint32(c.cur);
}
}
/// @dev A2 at the start of frame `k`. If the global state has not reached frame `k` yet (view called
/// before the first transaction of a new frame) nothing has happened since, so it is today's A2.
function _a2At(uint256 k, uint256 a2) internal view returns (uint256) {
return k <= _epoch ? _a2AtFrameStart[k] : a2;
}
/// @dev Honey owed to `h` since its snapshot, and its d re-based into frame `cur`. Never an over-estimate.
function _accrued(Account storage h, uint256 cur) internal view returns (uint256 honey, uint256 d) {
d = h.d;
uint256 bal = h.bal;
if (d == 0 && bal == 0) return (0, 0);
uint256 a2 = _a2;
uint256 e = h.epoch;
uint256 ded; // d_i * dA2, split by frame, each piece rounded up
if (cur == e) {
ded = d.fullMulDivUp(a2 - h.a2, QD);
} else {
uint256 s1 = _a2At(e + 1, a2);
ded = d.fullMulDivUp(s1 - h.a2, QD); // rest of the snapshot frame
d = HoneyMath.ceilShr(d, 64);
if (cur == e + 1) {
ded += d.fullMulDivUp(a2 - s1, QD); // the next frame
} else {
uint256 s2 = _a2At(e + 2, a2);
ded += d.fullMulDivUp(s2 - s1, QD); // the next frame, complete
d = HoneyMath.ceilShr(d, 64);
// Every later frame: its true factor is d >> 64k, bounded above by this d (already
// <= bal * 2^-64). Costs the holder at most 2^-64 of that honey; keeps the settle O(1).
ded += d.fullMulDivUp(a2 - s2, QD);
d = HoneyMath.ceilShr(d, 64 * (cur - e - 2));
}
}
uint256 gross = bal.fullMulDiv(_a0 - h.a0, Q0);
honey = gross.zeroFloorSub(ded);
uint256 cap = _owed;
if (honey > cap) honey = cap; // solvency guard: credits can never exceed what was distributed
}
/// @dev Settle `a`: credit accrued honey as a fresh lot, re-snapshot, and exclude it if it has code.
/// Returns whether the account is in the hive.
function _touch(address a, Clock memory c) internal returns (bool) {
Account storage h = _acct[a];
if (h.excluded) return false;
(uint256 honey, uint256 d) = _accrued(h, c.cur);
if (honey != 0) {
uint256 total = uint256(h.honey) + honey;
h.honey = total > type(uint120).max ? type(uint120).max : uint120(total);
(uint256 down, uint256 up) = HoneyMath.grow(honey << F, c.dt);
d += up;
_unripe += down;
unchecked {
h.bal += uint128(honey); // honey <= _owed <= supply
_eligible += uint128(honey);
_owed -= uint128(honey); // honey <= _owed
_paid += uint128(honey); // _paid <= _fed
}
emit Transfer(address(this), a, honey);
}
if (_hasForeignCode(a)) {
// Honey earned up to here is kept (it was just settled). From now on: no weight.
h.excluded = true;
h.d = 0;
_eligible -= h.bal;
_unripe = _unripe.zeroFloorSub(d);
emit Excluded(a);
return false;
}
h.d = uint192(d);
h.epoch = uint32(c.cur);
h.a0 = _a0;
h.a2 = _a2;
return true;
}
/// @dev Contract code that is not an EIP-7702 delegation designator (0xef0100 || address, 23 bytes).
/// EIP-3541 forbids deploying code that starts with 0xef, so the prefix cannot be faked.
function _hasForeignCode(address a) internal view returns (bool foreign) {
if (a == address(0) || a == DEAD) return true;
/// @solidity memory-safe-assembly
assembly {
let size := extcodesize(a)
if size {
foreign := 1
if eq(size, 23) {
mstore(0x00, 0)
extcodecopy(a, 0x00, 0, 3)
foreign := iszero(eq(shr(232, mload(0x00)), 0xef0100))
}
}
}
}
}
lib/solady/src/utils/FixedPointMathLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(int256 x)
internal
pure
returns (int256 w)
{
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `a * b == x * y`, with full precision.
function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// Compute the product mod `2**256` and mod `2**256 - 1`
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that `product = p1 * 2**256 + p0`.
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure `z` is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
z := mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
z := div(z, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
z := mul(
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
z = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let k := and(n, 0xff) // `n`, cleaned.
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(k, p1)) {
z := add(shl(sub(256, k), p1), shr(k, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(and(n, 0xff), z)
break
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
/// @solidity memory-safe-assembly
assembly {
let g := n
let r := mod(a, n)
for { let y := 1 } 1 {} {
let q := div(g, r)
let t := g
g := r
r := sub(t, mul(r, q))
let u := x
x := y
y := sub(u, mul(y, q))
if iszero(r) { break }
}
x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `max(0, x - y)`.
function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x + y)`.
function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(0, lt(add(x, y), x)), add(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x * y)`.
function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `x != 0 ? x : y`, without branching.
function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != bytes32(0) ? x : y`, without branching.
function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != address(0) ? x : y`, without branching.
function coalesce(address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(shl(96, x))))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns `sqrt(x * y)`. Also called the geometric mean.
function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x == y) return x;
uint256 p = rawMul(x, y);
if (y == rawDiv(p, x)) return sqrt(p);
for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) {
if ((p = fullMulDivUnchecked(x, y, z)) >= z) break;
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { z := mul(z, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
internal
pure
returns (uint256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
internal
pure
returns (int256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(uint256 x) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}
src/lib/HoneyMath.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
/// @title HoneyMath — directed-rounding 2^(±t / 7 days) for Veterans' honey
/// @notice Every function returns a proven bound, never a nearest value: `...Down` is <= the real number and
/// `...Up` is >= it. Favus.sol picks the direction that can only under-pay honey.
/// Derivation, error bound and the Python reference: favus/docs/honey-math.md, contracts/model/.
library HoneyMath {
/// @dev Ripeness half-life: half-ripe after one week.
uint256 internal constant HALF_LIFE = 7 days;
/// @dev Fixed point of the power function (Q127).
uint256 internal constant ONE = 1 << 127;
/// @dev powFracDown(r) <= 2^(-r/HALF_LIFE) * ONE <= powFracDown(r) + POW_ERR.
/// Each of the <= 20 multiply steps loses < 2 ulps (one for the floored table entry, one for the
/// floored product), so the result is at most 40 ulps (2^-121.7 relative) low.
uint256 internal constant POW_ERR = 40;
// K_j = floor(ONE * 2^(-2^j / 604800)), generated by model/honey_model.py and re-checked against this
// file by model/test_honey_model.py (test_solidity_table_matches).
uint256 private constant K0 = 0x7ffff662d209fa09876eec42cf01f222;
uint256 private constant K1 = 0x7fffecc5a4cccf8c77bbf72a011b76cd;
uint256 private constant K2 = 0x7fffd98b4c7d0cc7093900d8a6a6d878;
uint256 private constant K3 = 0x7fffb316a487ce8a2bf571b1e98fbd7c;
uint256 private constant K4 = 0x7fff662d7746632255983758ac1382d9;
uint256 private constant K5 = 0x7ffecc5ba7676f6999488be7d37c5cff;
uint256 private constant K6 = 0x7ffd98ba32360ad24c678a95b3b978a3;
uint256 private constant K7 = 0x7ffb317ff1ed01367168b83a4c886394;
uint256 private constant K8 = 0x7ff6632e18ff91061b0cda8aee0a413d;
uint256 private constant K9 = 0x7fecc714ffa49962de0cfdf5cc73bbb2;
uint256 private constant K10 = 0x7fd9910cfe5c9dab7c269801b7b2a420;
uint256 private constant K11 = 0x7fb32da43d2dac8263db72b1836cf0f5;
uint256 private constant K12 = 0x7f668963a1080bd23a6a166bb39ccaf1;
uint256 private constant K13 = 0x7ecdcac53dcc2e891f4e2a0d3e7c48ac;
uint256 private constant K14 = 0x7d9e721112aba89fce10141aee997dc9;
uint256 private constant K15 = 0x7b483aeb5843c8a925aabe17f7a981cf;
uint256 private constant K16 = 0x76bcf9feb1848a9a9649f472d597c5fa;
uint256 private constant K17 = 0x6e2583eddbb8ba5552aa72bff844c0f5;
uint256 private constant K18 = 0x5ec885bf9f231ecd9e0c91240730ae47;
uint256 private constant K19 = 0x462fbe93f44e3890f15ce0b1fac95268;
/// @notice Lower bound of 2^(-r / HALF_LIFE) in Q127. Requires r < HALF_LIFE (< 2^20).
function powFracDown(uint256 r) internal pure returns (uint256 p) {
unchecked {
p = ONE;
if (r & 0x00001 != 0) p = (p * K0) >> 127;
if (r & 0x00002 != 0) p = (p * K1) >> 127;
if (r & 0x00004 != 0) p = (p * K2) >> 127;
if (r & 0x00008 != 0) p = (p * K3) >> 127;
if (r & 0x00010 != 0) p = (p * K4) >> 127;
if (r & 0x00020 != 0) p = (p * K5) >> 127;
if (r & 0x00040 != 0) p = (p * K6) >> 127;
if (r & 0x00080 != 0) p = (p * K7) >> 127;
if (r & 0x00100 != 0) p = (p * K8) >> 127;
if (r & 0x00200 != 0) p = (p * K9) >> 127;
if (r & 0x00400 != 0) p = (p * K10) >> 127;
if (r & 0x00800 != 0) p = (p * K11) >> 127;
if (r & 0x01000 != 0) p = (p * K12) >> 127;
if (r & 0x02000 != 0) p = (p * K13) >> 127;
if (r & 0x04000 != 0) p = (p * K14) >> 127;
if (r & 0x08000 != 0) p = (p * K15) >> 127;
if (r & 0x10000 != 0) p = (p * K16) >> 127;
if (r & 0x20000 != 0) p = (p * K17) >> 127;
if (r & 0x40000 != 0) p = (p * K18) >> 127;
if (r & 0x80000 != 0) p = (p * K19) >> 127;
}
}
/// @notice Lower bound of v * 2^(-dt / HALF_LIFE).
function decayDown(uint256 v, uint256 dt) internal pure returns (uint256) {
unchecked {
uint256 n = dt / HALF_LIFE;
if (n >= 256) return 0;
return FixedPointMathLib.fullMulDiv(v, powFracDown(dt % HALF_LIFE), ONE) >> n;
}
}
/// @notice Upper bound of v * 2^(-dt / HALF_LIFE). Requires v < 2^255.
function decayUp(uint256 v, uint256 dt) internal pure returns (uint256) {
unchecked {
if (v == 0) return 0;
uint256 n = dt / HALF_LIFE;
if (n >= 256) return 1;
return ceilShr(FixedPointMathLib.fullMulDivUp(v, powFracDown(dt % HALF_LIFE) + POW_ERR, ONE), n);
}
}
/// @notice Bounds of v * 2^(+dt / HALF_LIFE): `down` <= real <= `up`.
/// @dev Requires dt < 64 * HALF_LIFE and v < 2^192 (so `v << n` cannot overflow).
function grow(uint256 v, uint256 dt) internal pure returns (uint256 down, uint256 up) {
unchecked {
uint256 pd = powFracDown(dt % HALF_LIFE);
v <<= dt / HALF_LIFE;
down = FixedPointMathLib.fullMulDiv(v, ONE, pd + POW_ERR);
up = FixedPointMathLib.fullMulDivUp(v, ONE, pd);
}
}
/// @notice ceil(v / 2^n) for any n.
function ceilShr(uint256 v, uint256 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
switch lt(n, 256)
case 1 { z := add(shr(n, v), iszero(iszero(and(v, sub(shl(n, 1), 1))))) }
default { z := iszero(iszero(v)) }
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 1000000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/",
"solmate/=lib/v4-core/lib/solmate/",
"openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"v4-core/=lib/v4-core/",
"v4-periphery/=lib/v4-periphery/",
"@uniswap/v4-core/=lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"permit2/=lib/v4-periphery/lib/permit2/",
"@ensdomains/=/root/claudecooks/InuPeg/contracts/lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/=/root/claudecooks/InuPeg/contracts/lib/v4-core/lib/openzeppelin-contracts/",
"ds-test/=/root/claudecooks/InuPeg/contracts/lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=/root/claudecooks/InuPeg/contracts/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=/root/claudecooks/InuPeg/contracts/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"hardhat/=/root/claudecooks/InuPeg/contracts/lib/v4-core/node_modules/hardhat/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.