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/hooks/ProcessAccountingGuardHook.sol": {
"content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
import {IHooks} from "lib/yieldnest-vault/src/interface/IHooks.sol";
import {IVault} from "lib/yieldnest-vault/src/interface/IVault.sol";
import {Math} from "lib/openzeppelin-contracts/contracts/utils/math/Math.sol";
/**
* @title ProcessAccountingGuardHook
* @notice This hook is used to check for excessive totalAssets changes
* when calling the processAccounting function for the vault.
* It checks if the total assets decreased too much or increased too much.
* It is used to prevent the vault from being exposed to anomalous totalAssets fluctuations.
* which can be a result of oracle manipulation or 3rd party protocol failures.
* the processAccounting call reverts if the totalAssets changed too much.
*/
contract ProcessAccountingGuardHook is IHooks {
using Math for uint256;
string public constant VERSION = "0.1.1";
error TotalAssetsDecreasedTooMuch(
uint256 totalAssetsBefore, uint256 totalAssetsAfter, uint256 maxTotalAssetsDecreaseRatio
);
error TotalAssetsIncreasedTooMuch(
uint256 totalAssetsBefore, uint256 totalAssetsAfter, uint256 maxTotalAssetsIncreaseRatio
);
error OnlyOwner();
error NotSupported();
error OnlyVault();
error TotalSupplyDecreased();
error TotalSupplyIncreasedForLoss();
error TotalSupplyIncreasedTooMuch(uint256 totalSupplyBefore, uint256 totalSupplyAfter);
error AlwaysComputeTotalAssetsIsEnabled();
event MaxTotalAssetsDecreaseRatioSet(uint256 oldRatio, uint256 newRatio);
event MaxTotalAssetsIncreaseRatioSet(uint256 oldRatio, uint256 newRatio);
event MaxTotalSupplyIncreaseRatioSet(uint256 oldRatio, uint256 newRatio);
event ExpectedPerformanceFeeSet(uint256 oldFee, uint256 newFee);
uint256 public constant RATIO_DENOMINATOR = 1e18;
uint256 public constant FEE_DENOMINATOR = 1e18;
IVault public immutable VAULT;
/// @notice The owner controls configuration settings
address public immutable owner;
/// @notice The maximum total assets decrease ratio during processAccounting()
uint256 public maxTotalAssetsDecreaseRatio; // as a ratio with RATIO_DENOMINATOR (1e18 = 100%)
/// @notice The maximum total assets increase ratio during processAccounting()
uint256 public maxTotalAssetsIncreaseRatio; // as a ratio with RATIO_DENOMINATOR (1e18 = 100%)
/// @notice The maximum total supply increase ratio during processAccounting()
uint256 public maxTotalSupplyIncreaseRatio; // as a ratio with RATIO_DENOMINATOR (1e18 = 100%)
uint256 public expectedPerformanceFee;
modifier onlyOwner() {
if (msg.sender != owner) revert OnlyOwner();
_;
}
modifier onlyVault() {
if (msg.sender != address(VAULT)) revert OnlyVault();
_;
}
/**
* @notice Constructor
* @param _vault The address of the vault
* @param _owner The address of the owner
* @param _maxTotalAssetsDecreaseRatio The maximum total assets decrease ratio
* @param _maxTotalAssetsIncreaseRatio The maximum total assets increase ratio
* @param _maxTotalSupplyIncreaseRatio The maximum total supply increase ratio
* @param _expectedPerformanceFee The expected performance fee
*/
constructor(
address _vault,
address _owner,
uint256 _maxTotalAssetsDecreaseRatio,
uint256 _maxTotalAssetsIncreaseRatio,
uint256 _maxTotalSupplyIncreaseRatio,
uint256 _expectedPerformanceFee
) {
VAULT = IVault(_vault);
owner = _owner;
maxTotalAssetsDecreaseRatio = _maxTotalAssetsDecreaseRatio;
maxTotalAssetsIncreaseRatio = _maxTotalAssetsIncreaseRatio;
maxTotalSupplyIncreaseRatio = _maxTotalSupplyIncreaseRatio;
expectedPerformanceFee = _expectedPerformanceFee;
}
/// @inheritdoc IHooks
function name() external pure returns (string memory) {
return "ProcessAccountingGuardHook";
}
/**
* @notice Set the maximum totalAssets decrease ratio
* @param _maxTotalAssetsDecreaseRatio The maximum totalAssets decrease ratio
*/
function setMaxTotalAssetsDecreaseRatio(uint256 _maxTotalAssetsDecreaseRatio) external onlyOwner {
uint256 old = maxTotalAssetsDecreaseRatio;
maxTotalAssetsDecreaseRatio = _maxTotalAssetsDecreaseRatio;
emit MaxTotalAssetsDecreaseRatioSet(old, _maxTotalAssetsDecreaseRatio);
}
/**
* @notice Set the maximum totalAssets increase ratio
* @param _maxTotalAssetsIncreaseRatio The maximum totalAssets increase ratio
*/
function setMaxTotalAssetsIncreaseRatio(uint256 _maxTotalAssetsIncreaseRatio) external onlyOwner {
uint256 old = maxTotalAssetsIncreaseRatio;
maxTotalAssetsIncreaseRatio = _maxTotalAssetsIncreaseRatio;
emit MaxTotalAssetsIncreaseRatioSet(old, _maxTotalAssetsIncreaseRatio);
}
/**
* @notice Set the maximum totalSupply increase ratio
* @param _maxTotalSupplyIncreaseRatio The maximum totalSupply increase ratio
*/
function setMaxTotalSupplyIncreaseRatio(uint256 _maxTotalSupplyIncreaseRatio) external onlyOwner {
uint256 old = maxTotalSupplyIncreaseRatio;
maxTotalSupplyIncreaseRatio = _maxTotalSupplyIncreaseRatio;
emit MaxTotalSupplyIncreaseRatioSet(old, _maxTotalSupplyIncreaseRatio);
}
/**
* @notice Set the expected performance fee
* @param _expectedPerformanceFee The expected performance fee
*/
function setExpectedPerformanceFee(uint256 _expectedPerformanceFee) external onlyOwner {
uint256 old = expectedPerformanceFee;
expectedPerformanceFee = _expectedPerformanceFee;
emit ExpectedPerformanceFeeSet(old, _expectedPerformanceFee);
}
function getConfig() external pure override returns (Config memory) {
return Config({
beforeDeposit: false,
afterDeposit: false,
beforeMint: false,
afterMint: false,
beforeRedeem: false,
afterRedeem: false,
beforeWithdraw: false,
afterWithdraw: false,
beforeProcessAccounting: false,
afterProcessAccounting: true
});
}
/// @inheritdoc IHooks
function setConfig(Config memory) external pure override {
revert NotSupported();
}
/**
* @notice Check if the total assets decreased too much or increased too much
*/
function afterProcessAccounting(AfterProcessAccountingParams memory params) external view override onlyVault {
if (VAULT.alwaysComputeTotalAssets()) {
revert AlwaysComputeTotalAssetsIsEnabled();
}
if (params.totalAssetsBeforeAccounting == 0) return; // Skip check if starting from zero
checkTotalAssetsChange(params);
checkTotalSupplyChange(params);
}
/**
* @notice Check if the total assets changed too much to the downside or upside
* @dev This check protects against anomalous rate changes for the vault.
* @dev Prevents processAccounting from running if totalAssets change falls outside bounds.
* @param params The parameters for the afterProcessAccounting function
*/
function checkTotalAssetsChange(AfterProcessAccountingParams memory params) public view {
if (params.totalAssetsAfterAccounting < params.totalAssetsBeforeAccounting) {
// Check for excessive decrease
uint256 decrease = params.totalAssetsBeforeAccounting - params.totalAssetsAfterAccounting;
uint256 decreaseRatio = (decrease * RATIO_DENOMINATOR) / params.totalAssetsBeforeAccounting;
if (decreaseRatio > maxTotalAssetsDecreaseRatio) {
revert TotalAssetsDecreasedTooMuch(
params.totalAssetsBeforeAccounting, params.totalAssetsAfterAccounting, maxTotalAssetsDecreaseRatio
);
}
} else if (params.totalAssetsAfterAccounting > params.totalAssetsBeforeAccounting) {
// Check for excessive increase
uint256 increase = params.totalAssetsAfterAccounting - params.totalAssetsBeforeAccounting;
uint256 increaseRatio = (increase * RATIO_DENOMINATOR) / params.totalAssetsBeforeAccounting;
if (increaseRatio > maxTotalAssetsIncreaseRatio) {
revert TotalAssetsIncreasedTooMuch(
params.totalAssetsBeforeAccounting, params.totalAssetsAfterAccounting, maxTotalAssetsIncreaseRatio
);
}
}
}
/**
* @notice Check if the total supply changed too much to the upside (decrease not permitted.)
* @dev This check protects against anomalous supply changes for the vault.
* @dev Prevents processAccounting from running if totalSupply change falls outside bounds.
* @param params The parameters for the afterProcessAccounting function
*/
function checkTotalSupplyChange(AfterProcessAccountingParams memory params) public view {
uint256 totalSupplyAfterAccounting = VAULT.totalSupply();
if (totalSupplyAfterAccounting < params.totalSupplyBeforeAccounting) {
// total supply must not decrease
revert TotalSupplyDecreased();
}
checkTotalSupplyIncreaseRatio(params.totalSupplyBeforeAccounting, totalSupplyAfterAccounting);
checkTotalSupplyIncreaseGivenPerformanceFee(
params.totalSupplyBeforeAccounting,
totalSupplyAfterAccounting,
params.totalBaseAssetsBeforeAccounting,
params.totalBaseAssetsAfterAccounting,
params.totalAssetsAfterAccounting
);
}
/**
* @notice Check if the total supply increased too much with respect to a max ratio change
* @dev This check protects against anomalous supply changes for the vault.
* @dev Prevents processAccounting from running if totalSupply increase falls outside bounds.
* @param totalSupplyBeforeAccounting The total supply before accounting
* @param totalSupplyAfterAccounting The total supply after accounting
*/
function checkTotalSupplyIncreaseRatio(uint256 totalSupplyBeforeAccounting, uint256 totalSupplyAfterAccounting)
public
view
{
uint256 totalSupplyIncrease = totalSupplyAfterAccounting - totalSupplyBeforeAccounting;
uint256 _maxTotalSupplyIncreaseRatio = maxTotalSupplyIncreaseRatio;
uint256 totalSupplyIncreaseRatio = (totalSupplyIncrease * RATIO_DENOMINATOR) / totalSupplyBeforeAccounting;
if (totalSupplyIncreaseRatio > _maxTotalSupplyIncreaseRatio) {
revert TotalSupplyIncreasedTooMuch(totalSupplyBeforeAccounting, totalSupplyAfterAccounting);
}
}
/**
* @notice Check if the total supply increased too much with respect to the expected performance fee
* @dev This check protects against anomalous supply changes for the vault.
* @dev Prevents processAccounting from running if totalSupply increases more than what the fee predicts.
* @param totalSupplyBeforeAccounting The total supply before accounting
* @param totalSupplyAfterAccounting The total supply after accounting
*/
function checkTotalSupplyIncreaseGivenPerformanceFee(
uint256 totalSupplyBeforeAccounting,
uint256 totalSupplyAfterAccounting,
uint256 totalBaseAssetsBeforeAccounting,
uint256 totalBaseAssetsAfterAccounting,
uint256 /* totalAssetsAfterAccounting */
) public view {
uint256 totalSupplyIncrease = totalSupplyAfterAccounting - totalSupplyBeforeAccounting;
if (totalSupplyIncrease > 0) {
if (totalBaseAssetsAfterAccounting <= totalBaseAssetsBeforeAccounting) {
// no shares should be minted for loss
revert TotalSupplyIncreasedForLoss();
}
uint256 totalBaseAssetsIncrease = totalBaseAssetsAfterAccounting - totalBaseAssetsBeforeAccounting;
uint256 maxFeeInBaseAssets =
totalBaseAssetsIncrease.mulDiv(expectedPerformanceFee, FEE_DENOMINATOR, Math.Rounding.Floor);
// maxShares is a looser bound that ensures the fee asset amount converted to vault shares at rate post mint
// is less than or equal to the total supply increase
uint256 maxShares = convertToShares(
maxFeeInBaseAssets, totalSupplyAfterAccounting, totalBaseAssetsAfterAccounting, Math.Rounding.Floor
);
if (totalSupplyIncrease > maxShares) {
revert TotalSupplyIncreasedTooMuch(totalSupplyBeforeAccounting, totalSupplyAfterAccounting);
}
}
}
/**
* @notice Internal function to convert assets to shares
* @dev This function replicates BaseVault functionality for internal use
* @param assets The assets to convert
* @param totalSupply The total supply
* @param totalAssets The total assets
* @param rounding The rounding mode
* @return The shares
*/
function convertToShares(uint256 assets, uint256 totalSupply, uint256 totalAssets, Math.Rounding rounding)
internal
pure
returns (uint256)
{
return assets.mulDiv(totalSupply + 1, totalAssets + 1, rounding);
}
/// UNUSED HOOKS ///
/// @inheritdoc IHooks
function beforeDeposit(DepositParams memory) external pure override {
// Not implemented
}
/// @inheritdoc IHooks
function afterDeposit(DepositParams memory) external pure override {
// Not implemented
}
/// @inheritdoc IHooks
function beforeMint(MintParams memory) external pure override {
// Not implemented
}
/// @inheritdoc IHooks
function afterMint(MintParams memory) external pure override {
// Not implemented
}
/// @inheritdoc IHooks
function beforeRedeem(RedeemParams memory) external pure override {
// Not implemented
}
/// @inheritdoc IHooks
function afterRedeem(RedeemParams memory) external pure override {
// Not implemented
}
/// @inheritdoc IHooks
function beforeWithdraw(WithdrawParams memory) external pure override {
// Not implemented
}
/// @inheritdoc IHooks
function afterWithdraw(WithdrawParams memory) external pure override {
// Not implemented
}
/// @inheritdoc IHooks
function beforeProcessAccounting(BeforeProcessAccountingParams memory) external pure override {
// Not implemented
}
}
"
},
"lib/yieldnest-vault/src/interface/IHooks.sol": {
"content": "// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.24;
import {IVault} from "src/interface/IVault.sol";
interface IHooks {
/**
* @notice Parameters for deposit operations
*/
struct DepositParams {
address asset;
uint256 assets;
address caller;
address receiver;
uint256 shares;
uint256 baseAssets;
}
/**
* @notice Parameters for mint operations
*/
struct MintParams {
address asset;
uint256 shares;
address caller;
address receiver;
uint256 assets;
uint256 baseAssets;
}
/**
* @notice Parameters for redeem operations
*/
struct RedeemParams {
address asset;
uint256 shares;
address caller;
address receiver;
address owner;
uint256 assets;
}
/**
* @notice Parameters for withdraw operations
*/
struct WithdrawParams {
address asset;
uint256 assets;
address caller;
address receiver;
address owner;
uint256 shares;
}
/**
* @notice Parameters for before process accounting operations
*/
struct BeforeProcessAccountingParams {
uint256 totalAssetsBeforeAccounting;
uint256 totalSupplyBeforeAccounting;
uint256 totalBaseAssetsBeforeAccounting;
}
/**
* @notice Parameters for after process accounting operations
*/
struct AfterProcessAccountingParams {
uint256 totalAssetsBeforeAccounting;
uint256 totalAssetsAfterAccounting;
uint256 totalSupplyBeforeAccounting;
uint256 totalSupplyAfterAccounting;
uint256 totalBaseAssetsBeforeAccounting;
uint256 totalBaseAssetsAfterAccounting;
}
/**
* @notice Config struct for the hooks
* @dev Each flag is a boolean value that indicates if the corresponding hook function is enabled for the vault
* if the flag is true, the hook function must be called by the vault.
* if the flag is false, the hook function is expected to be a no-op.
*/
struct Config {
bool beforeDeposit;
bool afterDeposit;
bool beforeMint;
bool afterMint;
bool beforeRedeem;
bool afterRedeem;
bool beforeWithdraw;
bool afterWithdraw;
bool beforeProcessAccounting;
bool afterProcessAccounting;
}
error CallerNotVault();
/**
* @notice Returns the name of the hooks module
* @return The name of the hooks module
*/
function name() external view returns (string memory);
/**
* @notice Returns the vault that the hooks are attached to
* @return The vault contract interface
*/
function VAULT() external view returns (IVault);
/**
* @notice Sets the hooks configuration
* @param config_ The configuration struct containing hook permissions
*/
function setConfig(Config memory config_) external;
/**
* @notice Gets the current hooks configuration
* @return The configuration struct containing hook permissions
*/
function getConfig() external view returns (Config memory);
/**
* @notice Hook called before deposit is processed
* @param params The deposit parameters
*/
function beforeDeposit(DepositParams memory params) external;
/**
* @notice Hook called after deposit is processed
* @param params The deposit parameters
*/
function afterDeposit(DepositParams memory params) external;
/**
* @notice Hook called before mint is processed
* @param params The mint parameters
*/
function beforeMint(MintParams memory params) external;
/**
* @notice Hook called after mint is processed
* @param params The mint parameters
*/
function afterMint(MintParams memory params) external;
/**
* @notice Hook called before redeem is processed
* @param params The redeem parameters
*/
function beforeRedeem(RedeemParams memory params) external;
/**
* @notice Hook called after redeem is processed
* @param params The redeem parameters
*/
function afterRedeem(RedeemParams memory params) external;
/**
* @notice Hook called before withdraw is processed
* @param params The withdraw parameters
*/
function beforeWithdraw(WithdrawParams memory params) external;
/**
* @notice Hook called after withdraw is processed
* @param params The withdraw parameters
*/
function afterWithdraw(WithdrawParams memory params) external;
/**
* @notice Hook called before process accounting is executed
* @param params The before process accounting parameters
*/
function beforeProcessAccounting(BeforeProcessAccountingParams memory params) external;
/**
* @notice Hook called after process accounting is executed
* @param params The after process accounting parameters
*/
function afterProcessAccounting(AfterProcessAccountingParams memory params) external;
}
"
},
"lib/yieldnest-vault/src/interface/IVault.sol": {
"content": "// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.24;
import {IERC4626} from "src/Common.sol";
import {IValidator} from "src/interface/IValidator.sol";
import {IHooks} from "src/interface/IHooks.sol";
interface IVault is IERC4626 {
struct VaultStorage {
uint256 totalAssets;
address provider;
address buffer;
bool paused;
uint8 decimals;
bool countNativeAsset;
bool alwaysComputeTotalAssets;
/// @notice The index of the default asset.
/// The default asset is vault.asset(), used for deposit, withdraw, redeem, mint as default.
/// If defaultAssetIndex is 0, the vault will use the base asset as default asset.
uint256 defaultAssetIndex;
}
struct AssetParams {
uint256 index;
bool active;
uint8 decimals;
}
struct AssetUpdateFields {
bool active;
}
struct AssetStorage {
mapping(address => AssetParams) assets;
address[] list;
}
struct OverriddenBaseWithdrawalFeeFields {
/// @notice The base withdrawal fee in basis points (1e8 = 100%) for the user to override
uint64 baseWithdrawalFee;
/// @notice Whether the fee is overridden for the user
bool isOverridden;
}
struct FeeStorage {
/// @notice The base withdrawal fee in basis points (1e8 = 100%)
uint64 baseWithdrawalFee;
mapping(address user => OverriddenBaseWithdrawalFeeFields fields) overriddenBaseWithdrawalFee;
}
struct HooksStorage {
IHooks hooks;
}
enum ParamType {
UINT256,
ADDRESS
}
struct ParamRule {
ParamType paramType;
bool isArray;
address[] allowList;
}
struct FunctionRule {
bool isActive;
ParamRule[] paramRules;
IValidator validator;
}
struct ProcessorStorage {
uint256 lastProcessed;
uint256 lastAccounting;
mapping(address => mapping(bytes4 => FunctionRule)) rules;
}
error Paused();
error Unpaused();
error ZeroAddress();
error ZeroAmount();
error ZeroRate();
error InvalidString();
error InvalidArray();
error ExceededMaxDeposit(address sender, uint256 amount, uint256 maxAssets);
error DefaultAsset();
error AssetNotEmpty(address);
error InvalidAsset(address);
error InvalidTarget(address);
error InvalidDecimals();
error InvalidFunction(address target, bytes4 funcSig);
error DuplicateAsset(address asset);
error ExceededMaxWithdraw(address, uint256, uint256);
error ExceededMaxRedeem(address, uint256, uint256);
error ProcessFailed(bytes, bytes);
error ProcessInvalid(bytes);
error ProviderNotSet();
error BufferNotSet();
error DepositFailed();
error AssetNotActive();
error ExceedsMaxBasisPoints(uint256 value);
error InvalidNativeAssetDecimals(uint256 decimals);
error InvalidAssetDecimals(uint256 decimals);
error InvalidDefaultAssetIndex(uint256 index);
error ExceedsMaxPerformanceFee(uint256 value);
error BaseAsset();
error CallerNotHooks();
error InvalidHooks();
event DepositAsset(
address indexed sender,
address indexed receiver,
address indexed asset,
uint256 assets,
uint256 baseAssets,
uint256 shares
);
event WithdrawAsset(
address indexed sender,
address indexed receiver,
address indexed owner,
address asset,
uint256 assets,
uint256 shares
);
event SetProvider(address indexed provider);
event SetBuffer(address indexed buffer);
event SetAlwaysComputeTotalAssets(bool alwaysComputeTotalAssets);
event NewAsset(address indexed asset, uint256 decimals, uint256 index);
event ProcessSuccess(address[] targets, uint256[] values, bytes[] data);
event Pause(bool paused);
event SetProcessorRule(address indexed target, bytes4, FunctionRule);
event NativeDeposit(uint256 amount);
event ProcessAccounting(uint256 timestamp, uint256 totalAssetsBefore, uint256 totalAssetsAfter);
event UpdateAsset(uint256 indexed index, address indexed asset, AssetUpdateFields fields);
event DeleteAsset(uint256 indexed index, address indexed asset);
event SetBaseWithdrawalFee(uint64 oldFee, uint64 newFee);
event WithdrawalFeeOverridden(address indexed user, uint64 baseWithdrawalFee, bool isOverridden);
event SetHooks(address indexed oldHooks, address indexed newHooks);
// 4626-MAX
function getAssets() external view returns (address[] memory list);
function getAsset(address asset_) external view returns (AssetParams memory);
function hasAsset(address asset_) external view returns (bool);
function getProcessorRule(address contractAddress, bytes4 funcSig) external view returns (FunctionRule memory);
function previewDepositAsset(address assetAddress, uint256 assets) external view returns (uint256);
function depositAsset(address assetAddress, uint256 amount, address receiver) external returns (uint256);
function provider() external view returns (address);
function buffer() external view returns (address);
function totalBaseAssets() external view returns (uint256);
function computeTotalAssets() external view returns (uint256);
function alwaysComputeTotalAssets() external view returns (bool);
// ADMIN
function setProvider(address provider) external;
function setBuffer(address buffer) external;
function setProcessorRule(address target, bytes4 functionSig, FunctionRule memory rule) external;
function setProcessorRules(address[] memory targets, bytes4[] memory functionSigs, FunctionRule[] memory rules)
external;
function addAsset(address asset_, bool active_) external;
function deleteAsset(uint256 index) external;
function pause() external;
function unpause() external;
function hooks() external view returns (IHooks);
function setHooks(address hooks) external;
function mintShares(address recipient, uint256 shares) external;
function withdrawAsset(address asset_, uint256 assets, address receiver, address owner)
external
returns (uint256);
function processAccounting() external;
function processor(address[] calldata targets, uint256[] calldata values, bytes[] calldata data)
external
returns (bytes[] memory);
// FEES
function _feeOnRaw(uint256 amount, address user) external view returns (uint256);
function _feeOnTotal(uint256 amount, address user) external view returns (uint256);
}
"
},
"lib/openzeppelin-contracts/contracts/utils/math/Math.sol": {
"content": "// 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/yieldnest-vault/src/Common.sol": {
"content": "/* solhint-disable no-empty-blocks, no-unused-import */
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.24;
import {AccessControlUpgradeable} from
"lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import {Address} from "lib/openzeppelin-contracts/contracts/utils/Address.sol";
import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol";
import {ERC20PermitUpgradeable} from
"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC20PermitUpgradeable.sol";
import {ERC20Upgradeable} from "lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol";
import {IAccessControl} from "lib/openzeppelin-contracts/contracts/access/IAccessControl.sol";
import {IERC20} from "lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol";
import {IERC20Metadata} from "lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol";
import {IERC20Permit} from "lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {IERC4626} from "lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol";
import {Math} from "lib/openzeppelin-contracts/contracts/utils/math/Math.sol";
import {ProxyAdmin} from "lib/openzeppelin-contracts/contracts/proxy/transparent/ProxyAdmin.sol";
import {ReentrancyGuardUpgradeable} from
"lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol";
import {SafeERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {TimelockController} from "lib/openzeppelin-contracts/contracts/governance/TimelockController.sol";
import {
TransparentUpgradeableProxy,
ITransparentUpgradeableProxy
} from "lib/openzeppelin-contracts/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
import {IERC165} from "lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol";
import {Initializable} from "lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";
import {OwnableUpgradeable} from "lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol";
import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol";
contract Common {}
"
},
"lib/yieldnest-vault/src/interface/IValidator.sol": {
"content": "// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.24;
interface IValidator {
/// @notice Validates a transaction before execution
/// @param target The address the transaction will be sent to
/// @param value The amount of ETH (in wei) that will be sent with the transaction
/// @param data The calldata that will be sent with the transaction
/// @dev This function should revert if the transaction is invalid
/// @dev This function is called before executing a transaction
function validate(address target, uint256 value, bytes calldata data) external view;
}
"
},
"lib/openzeppelin-contracts/contracts/utils/Panic.sol": {
"content": "// 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)
}
Submitted on: 2025-10-17 10:40:23
Comments
Log in to comment.
No comments yet.