Verified contractExactBUSL-1.1
MultiMint
Address0xd77f0d2053c062769f351e2094ea7d1f922e28cf
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 2,933 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,232,734
- Creation transaction
- 0xccf6d07730…6ee0d82342
49 files
- src/platform/projects/MultiMint.solmain19.38 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol8.29 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol9.28 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol3.66 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol1.18 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.34 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Arrays.sol18.34 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Comparators.sol443 B
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/SlotDerivation.sol5.32 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.15 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol14.72 KB
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol637 B
- lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/evm-m-extensions/lib/common/src/ERC20ExtendedUpgradeable.sol7.26 KB
- lib/evm-m-extensions/lib/common/src/ERC3009Upgradeable.sol13.55 KB
- lib/evm-m-extensions/lib/common/src/ERC712ExtendedUpgradeable.sol8.08 KB
- lib/evm-m-extensions/lib/common/src/StatefulERC712Upgradeable.sol1.99 KB
- lib/evm-m-extensions/lib/common/src/interfaces/IERC1271.sol747 B
- lib/evm-m-extensions/lib/common/src/interfaces/IERC20.sol3.86 KB
- lib/evm-m-extensions/lib/common/src/interfaces/IERC20Extended.sol3.28 KB
- lib/evm-m-extensions/lib/common/src/interfaces/IERC3009.sol9.67 KB
- lib/evm-m-extensions/lib/common/src/interfaces/IERC712.sol1.43 KB
- lib/evm-m-extensions/lib/common/src/interfaces/IERC712Extended.sol966 B
- lib/evm-m-extensions/lib/common/src/interfaces/IStatefulERC712.sol1.05 KB
- lib/evm-m-extensions/lib/common/src/libs/SignatureChecker.sol12.02 KB
- lib/evm-m-extensions/lib/common/src/libs/UIntMath.sol7.7 KB
- lib/evm-m-extensions/src/components/freezable/Freezable.sol6.29 KB
- lib/evm-m-extensions/src/components/freezable/IFreezable.sol2.65 KB
- lib/evm-m-extensions/src/components/pausable/IPausable.sol983 B
- lib/evm-m-extensions/src/components/pausable/Pausable.sol1.84 KB
- src/IPYUSDX.sol13.12 KB
- src/platform/Extension.sol12.86 KB
- src/platform/interfaces/IExtension.sol3.59 KB
- src/platform/interfaces/IExtensionBeacon.sol3.27 KB
- src/platform/projects/YieldToOne.sol10.68 KB
- src/platform/projects/interfaces/IMultiMint.sol7.97 KB
- src/platform/projects/interfaces/IYieldToOne.sol3.49 KB
- src/swap/interfaces/ISwapFacility.sol9.36 KB
src/platform/projects/MultiMint.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;
import { EnumerableSet } from "../../../lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol";
import { SafeERC20 } from "../../../lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import { UIntMath } from "../../../lib/evm-m-extensions/lib/common/src/libs/UIntMath.sol";
import { IERC20Metadata } from "../../../lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IERC20 } from "../../../lib/evm-m-extensions/lib/common/src/interfaces/IERC20.sol";
import { YieldToOne } from "./YieldToOne.sol";
import { IMultiMint } from "./interfaces/IMultiMint.sol";
import { ISwapFacility } from "../../swap/interfaces/ISwapFacility.sol";
abstract contract MultiMintStorageLayout {
struct Asset {
uint256 cap;
uint240 balance;
uint8 decimals;
}
/// @custom:storage-location erc7201:PYUSDX.storage.MultiMint
struct MultiMintStorage {
mapping(address => Asset) assets;
uint256 totalAssets;
EnumerableSet.AddressSet replaceAssetWhitelist;
}
// keccak256(abi.encode(uint256(keccak256("PYUSDX.storage.MultiMint")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant _MULTI_MINT_STORAGE_LOCATION =
0x57e19e611dcbdde2876919e2fe591d15cb50f046f296d11a2b28e0b3b8b3f900;
function _getMultiMintStorage() internal pure returns (MultiMintStorage storage $) {
bytes32 location = _MULTI_MINT_STORAGE_LOCATION;
assembly {
$.slot := location
}
}
}
/// @title MultiMint
/// @notice Upgradeable ERC20 token for wrapping PYUSDX or approved alternative stablecoins
/// into a token with yield claimable by a single recipient.
/// @dev Extends YieldToOne with a multi-collateral backing model. Users
/// can mint by depositing PYUSDX. Unwrapping always returns PYUSDX, other
/// stablecoins can only be extracted via `replaceAsset`.
/// @author M0 Labs
contract MultiMint is IMultiMint, MultiMintStorageLayout, YieldToOne {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20Metadata;
/* ============ Variables ============ */
/// @inheritdoc IMultiMint
bytes32 public constant ASSET_CAP_MANAGER_ROLE = keccak256("ASSET_CAP_MANAGER_ROLE");
/// @inheritdoc IMultiMint
uint8 public constant PYUSDX_DECIMALS = 6;
/* ============ Constructor ============ */
/// @custom:oz-upgrades-unsafe-allow constructor
/// @param pyusdx_ The address of the PYUSDX token.
/// @param swapFacility_ The address of the swap facility.
constructor(address pyusdx_, address swapFacility_) YieldToOne(pyusdx_, swapFacility_) {}
/* ============ Initializer ============ */
/// @notice Initializes the MultiMint extension token.
/// @param name The name of the token.
/// @param symbol The symbol of the token.
/// @param yieldRecipient_ The address of the yield recipient.
/// @param admin The address of the admin.
/// @param assetCapManager The address of the asset cap manager.
/// @param freezeManager The address of the freeze manager.
/// @param pauser The address of the pauser.
/// @param yieldRecipientManager The address of the yield recipient manager.
/// @param versionManager The address of the version manager.
function initialize(
string memory name,
string memory symbol,
address yieldRecipient_,
address admin,
address assetCapManager,
address freezeManager,
address pauser,
address yieldRecipientManager,
address versionManager
) public virtual initializer {
__MultiMint_init(
name,
symbol,
yieldRecipient_,
admin,
assetCapManager,
freezeManager,
pauser,
yieldRecipientManager,
versionManager
);
}
/// @dev Internal initializer for MultiMint. Grants ASSET_CAP_MANAGER_ROLE
/// and delegates to `__YieldToOne_init`.
/// @param name The name of the token.
/// @param symbol The symbol of the token.
/// @param yieldRecipient_ The address of the yield recipient.
/// @param admin The address of the admin.
/// @param assetCapManager The address of the asset cap manager.
/// @param freezeManager The address of the freeze manager.
/// @param pauser The address of the pauser.
/// @param yieldRecipientManager The address of the yield recipient manager.
/// @param versionManager The address of the version manager.
function __MultiMint_init(
string memory name,
string memory symbol,
address yieldRecipient_,
address admin,
address assetCapManager,
address freezeManager,
address pauser,
address yieldRecipientManager,
address versionManager
) internal onlyInitializing {
if (assetCapManager == address(0)) revert ZeroAssetCapManager();
__YieldToOne_init(
name,
symbol,
yieldRecipient_,
admin,
freezeManager,
pauser,
yieldRecipientManager,
versionManager
);
_grantRole(ASSET_CAP_MANAGER_ROLE, assetCapManager);
}
/* ============ Interactive Functions ============ */
/// @inheritdoc IMultiMint
function wrap(address asset, address recipient, uint256 amount) external onlySwapFacility {
_wrapAsset(asset, ISwapFacility(msg.sender).msgSender(), recipient, amount);
}
/// @inheritdoc IMultiMint
function replaceAsset(address asset, address recipient, uint256 amount) external onlySwapFacility {
_replaceAsset(asset, recipient, amount);
}
/// @inheritdoc IMultiMint
function setAssetCap(address asset, uint256 cap) external onlyRole(ASSET_CAP_MANAGER_ROLE) {
_revertIfInvalidAsset(asset);
MultiMintStorage storage $ = _getMultiMintStorage();
if ($.assets[asset].cap == cap) return;
if ($.assets[asset].decimals == 0) $.assets[asset].decimals = IERC20Metadata(asset).decimals();
$.assets[asset].cap = cap;
emit AssetCapSet(asset, cap);
}
/// @inheritdoc IMultiMint
function setReplaceAssetWhitelistCaller(address caller, bool allowed) external onlyRole(ASSET_CAP_MANAGER_ROLE) {
_setReplaceAssetWhitelistCaller(caller, allowed);
}
/// @inheritdoc IMultiMint
function setReplaceAssetWhitelistCaller(
address[] calldata callers,
bool[] calldata allowed
) external onlyRole(ASSET_CAP_MANAGER_ROLE) {
if (callers.length != allowed.length) revert ArrayLengthMismatch();
for (uint256 i; i < callers.length; ++i) {
_setReplaceAssetWhitelistCaller(callers[i], allowed[i]);
}
}
/* ============ View/Pure Functions ============ */
/// @inheritdoc IMultiMint
function assetBalanceOf(address asset) public view returns (uint256) {
return _getMultiMintStorage().assets[asset].balance;
}
/// @inheritdoc IMultiMint
function assetCap(address asset) public view returns (uint256) {
return _getMultiMintStorage().assets[asset].cap;
}
/// @inheritdoc IMultiMint
function assetDecimals(address asset) public view returns (uint8) {
return _getMultiMintStorage().assets[asset].decimals;
}
/// @inheritdoc IMultiMint
function totalAssets() public view returns (uint256) {
return _getMultiMintStorage().totalAssets;
}
/// @inheritdoc IMultiMint
function isAllowedAsset(address asset) public view returns (bool) {
return assetCap(asset) != 0;
}
/// @inheritdoc IMultiMint
function isAllowedToWrap(address asset, uint256 amount) public view returns (bool) {
if (amount == 0) return false;
uint256 extensionAmount = _fromAssetToExtensionAmount(asset, amount);
if (extensionAmount == 0) return false;
uint256 effectiveAmount = _fromExtensionToAssetAmount(asset, extensionAmount);
return assetCap(asset) >= (assetBalanceOf(asset) + effectiveAmount);
}
/// @inheritdoc IMultiMint
function isAllowedToUnwrap(uint256 amount) external view returns (bool) {
return amount != 0 && _pyusdxBacking() >= amount;
}
/// @inheritdoc IMultiMint
function isReplaceAssetWhitelistEnabled() external view returns (bool) {
return _getMultiMintStorage().replaceAssetWhitelist.length() != 0;
}
/// @inheritdoc IMultiMint
function getReplaceAssetWhitelist() external view returns (address[] memory) {
return _getMultiMintStorage().replaceAssetWhitelist.values();
}
/// @inheritdoc IMultiMint
function isAllowedToReplaceAsset(address caller, address asset, uint256 amount) external view returns (bool) {
if (amount == 0 || !isAllowedAsset(asset) || !_isCallerAllowedToReplaceAsset(caller)) return false;
uint256 assetAmount = _fromExtensionToAssetAmount(asset, amount);
return assetAmount != 0 && assetBalanceOf(asset) >= assetAmount;
}
/* ============ Hooks ============ */
/// @dev Hook called before wrapping `asset` into extension's tokens.
/// @param asset Address of the asset being deposited.
/// @param account The account initiating the wrap.
/// @param recipient The address that will receive extension tokens.
/// @param amount The amount of `asset` being deposited.
function _beforeWrap(address asset, address account, address recipient, uint256 amount) internal view virtual {
if (!isAllowedToWrap(asset, amount)) revert AssetCapReached(asset);
super._beforeWrap(account, recipient, amount);
}
/// @dev Hook called before unwrapping extension tokens for PYUSDX.
/// Adds PYUSDX backing check before the inherited pause+freeze
/// checks.
/// @param account The account from which tokens are burned.
/// @param amount The amount of extension tokens to unwrap.
function _beforeUnwrap(address account, uint256 amount) internal view virtual override {
_revertIfInsufficientPYUSDXBacking(amount);
super._beforeUnwrap(account, amount);
}
/* ============ Internal Interactive Functions ============ */
/// @dev Mints extension tokens by pulling `asset` from `msg.sender`.
/// Reverts on fee-on-transfer tokens or if the asset cap is reached.
/// For assets with more decimals than the extension, only the
/// non-dust portion is pulled; any dust is left with `msg.sender`
/// so that `assetBalance == totalAssets * factor` always holds.
/// @param asset Address of the asset to deposit.
/// @param account The original caller (resolved via swap facility).
/// @param recipient Address that will receive the extension tokens.
/// @param amount Amount of `asset` tokens to deposit (in asset decimals).
function _wrapAsset(address asset, address account, address recipient, uint256 amount) internal virtual {
_revertIfInvalidAsset(asset);
_revertIfZeroAccount(recipient);
_revertIfZeroAmount(amount);
// Convert to extension decimals and revert if it truncates to zero.
uint256 extensionAmount = _fromAssetToExtensionAmount(asset, amount);
_revertIfZeroAmount(extensionAmount);
// Round amount down to the largest non-dust multiple of factor. For
// assets with decimals <= 6 this equals `amount`; for higher decimals
// it discards the truncating-division dust so the asset/extension
// accounting stays exact across repeated wraps.
uint256 effectiveAmount = _fromExtensionToAssetAmount(asset, extensionAmount);
// Checks asset cap + pause + freeze via 4-arg hook.
_beforeWrap(asset, account, recipient, effectiveAmount);
uint256 assetBalanceBefore = IERC20Metadata(asset).balanceOf(address(this));
// Pull only the non-dust portion from caller.
IERC20Metadata(asset).safeTransferFrom(msg.sender, address(this), effectiveAmount);
// Fee-on-transfer detection.
uint256 amountReceived = IERC20Metadata(asset).balanceOf(address(this)) - assetBalanceBefore;
if (amountReceived < effectiveAmount) {
revert InsufficientAssetReceived(asset, effectiveAmount, amountReceived);
}
MultiMintStorage storage $ = _getMultiMintStorage();
// Update non-PYUSDX asset backing.
$.assets[asset].balance += UIntMath.safe240(effectiveAmount);
$.totalAssets += extensionAmount;
_mint(recipient, extensionAmount);
emit AssetWrapped(asset, effectiveAmount, recipient, extensionAmount);
}
/// @dev Pulls PYUSDX from `msg.sender` and sends `asset` from reserves to `recipient`.
/// @param asset Address of the asset to receive from reserves.
/// @param recipient Address that will receive the `asset` tokens.
/// @param amount Amount of PYUSDX to deposit (in PYUSDX decimals).
function _replaceAsset(address asset, address recipient, uint256 amount) internal virtual {
_requireNotPaused();
_revertIfInvalidAsset(asset);
if (!isAllowedAsset(asset)) revert AssetNotAllowed(asset);
address caller = ISwapFacility(msg.sender).msgSender();
if (!_isCallerAllowedToReplaceAsset(caller)) revert CallerNotAllowed(caller);
_revertIfZeroAccount(recipient);
_revertIfZeroAmount(amount);
// Convert PYUSDX amount to asset decimals and revert if truncates to zero.
uint256 assetAmount = _fromExtensionToAssetAmount(asset, amount);
_revertIfZeroAmount(assetAmount);
_revertIfInsufficientAssetBacking(asset, assetAmount);
MultiMintStorage storage $ = _getMultiMintStorage();
// Update non-PYUSDX asset backing.
$.assets[asset].balance -= UIntMath.safe240(assetAmount);
$.totalAssets -= amount;
// Pull PYUSDX from caller.
IERC20(pyusdx).transferFrom(msg.sender, address(this), amount);
// Send alt-asset to recipient.
IERC20Metadata(asset).safeTransfer(recipient, assetAmount);
emit AssetReplaced(asset, assetAmount, recipient, amount);
}
/// @dev Adds or removes `caller` from the replaceAsset whitelist.
/// Emits `ReplaceAssetWhitelistCallerSet` only when state actually changes.
/// @param caller The caller to add or remove.
/// @param allowed True to add, false to remove.
function _setReplaceAssetWhitelistCaller(address caller, bool allowed) internal {
_revertIfZeroAccount(caller);
EnumerableSet.AddressSet storage whitelist = _getMultiMintStorage().replaceAssetWhitelist;
bool changed = allowed ? whitelist.add(caller) : whitelist.remove(caller);
if (!changed) return;
emit ReplaceAssetWhitelistCallerSet(caller, allowed);
}
/* ============ Internal View Functions ============ */
/// @dev Returns the excess PYUSDX balance that is not backing extension tokens.
function _excess() internal view virtual override returns (uint256) {
uint256 pyusdxBalance = _pyusdxBalanceOf(address(this));
uint256 pyusdxBacking = _pyusdxBacking();
unchecked {
return pyusdxBalance > pyusdxBacking ? pyusdxBalance - pyusdxBacking : 0;
}
}
/// @dev Returns the current supply of PYUSDX backing the extension token excluding yield and donation amounts.
function _pyusdxBacking() internal view returns (uint256) {
uint256 totalAssets_ = totalAssets();
uint256 totalSupply_ = totalSupply();
unchecked {
return totalSupply_ > totalAssets_ ? totalSupply_ - totalAssets_ : 0;
}
}
/// @dev Returns true if `caller` passes the whitelist gate.
/// @param caller The address to check.
/// @return True if the whitelist is disabled or `caller` is whitelisted.
function _isCallerAllowedToReplaceAsset(address caller) internal view returns (bool) {
EnumerableSet.AddressSet storage whitelist = _getMultiMintStorage().replaceAssetWhitelist;
return whitelist.length() == 0 || whitelist.contains(caller);
}
/// @dev Reverts if `asset` is address(0) or PYUSDX.
/// @param asset Address of the asset to validate.
function _revertIfInvalidAsset(address asset) internal view {
if (asset == address(0) || asset == pyusdx) revert InvalidAsset(asset);
}
/// @dev Reverts if PYUSDX backing is insufficient for `amount`.
/// @param amount Amount of PYUSDX required.
function _revertIfInsufficientPYUSDXBacking(uint256 amount) internal view {
uint256 backing_ = _pyusdxBacking();
if (amount > backing_) revert InsufficientPYUSDXBacking(amount, backing_);
}
/// @dev Reverts if the extension holds less than `amount` of `asset`.
/// @param asset Address of the asset.
/// @param amount Amount of `asset` required (in asset decimals).
function _revertIfInsufficientAssetBacking(address asset, uint256 amount) internal view {
uint256 assetBacking_ = assetBalanceOf(asset);
if (amount > assetBacking_) revert InsufficientAssetBacking(asset, amount, assetBacking_);
}
/// @dev Converts `amount` from asset decimals to extension decimals.
/// @param asset Address of the asset.
/// @param amount Amount in asset decimals.
/// @return Amount in extension decimals.
function _fromAssetToExtensionAmount(address asset, uint256 amount) internal view returns (uint256) {
return _convertAmounts(assetDecimals(asset), PYUSDX_DECIMALS, amount);
}
/// @dev Converts `amount` from extension decimals to asset decimals.
/// @param asset Address of the asset.
/// @param amount Amount in extension decimals.
/// @return Amount in asset decimals.
function _fromExtensionToAssetAmount(address asset, uint256 amount) internal view returns (uint256) {
return _convertAmounts(PYUSDX_DECIMALS, assetDecimals(asset), amount);
}
/* ============ Internal Pure Functions ============ */
/// @dev Converts `amount` between decimal representations.
/// @param fromDecimals Decimals of the input amount.
/// @param toDecimals Decimals of the output amount.
/// @param amount The amount to convert.
/// @return The converted amount.
function _convertAmounts(uint8 fromDecimals, uint8 toDecimals, uint256 amount) internal pure returns (uint256) {
if (fromDecimals == toDecimals) return amount;
return
fromDecimals > toDecimals
? amount / (10 ** (fromDecimals - toDecimals))
: amount * (10 ** (toDecimals - fromDecimals));
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 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();
_;
}
function __Pausable_init() internal onlyInitializing {
}
function __Pausable_init_unchained() internal onlyInitializing {
}
/**
* @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/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Arrays.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.
pragma solidity ^0.8.20;
import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
using SlotDerivation for bytes32;
using StorageSlot for bytes32;
/**
* @dev Sort an array of uint256 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
uint256[] memory array,
function(uint256, uint256) pure returns (bool) comp
) internal pure returns (uint256[] memory) {
_quickSort(_begin(array), _end(array), comp);
return array;
}
/**
* @dev Variant of {sort} that sorts an array of uint256 in increasing order.
*/
function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
sort(array, Comparators.lt);
return array;
}
/**
* @dev Sort an array of address (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
address[] memory array,
function(address, address) pure returns (bool) comp
) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of address in increasing order.
*/
function sort(address[] memory array) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Sort an array of bytes32 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
bytes32[] memory array,
function(bytes32, bytes32) pure returns (bool) comp
) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
*/
function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
* at end (exclusive). Sorting follows the `comp` comparator.
*
* Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
*
* IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
* be used only if the limits are within a memory array.
*/
function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
unchecked {
if (end - begin < 0x40) return;
// Use first element as pivot
uint256 pivot = _mload(begin);
// Position where the pivot should be at the end of the loop
uint256 pos = begin;
for (uint256 it = begin + 0x20; it < end; it += 0x20) {
if (comp(_mload(it), pivot)) {
// If the value stored at the iterator's position comes before the pivot, we increment the
// position of the pivot and move the value there.
pos += 0x20;
_swap(pos, it);
}
}
_swap(begin, pos); // Swap pivot into place
_quickSort(begin, pos, comp); // Sort the left side of the pivot
_quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
}
}
/**
* @dev Pointer to the memory location of the first element of `array`.
*/
function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
assembly ("memory-safe") {
ptr := add(array, 0x20)
}
}
/**
* @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
* that comes just after the last element of the array.
*/
function _end(uint256[] memory array) private pure returns (uint256 ptr) {
unchecked {
return _begin(array) + array.length * 0x20;
}
}
/**
* @dev Load memory word (as a uint256) at location `ptr`.
*/
function _mload(uint256 ptr) private pure returns (uint256 value) {
assembly {
value := mload(ptr)
}
}
/**
* @dev Swaps the elements memory location `ptr1` and `ptr2`.
*/
function _swap(uint256 ptr1, uint256 ptr2) private pure {
assembly {
let value1 := mload(ptr1)
let value2 := mload(ptr2)
mstore(ptr1, value2)
mstore(ptr2, value1)
}
}
/// @dev Helper: low level cast address memory array to uint256 memory array
function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 memory array to uint256 memory array
function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast address comp function to uint256 comp function
function _castToUint256Comp(
function(address, address) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 comp function to uint256 comp function
function _castToUint256Comp(
function(bytes32, bytes32) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* NOTE: The `array` is expected to be sorted in ascending order, and to
* contain no repeated elements.
*
* IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
* support for repeated elements in the array. The {lowerBound} function should
* be used instead.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && unsafeAccess(array, low - 1).value == element) {
return low - 1;
} else {
return low;
}
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value greater or equal than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
*/
function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value strictly greater than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
*/
function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Same as {lowerBound}, but with an array in memory.
*/
function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Same as {upperBound}, but with an array in memory.
*/
function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getAddressSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytes32Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getUint256Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(address[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(uint256[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Comparators.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to compare values.
*
* _Available since v5.1._
*/
library Comparators {
function lt(uint256 a, uint256 b) internal pure returns (bool) {
return a < b;
}
function gt(uint256 a, uint256 b) internal pure returns (bool) {
return a > b;
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/SlotDerivation.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.
pragma solidity ^0.8.20;
/**
* @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
* corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
* the solidity language / compiler.
*
* See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
*
* Example usage:
* ```solidity
* contract Example {
* // Add the library methods
* using StorageSlot for bytes32;
* using SlotDerivation for bytes32;
*
* // Declare a namespace
* string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
*
* function setValueInNamespace(uint256 key, address newValue) internal {
* _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
* }
*
* function getValueInNamespace(uint256 key) internal view returns (address) {
* return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
* }
* }
* ```
*
* TIP: Consider using this library along with {StorageSlot}.
*
* NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
* upgrade safety will ignore the slots accessed through this library.
*
* _Available since v5.1._
*/
library SlotDerivation {
/**
* @dev Derive an ERC-7201 slot from a string (namespace).
*/
function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
assembly ("memory-safe") {
mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
slot := and(keccak256(0x00, 0x20), not(0xff))
}
}
/**
* @dev Add an offset to a slot to get the n-th element of a structure or an array.
*/
function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
unchecked {
return bytes32(uint256(slot) + pos);
}
}
/**
* @dev Derive the location of the first element in an array from the slot where the length is stored.
*/
function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, slot)
result := keccak256(0x00, 0x20)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, and(key, shr(96, not(0))))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, iszero(iszero(key)))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
import {Arrays} from "../Arrays.sol";
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
* - Set can be cleared (all elements removed) in O(n).
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function _clear(Set storage set) private {
uint256 len = _length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes32Set storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(AddressSet storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(UintSet storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)
pragma solidity >=0.4.11;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/evm-m-extensions/lib/common/src/ERC20ExtendedUpgradeable.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
import { ERC3009Upgradeable } from "./ERC3009Upgradeable.sol";
import { IERC20 } from "./interfaces/IERC20.sol";
import { IERC20Extended } from "./interfaces/IERC20Extended.sol";
abstract contract ERC20ExtendedUpgradeableStorageLayout {
/// @custom:storage-location erc7201:M0.storage.ERC20Extended
struct ERC20ExtendedStorageStruct {
mapping(address account => mapping(address spender => uint256 allowance)) allowance;
uint8 decimals;
string symbol;
}
// keccak256(abi.encode(uint256(keccak256("M0.storage.ERC20Extended")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant _ERC20_EXTENDED_STORAGE_LOCATION =
0xcbbe23efb65c1eaba394256c463812c20abdb5376e247eba1d0e1e92054da100;
function _getERC20ExtendedStorageLocation() internal pure returns (ERC20ExtendedStorageStruct storage $) {
assembly {
$.slot := _ERC20_EXTENDED_STORAGE_LOCATION
}
}
}
/**
* @title An upgradeable ERC20 token extended with EIP-2612 permits for signed approvals
* (via EIP-712 and with EIP-1271 and EIP-5267 compatibility).
* @author M0 Labs
*/
abstract contract ERC20ExtendedUpgradeable is
ERC20ExtendedUpgradeableStorageLayout,
ERC3009Upgradeable,
IERC20Extended
{
/* ============ Variables ============ */
/**
* @inheritdoc IERC20Extended
* @dev Keeping this constant, despite `permit` parameter name differences, to ensure max EIP-2612 compatibility.
* keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
*/
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/* ============ Initializer ============ */
function __ERC20ExtendedUpgradeable_init(
string memory name_,
string memory symbol_,
uint8 decimals_
) internal onlyInitializing {
__ERC3009Upgradeable_init(name_);
ERC20ExtendedStorageStruct storage $ = _getERC20ExtendedStorageLocation();
$.decimals = decimals_;
$.symbol = symbol_;
}
/* ============ Interactive Functions ============ */
/// @inheritdoc IERC20
function approve(address spender_, uint256 amount_) external returns (bool) {
_approve(msg.sender, spender_, amount_);
return true;
}
/// @inheritdoc IERC20Extended
function permit(
address owner_,
address spender_,
uint256 value_,
uint256 deadline_,
uint8 v_,
bytes32 r_,
bytes32 s_
) external {
_revertIfInvalidSignature(owner_, _permitAndGetDigest(owner_, spender_, value_, deadline_), v_, r_, s_);
}
/// @inheritdoc IERC20Extended
function permit(
address owner_,
address spender_,
uint256 value_,
uint256 deadline_,
bytes memory signature_
) external {
_revertIfInvalidSignature(owner_, _permitAndGetDigest(owner_, spender_, value_, deadline_), signature_);
}
/// @inheritdoc IERC20
function transfer(address recipient_, uint256 amount_) external returns (bool) {
_transfer(msg.sender, recipient_, amount_);
return true;
}
/// @inheritdoc IERC20
function transferFrom(address sender_, address recipient_, uint256 amount_) external returns (bool) {
ERC20ExtendedStorageStruct storage $ = _getERC20ExtendedStorageLocation();
uint256 spenderAllowance_ = $.allowance[sender_][msg.sender]; // Cache `spenderAllowance_` to stack.
if (spenderAllowance_ != type(uint256).max) {
if (spenderAllowance_ < amount_) revert InsufficientAllowance(msg.sender, spenderAllowance_, amount_);
unchecked {
_setAllowance($, sender_, msg.sender, spenderAllowance_ - amount_);
}
}
_transfer(sender_, recipient_, amount_);
return true;
}
/* ============ View/Pure Functions ============ */
/// @inheritdoc IERC20
function allowance(address account, address spender) public view returns (uint256) {
return _getERC20ExtendedStorageLocation().allowance[account][spender];
}
/// @inheritdoc IERC20
function decimals() external view virtual returns (uint8) {
return _getERC20ExtendedStorageLocation().decimals;
}
/// @inheritdoc IERC20
function name() external view virtual returns (string memory) {
return _getERC712ExtendedStorageLocation().name;
}
/// @inheritdoc IERC20
function symbol() external view virtual returns (string memory) {
return _getERC20ExtendedStorageLocation().symbol;
}
/* ============ Internal Interactive Functions ============ */
/**
* @dev Approve `spender_` to spend `amount_` of tokens from `account_`.
* @param account_ The address approving the allowance.
* @param spender_ The address approved to spend the tokens.
* @param amount_ The amount of tokens being approved for spending.
*/
function _approve(address account_, address spender_, uint256 amount_) internal virtual {
_setAllowance(_getERC20ExtendedStorageLocation(), account_, spender_, amount_);
emit Approval(account_, spender_, amount_);
}
/**
* @dev Set the `amount_` of tokens `spender_` is allowed to spend from `account_`.
* @param $ ERC20Extended storage location.
* @param account_ The address for which the allowance is set.
* @param spender_ The address allowed to spend the tokens.
* @param amount_ The amount of tokens being allowed for spending.
*/
function _setAllowance(
ERC20ExtendedStorageStruct storage $,
address account_,
address spender_,
uint256 amount_
) internal virtual {
$.allowance[account_][spender_] = amount_;
}
/**
* @dev Performs the approval based on the permit info, validates the deadline, and returns the digest.
* @param owner_ The address of the account approving the allowance.
* @param spender_ The address of the account being allowed to spend the tokens.
* @param amount_ The amount of tokens being approved for spending.
* @param deadline_ The deadline by which the signature must be used.
* @return digest_ The EIP-712 digest of the permit.
*/
function _permitAndGetDigest(
address owner_,
address spender_,
uint256 amount_,
uint256 deadline_
) internal virtual returns (bytes32) {
_revertIfExpired(deadline_);
_approve(owner_, spender_, amount_);
unchecked {
// Nonce realistically cannot overflow.
return
_getDigest(
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner_,
spender_,
amount_,
_getStatefulERC712ExtendedStorageLocation().nonces[owner_]++,
deadline_
)
)
);
}
}
}
lib/evm-m-extensions/lib/common/src/ERC3009Upgradeable.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
import { Initializable } from "../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";
import { IERC3009 } from "./interfaces/IERC3009.sol";
import { StatefulERC712Upgradeable } from "./StatefulERC712Upgradeable.sol";
abstract contract ERC3009UpgradeableStorageLayout {
/// @custom:storage-location erc7201:M0.storage.ERC3009
struct ERC3009StorageStruct {
mapping(address authorizer => mapping(bytes32 nonce => bool isNonceUsed)) authorizationState;
}
// keccak256(abi.encode(uint256(keccak256("M0.storage.ERC3009")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant _ERC3009_STORAGE_LOCATION =
0x1116a1d33aa5fb91b2652b3b0fdb63704173742d6dbecaf4256ebe33a4888600;
function _getERC3009StorageLocation() internal pure returns (ERC3009StorageStruct storage $) {
assembly {
$.slot := _ERC3009_STORAGE_LOCATION
}
}
}
/**
* @title ERC3009 implementation allowing the transfer of fungible assets via a signed authorization.
* @author M0 Labs
* @dev Inherits from ERC712ExtendedUpgradeable and StatefulERC712Upgradeable.
*/
abstract contract ERC3009Upgradeable is IERC3009, ERC3009UpgradeableStorageLayout, StatefulERC712Upgradeable {
/* ============ Variables ============ */
// solhint-disable-next-line max-line-length
/// @dev keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
/// @inheritdoc IERC3009
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH =
0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
// solhint-disable-next-line max-line-length
/// @dev keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
/// @inheritdoc IERC3009
bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH =
0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;
/**
* @inheritdoc IERC3009
* @dev keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
*/
bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH =
0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
/* ============ Initializer ============ */
/**
* @notice Initializes the ERC3009Upgradeable contract.
* @param name_ The name of the contract.
*/
function __ERC3009Upgradeable_init(string memory name_) internal onlyInitializing {
__StatefulERC712ExtendedUpgradeable_init(name_);
}
/* ============ Interactive Functions ============ */
/// @inheritdoc IERC3009
function transferWithAuthorization(
address from_,
address to_,
uint256 value_,
uint256 validAfter_,
uint256 validBefore_,
bytes32 nonce_,
bytes memory signature_
) external {
_revertIfInvalidSignature(
from_,
_getTransferWithAuthorizationDigest(from_, to_, value_, validAfter_, validBefore_, nonce_),
signature_
);
_transferWithAuthorization(from_, to_, value_, validAfter_, validBefore_, nonce_);
}
/// @inheritdoc IERC3009
function transferWithAuthorization(
address from_,
address to_,
uint256 value_,
uint256 validAfter_,
uint256 validBefore_,
bytes32 nonce_,
bytes32 r_,
bytes32 vs_
) external {
_revertIfInvalidSignature(
from_,
_getTransferWithAuthorizationDigest(from_, to_, value_, validAfter_, validBefore_, nonce_),
r_,
vs_
);
_transferWithAuthorization(from_, to_, value_, validAfter_, validBefore_, nonce_);
}
/// @inheritdoc IERC3009
function transferWithAuthorization(
address from_,
address to_,
uint256 value_,
uint256 validAfter_,
uint256 validBefore_,
bytes32 nonce_,
uint8 v_,
bytes32 r_,
bytes32 s_
) external {
_revertIfInvalidSignature(
from_,
_getTransferWithAuthorizationDigest(from_, to_, value_, validAfter_, validBefore_, nonce_),
v_,
r_,
s_
);
_transferWithAuthorization(from_, to_, value_, validAfter_, validBefore_, nonce_);
}
/// @inheritdoc IERC3009
function receiveWithAuthorization(
address from_,
address to_,
uint256 value_,
uint256 validAfter_,
uint256 validBefore_,
bytes32 nonce_,
bytes memory signature_
) external {
_revertIfInvalidSignature(
from_,
_getReceiveWithAuthorizationDigest(from_, to_, value_, validAfter_, validBefore_, nonce_),
signature_
);
_receiveWithAuthorization(from_, to_, value_, validAfter_, validBefore_, nonce_);
}
/// @inheritdoc IERC3009
function receiveWithAuthorization(
address from_,
address to_,
uint256 value_,
uint256 validAfter_,
uint256 validBefore_,
bytes32 nonce_,
bytes32 r_,
bytes32 vs_
) external {
_revertIfInvalidSignature(
from_,
_getReceiveWithAuthorizationDigest(from_, to_, value_, validAfter_, validBefore_, nonce_),
r_,
vs_
);
_receiveWithAuthorization(from_, to_, value_, validAfter_, validBefore_, nonce_);
}
/// @inheritdoc IERC3009
function receiveWithAuthorization(
address from_,
address to_,
uint256 value_,
uint256 validAfter_,
uint256 validBefore_,
bytes32 nonce_,
uint8 v_,
bytes32 r_,
bytes32 s_
) external {
_revertIfInvalidSignature(
from_,
_getReceiveWithAuthorizationDigest(from_, to_, value_, validAfter_, validBefore_, nonce_),
v_,
r_,
s_
);
_receiveWithAuthorization(from_, to_, value_, validAfter_, validBefore_, nonce_);
}
/// @inheritdoc IERC3009
function cancelAuthorization(address authorizer_, bytes32 nonce_, bytes memory signature_) external {
_revertIfInvalidSignature(authorizer_, _getCancelAuthorizationDigest(authorizer_, nonce_), signature_);
_cancelAuthorization(authorizer_, nonce_);
}
/// @inheritdoc IERC3009
function cancelAuthorization(address authorizer_, bytes32 nonce_, bytes32 r_, bytes32 vs_) external {
_revertIfInvalidSignature(authorizer_, _getCancelAuthorizationDigest(authorizer_, nonce_), r_, vs_);
_cancelAuthorization(authorizer_, nonce_);
}
/// @inheritdoc IERC3009
function cancelAuthorization(address authorizer_, bytes32 nonce_, uint8 v_, bytes32 r_, bytes32 s_) external {
_revertIfInvalidSignature(authorizer_, _getCancelAuthorizationDigest(authorizer_, nonce_), v_, r_, s_);
_cancelAuthorization(authorizer_, nonce_);
}
/* ============ View/Pure Functions ============ */
/// @inheritdoc IERC3009
function authorizationState(address authorizer, bytes32 nonce) public view returns (bool) {
return _getERC3009StorageLocation().authorizationState[authorizer][nonce];
}
/* ============ Internal Interactive Functions ============ */
/**
* @dev Common transfer function used by `transferWithAuthorization` and `_receiveWithAuthorization`.
* @param from_ Payer's address (Authorizer).
* @param to_ Payee's address.
* @param value_ Amount to be transferred.
* @param validAfter_ The time after which this is valid (unix time).
* @param validBefore_ The time before which this is valid (unix time).
* @param nonce_ Unique nonce.
*/
function _transferWithAuthorization(
address from_,
address to_,
uint256 value_,
uint256 validAfter_,
uint256 validBefore_,
bytes32 nonce_
) internal {
if (block.timestamp <= validAfter_) revert AuthorizationNotYetValid(block.timestamp, validAfter_);
if (block.timestamp >= validBefore_) revert AuthorizationExpired(block.timestamp, validBefore_);
_revertIfAuthorizationAlreadyUsed(from_, nonce_);
_getERC3009StorageLocation().authorizationState[from_][nonce_] = true;
emit AuthorizationUsed(from_, nonce_);
_transfer(from_, to_, value_);
}
/**
* @dev Common receive function used by `receiveWithAuthorization`.
* @param from_ Payer's address (Authorizer).
* @param to_ Payee's address.
* @param value_ Amount to be transferred.
* @param validAfter_ The time after which this is valid (unix time).
* @param validBefore_ The time before which this is valid (unix time).
* @param nonce_ Unique nonce.
*/
function _receiveWithAuthorization(
address from_,
address to_,
uint256 value_,
uint256 validAfter_,
uint256 validBefore_,
bytes32 nonce_
) internal {
if (msg.sender != to_) revert CallerMustBePayee(msg.sender, to_);
_transferWithAuthorization(from_, to_, value_, validAfter_, validBefore_, nonce_);
}
/**
* @dev Common cancel function used by `cancelAuthorization`.
* @param authorizer_ Authorizer's address.
* @param nonce_ Nonce of the authorization.
*/
function _cancelAuthorization(address authorizer_, bytes32 nonce_) internal {
_revertIfAuthorizationAlreadyUsed(authorizer_, nonce_);
_getERC3009StorageLocation().authorizationState[authorizer_][nonce_] = true;
emit AuthorizationCanceled(authorizer_, nonce_);
}
/**
* @dev Internal ERC20 transfer function that needs to be implemented by the inheriting contract.
* @param sender_ The sender's address.
* @param recipient_ The recipient's address.
* @param amount_ The amount to be transferred.
*/
function _transfer(address sender_, address recipient_, uint256 amount_) internal virtual;
/* ============ Internal View/Pure Functions ============ */
/**
* @dev Returns the internal EIP-712 digest of a transferWithAuthorization call.
* @param from_ Payer's address (Authorizer).
* @param to_ Payee's address.
* @param value_ Amount to be transferred.
* @param validAfter_ The time after which this is valid (unix time).
* @param validBefore_ The time before which this is valid (unix time).
* @param nonce_ Unique nonce.
* @return The internal EIP-712 digest.
*/
function _getTransferWithAuthorizationDigest(
address from_,
address to_,
uint256 value_,
uint256 validAfter_,
uint256 validBefore_,
bytes32 nonce_
) internal view returns (bytes32) {
return
_getDigest(
keccak256(
abi.encode(
TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
from_,
to_,
value_,
validAfter_,
validBefore_,
nonce_
)
)
);
}
/**
* @dev Returns the internal EIP-712 digest of a receiveWithAuthorization call.
* @param from_ Payer's address (Authorizer).
* @param to_ Payee's address.
* @param value_ Amount to be transferred.
* @param validAfter_ The time after which this is valid (unix time).
* @param validBefore_ The time before which this is valid (unix time).
* @param nonce_ Unique nonce.
* @return The internal EIP-712 digest.
*/
function _getReceiveWithAuthorizationDigest(
address from_,
address to_,
uint256 value_,
uint256 validAfter_,
uint256 validBefore_,
bytes32 nonce_
) internal view returns (bytes32) {
return
_getDigest(
keccak256(
abi.encode(
RECEIVE_WITH_AUTHORIZATION_TYPEHASH,
from_,
to_,
value_,
validAfter_,
validBefore_,
nonce_
)
)
);
}
/**
* @dev Returns the internal EIP-712 digest of a cancelAuthorization call.
* @param authorizer_ Authorizer's address.
* @param nonce_ Nonce of the authorization.
* @return The internal EIP-712 digest.
*/
function _getCancelAuthorizationDigest(address authorizer_, bytes32 nonce_) internal view returns (bytes32) {
return _getDigest(keccak256(abi.encode(CANCEL_AUTHORIZATION_TYPEHASH, authorizer_, nonce_)));
}
/**
* @dev Reverts if the authorization is already used.
* @param authorizer_ The authorizer's address.
* @param nonce_ The nonce of the authorization.
*/
function _revertIfAuthorizationAlreadyUsed(address authorizer_, bytes32 nonce_) internal view {
if (authorizationState(authorizer_, nonce_)) revert AuthorizationAlreadyUsed(authorizer_, nonce_);
}
}
lib/evm-m-extensions/lib/common/src/ERC712ExtendedUpgradeable.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
import { Initializable } from "../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";
import { IERC712 } from "./interfaces/IERC712.sol";
import { IERC712Extended } from "./interfaces/IERC712Extended.sol";
import { SignatureChecker } from "./libs/SignatureChecker.sol";
abstract contract ERC712ExtendedUpgradeableStorageLayout {
/// @custom:storage-location erc7201:M0.storage.ERC712Extended
struct ERC712ExtendedStorageStruct {
uint256 initialChainId;
bytes32 initialDomainSeparator;
string name;
}
// keccak256(abi.encode(uint256(keccak256("M0.storage.ERC712Extended")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant _ERC712_EXTENDED_STORAGE_LOCATION =
0x103ce0bed7138196cdb0d79ef04042681b16e7a2c58d74b78443c813042ea100;
function _getERC712ExtendedStorageLocation() internal pure returns (ERC712ExtendedStorageStruct storage $) {
assembly {
$.slot := _ERC712_EXTENDED_STORAGE_LOCATION
}
}
}
/**
* @title Typed structured data hashing and signing via EIP-712, extended by EIP-5267.
* @author M0 Labs
* @dev An abstract implementation to satisfy EIP-712: https://eips.ethereum.org/EIPS/eip-712
*/
abstract contract ERC712ExtendedUpgradeable is ERC712ExtendedUpgradeableStorageLayout, IERC712Extended, Initializable {
/* ============ Variables ============ */
/// @dev keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
bytes32 internal constant _EIP712_DOMAIN_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev keccak256("1")
bytes32 internal constant _EIP712_VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
/* ============ Initializer ============ */
/**
* @notice Initializes the ERC712ExtendedUpgradeable contract.
* @param name_ The name of the contract.
*/
function __ERC712ExtendedUpgradeable_init(string memory name_) internal onlyInitializing {
ERC712ExtendedStorageStruct storage $ = _getERC712ExtendedStorageLocation();
$.name = name_;
$.initialChainId = block.chainid;
$.initialDomainSeparator = _getDomainSeparator();
}
/* ============ View/Pure Functions ============ */
/// @inheritdoc IERC712Extended
function eip712Domain()
external
view
virtual
returns (
bytes1 fields_,
string memory name_,
string memory version_,
uint256 chainId_,
address verifyingContract_,
bytes32 salt_,
uint256[] memory extensions_
)
{
return (
hex"0f", // 01111
_getERC712ExtendedStorageLocation().name,
"1",
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/// @inheritdoc IERC712
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
ERC712ExtendedStorageStruct storage $ = _getERC712ExtendedStorageLocation();
return block.chainid == $.initialChainId ? $.initialDomainSeparator : _getDomainSeparator();
}
/* ============ Internal View/Pure Functions ============ */
/**
* @dev Computes the EIP-712 domain separator.
* @return The EIP-712 domain separator.
*/
function _getDomainSeparator() internal view returns (bytes32) {
return
keccak256(
abi.encode(
_EIP712_DOMAIN_HASH,
keccak256(bytes(_getERC712ExtendedStorageLocation().name)),
_EIP712_VERSION_HASH,
block.chainid,
address(this)
)
);
}
/**
* @dev Returns the digest to be signed, via EIP-712, given an internal digest (i.e. hash struct).
* @param internalDigest_ The internal digest.
* @return The digest to be signed.
*/
function _getDigest(bytes32 internalDigest_) internal view returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), internalDigest_));
}
/**
* @dev Revert if the signature is expired.
* @param expiry_ Timestamp at which the signature expires or max uint256 for no expiry.
*/
function _revertIfExpired(uint256 expiry_) internal view {
if (block.timestamp > expiry_) revert SignatureExpired(expiry_, block.timestamp);
}
/**
* @dev Revert if the signature is invalid.
* @dev We first validate if the signature is a valid ECDSA signature and return early if it is the case.
* Then, we validate if it is a valid ERC-1271 signature, and return early if it is the case.
* If not, we revert with the error from the ECDSA signature validation.
* @param signer_ The signer of the signature.
* @param digest_ The digest that was signed.
* @param signature_ The signature.
*/
function _revertIfInvalidSignature(address signer_, bytes32 digest_, bytes memory signature_) internal view {
SignatureChecker.Error error_ = SignatureChecker.validateECDSASignature(signer_, digest_, signature_);
if (error_ == SignatureChecker.Error.NoError) return;
if (SignatureChecker.isValidERC1271Signature(signer_, digest_, signature_)) return;
_revertIfError(error_);
}
/**
* @dev Returns the signer of a signed digest, via EIP-712, and reverts if the signature is invalid.
* @param digest_ The digest that was signed.
* @param v_ v of the signature.
* @param r_ r of the signature.
* @param s_ s of the signature.
* @return signer_ The signer of the digest.
*/
function _getSignerAndRevertIfInvalidSignature(
bytes32 digest_,
uint8 v_,
bytes32 r_,
bytes32 s_
) internal pure returns (address signer_) {
SignatureChecker.Error error_;
(error_, signer_) = SignatureChecker.recoverECDSASigner(digest_, v_, r_, s_);
_revertIfError(error_);
}
/**
* @dev Revert if the signature is invalid.
* @param signer_ The signer of the signature.
* @param digest_ The digest that was signed.
* @param r_ An ECDSA/secp256k1 signature parameter.
* @param vs_ An ECDSA/secp256k1 short signature parameter.
*/
function _revertIfInvalidSignature(address signer_, bytes32 digest_, bytes32 r_, bytes32 vs_) internal pure {
_revertIfError(SignatureChecker.validateECDSASignature(signer_, digest_, r_, vs_));
}
/**
* @dev Revert if the signature is invalid.
* @param signer_ The signer of the signature.
* @param digest_ The digest that was signed.
* @param v_ v of the signature.
* @param r_ r of the signature.
* @param s_ s of the signature.
*/
function _revertIfInvalidSignature(
address signer_,
bytes32 digest_,
uint8 v_,
bytes32 r_,
bytes32 s_
) internal pure {
_revertIfError(SignatureChecker.validateECDSASignature(signer_, digest_, v_, r_, s_));
}
/**
* @dev Revert if error.
* @param error_ The SignatureChecker Error enum.
*/
function _revertIfError(SignatureChecker.Error error_) private pure {
if (error_ == SignatureChecker.Error.NoError) return;
if (error_ == SignatureChecker.Error.InvalidSignature) revert InvalidSignature();
if (error_ == SignatureChecker.Error.InvalidSignatureLength) revert InvalidSignatureLength();
if (error_ == SignatureChecker.Error.InvalidSignatureS) revert InvalidSignatureS();
if (error_ == SignatureChecker.Error.InvalidSignatureV) revert InvalidSignatureV();
if (error_ == SignatureChecker.Error.SignerMismatch) revert SignerMismatch();
revert InvalidSignature();
}
}
lib/evm-m-extensions/lib/common/src/StatefulERC712Upgradeable.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
import { IStatefulERC712 } from "./interfaces/IStatefulERC712.sol";
import { ERC712ExtendedUpgradeable } from "./ERC712ExtendedUpgradeable.sol";
abstract contract StatefulERC712ExtendedUpgradeableStorageLayout {
/// @custom:storage-location erc7201:M0.storage.StatefulERC712Extended
struct StatefulERC712ExtendedStorageStruct {
mapping(address account => uint256 nonce) nonces; // Nonces for all signatures.
}
// keccak256(abi.encode(uint256(keccak256("M0.storage.StatefulERC712Extended")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant _STATEFUL_ERC712_EXTENDED_STORAGE_LOCATION =
0x1b21ba3f0a2135d61c468900b54084f04af8111bce0f8bbb6ab8c46d11afbd00;
function _getStatefulERC712ExtendedStorageLocation()
internal
pure
returns (StatefulERC712ExtendedStorageStruct storage $)
{
assembly {
$.slot := _STATEFUL_ERC712_EXTENDED_STORAGE_LOCATION
}
}
}
/**
* @title Stateful and upgradeable extension for EIP-712 typed structured data hashing and signing with nonces.
* @author M0 Labs
* @dev An abstract implementation to satisfy stateful EIP-712 with nonces.
*/
abstract contract StatefulERC712Upgradeable is
StatefulERC712ExtendedUpgradeableStorageLayout,
IStatefulERC712,
ERC712ExtendedUpgradeable
{
/* ============ Initializer ============ */
/**
* @notice Initializes the StatefulERC712Upgradeable contract.
* @param name The name of the contract.
*/
function __StatefulERC712ExtendedUpgradeable_init(string memory name) internal onlyInitializing {
__ERC712ExtendedUpgradeable_init(name);
}
/* ============ View/Pure Functions ============ */
/// @inheritdoc IStatefulERC712
function nonces(address account) external view returns (uint256) {
return _getStatefulERC712ExtendedStorageLocation().nonces[account];
}
}
lib/evm-m-extensions/lib/common/src/interfaces/IERC1271.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
/**
* @title Standard Signature Validation Method for Contracts via EIP-1271.
* @author M^0 Labs
* @dev The interface as defined by EIP-1271: https://eips.ethereum.org/EIPS/eip-1271
*/
interface IERC1271 {
/**
* @dev Returns a specific magic value if the provided signature is valid for the provided digest.
* @param digest Hash of the data purported to have been signed.
* @param signature Signature byte array associated with the digest.
* @return magicValue Magic value 0x1626ba7e if the signature is valid.
*/
function isValidSignature(bytes32 digest, bytes memory signature) external view returns (bytes4 magicValue);
}
lib/evm-m-extensions/lib/common/src/interfaces/IERC20.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
/**
* @title ERC20 Token Standard.
* @author M^0 Labs
* @dev The interface as defined by EIP-20: https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
/* ============ Events ============ */
/**
* @notice Emitted when `spender` has been approved for `amount` of the token balance of `account`.
* @param account The address of the account.
* @param spender The address of the spender being approved for the allowance.
* @param amount The amount of the allowance being approved.
*/
event Approval(address indexed account, address indexed spender, uint256 amount);
/**
* @notice Emitted when `amount` tokens is transferred from `sender` to `recipient`.
* @param sender The address of the sender who's token balance is decremented.
* @param recipient The address of the recipient who's token balance is incremented.
* @param amount The amount of tokens being transferred.
*/
event Transfer(address indexed sender, address indexed recipient, uint256 amount);
/* ============ Interactive Functions ============ */
/**
* @notice Allows a calling account to approve `spender` to spend up to `amount` of its token balance.
* @dev MUST emit an `Approval` event.
* @param spender The address of the account being allowed to spend up to the allowed amount.
* @param amount The amount of the allowance being approved.
* @return Whether or not the approval was successful.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @notice Allows a calling account to transfer `amount` tokens to `recipient`.
* @param recipient The address of the recipient who's token balance will be incremented.
* @param amount The amount of tokens being transferred.
* @return Whether or not the transfer was successful.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @notice Allows a calling account to transfer `amount` tokens from `sender`, with allowance, to a `recipient`.
* @param sender The address of the sender who's token balance will be decremented.
* @param recipient The address of the recipient who's token balance will be incremented.
* @param amount The amount of tokens being transferred.
* @return Whether or not the transfer was successful.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/* ============ View/Pure Functions ============ */
/**
* @notice Returns the allowance `spender` is allowed to spend on behalf of `account`.
* @param account The address of the account who's token balance `spender` is allowed to spend.
* @param spender The address of an account allowed to spend on behalf of `account`.
* @return The amount `spender` can spend on behalf of `account`.
*/
function allowance(address account, address spender) external view returns (uint256);
/**
* @notice Returns the token balance of `account`.
* @param account The address of some account.
* @return The token balance of `account`.
*/
function balanceOf(address account) external view returns (uint256);
/// @notice Returns the number of decimals UIs should assume all amounts have.
function decimals() external view returns (uint8);
/// @notice Returns the name of the contract/token.
function name() external view returns (string memory);
/// @notice Returns the symbol of the token.
function symbol() external view returns (string memory);
/// @notice Returns the current total supply of the token.
function totalSupply() external view returns (uint256);
}
lib/evm-m-extensions/lib/common/src/interfaces/IERC20Extended.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
import { IERC20 } from "./IERC20.sol";
import { IERC3009 } from "./IERC3009.sol";
/**
* @title An ERC20 token extended with EIP-2612 permits for signed approvals (via EIP-712
* and with EIP-1271 compatibility), and extended with EIP-3009 transfer with authorization (via EIP-712).
* @author M^0 Labs
* @dev The additional interface as defined by EIP-2612: https://eips.ethereum.org/EIPS/eip-2612
*/
interface IERC20Extended is IERC20, IERC3009 {
/* ============ Custom Errors ============ */
/**
* @notice Revert message when spender's allowance is not sufficient.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @notice Revert message emitted when the transferred amount is insufficient.
* @param amount Amount transferred.
*/
error InsufficientAmount(uint256 amount);
/**
* @notice Revert message emitted when the recipient of a token is invalid.
* @param recipient Address of the invalid recipient.
*/
error InvalidRecipient(address recipient);
/* ============ Interactive Functions ============ */
/**
* @notice Approves `spender` to spend up to `amount` of the token balance of `owner`, via a signature.
* @param owner The address of the account who's token balance is being approved to be spent by `spender`.
* @param spender The address of an account allowed to spend on behalf of `owner`.
* @param value The amount of the allowance being approved.
* @param deadline The last timestamp where the signature is still valid.
* @param v An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
* @param r An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
* @param s An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Approves `spender` to spend up to `amount` of the token balance of `owner`, via a signature.
* @param owner The address of the account who's token balance is being approved to be spent by `spender`.
* @param spender The address of an account allowed to spend on behalf of `owner`.
* @param value The amount of the allowance being approved.
* @param deadline The last timestamp where the signature is still valid.
* @param signature An arbitrary signature (EIP-712).
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, bytes memory signature) external;
/* ============ View/Pure Functions ============ */
/// @notice Returns the EIP712 typehash used in the encoding of the digest for the permit function.
function PERMIT_TYPEHASH() external view returns (bytes32);
}
lib/evm-m-extensions/lib/common/src/interfaces/IERC3009.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
import { IStatefulERC712 } from "./IStatefulERC712.sol";
/**
* @title Transfer via signed authorization following EIP-3009 standard.
* @author M^0 Labs
* @dev The interface as defined by EIP-3009: https://eips.ethereum.org/EIPS/eip-3009
*/
interface IERC3009 is IStatefulERC712 {
/* ============ Events ============ */
/**
* @notice Emitted when an authorization has been canceled.
* @param authorizer Authorizer's address.
* @param nonce Nonce of the canceled authorization.
*/
event AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce);
/**
* @notice Emitted when an authorization has been used.
* @param authorizer Authorizer's address.
* @param nonce Nonce of the used authorization.
*/
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
/* ============ Custom Errors ============ */
/**
* @notice Emitted when an authorization has already been used.
* @param authorizer Authorizer's address.
* @param nonce Nonce of the used authorization.
*/
error AuthorizationAlreadyUsed(address authorizer, bytes32 nonce);
/**
* @notice Emitted when an authorization is expired.
* @param timestamp Timestamp at which the transaction was submitted.
* @param validBefore Timestamp before which the authorization would have been valid.
*/
error AuthorizationExpired(uint256 timestamp, uint256 validBefore);
/**
* @notice Emitted when an authorization is not yet valid.
* @param timestamp Timestamp at which the transaction was submitted.
* @param validAfter Timestamp after which the authorization will be valid.
*/
error AuthorizationNotYetValid(uint256 timestamp, uint256 validAfter);
/**
* @notice Emitted when the caller of `receiveWithAuthorization` is not the payee.
* @param caller Caller's address.
* @param payee Payee's address.
*/
error CallerMustBePayee(address caller, address payee);
/* ============ Interactive Functions ============ */
/**
* @notice Execute a transfer with a signed authorization.
* @param from Payer's address (Authorizer).
* @param to Payee's address.
* @param value Amount to be transferred.
* @param validAfter The time after which this is valid (unix time).
* @param validBefore The time before which this is valid (unix time).
* @param nonce Unique nonce.
* @param signature A byte array ECDSA/secp256k1 signature (encoded r, s, v).
*/
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
bytes memory signature
) external;
/**
* @notice Execute a transfer with a signed authorization.
* @param from Payer's address (Authorizer).
* @param to Payee's address.
* @param value Amount to be transferred.
* @param validAfter The time after which this is valid (unix time).
* @param validBefore The time before which this is valid (unix time).
* @param nonce Unique nonce.
* @param r An ECDSA/secp256k1 signature parameter.
* @param vs An ECDSA/secp256k1 short signature parameter.
*/
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
bytes32 r,
bytes32 vs
) external;
/**
* @notice Execute a transfer with a signed authorization.
* @param from Payer's address (Authorizer).
* @param to Payee's address.
* @param value Amount to be transferred.
* @param validAfter The time after which this is valid (unix time).
* @param validBefore The time before which this is valid (unix time).
* @param nonce Unique nonce.
* @param v v of the signature.
* @param r r of the signature.
* @param s s of the signature.
*/
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Receive a transfer with a signed authorization from the payer.
* @dev This has an additional check to ensure that the payee's address matches
* the caller of this function to prevent front-running attacks.
* (See security considerations)
* @param from Payer's address (Authorizer).
* @param to Payee's address.
* @param value Amount to be transferred.
* @param validAfter The time after which this is valid (unix time).
* @param validBefore The time before which this is valid (unix time).
* @param nonce Unique nonce.
* @param signature A byte array ECDSA/secp256k1 signature (encoded r, s, v).
*/
function receiveWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
bytes memory signature
) external;
/**
* @notice Receive a transfer with a signed authorization from the payer.
* @dev This has an additional check to ensure that the payee's address matches
* the caller of this function to prevent front-running attacks.
* (See security considerations)
* @param from Payer's address (Authorizer).
* @param to Payee's address.
* @param value Amount to be transferred.
* @param validAfter The time after which this is valid (unix time).
* @param validBefore The time before which this is valid (unix time).
* @param nonce Unique nonce.
* @param r An ECDSA/secp256k1 signature parameter.
* @param vs An ECDSA/secp256k1 short signature parameter.
*/
function receiveWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
bytes32 r,
bytes32 vs
) external;
/**
* @notice Receive a transfer with a signed authorization from the payer.
* @dev This has an additional check to ensure that the payee's address matches
* the caller of this function to prevent front-running attacks.
* (See security considerations)
* @param from Payer's address (Authorizer).
* @param to Payee's address.
* @param value Amount to be transferred.
* @param validAfter The time after which this is valid (unix time).
* @param validBefore The time before which this is valid (unix time).
* @param nonce Unique nonce.
* @param v v of the signature.
* @param r r of the signature.
* @param s s of the signature.
*/
function receiveWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Attempt to cancel an authorization.
* @param authorizer Authorizer's address.
* @param nonce Nonce of the authorization.
* @param signature A byte array ECDSA/secp256k1 signature (encoded r, s, v).
*/
function cancelAuthorization(address authorizer, bytes32 nonce, bytes memory signature) external;
/**
* @notice Attempt to cancel an authorization.
* @param authorizer Authorizer's address.
* @param nonce Nonce of the authorization.
* @param r An ECDSA/secp256k1 signature parameter.
* @param vs An ECDSA/secp256k1 short signature parameter.
*/
function cancelAuthorization(address authorizer, bytes32 nonce, bytes32 r, bytes32 vs) external;
/**
* @notice Attempt to cancel an authorization.
* @param authorizer Authorizer's address.
* @param nonce Nonce of the authorization.
* @param v v of the signature.
* @param r r of the signature.
* @param s s of the signature.
*/
function cancelAuthorization(address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external;
/* ============ View/Pure Functions ============ */
/**
* @notice Returns the state of an authorization.
* @dev Nonces are randomly generated 32-byte data unique to the authorizer's address
* @param authorizer Authorizer's address.
* @param nonce Nonce of the authorization.
* @return True if the nonce is used.
*/
function authorizationState(address authorizer, bytes32 nonce) external view returns (bool);
/// @notice Returns `transferWithAuthorization` typehash.
function TRANSFER_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32);
/// @notice Returns `receiveWithAuthorization` typehash.
function RECEIVE_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32);
/// @notice Returns `cancelAuthorization` typehash.
function CANCEL_AUTHORIZATION_TYPEHASH() external view returns (bytes32);
}
lib/evm-m-extensions/lib/common/src/interfaces/IERC712.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
/**
* @title Typed structured data hashing and signing via EIP-712.
* @author M^0 Labs
* @dev The interface as defined by EIP-712: https://eips.ethereum.org/EIPS/eip-712
*/
interface IERC712 {
/* ============ Custom Errors ============ */
/// @notice Revert message when an invalid signature is detected.
error InvalidSignature();
/// @notice Revert message when a signature with invalid length is detected.
error InvalidSignatureLength();
/// @notice Revert message when the S portion of a signature is invalid.
error InvalidSignatureS();
/// @notice Revert message when the V portion of a signature is invalid.
error InvalidSignatureV();
/**
* @notice Revert message when a signature is being used beyond its deadline (i.e. expiry).
* @param deadline The last timestamp where the signature is still valid.
* @param timestamp The current timestamp.
*/
error SignatureExpired(uint256 deadline, uint256 timestamp);
/// @notice Revert message when a recovered signer does not match the account being purported to have signed.
error SignerMismatch();
/* ============ View/Pure Functions ============ */
/// @notice Returns the EIP712 domain separator used in the encoding of a signed digest.
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/evm-m-extensions/lib/common/src/interfaces/IERC712Extended.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
import { IERC712 } from "./IERC712.sol";
/**
* @title EIP-712 extended by EIP-5267.
* @author M^0 Labs
* @dev The additional interface as defined by EIP-5267: https://eips.ethereum.org/EIPS/eip-5267
*/
interface IERC712Extended is IERC712 {
/* ============ Events ============ */
/// @notice MAY be emitted to signal that the domain could have changed.
event EIP712DomainChanged();
/* ============ View/Pure Functions ============ */
/// @notice Returns the fields and values that describe the domain separator used by this contract for EIP-712.
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}
lib/evm-m-extensions/lib/common/src/interfaces/IStatefulERC712.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
import { IERC712Extended } from "./IERC712Extended.sol";
/**
* @title Stateful Extension for EIP-712 typed structured data hashing and signing with nonces.
* @author M^0 Labs
*/
interface IStatefulERC712 is IERC712Extended {
/* ============ Custom Errors ============ */
/**
* @notice Revert message when a signing account's nonce is not the expected current nonce.
* @param nonce The nonce used in the signature.
* @param expectedNonce The expected nonce to be used in a signature by the signing account.
*/
error InvalidAccountNonce(uint256 nonce, uint256 expectedNonce);
/* ============ View/Pure Functions ============ */
/**
* @notice Returns the next nonce to be used in a signature by `account`.
* @param account The address of some account.
* @return nonce The next nonce to be used in a signature by `account`.
*/
function nonces(address account) external view returns (uint256 nonce);
}
lib/evm-m-extensions/lib/common/src/libs/SignatureChecker.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
import { IERC1271 } from "../interfaces/IERC1271.sol";
/**
* @title A library to handle ECDSA/secp256k1 and ERC1271 signatures, individually or in arbitrarily in combination.
* @author M^0 Labs
*/
library SignatureChecker {
/* ============ Enums ============ */
/**
* @notice An enum representing the possible errors that can be emitted during signature validation.
* @param NoError No error occurred during signature validation.
* @param InvalidSignature The signature is invalid.
* @param InvalidSignatureLength The signature length is invalid.
* @param InvalidSignatureS The signature parameter S is invalid.
* @param InvalidSignatureV The signature parameter V is invalid.
* @param SignerMismatch The signer does not match the recovered signer.
*/
enum Error {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV,
SignerMismatch
}
/* ============ Internal View/Pure Functions ============ */
/**
* @dev Returns whether a signature is valid (ECDSA/secp256k1 or ERC1271) for a signer and digest.
* @dev Signatures must not be used as unique identifiers since the `ecrecover` EVM opcode
* allows for malleable (non-unique) signatures.
* See https://github.com/OpenZeppelin/openzeppelin-contracts/security/advisories/GHSA-4h98-2769-gh6h
* @param signer The address of the account purported to have signed.
* @param digest The hash of the data that was signed.
* @param signature A byte array signature.
* @return Whether the signature is valid or not.
*/
function isValidSignature(address signer, bytes32 digest, bytes memory signature) internal view returns (bool) {
return isValidECDSASignature(signer, digest, signature) || isValidERC1271Signature(signer, digest, signature);
}
/**
* @dev Returns whether an ERC1271 signature is valid for a signer and digest.
* @param signer The address of the account purported to have signed.
* @param digest The hash of the data that was signed.
* @param signature A byte array ERC1271 signature.
* @return Whether the signature is valid or not.
*/
function isValidERC1271Signature(
address signer,
bytes32 digest,
bytes memory signature
) internal view returns (bool) {
(bool success_, bytes memory result_) = signer.staticcall(
abi.encodeCall(IERC1271.isValidSignature, (digest, signature))
);
return
success_ &&
result_.length >= 32 &&
abi.decode(result_, (bytes32)) == bytes32(IERC1271.isValidSignature.selector);
}
/**
* @dev Decodes an ECDSA/secp256k1 signature from a byte array to standard v, r, and s parameters.
* @param signature A byte array ECDSA/secp256k1 signature.
* @return v An ECDSA/secp256k1 signature parameter.
* @return r An ECDSA/secp256k1 signature parameter.
* @return s An ECDSA/secp256k1 signature parameter.
*/
function decodeECDSASignature(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
// ecrecover takes the signature parameters, and they can be decoded using assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
}
/**
* @dev Decodes an ECDSA/secp256k1 short signature as defined by EIP2098
* from a byte array to standard v, r, and s parameters.
* @param signature A byte array ECDSA/secp256k1 short signature.
* @return r An ECDSA/secp256k1 signature parameter.
* @return vs An ECDSA/secp256k1 short signature parameter.
*/
function decodeShortECDSASignature(bytes memory signature) internal pure returns (bytes32 r, bytes32 vs) {
// ecrecover takes the signature parameters, and they can be decoded using assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
}
/**
* @dev Returns whether an ECDSA/secp256k1 signature is valid for a signer and digest.
* @param signer The address of the account purported to have signed.
* @param digest The hash of the data that was signed.
* @param signature A byte array ECDSA/secp256k1 signature (encoded r, s, v).
* @return Whether the signature is valid or not.
*/
function isValidECDSASignature(
address signer,
bytes32 digest,
bytes memory signature
) internal pure returns (bool) {
if (signature.length == 64) {
(bytes32 r, bytes32 vs) = decodeShortECDSASignature(signature);
return isValidECDSASignature(signer, digest, r, vs);
}
return validateECDSASignature(signer, digest, signature) == Error.NoError;
}
/**
* @dev Returns whether an ECDSA/secp256k1 short signature is valid for a signer and digest.
* @param signer The address of the account purported to have signed.
* @param digest The hash of the data that was signed.
* @param r An ECDSA/secp256k1 signature parameter.
* @param vs An ECDSA/secp256k1 short signature parameter.
* @return Whether the signature is valid or not.
*/
function isValidECDSASignature(address signer, bytes32 digest, bytes32 r, bytes32 vs) internal pure returns (bool) {
return validateECDSASignature(signer, digest, r, vs) == Error.NoError;
}
/**
* @dev Returns the signer of an ECDSA/secp256k1 signature for some digest.
* @param digest The hash of the data that was signed.
* @param signature A byte array ECDSA/secp256k1 signature.
* @return An error, if any, that occurred during the signer recovery.
* @return The address of the account recovered form the signature (0 if error).
*/
function recoverECDSASigner(bytes32 digest, bytes memory signature) internal pure returns (Error, address) {
if (signature.length != 65) return (Error.InvalidSignatureLength, address(0));
(uint8 v, bytes32 r, bytes32 s) = decodeECDSASignature(signature);
return recoverECDSASigner(digest, v, r, s);
}
/**
* @dev Returns the signer of an ECDSA/secp256k1 short signature for some digest.
* @dev See https://eips.ethereum.org/EIPS/eip-2098
* @param digest The hash of the data that was signed.
* @param r An ECDSA/secp256k1 signature parameter.
* @param vs An ECDSA/secp256k1 short signature parameter.
* @return An error, if any, that occurred during the signer recovery.
* @return The address of the account recovered form the signature (0 if error).
*/
function recoverECDSASigner(bytes32 digest, bytes32 r, bytes32 vs) internal pure returns (Error, address) {
unchecked {
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
return recoverECDSASigner(digest, v, r, s);
}
}
/**
* @dev Returns the signer of an ECDSA/secp256k1 signature for some digest.
* @param digest The hash of the data that was signed.
* @param v An ECDSA/secp256k1 signature parameter.
* @param r An ECDSA/secp256k1 signature parameter.
* @param s An ECDSA/secp256k1 signature parameter.
* @return An error, if any, that occurred during the signer recovery.
* @return signer The address of the account recovered form the signature (0 if error).
*/
function recoverECDSASigner(
bytes32 digest,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (Error, address signer) {
// Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}.
if (uint256(s) > uint256(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0))
return (Error.InvalidSignatureS, address(0));
if (v != 27 && v != 28) return (Error.InvalidSignatureV, address(0));
signer = ecrecover(digest, v, r, s);
return (signer == address(0)) ? (Error.InvalidSignature, address(0)) : (Error.NoError, signer);
}
/**
* @dev Returns an error, if any, in validating an ECDSA/secp256k1 signature for a signer and digest.
* @param signer The address of the account purported to have signed.
* @param digest The hash of the data that was signed.
* @param signature A byte array ERC1271 signature.
* @return An error, if any, that occurred during the signer recovery.
*/
function validateECDSASignature(
address signer,
bytes32 digest,
bytes memory signature
) internal pure returns (Error) {
(Error recoverError, address recoveredSigner) = recoverECDSASigner(digest, signature);
return (recoverError == Error.NoError) ? validateRecoveredSigner(signer, recoveredSigner) : recoverError;
}
/**
* @dev Returns an error, if any, in validating an ECDSA/secp256k1 short signature for a signer and digest.
* @param signer The address of the account purported to have signed.
* @param digest The hash of the data that was signed.
* @param r An ECDSA/secp256k1 signature parameter.
* @param vs An ECDSA/secp256k1 short signature parameter.
* @return An error, if any, that occurred during the signer recovery.
*/
function validateECDSASignature(
address signer,
bytes32 digest,
bytes32 r,
bytes32 vs
) internal pure returns (Error) {
(Error recoverError, address recoveredSigner) = recoverECDSASigner(digest, r, vs);
return (recoverError == Error.NoError) ? validateRecoveredSigner(signer, recoveredSigner) : recoverError;
}
/**
* @dev Returns an error, if any, in validating an ECDSA/secp256k1 signature for a signer and digest.
* @param signer The address of the account purported to have signed.
* @param digest The hash of the data that was signed.
* @param v An ECDSA/secp256k1 signature parameter.
* @param r An ECDSA/secp256k1 signature parameter.
* @param s An ECDSA/secp256k1 signature parameter.
* @return An error, if any, that occurred during the signer recovery.
*/
function validateECDSASignature(
address signer,
bytes32 digest,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (Error) {
(Error recoverError, address recoveredSigner) = recoverECDSASigner(digest, v, r, s);
return (recoverError == Error.NoError) ? validateRecoveredSigner(signer, recoveredSigner) : recoverError;
}
/**
* @dev Returns an error if `signer` is not `recoveredSigner`.
* @param signer The address of the some signer.
* @param recoveredSigner The address of the some recoveredSigner.
* @return An error if `signer` is not `recoveredSigner`.
*/
function validateRecoveredSigner(address signer, address recoveredSigner) internal pure returns (Error) {
return (signer == recoveredSigner) ? Error.NoError : Error.SignerMismatch;
}
}
lib/evm-m-extensions/lib/common/src/libs/UIntMath.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;
/**
* @title Library to perform safe math operations on uint types
* @author M^0 Labs
*/
library UIntMath {
/* ============ Custom Errors ============ */
/// @notice Emitted when a passed value is greater than the maximum value of uint16.
error InvalidUInt16();
/// @notice Emitted when a passed value is greater than the maximum value of uint32.
error InvalidUInt32();
/// @notice Emitted when a passed value is greater than the maximum value of uint40.
error InvalidUInt40();
/// @notice Emitted when a passed value is greater than the maximum value of uint48.
error InvalidUInt48();
/// @notice Emitted when a passed value is greater than the maximum value of uint112.
error InvalidUInt112();
/// @notice Emitted when a passed value is greater than the maximum value of uint128.
error InvalidUInt128();
/// @notice Emitted when a passed value is greater than the maximum value of uint240.
error InvalidUInt240();
/* ============ Internal View/Pure Functions ============ */
/**
* @notice Casts a uint256 value to a uint16, ensuring that it is less than or equal to the maximum uint16 value.
* @param n The value to cast.
* @return The value casted to uint16.
*/
function safe16(uint256 n) internal pure returns (uint16) {
if (n > type(uint16).max) revert InvalidUInt16();
return uint16(n);
}
/**
* @notice Casts a uint256 value to a uint32, ensuring that it is less than or equal to the maximum uint32 value.
* @param n The value to cast.
* @return The value casted to uint32.
*/
function safe32(uint256 n) internal pure returns (uint32) {
if (n > type(uint32).max) revert InvalidUInt32();
return uint32(n);
}
/**
* @notice Casts a uint256 value to a uint40, ensuring that it is less than or equal to the maximum uint40 value.
* @param n The value to cast.
* @return The value casted to uint40.
*/
function safe40(uint256 n) internal pure returns (uint40) {
if (n > type(uint40).max) revert InvalidUInt40();
return uint40(n);
}
/**
* @notice Casts a uint256 value to a uint48, ensuring that it is less than or equal to the maximum uint48 value.
* @param n The value to cast.
* @return The value casted to uint48.
*/
function safe48(uint256 n) internal pure returns (uint48) {
if (n > type(uint48).max) revert InvalidUInt48();
return uint48(n);
}
/**
* @notice Casts a uint256 value to a uint112, ensuring that it is less than or equal to the maximum uint112 value.
* @param n The value to cast.
* @return The value casted to uint112.
*/
function safe112(uint256 n) internal pure returns (uint112) {
if (n > type(uint112).max) revert InvalidUInt112();
return uint112(n);
}
/**
* @notice Casts a uint256 value to a uint128, ensuring that it is less than or equal to the maximum uint128 value.
* @param n The value to cast.
* @return The value casted to uint128.
*/
function safe128(uint256 n) internal pure returns (uint128) {
if (n > type(uint128).max) revert InvalidUInt128();
return uint128(n);
}
/**
* @notice Casts a uint256 value to a uint240, ensuring that it is less than or equal to the maximum uint240 value.
* @param n The value to cast.
* @return The value casted to uint240.
*/
function safe240(uint256 n) internal pure returns (uint240) {
if (n > type(uint240).max) revert InvalidUInt240();
return uint240(n);
}
/**
* @notice Limits a uint256 value to the maximum uint32 value.
* @param n The value to bound.
* @return The value limited to within uint32 bounds.
*/
function bound32(uint256 n) internal pure returns (uint32) {
return uint32(min256(n, uint256(type(uint32).max)));
}
/**
* @notice Limits a uint256 value to the maximum uint112 value.
* @param n The value to bound.
* @return The value limited to within uint112 bounds.
*/
function bound112(uint256 n) internal pure returns (uint112) {
return uint112(min256(n, uint256(type(uint112).max)));
}
/**
* @notice Limits a uint256 value to the maximum uint128 value.
* @param n The value to bound.
* @return The value limited to within uint128 bounds.
*/
function bound128(uint256 n) internal pure returns (uint128) {
return uint128(min256(n, uint256(type(uint128).max)));
}
/**
* @notice Limits a uint256 value to the maximum uint240 value.
* @param n The value to bound.
* @return The value limited to within uint240 bounds.
*/
function bound240(uint256 n) internal pure returns (uint240) {
return uint240(min256(n, uint256(type(uint240).max)));
}
/**
* @notice Compares two uint32 values and returns the larger one.
* @param a Value to compare.
* @param b Value to compare.
* @return The larger value.
*/
function max32(uint32 a, uint32 b) internal pure returns (uint32) {
return a > b ? a : b;
}
/**
* @notice Compares two uint40 values and returns the larger one.
* @param a Value to compare.
* @param b Value to compare.
* @return The larger value.
*/
function max40(uint40 a, uint40 b) internal pure returns (uint40) {
return a > b ? a : b;
}
/**
* @notice Compares two uint128 values and returns the larger one.
* @param a Value to compare.
* @param b Value to compare.
* @return The larger value.
*/
function max128(uint128 a, uint128 b) internal pure returns (uint128) {
return a > b ? a : b;
}
/**
* @notice Compares two uint240 values and returns the larger one.
* @param a Value to compare.
* @param b Value to compare.
* @return The larger value.
*/
function max240(uint240 a, uint240 b) internal pure returns (uint240) {
return a > b ? a : b;
}
/**
* @notice Compares two uint32 values and returns the lesser one.
* @param a Value to compare.
* @param b Value to compare.
* @return The lesser value.
*/
function min32(uint32 a, uint32 b) internal pure returns (uint32) {
return a < b ? a : b;
}
/**
* @notice Compares two uint40 values and returns the lesser one.
* @param a Value to compare.
* @param b Value to compare.
* @return The lesser value.
*/
function min40(uint40 a, uint40 b) internal pure returns (uint40) {
return a < b ? a : b;
}
/**
* @notice Compares two uint240 values and returns the lesser one.
* @param a Value to compare.
* @param b Value to compare.
* @return The lesser value.
*/
function min240(uint240 a, uint240 b) internal pure returns (uint240) {
return a < b ? a : b;
}
/**
* @notice Compares two uint112 values and returns the lesser one.
* @param a Value to compare.
* @param b Value to compare.
* @return The lesser value.
*/
function min112(uint112 a, uint112 b) internal pure returns (uint112) {
return a < b ? a : b;
}
/**
* @notice Compares two uint256 values and returns the lesser one.
* @param a Value to compare.
* @param b Value to compare.
* @return The lesser value.
*/
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
lib/evm-m-extensions/src/components/freezable/Freezable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import { AccessControlUpgradeable } from "../../../lib/common/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import { IFreezable } from "./IFreezable.sol";
abstract contract FreezableStorageLayout {
/// @custom:storage-location erc7201:M0.storage.Freezable
struct FreezableStorageStruct {
mapping(address account => bool isFrozen) isFrozen;
}
// keccak256(abi.encode(uint256(keccak256("M0.storage.Freezable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant _FREEZABLE_STORAGE_LOCATION =
0x2fd5767309dce890c526ace85d7fe164825199d7dcd99c33588befc51b32ce00;
function _getFreezableStorageLocation() internal pure returns (FreezableStorageStruct storage $) {
assembly {
$.slot := _FREEZABLE_STORAGE_LOCATION
}
}
}
/**
* @title Freezable
* @notice Upgradeable contract that allows for the freezing of accounts.
* @dev This contract is used to prevent certain accounts from interacting with the contract.
* @author M0 Labs
*/
abstract contract Freezable is IFreezable, FreezableStorageLayout, AccessControlUpgradeable {
/* ============ Variables ============ */
/// @inheritdoc IFreezable
bytes32 public constant FREEZE_MANAGER_ROLE = keccak256("FREEZE_MANAGER_ROLE");
/* ============ Initializer ============ */
/**
* @notice Initializes the contract with the given freeze manager.
* @param freezeManager The address of a freeze manager.
*/
function __Freezable_init(address freezeManager) internal onlyInitializing {
if (freezeManager == address(0)) revert ZeroFreezeManager();
_grantRole(FREEZE_MANAGER_ROLE, freezeManager);
}
/* ============ Interactive Functions ============ */
/// @inheritdoc IFreezable
function freeze(address account) external virtual onlyRole(FREEZE_MANAGER_ROLE) {
_freeze(_getFreezableStorageLocation(), account);
}
/// @inheritdoc IFreezable
function freezeAccounts(address[] calldata accounts) external virtual onlyRole(FREEZE_MANAGER_ROLE) {
FreezableStorageStruct storage $ = _getFreezableStorageLocation();
for (uint256 i; i < accounts.length; ++i) {
_freeze($, accounts[i]);
}
}
/// @inheritdoc IFreezable
function unfreeze(address account) external onlyRole(FREEZE_MANAGER_ROLE) {
_unfreeze(_getFreezableStorageLocation(), account);
}
/// @inheritdoc IFreezable
function unfreezeAccounts(address[] calldata accounts) external onlyRole(FREEZE_MANAGER_ROLE) {
FreezableStorageStruct storage $ = _getFreezableStorageLocation();
for (uint256 i; i < accounts.length; ++i) {
_unfreeze($, accounts[i]);
}
}
/* ============ View/Pure Functions ============ */
/// @inheritdoc IFreezable
function isFrozen(address account) public view returns (bool) {
return _getFreezableStorageLocation().isFrozen[account];
}
/* ============ Hooks For Internal Interactive Functions ============ */
/**
* @dev Hook called before freezing an account.
* @param account The account to be frozen.
*/
function _beforeFreeze(address account) internal virtual {}
/**
* @dev Hook called before unfreezing an account.
* @param account The account to be unfrozen.
*/
function _beforeUnfreeze(address account) internal virtual {}
/* ============ Internal Interactive Functions ============ */
/**
* @notice Internal function that freezes an account.
* @param $ The storage location of the freezable contract.
* @param account The account to freeze.
*/
function _freeze(FreezableStorageStruct storage $, address account) internal {
// Return early if the account is already frozen
if ($.isFrozen[account]) return;
_beforeFreeze(account);
$.isFrozen[account] = true;
emit Frozen(account, block.timestamp);
}
/**
* @notice Internal function that unfreezes an account.
* @param $ The storage location of the freezable contract.
* @param account The account to unfreeze.
*/
function _unfreeze(FreezableStorageStruct storage $, address account) internal {
// Return early if the account is not frozen
if (!$.isFrozen[account]) return;
_beforeUnfreeze(account);
$.isFrozen[account] = false;
emit Unfrozen(account, block.timestamp);
}
/* ============ Internal View/Pure Functions ============ */
/**
* @notice Internal function that reverts if an account is frozen.
* @dev Called by inheriting contracts to check if an account is frozen.
* @param $ The storage location of the freezable contract.
* @param account The account to check.
*/
function _revertIfFrozen(FreezableStorageStruct storage $, address account) internal view {
if ($.isFrozen[account]) revert AccountFrozen(account);
}
/**
* @notice Internal function that reverts if an account is frozen.
* @dev Called by inheriting contracts to check if an account is frozen.
* @param account The account to check.
*/
function _revertIfFrozen(address account) internal view {
if (_getFreezableStorageLocation().isFrozen[account]) revert AccountFrozen(account);
}
/**
* @notice Internal function that reverts if an account is not frozen.
* @dev Called by inheriting contracts to check if an account is not frozen.
* @param $ The storage location of the freezable contract.
* @param account The account to check.
*/
function _revertIfNotFrozen(FreezableStorageStruct storage $, address account) internal view {
if (!$.isFrozen[account]) revert AccountNotFrozen(account);
}
/**
* @notice Internal function that reverts if an account is not frozen.
* @dev Called by inheriting contracts to check if an account is not frozen.
* @param account The account to check.
*/
function _revertIfNotFrozen(address account) internal view {
if (!_getFreezableStorageLocation().isFrozen[account]) revert AccountNotFrozen(account);
}
}
lib/evm-m-extensions/src/components/freezable/IFreezable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
/**
* @title Freezable interface.
* @author M0 Labs
*/
interface IFreezable {
/* ============ Events ============ */
/**
* @notice Emitted when an account is frozen.
* @param account The address of the frozen account.
* @param timestamp The timestamp at which the account was frozen.
*/
event Frozen(address indexed account, uint256 timestamp);
/**
* @notice Emitted when an account is unfrozen.
* @param account The address of the unfrozen account.
* @param timestamp The timestamp at which the account was unfrozen.
*/
event Unfrozen(address indexed account, uint256 timestamp);
/* ============ Errors ============ */
/**
* @notice Emitted when an account is already frozen.
* @param account The address of the frozen account.
*/
error AccountFrozen(address account);
/**
* @notice Emitted when an account is not frozen.
* @param account The address of the account that is not frozen.
*/
error AccountNotFrozen(address account);
/// @notice Emitted if no freeze manager is set.
error ZeroFreezeManager();
/* ============ Interactive Functions ============ */
/**
* @notice Freezes an account.
* @dev MUST only be callable by the FREEZE_MANAGER_ROLE.
* @param account The address of the account to freeze.
*/
function freeze(address account) external;
/**
* @notice Freezes multiple accounts.
* @dev MUST only be callable by the FREEZE_MANAGER_ROLE.
* @param accounts The list of addresses to freeze.
*/
function freezeAccounts(address[] calldata accounts) external;
/**
* @notice Unfreezes an account.
* @dev MUST only be callable by the FREEZE_MANAGER_ROLE.
* @param account The address of the account to unfreeze.
*/
function unfreeze(address account) external;
/**
* @notice Unfreezes multiple accounts.
* @dev MUST only be callable by the FREEZE_MANAGER_ROLE.
* @param accounts The list of addresses to unfreeze.
*/
function unfreezeAccounts(address[] calldata accounts) external;
/* ============ View/Pure Functions ============ */
/// @notice The role that can manage the freezelist.
function FREEZE_MANAGER_ROLE() external view returns (bytes32);
/**
* @notice Returns whether an account is frozen or not.
* @param account The address of the account to check.
* @return True if the account is frozen, false otherwise.
*/
function isFrozen(address account) external view returns (bool);
}
lib/evm-m-extensions/src/components/pausable/IPausable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
/**
* @title Pausable interface.
* @author M0 Labs
*/
interface IPausable {
/* ============ Errors ============ */
/// @notice Emitted if no pauser is set.
error ZeroPauser();
/* ============ Interactive Functions ============ */
/**
* @notice Pauses the contract.
* @dev Can only be called by an account with the PAUSER_ROLE.
* @dev When paused, wrap/unwrap and transfer of tokens should be disabled.
* Approval should still be enabled to allow users to change their allowances.
*/
function pause() external;
/**
* @notice Unpauses the contract.
* @dev Can only be called by an account with the PAUSER_ROLE.
*/
function unpause() external;
/* ============ View/Pure Functions ============ */
/// @notice The role that can pause/unpause the contract.
function PAUSER_ROLE() external view returns (bytes32);
}
lib/evm-m-extensions/src/components/pausable/Pausable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import { AccessControlUpgradeable } from "../../../lib/common/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import { PausableUpgradeable } from "../../../lib/common/lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol";
import { IPausable } from "./IPausable.sol";
/**
* @title Pausable
* @notice Upgradeable contract that allows to pause the inheriting contract.
* @dev Relies on PausableUpgradeable from OpenZeppelin for pause functionality.
* @author M0 Labs
*/
abstract contract Pausable is IPausable, AccessControlUpgradeable, PausableUpgradeable {
/* ============ Variables ============ */
/// @inheritdoc IPausable
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/* ============ Initializer ============ */
/**
* @notice Initializes the contract with the given pauser.
* @param pauser The address of a pauser.
*/
function __Pausable_init(address pauser) internal onlyInitializing {
if (pauser == address(0)) revert ZeroPauser();
_grantRole(PAUSER_ROLE, pauser);
}
/* ============ Interactive Functions ============ */
/// @inheritdoc IPausable
function pause() external onlyRole(PAUSER_ROLE) {
_beforePause();
_pause();
}
/// @inheritdoc IPausable
function unpause() external onlyRole(PAUSER_ROLE) {
_beforeUnpause();
_unpause();
}
/* ============ Hooks For Internal Interactive Functions ============ */
/**
* @dev Hook called before pausing the contract.
*/
function _beforePause() internal virtual {}
/**
* @dev Hook called before unpausing the contract.
*/
function _beforeUnpause() internal virtual {}
}
src/IPYUSDX.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.34;
/// @title IPYUSDX
/// @author M0 Labs
/// @notice Interface for PYUSDX upgradeable ERC20 non-rebasing token with claimable yield
/// @dev PYUSDX is an upgradeable ERC20 token with:
/// - Claimable yield via continuous indexing
/// - Built-in pausing and compliance functionalities
/// - Earner Manager controlled yield distribution
interface IPYUSDX {
/* ============ Events ============ */
/// @notice Emitted when earning is started for an account.
/// @param account The account that started earning.
event StartedEarning(address indexed account);
/// @notice Emitted when earning is stopped for an account.
/// @param account The account that stopped earning.
event StoppedEarning(address indexed account);
/// @notice Emitted when account info is updated.
/// @param account The account that was updated.
/// @param earnerRate The new earner rate in basis points (0 = not earning).
/// @param feeRate The new fee rate in basis points.
/// @param claimRecipient The new claim recipient address.
event AccountInfoUpdated(
address indexed account,
uint16 earnerRate,
uint16 feeRate,
address indexed claimRecipient
);
/// @notice Emitted when the earner manager is set or updated.
/// @param earnerManager The address of the new earner manager.
event EarnerManagerSet(address indexed earnerManager);
/// @notice Emitted when an account's index is updated.
event IndexUpdated(address indexed account, uint128 currentIndex);
/// @notice Emitted when yield is claimed for an account.
event YieldClaimed(address indexed account, uint256 yieldNetOfFee);
/// @notice Emitted when a fee is claimed from an account's yield.
event FeeClaimed(address indexed account, address indexed recipient, uint256 fee);
/// @notice Emitted when earner manager distributed additional reward for an account.
event RewardDistributed(address indexed account, uint256 amount);
/* ============ Structs ============ */
/// @notice Parameters for initializing the PYUSDX contract.
struct InitializeParams {
string name;
string symbol;
address admin;
address pauser;
address freezeManager;
address forcedTransferManager;
address earnerManager;
address rateLimitManager;
address issuer;
}
/* ============ Custom Errors ============ */
/// @notice Thrown when the admin address is zero.
error ZeroAdmin();
/// @notice Thrown when the issuer address is zero.
error ZeroIssuer();
/// @notice Thrown when the earner manager address is zero.
error ZeroEarnerManager();
/// @notice Thrown when an account address is zero.
error ZeroAccount();
/// @notice Thrown when an amount is zero.
error ZeroAmount();
/// @notice Thrown when the caller is not the earner manager.
error NotEarnerManager();
/// @notice Thrown when account info is invalid (e.g., not earning but has fee rate).
error InvalidAccountInfo();
/// @notice Thrown when the fee rate exceeds the maximum.
error FeeRateTooHigh(uint16 feeRate);
/// @notice Thrown when the earner rate exceeds the maximum.
error EarnerRateTooHigh(uint16 earnerRate);
/// @notice Thrown when an input array is empty.
error ArrayLengthZero();
/// @notice Thrown when burn amount exceeds account balance.
error InsufficientBalance(address account, uint256 balance, uint256 amount);
/* ============ Interactive Functions ============ */
/// @notice Mints PYUSDX to an account.
/// @dev MUST only be callable by ISSUER_ROLE.
/// @dev MUST revert if the contract is paused.
/// @dev MUST revert if the account is frozen.
/// @param account The account receiving the minted PYUSDX.
/// @param amount The amount of PYUSDX to mint.
function mint(address account, uint256 amount) external;
/// @notice Burns PYUSDX from an account.
/// @dev MUST only be callable by ISSUER_ROLE.
/// @dev MUST revert if the contract is paused.
/// @dev MUST revert if the account is frozen.
/// @dev `ISSUER_ROLE` is expected to be granted only to contracts that burn from their
/// own non-earning balance (e.g., IssuerGateway, Portal). Burning directly from an
/// earning account does not pre-claim accrued yield: `_subtractEarningAmount` rounds
/// the consumed principal up (e.g. in favor of the protocol), so any unclaimed yield
/// at the time of burn is subject to a sub-unit rounding loss in present value.
/// @param account The account from which PYUSDX is burnt.
/// @param amount The amount of PYUSDX to burn.
function burn(address account, uint256 amount) external;
/// @notice Claims accrued yield for an account.
/// @dev Anyone can call on behalf of any account.
/// @dev MUST revert if the contract is paused.
/// @dev MUST revert if the account is frozen.
/// @param account The account to claim yield for.
/// @return yieldWithFee The gross yield claimed.
/// @return fee The fee deducted.
/// @return yieldNetOfFee The net yield after fee.
function claimFor(address account) external returns (uint256 yieldWithFee, uint256 fee, uint256 yieldNetOfFee);
/// @notice Claims accrued yield for multiple accounts.
/// @dev MUST revert if the contract is paused or any account is frozen.
/// @param accounts The accounts to claim yield for.
/// @return yieldWithFees The gross yield claimed per account.
/// @return fees The fee deducted per account.
/// @return yieldNetOfFees The net yield per account.
function claimFor(
address[] calldata accounts
) external returns (uint256[] memory yieldWithFees, uint256[] memory fees, uint256[] memory yieldNetOfFees);
/// @notice Sets account info for a single account.
/// @dev MUST only be callable by the earner manager.
/// @dev Callable while paused so the earner manager retains an emergency lever over
/// earner configuration. When called while paused, any accrued yield is
/// materialized onto `account`'s own balance and the `claimRecipient` routing and
/// fee `_transfer` are skipped — the earner manager forgoes the fee for that call.
/// The forgone fee is recoverable: `freeze(account)` followed by
/// `forceTransfer(account, feeRecipient, amount)` can move the fee portion out of
/// the earner's balance after the incident response.
/// @param account The account to configure.
/// @param earnerRate The earner rate in basis points (0 to stop earning).
/// @param feeRate The fee rate on yield (basis points, 0-10000).
/// @param claimRecipient The address to receive claimed yield (address(0) to clear).
function setAccountInfo(address account, uint16 earnerRate, uint16 feeRate, address claimRecipient) external;
/// @notice Sets account info for multiple accounts.
/// @dev MUST only be callable by the earner manager.
/// @dev MUST revert if array lengths do not match.
/// @dev Pause semantics match the single-account overload: yield materializes to each
/// account's own balance, fee and `claimRecipient` routing are skipped per entry.
/// The forgone fee on any entry is recoverable post-incident via `freeze` +
/// `forceTransfer`.
/// @param accounts The accounts to configure.
/// @param earnerRates The earner rates for each account (basis points).
/// @param feeRates The fee rates for each account (basis points).
/// @param claimRecipients The addresses to receive claimed yield.
function setAccountInfo(
address[] calldata accounts,
uint16[] calldata earnerRates,
uint16[] calldata feeRates,
address[] calldata claimRecipients
) external;
/// @notice Distributes a reward to an account by minting new PYUSDX.
/// @dev MUST only be callable by the earner manager.
/// @dev MUST revert if the contract is paused.
/// @dev MUST revert if the account is frozen.
/// @param account The account to receive the reward.
/// @param amount The amount of PYUSDX to distribute.
function distributeReward(address account, uint256 amount) external;
/// @notice Sets the earner manager address.
/// @dev MUST only be callable by DEFAULT_ADMIN_ROLE.
/// @param earnerManager The new earner manager address.
function setEarnerManager(address earnerManager) external;
/* ============ View/Pure Functions ============ */
/// @notice The maximum fee rate (10000 = 100%).
function ONE_HUNDRED_PERCENT() external view returns (uint16);
/// @notice Precision scaling for index calculations (1e12).
function EXP_SCALED_ONE() external view returns (uint128);
/// @notice The role that can issue (mint/burn) PYUSDX tokens.
function ISSUER_ROLE() external view returns (bytes32);
/// @notice The earner manager address.
function earnerManager() external view returns (address);
/// @notice Returns whether an account is earning.
/// @param account The account to query.
/// @return True if the account is earning (earnerRate > 0).
function isEarning(address account) external view returns (bool);
/// @notice Returns the recipient of yield claims for an account.
/// @dev Returns the account itself if no claim recipient is set.
/// @param account The account to query.
/// @return The claim recipient address.
function claimRecipientFor(address account) external view returns (address);
/// @notice Returns earning configuration for an account.
/// @param account The account to query.
/// @return earnerRate The earner rate in basis points (0 = not earning).
/// @return feeRate The fee rate on yield (basis points).
/// @return claimRecipient The address that receives claimed yield.
function getAccountEarningInfo(
address account
) external view returns (uint16 earnerRate, uint16 feeRate, address claimRecipient);
/// @notice Returns accrued yield, fee, and net yield for an account.
/// @param account The account to query.
/// @return yieldWithFee The total accrued yield including fee.
/// @return fee The fee portion of the accrued yield.
/// @return yieldNetOfFee The accrued yield net of fee.
function accruedYieldAndFeeOf(
address account
) external view returns (uint256 yieldWithFee, uint256 fee, uint256 yieldNetOfFee);
/// @notice Returns the accrued but unclaimed yield (net of fee) for an account.
/// @param account The account to query.
/// @return The accrued yield net of fee (0 if account not earning).
function accruedYieldOf(address account) external view returns (uint256);
/// @notice Returns the accrued yield that would be claimed by the account itself.
/// @param account The account to query.
/// @return The accrued yield to self (0 if account not earning or yield is redirected).
function accruedYieldToSelfOf(address account) external view returns (uint256);
/// @notice Returns the accrued fee for an account.
/// @param account The account to query.
/// @return The accrued fee (0 if account not earning).
function accruedFeeOf(address account) external view returns (uint256);
/// @notice Returns the token balance including any accrued yield.
/// @dev Note: Claiming yield may not result in this balance if yield is redirected.
/// @param account The account to query.
/// @return Balance plus accrued yield.
function balanceWithYieldOf(address account) external view returns (uint256);
/// @notice Returns the earning principal of an account.
/// @param account The account to query.
/// @return The principal amount used for yield calculations.
function earningPrincipalOf(address account) external view returns (uint112);
/// @notice Returns the stored (last snapshotted) index for an account.
/// @param account The account to query.
/// @return The last stored index value.
function lastIndexOf(address account) external view returns (uint128);
/// @notice Returns the computed current index for an account.
/// @dev Returns EXP_SCALED_ONE (1e12) for non-earners.
/// @param account The account to query.
/// @return The current index value.
function currentIndexOf(address account) external view returns (uint128);
/// @notice Returns the last update timestamp for an account.
/// @param account The account to query.
/// @return The last update timestamp.
function lastUpdateTimestampOf(address account) external view returns (uint40);
}
src/platform/Extension.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.34;
import { ERC20ExtendedUpgradeable } from "../../lib/evm-m-extensions/lib/common/src/ERC20ExtendedUpgradeable.sol";
import { IERC20 } from "../../lib/evm-m-extensions/lib/common/src/interfaces/IERC20.sol";
import { StorageSlot } from "../../lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol";
import { Freezable } from "../../lib/evm-m-extensions/src/components/freezable/Freezable.sol";
import { Pausable } from "../../lib/evm-m-extensions/src/components/pausable/Pausable.sol";
import { IERC1967 } from "../../lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol";
import { IExtension } from "./interfaces/IExtension.sol";
import { IExtensionBeacon } from "./interfaces/IExtensionBeacon.sol";
import { ISwapFacility } from "../swap/interfaces/ISwapFacility.sol";
/// @title Extension
/// @notice Upgradeable ERC20 base contract for wrapping PYUSDX into a branded extension token.
/// @author M0 Labs
abstract contract Extension is IExtension, ERC20ExtendedUpgradeable, Freezable, Pausable {
/* ============ Constants ============ */
/// @dev ERC-1967 beacon storage slot (shared with ExtensionBeaconProxy).
/// bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/// @dev ERC-1967 implementation storage slot (used for pinned mode, shared with ExtensionBeaconProxy).
/// bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/// @dev Storage location for the origin beacon address (shared with ExtensionBeaconProxy).
/// keccak256(abi.encode(uint256(keccak256("M0.storage.PYUSDXOriginBeacon")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant _ORIGIN_BEACON_SLOT = 0x0db096ce50da19b63b97b47df5b0c87e2ed1677b3d801ad424e1bbfc0bb0c300;
/* ============ Variables ============ */
/// @inheritdoc IExtension
bytes32 public constant VERSION_MANAGER_ROLE = keccak256("VERSION_MANAGER_ROLE");
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
/// @inheritdoc IExtension
address public immutable pyusdx;
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
/// @inheritdoc IExtension
address public immutable swapFacility;
/* ============ Modifiers ============ */
modifier onlySwapFacility() {
if (msg.sender != swapFacility) revert NotSwapFacility();
_;
}
/* ============ Constructor ============ */
/// @custom:oz-upgrades-unsafe-allow constructor
/// @notice Constructs Extension Implementation contract.
/// @dev Sets immutable storage.
/// @param pyusdx_ The address of the PYUSDX token.
/// @param swapFacility_ The address of the swap facility.
constructor(address pyusdx_, address swapFacility_) {
if ((pyusdx = pyusdx_) == address(0)) revert ZeroPYUSDX();
if ((swapFacility = swapFacility_) == address(0)) revert ZeroSwapFacility();
_disableInitializers();
}
/* ============ Initializer ============ */
/// @notice Initializes the generic PYUSDX extension token.
/// @param name The name of the token.
/// @param symbol The symbol of the token.
/// @param freezeManager The address of the freeze manager.
/// @param pauser The address of the pauser.
function __Extension_init(
string memory name,
string memory symbol,
address freezeManager,
address pauser
) internal onlyInitializing {
__ERC20ExtendedUpgradeable_init(name, symbol, 6);
__Freezable_init(freezeManager);
__Pausable_init(pauser);
}
/* ============ Interactive Functions ============ */
/// @inheritdoc IExtension
function wrap(address recipient, uint256 amount) external onlySwapFacility {
_wrap(ISwapFacility(msg.sender).msgSender(), recipient, amount);
}
/// @inheritdoc IExtension
function unwrap(uint256 amount) external onlySwapFacility {
_unwrap(ISwapFacility(msg.sender).msgSender(), amount);
}
/// @inheritdoc IExtension
function pinVersion(uint256 version) external onlyRole(VERSION_MANAGER_ROLE) {
if (version == 0) revert ZeroVersion();
address beacon = StorageSlot.getAddressSlot(_ORIGIN_BEACON_SLOT).value;
address implementation = IExtensionBeacon(beacon).implementation(version);
// NOTE: Mutates both ERC-1967 slots to switch the proxy from beacon mode to direct mode,
// so that external ERC-1967 readers (block explorers, tooling) detect a direct proxy
// pointing at the pinned implementation, instead of resolving the latest version via the beacon.
StorageSlot.getAddressSlot(_BEACON_SLOT).value = address(0);
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = implementation;
emit IERC1967.BeaconUpgraded(address(0));
emit IERC1967.Upgraded(implementation);
}
/// @inheritdoc IExtension
function unpinVersion() external onlyRole(VERSION_MANAGER_ROLE) {
if (StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value == address(0)) revert NotPinned();
address beacon = StorageSlot.getAddressSlot(_ORIGIN_BEACON_SLOT).value;
// NOTE: Mutates both ERC-1967 slots to switch the proxy back to beacon mode,
// so external ERC-1967 readers detect a beacon proxy again and
// resolve the latest implementation via the beacon registry.
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = address(0);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = beacon;
emit IERC1967.Upgraded(address(0));
emit IERC1967.BeaconUpgraded(beacon);
}
/* ============ View/Pure Functions ============ */
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256);
/// @inheritdoc IExtension
function pinnedImplementation() public view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/// @inheritdoc IExtension
function originBeacon() external view returns (address) {
return StorageSlot.getAddressSlot(_ORIGIN_BEACON_SLOT).value;
}
/// @inheritdoc IExtension
function isPinned() external view returns (bool) {
return pinnedImplementation() != address(0);
}
/* ============ Hooks For Internal Interactive Functions ============ */
/// @dev Hook called before approval of PYUSDX Extension token.
/// @param account The sender's address.
/// @param spender The spender address.
function _beforeApprove(address account, address spender, uint256 /* amount */) internal view virtual {
FreezableStorageStruct storage $ = _getFreezableStorageLocation();
_revertIfFrozen($, account);
_revertIfFrozen($, spender);
}
/// @dev Hook called before wrapping PYUSDX into PYUSDX Extension token.
/// @param account The account from which PYUSDX is deposited.
/// @param recipient The account receiving the minted PYUSDX Extension token.
function _beforeWrap(address account, address recipient, uint256 /* amount */) internal view virtual {
_requireNotPaused();
FreezableStorageStruct storage $ = _getFreezableStorageLocation();
_revertIfFrozen($, account);
_revertIfFrozen($, recipient);
}
/// @dev Hook called before unwrapping PYUSDX Extension token.
/// @param account The original caller (resolved via swap facility).
function _beforeUnwrap(address account, uint256 /* amount */) internal view virtual {
_requireNotPaused();
_revertIfFrozen(_getFreezableStorageLocation(), account);
}
/// @dev Hook called before transferring PYUSDX Extension token.
/// @param sender The sender's address.
/// @param recipient The recipient's address.
function _beforeTransfer(address sender, address recipient, uint256 /* amount */) internal view virtual {
_requireNotPaused();
FreezableStorageStruct storage $ = _getFreezableStorageLocation();
_revertIfFrozen($, msg.sender);
_revertIfFrozen($, sender);
_revertIfFrozen($, recipient);
}
/* ============ Internal Interactive Functions ============ */
/// @dev Approve `spender` to spend `amount` of tokens from `account`.
/// @param account The address approving the allowance.
/// @param spender The address approved to spend the tokens.
/// @param amount The amount of tokens being approved for spending.
function _approve(address account, address spender, uint256 amount) internal override {
_beforeApprove(account, spender, amount);
super._approve(account, spender, amount);
}
/// @dev Wraps `amount` PYUSDX from `account` into extension token for `recipient`.
/// @param account The original caller (resolved via swap facility).
/// @param recipient The account receiving the minted extension token.
/// @param amount The amount of PYUSDX deposited.
function _wrap(address account, address recipient, uint256 amount) internal {
_revertIfZeroAccount(recipient);
_revertIfZeroAmount(amount);
_beforeWrap(account, recipient, amount);
IERC20(pyusdx).transferFrom(msg.sender, address(this), amount);
_mint(recipient, amount);
}
/// @dev Unwraps `amount` extension token from `account` into PYUSDX.
/// @param account The original caller (resolved via swap facility).
/// @param amount The amount of extension token burned.
function _unwrap(address account, uint256 amount) internal {
_revertIfZeroAmount(amount);
_revertIfInsufficientBalance(msg.sender, amount);
_beforeUnwrap(account, amount);
_burn(msg.sender, amount);
IERC20(pyusdx).transfer(msg.sender, amount);
}
/// @dev Mints `amount` tokens to `recipient`.
/// @param recipient The address to which the tokens will be minted.
/// @param amount The amount of tokens to mint.
function _mint(address recipient, uint256 amount) internal virtual;
/// @dev Burns `amount` tokens from `account`.
/// @param account The address from which the tokens will be burned.
/// @param amount The amount of tokens to burn.
function _burn(address account, uint256 amount) internal virtual;
/// @dev Internal balance update function that needs to be implemented by the inheriting contract.
/// @param sender The sender's address.
/// @param recipient The recipient's address.
/// @param amount The amount to be transferred.
function _update(address sender, address recipient, uint256 amount) internal virtual;
/// @dev Internal ERC20 transfer function.
/// @param sender The sender's address.
/// @param recipient The recipient's address.
/// @param amount The amount to be transferred.
function _transfer(address sender, address recipient, uint256 amount) internal override {
_revertIfZeroAccount(recipient);
_beforeTransfer(sender, recipient, amount);
emit Transfer(sender, recipient, amount);
if (amount == 0) return;
_revertIfInsufficientBalance(sender, amount);
_update(sender, recipient, amount);
}
/* ============ Internal View/Pure Functions ============ */
/// @dev Returns the PYUSDX balance of `account`.
/// @param account The account being queried.
/// @return balance The PYUSDX balance of the account.
function _pyusdxBalanceOf(address account) internal view returns (uint256) {
return IERC20(pyusdx).balanceOf(account);
}
/// @dev Reverts if `recipient` is address(0).
/// @param recipient Address of a recipient.
function _revertIfZeroAccount(address recipient) internal pure {
if (recipient == address(0)) revert ZeroAccount();
}
/// @dev Reverts if `amount` is equal to 0.
/// @param amount Amount of token.
function _revertIfZeroAmount(uint256 amount) internal pure {
if (amount == 0) revert ZeroAmount();
}
/// @dev Reverts if `account` balance is below `amount`.
/// @param account Address of an account.
/// @param amount Amount to transfer or burn.
function _revertIfInsufficientBalance(address account, uint256 amount) internal view {
uint256 balance = balanceOf(account);
if (balance < amount) revert InsufficientBalance(account, balance, amount);
}
}
src/platform/interfaces/IExtension.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.34;
import { IERC20Extended } from "../../../lib/evm-m-extensions/lib/common/src/interfaces/IERC20Extended.sol";
/// @title PYUSDX Extension interface extending Extended ERC20.
/// @author M0 Labs
interface IExtension is IERC20Extended {
/* ============ Custom Errors ============ */
/// @notice Emitted when there is insufficient balance to decrement from `account`.
/// @param account The account with insufficient balance.
/// @param balance The balance of the account.
/// @param amount The amount to decrement.
error InsufficientBalance(address account, uint256 balance, uint256 amount);
/// @notice Emitted when the account is address(0).
error ZeroAccount();
/// @notice Emitted when the amount is 0.
error ZeroAmount();
/// @notice Emitted in constructor if PYUSDX is 0x0.
error ZeroPYUSDX();
/// @notice Emitted in constructor if swap facility is 0x0.
error ZeroSwapFacility();
/// @notice Emitted when the caller is not the swap facility.
error NotSwapFacility();
/// @notice Emitted when attempting to unpin a proxy that is not pinned.
error NotPinned();
/// @notice Emitted when pinning to version 0.
error ZeroVersion();
/* ============ Interactive Functions ============ */
/// @notice Wraps `amount` PYUSDX from the caller into extension token for `recipient`.
/// @dev Pulls PYUSDX from `msg.sender` via `transferFrom`. Only callable by the swap facility.
/// @param recipient The account receiving the minted extension token.
/// @param amount The amount of extension token minted.
function wrap(address recipient, uint256 amount) external;
/// @notice Unwraps `amount` extension token from the caller back into PYUSDX.
/// @dev Burns extension tokens from `msg.sender` and transfers PYUSDX to `msg.sender`.
/// Only callable by the swap facility.
/// @param amount The amount of extension token burned.
function unwrap(uint256 amount) external;
/// @notice Pins this proxy to a specific implementation version.
/// @dev Only callable by an address with VERSION_MANAGER_ROLE.
/// @param version The version number to pin to (must be > 0).
function pinVersion(uint256 version) external;
/// @notice Unpins this proxy, restoring beacon-follows-latest behavior.
/// @dev Only callable by an address with VERSION_MANAGER_ROLE.
function unpinVersion() external;
/* ============ View/Pure Functions ============ */
/// @notice The address of the PYUSDX token contract.
function pyusdx() external view returns (address);
/// @notice The address of the swap facility contract.
function swapFacility() external view returns (address);
/// @notice Returns the origin beacon address (set at construction, never changes).
/// @return The origin beacon address.
function originBeacon() external view returns (address);
/// @notice Returns whether the proxy is currently pinned to a specific implementation.
/// @return True if pinned, false if following the beacon's latest.
function isPinned() external view returns (bool);
/// @notice Returns the pinned implementation address, or address(0) if not pinned.
/// @return The pinned implementation address.
function pinnedImplementation() external view returns (address);
/// @notice Role required to call `pinVersion` / `unpinVersion`.
function VERSION_MANAGER_ROLE() external view returns (bytes32);
}
src/platform/interfaces/IExtensionBeacon.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.34;
/// @title PYUSDX Extension Beacon interface.
/// @notice Defines the interface for the extension implementation registry.
/// Each beacon serves a single extension type (YieldToOne or MultiMint)
/// and is fully ERC-1967 compliant.
/// @author M0 Labs
interface IExtensionBeacon {
/* ============ Events ============ */
/// @notice Emitted when a new implementation is registered.
/// @param version The version number assigned to the implementation.
/// @param implementation The address of the registered implementation.
event ImplementationRegistered(uint256 indexed version, address indexed implementation);
/* ============ Errors ============ */
/// @notice Thrown if the implementation address is 0x0.
error ZeroImplementation();
/// @notice Thrown if PYUSDX is 0x0.
error ZeroPYUSDX();
/// @notice Thrown if swap facility is 0x0.
error ZeroSwapFacility();
/// @notice Thrown if the admin address is 0x0.
error ZeroAdmin();
/// @notice Thrown if the beacon manager address is 0x0.
error ZeroBeaconManager();
/// @notice Thrown if PYUSDX address does not match the one in SwapFacility.
error PYUSDXMismatch();
/// @notice Thrown if the extension address is invalid (e.g. wrong pyusdx/swapFacility wiring or not a contract).
error InvalidExtension();
/// @notice Thrown when querying an implementation for a version with no registration.
error NoImplementationRegistered();
/* ============ Interactive Functions ============ */
/// @notice Registers a new implementation.
/// @dev MUST only be callable by an address with the `BEACON_MANAGER_ROLE` role.
/// Validates the implementation wiring and auto-increments the version.
/// @param implementation The address of the implementation contract.
/// @return version The version number assigned to the implementation.
function registerImplementation(address implementation) external returns (uint256 version);
/* ============ View/Pure Functions ============ */
/// @notice The role identifier for the beacon manager role.
function BEACON_MANAGER_ROLE() external view returns (bytes32);
/// @notice Returns the latest registered implementation (ERC-1967 standard zero-arg form).
/// @return The address of the latest implementation.
function implementation() external view returns (address);
/// @notice Returns the implementation for a specific version.
/// @param version The version number.
/// @return The address of the implementation at the specified version.
function implementation(uint256 version) external view returns (address);
/// @notice Returns the latest version number.
/// @dev Version numbering starts at 1 (the first registered implementation is version 1).
/// @return The latest version number.
function latestVersion() external view returns (uint256);
/// @notice The address of the PYUSDX token contract.
function pyusdx() external view returns (address);
/// @notice The address of the SwapFacility contract.
function swapFacility() external view returns (address);
}
src/platform/projects/YieldToOne.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.34;
import { IERC20 } from "../../../lib/evm-m-extensions/lib/common/src/interfaces/IERC20.sol";
import { IPYUSDX } from "../../IPYUSDX.sol";
import { Extension } from "../Extension.sol";
import { IYieldToOne } from "./interfaces/IYieldToOne.sol";
abstract contract YieldToOneStorageLayout {
/// @custom:storage-location erc7201:PYUSDX.storage.YieldToOne
struct YieldToOneStorage {
uint256 totalSupply;
address yieldRecipient;
mapping(address account => uint256 balance) balanceOf;
}
// keccak256(abi.encode(uint256(keccak256("PYUSDX.storage.YieldToOne")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant _YIELD_TO_ONE_STORAGE_LOCATION =
0xdeb0f77528a555c599f306cdb984f1f31ca08f014cad1aa7b02fa3fece5e2e00;
function _getYieldToOneStorage() internal pure returns (YieldToOneStorage storage $) {
bytes32 location = _YIELD_TO_ONE_STORAGE_LOCATION;
assembly {
$.slot := location
}
}
}
/// @title YieldToOne
/// @notice Upgradeable ERC20 token wrapping PYUSDX into a branded non-rebasing stablecoin
/// with all yield claimable by a single recipient.
/// @dev Yield accrues on the extension's PYUSDX balance via PYUSDX's per-account earning
/// system. When the extension's pending yield is claimed, it is first realized from
/// PYUSDX (net of PYUSDX's fee), then minted as extension tokens to the yield recipient.
/// @author M0 Labs
contract YieldToOne is IYieldToOne, YieldToOneStorageLayout, Extension {
/* ============ Variables ============ */
/// @inheritdoc IYieldToOne
bytes32 public constant YIELD_RECIPIENT_MANAGER_ROLE = keccak256("YIELD_RECIPIENT_MANAGER_ROLE");
/* ============ Constructor ============ */
/// @custom:oz-upgrades-unsafe-allow constructor
/// @param pyusdx_ The address of the PYUSDX token.
/// @param swapFacility_ The address of the swap facility.
constructor(address pyusdx_, address swapFacility_) Extension(pyusdx_, swapFacility_) {}
/* ============ Initializer ============ */
/// @notice Initializes the YieldToOne extension token.
/// @param name The name of the token.
/// @param symbol The symbol of the token.
/// @param yieldRecipient_ The address of the yield recipient.
/// @param admin The address of the admin.
/// @param freezeManager The address of the freeze manager.
/// @param pauser The address of the pauser.
/// @param yieldRecipientManager The address of the yield recipient manager.
/// @param versionManager The address of the version manager.
function initialize(
string memory name,
string memory symbol,
address yieldRecipient_,
address admin,
address freezeManager,
address pauser,
address yieldRecipientManager,
address versionManager
) public virtual initializer {
__YieldToOne_init(
name,
symbol,
yieldRecipient_,
admin,
freezeManager,
pauser,
yieldRecipientManager,
versionManager
);
}
/// @dev Internal initializer. Sets up ERC20 metadata, roles, and the
/// yield recipient.
/// @param name The name of the token.
/// @param symbol The symbol of the token.
/// @param yieldRecipient_ The address of the yield recipient.
/// @param admin The address of the admin.
/// @param freezeManager The address of the freeze manager.
/// @param pauser The address of the pauser.
/// @param yieldRecipientManager The address of the yield recipient manager.
/// @param versionManager The address of the version manager.
function __YieldToOne_init(
string memory name,
string memory symbol,
address yieldRecipient_,
address admin,
address freezeManager,
address pauser,
address yieldRecipientManager,
address versionManager
) internal onlyInitializing {
if (admin == address(0)) revert ZeroAdmin();
if (yieldRecipientManager == address(0)) revert ZeroYieldRecipientManager();
if (versionManager == address(0)) revert ZeroVersionManager();
__AccessControl_init();
__Extension_init(name, symbol, freezeManager, pauser);
_setYieldRecipient(yieldRecipient_);
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(VERSION_MANAGER_ROLE, versionManager);
_grantRole(YIELD_RECIPIENT_MANAGER_ROLE, yieldRecipientManager);
}
/* ============ Interactive Functions ============ */
/// @inheritdoc IYieldToOne
function claimYield() public virtual returns (uint256) {
_beforeClaimYield();
// NOTE: Realize any pending PYUSDX yield
IPYUSDX(pyusdx).claimFor(address(this));
// NOTE: Excess accounts for the newly claimed yield and any prior unclaimed yield
// (i.e. PYUSDX donation or `claimFor()` the extension at the PYUSDX level)
uint256 excess = _excess();
if (excess == 0) return 0;
emit YieldClaimed(excess);
// NOTE: mint the excess PYUSDX as extension tokens
_mint(yieldRecipient(), excess);
return excess;
}
/// @inheritdoc IYieldToOne
function setYieldRecipient(address account) external virtual onlyRole(YIELD_RECIPIENT_MANAGER_ROLE) {
// NOTE: Skip the claim when the outgoing recipient is frozen — `_beforeClaimYield`
// would otherwise revert on the freeze check, blocking the admin's ability
// to rotate a compromised recipient mid-incident. Pending PYUSDX yield
// remains as `_excess()` and is paid to the next recipient on their first
// claim. The frozen recipient's forgone slice is an accepted cost of the
// incident-response path.
if (!isFrozen(yieldRecipient())) claimYield();
_setYieldRecipient(account);
}
/* ============ View/Pure Functions ============ */
/// @inheritdoc IERC20
function balanceOf(address account) public view override returns (uint256) {
return _getYieldToOneStorage().balanceOf[account];
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _getYieldToOneStorage().totalSupply;
}
/// @inheritdoc IYieldToOne
function yield() public view virtual returns (uint256) {
return _excess() + IPYUSDX(pyusdx).accruedYieldToSelfOf(address(this));
}
/// @inheritdoc IYieldToOne
function yieldRecipient() public view returns (address) {
return _getYieldToOneStorage().yieldRecipient;
}
/* ============ Hooks ============ */
/// @dev Hook called before claiming yield. Restricts the caller to
/// `YIELD_RECIPIENT_MANAGER_ROLE` and reverts if the yield recipient is frozen.
/// Intentionally omits `_requireNotPaused()` so the admin can rotate a compromised
/// recipient mid-incident via `setYieldRecipient` (which calls `claimYield`
/// internally). Minted extension tokens cannot move while paused —
/// `_beforeTransfer`, `_beforeWrap`, and `_beforeUnwrap` all enforce the pause —
/// so supply minted during pause is economically inert until unpause.
function _beforeClaimYield() internal view virtual onlyRole(YIELD_RECIPIENT_MANAGER_ROLE) {
_revertIfFrozen(_getFreezableStorageLocation(), yieldRecipient());
}
/* ============ Internal Interactive Functions ============ */
/// @dev Mints `amount` extension tokens to `recipient`.
/// @param recipient The address receiving the minted tokens.
/// @param amount The amount of tokens to mint.
function _mint(address recipient, uint256 amount) internal override {
YieldToOneStorage storage $ = _getYieldToOneStorage();
$.totalSupply += amount;
unchecked {
$.balanceOf[recipient] += amount;
}
emit Transfer(address(0), recipient, amount);
}
/// @dev Burns `amount` extension tokens from `account`.
/// @param account The address from which tokens are burned.
/// @param amount The amount of tokens to burn.
function _burn(address account, uint256 amount) internal override {
YieldToOneStorage storage $ = _getYieldToOneStorage();
// NOTE: `amount` is verified to not exceed `$.balanceOf[account]` by the caller, so
// subtraction cannot underflow. `totalSupply >= balanceOf[account]` by invariant.
unchecked {
$.totalSupply -= amount;
$.balanceOf[account] -= amount;
}
emit Transfer(account, address(0), amount);
}
/// @dev Internal balance update on transfer.
/// @param sender The address sending tokens.
/// @param recipient The address receiving tokens.
/// @param amount The amount to transfer.
function _update(address sender, address recipient, uint256 amount) internal override {
YieldToOneStorage storage $ = _getYieldToOneStorage();
// NOTE: `amount` is verified to not exceed `$.balanceOf[sender]` by the caller, so
// subtraction cannot underflow. Addition cannot overflow because `totalSupply`
// (which bounds the sum of all balances) fits in uint256.
unchecked {
$.balanceOf[sender] -= amount;
$.balanceOf[recipient] += amount;
}
}
/// @dev Sets the yield recipient. Reverts if address(0).
/// @param yieldRecipient_ The address of the new yield recipient.
function _setYieldRecipient(address yieldRecipient_) internal {
if (yieldRecipient_ == address(0)) revert ZeroYieldRecipient();
YieldToOneStorage storage $ = _getYieldToOneStorage();
if ($.yieldRecipient == yieldRecipient_) return;
$.yieldRecipient = yieldRecipient_;
emit YieldRecipientSet(yieldRecipient_);
}
/* ============ Internal View Functions ============ */
/// @dev Returns the excess PYUSDX balance of the extension
function _excess() internal view virtual returns (uint256) {
uint256 pyusdxBalance = _pyusdxBalanceOf(address(this));
uint256 totalSupply_ = totalSupply();
unchecked {
return pyusdxBalance > totalSupply_ ? pyusdxBalance - totalSupply_ : 0;
}
}
}
src/platform/projects/interfaces/IMultiMint.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.34;
import { IYieldToOne } from "./IYieldToOne.sol";
interface IMultiMint is IYieldToOne {
/* ============ Events ============ */
/// @notice Emitted when asset cap is set.
/// @param asset Address of the asset.
/// @param cap Maximum allowed amount of `asset` that can back the extension.
event AssetCapSet(address indexed asset, uint256 cap);
/// @notice Emitted when a caller's allow status on the replaceAsset whitelist changes.
/// @param caller The caller whose allow status changed.
/// @param allowed The new allow status (true = whitelisted, false = removed).
event ReplaceAssetWhitelistCallerSet(address indexed caller, bool indexed allowed);
/// @notice Emitted when an asset is wrapped into extension tokens.
/// @param asset Address of the asset deposited.
/// @param assetAmount Amount of asset deposited (in asset decimals).
/// @param recipient Address that received the extension tokens.
/// @param extensionAmount Amount of extension tokens minted.
event AssetWrapped(address indexed asset, uint256 assetAmount, address indexed recipient, uint256 extensionAmount);
/// @notice Emitted when an asset is replaced with PYUSDX.
/// @param asset Address of the asset.
/// @param assetAmount Amount of asset replaced.
/// @param recipient Address that received the asset.
/// @param pyusdxAmount Amount of PYUSDX deposited.
event AssetReplaced(address indexed asset, uint256 assetAmount, address indexed recipient, uint256 pyusdxAmount);
/* ============ Custom Errors ============ */
/// @notice Emitted in initializer if Asset Cap Manager is 0x0.
error ZeroAssetCapManager();
/// @notice Reverts when batch input arrays have differing lengths.
error ArrayLengthMismatch();
/// @notice Emitted if the asset cap is reached.
/// @param asset Address of the asset.
error AssetCapReached(address asset);
/// @notice Emitted if there is not enough of an asset to replace with PYUSDX.
/// @param asset Address of the asset.
/// @param amount Amount of asset requested.
/// @param assetAvailable Amount of asset available.
error InsufficientAssetBacking(address asset, uint256 amount, uint256 assetAvailable);
/// @notice Emitted when wrapping an asset and receiving less than expected (fee-on-transfer).
/// @param asset Address of the asset.
/// @param amountExpected Amount of asset expected.
/// @param amountReceived Amount of asset received.
error InsufficientAssetReceived(address asset, uint256 amountExpected, uint256 amountReceived);
/// @notice Emitted if `unwrap()` is called but there is not enough PYUSDX backing.
/// @param amount Amount of PYUSDX to unwrap requested.
/// @param available Amount of PYUSDX backing available.
error InsufficientPYUSDXBacking(uint256 amount, uint256 available);
/// @notice Emitted if an invalid asset is used.
/// @param asset Address of the invalid asset.
error InvalidAsset(address asset);
/// @notice Emitted if `asset` has cap == 0 (unregistered or disabled).
/// @param asset Address of the disallowed asset.
error AssetNotAllowed(address asset);
/// @notice Reverts when the caller is not permitted to perform the operation.
/// @param caller The address that attempted the call.
error CallerNotAllowed(address caller);
/* ============ Interactive Functions ============ */
/// @notice Mint extension tokens by depositing `asset` tokens.
/// @dev `amount` must be formatted in the `asset` token's decimals.
/// @param asset Address of the asset to deposit.
/// @param recipient Address that will receive the extension tokens.
/// @param amount Amount of asset tokens to deposit.
function wrap(address asset, address recipient, uint256 amount) external;
/// @notice Allows depositing PYUSDX to receive `asset` tokens from reserves.
/// @dev `amount` MUST be formatted in PYUSDX decimals (6).
/// @param asset Address of the asset to receive.
/// @param recipient Address that will receive the `asset` token.
/// @param amount Amount of PYUSDX to deposit (in PYUSDX decimals).
function replaceAsset(address asset, address recipient, uint256 amount) external;
/// @notice Sets the asset cap for a given `asset`.
/// @dev MUST only be callable by an account with the ASSET_CAP_MANAGER_ROLE.
/// Setting `cap` to 0 disables both `wrap` and `replaceAsset` for this asset;
/// existing balances remain unwrappable to PYUSDX.
/// @param asset Address of the asset.
/// @param cap Maximum allowed amount of `asset` that can back the extension.
function setAssetCap(address asset, uint256 cap) external;
/// @notice Sets `caller`'s allow status on the replaceAsset whitelist.
/// @dev MUST only be callable by ASSET_CAP_MANAGER_ROLE.
/// No-op (no event) if the caller is already in the requested state.
/// @param caller The caller to add or remove.
/// @param allowed True to add, false to remove.
function setReplaceAssetWhitelistCaller(address caller, bool allowed) external;
/// @notice Batch variant of setReplaceAssetWhitelistCaller.
/// @dev MUST only be callable by ASSET_CAP_MANAGER_ROLE.
/// Reverts on array length mismatch.
/// @param callers The callers to add or remove.
/// @param allowed The corresponding allow statuses.
function setReplaceAssetWhitelistCaller(address[] calldata callers, bool[] calldata allowed) external;
/* ============ View/Pure Functions ============ */
/// @notice The role that can set the assets cap.
function ASSET_CAP_MANAGER_ROLE() external view returns (bytes32);
/// @notice Number of decimals used by PYUSDX.
function PYUSDX_DECIMALS() external view returns (uint8);
/// @notice Gets the cached balance of a given asset held by the extension.
function assetBalanceOf(address asset) external view returns (uint256);
/// @notice Gets the asset cap for a given asset.
function assetCap(address asset) external view returns (uint256);
/// @notice Gets the cached decimals of a given asset.
function assetDecimals(address asset) external view returns (uint8);
/// @notice Gets the total non-PYUSDX assets held by the extension (in extension decimals).
function totalAssets() external view returns (uint256);
/// @notice Get the addresses allowed to call `replaceAsset`.
function getReplaceAssetWhitelist() external view returns (address[] memory);
/// @notice Checks if an asset is allowed as backing.
function isAllowedAsset(address asset) external view returns (bool);
/// @notice Checks if wrapping `amount` of `asset` is allowed.
/// @dev `amount` MUST be formatted in `asset`'s decimals.
function isAllowedToWrap(address asset, uint256 amount) external view returns (bool);
/// @notice Checks if unwrapping `amount` of extension tokens is allowed.
/// @dev `amount` MUST be formatted in extension's decimals (6).
function isAllowedToUnwrap(uint256 amount) external view returns (bool);
/// @notice Checks if `caller` is allowed to replace `asset` with `amount` of PYUSDX.
/// @dev `amount` MUST be formatted in PYUSDX decimals.
/// @param caller The address of the caller to check.
/// @param asset The address of the asset to replace.
/// @param amount The amount of PYUSDX to deposit.
function isAllowedToReplaceAsset(address caller, address asset, uint256 amount) external view returns (bool);
/// @notice Whether the replaceAsset whitelist is currently enforced.
function isReplaceAssetWhitelistEnabled() external view returns (bool);
}
src/platform/projects/interfaces/IYieldToOne.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.34;
/// @title PYUSDX Extension where all yield is claimable by a single recipient.
/// @author M0 Labs
interface IYieldToOne {
/* ============ Events ============ */
/// @notice Emitted when this contract's excess PYUSDX yield is claimed.
/// @param yield The amount of yield claimed.
event YieldClaimed(uint256 yield);
/// @notice Emitted when the yield recipient is set.
/// @param yieldRecipient The address of the new yield recipient.
event YieldRecipientSet(address indexed yieldRecipient);
/* ============ Custom Errors ============ */
/// @notice Emitted in initializer if Yield Recipient is 0x0.
error ZeroYieldRecipient();
/// @notice Emitted in initializer if Yield Recipient Manager is 0x0.
error ZeroYieldRecipientManager();
/// @notice Emitted in initializer if Version Manager is 0x0.
error ZeroVersionManager();
/// @notice Emitted in initializer if Admin is 0x0.
error ZeroAdmin();
/* ============ Interactive Functions ============ */
/// @notice Claims accrued yield to the yield recipient.
/// @dev MUST only be callable by the YIELD_RECIPIENT_MANAGER_ROLE.
/// @dev Calls `pyusdx.claimFor(address(this))` to realize pending yield,
/// then mints extension tokens for the resulting increase in totalSupply.
/// @dev Callable while paused so the admin retains an emergency lever to rotate a
/// compromised yield recipient mid-incident via `setYieldRecipient`. The
/// freshly minted extension tokens cannot move while paused because transfer,
/// wrap, and unwrap all revert, so the supply is economically inert until
/// unpause.
/// @dev Reverts if the current yield recipient is frozen. Use `setYieldRecipient`
/// to rotate to a non-frozen recipient first; that path skips the internal
/// claim so the pending yield stays as excess and accrues to the next
/// recipient on their first claim.
function claimYield() external returns (uint256);
/// @notice Sets the yield recipient.
/// @dev MUST only be callable by the YIELD_RECIPIENT_MANAGER_ROLE.
/// @dev SHOULD revert if `yieldRecipient` is 0x0.
/// @dev SHOULD return early if the `yieldRecipient` is already the actual yield recipient.
/// @dev Internally calls `claimYield()` to pay out the outgoing recipient, unless
/// the outgoing recipient is frozen. When frozen, the claim is skipped:
/// pending PYUSDX yield remains as excess on the extension and is paid to
/// the next recipient's first claim. Makes recipient rotation usable as an
/// incident-response lever while a compromised recipient is frozen, at the
/// cost of the outgoing recipient's pending slice.
/// @param yieldRecipient The address of the new yield recipient.
function setYieldRecipient(address yieldRecipient) external;
/* ============ View/Pure Functions ============ */
/// @notice The role that can manage the yield recipient.
function YIELD_RECIPIENT_MANAGER_ROLE() external view returns (bytes32);
/// @notice The amount of pending accrued yield from PYUSDX.
function yield() external view returns (uint256);
/// @notice The address of the yield recipient.
function yieldRecipient() external view returns (address);
}
src/swap/interfaces/ISwapFacility.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.34;
/// @title Swap Facility interface.
/// @author M0 Labs
interface ISwapFacility {
/* ============ Events ============ */
/// @notice Emitted when PYUSDX Extension is swapped for another PYUSDX Extension.
/// @param extensionIn The address of the input PYUSDX Extension.
/// @param extensionOut The address of the output PYUSDX Extension.
/// @param amount The amount swapped.
/// @param recipient The address to receive the output PYUSDX Extension token.
event Swapped(address indexed extensionIn, address indexed extensionOut, uint256 amount, address indexed recipient);
/// @notice Emitted when PYUSDX token is swapped for PYUSDX Extension.
/// @param token The address of the PYUSDX token.
/// @param extensionOut The address of the output PYUSDX Extension.
/// @param amount The amount swapped.
/// @param recipient The address to receive the output PYUSDX Extension token.
event SwappedIn(address indexed token, address indexed extensionOut, uint256 amount, address indexed recipient);
/// @notice Emitted when PYUSDX Extension is swapped for PYUSDX token.
/// @param token The address of the PYUSDX token.
/// @param extensionIn The address of the input PYUSDX Extension.
/// @param amount The amount swapped.
/// @param recipient The address to receive the PYUSDX token.
event SwappedOut(address indexed extensionIn, address indexed token, uint256 amount, address indexed recipient);
/// @notice Emitted when PYUSDX token is swapped for MultiMint Extension.
/// @param asset The address of the asset.
/// @param extensionOut The address of the MultiMint Extension.
/// @param amount The amount swapped.
/// @param recipient The address to receive the MultiMint Extension tokens.
event SwappedInMultiMint(
address indexed asset,
address indexed extensionOut,
uint256 amount,
address indexed recipient
);
/// @notice Emitted when `asset` is replaced with PYUSDX for a MultiMint Extension.
/// @param asset The address of an asset.
/// @param extensionOut The address of a MultiMint Extension.
/// @param amount The amount of PYUSDX tokens deposited to replace `asset`.
/// @param recipient The address that received the `asset` tokens.
event MultiMintAssetReplaced(
address indexed asset,
address indexed extensionOut,
uint256 amount,
address indexed recipient
);
/* ============ Custom Errors ============ */
/// @notice Thrown in the constructor if the extension factory is 0x0.
error ZeroExtensionFactory();
/// @notice Thrown in the constructor if PYUSDX Token is 0x0.
error ZeroPYUSDXToken();
/// @notice Thrown in `swap` functions if an extension is not approved.
error NotApprovedExtension(address extension);
/// @notice Thrown in `swap` function if the provided tokens do not represent a valid swap path.
error InvalidSwapPath(address tokenIn, address tokenOut);
/* ============ Interactive Functions ============ */
/// @notice Swaps between two tokens, which can be PYUSDX, PYUSDX Extensions, or an asset used by MultiMint Extensions.
/// @param tokenIn The address of the token to swap from.
/// @param tokenOut The address of the token to swap to.
/// @param amount The amount to swap.
/// @param recipient The address to receive the swapped tokens.
function swap(address tokenIn, address tokenOut, uint256 amount, address recipient) external;
/// @notice Swaps between two tokens using permit.
/// @param tokenIn The address of the token to swap from.
/// @param tokenOut The address of the token to swap to.
/// @param amount The amount to swap.
/// @param recipient The address to receive the swapped tokens.
/// @param deadline The last timestamp where the signature is still valid.
/// @param v An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
/// @param r An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
/// @param s An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
function swapWithPermit(
address tokenIn,
address tokenOut,
uint256 amount,
address recipient,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/// @notice Swaps between two tokens using permit.
/// @param tokenIn The address of the token to swap from.
/// @param tokenOut The address of the token to swap to.
/// @param amount The amount to swap.
/// @param recipient The address to receive the swapped tokens.
/// @param deadline The last timestamp where the signature is still valid.
/// @param signature An arbitrary signature (EIP-712).
function swapWithPermit(
address tokenIn,
address tokenOut,
uint256 amount,
address recipient,
uint256 deadline,
bytes calldata signature
) external;
/// @notice Swaps PYUSDX token to PYUSDX Extension.
/// @param extensionOut The address of the PYUSDX Extension to swap to.
/// @param amount The amount of PYUSDX token to swap.
/// @param recipient The address to receive the swapped PYUSDX Extension tokens.
function swapIn(address extensionOut, uint256 amount, address recipient) external;
/// @notice Swaps PYUSDX Extension to PYUSDX token.
/// @param extensionIn The address of the PYUSDX Extension to swap from.
/// @param amount The amount of PYUSDX Extension tokens to swap.
/// @param recipient The address to receive PYUSDX tokens.
function swapOut(address extensionIn, uint256 amount, address recipient) external;
/// @notice Replaces `asset` held in a MultiMint Extension with `amount` of PYUSDX.
/// @param asset The address of the asset.
/// @param tokenIn The address of PYUSDX or a PYUSDX extension to provide PYUSDX from.
/// @param extensionOut The address of a MultiMint Extension.
/// @param amount The amount of PYUSDX to replace.
/// @param recipient The address to receive `asset` tokens equivalent to `amount` of PYUSDX.
function replaceAsset(
address asset,
address tokenIn,
address extensionOut,
uint256 amount,
address recipient
) external;
/// @notice Replaces `asset` held in a MultiMint Extension with `amount` of PYUSDX using permit.
/// @param asset The address of the asset.
/// @param tokenIn The address of PYUSDX or a PYUSDX extension to provide PYUSDX from.
/// @param extensionOut The address of a MultiMint Extension.
/// @param amount The amount of PYUSDX to replace.
/// @param recipient The address to receive `asset` tokens equivalent to `amount` of PYUSDX.
/// @param deadline The last timestamp where the signature is still valid.
/// @param v An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
/// @param r An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
/// @param s An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
function replaceAssetWithPermit(
address asset,
address tokenIn,
address extensionOut,
uint256 amount,
address recipient,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/// @notice Replaces `asset` held in a MultiMint Extension with `amount` of PYUSDX using permit.
/// @param asset The address of the asset.
/// @param tokenIn The address of PYUSDX or a PYUSDX extension to provide PYUSDX from.
/// @param extensionOut The address of a MultiMint Extension.
/// @param amount The amount of PYUSDX to replace.
/// @param recipient The address to receive `asset` tokens equivalent to `amount` of PYUSDX.
/// @param deadline The last timestamp where the signature is still valid.
/// @param signature An arbitrary signature (EIP-712).
function replaceAssetWithPermit(
address asset,
address tokenIn,
address extensionOut,
uint256 amount,
address recipient,
uint256 deadline,
bytes calldata signature
) external;
/* ============ View/Pure Functions ============ */
/// @notice The address of the PYUSDX Token contract.
function pyusdx() external view returns (address);
/// @notice The address of the PYUSDX Extension Factory contract.
function extensionFactory() external view returns (address);
/// @notice Returns the address that called `swap`.
/// @dev Must be used instead of `msg.sender` in PYUSDX Extensions contracts to get the original sender.
function msgSender() external view returns (address);
/// @notice Checks if the extension is approved.
/// @param extension The extension address to check.
/// @return True if approved, false otherwise.
function isApprovedExtension(address extension) external view returns (bool);
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 2933,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@ensdomains/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/contracts-upgradeable/=lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"@uniswap/v4-core/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/v4-core/",
"common/=lib/evm-m-extensions/lib/common/src/",
"ds-test/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"evm-m-extensions/=lib/evm-m-extensions/",
"forge-gas-snapshot/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"hardhat/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts-upgradeable/=lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/evm-m-extensions/lib/common/lib/openzeppelin-contracts/",
"openzeppelin-foundry-upgrades/=lib/evm-m-extensions/lib/openzeppelin-foundry-upgrades/src/",
"permit2/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/permit2/",
"safe-smart-account/=lib/evm-m-extensions/lib/common/lib/safe-utils/lib/safe-smart-account/",
"safe-utils/=lib/evm-m-extensions/lib/common/lib/safe-utils/src/",
"solidity-http/=lib/evm-m-extensions/lib/common/lib/safe-utils/lib/solidity-http/src/",
"solidity-stringutils/=lib/evm-m-extensions/lib/common/lib/safe-utils/lib/solidity-stringutils/",
"solmate/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/v4-core/lib/solmate/",
"uniswap-v4-periphery/=lib/evm-m-extensions/lib/uniswap-v4-periphery/",
"v4-core/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/v4-core/src/",
"wrapped-m-token/=lib/evm-m-extensions/lib/wrapped-m-token/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.