Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/modules/YieldModule.sol": {
"content": "// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.20;
import {PausableUpgradeable} from "openzeppelin-contracts-upgradeable/utils/PausableUpgradeable.sol";
import {Math} from "openzeppelin-contracts/utils/math/Math.sol";
import {SafeCast} from "openzeppelin-contracts/utils/math/SafeCast.sol";
import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IAggregator} from "src/interfaces/oracles/IAggregator.sol";
import {IYieldModule} from "src/interfaces/modules/IYieldModule.sol";
import {IRegistryContract} from "src/interfaces/registry/IRegistryContract.sol";
import {IRegistryAccess} from "src/interfaces/registry/IRegistryAccess.sol";
import {CheckAccessControl} from "src/utils/CheckAccessControl.sol";
import {IOracle} from "src/interfaces/oracles/IOracle.sol";
import {ITokenMapping} from "src/interfaces/tokenManager/ITokenMapping.sol";
import {
YIELD_MODULE_TOKENOMICS_OPERATOR_ROLE,
YIELD_MODULE_SUPER_ADMIN_ROLE,
YIELD_MODULE_P90_INTEREST_ROLE,
YIELD_MODULE_MAX_DATA_AGE_ROLE,
YIELD_MODULE_UPDATER_ROLE,
PAUSING_CONTRACTS_ROLE,
DEFAULT_ADMIN_ROLE,
DEFAULT_YIELD_FEED_RATE,
INITIAL_YIELD_MODULE_MAX_DATA_AGE,
CONTRACT_REGISTRY_ACCESS,
CONTRACT_ORACLE,
CONTRACT_TOKEN_MAPPING,
BASIS_POINT_BASE
} from "src/constants.sol";
import {
YieldSourceNotFound,
YieldSourceDataTooOld,
YieldSourceAlreadyExists,
NullContract,
MaxDataAgeZero,
InvalidFeed,
NullAddress,
SameValue,
InvalidWeeklyInterestBps,
TreasuryAlreadyExists,
TreasuryNotFound,
InvalidInput
} from "src/errors.sol";
/// @title Eur0 YieldModule
/// @notice Contract for blending various assets in treasury interest rates.
/// @dev Uses Chainlink V3 interfaces for oracle data and manual overrides for fallback
contract YieldModule is PausableUpgradeable, IYieldModule {
using CheckAccessControl for IRegistryAccess;
using SafeCast for int256;
using SafeCast for uint256;
/*//////////////////////////////////////////////////////////////
Events
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a new YieldSource is added.
event YieldSourceAdded(
address indexed asset, address indexed feedAddress, uint256 weeklyInterestBps
);
/// @notice Emitted when a YieldSource is removed.
event YieldSourceRemoved(address indexed asset);
/// @notice Emitted when a YieldSource interest rate is updated.
event InterestRateUpdated(address indexed asset, uint256 weeklyInterestBps);
/// @notice Emitted when a YieldSource interest rate is overridden.
event InterestRateOverridden(address indexed asset, uint256 weeklyInterestBps);
/// @notice Emitted when an YieldSource feed is updated.
event FeedUpdated(address indexed asset, address indexed feedAddress);
/// @notice Emitted when the maximum data age is set.
event MaxDataAgeSet(uint256 maxDataAge);
/// @notice Emitted when the P90 interest rate is set.
event P90InterestRateSet(uint256 p90Rate);
/// @notice Emitted when a treasury is removed.
event TreasuryRemoved(address indexed treasury);
/// @notice Emitted when a treasury is added.
event TreasuryAdded(address indexed treasury);
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*/
/// @custom:storage-location erc7201:YieldModule.storage.v0
struct YieldModuleStorageV0 {
/// The address of the registry contract.
IRegistryContract registryContract;
/// The address of the registry access contract.
IRegistryAccess registryAccess;
/// The address of the oracle contract.
IOracle oracle;
/// The address of the token mapping contract.
ITokenMapping tokenMapping;
/// Maximum data age
uint256 maxDataAge;
/// P90 interest rate
uint256 p90Rate;
/// Mapping of yield sources
mapping(address => YieldSourceData) yieldSources;
/// Array of treasury addresses
address[] treasuries;
}
// keccak256(abi.encode(uint256(keccak256("YieldModule.storage.v0")) - 1)) & ~bytes32(uint256(0xff))
// solhint-disable-next-line
bytes32 public constant YieldModuleStorageV0Location =
0x78c0d34884bf8d0cac6810bafad21ac3cbbe678f28b9d1e3ae3dde64377fa000;
/*//////////////////////////////////////////////////////////////
Constructor
//////////////////////////////////////////////////////////////*/
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/// @notice Initializes the contract with a registry contract
/// @param registryContract Address of the registry contract for contracts management.
function initialize(address registryContract) public initializer {
if (registryContract == address(0)) {
revert NullContract();
}
if (INITIAL_YIELD_MODULE_MAX_DATA_AGE == 0) {
revert MaxDataAgeZero();
}
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
__Pausable_init_unchained();
$.registryContract = IRegistryContract(registryContract);
$.registryAccess = IRegistryAccess($.registryContract.getContract(CONTRACT_REGISTRY_ACCESS));
$.oracle = IOracle($.registryContract.getContract(CONTRACT_ORACLE));
$.tokenMapping = ITokenMapping($.registryContract.getContract(CONTRACT_TOKEN_MAPPING));
$.maxDataAge = INITIAL_YIELD_MODULE_MAX_DATA_AGE;
emit MaxDataAgeSet($.maxDataAge);
}
/*//////////////////////////////////////////////////////////////
External
//////////////////////////////////////////////////////////////*/
/// @notice Pauses all yield module operations.
/// @dev Can only be called by an account with the PAUSING_CONTRACTS_ROLE.
function pause() external {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
$.registryAccess.onlyMatchingRole(PAUSING_CONTRACTS_ROLE);
_pause();
}
/// @notice Unpauses all yield module operations.
/// @dev Can only be called by an account with the DEFAULT_ADMIN_ROLE.
function unpause() external {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
$.registryAccess.onlyMatchingRole(DEFAULT_ADMIN_ROLE);
_unpause();
}
/// @inheritdoc IYieldModule
function addYieldSourceWithFeed(address asset, address feedAddress) external whenNotPaused {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
$.registryAccess.onlyMatchingRole(YIELD_MODULE_TOKENOMICS_OPERATOR_ROLE);
_validateFeedInterface(feedAddress);
_validateAndCreateYieldSource(asset, feedAddress, DEFAULT_YIELD_FEED_RATE);
}
/// @inheritdoc IYieldModule
function addYieldSourceWithWeeklyInterest(address asset, uint256 weeklyInterestBps)
external
whenNotPaused
{
if (weeklyInterestBps > BASIS_POINT_BASE) {
revert InvalidWeeklyInterestBps();
}
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
$.registryAccess.onlyMatchingRole(YIELD_MODULE_TOKENOMICS_OPERATOR_ROLE);
_validateAndCreateYieldSource(asset, address(0), weeklyInterestBps);
}
/// @inheritdoc IYieldModule
function removeYieldSource(address asset) external whenNotPaused {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
$.registryAccess.onlyMatchingRole(YIELD_MODULE_SUPER_ADMIN_ROLE);
if ($.yieldSources[asset].lastUpdated == 0) {
revert YieldSourceNotFound();
}
delete $.yieldSources[asset];
emit YieldSourceRemoved(asset);
}
/// @inheritdoc IYieldModule
function removeTreasury(address treasury) external whenNotPaused {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
$.registryAccess.onlyMatchingRole(YIELD_MODULE_SUPER_ADMIN_ROLE);
bool found = false;
for (uint256 i = 0; i < $.treasuries.length;) {
if ($.treasuries[i] == treasury) {
// Move last treasury to current position, treasury order is not important
$.treasuries[i] = $.treasuries[$.treasuries.length - 1];
$.treasuries.pop();
emit TreasuryRemoved(treasury);
found = true;
break;
}
unchecked {
++i;
}
}
if (!found) {
revert TreasuryNotFound();
}
}
/// @inheritdoc IYieldModule
function addTreasury(address treasury) external whenNotPaused {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
$.registryAccess.onlyMatchingRole(YIELD_MODULE_SUPER_ADMIN_ROLE);
if (treasury == address(0)) {
revert NullAddress();
}
for (uint256 i = 0; i < $.treasuries.length;) {
if ($.treasuries[i] == treasury) {
revert TreasuryAlreadyExists();
}
unchecked {
++i;
}
}
$.treasuries.push(treasury);
emit TreasuryAdded(treasury);
}
/// @inheritdoc IYieldModule
function updateInterestRate(address asset, uint256 weeklyInterestBps) external whenNotPaused {
if (weeklyInterestBps > BASIS_POINT_BASE) {
revert InvalidWeeklyInterestBps();
}
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
$.registryAccess.onlyMatchingRole(YIELD_MODULE_UPDATER_ROLE);
YieldSourceData storage source = _getYieldSource(asset);
// If the yield source is using an oracle, we need to override the interest rate
if (source.feed != IAggregator(address(0))) {
source.weeklyInterestBps = weeklyInterestBps;
source.lastUpdated = block.timestamp;
source.feed = IAggregator(address(0)); // disable oracle until next manual update
emit InterestRateOverridden(asset, source.weeklyInterestBps);
} else {
// If the yield source is using a manual rate (no oracle), update the interest rate
source.weeklyInterestBps = weeklyInterestBps;
source.lastUpdated = block.timestamp;
emit InterestRateUpdated(asset, source.weeklyInterestBps);
}
}
/// @inheritdoc IYieldModule
function updateFeed(address asset, address feedAddress) external whenNotPaused {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
$.registryAccess.onlyMatchingRole(YIELD_MODULE_UPDATER_ROLE);
YieldSourceData storage source = _getYieldSource(asset);
_validateFeedInterface(feedAddress);
source.feed = IAggregator(feedAddress);
source.lastUpdated = block.timestamp;
if (source.weeklyInterestBps != 0) {
source.weeklyInterestBps = 0;
}
emit FeedUpdated(asset, feedAddress);
}
/// @inheritdoc IYieldModule
function setMaxDataAge(uint256 maxDataAge) external whenNotPaused {
if (maxDataAge == 0) revert MaxDataAgeZero();
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
$.registryAccess.onlyMatchingRole(YIELD_MODULE_MAX_DATA_AGE_ROLE);
if ($.maxDataAge == maxDataAge) revert SameValue();
$.maxDataAge = maxDataAge;
emit MaxDataAgeSet($.maxDataAge);
}
/// @inheritdoc IYieldModule
function setP90InterestRate(uint256 p90Rate) external whenNotPaused {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
$.registryAccess.onlyMatchingRole(YIELD_MODULE_P90_INTEREST_ROLE);
// P90 rate should be less than 10000 basis points
if (p90Rate == 0 || p90Rate >= BASIS_POINT_BASE) {
revert InvalidInput();
}
if ($.p90Rate == p90Rate) revert SameValue();
$.p90Rate = p90Rate;
emit P90InterestRateSet(p90Rate);
}
/// @inheritdoc IYieldModule
function getMaxDataAge() external view returns (uint256) {
return _yieldModuleStorageV0().maxDataAge;
}
/// @inheritdoc IYieldModule
function getBlendedWeeklyInterest() public view whenNotPaused returns (uint256 blendedRate) {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
uint256 totalValue = 0;
uint256 weightedSum = 0;
address[] memory rwas = $.tokenMapping.getAllEur0CollateralTokens();
// Iterate over each stored rwa/asset.
for (uint256 i = 0; i < rwas.length;) {
address rwa = rwas[i];
// fetch the current interest rate from the oracle feed
// go over all treasuries to calculate the total rwa balance across all treasuries
(uint256 rate, uint256 balance) = _getYieldSourceRateAndAmount(rwa);
if (balance > 0) {
uint256 price = $.oracle.getPrice(rwa);
uint8 decimals = IERC20Metadata(rwa).decimals();
// update the totalValue in USD accordingly
uint256 assetValue = Math.mulDiv(price, balance, 10 ** decimals);
totalValue += assetValue;
// Update the weightedSum accordingly.
weightedSum += rate * assetValue;
}
unchecked {
++i;
}
}
// calculate the weeklyBlendedInterestRate
blendedRate =
totalValue > 0 ? Math.mulDiv(weightedSum, 1, totalValue, Math.Rounding.Floor) : 0;
if (blendedRate > BASIS_POINT_BASE) revert InvalidWeeklyInterestBps();
}
/// @inheritdoc IYieldModule
function getP90InterestRate() public view whenNotPaused returns (uint256) {
return _yieldModuleStorageV0().p90Rate;
}
/// @inheritdoc IYieldModule
function getYieldSource(address asset) external view returns (YieldSourceData memory) {
return _getYieldSource(asset);
}
/// @inheritdoc IYieldModule
function getYieldSourceCount() external view returns (uint256) {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
address[] memory rwas = $.tokenMapping.getAllEur0CollateralTokens();
uint256 count = 0;
for (uint256 i = 0; i < rwas.length;) {
if ($.yieldSources[rwas[i]].lastUpdated != 0) {
unchecked {
++count;
}
}
unchecked {
++i;
}
}
return count;
}
/// @inheritdoc IYieldModule
function getAllYieldSourceData() external view returns (YieldSourceData[] memory) {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
address[] memory rwas = $.tokenMapping.getAllEur0CollateralTokens();
uint256 count = 0;
// First count valid yield sources
for (uint256 i = 0; i < rwas.length;) {
if ($.yieldSources[rwas[i]].lastUpdated != 0) {
unchecked {
++count;
}
}
unchecked {
++i;
}
}
YieldSourceData[] memory yieldSources = new YieldSourceData[](count);
count = 0;
// Then populate the array
for (uint256 i = 0; i < rwas.length;) {
address rwa = rwas[i];
if ($.yieldSources[rwa].lastUpdated != 0) {
yieldSources[count] = $.yieldSources[rwa];
unchecked {
++count;
}
}
unchecked {
++i;
}
}
return yieldSources;
}
/// @inheritdoc IYieldModule
function getTreasuryCount() external view returns (uint256) {
return _yieldModuleStorageV0().treasuries.length;
}
/// @inheritdoc IYieldModule
function getAllTreasury() external view returns (address[] memory) {
return _yieldModuleStorageV0().treasuries;
}
/*//////////////////////////////////////////////////////////////
Internal
//////////////////////////////////////////////////////////////*/
/// @notice Returns the storage struct of the contract.
/// @return $ .
function _yieldModuleStorageV0() internal pure returns (YieldModuleStorageV0 storage $) {
bytes32 position = YieldModuleStorageV0Location;
// solhint-disable-next-line no-inline-assembly
assembly {
$.slot := position
}
}
/// @notice Creates a new yield source
/// @param asset The address of the asset
/// @param feed The address of the feed
/// @param rate The rate of the yield source
function _validateAndCreateYieldSource(address asset, address feed, uint256 rate) private {
if (asset == address(0)) revert NullAddress();
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
if ($.yieldSources[asset].lastUpdated != 0) {
revert YieldSourceAlreadyExists();
}
$.yieldSources[asset] = YieldSourceData({
feed: IAggregator(feed),
weeklyInterestBps: rate,
lastUpdated: block.timestamp
});
emit YieldSourceAdded(asset, feed, rate);
}
/// @notice Validates Chainlink feed contract interface
/// @param feedAddress The address of the feed contract
function _validateFeedInterface(address feedAddress) private view {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
// Fetch the latest round data from the feed
// slither-disable-next-line unused-return
(,,, uint256 updatedAt, uint80 answeredInRound) = IAggregator(feedAddress).latestRoundData();
// Validate the feed data integrity
if (answeredInRound == 0 || updatedAt == 0) revert InvalidFeed();
// Ensure data is recent enough
if (block.timestamp - updatedAt > $.maxDataAge) {
revert YieldSourceDataTooOld();
}
}
/// @notice Returns the yield source data for a given asset address
/// @param asset The address of the asset to get the yield source data for
/// @return source The yield source data
function _getYieldSource(address asset) private view returns (YieldSourceData storage) {
if (asset == address(0)) revert NullAddress();
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
if ($.yieldSources[asset].lastUpdated == 0) {
revert YieldSourceNotFound();
}
return $.yieldSources[asset];
}
/// @notice Returns the latest valid rate and amount for an yield source in USD
/// @param asset The address of the asset to get the yield source data for
/// @return rate The latest valid rate for the yield source
/// @return amount The asset amount across all treasuries
function _getYieldSourceRateAndAmount(address asset)
private
view
returns (uint256 rate, uint256 amount)
{
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
YieldSourceData memory source = _getYieldSource(asset);
// Try to get oracle rate first
if (source.feed != IAggregator(address(0))) {
// slither-disable-next-line unused-return
(, int256 oracleRate,, uint256 updatedAt,) = source.feed.latestRoundData();
if (updatedAt == 0) revert InvalidFeed();
if (block.timestamp - updatedAt > $.maxDataAge) {
revert YieldSourceDataTooOld();
}
if (oracleRate < 0) oracleRate = 0;
rate = oracleRate.toUint256();
if (rate > BASIS_POINT_BASE) revert InvalidWeeklyInterestBps();
} else {
if (block.timestamp - source.lastUpdated > $.maxDataAge) {
revert YieldSourceDataTooOld();
}
rate = source.weeklyInterestBps;
}
amount = _getAssetBacking(asset);
}
/// @notice Calculates the backing amount of an asset inside our treasuries
/// @param asset The address of the asset to calculate the backing amount for
/// @return totalAmount The backing amount of the asset sitting in our treasuries
function _getAssetBacking(address asset) internal view returns (uint256) {
YieldModuleStorageV0 storage $ = _yieldModuleStorageV0();
uint256 totalAmount = 0;
for (uint256 i = 0; i < $.treasuries.length;) {
address treasury = $.treasuries[i];
totalAmount += IERC20(asset).balanceOf(treasury);
unchecked {
++i;
}
}
return totalAmount;
}
}
"
},
"lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}
"
},
"lib/openzeppelin-contracts/contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return 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.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev 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 {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// 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 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 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 prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, 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 {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
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 for
// four bits. That is, denominator * inv = 1 mod 2^4.
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^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // 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 * inverse;
return result;
}
}
/**
* @notice 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) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @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 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @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": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 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) {
Submitted on: 2025-10-25 19:23:16
Comments
Log in to comment.
No comments yet.