Verified contractPartialApache-2.0
UniV3CLPYieldSourceOracle
Address0x779bcebf0161ed88aba07c561248650301c97a77
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.30
- Same code
1 more contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- prague
- License
- Apache-2.0
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,581,176
- Creation transaction
- 0x3b09219b57…4a9db8f22f
27 files
- src/accounting/oracles/UniV3CLPYieldSourceOracle.solmain17.97 KB
- lib/modulekit/src/integrations/interfaces/chainlink/IAggregatorV3.sol1.26 KB
- lib/openzeppelin-contracts/contracts/access/AccessControl.sol7.03 KB
- lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.34 KB
- 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/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol879 B
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.15 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/v4-core/src/libraries/BitMath.sol2.61 KB
- lib/v4-core/src/libraries/CustomRevert.sol5.17 KB
- lib/v4-core/src/libraries/FullMath.sol5.46 KB
- lib/v4-core/src/libraries/TickMath.sol12.38 KB
- src/accounting/oracles/AbstractYieldSourceOracle.sol6.96 KB
- src/accounting/oracles/UniV3CLPRegistry.sol17.71 KB
- src/interfaces/accounting/ISuperLedger.sol8.44 KB
- src/interfaces/accounting/ISuperLedgerConfiguration.sol12.05 KB
- src/interfaces/accounting/IYieldSourceOracle.sol9.31 KB
- src/vendor/awesome-oracles/IOracle.sol1.61 KB
- src/vendor/chainlink/IChainlinkProxyAggregator.sol457 B
- src/vendor/uniswap/v3/CLLiquidityAmounts.sol5.27 KB
- src/vendor/uniswap/v3/INonfungiblePositionManager.sol2.75 KB
- src/vendor/uniswap/v3/IUniswapV3CLPool.sol1.73 KB
src/accounting/oracles/UniV3CLPYieldSourceOracle.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
// External
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { IAggregatorV3 } from "modulekit/integrations/interfaces/chainlink/IAggregatorV3.sol";
// Superform vendor
import { CLLiquidityAmounts } from "../../vendor/uniswap/v3/CLLiquidityAmounts.sol";
import { IUniswapV3CLPool } from "../../vendor/uniswap/v3/IUniswapV3CLPool.sol";
import { INonfungiblePositionManager } from "../../vendor/uniswap/v3/INonfungiblePositionManager.sol";
// Superform
import { AbstractYieldSourceOracle } from "./AbstractYieldSourceOracle.sol";
import { UniV3CLPRegistry } from "./UniV3CLPRegistry.sol";
/// @title UniV3CLPYieldSourceOracle
/// @author Superform Labs
/// @notice Singleton oracle for Uniswap V3-style concentrated liquidity LP positions.
/// @dev Backed by a UniV3CLPRegistry that maps positionKey → PositionConfig.
/// The `yieldSourceAddress` parameter in all oracle methods is a `positionKey`
/// returned by UniV3CLPRegistry.registerPosition().
///
/// SUPPORTS:
/// - Uniswap V3 (Ethereum, Arbitrum, BSC) — fully compatible
/// - Aerodrome Slipstream (Base) — fully compatible (tickSpacing in fee field, same ABI)
///
/// NOT SUPPORTED:
/// - Algebra / SparkDEX — different positions() ABI (no fee/tickSpacing field)
/// A separate AlgebraCLPYieldSourceOracle is needed for those forks.
///
/// PRICING MECHANISM (manipulation resistant):
/// Step 1 — liquidity → (amount0, amount1):
/// Reconstructs sqrtPriceX96 from Chainlink cross-rate (NOT the pool's live slot0).
/// sqrtPrice = sqrt(price0 * feed1Scale * token1Scale / (price1 * feed0Scale * token0Scale)) * Q96
/// Clamps to [sqrtPriceAtTick(tickLower), sqrtPriceAtTick(tickUpper)].
/// Calls getAmountsForLiquidity with the fixed range and the Chainlink-derived price.
/// This prevents flash-loan price manipulation of the oracle.
///
/// Step 2 — (amount0, amount1) → token0 value:
/// amount1InToken0 = amount1 * price1 * feed0Scale * token0Scale
/// / (price0 * feed1Scale * token1Scale)
/// PPS = amount0 + amount1InToken0
///
/// SHARE UNIT: 1 "share" = 1e18 liquidity units (consistent with UniV2 LP oracle).
///
/// SINGLETON: A single deployment of this contract serves all positions registered in
/// the UniV3CLPRegistry. Add new pools/tick-ranges by calling registry.registerPosition().
contract UniV3CLPYieldSourceOracle is AbstractYieldSourceOracle {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when a zero address is provided (registry address in constructor)
error ZERO_ADDRESS();
/// @notice Thrown when a Chainlink price is non-positive, at circuit breaker bounds, or cross-rate is zero
error INVALID_PRICE();
/// @notice Thrown when a Chainlink feed has not been updated within the registered maxStaleness
error STALE_PRICE();
/// @notice Thrown when the L2 sequencer is currently down
error SEQUENCER_DOWN();
/// @notice Thrown when the L2 sequencer just restarted and the grace period has not elapsed
error GRACE_PERIOD_NOT_OVER();
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Share decimals (1 share = 1e18 liquidity units)
uint8 private constant SHARE_DECIMALS = 18;
/// @notice One share in liquidity units
uint128 private constant ONE_SHARE_LIQUIDITY = 1e18;
/// @notice Q96 constant (2^96) used for sqrtPriceX96 construction
uint256 private constant FIXED_POINT_96_Q96 = 0x1000000000000000000000000;
/*//////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice Registry holding all position configurations
UniV3CLPRegistry public immutable REGISTRY;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @param superLedgerConfiguration_ SuperLedgerConfiguration address
/// @param registry_ UniV3CLPRegistry address (must be non-zero)
constructor(
address superLedgerConfiguration_,
address registry_
)
AbstractYieldSourceOracle(superLedgerConfiguration_)
{
if (registry_ == address(0)) revert ZERO_ADDRESS();
REGISTRY = UniV3CLPRegistry(registry_);
}
/*//////////////////////////////////////////////////////////////
EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc AbstractYieldSourceOracle
/// @notice Returns 18 — share decimals are always 18 (1 share = 1e18 liquidity units)
function decimals(address) external pure override returns (uint8) {
return SHARE_DECIMALS;
}
/// @inheritdoc AbstractYieldSourceOracle
/// @notice Returns the estimated liquidity units receivable for assetsIn token0 (floor rounded)
/// @param yieldSourceAddress positionKey from UniV3CLPRegistry.registerPosition()
function getShareOutput(
address yieldSourceAddress,
address,
uint256 assetsIn
)
external
view
override
returns (uint256)
{
if (assetsIn == 0) return 0;
uint256 pps = getPricePerShare(yieldSourceAddress);
if (pps == 0) return 0;
// shares_out = assetsIn * ONE_SHARE / pps (floor)
return Math.mulDiv(assetsIn, uint256(ONE_SHARE_LIQUIDITY), pps);
}
/// @inheritdoc AbstractYieldSourceOracle
/// @notice Returns the liquidity units to burn for a withdrawal of assetsIn token0 (ceil rounded)
/// @param yieldSourceAddress positionKey from UniV3CLPRegistry.registerPosition()
function getWithdrawalShareOutput(
address yieldSourceAddress,
address,
uint256 assetsIn
)
external
view
override
returns (uint256)
{
if (assetsIn == 0) return 0;
uint256 pps = getPricePerShare(yieldSourceAddress);
if (pps == 0) return 0;
return Math.mulDiv(assetsIn, uint256(ONE_SHARE_LIQUIDITY), pps, Math.Rounding.Ceil);
}
/// @inheritdoc AbstractYieldSourceOracle
/// @notice Returns the token0 value of sharesIn liquidity units
/// @param yieldSourceAddress positionKey from UniV3CLPRegistry.registerPosition()
function getAssetOutput(
address yieldSourceAddress,
address,
uint256 sharesIn
)
public
view
override
returns (uint256)
{
if (sharesIn == 0) return 0;
uint256 pps = getPricePerShare(yieldSourceAddress);
return Math.mulDiv(sharesIn, pps, uint256(ONE_SHARE_LIQUIDITY));
}
/// @inheritdoc AbstractYieldSourceOracle
/// @notice Returns the fair price of ONE_SHARE_LIQUIDITY (1e18) liquidity units in token0 terms
/// @dev Pricing steps:
/// 1. Load PositionConfig from registry (reverts POSITION_NOT_REGISTERED for unknown keys)
/// 2. Check L2 sequencer liveness (no-op when sequencerUptimeFeed is address(0))
/// 3. Fetch and validate Chainlink prices for token0/USD and token1/USD
/// 4. Reconstruct sqrtPriceX96 from cross-rate (flash-loan resistant)
/// 5. Clamp to [sqrtPriceAX96, sqrtPriceBX96] (precomputed tick boundaries)
/// 6. Call getAmountsForLiquidity for ONE_SHARE_LIQUIDITY
/// 7. Convert amount1 to token0 terms and return amount0 + amount1InToken0
/// @param yieldSourceAddress positionKey from UniV3CLPRegistry.registerPosition()
function getPricePerShare(address yieldSourceAddress) public view override returns (uint256) {
UniV3CLPRegistry.PositionConfig memory cfg = REGISTRY.getPositionConfig(yieldSourceAddress);
_checkSequencer(cfg.sequencerUptimeFeed, cfg.gracePeriod);
(uint256 price0, uint256 price1) = _getPrices(cfg);
// Reconstruct sqrtPriceX96 from Chainlink cross-rate
// sqrtPriceX96 = sqrt(token1_atoms_per_token0_atom) * 2^96
// where token1_atoms_per_token0_atom = price0 * feed1Scale * token1Scale
// / (price1 * feed0Scale * token0Scale)
// Use sqrt(num) * Q96 / sqrt(den) to avoid 2^192 overflow
uint256 sqrtNum = Math.sqrt(price0 * cfg.feed1Scale * cfg.token1Scale);
uint256 sqrtDen = Math.sqrt(price1 * cfg.feed0Scale * cfg.token0Scale);
if (sqrtDen == 0) revert INVALID_PRICE();
uint160 sqrtPriceCL = uint160(Math.mulDiv(sqrtNum, FIXED_POINT_96_Q96, sqrtDen));
// Clamp to tick range boundaries:
// below lower → all liquidity in token0
// above upper → all liquidity in token1
uint160 sqrtPriceForCalc = sqrtPriceCL < cfg.sqrtPriceAX96
? cfg.sqrtPriceAX96
: (sqrtPriceCL > cfg.sqrtPriceBX96 ? cfg.sqrtPriceBX96 : sqrtPriceCL);
// Get token0 and token1 amounts for ONE_SHARE_LIQUIDITY at the Chainlink-derived price
(uint256 amount0, uint256 amount1) = CLLiquidityAmounts.getAmountsForLiquidity(
sqrtPriceForCalc, cfg.sqrtPriceAX96, cfg.sqrtPriceBX96, ONE_SHARE_LIQUIDITY
);
// Convert amount1 to token0 terms using Chainlink cross-rate:
// p1InToken0 = price1 * feed0Scale * token0Scale / (price0 * feed1Scale * token1Scale)
// amount1InToken0 = amount1 * p1InToken0 / token1Scale
// = amount1 * price1 * feed0Scale * token0Scale
// / (price0 * feed1Scale * token1Scale)
// (token1Scale appears once in denominator: once for the price conversion, consumed by p1InToken0)
uint256 amount1InToken0;
if (amount1 > 0) {
amount1InToken0 = Math.mulDiv(
amount1 * price1,
cfg.feed0Scale * cfg.token0Scale,
price0 * cfg.feed1Scale * cfg.token1Scale
);
}
return amount0 + amount1InToken0;
}
/// @inheritdoc AbstractYieldSourceOracle
/// @notice Returns the total liquidity (in share units) held by an owner across all matching positions
/// @dev Iterates over all NFT positions owned by ownerOfShares.
/// Matches positions where (token0, token1, tickLower, tickUpper) equals the registry config.
/// O(N) in number of positions held by ownerOfShares — acceptable for view-only accounting.
/// @param yieldSourceAddress positionKey from UniV3CLPRegistry.registerPosition()
function getBalanceOfOwner(
address yieldSourceAddress,
address ownerOfShares
)
external
view
override
returns (uint256)
{
return _getBalanceOfOwner(yieldSourceAddress, ownerOfShares);
}
/// @inheritdoc AbstractYieldSourceOracle
/// @notice Returns the token0 value of an owner's matching LP positions
/// @param yieldSourceAddress positionKey from UniV3CLPRegistry.registerPosition()
function getTVLByOwnerOfShares(
address yieldSourceAddress,
address ownerOfShares
)
public
view
override
returns (uint256)
{
uint256 shares = _getBalanceOfOwner(yieldSourceAddress, ownerOfShares);
if (shares == 0) return 0;
return getAssetOutput(yieldSourceAddress, address(0), shares);
}
/// @inheritdoc AbstractYieldSourceOracle
/// @notice Returns the value of the pool's current active liquidity in token0 terms
/// @dev Returns non-zero only when the current tick is within [tickLower, tickUpper).
/// Uses pool.liquidity() which is the active liquidity at the current tick.
/// This includes all in-range LPs, not just a single strategy's positions.
/// For per-strategy TVL, use getTVLByOwnerOfShares() instead.
///
/// WARNING: This function reads slot0() for the current tick and pool.liquidity() for
/// active liquidity. Both values are manipulable via flash loans or large swaps.
/// Do NOT use this function for on-chain accounting decisions, collateral valuation,
/// or any security-critical path. For manipulation-resistant per-owner TVL,
/// use getTVLByOwnerOfShares() which relies on Chainlink-derived pricing only.
/// @param yieldSourceAddress positionKey from UniV3CLPRegistry.registerPosition()
function getTVL(address yieldSourceAddress) public view override returns (uint256) {
UniV3CLPRegistry.PositionConfig memory cfg = REGISTRY.getPositionConfig(yieldSourceAddress);
(, int24 currentTick) = IUniswapV3CLPool(cfg.pool).slot0();
if (currentTick < cfg.tickLower || currentTick >= cfg.tickUpper) return 0;
uint128 activeLiquidity = IUniswapV3CLPool(cfg.pool).liquidity();
if (activeLiquidity == 0) return 0;
return getAssetOutput(yieldSourceAddress, address(0), uint256(activeLiquidity));
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Fetches and validates both Chainlink prices from the registry config
/// @param cfg The position configuration containing feed addresses, circuit breaker bounds, and staleness
/// @return price0 The validated Chainlink price for token0/USD
/// @return price1 The validated Chainlink price for token1/USD
function _getPrices(UniV3CLPRegistry.PositionConfig memory cfg)
internal
view
returns (uint256 price0, uint256 price1)
{
price0 = _getChainlinkPrice(
IAggregatorV3(cfg.feed0), cfg.feed0MinAnswer, cfg.feed0MaxAnswer, cfg.maxStaleness
);
price1 = _getChainlinkPrice(
IAggregatorV3(cfg.feed1), cfg.feed1MinAnswer, cfg.feed1MaxAnswer, cfg.maxStaleness
);
}
/// @notice Fetches and validates a single Chainlink price feed answer
/// @param feed Chainlink aggregator interface
/// @param minAnswer Circuit breaker lower bound (0 = disabled)
/// @param maxAnswer Circuit breaker upper bound (0 = disabled)
/// @param maxStaleness Maximum seconds since last update before reverting
/// @return The validated price as a positive uint256
function _getChainlinkPrice(
IAggregatorV3 feed,
int192 minAnswer,
int192 maxAnswer,
uint256 maxStaleness
)
internal
view
returns (uint256)
{
(, int256 answer,, uint256 updatedAt,) = feed.latestRoundData();
if (answer <= 0) revert INVALID_PRICE();
if (block.timestamp - updatedAt > maxStaleness) revert STALE_PRICE();
if (minAnswer > 0 && answer <= int256(minAnswer)) revert INVALID_PRICE();
if (maxAnswer > 0 && answer >= int256(maxAnswer)) revert INVALID_PRICE();
return uint256(answer);
}
/// @notice Checks L2 sequencer liveness; no-op when sequencerFeed is address(0)
/// @param sequencerFeed Address of the L2 sequencer uptime feed (address(0) to skip)
/// @param gracePeriod Seconds to wait after sequencer restart before accepting prices
function _checkSequencer(address sequencerFeed, uint256 gracePeriod) internal view {
if (sequencerFeed == address(0)) return;
(, int256 answer,, uint256 startedAt,) = IAggregatorV3(sequencerFeed).latestRoundData();
if (answer != 0) revert SEQUENCER_DOWN();
if (block.timestamp - startedAt < gracePeriod) revert GRACE_PERIOD_NOT_OVER();
}
/// @notice Returns the total liquidity (in share units) held by an owner across all matching positions
/// @dev Iterates over all NFT positions owned by ownerOfShares.
/// Matches positions where (token0, token1, tickLower, tickUpper) equals the registry config.
/// O(N) in number of positions held by ownerOfShares — acceptable for view-only accounting.
/// @param yieldSourceAddress positionKey from UniV3CLPRegistry.registerPosition()
/// @param ownerOfShares Address whose NFT positions to scan
/// @return totalLiquidity Sum of matching position liquidity
function _getBalanceOfOwner(
address yieldSourceAddress,
address ownerOfShares
)
internal
view
returns (uint256 totalLiquidity)
{
UniV3CLPRegistry.PositionConfig memory cfg = REGISTRY.getPositionConfig(yieldSourceAddress);
INonfungiblePositionManager nftManager = INonfungiblePositionManager(cfg.nftManager);
uint256 nftBalance = nftManager.balanceOf(ownerOfShares);
if (nftBalance == 0) return 0;
address t0 = cfg.token0;
address t1 = cfg.token1;
int24 tL = cfg.tickLower;
int24 tU = cfg.tickUpper;
for (uint256 i; i < nftBalance;) {
uint256 tokenId = nftManager.tokenOfOwnerByIndex(ownerOfShares, i);
(
,
,
address posToken0,
address posToken1,
,
int24 posTickLower,
int24 posTickUpper,
uint128 posLiquidity,
,
,
,
) = nftManager.positions(tokenId);
if (posToken0 == t0 && posToken1 == t1 && posTickLower == tL && posTickUpper == tU) {
totalLiquidity += posLiquidity;
}
unchecked {
++i;
}
}
}
}
lib/modulekit/src/integrations/interfaces/chainlink/IAggregatorV3.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IAggregatorV3 {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestAnswer() external view returns (uint256);
function getTimestamp(uint256 _roundId) external view returns (uint256);
function phaseId() external view returns (uint16);
function phaseAggregators(uint16 _phaseId) external view returns (address);
}
lib/openzeppelin-contracts/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
lib/openzeppelin-contracts/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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.1.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.1.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/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
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/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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.3.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 `a ? b : c`. 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. `a ? b : c`) 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) {
// (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 byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 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 last 16 bytes.
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;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
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 an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an 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 An 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-core/src/libraries/BitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}
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-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-core/src/libraries/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}
src/accounting/oracles/AbstractYieldSourceOracle.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
// Superform
import { IYieldSourceOracle } from "../../interfaces/accounting/IYieldSourceOracle.sol";
import { ISuperLedgerConfiguration } from "../../interfaces/accounting/ISuperLedgerConfiguration.sol";
import { ISuperLedger } from "../../interfaces/accounting/ISuperLedger.sol";
/// @title AbstractYieldSourceOracle
/// @author Superform Labs
/// @notice Abstract base contract that implements common functionality for yield source oracles
/// @dev Provides implementations for batch methods to reduce redundancy across concrete oracles
/// Concrete oracle implementations must extend this class and implement the abstract methods
/// The oracle pattern separates price/yield discovery from the core accounting system
abstract contract AbstractYieldSourceOracle is IYieldSourceOracle {
/*//////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////*/
/// @notice Immutable address of the SuperLedgerConfiguration contract
address public immutable SUPER_LEDGER_CONFIGURATION;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Constructor to set the SuperLedgerConfiguration address
/// @param superLedgerConfiguration_ Address of the SuperLedgerConfiguration contract
constructor(address superLedgerConfiguration_) {
SUPER_LEDGER_CONFIGURATION = superLedgerConfiguration_;
}
/*//////////////////////////////////////////////////////////////
EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IYieldSourceOracle
function decimals(address yieldSourceAddress) external view virtual returns (uint8);
/// @inheritdoc IYieldSourceOracle
function getShareOutput(
address yieldSourceAddress,
address assetIn,
uint256 assetsIn
)
external
view
virtual
returns (uint256);
/// @inheritdoc IYieldSourceOracle
function getWithdrawalShareOutput(
address yieldSourceAddress,
address assetIn,
uint256 assetsIn
)
external
view
virtual
returns (uint256);
/// @inheritdoc IYieldSourceOracle
function getAssetOutput(
address yieldSourceAddress,
address assetOut,
uint256 sharesIn
)
public
view
virtual
returns (uint256);
/// @inheritdoc IYieldSourceOracle
function getPricePerShare(address yieldSourceAddress) public view virtual returns (uint256);
/// @inheritdoc IYieldSourceOracle
function getTVLByOwnerOfShares(
address yieldSourceAddress,
address ownerOfShares
)
public
view
virtual
returns (uint256);
/// @inheritdoc IYieldSourceOracle
function getTVL(address yieldSourceAddress) public view virtual returns (uint256);
/// @inheritdoc IYieldSourceOracle
function getAssetOutputWithFees(
bytes32 yieldSourceOracleId,
address yieldSourceAddress,
address assetOut,
address user,
uint256 usedShares
)
external
view
virtual
returns (uint256)
{
// Get base asset output without fees
uint256 assetOutput = getAssetOutput(yieldSourceAddress, assetOut, usedShares);
try ISuperLedgerConfiguration(SUPER_LEDGER_CONFIGURATION).getYieldSourceOracleConfig(yieldSourceOracleId)
returns (ISuperLedgerConfiguration.YieldSourceOracleConfig memory config) {
// Configuration found, calculate fees if applicable
if (config.feePercent > 0 && config.ledger != address(0)) {
// Calculate fees using the associated ledger
uint256 pps = IYieldSourceOracle(config.yieldSourceOracle).getPricePerShare(yieldSourceAddress);
uint8 _decimals = IYieldSourceOracle(config.yieldSourceOracle).decimals(yieldSourceAddress);
uint256 feeAmount = ISuperLedger(config.ledger).previewFees(
user, yieldSourceAddress, assetOutput, usedShares, config.feePercent, pps, _decimals
);
// Add fees to the asset output (opposite of BaseLedger which subtracted)
return assetOutput + feeAmount;
}
// Valid config but no fees, return base asset output
return assetOutput;
} catch {
// Configuration not found or invalid, return asset output without fees
return assetOutput;
}
}
/// @inheritdoc IYieldSourceOracle
function getPricePerShareMultiple(address[] memory yieldSourceAddresses)
external
view
returns (uint256[] memory pricesPerShare)
{
uint256 length = yieldSourceAddresses.length;
pricesPerShare = new uint256[](length);
// Iterate through all yield sources and get individual prices
for (uint256 i; i < length; ++i) {
pricesPerShare[i] = getPricePerShare(yieldSourceAddresses[i]);
}
}
/// @inheritdoc IYieldSourceOracle
function getBalanceOfOwner(
address yieldSourceAddress,
address ownerOfShares
)
external
view
virtual
returns (uint256);
/// @inheritdoc IYieldSourceOracle
function getTVLByOwnerOfSharesMultiple(
address[] memory yieldSourceAddresses,
address[][] memory ownersOfShares
)
external
view
returns (uint256[][] memory userTvls)
{
uint256 length = yieldSourceAddresses.length;
if (length != ownersOfShares.length) revert ARRAY_LENGTH_MISMATCH();
userTvls = new uint256[][](length);
// Process each yield source
for (uint256 i; i < length; ++i) {
address yieldSource = yieldSourceAddresses[i];
address[] memory owners = ownersOfShares[i];
uint256 ownersLength = owners.length;
userTvls[i] = new uint256[](ownersLength);
// For each yield source, process each owner
for (uint256 j; j < ownersLength; ++j) {
uint256 userTvl = getTVLByOwnerOfShares(yieldSource, owners[j]);
userTvls[i][j] = userTvl;
}
}
}
/// @inheritdoc IYieldSourceOracle
function getTVLMultiple(address[] memory yieldSourceAddresses) external view returns (uint256[] memory tvls) {
uint256 length = yieldSourceAddresses.length;
tvls = new uint256[](length);
// Get TVL for each yield source
for (uint256 i; i < length; ++i) {
tvls[i] = getTVL(yieldSourceAddresses[i]);
}
}
}
src/accounting/oracles/UniV3CLPRegistry.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
// External
import { AccessControl } from "@openzeppelin/contracts/access/AccessControl.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/interfaces/IERC20Metadata.sol";
import { IAggregatorV3 } from "modulekit/integrations/interfaces/chainlink/IAggregatorV3.sol";
import { TickMath } from "v4-core/libraries/TickMath.sol";
// Superform vendor
import { IUniswapV3CLPool } from "../../vendor/uniswap/v3/IUniswapV3CLPool.sol";
import { IChainlinkProxy, IChainlinkAggregator } from "../../vendor/chainlink/IChainlinkProxyAggregator.sol";
/// @title UniV3CLPRegistry
/// @author Superform Labs
/// @notice Singleton registry for UniV3-style concentrated liquidity position configurations.
/// @dev Replaces per-deployment immutables with a single registry that maps a derived
/// `positionKey` (pseudo-address) to a precomputed `PositionConfig`.
///
/// A positionKey is:
/// address(uint160(uint256(keccak256(abi.encode(pool, nftManager, tickLower, tickUpper)))))
///
/// Both `pool` and `nftManager` are in the key so UniV3 (Ethereum/Arbitrum/BSC) and
/// Aerodrome Slipstream (Base) can coexist on the same chain even if they happen to
/// share a pool address but use different NFT managers.
///
/// All per-position values that are expensive to compute on every oracle call are
/// precomputed at registration time:
/// - Token/feed decimal scales (10**decimals())
/// - Chainlink circuit breaker bounds (minAnswer/maxAnswer from aggregator proxy)
/// - Tick-boundary sqrtPriceX96 values (TickMath.getSqrtPriceAtTick)
///
/// Deregistration is gated by a 2-day timelock to prevent accidental removal.
contract UniV3CLPRegistry is AccessControl {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when a zero address is provided where a valid address is required
error ZERO_ADDRESS();
/// @notice Thrown when attempting to register a positionKey that already exists
error POSITION_ALREADY_REGISTERED();
/// @notice Thrown when querying or acting on a positionKey that is not registered
error POSITION_NOT_REGISTERED();
/// @notice Thrown when attempting to execute/cancel a deregistration that was never proposed
error DEREGISTRATION_NOT_PENDING();
/// @notice Thrown when the 2-day deregistration timelock has not elapsed yet
error DEREGISTRATION_TIMELOCK_NOT_ELAPSED();
/// @notice Thrown when maxStaleness is zero (would make all oracle reads revert immediately)
error INVALID_STALENESS();
/// @notice Thrown when tickLower >= tickUpper (invalid range)
error INVALID_TICK_RANGE();
/// @notice Thrown when tickLower or tickUpper is not a multiple of pool.tickSpacing()
error INVALID_TICK_ALIGNMENT();
/// @notice Thrown when the provided token0 or token1 does not match the pool's tokens
error TOKEN_MISMATCH();
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Role required to register and deregister positions
bytes32 public constant POSITION_MANAGER_ROLE = keccak256("POSITION_MANAGER_ROLE");
/// @notice Minimum delay between proposing and executing a deregistration
uint256 public constant DEREGISTER_DELAY = 2 days;
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/// @notice Complete configuration for a CLP position, with all expensive values precomputed
struct PositionConfig {
address pool;
address nftManager;
int24 tickLower;
int24 tickUpper;
address token0;
address token1;
uint256 token0Scale; // precomputed: 10**token0.decimals()
uint256 token1Scale; // precomputed: 10**token1.decimals()
address feed0;
address feed1;
uint256 feed0Scale; // precomputed: 10**feed0.decimals()
uint256 feed1Scale; // precomputed: 10**feed1.decimals()
int192 feed0MinAnswer; // circuit breaker lower bound (0 = disabled)
int192 feed0MaxAnswer; // circuit breaker upper bound (0 = disabled)
int192 feed1MinAnswer;
int192 feed1MaxAnswer;
uint256 maxStaleness;
address sequencerUptimeFeed;
uint256 gracePeriod;
uint160 sqrtPriceAX96; // precomputed: TickMath.getSqrtPriceAtTick(tickLower)
uint160 sqrtPriceBX96; // precomputed: TickMath.getSqrtPriceAtTick(tickUpper)
bool registered;
}
/*//////////////////////////////////////////////////////////////
STATE
//////////////////////////////////////////////////////////////*/
/// @notice Mapping from positionKey to PositionConfig
mapping(address positionKey => PositionConfig) private _positions;
/// @notice Mapping from positionKey to earliest timestamp at which deregistration can execute
mapping(address positionKey => uint256 executeAt) public pendingDeregistrations;
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a new CLP position is registered in the registry
/// @param positionKey The derived pseudo-address key for this position
/// @param pool The UniV3-compatible pool address
/// @param nftManager The NonfungiblePositionManager for this pool's DEX
/// @param tickLower Lower tick of the strategy's range
/// @param tickUpper Upper tick of the strategy's range
/// @param token0 The address of token0
/// @param token1 The address of token1
event PositionRegistered(
address indexed positionKey,
address indexed pool,
address indexed nftManager,
int24 tickLower,
int24 tickUpper,
address token0,
address token1
);
/// @notice Emitted when a position deregistration is proposed, starting the timelock
/// @param positionKey The position key being proposed for deregistration
/// @param executeAt The earliest timestamp at which deregistration can execute
event PositionDeregistrationProposed(address indexed positionKey, uint256 executeAt);
/// @notice Emitted when a pending position deregistration is cancelled
/// @param positionKey The position key whose deregistration was cancelled
event PositionDeregistrationCancelled(address indexed positionKey);
/// @notice Emitted when a position is deregistered after the timelock elapses
/// @param positionKey The position key that was deregistered
event PositionDeregistered(address indexed positionKey);
/// @notice Emitted when circuit breaker bounds are refreshed for a position
/// @param positionKey The position key whose bounds were refreshed
event CircuitBreakerBoundsRefreshed(address indexed positionKey);
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @param admin Address that receives DEFAULT_ADMIN_ROLE and POSITION_MANAGER_ROLE
constructor(address admin) {
if (admin == address(0)) revert ZERO_ADDRESS();
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(POSITION_MANAGER_ROLE, admin);
}
/*//////////////////////////////////////////////////////////////
EXTERNAL STATE-CHANGING FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Registers a CLP position configuration, precomputing all expensive values.
/// @param pool UniV3-compatible pool address
/// @param nftManager NonfungiblePositionManager for this pool's DEX
/// @param tickLower Lower tick of the strategy's range (must be < tickUpper)
/// @param tickUpper Upper tick of the strategy's range
/// @param token0 token0 of the pool (must match pool.token0())
/// @param token1 token1 of the pool
/// @param feed0 Chainlink price feed for token0/USD
/// @param feed1 Chainlink price feed for token1/USD
/// @param maxStaleness Max seconds since last Chainlink update before reverting (must be > 0)
/// @param sequencerUptimeFeed L2 sequencer uptime feed (address(0) to disable on L1)
/// @param gracePeriod Seconds to wait after sequencer restart before accepting prices
/// @return positionKey Derived pseudo-address key for this position
function registerPosition(
address pool,
address nftManager,
int24 tickLower,
int24 tickUpper,
address token0,
address token1,
address feed0,
address feed1,
uint256 maxStaleness,
address sequencerUptimeFeed,
uint256 gracePeriod
)
external
onlyRole(POSITION_MANAGER_ROLE)
returns (address positionKey)
{
if (
pool == address(0) || nftManager == address(0) || token0 == address(0) || token1 == address(0)
|| feed0 == address(0) || feed1 == address(0)
) revert ZERO_ADDRESS();
if (maxStaleness == 0) revert INVALID_STALENESS();
if (tickLower >= tickUpper) revert INVALID_TICK_RANGE();
if (token0 != IUniswapV3CLPool(pool).token0() || token1 != IUniswapV3CLPool(pool).token1()) {
revert TOKEN_MISMATCH();
}
int24 spacing = IUniswapV3CLPool(pool).tickSpacing();
if (tickLower % spacing != 0 || tickUpper % spacing != 0) revert INVALID_TICK_ALIGNMENT();
positionKey = computePositionKey(pool, nftManager, tickLower, tickUpper);
if (_positions[positionKey].registered) revert POSITION_ALREADY_REGISTERED();
// Write base fields directly to storage via pointer (avoids local variable accumulation)
_writeBaseFields(positionKey, pool, nftManager, tickLower, tickUpper, token0, token1);
_writeFeedAndMetaFields(positionKey, feed0, feed1, maxStaleness, sequencerUptimeFeed, gracePeriod);
// Precompute derived values (reads from already-stored fields; separate frame keeps stack depth low)
_precomputeDerivedFields(positionKey);
emit PositionRegistered(positionKey, pool, nftManager, tickLower, tickUpper, token0, token1);
}
/// @notice Proposes deregistration of a position, starting the 2-day timelock
function proposeDeregisterPosition(address positionKey) external onlyRole(POSITION_MANAGER_ROLE) {
if (!_positions[positionKey].registered) revert POSITION_NOT_REGISTERED();
uint256 executeAt = block.timestamp + DEREGISTER_DELAY;
pendingDeregistrations[positionKey] = executeAt;
emit PositionDeregistrationProposed(positionKey, executeAt);
}
/// @notice Executes a deregistration after the timelock has elapsed
function executeDeregisterPosition(address positionKey) external onlyRole(POSITION_MANAGER_ROLE) {
uint256 executeAt = pendingDeregistrations[positionKey];
if (executeAt == 0) revert DEREGISTRATION_NOT_PENDING();
if (block.timestamp < executeAt) revert DEREGISTRATION_TIMELOCK_NOT_ELAPSED();
delete pendingDeregistrations[positionKey];
delete _positions[positionKey];
emit PositionDeregistered(positionKey);
}
/// @notice Cancels a pending deregistration before it executes
/// @param positionKey The position key whose deregistration to cancel
function cancelDeregisterPosition(address positionKey) external onlyRole(POSITION_MANAGER_ROLE) {
if (pendingDeregistrations[positionKey] == 0) revert DEREGISTRATION_NOT_PENDING();
delete pendingDeregistrations[positionKey];
emit PositionDeregistrationCancelled(positionKey);
}
/// @notice Refreshes the cached circuit breaker bounds from the current Chainlink aggregator
/// @dev Circuit breaker bounds are snapshotted at registration time. If Chainlink upgrades the
/// aggregator behind the proxy, the cached bounds become stale. Call this function to
/// re-read the current bounds from the proxy.
/// @param positionKey The registered position key to refresh
function refreshCircuitBreakerBounds(address positionKey) external onlyRole(POSITION_MANAGER_ROLE) {
PositionConfig storage cfg = _positions[positionKey];
if (!cfg.registered) revert POSITION_NOT_REGISTERED();
(cfg.feed0MinAnswer, cfg.feed0MaxAnswer) = _readCircuitBreakerBounds(cfg.feed0);
(cfg.feed1MinAnswer, cfg.feed1MaxAnswer) = _readCircuitBreakerBounds(cfg.feed1);
emit CircuitBreakerBoundsRefreshed(positionKey);
}
/*//////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Computes the deterministic positionKey for a (pool, nftManager, tick range) tuple
/// @dev Both pool and nftManager are in the key so UniV3 and Aerodrome Slipstream can
/// coexist on the same chain even if they happen to share a pool address.
function computePositionKey(
address pool,
address nftManager,
int24 tickLower,
int24 tickUpper
)
public
pure
returns (address)
{
return address(uint160(uint256(keccak256(abi.encode(pool, nftManager, tickLower, tickUpper)))));
}
/// @notice Returns the configuration for a registered position
/// @dev Reverts with POSITION_NOT_REGISTERED for unknown keys
function getPositionConfig(address positionKey) external view returns (PositionConfig memory) {
PositionConfig memory cfg = _positions[positionKey];
if (!cfg.registered) revert POSITION_NOT_REGISTERED();
return cfg;
}
/// @notice Returns whether a positionKey is registered
function isRegistered(address positionKey) external view returns (bool) {
return _positions[positionKey].registered;
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @dev Writes pool/token base fields. Separate function to keep stack depth bounded.
function _writeBaseFields(
address positionKey,
address pool,
address nftManager,
int24 tickLower,
int24 tickUpper,
address token0,
address token1
)
private
{
PositionConfig storage cfg = _positions[positionKey];
cfg.pool = pool;
cfg.nftManager = nftManager;
cfg.tickLower = tickLower;
cfg.tickUpper = tickUpper;
cfg.token0 = token0;
cfg.token1 = token1;
}
/// @dev Writes feed + meta fields. Separate function to keep stack depth bounded.
function _writeFeedAndMetaFields(
address positionKey,
address feed0,
address feed1,
uint256 maxStaleness,
address sequencerUptimeFeed,
uint256 gracePeriod
)
private
{
PositionConfig storage cfg = _positions[positionKey];
cfg.feed0 = feed0;
cfg.feed1 = feed1;
cfg.maxStaleness = maxStaleness;
cfg.sequencerUptimeFeed = sequencerUptimeFeed;
cfg.gracePeriod = gracePeriod;
}
/// @dev Precomputes all derived fields (scales, circuit breaker bounds, sqrtPrices) from stored addresses.
/// Reads from already-written storage so only needs the positionKey — minimises stack depth.
function _precomputeDerivedFields(address positionKey) private {
PositionConfig storage cfg = _positions[positionKey];
// Token decimal scales
cfg.token0Scale = 10 ** IERC20Metadata(cfg.token0).decimals();
cfg.token1Scale = 10 ** IERC20Metadata(cfg.token1).decimals();
// Feed decimal scales
cfg.feed0Scale = 10 ** IAggregatorV3(cfg.feed0).decimals();
cfg.feed1Scale = 10 ** IAggregatorV3(cfg.feed1).decimals();
// Circuit breaker bounds from Chainlink aggregator proxy
(cfg.feed0MinAnswer, cfg.feed0MaxAnswer) = _readCircuitBreakerBounds(cfg.feed0);
(cfg.feed1MinAnswer, cfg.feed1MaxAnswer) = _readCircuitBreakerBounds(cfg.feed1);
// Tick-boundary sqrtPriceX96 values
cfg.sqrtPriceAX96 = TickMath.getSqrtPriceAtTick(cfg.tickLower);
cfg.sqrtPriceBX96 = TickMath.getSqrtPriceAtTick(cfg.tickUpper);
cfg.registered = true;
}
/// @notice Reads circuit breaker bounds from the Chainlink aggregator behind a proxy
/// @dev Uses try/catch so that feeds without a proxy interface gracefully return (0, 0),
/// disabling the circuit breaker check for that feed
function _readCircuitBreakerBounds(address feed) private view returns (int192 minAns, int192 maxAns) {
try IChainlinkProxy(feed).aggregator() returns (address agg) {
try IChainlinkAggregator(agg).minAnswer() returns (int192 min) {
minAns = min;
} catch { }
try IChainlinkAggregator(agg).maxAnswer() returns (int192 max) {
maxAns = max;
} catch { }
} catch { }
}
}
src/interfaces/accounting/ISuperLedger.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
/// @title ISuperLedgerData
/// @author Superform Labs
/// @notice Interface defining core data structures and events for ledger accounting
/// @dev This interface is extended by ISuperLedger to provide a complete accounting system
/// It separates data structures and events from functional methods
interface ISuperLedgerData {
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/// @notice Represents a single accounting entry in a user's ledger
/// @dev Used to track shares and their acquisition price for accurate profit calculation
struct LedgerEntry {
/// @notice Amount of shares available to be consumed in this entry
uint256 amountSharesAvailableToConsume;
/// @notice Price at which these shares were acquired (in asset terms)
uint256 price;
}
/// @notice Collection of ledger entries for a user's position
/// @dev Manages entries in a FIFO queue for accurate cost basis calculation
struct Ledger {
/// @notice Array of ledger entries
LedgerEntry[] entries;
/// @notice Number of entries that still have unconsumed shares
uint256 unconsumedEntries;
}
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when shares are added to a user's ledger
/// @param user The user whose ledger is being updated
/// @param yieldSourceOracle The oracle providing price information
/// @param yieldSource The yield-bearing asset being accounted for
/// @param amount The amount of shares being added
/// @param pps The price per share at the time of inflow (in asset terms)
event AccountingInflow(
address indexed user,
address indexed yieldSourceOracle,
address indexed yieldSource,
uint256 amount,
uint256 pps
);
/// @notice Emitted when shares are consumed from a user's ledger
/// @param user The user whose ledger is being updated
/// @param yieldSourceOracle The oracle providing price information
/// @param yieldSource The yield-bearing asset being accounted for
/// @param amount The amount of shares or assets being processed
/// @param feeAmount The performance fee charged on yield profit
event AccountingOutflow(
address indexed user,
address indexed yieldSourceOracle,
address indexed yieldSource,
uint256 amount,
uint256 feeAmount
);
/// @notice Emitted when the amount of shares used is capped due to insufficient shares
/// @param originalVal The original amount of shares used
/// @param cappedVal The capped amount of shares used
event UsedSharesCapped(uint256 originalVal, uint256 cappedVal);
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when a referenced hook cannot be found
error HOOK_NOT_FOUND();
/// @notice Thrown when a price returned from an oracle is invalid (typically zero)
error INVALID_PRICE();
/// @notice Thrown when attempting to charge a fee without a valid fee percentage
error FEE_NOT_SET();
/// @notice Thrown when setting a fee percentage outside the allowed range
error INVALID_FEE_PERCENT();
/// @notice Thrown when a critical address parameter is set to the zero address
error ZERO_ADDRESS_NOT_ALLOWED();
/// @notice Thrown when an unauthorized address attempts a restricted operation
error NOT_AUTHORIZED();
/// @notice Thrown when a non-manager address attempts a manager-only operation
error NOT_MANAGER();
/// @notice Thrown when a manager is required but not set
error MANAGER_NOT_SET();
/// @notice Thrown when providing an empty array where at least one element is required
error ZERO_LENGTH();
/// @notice Thrown when an ID parameter is set to zero
error ZERO_ID_NOT_ALLOWED();
/// @notice Thrown when an operation references an invalid ledger
error INVALID_LEDGER();
}
/// @title ISuperLedger
/// @author Superform Labs
/// @notice Interface for the SuperLedger contract that manages yield accounting
/// @dev Extends ISuperLedgerData to provide methods for tracking and calculating performance fees
/// The accounting system tracks shares and their cost basis to accurately calculate yield
interface ISuperLedger is ISuperLedgerData {
/*//////////////////////////////////////////////////////////////
EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Updates accounting for a user's yield source interaction
/// @dev For inflows, records new shares at current price; for outflows, calculates fees based on profit
/// Only authorized executors can call this function
/// For outflows, the fee is calculated as a percentage of the profit:
/// profit = (current_value - cost_basis) where current_value is based on oracle price
/// @param user The user address whose accounting is being updated
/// @param yieldSource The yield source address (e.g. aUSDC, cUSDC, etc.)
/// @param yieldSourceOracleId ID for looking up the oracle configuration for this yield source
/// @param isInflow Whether this is an inflow (true) or outflow (false)
/// @param amountSharesOrAssets The amount of shares (for inflow) or assets (for outflow)
/// @param usedShares The amount of shares used for outflow calculation (0 for inflows)
/// @return feeAmount The amount of fee to be collected in the asset being withdrawn (0 for inflows)
function updateAccounting(
address user,
address yieldSource,
bytes32 yieldSourceOracleId,
bool isInflow,
uint256 amountSharesOrAssets,
uint256 usedShares
)
external
returns (uint256 feeAmount);
/// @notice Previews fees for a given amount of assets obtained from shares without modifying state
/// @dev Used to estimate fees before executing a transaction
/// Fee calculation: fee = (current_value - cost_basis) * fee_percent / 10_000
/// Returns 0 if there is no profit (current_value <= cost_basis)
/// @param user The user address whose fees are being calculated
/// @param yieldSourceAddress The yield source address (e.g. aUSDC, cUSDC, etc.)
/// @param amountAssets The amount of assets retrieved from shares (current value)
/// @param usedShares The amount of shares used to obtain the assets
/// @param feePercent The fee percentage in basis points (0-10000, where 10000 = 100%)
/// @param pps The price per share at the time of outflow (in asset terms)
/// @param decimals Decimal precision of the yield source
/// @return feeAmount The amount of fee to be collected in the asset being withdrawn
function previewFees(
address user,
address yieldSourceAddress,
uint256 amountAssets,
uint256 usedShares,
uint256 feePercent,
uint256 pps,
uint256 decimals
)
external
view
returns (uint256 feeAmount);
/// @notice Calculates the cost basis for a given user and amount of shares without modifying state
/// @dev Cost basis represents the original asset value of the shares when they were acquired
/// This is calculated proportionally based on the shares being consumed
/// Formula: user_cost_basis * (used_shares / total_shares)
/// @param user The user address whose cost basis is being calculated
/// @param yieldSource The yield source address (e.g. aUSDC, cUSDC, etc.)
/// @param usedShares The amount of shares to calculate cost basis for
/// @return costBasis The original asset value of the specified shares
/// @return updatedUsedShares The amount of shares that will be consumed
function calculateCostBasisView(
address user,
address yieldSource,
uint256 usedShares
)
external
view
returns (uint256 costBasis, uint256 updatedUsedShares);
}
src/interfaces/accounting/ISuperLedgerConfiguration.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
/// @title ISuperLedgerConfiguration
/// @author Superform Labs
/// @notice Interface for configuring yield source oracles and their associated fee parameters
/// @dev This interface defines the governance layer for yield tracking and fee collection
/// It manages configurations for yield source oracles, including fee percentages,
/// fee recipients, and management permissions
interface ISuperLedgerConfiguration {
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/// @notice Configuration for a yield source oracle
/// @dev Stored configuration for a particular yield source, identified by its ID elsewhere
struct YieldSourceOracleConfig {
/// @notice Address of the oracle that provides price information for this yield source
address yieldSourceOracle;
/// @notice Fee percentage charged on yield in basis points (0-10000, where 10000 = 100%)
uint256 feePercent;
/// @notice Address that receives collected fees
address feeRecipient;
/// @notice Address with permission to update this configuration
address manager;
/// @notice Address of the ledger contract that uses this configuration
address ledger;
}
/// @notice Input arguments for creating or updating a yield source oracle configuration
/// @dev Similar to YieldSourceOracleConfig but includes the ID and excludes the manager
/// The manager is either derived from existing config or set to msg.sender for new configs
struct YieldSourceOracleConfigArgs {
/// @notice Address of the oracle that provides price information
address yieldSourceOracle;
/// @notice Fee percentage charged on yield in basis points (0-10000, where 10000 = 100%)
uint256 feePercent;
/// @notice Address that receives collected fees
address feeRecipient;
/// @notice Address of the ledger contract that uses this configuration
address ledger;
}
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when a function restricted to managers is called by a non-manager address
error NOT_MANAGER();
/// @notice Thrown when providing an empty array where at least one element is required
error ZERO_LENGTH();
/// @notice Thrown when attempting to create a configuration that already exists
error CONFIG_EXISTS();
/// @notice Thrown when referencing a configuration that doesn't exist
error CONFIG_NOT_FOUND();
/// @notice Thrown when trying to accept a configuration proposal before the waiting period ends
error CANNOT_ACCEPT_YET();
/// @notice Thrown when a manager mismatch is detected during configuration operations
error MANAGER_NOT_MATCHED();
/// @notice Thrown when a zero ID is provided for a configuration
error ZERO_ID_NOT_ALLOWED();
/// @notice Thrown when setting a fee percentage outside the allowed range (0-10000)
error INVALID_FEE_PERCENT();
/// @notice Thrown when there is no pending proposal
error NO_PENDING_PROPOSAL();
/// @notice Thrown when attempting to accept a manager role without being the pending manager
error NOT_PENDING_MANAGER();
/// @notice Thrown when attempting to propose changes to a configuration that already has pending changes
error CHANGE_ALREADY_PROPOSED();
/// @notice Thrown when a critical address parameter is set to the zero address
error ZERO_ADDRESS_NOT_ALLOWED();
/// @notice Thrown when the length of input arrays do not match
error LENGTH_MISMATCH();
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a new yield source oracle configuration is created
/// @param yieldSourceOracleId Unique identifier for the yield source oracle
/// @param yieldSourceOracle Address of the oracle contract
/// @param feePercent Fee percentage in basis points
/// @param manager Address with permission to update this configuration
/// @param feeRecipient Address that receives collected fees
/// @param ledger Address of the ledger contract using this configuration
event YieldSourceOracleConfigSet(
bytes32 indexed yieldSourceOracleId,
address indexed yieldSourceOracle,
uint256 feePercent,
address feeRecipient,
address manager,
address ledger
);
/// @notice Emitted when changes to a yield source oracle configuration are proposed
/// @param yieldSourceOracleId Unique identifier for the yield source oracle
/// @param yieldSourceOracle Proposed oracle contract address
/// @param feePercent Proposed fee percentage in basis points
/// @param manager Current manager address (unchanged during proposal)
/// @param feeRecipient Proposed fee recipient address
/// @param ledger Proposed ledger contract address
event YieldSourceOracleConfigProposalSet(
bytes32 indexed yieldSourceOracleId,
address indexed yieldSourceOracle,
uint256 feePercent,
address feeRecipient,
address manager,
address ledger
);
/// @notice Emitted when proposed changes to a yield source oracle configuration are accepted
/// @param yieldSourceOracleId Unique identifier for the yield source oracle
/// @param yieldSourceOracle New oracle contract address
/// @param feePercent New fee percentage in basis points
/// @param manager Current manager address
/// @param feeRecipient New fee recipient address
/// @param ledger New ledger contract address
event YieldSourceOracleConfigAccepted(
bytes32 indexed yieldSourceOracleId,
address indexed yieldSourceOracle,
uint256 feePercent,
address feeRecipient,
address manager,
address ledger
);
/// @notice Emitted when the transfer of manager role is initiated
/// @param yieldSourceOracleId Unique identifier for the yield source oracle
/// @param currentManager Address of the current manager
/// @param newManager Address of the proposed new manager
event ManagerRoleTransferStarted(
bytes32 indexed yieldSourceOracleId, address indexed currentManager, address indexed newManager
);
/// @notice Emitted when the transfer of manager role is completed
/// @param yieldSourceOracleId Unique identifier for the yield source oracle
/// @param newManager Address of the new manager who accepted the role
event ManagerRoleTransferAccepted(bytes32 indexed yieldSourceOracleId, address indexed newManager);
/// @notice Emitted when a yield source oracle configuration proposal is cancelled.
/// @param yieldSourceOracleId The identifier of the yield source oracle.
/// @param yieldSourceOracle The proposed oracle address.
/// @param feePercent The proposed fee percentage.
/// @param feeRecipient The proposed fee recipient.
/// @param manager The manager who proposed the change.
/// @param ledger The proposed ledger address.
event YieldSourceOracleConfigProposalCancelled(
bytes32 indexed yieldSourceOracleId,
address yieldSourceOracle,
uint256 feePercent,
address feeRecipient,
address manager,
address ledger
);
/*//////////////////////////////////////////////////////////////
EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Creates initial configurations for yield source oracles
/// @dev This function can only be used for first-time configuration setup
/// For existing configurations, use proposeYieldSourceOracleConfig instead
/// The caller becomes the manager for each new configuration
/// @param salts Array of salt values to generate unique identifiers
/// @param configs Array of initial oracle configurations to be created
function setYieldSourceOracles(bytes32[] calldata salts, YieldSourceOracleConfigArgs[] calldata configs) external;
/// @notice Proposes changes to existing yield source oracle configurations
/// @dev Only the current manager of a configuration can propose changes
/// Proposals are subject to a time-lock before they can be accepted
/// Fee percentage changes are limited to a maximum percentage change
/// @param yieldSourceOracleIds Array of yield source IDs to propose changes for
/// @param configs Array of proposed configuration changes
function proposeYieldSourceOracleConfig(
bytes32[] calldata yieldSourceOracleIds,
YieldSourceOracleConfigArgs[] calldata configs
)
external;
/// @notice Accepts previously proposed changes to yield source oracle configurations
/// @dev Can only be called by the manager after the time-lock period has passed
/// Accepting the proposal replaces the current configuration with the proposed one
/// @param yieldSourceOracleIds Array of yield source IDs with pending proposals to accept
function acceptYieldSourceOracleConfigProposal(bytes32[] calldata yieldSourceOracleIds) external;
/// @notice Initiates the transfer of manager role to a new address
/// @dev First step in a two-step process for transferring management rights
/// Only the current manager can initiate the transfer
/// The transfer must be accepted by the new manager to complete
/// @param yieldSourceOracleId The yield source oracle ID to transfer management of
/// @param newManager The address of the proposed new manager
function transferManagerRole(bytes32 yieldSourceOracleId, address newManager) external;
/// @notice Accepts the pending manager role transfer
/// @dev Second step in the two-step process for transferring management rights
/// Can only be called by the address designated as the pending manager
/// Completes the transfer, giving the caller full management rights
/// @param yieldSourceOracleId The yield source oracle ID to accept management of
function acceptManagerRole(bytes32 yieldSourceOracleId) external;
/// @notice Retrieves the current configuration for a yield source oracle
/// @dev Used by components that need oracle and fee information
/// Returns the complete configuration structure including all parameters
/// @param yieldSourceOracleId The unique identifier for the yield source oracle
/// @return Complete configuration struct for the specified yield source oracle
function getYieldSourceOracleConfig(bytes32 yieldSourceOracleId)
external
view
returns (YieldSourceOracleConfig memory);
/// @notice Retrieves configurations for multiple yield source oracles in a single call
/// @dev Batch version of getYieldSourceOracleConfig for gas efficiency
/// Returns an array of configurations in the same order as the input IDs
/// @param yieldSourceOracleIds Array of yield source oracle IDs to retrieve
/// @return configs Array of configuration structs for the specified yield source oracles
function getYieldSourceOracleConfigs(bytes32[] calldata yieldSourceOracleIds)
external
view
returns (YieldSourceOracleConfig[] memory configs);
/// @notice Retrieves all yield source oracle IDs owned by a specific address
/// @param owner The address to query for owned yield source oracle IDs
/// @return Array of yield source oracle IDs owned by the specified address
function getAllYieldSourceOracleIdsByOwner(address owner) external view returns (bytes32[] memory);
}
src/interfaces/accounting/IYieldSourceOracle.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
// Superform
import { IOracle } from "../../vendor/awesome-oracles/IOracle.sol";
/// @title IYieldSourceOracle
/// @author Superform Labs
/// @notice Interface for oracles that provide price and TVL data for yield-bearing assets
interface IYieldSourceOracle {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Error when array lengths do not match in batch operations
/// @dev Thrown when the lengths of input arrays in multi-asset operations don't match
error ARRAY_LENGTH_MISMATCH();
/// @notice Error when base asset is not valid for the yield source
/// @dev Thrown when attempting to use an asset that isn't supported by the yield source
error INVALID_BASE_ASSET();
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/// @notice Struct to hold local variables for getTVLMultipleUSD
/// @dev Used to manage complex computation state without stack-too-deep errors
/// These variables support the calculation of USD-denominated TVL values
/// across multiple yield sources and owners
struct TVLMultipleUSDVars {
/// @notice Number of yield sources being processed
uint256 length;
/// @notice Number of share owners being processed
uint256 ownersLength;
/// @notice Base amount in the underlying asset's native units
uint256 baseAmount;
/// @notice Accumulated TVL in USD for a specific user
uint256 userTvlUSD;
/// @notice Accumulated total TVL in USD across all sources
uint256 totalTvlUSD;
/// @notice Current yield source being processed
address yieldSource;
/// @notice Array of addresses that own shares in the yield source
address[] owners;
/// @notice Oracle registry used for price conversions
IOracle registry;
}
/*//////////////////////////////////////////////////////////////
VIEW METHODS
//////////////////////////////////////////////////////////////*/
/// @notice Returns the number of decimals of the yield source shares
/// @dev Critical for accurately interpreting share amounts and calculating prices
/// Different yield sources may have different decimal precision
/// @param yieldSourceAddress The address of the yield-bearing token contract
/// @return decimals The number of decimals used by the yield source's share token
function decimals(address yieldSourceAddress) external view returns (uint8);
/// @notice Calculates the number of shares that would be received for a given amount of assets
/// @dev Used for deposit simulations and to calculate current exchange rates
/// @param yieldSourceAddress The yield-bearing token address (e.g., aUSDC, cDAI)
/// @param assetIn The underlying asset being deposited (e.g., USDC, DAI)
/// @param assetsIn The amount of underlying assets to deposit, in the asset's native units
/// @return shares The number of yield-bearing shares that would be received
function getShareOutput(
address yieldSourceAddress,
address assetIn,
uint256 assetsIn
)
external
view
returns (uint256);
/// @notice Calculates the amount of shares that would be burnt when withdrawing a given amount of assets
/// @dev Used by oracles to simulate withdrawals and to derive the current exchange rate
/// @param yieldSourceAddress The address of the yield-bearing token (e.g., aUSDC, cDAI)
/// @param assetIn The address of the underlying asset to be withdrawn (e.g., USDC, DAI)
/// @param assetsIn The amount of underlying assets to withdraw, denominated in the asset’s native units
/// @return shares The amount of yield-bearing shares that would be burnt after withdrawal
function getWithdrawalShareOutput(
address yieldSourceAddress,
address assetIn,
uint256 assetsIn
)
external
view
returns (uint256);
/// @notice Calculates the number of underlying assets that would be received for a given amount of shares
/// @dev Used for withdrawal simulations and to calculate current yield
/// @param yieldSourceAddress The yield-bearing token address (e.g., aUSDC, cDAI)
/// @param assetIn The underlying asset to receive (e.g., USDC, DAI)
/// @param sharesIn The amount of yield-bearing shares to redeem
/// @return assets The number of underlying assets that would be received
function getAssetOutput(
address yieldSourceAddress,
address assetIn,
uint256 sharesIn
)
external
view
returns (uint256);
/// @notice Retrieves the current price per share in terms of the underlying asset
/// @dev Core function for calculating yields and determining returns
/// @param yieldSourceAddress The yield-bearing token address to get the price for
/// @return pricePerShare The current price per share in underlying asset terms, scaled by decimals
function getPricePerShare(address yieldSourceAddress) external view returns (uint256);
/// @notice Calculates the total value locked in a yield source by a specific owner
/// @dev Used to track individual position sizes within the system
/// @param yieldSourceAddress The yield-bearing token address to check
/// @param ownerOfShares The address owning the yield-bearing tokens
/// @return tvl The total value locked by the owner, in underlying asset terms
function getTVLByOwnerOfShares(address yieldSourceAddress, address ownerOfShares) external view returns (uint256);
/// @notice Gets the share balance of a specific owner in a yield source
/// @dev Returns raw share balance without converting to underlying assets
/// Used to track participation in the system and for accounting
/// @param yieldSourceAddress The yield-bearing token address
/// @param ownerOfShares The address to check the balance for
/// @return balance The number of yield-bearing tokens owned by the address
function getBalanceOfOwner(address yieldSourceAddress, address ownerOfShares) external view returns (uint256);
/// @notice Calculates the total value locked across all users in a yield source
/// @dev Critical for monitoring the size of each yield source in the system
/// @param yieldSourceAddress The yield-bearing token address to check
/// @return tvl The total value locked in the yield source, in underlying asset terms
function getTVL(address yieldSourceAddress) external view returns (uint256);
/// @notice Batch version of getPricePerShare for multiple yield sources
/// @dev Efficiently retrieves current prices for multiple yield sources
/// @param yieldSourceAddresses Array of yield-bearing token addresses
/// @return pricesPerShare Array of current prices for each yield source
function getPricePerShareMultiple(address[] memory yieldSourceAddresses)
external
view
returns (uint256[] memory pricesPerShare);
/// @notice Batch version of getTVLByOwnerOfShares for multiple yield sources and owners
/// @dev Efficiently calculates TVL for multiple owners across multiple yield sources
/// @param yieldSourceAddresses Array of yield-bearing token addresses
/// @param ownersOfShares 2D array where each sub-array contains owner addresses for a yield source
/// @return userTvls 2D array of TVL values for each owner in each yield source
function getTVLByOwnerOfSharesMultiple(
address[] memory yieldSourceAddresses,
address[][] memory ownersOfShares
)
external
view
returns (uint256[][] memory userTvls);
/// @notice Batch version of getTVL for multiple yield sources
/// @dev Efficiently calculates total TVL across multiple yield sources
/// @param yieldSourceAddresses Array of yield-bearing token addresses
/// @return tvls Array containing the total TVL for each yield source
function getTVLMultiple(address[] memory yieldSourceAddresses) external view returns (uint256[] memory tvls);
/// @notice Calculates the asset output with fees added for an outflow operation
/// @dev Gets the asset output from the oracle and adds any applicable fees
/// Uses try/catch to handle cases where oracle configuration doesn't exist
/// @param yieldSourceOracleId Identifier for the yield source oracle configuration
/// @param yieldSourceAddress Address of the yield-bearing asset
/// @param assetOut Address of the output asset
/// @param user Address of the user performing the outflow
/// @param usedShares Amount of shares being withdrawn
/// @return Total asset amount including fees
function getAssetOutputWithFees(
bytes32 yieldSourceOracleId,
address yieldSourceAddress,
address assetOut,
address user,
uint256 usedShares
)
external
view
returns (uint256);
}
src/vendor/awesome-oracles/IOracle.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
/// @title Common interface for price oracles.
/// @dev Implements the spec at https://eips.ethereum.org/EIPS/eip-7726
interface IOracle {
/// @notice The oracle does not support the given base/quote pair.
/// @param base The asset that the user needs to know the value or price for.
/// @param quote The asset in which the user needs to value or price the base.
error OracleUnsupportedPair(address base, address quote);
/// @notice The oracle is not capable to provide data within a degree of confidence.
/// @param base The asset that the user needs to know the value or price for.
/// @param quote The asset in which the user needs to value or price the base.
error OracleUntrustedData(address base, address quote);
/// @notice Returns the value of `baseAmount` of `base` in `quote` terms.
/// @dev MUST round down towards 0.
/// MUST revert with `OracleUnsupportedPair` if not capable to provide data for the specified `base` and `quote`
/// pair.
/// MUST revert with `OracleUntrustedData` if not capable to provide data within a degree of confidence publicly
/// specified.
/// @param baseAmount The amount of `base` to convert.
/// @param base The asset that the user needs to know the value for.
/// @param quote The asset in which the user needs to value the base.
/// @return quoteAmount The value of `baseAmount` of `base` in `quote` terms
function getQuote(uint256 baseAmount, address base, address quote) external view returns (uint256 quoteAmount);
}
src/vendor/chainlink/IChainlinkProxyAggregator.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
/// @dev Minimal interface for Chainlink proxy to access underlying aggregator
interface IChainlinkProxy {
function aggregator() external view returns (address);
}
/// @dev Minimal interface for Chainlink aggregator circuit breaker bounds
interface IChainlinkAggregator {
function minAnswer() external view returns (int192);
function maxAnswer() external view returns (int192);
}
src/vendor/uniswap/v3/CLLiquidityAmounts.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.30;
// External
import { FullMath } from "v4-core/libraries/FullMath.sol";
/// @title CLLiquidityAmounts
/// @notice Helpers for computing liquidity amounts from token amounts and prices for Uniswap V3-style CL pools
/// @dev Vendored from Uniswap V3 Periphery / Uniswap V4 core test utils.
/// Original: https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/LiquidityAmounts.sol
library CLLiquidityAmounts {
/// @notice Thrown when a uint256 value cannot be safely downcast to uint128
error LIQUIDITY_OVERFLOW();
uint256 internal constant Q96 = 0x1000000000000000000000000;
/// @notice Downcasts uint256 to uint128 (reverts on overflow)
function toUint128(uint256 x) private pure returns (uint128 y) {
y = uint128(x);
if (uint256(y) != x) revert LIQUIDITY_OVERFLOW();
}
/// @notice Computes the amount of liquidity for a given amount of token0 and price range
function getLiquidityForAmount0(
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint256 amount0
)
internal
pure
returns (uint128 liquidity)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
uint256 intermediate = FullMath.mulDiv(sqrtPriceAX96, sqrtPriceBX96, Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtPriceBX96 - sqrtPriceAX96));
}
/// @notice Computes the amount of liquidity for a given amount of token1 and price range
function getLiquidityForAmount1(
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint256 amount1
)
internal
pure
returns (uint128 liquidity)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return toUint128(FullMath.mulDiv(amount1, Q96, sqrtPriceBX96 - sqrtPriceAX96));
}
/// @notice Computes the maximum amount of liquidity for given amounts of token0, token1 and prices
function getLiquidityForAmounts(
uint160 sqrtPriceX96,
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint256 amount0,
uint256 amount1
)
internal
pure
returns (uint128 liquidity)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
if (sqrtPriceX96 <= sqrtPriceAX96) {
liquidity = getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0);
} else if (sqrtPriceX96 < sqrtPriceBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, sqrtPriceBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
function getAmount0ForLiquidity(
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint128 liquidity
)
internal
pure
returns (uint256 amount0)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return FullMath.mulDiv(uint256(liquidity) << 96, sqrtPriceBX96 - sqrtPriceAX96, sqrtPriceBX96) / sqrtPriceAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
function getAmount1ForLiquidity(
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint128 liquidity
)
internal
pure
returns (uint256 amount1)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity
/// @param sqrtPriceX96 Current pool sqrtPrice
/// @param sqrtPriceAX96 Lower tick boundary sqrtPrice
/// @param sqrtPriceBX96 Upper tick boundary sqrtPrice
/// @param liquidity Liquidity to value
/// @return amount0 Amount of token0
/// @return amount1 Amount of token1
function getAmountsForLiquidity(
uint160 sqrtPriceX96,
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint128 liquidity
)
internal
pure
returns (uint256 amount0, uint256 amount1)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
if (sqrtPriceX96 <= sqrtPriceAX96) {
amount0 = getAmount0ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
} else if (sqrtPriceX96 < sqrtPriceBX96) {
amount0 = getAmount0ForLiquidity(sqrtPriceX96, sqrtPriceBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
}
}
}
src/vendor/uniswap/v3/INonfungiblePositionManager.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
/// @title INonfungiblePositionManager
/// @notice Minimal interface for UniV3-compatible NFT position managers
/// @dev Compatible with:
/// - Uniswap V3 NonfungiblePositionManager (fee at position[4])
/// - Aerodrome Slipstream NonfungiblePositionManager (tickSpacing at position[4])
/// NOT compatible with Algebra / SparkDEX which omits the fee/tickSpacing field entirely
/// (use a separate Algebra-specific interface for those DEXes).
///
/// ABI note: both UniV3 and Slipstream place a uint24/int24 value at the same byte offset
/// before tickLower, so decoding is correct for both even though the field meaning differs.
interface INonfungiblePositionManager {
/// @notice Returns the position information associated with a given token ID
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The approved address of the token
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return feeOrTickSpacing The fee tier (UniV3) or tick spacing (Slipstream) of the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The upper end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 feeOrTickSpacing,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns the number of NFT positions owned by a given address
function balanceOf(address owner) external view returns (uint256);
/// @notice Returns the tokenId at a given index of the positions list for the given owner
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
}
src/vendor/uniswap/v3/IUniswapV3CLPool.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
/// @title IUniswapV3CLPool
/// @notice Minimal interface for Uniswap V3-compatible concentrated liquidity pools
/// @dev Compatible with UniV3, Aerodrome Slipstream, and other UniV3 forks.
/// For Algebra (SparkDEX), globalState() replaces slot0() but tick/sqrtPrice are
/// accessible similarly — a separate oracle variant is needed for Algebra pools.
interface IUniswapV3CLPool {
/// @notice The current state of the pool
/// @return sqrtPriceX96 The current price as a sqrt(token1/token0) Q64.96 value
/// @return tick The current tick
/// @dev Only the first two return values are declared here; additional values (observationIndex,
/// observationCardinality, etc.) vary between UniV3 (7 fields) and Aerodrome Slipstream
/// (6 fields, no feeProtocol). Declaring only 2 fields is forward-compatible with both:
/// Solidity ABI decoder accepts return data that is larger than the declared size.
function slot0() external view returns (uint160 sqrtPriceX96, int24 tick);
/// @notice The currently in-range liquidity available to the pool
/// @dev Only reflects liquidity positions spanning the current tick
function liquidity() external view returns (uint128);
/// @notice The first of the two tokens of the pool, sorted by address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
function token1() external view returns (address);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value
function tickSpacing() external view returns (int24);
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "none"
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@ERC4337/=lib/modulekit/node_modules/@ERC4337/",
"@account-abstraction/=lib/modulekit/node_modules/account-abstraction/contracts/",
"@biconomy/=lib/nexus/node_modules/@biconomy/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@erc7579/=lib/nexus/node_modules/@erc7579/",
"@gnosis.pm/=lib/nexus/node_modules/@gnosis.pm/",
"@memview-sol/=lib/evm-gateway-contracts/lib/memview-sol/contracts/",
"@nexus/=lib/nexus/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@pendle/=lib/pendle-core-v2-public/contracts/",
"@pigeon/=lib/pigeon/src/",
"@prb/math/=lib/modulekit/node_modules/@prb/math/src/",
"@rhinestone/erc4337-validation/=lib/modulekit/node_modules/@rhinestone/erc4337-validation/",
"@safe-global/=lib/nexus/node_modules/@safe-global/",
"@safe/=lib/safe-smart-account/contracts/",
"@safe7579/=lib/safe7579/src/",
"@solady/=lib/solady/",
"@stringutils/=lib/solidity-stringutils/src/",
"@surl/=lib/surl/src/",
"@zerodev/=lib/nexus/node_modules/@zerodev/",
"ExcessivelySafeCall/=lib/ExcessivelySafeCall/src/",
"account-abstraction-v0.6/=lib/modulekit/node_modules/@ERC4337/account-abstraction-v0.6/contracts/",
"account-abstraction/=lib/modulekit/node_modules/@ERC4337/account-abstraction/contracts/",
"checknsignatures/=lib/checknsignatures/src/",
"composability/=lib/nexus/node_modules/@biconomy/composability/contracts/",
"ds-test/=lib/nexus/node_modules/ds-test/",
"enumerableset4337/=lib/nexus/node_modules/erc7739-validator-base/node_modules/@erc7579/enumerablemap4337/src/",
"erc4337-validation/=lib/modulekit/node_modules/@rhinestone/erc4337-validation/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"erc7579/=lib/nexus/node_modules/erc7579/",
"erc7739-validator-base/=lib/nexus/node_modules/erc7739-validator-base/",
"erc7739Validator/=lib/nexus/node_modules/erc7739-validator-base/src/",
"eth-gas-reporter/=lib/nexus/node_modules/eth-gas-reporter/",
"evm-gateway-contracts/=lib/evm-gateway-contracts/",
"evm-gateway/=lib/evm-gateway-contracts/src/",
"excessively-safe-call/=lib/ExcessivelySafeCall/src/",
"excessivelySafeCall/=lib/ExcessivelySafeCall/src/",
"forge-std/=lib/modulekit/node_modules/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat-deploy/=lib/nexus/node_modules/hardhat-deploy/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"kernel/=lib/nexus/node_modules/erc7739-validator-base/node_modules/@zerodev/kernel/src/",
"memview-sol/=lib/evm-gateway-contracts/lib/memview-sol/contracts/",
"module-bases/=lib/safe7579/node_modules/@rhinestone/module-bases/src/",
"modulekit/=lib/modulekit/src/",
"nexus/=lib/nexus/",
"openzeppelin-contracts-upgradeable/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"pendle-core-v2-public/=lib/pendle-core-v2-public/contracts/",
"pigeon/=lib/pigeon/src/",
"prep/=lib/nexus/node_modules/prep/",
"rhinestone/checknsignatures/=lib/checknsignatures/",
"safe-smart-account/=lib/safe-smart-account/",
"safe7579/=lib/safe7579/",
"sentinellist/=lib/nexus/node_modules/sentinellist/src/",
"solady/=lib/nexus/node_modules/solady/src/",
"solarray/=lib/nexus/node_modules/solarray/src/",
"solidity-stringutils/=lib/solidity-stringutils/",
"solmate/=lib/v4-core/lib/solmate/",
"surl/=lib/surl/",
"test/mock_fiattoken/=lib/evm-gateway-contracts/test/mock_fiattoken/",
"v4-core/=lib/v4-core/src/",
"lib/evm-gateway-contracts:src/=lib/evm-gateway-contracts/src/",
"lib/evm-gateway-contracts:test/=lib/evm-gateway-contracts/test/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.