Verified contractPartialApache-2.0
AgoraDollar
Address0xc1e3c7d486d6a92fbe920232e439eec2ceb112da
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 100,000,000 runs
- EVM version
- cancun
- Via IR
- yes
- License
- Apache-2.0
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,219,927
- Creation transaction
- 0x3b83e617e1…f40aca2016
24 files
- node_modules/agora-dollar-dev/src/contracts/AgoraDollar.solmain19.79 KB
- node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol8.91 KB
- node_modules/@openzeppelin/contracts/interfaces/draft-IERC6093.sol6.54 KB
- node_modules/@openzeppelin/contracts/utils/Panic.sol1.97 KB
- node_modules/@openzeppelin/contracts/utils/ShortStrings.sol4.28 KB
- node_modules/@openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
- node_modules/@openzeppelin/contracts/utils/Strings.sol16.84 KB
- node_modules/@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol3.7 KB
- node_modules/@openzeppelin/contracts/utils/math/Math.sol28.31 KB
- node_modules/@openzeppelin/contracts/utils/math/SafeCast.sol34.94 KB
- node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol2.61 KB
- node_modules/@openzeppelin/contracts/utils/structs/EnumerableSet.sol12.89 KB
- node_modules/agora-contracts/src/contracts/access-control/AgoraAccessControl.sol12.36 KB
- node_modules/agora-dollar-dev/src/contracts/AgoraDollarAccessControl.sol11.19 KB
- node_modules/agora-dollar-dev/src/contracts/AgoraDollarCore.sol20.14 KB
- node_modules/agora-dollar-dev/src/contracts/AgoraDollarMintRateLimit.sol8.65 KB
- node_modules/agora-dollar-dev/src/contracts/Eip3009.sol10.86 KB
- node_modules/agora-dollar-dev/src/contracts/Eip712.sol6.34 KB
- node_modules/agora-dollar-dev/src/contracts/Erc20Core.sol6.52 KB
- node_modules/agora-dollar-dev/src/contracts/Erc20Privileged.sol12.11 KB
- node_modules/agora-dollar-dev/src/contracts/Erc2612.sol5.09 KB
- node_modules/agora-dollar-dev/src/contracts/proxy/StorageLib.sol18.41 KB
- node_modules/solady/src/utils/SafeCastLib.sol11.81 KB
- node_modules/solady/src/utils/SignatureCheckerLib.sol26.57 KB
node_modules/agora-dollar-dev/src/contracts/AgoraDollar.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.28;
// ====================================================================
// _ ______ ___ _______ _
// / \ .' ___ | .' `.|_ __ \ / \
// / _ \ / .' \_| / .-. \ | |__) | / _ \
// / ___ \ | | ____ | | | | | __ / / ___ \
// _/ / \ \_\ `.___] |\ `-' /_| | \ \_ _/ / \ \_
// |____| |____|`._____.' `.___.'|____| |___||____| |____|
// ====================================================================
// =========================== AgoraDollar ============================
// ====================================================================
import { AgoraDollarCore, ConstructorParams, ShortStrings } from "./AgoraDollarCore.sol";
import { StorageLib } from "./proxy/StorageLib.sol";
/// @title AgoraDollar
/// @notice AgoraDollar is a digital dollar implementation
/// @author Agora
contract AgoraDollar is AgoraDollarCore {
using StorageLib for uint256;
using ShortStrings for *;
/// @notice The AgoraDollar Constructor, invoked upon deployment
/// @param _params The constructor params for AgoraDollar
constructor(ConstructorParams memory _params) AgoraDollarCore(_params) {}
//==============================================================================
// External View Functions: Erc3009
//==============================================================================
// solhint-disable func-name-mixedcase
/// @notice The ```TRANSFER_WITH_AUTHORIZATION_TYPEHASH``` function returns the typehash for the transfer with authorization
function TRANSFER_WITH_AUTHORIZATION_TYPEHASH() external pure returns (bytes32) {
return TRANSFER_WITH_AUTHORIZATION_TYPEHASH_;
}
/// @notice The ```RECEIVE_WITH_AUTHORIZATION_TYPEHASH``` function returns the typehash for the receive with authorization
function RECEIVE_WITH_AUTHORIZATION_TYPEHASH() external pure returns (bytes32) {
return RECEIVE_WITH_AUTHORIZATION_TYPEHASH_;
}
/// @notice The ```CANCEL_AUTHORIZATION_TYPEHASH``` function returns the typehash for the cancel authorization
function CANCEL_AUTHORIZATION_TYPEHASH() external pure returns (bytes32) {
return CANCEL_AUTHORIZATION_TYPEHASH_;
}
/// @notice The ```authorizationState``` function returns the state of the authorization nonce for a given authorizer
/// @param _authorizer The account which is providing the authorization
/// @param _nonce The unique nonce for the authorization
/// @return _isNonceUsed The state of the authorization
function authorizationState(address _authorizer, bytes32 _nonce) external view returns (bool _isNonceUsed) {
_isNonceUsed = StorageLib.getPointerToEip3009Storage().isAuthorizationUsed[_authorizer][_nonce];
}
//==============================================================================
// External View Functions: Eip712
//==============================================================================
/// @notice The ```hashTypedDataV4``` function hashes the typed data according to Eip712
/// @param _structHash The hash of the struct
function hashTypedDataV4(bytes32 _structHash) external view returns (bytes32) {
return _hashTypedDataV4({ structHash: _structHash });
}
/// @notice The ```domainSeparatorV4``` function returns the domain separator for Eip712
function domainSeparatorV4() external view returns (bytes32) {
return _domainSeparatorV4();
}
//==============================================================================
// External View Functions: Erc2612
//==============================================================================
/// @notice The ```ERC2612_STORAGE_SLOT``` function returns the storage slot for Erc2612 storage
function ERC2612_STORAGE_SLOT() external pure returns (bytes32) {
return StorageLib.ERC2612_STORAGE_SLOT_;
}
/// @notice The ```nonces``` function returns the nonce for a given account according to Erc2612
function nonces(address _account) external view returns (uint256 _nonce) {
_nonce = StorageLib.getPointerToErc2612Storage().nonces[_account];
}
//==============================================================================
// External View Functions: Erc20
//==============================================================================
/// @notice The ```name``` function returns the name of the token
function name() external view returns (string memory) {
return _name.toString();
}
/// @notice The ```symbol``` function returns the symbol of the token
function symbol() external view returns (string memory) {
return _symbol.toString();
}
/// @notice The ```balanceOf``` function returns the token balance of a given account
/// @param _account The account to check the balance of
/// @return The balance of the account
function balanceOf(address _account) external view returns (uint256) {
return StorageLib.getPointerToErc20CoreStorage().accountData[_account].balance;
}
/// @notice The ```allowance``` function returns the allowance a given owner has given to the spender
/// @param _owner The account which is giving the allowance
/// @param _spender The account which is being given the allowance
/// @return The allowance the owner has given to the spender
function allowance(address _owner, address _spender) external view returns (uint256) {
return StorageLib.getPointerToErc20CoreStorage().accountAllowances[_owner][_spender];
}
/// @notice The ```totalSupply``` function returns the total supply of the token
/// @return The total supply of the token
function totalSupply() external view returns (uint256) {
return StorageLib.getPointerToErc20CoreStorage().totalSupply;
}
/// @notice The ```isAccountFrozen``` function returns a boolean indicating if an account is frozen
/// @param _account The account whose frozen status to check
function isAccountFrozen(address _account) external view returns (bool) {
return StorageLib.getPointerToErc20CoreStorage().accountData[_account].isFrozen;
}
/// @notice The ```accountData``` function returns Erc20 information about a given account
/// @param _account The account to get the Erc20 information for
/// @return The Erc20 information for the account (balance, isFrozenStatus)
function accountData(address _account) external view returns (StorageLib.Erc20AccountData memory) {
return StorageLib.getPointerToErc20CoreStorage().accountData[_account];
}
/// @notice The ```ERC20_CORE_STORAGE_SLOT``` function returns the storage slot for Erc20 storage
function ERC20_CORE_STORAGE_SLOT() external pure returns (bytes32) {
return StorageLib.ERC20_CORE_STORAGE_SLOT_;
}
//==============================================================================
// External View Functions: AgoraDollarAccessControl
//==============================================================================
/// @notice The ```getMinterRoleMembers``` function returns the addresses holding `MINTER_ROLE`
/// @return The array of addresses holding `MINTER_ROLE`
function getMinterRoleMembers() external view returns (address[] memory) {
return getRoleMembers(MINTER_ROLE);
}
/// @notice The ```getBurnerRoleMembers``` function returns the addresses holding `BURNER_ROLE`
/// @return The array of addresses holding `BURNER_ROLE`
function getBurnerRoleMembers() external view returns (address[] memory) {
return getRoleMembers(BURNER_ROLE);
}
/// @notice The ```getPauserRoleMembers``` function returns the addresses holding `PAUSER_ROLE`
/// @return The array of addresses holding `PAUSER_ROLE`
function getPauserRoleMembers() external view returns (address[] memory) {
return getRoleMembers(PAUSER_ROLE);
}
/// @notice The ```getFreezerRoleMembers``` function returns the addresses holding `FREEZER_ROLE`
/// @return The array of addresses holding `FREEZER_ROLE`
function getFreezerRoleMembers() external view returns (address[] memory) {
return getRoleMembers(FREEZER_ROLE);
}
/// @notice The ```getBridgeMinterRoleMembers``` function returns the addresses holding `BRIDGE_MINTER_ROLE`
/// @return The array of addresses holding `BRIDGE_MINTER_ROLE`
function getBridgeMinterRoleMembers() external view returns (address[] memory) {
return getRoleMembers(BRIDGE_MINTER_ROLE);
}
/// @notice The ```getBridgeBurnerRoleMembers``` function returns the addresses holding `BRIDGE_BURNER_ROLE`
/// @return The array of addresses holding `BRIDGE_BURNER_ROLE`
function getBridgeBurnerRoleMembers() external view returns (address[] memory) {
return getRoleMembers(BRIDGE_BURNER_ROLE);
}
/// @notice The ```getRateLimitManagerRoleMembers``` function returns the addresses holding `RATE_LIMIT_MANAGER_ROLE`
/// @return The array of addresses holding `RATE_LIMIT_MANAGER_ROLE`
function getRateLimitManagerRoleMembers() external view returns (address[] memory) {
return getRoleMembers(RATE_LIMIT_MANAGER_ROLE);
}
//==============================================================================
// External View Functions: Eip712
//==============================================================================
/// @notice The ```eip712Domain``` function returns the Eip712 domain data
function eip712Domain()
external
view
returns (
bytes1 _fields,
string memory _name,
string memory _version,
uint256 _chainId,
address _verifyingContract,
bytes32 _salt,
uint256[] memory _extensions
)
{
return (
hex"0f", // 01111
_Eip712Name(),
_Eip712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
//==============================================================================
// External View Functions: AgoraDollarErc1967Proxy
//==============================================================================
/// @notice The ```proxyAdminAddress``` function returns the address of the proxy admin
/// @return The address of the proxy admin
function proxyAdminAddress() external view returns (address) {
return StorageLib.getPointerToAgoraDollarErc1967ProxyAdminStorage().proxyAdminAddress;
}
/// @notice The ```isMsgSenderFrozenCheckEnabled``` function returns a boolean indicating if the msg.sender frozen check is turned on
/// @return A boolean indicating if the msg sender frozen check is true
function isMsgSenderFrozenCheckEnabled() external view returns (bool) {
return StorageLib.sloadImplementationSlotDataAsUint256().isMsgSenderFrozenCheckEnabled();
}
/// @notice The ```isTransferPaused``` function returns a boolean indicating if transfers are paused
/// @return A boolean indicating if transfers are paused
function isTransferPaused() external view returns (bool) {
return StorageLib.sloadImplementationSlotDataAsUint256().isTransferPaused();
}
/// @notice The ```isSignatureVerificationPaused``` function returns a boolean indicating if signature verification is paused
/// @return A boolean indicating if signature verification is paused
function isSignatureVerificationPaused() external view returns (bool) {
return StorageLib.sloadImplementationSlotDataAsUint256().isSignatureVerificationPaused();
}
/// @notice The ```isMintPaused``` function returns a boolean indicating if minting is paused
/// @return A boolean indicating if minting is paused
function isMintPaused() external view returns (bool) {
return StorageLib.sloadImplementationSlotDataAsUint256().isMintPaused();
}
/// @notice The ```isBurnFromPaused``` function returns a boolean indicating if burnFrom is paused
/// @return A boolean indicating if burnFrom is paused
function isBurnFromPaused() external view returns (bool) {
return StorageLib.sloadImplementationSlotDataAsUint256().isBurnFromPaused();
}
/// @notice The ```isFreezingPaused``` function returns a boolean indicating if freezing is paused
/// @return A boolean indicating if freezing is paused
function isFreezingPaused() external view returns (bool) {
return StorageLib.sloadImplementationSlotDataAsUint256().isFreezingPaused();
}
/// @notice The ```isTransferUpgraded``` function returns a boolean indicating if the transfer function is upgraded
/// @return A boolean indicating if the transfer function is upgraded
function isTransferUpgraded() external view returns (bool) {
return StorageLib.sloadImplementationSlotDataAsUint256().isTransferUpgraded();
}
/// @notice The ```isTransferFromUpgraded``` function returns a boolean indicating if the transferFrom function is upgraded
/// @return A boolean indicating if the transferFrom function is upgraded
function isTransferFromUpgraded() external view returns (bool) {
return StorageLib.sloadImplementationSlotDataAsUint256().isTransferFromUpgraded();
}
/// @notice The ```isTransferWithAuthorizationUpgraded``` function returns a boolean indicating if the transferWithAuthorization function is upgraded
/// @return A boolean indicating if the transferWithAuthorization function is upgraded
function isTransferWithAuthorizationUpgraded() external view returns (bool) {
return StorageLib.sloadImplementationSlotDataAsUint256().isTransferWithAuthorizationUpgraded();
}
/// @notice The ```isReceiveWithAuthorizationUpgraded``` function returns a boolean indicating if the receiveWithAuthorization function is upgraded
/// @return A boolean indicating if the receiveWithAuthorization function is upgraded
function isReceiveWithAuthorizationUpgraded() external view returns (bool) {
return StorageLib.sloadImplementationSlotDataAsUint256().isReceiveWithAuthorizationUpgraded();
}
/// @notice The ```isBridgingPaused``` function returns a boolean indicating if bridging is paused
/// @return A boolean indicating if bridging is paused
function isBridgingPaused() external view returns (bool) {
return StorageLib.sloadImplementationSlotDataAsUint256().isBridgingPaused();
}
/// @notice The ```implementation``` function returns the address of the implementation contract
/// @return The address of the implementation contract
function implementation() external view returns (address) {
return StorageLib.sloadImplementationSlotDataAsUint256().implementation();
}
//==============================================================================
// External View Functions: StorageLib Proxy Storage Bitmasks
//==============================================================================
/// @notice The ```IS_MSG_SENDER_FROZEN_CHECK_ENABLED_BIT_POSITION``` function returns a uint256 with a single bit flipped which indicates the bit position
/// @return A uint256 with a single bit flipped to 1
function IS_MSG_SENDER_FROZEN_CHECK_ENABLED_BIT_POSITION() external pure returns (uint256) {
return StorageLib.IS_MSG_SENDER_FROZEN_CHECK_ENABLED_BIT_POSITION_;
}
/// @notice The ```IS_TRANSFER_PAUSED_BIT_POSITION``` function returns a uint256 with a single bit flipped which indicates the bit position
/// @return A uint256 with a single bit flipped to 1
function IS_MINT_PAUSED_BIT_POSITION() external pure returns (uint256) {
return StorageLib.IS_MINT_PAUSED_BIT_POSITION_;
}
/// @notice The ```IS_BURN_FROM_PAUSED_BIT_POSITION``` function returns a uint256 with a single bit flipped which indicates the bit position
/// @return A uint256 with a single bit flipped to 1
function IS_BURN_FROM_PAUSED_BIT_POSITION() external pure returns (uint256) {
return StorageLib.IS_BURN_FROM_PAUSED_BIT_POSITION_;
}
/// @notice The ```IS_FREEZING_PAUSED_BIT_POSITION``` function returns a uint256 with a single bit flipped which indicates the bit position
/// @return A uint256 with a single bit flipped to 1
function IS_FREEZING_PAUSED_BIT_POSITION() external pure returns (uint256) {
return StorageLib.IS_FREEZING_PAUSED_BIT_POSITION_;
}
/// @notice The ```IS_TRANSFER_PAUSED_BIT_POSITION``` function returns a uint256 with a single bit flipped which indicates the bit position
/// @return A uint256 with a single bit flipped to 1
function IS_TRANSFER_PAUSED_BIT_POSITION() external pure returns (uint256) {
return StorageLib.IS_TRANSFER_PAUSED_BIT_POSITION_;
}
/// @notice The ```IS_SIGNATURE_VERIFICATION_PAUSED_BIT_POSITION``` function returns a uint256 with a single bit flipped which indicates the bit position
/// @return A uint256 with a single bit flipped to 1
function IS_SIGNATURE_VERIFICATION_PAUSED_BIT_POSITION() external pure returns (uint256) {
return StorageLib.IS_SIGNATURE_VERIFICATION_PAUSED_BIT_POSITION_;
}
/// @notice The ```IS_MINT_UPGRADED_BIT_POSITION``` function returns a uint256 with a single bit flipped which indicates the bit position
/// @return A uint256 with a single bit flipped to 1
function IS_TRANSFER_UPGRADED_BIT_POSITION() external pure returns (uint256) {
return StorageLib.IS_TRANSFER_UPGRADED_BIT_POSITION_;
}
/// @notice The ```IS_TRANSFER_FROM_UPGRADED_BIT_POSITION``` function returns a uint256 with a single bit flipped which indicates the bit position
/// @return A uint256 with a single bit flipped to 1
function IS_TRANSFER_FROM_UPGRADED_BIT_POSITION() external pure returns (uint256) {
return StorageLib.IS_TRANSFER_FROM_UPGRADED_BIT_POSITION_;
}
/// @notice The ```IS_TRANSFER_WITH_AUTHORIZATION_UPGRADED_BIT_POSITION``` function returns a uint256 with a single bit flipped which indicates the bit position
/// @return A uint256 with a single bit flipped to 1
function IS_TRANSFER_WITH_AUTHORIZATION_UPGRADED_BIT_POSITION() external pure returns (uint256) {
return StorageLib.IS_TRANSFER_WITH_AUTHORIZATION_UPGRADED_BIT_POSITION_;
}
/// @notice The ```IS_RECEIVE_WITH_AUTHORIZATION_UPGRADED_BIT_POSITION``` function returns a uint256 with a single bit flipped which indicates the bit position
/// @return A uint256 with a single bit flipped to 1
function IS_RECEIVE_WITH_AUTHORIZATION_UPGRADED_BIT_POSITION() external pure returns (uint256) {
return StorageLib.IS_RECEIVE_WITH_AUTHORIZATION_UPGRADED_BIT_POSITION_;
}
//==============================================================================
// Version Functions
//==============================================================================
/// @notice The ```Version``` struct is used to represent the version of the AgoraDollar
/// @param major The major version number
/// @param minor The minor version number
/// @param patch The patch version number
struct Version {
uint256 major;
uint256 minor;
uint256 patch;
}
/// @notice The ```version``` function returns the version of the AgoraDollar
/// @return _version The version of the AgoraDollar
function version() public pure returns (Version memory _version) {
_version = Version({ major: 2, minor: 1, patch: 0 });
}
}
node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 reininitialization) 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 Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
node_modules/@openzeppelin/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @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 ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
node_modules/@openzeppelin/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)
}
}
}
node_modules/@openzeppelin/contracts/utils/ShortStrings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ShortStrings.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
// | length | 0x BB |
type ShortString is bytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/
library ShortStrings {
// Used as an identifier for strings longer than 31 bytes.
bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
error StringTooLong(string str);
error InvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/
function toShortString(string memory str) internal pure returns (ShortString) {
bytes memory bstr = bytes(str);
if (bstr.length > 31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/
function toString(ShortString sstr) internal pure returns (string memory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
assembly ("memory-safe") {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/
function byteLength(ShortString sstr) internal pure returns (uint256) {
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
if (result > 31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
if (bytes(value).length < 32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value = value;
return ShortString.wrap(FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using
* {setWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}
node_modules/@openzeppelin/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
}
}
}
node_modules/@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guaratees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(buffer, add(0x20, offset)))
}
}
}
node_modules/@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}
node_modules/@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, 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 {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @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 {
// 512-bit multiply [prod1 prod0] = 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 = prod1 * 2²⁵⁶ + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2²⁵⁶. 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 prod1
// is no longer required.
result = prod0 * 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 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 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 exp;
unchecked {
exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
value >>= exp;
result += exp;
exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
value >>= exp;
result += exp;
exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
value >>= exp;
result += exp;
exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
value >>= exp;
result += exp;
exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
value >>= exp;
result += exp;
exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
value >>= exp;
result += exp;
exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
value >>= exp;
result += exp;
result += SafeCast.toUint(value > 1);
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + 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 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 isGt;
unchecked {
isGt = SafeCast.toUint(value > (1 << 128) - 1);
value >>= isGt * 128;
result += isGt * 16;
isGt = SafeCast.toUint(value > (1 << 64) - 1);
value >>= isGt * 64;
result += isGt * 8;
isGt = SafeCast.toUint(value > (1 << 32) - 1);
value >>= isGt * 32;
result += isGt * 4;
isGt = SafeCast.toUint(value > (1 << 16) - 1);
value >>= isGt * 16;
result += isGt * 2;
result += SafeCast.toUint(value > (1 << 8) - 1);
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + 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;
}
}
node_modules/@openzeppelin/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))
}
}
}
node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @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, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
node_modules/@openzeppelin/contracts/utils/structs/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @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.
*
* ```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 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 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 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 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;
}
}
node_modules/agora-contracts/src/contracts/access-control/AgoraAccessControl.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.0;
// ====================================================================
// _ ______ ___ _______ _
// / \ .' ___ | .' `.|_ __ \ / \
// / _ \ / .' \_| / .-. \ | |__) | / _ \
// / ___ \ | | ____ | | | | | __ / / ___ \
// _/ / \ \_\ `.___] |\ `-' /_| | \ \_ _/ / \ \_
// |____| |____|`._____.' `.___.'|____| |___||____| |____|
// ====================================================================
// ======================== AgoraAccessControl ========================
// ====================================================================
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/// @title AgoraAccessControl
/// @notice An abstract contract that provides role-based access control with enumerable membership tracking
abstract contract AgoraAccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.Bytes32Set;
string public constant ACCESS_CONTROL_MANAGER_ROLE = "ACCESS_CONTROL_MANAGER_ROLE";
/// @notice The AgoraAccessControlStorage struct
/// @param roleData A mapping of role identifier to AgoraAccessControlRoleData to store role data
/// @custom:storage-location erc7201:AgoraAccessControl.AgoraAccessControlStorage
struct AgoraAccessControlStorage {
EnumerableSet.Bytes32Set roles;
mapping(string _role => EnumerableSet.AddressSet membership) roleMembership;
}
//==============================================================================
// Initialization Functions
//==============================================================================
function _initializeAgoraAccessControl(address _initialAdminAddress) internal virtual {
_addRoleToSet({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_setRoleMembership({ _role: ACCESS_CONTROL_MANAGER_ROLE, _member: _initialAdminAddress, _insert: true });
emit RoleAssigned({ role: ACCESS_CONTROL_MANAGER_ROLE, member: _initialAdminAddress });
}
// ============================================================================================
// Procedural Functions
// ============================================================================================
function _addRoleToSet(string memory _role) internal virtual {
// Checks: Role name must be shorter than 32 bytes
if (bytes(_role).length > 32) revert RoleNameTooLong();
_getPointerToAgoraAccessControlStorage().roles.add(bytes32(bytes(_role)));
}
function _removeRoleFromSet(string memory _role) internal virtual {
if (_getPointerToAgoraAccessControlStorage().roleMembership[_role].length() > 0) {
revert CannotRemoveRoleWithMembers({ role: _role });
}
_getPointerToAgoraAccessControlStorage().roles.remove(bytes32(bytes(_role)));
}
function _assignRole(string memory _role, address _member, bool _addRole) internal virtual {
// Checks: Role must exist
_requireRoleExists({ _role: _role });
// Effects: Set the roleMembership to the new _member
_setRoleMembership({ _role: _role, _member: _member, _insert: _addRole });
// Emit event
if (_addRole) emit RoleAssigned({ role: _role, member: _member });
else emit RoleRevoked({ role: _role, member: _member });
}
/// @notice The ```grantAccessControlManagerRole``` function grants `ACCESS_CONTROL_MANAGER_ROLE` to an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be granted the role
function grantAccessControlManagerRole(address _member) public virtual {
// Checks: Only `ACCESS_CONTROL_MANAGER_ROLE` can grant the role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: ACCESS_CONTROL_MANAGER_ROLE, _member: _member, _addRole: true });
}
/// @notice The ```revokeAccessControlManagerRole``` function revokes `ACCESS_CONTROL_MANAGER_ROLE` from an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @dev An `ACCESS_CONTROL_MANAGER_ROLE` member can't remove oneself from the role.
/// @param _member The address to be revoked the role
function revokeAccessControlManagerRole(address _member) public virtual {
// Checks: Only `ACCESS_CONTROL_MANAGER_ROLE` can revoke the role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
// Checks: cannot revoke oneself as `ACCESS_CONTROL_MANAGER_ROLE`
if (_member == msg.sender) revert CannotRevokeSelf();
_assignRole({ _role: ACCESS_CONTROL_MANAGER_ROLE, _member: _member, _addRole: false });
}
// ============================================================================================
// Internal Effects Functions
// ============================================================================================
/// @notice The ```_setRoleMembership``` function sets the role membership
/// @param _role The role identifier to transfer
/// @param _member The address of the new role
/// @param _insert Whether to add or remove the address from the role
function _setRoleMembership(string memory _role, address _member, bool _insert) internal virtual {
if (_insert) _getPointerToAgoraAccessControlStorage().roleMembership[_role].add(_member);
else _getPointerToAgoraAccessControlStorage().roleMembership[_role].remove(_member);
}
// ============================================================================================
// Internal Checks Functions
// ============================================================================================
/// @notice The ```_roleExists``` function checks if _role exists in the role set
/// @param _role The role identifier to check
/// @return Whether or not _role exists as a known role
function _roleExists(string memory _role) internal view virtual returns (bool) {
return _getPointerToAgoraAccessControlStorage().roles.contains(bytes32(bytes(_role)));
}
/// @notice The ```_requireRoleExists``` function revers if _role does not exist in the role set
/// @param _role The role identifier to check
function _requireRoleExists(string memory _role) internal view virtual {
if (!_roleExists({ _role: _role })) revert RoleDoesNotExist({ role: _role });
}
/// @notice The ```_isRole``` function checks if the member has the role
/// @param _role The role identifier to check
/// @param _member The address to check against the role
/// @return Whether or not the address has the role
function _isRole(string memory _role, address _member) internal view virtual returns (bool) {
return _getPointerToAgoraAccessControlStorage().roleMembership[_role].contains(_member);
}
/// @notice The ```_requireIsRole``` function reverts if member doesn't have the role
/// @param _role The role identifier to check
/// @param _member The address to check against the role
function _requireIsRole(string memory _role, address _member) internal view virtual {
if (!_isRole({ _role: _role, _member: _member })) revert AddressIsNotRole({ role: _role });
}
/// @notice The ```_requireSenderIsRole``` function reverts if msg.sender doesn't have the role
/// @dev This function is to be implemented by a public function
/// @param _role The role identifier to check
function _requireSenderIsRole(string memory _role) internal view virtual {
_requireIsRole({ _role: _role, _member: msg.sender });
}
//==============================================================================
// Public View Functions
//==============================================================================
/// @notice The ```hasRole``` function checks if _member has the role
/// @param _role The role identifier to check
/// @param _member The address to check against the role
/// @return Whether or not _member has the role
function hasRole(string memory _role, address _member) public view virtual returns (bool) {
return _isRole({ _role: _role, _member: _member });
}
/// @notice The ```getRoleMembers``` function returns the members of the role
/// @param _role The role identifier to check
/// @return The members of the role
function getRoleMembers(string memory _role) public view virtual returns (address[] memory) {
EnumerableSet.AddressSet storage _roleMembership = _getPointerToAgoraAccessControlStorage().roleMembership[
_role
];
return _roleMembership.values();
}
/// @notice The ```getAllRoles``` function returns all roles
/// @return _roles The roles
function getAllRoles() public view virtual returns (string[] memory _roles) {
uint256 _length = _getPointerToAgoraAccessControlStorage().roles.length();
_roles = new string[](_length);
for (uint256 i = 0; i < _length; i++) {
_roles[i] = string(abi.encodePacked(_getPointerToAgoraAccessControlStorage().roles.at(i)));
}
}
/// @notice The ```getAccessControlManagerRoleMembers``` function returns the addresses holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @return The array of addresses holding `ACCESS_CONTROL_MANAGER_ROLE`
function getAccessControlManagerRoleMembers() public view virtual returns (address[] memory) {
return getRoleMembers(ACCESS_CONTROL_MANAGER_ROLE);
}
//==============================================================================
// Erc 7201: UnstructuredNamespace Storage Functions
//==============================================================================
/// @notice The ```AGORA_ACCESS_CONTROL_STORAGE_SLOT``` is the storage slot for the AgoraAccessControlStorage struct
/// @dev keccak256(abi.encode(uint256(keccak256("AgoraAccessControlStorage")) - 1)) & ~bytes32(uint256(0xff))
bytes32 public constant AGORA_ACCESS_CONTROL_STORAGE_SLOT =
0x8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b000;
/// @notice The ```_getPointerToAgoraAccessControlStorage``` function returns a pointer to the AgoraAccessControlStorage struct
/// @return $ A pointer to the AgoraAccessControlStorage struct
function _getPointerToAgoraAccessControlStorage()
internal
pure
virtual
returns (AgoraAccessControlStorage storage $)
{
/// @solidity memory-safe-assembly
assembly {
$.slot := AGORA_ACCESS_CONTROL_STORAGE_SLOT
}
}
// ============================================================================================
// Events
// ============================================================================================
/// @notice The ```RoleAssigned``` event is emitted when the role is assigned
/// @param role The string identifier of the role that was transferred
/// @param member The address of the new role member
event RoleAssigned(string indexed role, address indexed member);
/// @notice The ```RoleRevoked``` event is emitted when the role is revoked
/// @param role The string identifier of the role that was transferred
/// @param member The address of the previous role member
event RoleRevoked(string indexed role, address indexed member);
// ============================================================================================
// Errors
// ============================================================================================
/// @notice Emitted when role is transferred
/// @param role The role identifier
error AddressIsNotRole(string role);
/// @notice Emitted when role name is too long
error RoleNameTooLong();
/// @notice Emitted when role does not exist
error RoleDoesNotExist(string role);
/// @notice Emitted when role still has members
error CannotRemoveRoleWithMembers(string role);
/// @notice Emitted when a member attempts removing oneself
error CannotRevokeSelf();
}
node_modules/agora-dollar-dev/src/contracts/AgoraDollarAccessControl.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.28;
// ====================================================================
// _ ______ ___ _______ _
// / \ .' ___ | .' `.|_ __ \ / \
// / _ \ / .' \_| / .-. \ | |__) | / _ \
// / ___ \ | | ____ | | | | | __ / / ___ \
// _/ / \ \_\ `.___] |\ `-' /_| | \ \_ _/ / \ \_
// |____| |____|`._____.' `.___.'|____| |___||____| |____|
// ====================================================================
// ===================== AgoraDollarAccessControl =====================
// ====================================================================
import { AgoraAccessControl } from "agora-contracts/access-control/AgoraAccessControl.sol";
/// @title AgoraDollarAccessControl
/// @notice An abstract contract that manages access control for the AgoraDollar contract
/// @author Agora
abstract contract AgoraDollarAccessControl is AgoraAccessControl {
/// @notice The MINTER_ROLE identifier
string public constant MINTER_ROLE = "MINTER_ROLE";
/// @notice The BURNER_ROLE identifier
string public constant BURNER_ROLE = "BURNER_ROLE";
/// @notice The PAUSER_ROLE identifier
string public constant PAUSER_ROLE = "PAUSER_ROLE";
/// @notice The FREEZER_ROLE identifier
string public constant FREEZER_ROLE = "FREEZER_ROLE";
/// @notice The BRIDGE_MINTER_ROLE identifier
string public constant BRIDGE_MINTER_ROLE = "BRIDGE_MINTER_ROLE";
/// @notice The BRIDGE_BURNER_ROLE identifier
string public constant BRIDGE_BURNER_ROLE = "BRIDGE_BURNER_ROLE";
/// @notice The RATE_LIMIT_MANAGER_ROLE identifier
string public constant RATE_LIMIT_MANAGER_ROLE = "RATE_LIMIT_MANAGER_ROLE";
/// @notice The ```_initializeAgoraDollarAccessControl``` function initializes the AgoraDollarAccessControl contract
/// @dev This function adds the default roles that are required by the AgoraDollar contract
/// @param _initialAdminAddress The address of the initial `ACCESS_CONTROL_MANAGER_ROLE` holder
/// @param _initialMinter The address of the initial `MINTER_ROLE` holder
/// @param _initialBurner The address of the initial `BURNER_ROLE` holder
/// @param _initialPauser The address of the initial `PAUSER_ROLE` holder
/// @param _initialFreezer The address of the initial `FREEZER_ROLE` holder
function _initializeAgoraDollarAccessControl(
address _initialAdminAddress,
address _initialMinter,
address _initialBurner,
address _initialPauser,
address _initialFreezer,
address _initialRateLimitManager
) internal {
_initializeAgoraAccessControl({ _initialAdminAddress: _initialAdminAddress });
// setup the minter role
_addRoleToSet({ _role: MINTER_ROLE });
_assignRole({ _role: MINTER_ROLE, _member: _initialMinter, _addRole: true });
// setup the burner role
_addRoleToSet({ _role: BURNER_ROLE });
_assignRole({ _role: BURNER_ROLE, _member: _initialBurner, _addRole: true });
// setup the pauser role
_addRoleToSet({ _role: PAUSER_ROLE });
_assignRole({ _role: PAUSER_ROLE, _member: _initialPauser, _addRole: true });
// setup the freezer role
_addRoleToSet({ _role: FREEZER_ROLE });
_assignRole({ _role: FREEZER_ROLE, _member: _initialFreezer, _addRole: true });
// setup the rate limit manager role
_addRoleToSet({ _role: RATE_LIMIT_MANAGER_ROLE });
_assignRole({ _role: RATE_LIMIT_MANAGER_ROLE, _member: _initialRateLimitManager, _addRole: true });
// setup the bridge minter role
_addRoleToSet({ _role: BRIDGE_MINTER_ROLE });
// setup the bridge burner role
_addRoleToSet({ _role: BRIDGE_BURNER_ROLE });
}
// ============================================================================================
// External Procedural Functions
// ============================================================================================
/// @notice The ```grantMinterRole``` function grants `MINTER_ROLE` to an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function grantMinterRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: MINTER_ROLE, _member: _member, _addRole: true });
}
/// @notice The ```revokeMinterRole``` function revokes `MINTER_ROLE` from an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function revokeMinterRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: MINTER_ROLE, _member: _member, _addRole: false });
}
/// @notice The ```grantBurnerRole``` function grants `BURNER_ROLE` to an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function grantBurnerRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: BURNER_ROLE, _member: _member, _addRole: true });
}
/// @notice The ```revokeBurnerRole``` function revokes `BURNER_ROLE` from an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function revokeBurnerRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: BURNER_ROLE, _member: _member, _addRole: false });
}
/// @notice The ```grantPauserRole``` function grants `PAUSER_ROLE` to an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function grantPauserRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: PAUSER_ROLE, _member: _member, _addRole: true });
}
/// @notice The ```revokePauserRole``` function revokes `PAUSER_ROLE` from an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function revokePauserRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: PAUSER_ROLE, _member: _member, _addRole: false });
}
/// @notice The ```grantFreezerRole``` function grants `FREEZER_ROLE` to an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function grantFreezerRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: FREEZER_ROLE, _member: _member, _addRole: true });
}
/// @notice The ```revokeFreezerRole``` function revokes `FREEZER_ROLE` from an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function revokeFreezerRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: FREEZER_ROLE, _member: _member, _addRole: false });
}
/// @notice The ```grantBridgeMinterRole``` function grants `BRIDGE_MINTER_ROLE` to an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function grantBridgeMinterRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: BRIDGE_MINTER_ROLE, _member: _member, _addRole: true });
}
/// @notice The ```revokeBridgeMinterRole``` function revokes `BRIDGE_MINTER_ROLE` from an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function revokeBridgeMinterRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: BRIDGE_MINTER_ROLE, _member: _member, _addRole: false });
}
/// @notice The ```grantBridgeBurnerRole``` function grants `BRIDGE_BURNER_ROLE` to an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function grantBridgeBurnerRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: BRIDGE_BURNER_ROLE, _member: _member, _addRole: true });
}
/// @notice The ```revokeBridgeBurnerRole``` function revokes `BRIDGE_BURNER_ROLE` from an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function revokeBridgeBurnerRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: BRIDGE_BURNER_ROLE, _member: _member, _addRole: false });
}
/// @notice The ```grantRateLimitManagerRole``` function grants `RATE_LIMIT_MANAGER_ROLE` to an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function grantRateLimitManagerRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: RATE_LIMIT_MANAGER_ROLE, _member: _member, _addRole: true });
}
/// @notice The ```revokeRateLimitManagerRole``` function revokes `RATE_LIMIT_MANAGER_ROLE` from an address
/// @dev Must be called by an address holding `ACCESS_CONTROL_MANAGER_ROLE`
/// @param _member The address to be assigned the role
function revokeRateLimitManagerRole(address _member) external {
// Checks: Only Admin can transfer role
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
_assignRole({ _role: RATE_LIMIT_MANAGER_ROLE, _member: _member, _addRole: false });
}
}
node_modules/agora-dollar-dev/src/contracts/AgoraDollarCore.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.28;
// solhint-disable func-name-mixedcase
// ====================================================================
// _ ______ ___ _______ _
// / \ .' ___ | .' `.|_ __ \ / \
// / _ \ / .' \_| / .-. \ | |__) | / _ \
// / ___ \ | | ____ | | | | | __ / / ___ \
// _/ / \ \_\ `.___] |\ `-' /_| | \ \_ _/ / \ \_
// |____| |____|`._____.' `.___.'|____| |___||____| |____|
// ====================================================================
// ========================= AgoraDollarCore ==========================
// ====================================================================
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { ShortString, ShortStrings } from "@openzeppelin/contracts/utils/ShortStrings.sol";
import { Eip3009 } from "./Eip3009.sol";
import { Eip712 } from "./Eip712.sol";
import { Erc20Privileged } from "./Erc20Privileged.sol";
import { Erc2612 } from "./Erc2612.sol";
import { StorageLib } from "./proxy/StorageLib.sol";
/// @notice The Constructor Params for AgoraDollarCore
/// @param name The name of the token
/// @param symbol The symbol of the token
/// @param eip712Name The name of the Eip712 domain
/// @param eip712Version The version of the Eip712 domain
/// @param proxyAddress The address of the proxy contract
struct ConstructorParams {
string name;
string symbol;
string eip712Name;
string eip712Version;
address proxyAddress;
}
/// @notice The ```InitializeParams``` struct is used to initialize `AgoraDollarCore`
/// @param initialAdminAddress The address of the initial admin
/// @param initialMinterAddress The address of the initial minter
/// @param initialBurnerAddress The address of the initial burner
/// @param initialPauserAddress The address of the initial pauser
/// @param initialFreezerAddress The address of the initial freezer
/// @param initialRateLimitManagerAddress The address of the initial rate limit manager
struct InitializeParams {
address initialAdminAddress;
address initialMinterAddress;
address initialBurnerAddress;
address initialPauserAddress;
address initialFreezerAddress;
address initialRateLimitManagerAddress;
}
/// @title AgoraDollarCore
/// @notice The AgoraDollarCore contract is the core implementation of the Agora Dollar token
/// @author Agora
contract AgoraDollarCore is Initializable, Eip3009, Erc2612, Erc20Privileged {
using StorageLib for uint256;
using ShortStrings for *;
ShortString internal immutable _name;
ShortString internal immutable _symbol;
uint8 public immutable decimals = 6;
constructor(
ConstructorParams memory _params
) Eip712(_params.eip712Name, _params.eip712Version, _params.proxyAddress) {
_name = _params.name.toShortString();
_symbol = _params.symbol.toShortString();
// Prevent implementation from being initialized
_disableInitializers();
}
/// @notice The ```initialize``` function initializes the AgoraDollarCore and inherited contracts
/// @dev Has a modifier to prevent reinitialization
/// @param _params The struct to define the initial addresses for role-based access control
function initialize(InitializeParams memory _params) external reinitializer(4) {
_initializeAgoraDollarAccessControl({
_initialAdminAddress: _params.initialAdminAddress,
_initialMinter: _params.initialMinterAddress,
_initialBurner: _params.initialBurnerAddress,
_initialPauser: _params.initialPauserAddress,
_initialFreezer: _params.initialFreezerAddress,
_initialRateLimitManager: _params.initialRateLimitManagerAddress
});
}
//==============================================================================
// External stateful Functions: Erc20
//==============================================================================
/// The ```approve``` function is used to approve a spender to spend a certain amount of tokens on behalf of the caller
/// @dev This function reverts on failure
/// @param _spender The address of the spender
/// @param _value The amount of tokens to approve for spending
/// @return success A boolean indicating if the approval was successful
function approve(address _spender, uint256 _value) external returns (bool) {
_approve({ _owner: msg.sender, _spender: _spender, _value: _value });
return true;
}
function transfer(address _to, uint256 _value) external returns (bool) {
// NOTE: implemented in proxy, here to check for signature collisions
}
function transferFrom(address _from, address _to, uint256 _value) external returns (bool) {
// NOTE: implemented in proxy, here to check for signature collisions
}
//==============================================================================
// External Stateful Functions: Erc3009
//==============================================================================
function transferWithAuthorization(
address _from,
address _to,
uint256 _value,
uint256 _validAfter,
uint256 _validBefore,
bytes32 _nonce,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
// NOTE: implemented in proxy, here to check for signature collisions
}
function transferWithAuthorization(
address _from,
address _to,
uint256 _value,
uint256 _validAfter,
uint256 _validBefore,
bytes32 _nonce,
bytes memory _signature
) public {
// NOTE: implemented in proxy, here to check for signature collisions
}
function receiveWithAuthorization(
address _from,
address _to,
uint256 _value,
uint256 _validAfter,
uint256 _validBefore,
bytes32 _nonce,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
// NOTE: implemented in proxy, here to check for signature collisions
}
function receiveWithAuthorization(
address _from,
address _to,
uint256 _value,
uint256 _validAfter,
uint256 _validBefore,
bytes32 _nonce,
bytes memory _signature
) public {
// NOTE: implemented in proxy, here to check for signature collisions
}
/// @notice The ```cancelAuthorization``` function cancels an authorization nonce
/// @dev EOA wallet signatures should be packed in the order of r, s, v
/// @param _authorizer Authorizer's address
/// @param _nonce Nonce of the authorization
/// @param _v ECDSA signature v value
/// @param _r ECDSA signature r value
/// @param _s ECDSA signature s value
function cancelAuthorization(address _authorizer, bytes32 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external {
cancelAuthorization({ _authorizer: _authorizer, _nonce: _nonce, _signature: abi.encodePacked(_r, _s, _v) });
}
/// @notice The ```cancelAuthorization``` function cancels an authorization nonce
/// @dev EOA wallet signatures should be packed in the order of r, s, v
/// @param _authorizer Authorizer's address
/// @param _nonce Nonce of the authorization
/// @param _signature Signature byte array produced by an EOA wallet or a contract wallet
function cancelAuthorization(address _authorizer, bytes32 _nonce, bytes memory _signature) public {
// Effects: mark the signature as used
_cancelAuthorization({ _authorizer: _authorizer, _nonce: _nonce, _signature: _signature });
}
//==============================================================================
// Contract Data Setters Functions
//==============================================================================
/// @notice The ```setIsMsgSenderCheckEnabled``` function sets the isMsgSenderCheckEnabled state variable
/// @param _isEnabled The new value of the isMsgSenderCheckEnabled state variable
function setIsMsgSenderCheckEnabled(bool _isEnabled) external {
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
uint256 _contractData = StorageLib.sloadImplementationSlotDataAsUint256();
uint256 _newContractData = _contractData.setBitWithMask({
_bitToSet: StorageLib.IS_MSG_SENDER_FROZEN_CHECK_ENABLED_BIT_POSITION_,
_setBitToOne: _isEnabled
});
_newContractData.sstoreImplementationSlotDataAsUint256();
emit SetIsMsgSenderCheckEnabled({ isEnabled: _isEnabled });
}
/// @notice The ```setIsMintPaused``` function sets the isMintPaused state variable
/// @param _isPaused The new value of the isMintPaused state variable
function setIsMintPaused(bool _isPaused) external {
_requireSenderIsRole({ _role: PAUSER_ROLE });
uint256 _contractData = StorageLib.sloadImplementationSlotDataAsUint256();
uint256 _newContractData = _contractData.setBitWithMask({
_bitToSet: StorageLib.IS_MINT_PAUSED_BIT_POSITION_,
_setBitToOne: _isPaused
});
_newContractData.sstoreImplementationSlotDataAsUint256();
emit SetIsMintPaused({ isPaused: _isPaused });
}
/// @notice The ```setIsBurnFromPaused``` function sets the isBurnFromPaused state variable
/// @param _isPaused The new value of the isBurnFromPaused state variable
function setIsBurnFromPaused(bool _isPaused) external {
_requireSenderIsRole({ _role: PAUSER_ROLE });
uint256 _contractData = StorageLib.sloadImplementationSlotDataAsUint256();
uint256 _newContractData = _contractData.setBitWithMask({
_bitToSet: StorageLib.IS_BURN_FROM_PAUSED_BIT_POSITION_,
_setBitToOne: _isPaused
});
_newContractData.sstoreImplementationSlotDataAsUint256();
emit SetIsBurnFromPaused({ isPaused: _isPaused });
}
/// @notice The ```setIsFreezingPaused``` function sets the isFreezingPaused state variable
/// @param _isPaused The new value of the isFreezingPaused state variable
function setIsFreezingPaused(bool _isPaused) external {
_requireSenderIsRole({ _role: PAUSER_ROLE });
uint256 _contractData = StorageLib.sloadImplementationSlotDataAsUint256();
uint256 _newContractData = _contractData.setBitWithMask({
_bitToSet: StorageLib.IS_FREEZING_PAUSED_BIT_POSITION_,
_setBitToOne: _isPaused
});
_newContractData.sstoreImplementationSlotDataAsUint256();
emit SetIsFreezingPaused({ isPaused: _isPaused });
}
/// @notice The ```setIsTransferPaused``` function sets the isTransferPaused state variable
/// @param _isPaused The new value of the isTransferPaused state variable
function setIsTransferPaused(bool _isPaused) external {
_requireSenderIsRole({ _role: PAUSER_ROLE });
uint256 _contractData = StorageLib.sloadImplementationSlotDataAsUint256();
uint256 _newContractData = _contractData.setBitWithMask({
_bitToSet: StorageLib.IS_TRANSFER_PAUSED_BIT_POSITION_,
_setBitToOne: _isPaused
});
_newContractData.sstoreImplementationSlotDataAsUint256();
emit SetIsTransferPaused({ isPaused: _isPaused });
}
/// @notice The ```setIsSignatureVerificationPaused``` function sets the isSignatureVerificationPaused state variable
/// @param _isPaused The new value of the isSignatureVerificationPaused state variable
function setIsSignatureVerificationPaused(bool _isPaused) external {
_requireSenderIsRole({ _role: PAUSER_ROLE });
uint256 _contractData = StorageLib.sloadImplementationSlotDataAsUint256();
uint256 _newContractData = _contractData.setBitWithMask({
_bitToSet: StorageLib.IS_SIGNATURE_VERIFICATION_PAUSED_BIT_POSITION_,
_setBitToOne: _isPaused
});
_newContractData.sstoreImplementationSlotDataAsUint256();
emit SetIsSignatureVerificationPaused({ isPaused: _isPaused });
}
/// @notice The ```setIsBridgingPaused``` function sets the isBridgingPaused state variable
/// @dev Enabling this flag prevents minting or burning from `BRIDGE_MINTER|BURNER_ROLE`
/// @param _isPaused The new value of the isBridgingPaused state variable
function setIsBridgingPaused(bool _isPaused) external {
_requireSenderIsRole({ _role: PAUSER_ROLE });
uint256 _contractData = StorageLib.sloadImplementationSlotDataAsUint256();
uint256 _newContractData = _contractData.setBitWithMask({
_bitToSet: StorageLib.IS_BRIDGING_PAUSED_BIT_POSITION_,
_setBitToOne: _isPaused
});
_newContractData.sstoreImplementationSlotDataAsUint256();
emit SetIsBridgingPaused({ isPaused: _isPaused });
}
/// @notice The ```setIsTransferUpgraded``` function sets the isTransferUpgraded state variable
/// @dev This flag forces the contract to use the implementation logic to call `transfer()`.
/// Ensure the implementation defines the `transfer()` function before setting this to true.
/// @param _isUpgraded The new value of the isTransferUpgraded state variable
function setIsTransferUpgraded(bool _isUpgraded) external {
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
uint256 _contractData = StorageLib.sloadImplementationSlotDataAsUint256();
uint256 _newContractData = _contractData.setBitWithMask({
_bitToSet: StorageLib.IS_TRANSFER_UPGRADED_BIT_POSITION_,
_setBitToOne: _isUpgraded
});
_newContractData.sstoreImplementationSlotDataAsUint256();
emit SetIsTransferUpgraded({ isUpgraded: _isUpgraded });
}
/// @notice The ```setIsTransferFromUpgraded``` function sets the isTransferFromUpgraded state variable
/// @dev This flag forces the contract to use the implementation logic to call `transferFrom()`.
/// Ensure the implementation defines the `transferFrom()` function before setting this to true.
/// @param _isUpgraded The new value of the isTransferFromUpgraded state variable
function setIsTransferFromUpgraded(bool _isUpgraded) external {
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
uint256 _contractData = StorageLib.sloadImplementationSlotDataAsUint256();
uint256 _newContractData = _contractData.setBitWithMask({
_bitToSet: StorageLib.IS_TRANSFER_FROM_UPGRADED_BIT_POSITION_,
_setBitToOne: _isUpgraded
});
_newContractData.sstoreImplementationSlotDataAsUint256();
emit SetIsTransferFromUpgraded({ isUpgraded: _isUpgraded });
}
/// @notice The ```setIsTransferWithAuthorizationUpgraded``` function sets the isTransferWithAuthorizationUpgraded state variable
/// @dev This flag forces the contract to use the implementation logic to call `transferWithAuthorization()`.
/// Ensure the implementation defines the `transferWithAuthorization()` function before setting this to true.
/// @param _isUpgraded The new value of the isTransferWithAuthorizationUpgraded state variable
function setIsTransferWithAuthorizationUpgraded(bool _isUpgraded) external {
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
uint256 _contractData = StorageLib.sloadImplementationSlotDataAsUint256();
uint256 _newContractData = _contractData.setBitWithMask({
_bitToSet: StorageLib.IS_TRANSFER_WITH_AUTHORIZATION_UPGRADED_BIT_POSITION_,
_setBitToOne: _isUpgraded
});
_newContractData.sstoreImplementationSlotDataAsUint256();
emit SetIsTransferWithAuthorizationUpgraded({ isUpgraded: _isUpgraded });
}
/// @notice The ```setIsReceiveWithAuthorizationUpgraded``` function sets the isReceiveWithAuthorizationUpgraded state variable
/// @dev This flag forces the contract to use the implementation logic to call `receiveWithAuthorization()`.
/// Ensure the implementation defines the `receiveWithAuthorization()` function before setting this to true.
/// @param _isUpgraded The new value of the isReceiveWithAuthorizationUpgraded state variable
function setIsReceiveWithAuthorizationUpgraded(bool _isUpgraded) external {
_requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
uint256 _contractData = StorageLib.sloadImplementationSlotDataAsUint256();
uint256 _newContractData = _contractData.setBitWithMask({
_bitToSet: StorageLib.IS_RECEIVE_WITH_AUTHORIZATION_UPGRADED_BIT_POSITION_,
_setBitToOne: _isUpgraded
});
_newContractData.sstoreImplementationSlotDataAsUint256();
emit SetIsReceiveWithAuthorizationUpgraded({ isUpgraded: _isUpgraded });
}
//==============================================================================
// Events
//==============================================================================
/// @notice The ```SetIsMsgSenderCheckEnabled``` event is emitted when the isMsgSenderCheckEnabled state variable is updated
/// @param isEnabled The new value of the isMsgSenderCheckEnabled state variable
event SetIsMsgSenderCheckEnabled(bool isEnabled);
/// @notice The ```SetIsMintPaused``` event is emitted when the isMintPaused state variable is updated
/// @param isPaused The new value of the isMintPaused state variable
event SetIsMintPaused(bool isPaused);
/// @notice The ```SetIsBurnFromPaused``` event is emitted when the isBurnFromPaused state variable is updated
/// @param isPaused The new value of the isBurnFromPaused state variable
event SetIsBurnFromPaused(bool isPaused);
/// @notice The ```SetIsFreezingPaused``` event is emitted when the isFreezingPaused state variable is updated
/// @param isPaused The new value of the isFreezingPaused state variable
event SetIsFreezingPaused(bool isPaused);
/// @notice The ```SetIsTransferPaused``` event is emitted when the isTransferPaused state variable is updated
/// @param isPaused The new value of the isTransferPaused state variable
event SetIsTransferPaused(bool isPaused);
/// @notice The ```SetIsSignatureVerificationPaused``` event is emitted when the isSignatureVerificationPaused state variable is updated
/// @param isPaused The new value of the isSignatureVerificationPaused state variable
event SetIsSignatureVerificationPaused(bool isPaused);
/// @notice The ```SetIsTransferUpgraded``` event is emitted when the isTransferUpgraded state variable is updated
/// @param isUpgraded The new value of the isTransferUpgraded state variable
event SetIsTransferUpgraded(bool isUpgraded);
/// @notice The ```SetIsTransferFromUpgraded``` event is emitted when the isTransferFromUpgraded state variable is updated
/// @param isUpgraded The new value of the isTransferFromUpgraded state variable
event SetIsTransferFromUpgraded(bool isUpgraded);
/// @notice The ```SetIsTransferWithAuthorizationUpgraded``` event is emitted when the isTransferWithAuthorizationUpgraded state variable is updated
/// @param isUpgraded The new value of the isTransferWithAuthorizationUpgraded state variable
event SetIsTransferWithAuthorizationUpgraded(bool isUpgraded);
/// @notice The ```SetIsReceiveWithAuthorizationUpgraded``` event is emitted when the isReceiveWithAuthorizationUpgraded state variable is updated
/// @param isUpgraded The new value of the isReceiveWithAuthorizationUpgraded state variable
event SetIsReceiveWithAuthorizationUpgraded(bool isUpgraded);
/// @notice The ```SetIsBridgingPaused``` event is emitted when the isBridgingPaused state variable is updated
/// @param isPaused The new value of the isBridgingPaused state variable
event SetIsBridgingPaused(bool isPaused);
}
node_modules/agora-dollar-dev/src/contracts/AgoraDollarMintRateLimit.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.28;
// ====================================================================
// _ ______ ___ _______ _
// / \ .' ___ | .' `.|_ __ \ / \
// / _ \ / .' \_| / .-. \ | |__) | / _ \
// / ___ \ | | ____ | | | | | __ / / ___ \
// _/ / \ \_\ `.___] |\ `-' /_| | \ \_ _/ / \ \_
// |____| |____|`._____.' `.___.'|____| |___||____| |____|
// ====================================================================
// ==================== AgoraDollarMintRateLimit ======================
// ====================================================================
import { AgoraDollarAccessControl } from "./AgoraDollarAccessControl.sol";
import { StorageLib } from "./proxy/StorageLib.sol";
/// @notice The ```AgoraDollarMintRateLimit``` contract implements a linear decay rate limit for the `_mint` functionality.
/// @dev Inspired by the LayerZero rate limiter:
/// https://github.com/LayerZero-Labs/devtools/blob/main/packages/oapp-evm/contracts/oapp/utils/RateLimiter.sol
abstract contract AgoraDollarMintRateLimit is AgoraDollarAccessControl {
/// @notice Rate Limit Configuration struct.
/// @param address The address of the minter
/// @param limit This represents the maximum allowed amount within a given window.
/// @param window Defines the duration of the rate limiting window.
struct MintRateLimitConfig {
address minter;
uint256 limit;
uint256 window;
}
//==============================================================================
// Internal Procedural Functions
//==============================================================================
/// @notice Sets the Rate Limit.
/// @param _rateLimitConfig A `MintRateLimitConfig` struct representing the rate limit configuration.
/// - `minter`: The minter address for which the rate limit is being set.
/// - `limit`: This represents the maximum allowed amount within a given window.
/// - `window`: Defines the duration of the rate limiting window.
function _setMintRateLimit(MintRateLimitConfig memory _rateLimitConfig) internal {
StorageLib.RateLimit storage rateLimit = StorageLib.getPointerToMintRateLimitStorage().rateLimits[
_rateLimitConfig.minter
];
// @dev Ensure we checkpoint the existing rate limit as to not retroactively apply the new decay rate.
_outflow({ _minter: _rateLimitConfig.minter, _amount: 0 });
// @dev Does NOT reset the amountInFlight/lastUpdated of an existing rate limit.
rateLimit.limit = _rateLimitConfig.limit;
rateLimit.window = _rateLimitConfig.window;
emit MintRateLimitChanged(_rateLimitConfig);
}
/// @notice Checks current amount in flight and amount that can be minted for a given rate limit window.
/// @param _amountInFlight The amount in the current window.
/// @param _lastUpdated Timestamp representing the last time the rate limit was checked or updated.
/// @param _limit This represents the maximum allowed amount within a given window.
/// @param _window Defines the duration of the rate limiting window.
/// @return currentAmountInFlight The amount in the current window.
/// @return amountCanBeMinted The amount that can be minted.
function _amountCanBeMinted(
uint256 _amountInFlight,
uint256 _lastUpdated,
uint256 _limit,
uint256 _window
) internal view returns (uint256 currentAmountInFlight, uint256 amountCanBeMinted) {
//slither-disable-next-line timestamp
uint256 _timeSinceLastMint = block.timestamp - _lastUpdated;
// @dev Presumes linear decay.
uint256 _decay = (_limit * _timeSinceLastMint) / (_window > 0 ? _window : 1); // prevent division by zero
currentAmountInFlight = _amountInFlight <= _decay ? 0 : _amountInFlight - _decay;
// @dev In the event the _limit is lowered, and the 'in-flight' amount is higher than the _limit, set to 0.
amountCanBeMinted = _limit <= currentAmountInFlight ? 0 : _limit - currentAmountInFlight;
}
/// @notice Verifies whether the specified amount falls within the rate limit constraints for the targeted
/// minter address. On successful verification, it updates amountInFlight and lastUpdated. If the amount exceeds
/// the rate limit, the operation reverts.
/// @param _minter The address of the minter
/// @param _amount The amount to check for rate limit constraints.
function _outflow(address _minter, uint256 _amount) internal {
StorageLib.RateLimit storage rateLimit = StorageLib.getPointerToMintRateLimitStorage().rateLimits[_minter];
(uint256 currentAmountInFlight, uint256 amountCanBeMinted) = _amountCanBeMinted({
_amountInFlight: rateLimit.amountInFlight,
_lastUpdated: rateLimit.lastUpdated,
_limit: rateLimit.limit,
_window: rateLimit.window
});
if (_amount > amountCanBeMinted) revert RateLimitExceeded();
rateLimit.amountInFlight = currentAmountInFlight + _amount;
rateLimit.lastUpdated = block.timestamp;
}
/// @notice Get the current amount that can be sent to this destination endpoint id for the given rate limit window.
/// @param _minter The address of the minter
/// @return currentAmountInFlight The current amount in the current window.
/// @return amountCanBeMinted The amount that can be minted.
/// @dev Returns (0, 0) if _minter does not have BRIDGE_MINTER_ROLE or MINTER_ROLE
function getAmountCanBeMinted(
address _minter
) external view returns (uint256 currentAmountInFlight, uint256 amountCanBeMinted) {
// Check if _minter has BRIDGE_MINTER_ROLE or MINTER_ROLE
if (
!_isRole({ _role: BRIDGE_MINTER_ROLE, _member: _minter }) &&
!_isRole({ _role: MINTER_ROLE, _member: _minter })
) return (0, 0);
StorageLib.RateLimit memory rateLimit = StorageLib.getPointerToMintRateLimitStorage().rateLimits[_minter];
return
_amountCanBeMinted({
_amountInFlight: rateLimit.amountInFlight,
_lastUpdated: rateLimit.lastUpdated,
_limit: rateLimit.limit,
_window: rateLimit.window
});
}
/// @notice Gets the rate limit for a given minter address.
/// @param _minter The address of the minter
/// @return The rate limit config for the given minter address.
function getMintRateLimit(address _minter) external view returns (StorageLib.RateLimit memory) {
return StorageLib.getPointerToMintRateLimitStorage().rateLimits[_minter];
}
/// @notice Sets the rate limits based on MintRateLimitConfig array.
/// @dev Must be called by an address holding `RATE_LIMIT_MANAGER_ROLE`
/// @dev These values are stored in the StorageLib.RateLimit struct for each minter address.
/// @dev Does NOT reset the amountInFlight/lastUpdated of an existing rate limit.
/// @dev Disabling the rate limit should be achieved by setting it to a large value (uint128.max)
/// @param _rateLimitConfig structure defining the rate limits for inbound transfers.
function setMintRateLimit(MintRateLimitConfig calldata _rateLimitConfig) external {
/// Checks: Only `RATE_LIMIT_MANAGER_ROLE` can set the rate limits
_requireSenderIsRole(RATE_LIMIT_MANAGER_ROLE);
/// Effects: Set the rate limits
_setMintRateLimit(_rateLimitConfig);
}
//==============================================================================
// Errors
//==============================================================================
/// @notice The ```RateLimitExceeded``` error is emitted when a rate limit is exceeded during an attempted mint
error RateLimitExceeded();
//==============================================================================
// Events
//==============================================================================
/// @notice Emitted when _setMintRateLimit occurs
/// @param rateLimitConfig A `MintRateLimitConfig` struct representing the rate limit configurations set.
/// - `address`: The minter address for which the rate limit is being set.
/// - `limit`: This represents the maximum allowed amount within a given window.
/// - `window`: Defines the duration of the rate limiting window.
event MintRateLimitChanged(MintRateLimitConfig rateLimitConfig);
}
node_modules/agora-dollar-dev/src/contracts/Eip3009.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.28;
// ====================================================================
// _ ______ ___ _______ _
// / \ .' ___ | .' `.|_ __ \ / \
// / _ \ / .' \_| / .-. \ | |__) | / _ \
// / ___ \ | | ____ | | | | | __ / / ___ \
// _/ / \ \_\ `.___] |\ `-' /_| | \ \_ _/ / \ \_
// |____| |____|`._____.' `.___.'|____| |___||____| |____|
// ====================================================================
// ============================= Eip3009 ==============================
// ====================================================================
import { MessageHashUtils } from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import { SafeCastLib } from "solady/src/utils/SafeCastLib.sol";
import { SignatureCheckerLib } from "solady/src/utils/SignatureCheckerLib.sol";
import { Eip712 } from "./Eip712.sol";
import { Erc20Core } from "./Erc20Core.sol";
import { StorageLib } from "./proxy/StorageLib.sol";
/// @title Eip3009
/// @notice Eip3009 provides internal implementations for gas-abstracted transfers under Eip3009 guidelines
/// @author Agora, inspired by Circle's Eip3009 implementation
abstract contract Eip3009 is Eip712, Erc20Core {
using SafeCastLib for uint256;
using StorageLib for uint256;
/// @notice keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 internal constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH_ =
0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
/// @notice keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 internal constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH_ =
0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;
/// @notice keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
bytes32 internal constant CANCEL_AUTHORIZATION_TYPEHASH_ =
0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
//==============================================================================
// Internal Procedural Functions
//==============================================================================
/// @notice The ```_transferWithAuthorization``` function executes a transfer with a signed authorization
/// @dev EOA wallet signatures should be packed in the order of r, s, v
/// @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 Signature byte array produced by an EOA wallet or a contract wallet
function _transferWithAuthorization(
address _from,
address _to,
uint256 _value,
uint256 _validAfter,
uint256 _validBefore,
bytes32 _nonce,
bytes memory _signature
) internal {
// Checks: authorization validity
if (block.timestamp <= _validAfter) revert InvalidAuthorization();
if (block.timestamp >= _validBefore) revert ExpiredAuthorization();
_requireUnusedAuthorization({ _authorizer: _from, _nonce: _nonce });
// Checks: valid signature
_requireIsValidSignatureNow({
_signer: _from,
_dataHash: keccak256(
abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH_, _from, _to, _value, _validAfter, _validBefore, _nonce)
),
_signature: _signature
});
// Effects: mark authorization as used and transfer
_markAuthorizationAsUsed({ _authorizer: _from, _nonce: _nonce });
_transfer({ _from: _from, _to: _to, _transferValue: _value.toUint248() });
}
/// @notice The ```_receiveWithAuthorization``` function receives 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
/// @dev EOA wallet signatures should be packed in the order of r, s, v
/// @param _from Payer's address (Authorizer)
/// @param _to Payee's address
/// @param _value Amount to be transferred
/// @param _validAfter The block.timestamp after which the authorization is valid
/// @param _validBefore The block.timestamp before which the authorization is valid
/// @param _nonce Unique nonce
/// @param _signature Signature byte array produced by an EOA wallet or a contract wallet
function _receiveWithAuthorization(
address _from,
address _to,
uint256 _value,
uint256 _validAfter,
uint256 _validBefore,
bytes32 _nonce,
bytes memory _signature
) internal {
// Checks: authorization validity
if (_to != msg.sender) revert InvalidPayee({ caller: msg.sender, payee: _to });
if (block.timestamp <= _validAfter) revert InvalidAuthorization();
if (block.timestamp >= _validBefore) revert ExpiredAuthorization();
_requireUnusedAuthorization({ _authorizer: _from, _nonce: _nonce });
// Checks: valid signature
_requireIsValidSignatureNow({
_signer: _from,
_dataHash: keccak256(
abi.encode(RECEIVE_WITH_AUTHORIZATION_TYPEHASH_, _from, _to, _value, _validAfter, _validBefore, _nonce)
),
_signature: _signature
});
// Effects: mark authorization as used and transfer
_markAuthorizationAsUsed({ _authorizer: _from, _nonce: _nonce });
_transfer({ _from: _from, _to: _to, _transferValue: _value.toUint248() });
}
/// @notice The ```_cancelAuthorization``` function cancels an authorization
/// @dev EOA wallet signatures should be packed in the order of r, s, v
/// @param _authorizer Authorizer's address
/// @param _nonce Nonce of the authorization
/// @param _signature Signature byte array produced by an EOA wallet or a contract wallet
function _cancelAuthorization(address _authorizer, bytes32 _nonce, bytes memory _signature) internal {
_requireUnusedAuthorization({ _authorizer: _authorizer, _nonce: _nonce });
_requireIsValidSignatureNow({
_signer: _authorizer,
_dataHash: keccak256(abi.encode(CANCEL_AUTHORIZATION_TYPEHASH_, _authorizer, _nonce)),
_signature: _signature
});
StorageLib.getPointerToEip3009Storage().isAuthorizationUsed[_authorizer][_nonce] = true;
emit AuthorizationCanceled({ authorizer: _authorizer, nonce: _nonce });
}
//==============================================================================
// Internal Checks Functions
//==============================================================================
/// @notice The ```_requireIsValidSignatureNow``` function validates that signature against input data struct
/// @param _signer Signer's address
/// @param _dataHash Hash of encoded data struct
/// @param _signature Signature byte array produced by an EOA wallet or a contract wallet
function _requireIsValidSignatureNow(address _signer, bytes32 _dataHash, bytes memory _signature) private view {
if (
!SignatureCheckerLib.isValidSignatureNow({
signer: _signer,
hash: MessageHashUtils.toTypedDataHash({
domainSeparator: _domainSeparatorV4(),
structHash: _dataHash
}),
signature: _signature
})
) revert InvalidSignature();
}
/// @notice The ```_requireUnusedAuthorization``` checks that an authorization nonce is unused
/// @param _authorizer Authorizer's address
/// @param _nonce Nonce of the authorization
function _requireUnusedAuthorization(address _authorizer, bytes32 _nonce) private view {
if (StorageLib.getPointerToEip3009Storage().isAuthorizationUsed[_authorizer][_nonce]) {
revert UsedOrCanceledAuthorization();
}
}
//==============================================================================
// Internal Effects Functions
//==============================================================================
/// @notice The ```_markAuthorizationAsUsed``` function marks an authorization nonce as used
/// @param _authorizer Authorizer's address
/// @param _nonce Nonce of the authorization
function _markAuthorizationAsUsed(address _authorizer, bytes32 _nonce) private {
StorageLib.getPointerToEip3009Storage().isAuthorizationUsed[_authorizer][_nonce] = true;
emit AuthorizationUsed({ authorizer: _authorizer, nonce: _nonce });
}
//==============================================================================
// Events
//==============================================================================
/// @notice ```AuthorizationUsed``` event is emitted when an authorization is used
/// @param authorizer Authorizer's address
/// @param nonce Nonce of the authorization
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
/// @notice ```AuthorizationCanceled``` event is emitted when an authorization is canceled
/// @param authorizer Authorizer's address
/// @param nonce Nonce of the authorization
event AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce);
//==============================================================================
// Errors
//==============================================================================
/// @notice The ```InvalidPayee``` error is emitted when the payee does not match sender in receiveWithAuthorization
/// @param caller The caller of the function
/// @param payee The expected payee in the function
error InvalidPayee(address caller, address payee);
/// @notice The ```InvalidAuthorization``` error is emitted when the authorization is invalid because its too early
error InvalidAuthorization();
/// @notice The ```ExpiredAuthorization``` error is emitted when the authorization is expired
error ExpiredAuthorization();
/// @notice The ```InvalidSignature``` error is emitted when the signature is invalid
error InvalidSignature();
/// @notice The ```UsedOrCanceledAuthorization``` error is emitted when the authorization nonce is already used or canceled
error UsedOrCanceledAuthorization();
}
node_modules/agora-dollar-dev/src/contracts/Eip712.sol
// SPDX-License-Identifier: Apache-2.0
// ***NOTE***: This file has been modified to remove external functions and storage for use in a transparent-ish proxy
// ***NOTE***: Modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/dbb6104ce834628e473d2173bbc9d47f81a9eec3/contracts/utils/cryptography/EIP712.sol
pragma solidity 0.8.28;
// ====================================================================
// _ ______ ___ _______ _
// / \ .' ___ | .' `.|_ __ \ / \
// / _ \ / .' \_| / .-. \ | |__) | / _ \
// / ___ \ | | ____ | | | | | __ / / ___ \
// _/ / \ \_\ `.___] |\ `-' /_| | \ \_ _/ / \ \_
// |____| |____|`._____.' `.___.'|____| |___||____| |____|
// ====================================================================
// ============================= Eip712 ===============================
// ====================================================================
import { ShortString, ShortStrings } from "@openzeppelin/contracts/utils/ShortStrings.sol";
import { MessageHashUtils } from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
*/
/// @title Eip712
/// @author Agora, modified from OpenZeppelin implementation
abstract contract Eip712 {
using ShortStrings for *;
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _cachedDomainSeparator;
uint256 private immutable _cachedChainId;
address private immutable _cachedThis;
bytes32 private immutable _hashedName;
bytes32 private immutable _hashedVersion;
ShortString private immutable _name;
ShortString private immutable _version;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*/
constructor(string memory name, string memory version, address expectedProxyAddress) {
_name = name.toShortString();
_version = version.toShortString();
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = keccak256(
abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, expectedProxyAddress)
);
_cachedThis = expectedProxyAddress;
}
/// @dev Returns the domain separator for the current chain
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _cachedThis && block.chainid == _cachedChainId) return _cachedDomainSeparator;
else return _buildDomainSeparator();
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view returns (bytes32) {
return MessageHashUtils.toTypedDataHash({ domainSeparator: _domainSeparatorV4(), structHash: structHash });
}
/**
* @dev The name parameter for the Eip712 domain.
*
* NOTE: By default this function reads _name which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _Eip712Name() internal view returns (string memory) {
return _name.toString();
}
/**
* @dev The version parameter for the Eip712 domain.
*
* NOTE: By default this function reads _version which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _Eip712Version() internal view returns (string memory) {
return _version.toString();
}
}
node_modules/agora-dollar-dev/src/contracts/Erc20Core.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.28;
// ====================================================================
// _ ______ ___ _______ _
// / \ .' ___ | .' `.|_ __ \ / \
// / _ \ / .' \_| / .-. \ | |__) | / _ \
// / ___ \ | | ____ | | | | | __ / / ___ \
// _/ / \ \_\ `.___] |\ `-' /_| | \ \_ _/ / \ \_
// |____| |____|`._____.' `.___.'|____| |___||____| |____|
// ====================================================================
// ============================ Erc20Core =============================
// ====================================================================
import { IERC20Errors as IErc20Errors } from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import { SafeCastLib } from "solady/src/utils/SafeCastLib.sol";
import { StorageLib } from "./proxy/StorageLib.sol";
/// @notice The ```Erc20Core``` contract is a base contract for the Erc20 standard
/// @title Erc20Core
/// @author Agora
abstract contract Erc20Core is IErc20Errors {
using StorageLib for uint256;
using SafeCastLib for uint256;
//==============================================================================
// Internal Procedural Functions
//==============================================================================
/// The ```_approve``` function is used to approve a spender to spend a certain amount of tokens on behalf of the caller
/// @dev This function reverts on failure
/// @param _spender The address of the spender
/// @param _value The amount of tokens to approve for spending
function _approve(address _owner, address _spender, uint256 _value) internal {
StorageLib.getPointerToErc20CoreStorage().accountAllowances[_owner][_spender] = _value;
emit Approval({ owner: _owner, spender: _spender, value: _value });
}
/// @notice The ```_transfer``` function transfers tokens which belong to the caller
/// @dev This function reverts on failure
/// @param _to The address of the recipient
/// @param _transferValue The amount of tokens to transfer
function _transfer(address _from, address _to, uint248 _transferValue) internal {
// Checks: Ensure _from address is not frozen
StorageLib.Erc20AccountData memory _accountDataFrom = StorageLib.getPointerToErc20CoreStorage().accountData[
_from
];
if (_accountDataFrom.isFrozen) revert AccountIsFrozen({ frozenAccount: _from });
// Checks: Ensure _from has enough balance
if (_accountDataFrom.balance < _transferValue) {
revert ERC20InsufficientBalance({
sender: _from,
balance: _accountDataFrom.balance,
needed: _transferValue
});
}
// Effects: update balances on the _from account
unchecked {
// Underflow not possible: _transferValue <= fromBalance asserted above
StorageLib.getPointerToErc20CoreStorage().accountData[_from].balance =
_accountDataFrom.balance -
_transferValue;
}
// NOTE: typically checks are done before effects, but in this case we need to handle the case where _to == _from and so we want to read the latest values
// Checks: Ensure _to address is not frozen
StorageLib.Erc20AccountData memory _accountDataTo = StorageLib.getPointerToErc20CoreStorage().accountData[_to];
if (_accountDataTo.isFrozen) revert AccountIsFrozen({ frozenAccount: _to });
// Effects: update balances on the _to account
unchecked {
// Overflow not possible: _transferValue + toBalance <= (2^248 -1) x 10^-6 [more money than atoms in the galaxy]
StorageLib.getPointerToErc20CoreStorage().accountData[_to].balance =
_accountDataTo.balance +
_transferValue;
}
emit Transfer({ from: _from, to: _to, value: _transferValue });
}
/// @notice The ```_spendAllowance``` function decrements a spenders allowance
/// @dev Treats type(uint256).max as infinite allowance and does not update balance
/// @param _owner The address of the owner
/// @param _spender The address of the spender
/// @param _value The amount of allowance to decrement
function _spendAllowance(address _owner, address _spender, uint256 _value) internal {
uint256 _currentAllowance = StorageLib.getPointerToErc20CoreStorage().accountAllowances[_owner][_spender];
// We treat uint256.max as infinite allowance, so we don't need to read/write storage in that case
if (_currentAllowance != type(uint256).max) {
if (_currentAllowance < _value) {
revert ERC20InsufficientAllowance({ spender: _spender, allowance: _currentAllowance, needed: _value });
}
unchecked {
StorageLib.getPointerToErc20CoreStorage().accountAllowances[_owner][_spender] =
_currentAllowance -
_value;
}
}
}
//==============================================================================
// Events
//==============================================================================
/// @notice The ```Transfer``` event is emitted when tokens are transferred from one account to another
/// @param from The account that is transferring tokens
/// @param to The account that is receiving tokens
/// @param value The amount of tokens being transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice ```Approval``` emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}
/// @param owner The account that is allowing the spender to spend
/// @param spender The account that is allowed to spend
/// @param value The amount of funds that the spender is allowed to spend
event Approval(address indexed owner, address indexed spender, uint256 value);
//==============================================================================
// Errors
//==============================================================================
/// @notice ```AccountIsFrozen``` error is emitted when an account is frozen and a transfer is attempted
/// @param frozenAccount The account that is frozen
error AccountIsFrozen(address frozenAccount);
}
node_modules/agora-dollar-dev/src/contracts/Erc20Privileged.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.28;
// ====================================================================
// _ ______ ___ _______ _
// / \ .' ___ | .' `.|_ __ \ / \
// / _ \ / .' \_| / .-. \ | |__) | / _ \
// / ___ \ | | ____ | | | | | __ / / ___ \
// _/ / \ \_\ `.___] |\ `-' /_| | \ \_ _/ / \ \_
// |____| |____|`._____.' `.___.'|____| |___||____| |____|
// ====================================================================
// ========================= Erc20Privileged ==========================
// ====================================================================
import { SafeCastLib } from "solady/src/utils/SafeCastLib.sol";
import { AgoraDollarMintRateLimit } from "./AgoraDollarMintRateLimit.sol";
import { Erc20Core } from "./Erc20Core.sol";
import { StorageLib } from "./proxy/StorageLib.sol";
/// @notice The ```Erc20Privileged``` contract extends the ```Erc20Core``` contract with privileged actions (mint, burn, freeze)
abstract contract Erc20Privileged is Erc20Core, AgoraDollarMintRateLimit {
using SafeCastLib for uint256;
using StorageLib for uint256;
//==============================================================================
// Mint Functions
//==============================================================================
/// @notice Parameters for a single mint operation
/// @param receiverAddress The address to mint tokens to
/// @param value The amount of tokens to mint
struct BatchMintParam {
address receiverAddress;
uint256 value;
}
/// @notice The ```batchMint``` function mints tokens to multiple accounts in a single transaction
/// @dev This function must be called by an address to which the MINTER_ROLE is granted
/// @dev Reverts on failure
/// @param _mints An array of ```BatchMintParam``` structs
function batchMint(BatchMintParam[] memory _mints) external {
// Checks: sender must be minter
_requireSenderIsRole({ _role: MINTER_ROLE });
// Checks: minting must not be paused
if (StorageLib.sloadImplementationSlotDataAsUint256().isMintPaused()) revert StorageLib.MintPaused();
// Effects: add to totalSupply and account balances
for (uint256 i = 0; i < _mints.length; i++) {
_mint({ _account: _mints[i].receiverAddress, _amount: _mints[i].value });
}
}
/// @notice The ```mint``` function mints tokens to an account. It is part of IMintableBurnable
/// @dev This function must be called by an address with `MINTER_ROLE` or `BRIDGE_MINTER_ROLE`
/// @dev Reverts on failure
/// @param _to An address to mint to
/// @param _amount The amount of tokens to mint
/// @dev Note, this allows minting to frozen accounts. This is to allow bridge contracts to mint to frozen accounts if needed.
function mint(address _to, uint256 _amount) external returns (bool) {
// Checks: sender must be `BRIDGE_MINTER_ROLE` or `MINTER_ROLE`
if (
!_isRole({ _role: BRIDGE_MINTER_ROLE, _member: msg.sender }) &&
!_isRole({ _role: MINTER_ROLE, _member: msg.sender })
) revert AddressIsNotMinterRole();
// Checks: minting must not be paused
if (StorageLib.sloadImplementationSlotDataAsUint256().isMintPaused()) revert StorageLib.MintPaused();
// Checks: bridging must not be paused
if (
_isRole({ _role: BRIDGE_MINTER_ROLE, _member: msg.sender }) &&
StorageLib.sloadImplementationSlotDataAsUint256().isBridgingPaused()
) revert StorageLib.BridgingPaused();
_mint({ _account: _to, _amount: _amount });
return true;
}
/// @dev The maximum amount that can be minted is `type(uint248).max` due to storage optimization
function _mint(address _account, uint256 _amount) internal {
_outflow({ _minter: msg.sender, _amount: _amount });
// Checks: account cannot be 0 address
if (_account == address(0)) revert ERC20InvalidReceiver({ receiver: address(0) });
uint248 _value248 = _amount.toUint248();
// Checks: amount cannot be zero
if (_value248 == 0) revert ZeroAmount();
// Effects: add to totalSupply and account balance
StorageLib.getPointerToErc20CoreStorage().totalSupply += _value248;
StorageLib.getPointerToErc20CoreStorage().accountData[_account].balance += _value248;
// Emit event
emit Transfer({ from: address(0), to: _account, value: _amount });
emit Minted({ sender: msg.sender, receiver: _account, value: _amount });
}
//==============================================================================
// Burn Functions
//==============================================================================
/// @notice Parameters for a single burn operation
/// @param burnFromAddress The address to burn tokens from
/// @param value The amount of tokens to burn
struct BatchBurnFromParam {
address burnFromAddress;
uint256 value;
}
/// @notice The ```batchBurnFrom``` function burns tokens from multiple accounts in a single transaction
/// @dev This function must be called by an address to which the BURNER_ROLE is granted
/// @dev Reverts on failure
/// @param _burns An array of ```BatchBurnFromParam``` structs
function batchBurnFrom(BatchBurnFromParam[] memory _burns) external {
// Checks: sender must be burner
_requireSenderIsRole({ _role: BURNER_ROLE });
// Checks: burnFrom must not be paused
if (StorageLib.sloadImplementationSlotDataAsUint256().isBurnFromPaused()) revert StorageLib.BurnFromPaused();
for (uint256 i = 0; i < _burns.length; i++) {
_burn({ _account: _burns[i].burnFromAddress, _amount: _burns[i].value });
}
}
/// @notice The ```burn``` function burns tokens from an account. It is part of IMintableBurnable
/// @dev This function must be called by an address with `BURNER_ROLE` or `BRIDGE_BURNER_ROLE`
/// @dev Reverts on failure
/// @param _from An address to burn from
/// @param _amount Amount of tokens to burn
function burn(address _from, uint256 _amount) external returns (bool) {
// Checks: sender must be `BRIDGE_BURNER_ROLE` or `BURNER_ROLE`
if (
!_isRole({ _role: BRIDGE_BURNER_ROLE, _member: msg.sender }) &&
!_isRole({ _role: BURNER_ROLE, _member: msg.sender })
) revert AddressIsNotBurnerRole();
// Checks: burnFrom must not be paused
if (StorageLib.sloadImplementationSlotDataAsUint256().isBurnFromPaused()) revert StorageLib.BurnFromPaused();
if (_isRole({ _role: BRIDGE_BURNER_ROLE, _member: msg.sender })) {
// Checks: bridging must not be paused
if (StorageLib.sloadImplementationSlotDataAsUint256().isBridgingPaused()) {
revert StorageLib.BridgingPaused();
}
// Checks: _from account must not be frozen
StorageLib.Erc20AccountData memory _accountDataFrom = StorageLib.getPointerToErc20CoreStorage().accountData[
_from
];
if (_accountDataFrom.isFrozen) revert AccountIsFrozen({ frozenAccount: _from });
}
_burn({ _account: _from, _amount: _amount });
return true;
}
function _burn(address _account, uint256 _amount) internal {
uint248 _value248 = _amount.toUint248();
// Checks: amount cannot be zero
if (_value248 == 0) revert ZeroAmount();
// Checks: ensure _account has enough balance
StorageLib.Erc20AccountData memory _accountDataFrom = StorageLib.getPointerToErc20CoreStorage().accountData[
_account
];
if (_accountDataFrom.balance < _value248) {
revert ERC20InsufficientBalance({ sender: _account, balance: _accountDataFrom.balance, needed: _value248 });
}
// Effects: subtract from totalSupply and account balance
StorageLib.getPointerToErc20CoreStorage().totalSupply -= _value248;
StorageLib.getPointerToErc20CoreStorage().accountData[_account].balance -= _value248;
// emit event (include Burned event to prevent spoofing of Transfer event as we don't check for 0 address in transfer)
emit Transfer({ from: _account, to: address(0), value: _amount });
emit Burned({ sender: msg.sender, burnFrom: _account, value: _amount });
}
//==============================================================================
// Freeze Functions
//==============================================================================
/// @notice The ```batchFreeze``` function freezes a set of accounts so that it cannot transfer tokens
/// @param _addresses The addresses of the accounts getting frozen
function batchFreeze(address[] memory _addresses) external {
// Checks: Only the FREEZER_ROLE can freeze addresses
_requireSenderIsRole({ _role: FREEZER_ROLE });
if (StorageLib.sloadImplementationSlotDataAsUint256().isFreezingPaused()) revert StorageLib.FreezingPaused();
for (uint256 _i = 0; _i < _addresses.length; _i++) {
// Effects: freeze the addresses
StorageLib.getPointerToErc20CoreStorage().accountData[_addresses[_i]].isFrozen = true;
emit AccountFrozen({ account: _addresses[_i] });
}
}
/// @notice The ```batchUnfreeze``` function unfreezes a set of accounts so that it can transfer tokens again
/// @param _addresses The addresses of the accounts getting unfrozen
function batchUnfreeze(address[] memory _addresses) external {
// Checks: Only the FREEZER_ROLE can unfreeze addresses
_requireSenderIsRole({ _role: FREEZER_ROLE });
if (StorageLib.sloadImplementationSlotDataAsUint256().isFreezingPaused()) revert StorageLib.FreezingPaused();
for (uint256 _i = 0; _i < _addresses.length; _i++) {
// Effects: unfreeze the addresses
StorageLib.getPointerToErc20CoreStorage().accountData[_addresses[_i]].isFrozen = false;
emit AccountUnfrozen({ account: _addresses[_i] });
}
}
//==============================================================================
// Errors
//==============================================================================
/// @notice Error when an amount is unexpectedly zero.
error ZeroAmount();
/// @notice Emitted when the caller of `burn()` does not have the necessary role.
error AddressIsNotBurnerRole();
/// @notice Emitted when the caller of `mint()` does not have the necessary role.
error AddressIsNotMinterRole();
//==============================================================================
// Events
//==============================================================================
/// @notice The ```AccountUnfrozen``` event is emitted when an account is unfrozen
/// @param account The account that was unfrozen
event AccountUnfrozen(address indexed account);
/// @notice The ```AccountFrozen``` event is emitted when an account is frozen
/// @param account The account that was frozen
event AccountFrozen(address indexed account);
/// @notice The ```Minted``` event is emitted when tokens are minted
/// @param sender The account that initiated the mint
/// @param receiver The account that received the minted tokens
/// @param value The amount of tokens minted
event Minted(address indexed sender, address indexed receiver, uint256 value);
/// @notice The ```Burned``` event is emitted when tokens are burned
/// @param sender The account that initiated the burn
/// @param burnFrom The account that burned the tokens
/// @param value The amount of tokens burned
event Burned(address indexed sender, address indexed burnFrom, uint256 value);
}
node_modules/agora-dollar-dev/src/contracts/Erc2612.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.28;
// ====================================================================
// _ ______ ___ _______ _
// / \ .' ___ | .' `.|_ __ \ / \
// / _ \ / .' \_| / .-. \ | |__) | / _ \
// / ___ \ | | ____ | | | | | __ / / ___ \
// _/ / \ \_\ `.___] |\ `-' /_| | \ \_ _/ / \ \_
// |____| |____|`._____.' `.___.'|____| |___||____| |____|
// ====================================================================
// ============================= Erc2612 ==============================
// ====================================================================
import { SignatureCheckerLib } from "solady/src/utils/SignatureCheckerLib.sol";
import { Eip712 } from "./Eip712.sol";
import { Erc20Core } from "./Erc20Core.sol";
import { StorageLib } from "./proxy/StorageLib.sol";
abstract contract Erc2612 is Eip712, Erc20Core {
using StorageLib for uint256;
/// @notice The ```PERMIT_TYPEHASH``` stores keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
//==============================================================================
// External Procedural Functions
//==============================================================================
/// @notice The ```permit``` function sets an allowance with a signature
/// @param _owner The account that signed the message
/// @param _spender The account that is allowed to spend the funds
/// @param _value The amount of funds that can be spent
/// @param _deadline The time by which the transaction must be completed
/// @param _v The v of the ECDSA signature
/// @param _r The r of the ECDSA signature
/// @param _s The s of the ECDSA signature
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
permit({
_owner: _owner,
_spender: _spender,
_value: _value,
_deadline: _deadline,
_signature: abi.encodePacked(_r, _s, _v)
});
}
/// @notice The ```permit``` function sets an allowance with a signature
/// @param _owner The account that signed the message
/// @param _spender The account that is allowed to spend the funds
/// @param _value The amount of funds that can be spent
/// @param _deadline The time by which the transaction must be completed
/// @param _signature The signature of the message
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
bytes memory _signature
) public {
// Checks: contract-wide access control
bool _isSignatureVerificationPaused = StorageLib
.sloadImplementationSlotDataAsUint256()
.isSignatureVerificationPaused();
if (_isSignatureVerificationPaused) revert StorageLib.SignatureVerificationPaused();
// Checks: deadline
if (block.timestamp > _deadline) revert Erc2612ExpiredSignature({ deadline: _deadline });
// Effects: increment nonce
uint256 _nextNonce;
unchecked {
_nextNonce = StorageLib.getPointerToErc2612Storage().nonces[_owner]++;
}
bytes32 _structHash = keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, _nextNonce, _deadline));
bytes32 _hash = _hashTypedDataV4({ structHash: _structHash });
// Checks: is valid eoa or eip1271 signature
bool _isValidSignature = SignatureCheckerLib.isValidSignatureNow({
signer: _owner,
hash: _hash,
signature: _signature
});
if (!_isValidSignature) revert Erc2612InvalidSignature();
// Effects: update bookkeeping
_approve({ _owner: _owner, _spender: _spender, _value: _value });
}
/// @notice The ```DOMAIN_SEPARATOR``` function returns the configured domain separator
/// @return _domainSeparator The domain separator
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32 _domainSeparator) {
_domainSeparator = _domainSeparatorV4();
}
//==============================================================================
// Errors
//==============================================================================
/// @notice The ```Erc2612ExpiredSignature``` error is emitted when the signature is expired
/// @param deadline the time by which the transaction must be completed
error Erc2612ExpiredSignature(uint256 deadline);
/// @notice The ```Erc2612InvalidSignature``` error is emitted when the signature is invalid
error Erc2612InvalidSignature();
}
node_modules/agora-dollar-dev/src/contracts/proxy/StorageLib.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.28;
// ====================================================================
// _ ______ ___ _______ _
// / \ .' ___ | .' `.|_ __ \ / \
// / _ \ / .' \_| / .-. \ | |__) | / _ \
// / ___ \ | | ____ | | | | | __ / / ___ \
// _/ / \ \_\ `.___] |\ `-' /_| | \ \_ _/ / \ \_
// |____| |____|`._____.' `.___.'|____| |___||____| |____|
// ====================================================================
// ============================ StorageLib ============================
// ====================================================================
/**
* This library contains information for accessing unstructured storage following erc1967
* and erc7201 standards.
*
* The erc1967 storage slots are defined using their own formula/namespace.
* These are listed last in the contract.
*
* The erc7201 namespace is defined as <ContractName>.<Namespace>
* The deriveErc7201StorageSlot() function is used to derive the storage slot for a given namespace
* and to check that value against the hard-coded bytes32 value for the slot location in testing frameworks
* Each inherited contract has its own struct of the form <ContractName>Storage which matches <Namespace>
* from above. Each struct is held in a unique namespace and has a unique storage slot.
* See: https://eips.ethereum.org/EIPS/eip-7201 for additional information regarding this standard
*/
/// @title StorageLib
/// @dev Implements pure functions for calculating and accessing storage slots according to eip1967 and eip7201
/// @author Agora
library StorageLib {
/// @notice Global namespace for use in deriving storage slot locations
string internal constant GLOBAL_ERC7201_NAMESPACE = "AgoraDollarErc1967Proxy";
// Use this function to check hardcoded bytes32 values against the expected formula
function deriveErc7201StorageSlot(string memory _localNamespace) internal pure returns (bytes32) {
bytes memory _namespace = abi.encodePacked(GLOBAL_ERC7201_NAMESPACE, ".", _localNamespace);
return keccak256(abi.encode(uint256(keccak256(_namespace)) - 1)) & ~bytes32(uint256(0xff));
}
//==============================================================================
// Eip3009 Storage Items
//==============================================================================
/// @notice The EIP3009 namespace
string internal constant EIP3009_NAMESPACE = "Eip3009Storage";
/// @notice The Eip3009Storage struct
/// @param isAuthorizationUsed A mapping of authorizer to nonce to boolean to indicate if the nonce has been used
/// @custom:storage-location erc7201:AgoraDollarErc1967Proxy.Eip3009Storage
struct Eip3009Storage {
mapping(address _authorizer => mapping(bytes32 _nonce => bool _isNonceUsed)) isAuthorizationUsed;
}
/// @notice The ```EIP3009_STORAGE_SLOT_``` is the storage slot for the Eip3009Storage struct
/// @dev keccak256(abi.encode(uint256(keccak256("AgoraDollarErc1967Proxy.Eip3009Storage")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant EIP3009_STORAGE_SLOT_ =
0xbb0a37da742be2e3b68bdb11d195150f4243c03fb37d3cdfa756046082a38600;
/// @notice The ```getPointerToEip3009Storage``` function returns a pointer to the Eip3009Storage struct
/// @return $ A pointer to the Eip3009Storage struct
function getPointerToEip3009Storage() internal pure returns (Eip3009Storage storage $) {
/// @solidity memory-safe-assembly
assembly {
$.slot := EIP3009_STORAGE_SLOT_
}
}
//==============================================================================
// Erc2612 Storage Items
//==============================================================================
/// @notice The Erc2612 namespace
string internal constant ERC2612_NAMESPACE = "Erc2612Storage";
/// @notice The Erc2612Storage struct
/// @param nonces A mapping of signer address to uint256 to store the nonce
/// @custom:storage-location erc7201:AgoraDollarErc1967Proxy.Erc2612Storage
struct Erc2612Storage {
mapping(address _signer => uint256 _nonce) nonces;
}
/// @notice The ```ERC2612_STORAGE_SLOT_``` is the storage slot for the Erc2612Storage struct
/// @dev keccak256(abi.encode(uint256(keccak256("AgoraDollarErc1967Proxy.Erc2612Storage")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant ERC2612_STORAGE_SLOT_ =
0x69e87f5b9323740fce20cdf574dacd1d10e756da64a1f2df70fd1ace4c7cc300;
/// @notice The ```getPointerToErc2612Storage``` function returns a pointer to the Erc2612Storage struct
/// @return $ A pointer to the Erc2612Storage struct
function getPointerToErc2612Storage() internal pure returns (Erc2612Storage storage $) {
/// @solidity memory-safe-assembly
assembly {
$.slot := ERC2612_STORAGE_SLOT_
}
}
//==============================================================================
// Erc20Core Storage Items
//==============================================================================
/// @notice The Erc20Core namespace
string internal constant ERC20_CORE_NAMESPACE = "Erc20CoreStorage";
/// @notice The Erc20AccountData struct
/// @param isFrozen A boolean to indicate if the account is frozen
/// @param balance A uint248 to store the balance of the account
struct Erc20AccountData {
bool isFrozen;
uint248 balance;
}
/// @notice The Erc20CoreStorage struct
/// @param accountData A mapping of address to Erc20AccountData to store account data
/// @param accountAllowances A mapping of owner to spender to uint256 to store the allowance
/// @param totalSupply A uint256 to store the total supply of tokens
/// @custom:storage-location erc7201:AgoraDollarErc1967Proxy.Erc20CoreStorage
struct Erc20CoreStorage {
/// @dev _account The account whose data we are accessing
/// @dev _accountData The account data for the account
mapping(address _account => Erc20AccountData _accountData) accountData;
/// @dev _owner The owner of the tokens
/// @dev _spender The spender of the tokens
/// @dev _accountAllowance The allowance of the spender
mapping(address _owner => mapping(address _spender => uint256 _accountAllowance)) accountAllowances;
/// @dev The total supply of tokens
uint256 totalSupply;
}
/// @notice The ```ERC20_CORE_STORAGE_SLOT_``` is the storage slot for the Erc20CoreStorage struct
/// @dev keccak256(abi.encode(uint256(keccak256("AgoraDollarErc1967Proxy.Erc20CoreStorage")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant ERC20_CORE_STORAGE_SLOT_ =
0x455730fed596673e69db1907be2e521374ba893f1a04cc5f5dd931616cd6b700;
/// @notice The ```getPointerToErc20CoreStorage``` function returns a pointer to the Erc20CoreStorage struct
/// @return $ A pointer to the Erc20CoreStorage struct
function getPointerToErc20CoreStorage() internal pure returns (Erc20CoreStorage storage $) {
/// @solidity memory-safe-assembly
assembly {
$.slot := ERC20_CORE_STORAGE_SLOT_
}
}
//==============================================================================
// AgoraDollarErc1967 Admin Slot Items
//==============================================================================
/// @notice The AgoraDollarErc1967ProxyAdminStorage struct
/// @param proxyAdminAddress The address of the proxy admin contract
/// @custom:storage-location erc1967:eip1967.proxy.admin
struct AgoraDollarErc1967ProxyAdminStorage {
address proxyAdminAddress;
}
/// @notice The ```AGORA_DOLLAR_ERC1967_PROXY_ADMIN_STORAGE_SLOT_``` is the storage slot for the AgoraDollarErc1967ProxyAdminStorage struct
/// @dev NOTE: deviates from erc7201 standard because erc1967 defines its own storage slot algorithm
/// @dev bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)
bytes32 internal constant AGORA_DOLLAR_ERC1967_PROXY_ADMIN_STORAGE_SLOT_ =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/// @notice The ```getPointerToAgoraDollarErc1967ProxyAdminStorage``` function returns a pointer to the AgoraDollarErc1967ProxyAdminStorage struct
/// @return adminSlot A pointer to the AgoraDollarErc1967ProxyAdminStorage struct
function getPointerToAgoraDollarErc1967ProxyAdminStorage()
internal
pure
returns (AgoraDollarErc1967ProxyAdminStorage storage adminSlot)
{
/// @solidity memory-safe-assembly
assembly {
adminSlot.slot := AGORA_DOLLAR_ERC1967_PROXY_ADMIN_STORAGE_SLOT_
}
}
//==============================================================================
// AgoraDollarErc1967Proxy Implementation Slot Items
//==============================================================================
/// @notice The AgoraDollarErc1967ProxyContractStorage struct
/// @param implementationAddress The address of the implementation contract
/// @param placeholder A placeholder for bits to be used as bitmask items
/// @custom:storage-location erc1967:eip1967.proxy.implementation
struct AgoraDollarErc1967ProxyContractStorage {
address implementationAddress; // least significant bits first
uint96 placeholder; // Placeholder for bitmask items defined below
}
/// @notice The ```AGORA_DOLLAR_ERC1967_PROXY_CONTRACT_STORAGE_SLOT_``` is the storage slot for the AgoraDollarErc1967ProxyContractStorage struct
/// @dev bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)
bytes32 internal constant AGORA_DOLLAR_ERC1967_PROXY_CONTRACT_STORAGE_SLOT_ =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/// @notice The ```getPointerToAgoraDollarErc1967ProxyContractStorage``` function returns a pointer to the storage slot for the implementation address
/// @return contractData A pointer to the data in the storage slot for the implementation address and other contract data
function getPointerToAgoraDollarErc1967ProxyContractStorage()
internal
pure
returns (AgoraDollarErc1967ProxyContractStorage storage contractData)
{
/// @solidity memory-safe-assembly
assembly {
contractData.slot := AGORA_DOLLAR_ERC1967_PROXY_CONTRACT_STORAGE_SLOT_
}
}
/// @notice The ```sloadImplementationSlotDataAsUint256``` function returns the data at the implementation slot as a uint256
/// @dev Named this way to draw attention to the sload call
/// @return _contractData The data at the implementation slot as a uint256
function sloadImplementationSlotDataAsUint256() internal view returns (uint256 _contractData) {
/// @solidity memory-safe-assembly
assembly {
_contractData := sload(AGORA_DOLLAR_ERC1967_PROXY_CONTRACT_STORAGE_SLOT_)
}
}
/// @notice The ```sstoreImplementationSlotDataAsUint256``` function stores the data at the implementation slot
/// @dev Named this way to draw attention to the sstore call
/// @param _contractData The data to store at the implementation slot, given as a uint256
function sstoreImplementationSlotDataAsUint256(uint256 _contractData) internal {
/// @solidity memory-safe-assembly
assembly {
sstore(AGORA_DOLLAR_ERC1967_PROXY_CONTRACT_STORAGE_SLOT_, _contractData)
}
}
// Contract Access Control masks
uint256 internal constant IS_MSG_SENDER_FROZEN_CHECK_ENABLED_BIT_POSITION_ = 1 << (255 - 95);
uint256 internal constant IS_MINT_PAUSED_BIT_POSITION_ = 1 << (255 - 94);
uint256 internal constant IS_BURN_FROM_PAUSED_BIT_POSITION_ = 1 << (255 - 93);
uint256 internal constant IS_FREEZING_PAUSED_BIT_POSITION_ = 1 << (255 - 92);
uint256 internal constant IS_TRANSFER_PAUSED_BIT_POSITION_ = 1 << (255 - 91);
uint256 internal constant IS_SIGNATURE_VERIFICATION_PAUSED_BIT_POSITION_ = 1 << (255 - 90);
// internal function upgrade masks
// Erc20
uint256 internal constant IS_TRANSFER_UPGRADED_BIT_POSITION_ = 1 << (255 - 89);
uint256 internal constant IS_TRANSFER_FROM_UPGRADED_BIT_POSITION_ = 1 << (255 - 88);
// Eip 3009
uint256 internal constant IS_TRANSFER_WITH_AUTHORIZATION_UPGRADED_BIT_POSITION_ = 1 << (255 - 87);
uint256 internal constant IS_RECEIVE_WITH_AUTHORIZATION_UPGRADED_BIT_POSITION_ = 1 << (255 - 86);
// Bridging
uint256 internal constant IS_BRIDGING_PAUSED_BIT_POSITION_ = 1 << (255 - 85);
//==============================================================================
// Bitmask Functions
//==============================================================================
// These function use a bitmask to check if a specific bit is set in the contract data
function isMsgSenderFrozenCheckEnabled(uint256 _contractData) internal pure returns (bool) {
return _contractData & IS_MSG_SENDER_FROZEN_CHECK_ENABLED_BIT_POSITION_ != 0;
}
function isMintPaused(uint256 _contractData) internal pure returns (bool) {
return _contractData & IS_MINT_PAUSED_BIT_POSITION_ != 0;
}
function isBurnFromPaused(uint256 _contractData) internal pure returns (bool) {
return _contractData & IS_BURN_FROM_PAUSED_BIT_POSITION_ != 0;
}
function isFreezingPaused(uint256 _contractData) internal pure returns (bool) {
return _contractData & IS_FREEZING_PAUSED_BIT_POSITION_ != 0;
}
function isTransferPaused(uint256 _contractData) internal pure returns (bool) {
return _contractData & IS_TRANSFER_PAUSED_BIT_POSITION_ != 0;
}
function isSignatureVerificationPaused(uint256 _contractData) internal pure returns (bool) {
return _contractData & IS_SIGNATURE_VERIFICATION_PAUSED_BIT_POSITION_ != 0;
}
function isTransferUpgraded(uint256 _contractData) internal pure returns (bool) {
return _contractData & IS_TRANSFER_UPGRADED_BIT_POSITION_ != 0;
}
function isTransferFromUpgraded(uint256 _contractData) internal pure returns (bool) {
return _contractData & IS_TRANSFER_FROM_UPGRADED_BIT_POSITION_ != 0;
}
function isTransferWithAuthorizationUpgraded(uint256 _contractData) internal pure returns (bool) {
return _contractData & IS_TRANSFER_WITH_AUTHORIZATION_UPGRADED_BIT_POSITION_ != 0;
}
function isReceiveWithAuthorizationUpgraded(uint256 _contractData) internal pure returns (bool) {
return _contractData & IS_RECEIVE_WITH_AUTHORIZATION_UPGRADED_BIT_POSITION_ != 0;
}
function isBridgingPaused(uint256 _contractData) internal pure returns (bool) {
return _contractData & IS_BRIDGING_PAUSED_BIT_POSITION_ != 0;
}
function implementation(uint256 _contractData) internal pure returns (address) {
// return least significant 160 bits and cast to an address
return address(uint160(_contractData));
}
function setBitWithMask(
uint256 _original,
uint256 _bitToSet,
bool _setBitToOne
) internal pure returns (uint256 _new) {
// Sets the specified bit to 1 or 0
_new = _setBitToOne ? _original | _bitToSet : _original & ~_bitToSet;
}
//==============================================================================
// RateLimit Slot Items
//==============================================================================
/// @notice Rate Limit struct.
/// @param amountInFlight The amount in the current window.
/// @param lastUpdated Timestamp representing the last time the rate limit was checked or updated.
/// @param limit This represents the maximum allowed amount within a given window.
/// @param window Defines the duration of the rate limiting window.
struct RateLimit {
uint256 amountInFlight;
uint256 lastUpdated;
uint256 limit;
uint256 window;
}
/// @notice The MintRateLimitStorage struct
/// @param MintRateLimitStorage Mapping from minter address to RateLimit configurations.
/// @custom:storage-location erc7201:AgoraDollarErc1967Proxy.MintRateLimitStorage
struct MintRateLimitStorage {
mapping(address minter => RateLimit limit) rateLimits;
}
/// @notice The ```MINT_RATE_LIMIT_STORAGE_SLOT``` is the storage slot for the MintRateLimitStorage struct
/// @dev keccak256(abi.encode(uint256(keccak256("AgoraDollarErc1967Proxy.MintRateLimitStorage")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant MINT_RATE_LIMIT_STORAGE_SLOT =
0xdbb7496039d83aff244e00691e8f456fd1760542eb35f98e0e87f449c82c5500;
/// @notice The ```getPointerToMintRateLimitStorage``` function returns a pointer to the MintRateLimitStorage struct
/// @return $ A pointer to the MintRateLimitStorage struct
function getPointerToMintRateLimitStorage() internal pure returns (MintRateLimitStorage storage $) {
/// @solidity memory-safe-assembly
assembly {
$.slot := MINT_RATE_LIMIT_STORAGE_SLOT
}
}
//==============================================================================
// Errors
//==============================================================================
/// @notice The ```TransferPaused``` error is emitted when transfers are paused during an attempted transfer
error TransferPaused();
/// @notice The ```SignatureVerificationPaused``` error is emitted when signature verification is paused during an attempted transfer
error SignatureVerificationPaused();
/// @notice The ```MintPaused``` error is emitted when minting is paused during an attempted mint
error MintPaused();
/// @notice The ```BurnFromPaused``` error is emitted when burning is paused during an attempted burn
error BurnFromPaused();
/// @notice The ```FreezingPaused``` error is emitted when freezing is paused during an attempted call to freeze() or unfreeze()
error FreezingPaused();
/// @notice The ```BridgingPaused``` error is emitted when bridging is paused during an attempted bridge mint or burn
error BridgingPaused();
}
node_modules/solady/src/utils/SafeCastLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe integer casting library that reverts on overflow.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeCastLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)
library SafeCastLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
error Overflow();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* UNSIGNED INTEGER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function toUint8(uint256 x) internal pure returns (uint8) {
if (x >= 1 << 8) _revertOverflow();
return uint8(x);
}
function toUint16(uint256 x) internal pure returns (uint16) {
if (x >= 1 << 16) _revertOverflow();
return uint16(x);
}
function toUint24(uint256 x) internal pure returns (uint24) {
if (x >= 1 << 24) _revertOverflow();
return uint24(x);
}
function toUint32(uint256 x) internal pure returns (uint32) {
if (x >= 1 << 32) _revertOverflow();
return uint32(x);
}
function toUint40(uint256 x) internal pure returns (uint40) {
if (x >= 1 << 40) _revertOverflow();
return uint40(x);
}
function toUint48(uint256 x) internal pure returns (uint48) {
if (x >= 1 << 48) _revertOverflow();
return uint48(x);
}
function toUint56(uint256 x) internal pure returns (uint56) {
if (x >= 1 << 56) _revertOverflow();
return uint56(x);
}
function toUint64(uint256 x) internal pure returns (uint64) {
if (x >= 1 << 64) _revertOverflow();
return uint64(x);
}
function toUint72(uint256 x) internal pure returns (uint72) {
if (x >= 1 << 72) _revertOverflow();
return uint72(x);
}
function toUint80(uint256 x) internal pure returns (uint80) {
if (x >= 1 << 80) _revertOverflow();
return uint80(x);
}
function toUint88(uint256 x) internal pure returns (uint88) {
if (x >= 1 << 88) _revertOverflow();
return uint88(x);
}
function toUint96(uint256 x) internal pure returns (uint96) {
if (x >= 1 << 96) _revertOverflow();
return uint96(x);
}
function toUint104(uint256 x) internal pure returns (uint104) {
if (x >= 1 << 104) _revertOverflow();
return uint104(x);
}
function toUint112(uint256 x) internal pure returns (uint112) {
if (x >= 1 << 112) _revertOverflow();
return uint112(x);
}
function toUint120(uint256 x) internal pure returns (uint120) {
if (x >= 1 << 120) _revertOverflow();
return uint120(x);
}
function toUint128(uint256 x) internal pure returns (uint128) {
if (x >= 1 << 128) _revertOverflow();
return uint128(x);
}
function toUint136(uint256 x) internal pure returns (uint136) {
if (x >= 1 << 136) _revertOverflow();
return uint136(x);
}
function toUint144(uint256 x) internal pure returns (uint144) {
if (x >= 1 << 144) _revertOverflow();
return uint144(x);
}
function toUint152(uint256 x) internal pure returns (uint152) {
if (x >= 1 << 152) _revertOverflow();
return uint152(x);
}
function toUint160(uint256 x) internal pure returns (uint160) {
if (x >= 1 << 160) _revertOverflow();
return uint160(x);
}
function toUint168(uint256 x) internal pure returns (uint168) {
if (x >= 1 << 168) _revertOverflow();
return uint168(x);
}
function toUint176(uint256 x) internal pure returns (uint176) {
if (x >= 1 << 176) _revertOverflow();
return uint176(x);
}
function toUint184(uint256 x) internal pure returns (uint184) {
if (x >= 1 << 184) _revertOverflow();
return uint184(x);
}
function toUint192(uint256 x) internal pure returns (uint192) {
if (x >= 1 << 192) _revertOverflow();
return uint192(x);
}
function toUint200(uint256 x) internal pure returns (uint200) {
if (x >= 1 << 200) _revertOverflow();
return uint200(x);
}
function toUint208(uint256 x) internal pure returns (uint208) {
if (x >= 1 << 208) _revertOverflow();
return uint208(x);
}
function toUint216(uint256 x) internal pure returns (uint216) {
if (x >= 1 << 216) _revertOverflow();
return uint216(x);
}
function toUint224(uint256 x) internal pure returns (uint224) {
if (x >= 1 << 224) _revertOverflow();
return uint224(x);
}
function toUint232(uint256 x) internal pure returns (uint232) {
if (x >= 1 << 232) _revertOverflow();
return uint232(x);
}
function toUint240(uint256 x) internal pure returns (uint240) {
if (x >= 1 << 240) _revertOverflow();
return uint240(x);
}
function toUint248(uint256 x) internal pure returns (uint248) {
if (x >= 1 << 248) _revertOverflow();
return uint248(x);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIGNED INTEGER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function toInt8(int256 x) internal pure returns (int8) {
int8 y = int8(x);
if (x != y) _revertOverflow();
return y;
}
function toInt16(int256 x) internal pure returns (int16) {
int16 y = int16(x);
if (x != y) _revertOverflow();
return y;
}
function toInt24(int256 x) internal pure returns (int24) {
int24 y = int24(x);
if (x != y) _revertOverflow();
return y;
}
function toInt32(int256 x) internal pure returns (int32) {
int32 y = int32(x);
if (x != y) _revertOverflow();
return y;
}
function toInt40(int256 x) internal pure returns (int40) {
int40 y = int40(x);
if (x != y) _revertOverflow();
return y;
}
function toInt48(int256 x) internal pure returns (int48) {
int48 y = int48(x);
if (x != y) _revertOverflow();
return y;
}
function toInt56(int256 x) internal pure returns (int56) {
int56 y = int56(x);
if (x != y) _revertOverflow();
return y;
}
function toInt64(int256 x) internal pure returns (int64) {
int64 y = int64(x);
if (x != y) _revertOverflow();
return y;
}
function toInt72(int256 x) internal pure returns (int72) {
int72 y = int72(x);
if (x != y) _revertOverflow();
return y;
}
function toInt80(int256 x) internal pure returns (int80) {
int80 y = int80(x);
if (x != y) _revertOverflow();
return y;
}
function toInt88(int256 x) internal pure returns (int88) {
int88 y = int88(x);
if (x != y) _revertOverflow();
return y;
}
function toInt96(int256 x) internal pure returns (int96) {
int96 y = int96(x);
if (x != y) _revertOverflow();
return y;
}
function toInt104(int256 x) internal pure returns (int104) {
int104 y = int104(x);
if (x != y) _revertOverflow();
return y;
}
function toInt112(int256 x) internal pure returns (int112) {
int112 y = int112(x);
if (x != y) _revertOverflow();
return y;
}
function toInt120(int256 x) internal pure returns (int120) {
int120 y = int120(x);
if (x != y) _revertOverflow();
return y;
}
function toInt128(int256 x) internal pure returns (int128) {
int128 y = int128(x);
if (x != y) _revertOverflow();
return y;
}
function toInt136(int256 x) internal pure returns (int136) {
int136 y = int136(x);
if (x != y) _revertOverflow();
return y;
}
function toInt144(int256 x) internal pure returns (int144) {
int144 y = int144(x);
if (x != y) _revertOverflow();
return y;
}
function toInt152(int256 x) internal pure returns (int152) {
int152 y = int152(x);
if (x != y) _revertOverflow();
return y;
}
function toInt160(int256 x) internal pure returns (int160) {
int160 y = int160(x);
if (x != y) _revertOverflow();
return y;
}
function toInt168(int256 x) internal pure returns (int168) {
int168 y = int168(x);
if (x != y) _revertOverflow();
return y;
}
function toInt176(int256 x) internal pure returns (int176) {
int176 y = int176(x);
if (x != y) _revertOverflow();
return y;
}
function toInt184(int256 x) internal pure returns (int184) {
int184 y = int184(x);
if (x != y) _revertOverflow();
return y;
}
function toInt192(int256 x) internal pure returns (int192) {
int192 y = int192(x);
if (x != y) _revertOverflow();
return y;
}
function toInt200(int256 x) internal pure returns (int200) {
int200 y = int200(x);
if (x != y) _revertOverflow();
return y;
}
function toInt208(int256 x) internal pure returns (int208) {
int208 y = int208(x);
if (x != y) _revertOverflow();
return y;
}
function toInt216(int256 x) internal pure returns (int216) {
int216 y = int216(x);
if (x != y) _revertOverflow();
return y;
}
function toInt224(int256 x) internal pure returns (int224) {
int224 y = int224(x);
if (x != y) _revertOverflow();
return y;
}
function toInt232(int256 x) internal pure returns (int232) {
int232 y = int232(x);
if (x != y) _revertOverflow();
return y;
}
function toInt240(int256 x) internal pure returns (int240) {
int240 y = int240(x);
if (x != y) _revertOverflow();
return y;
}
function toInt248(int256 x) internal pure returns (int248) {
int248 y = int248(x);
if (x != y) _revertOverflow();
return y;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* OTHER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function toInt256(uint256 x) internal pure returns (int256) {
if (x >= 1 << 255) _revertOverflow();
return int256(x);
}
function toUint256(int256 x) internal pure returns (uint256) {
if (x < 0) _revertOverflow();
return uint256(x);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function _revertOverflow() private pure {
/// @solidity memory-safe-assembly
assembly {
// Store the function selector of `Overflow()`.
mstore(0x00, 0x35278d12)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
}
}
node_modules/solady/src/utils/SignatureCheckerLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Signature verification helper that supports both ECDSA signatures from EOAs
/// and ERC1271 signatures from smart contract wallets like Argent and Gnosis safe.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SignatureCheckerLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/SignatureChecker.sol)
///
/// @dev Note:
/// - The signature checking functions use the ecrecover precompile (0x1).
/// - The `bytes memory signature` variants use the identity precompile (0x4)
/// to copy memory internally.
/// - Unlike ECDSA signatures, contract signatures are revocable.
/// - As of Solady version 0.0.134, all `bytes signature` variants accept both
/// regular 65-byte `(r, s, v)` and EIP-2098 `(r, vs)` short form signatures.
/// See: https://eips.ethereum.org/EIPS/eip-2098
/// This is for calldata efficiency on smart accounts prevalent on L2s.
///
/// WARNING! Do NOT use signatures as unique identifiers:
/// - Use a nonce in the digest to prevent replay attacks on the same contract.
/// - Use EIP-712 for the digest to prevent replay attacks across different chains and contracts.
/// EIP-712 also enables readable signing of typed data for better user safety.
/// This implementation does NOT check if a signature is non-malleable.
library SignatureCheckerLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIGNATURE CHECKING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether `signature` is valid for `signer` and `hash`.
/// If `signer` is a smart contract, the signature is validated with ERC1271.
/// Otherwise, the signature is validated with `ECDSA.recover`.
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits of `signer` in case they are dirty.
for { signer := shr(96, shl(96, signer)) } signer {} {
let m := mload(0x40)
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
if eq(mload(signature), 64) {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
let t :=
staticcall(
gas(), // Amount of gas left for the transaction.
1, // Address of `ecrecover`.
0x00, // Start of input.
0x80, // Size of input.
0x01, // Start of output.
0x20 // Size of output.
)
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if iszero(or(iszero(returndatasize()), xor(signer, mload(t)))) {
isValid := 1
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
if eq(mload(signature), 65) {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
let t :=
staticcall(
gas(), // Amount of gas left for the transaction.
1, // Address of `ecrecover`.
0x00, // Start of input.
0x80, // Size of input.
0x01, // Start of output.
0x20 // Size of output.
)
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if iszero(or(iszero(returndatasize()), xor(signer, mload(t)))) {
isValid := 1
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
// Copy the `signature` over.
let n := add(0x20, mload(signature))
pop(staticcall(gas(), 4, signature, n, add(m, 0x44), n))
// forgefmt: disable-next-item
isValid := and(
// Whether the returndata is the magic value `0x1626ba7e` (left-aligned).
eq(mload(d), f),
// Whether the staticcall does not revert.
// This must be placed at the end of the `and` clause,
// as the arguments are evaluated from right to left.
staticcall(
gas(), // Remaining gas.
signer, // The `signer` address.
m, // Offset of calldata in memory.
add(returndatasize(), 0x44), // Length of calldata in memory.
d, // Offset of returndata.
0x20 // Length of returndata to write.
)
)
break
}
}
}
/// @dev Returns whether `signature` is valid for `signer` and `hash`.
/// If `signer` is a smart contract, the signature is validated with ERC1271.
/// Otherwise, the signature is validated with `ECDSA.recover`.
function isValidSignatureNowCalldata(address signer, bytes32 hash, bytes calldata signature)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits of `signer` in case they are dirty.
for { signer := shr(96, shl(96, signer)) } signer {} {
let m := mload(0x40)
mstore(0x00, hash)
if eq(signature.length, 64) {
let vs := calldataload(add(signature.offset, 0x20))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, calldataload(signature.offset)) // `r`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
let t :=
staticcall(
gas(), // Amount of gas left for the transaction.
1, // Address of `ecrecover`.
0x00, // Start of input.
0x80, // Size of input.
0x01, // Start of output.
0x20 // Size of output.
)
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if iszero(or(iszero(returndatasize()), xor(signer, mload(t)))) {
isValid := 1
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
if eq(signature.length, 65) {
mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) // `v`.
calldatacopy(0x40, signature.offset, 0x40) // `r`, `s`.
let t :=
staticcall(
gas(), // Amount of gas left for the transaction.
1, // Address of `ecrecover`.
0x00, // Start of input.
0x80, // Size of input.
0x01, // Start of output.
0x20 // Size of output.
)
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if iszero(or(iszero(returndatasize()), xor(signer, mload(t)))) {
isValid := 1
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), signature.length)
// Copy the `signature` over.
calldatacopy(add(m, 0x64), signature.offset, signature.length)
// forgefmt: disable-next-item
isValid := and(
// Whether the returndata is the magic value `0x1626ba7e` (left-aligned).
eq(mload(d), f),
// Whether the staticcall does not revert.
// This must be placed at the end of the `and` clause,
// as the arguments are evaluated from right to left.
staticcall(
gas(), // Remaining gas.
signer, // The `signer` address.
m, // Offset of calldata in memory.
add(signature.length, 0x64), // Length of calldata in memory.
d, // Offset of returndata.
0x20 // Length of returndata to write.
)
)
break
}
}
}
/// @dev Returns whether the signature (`r`, `vs`) is valid for `signer` and `hash`.
/// If `signer` is a smart contract, the signature is validated with ERC1271.
/// Otherwise, the signature is validated with `ECDSA.recover`.
function isValidSignatureNow(address signer, bytes32 hash, bytes32 r, bytes32 vs)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits of `signer` in case they are dirty.
for { signer := shr(96, shl(96, signer)) } signer {} {
let m := mload(0x40)
mstore(0x00, hash)
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, r) // `r`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
let t :=
staticcall(
gas(), // Amount of gas left for the transaction.
1, // Address of `ecrecover`.
0x00, // Start of input.
0x80, // Size of input.
0x01, // Start of output.
0x20 // Size of output.
)
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if iszero(or(iszero(returndatasize()), xor(signer, mload(t)))) {
isValid := 1
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Length of the signature.
mstore(add(m, 0x64), r) // `r`.
mstore(add(m, 0x84), mload(0x60)) // `s`.
mstore8(add(m, 0xa4), mload(0x20)) // `v`.
// forgefmt: disable-next-item
isValid := and(
// Whether the returndata is the magic value `0x1626ba7e` (left-aligned).
eq(mload(d), f),
// Whether the staticcall does not revert.
// This must be placed at the end of the `and` clause,
// as the arguments are evaluated from right to left.
staticcall(
gas(), // Remaining gas.
signer, // The `signer` address.
m, // Offset of calldata in memory.
0xa5, // Length of calldata in memory.
d, // Offset of returndata.
0x20 // Length of returndata to write.
)
)
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/// @dev Returns whether the signature (`v`, `r`, `s`) is valid for `signer` and `hash`.
/// If `signer` is a smart contract, the signature is validated with ERC1271.
/// Otherwise, the signature is validated with `ECDSA.recover`.
function isValidSignatureNow(address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits of `signer` in case they are dirty.
for { signer := shr(96, shl(96, signer)) } signer {} {
let m := mload(0x40)
mstore(0x00, hash)
mstore(0x20, and(v, 0xff)) // `v`.
mstore(0x40, r) // `r`.
mstore(0x60, s) // `s`.
let t :=
staticcall(
gas(), // Amount of gas left for the transaction.
1, // Address of `ecrecover`.
0x00, // Start of input.
0x80, // Size of input.
0x01, // Start of output.
0x20 // Size of output.
)
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if iszero(or(iszero(returndatasize()), xor(signer, mload(t)))) {
isValid := 1
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Length of the signature.
mstore(add(m, 0x64), r) // `r`.
mstore(add(m, 0x84), s) // `s`.
mstore8(add(m, 0xa4), v) // `v`.
// forgefmt: disable-next-item
isValid := and(
// Whether the returndata is the magic value `0x1626ba7e` (left-aligned).
eq(mload(d), f),
// Whether the staticcall does not revert.
// This must be placed at the end of the `and` clause,
// as the arguments are evaluated from right to left.
staticcall(
gas(), // Remaining gas.
signer, // The `signer` address.
m, // Offset of calldata in memory.
0xa5, // Length of calldata in memory.
d, // Offset of returndata.
0x20 // Length of returndata to write.
)
)
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC1271 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether `signature` is valid for `hash` for an ERC1271 `signer` contract.
function isValidERC1271SignatureNow(address signer, bytes32 hash, bytes memory signature)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
// Copy the `signature` over.
let n := add(0x20, mload(signature))
pop(staticcall(gas(), 4, signature, n, add(m, 0x44), n))
// forgefmt: disable-next-item
isValid := and(
// Whether the returndata is the magic value `0x1626ba7e` (left-aligned).
eq(mload(d), f),
// Whether the staticcall does not revert.
// This must be placed at the end of the `and` clause,
// as the arguments are evaluated from right to left.
staticcall(
gas(), // Remaining gas.
signer, // The `signer` address.
m, // Offset of calldata in memory.
add(returndatasize(), 0x44), // Length of calldata in memory.
d, // Offset of returndata.
0x20 // Length of returndata to write.
)
)
}
}
/// @dev Returns whether `signature` is valid for `hash` for an ERC1271 `signer` contract.
function isValidERC1271SignatureNowCalldata(
address signer,
bytes32 hash,
bytes calldata signature
) internal view returns (bool isValid) {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), signature.length)
// Copy the `signature` over.
calldatacopy(add(m, 0x64), signature.offset, signature.length)
// forgefmt: disable-next-item
isValid := and(
// Whether the returndata is the magic value `0x1626ba7e` (left-aligned).
eq(mload(d), f),
// Whether the staticcall does not revert.
// This must be placed at the end of the `and` clause,
// as the arguments are evaluated from right to left.
staticcall(
gas(), // Remaining gas.
signer, // The `signer` address.
m, // Offset of calldata in memory.
add(signature.length, 0x64), // Length of calldata in memory.
d, // Offset of returndata.
0x20 // Length of returndata to write.
)
)
}
}
/// @dev Returns whether the signature (`r`, `vs`) is valid for `hash`
/// for an ERC1271 `signer` contract.
function isValidERC1271SignatureNow(address signer, bytes32 hash, bytes32 r, bytes32 vs)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Length of the signature.
mstore(add(m, 0x64), r) // `r`.
mstore(add(m, 0x84), shr(1, shl(1, vs))) // `s`.
mstore8(add(m, 0xa4), add(shr(255, vs), 27)) // `v`.
// forgefmt: disable-next-item
isValid := and(
// Whether the returndata is the magic value `0x1626ba7e` (left-aligned).
eq(mload(d), f),
// Whether the staticcall does not revert.
// This must be placed at the end of the `and` clause,
// as the arguments are evaluated from right to left.
staticcall(
gas(), // Remaining gas.
signer, // The `signer` address.
m, // Offset of calldata in memory.
0xa5, // Length of calldata in memory.
d, // Offset of returndata.
0x20 // Length of returndata to write.
)
)
}
}
/// @dev Returns whether the signature (`v`, `r`, `s`) is valid for `hash`
/// for an ERC1271 `signer` contract.
function isValidERC1271SignatureNow(address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Length of the signature.
mstore(add(m, 0x64), r) // `r`.
mstore(add(m, 0x84), s) // `s`.
mstore8(add(m, 0xa4), v) // `v`.
// forgefmt: disable-next-item
isValid := and(
// Whether the returndata is the magic value `0x1626ba7e` (left-aligned).
eq(mload(d), f),
// Whether the staticcall does not revert.
// This must be placed at the end of the `and` clause,
// as the arguments are evaluated from right to left.
staticcall(
gas(), // Remaining gas.
signer, // The `signer` address.
m, // Offset of calldata in memory.
0xa5, // Length of calldata in memory.
d, // Offset of returndata.
0x20 // Length of returndata to write.
)
)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HASHING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an Ethereum Signed Message, created from a `hash`.
/// This produces a hash corresponding to the one signed with the
/// [`eth_sign`](https://eth.wiki/json-rpc/API#eth_sign)
/// JSON-RPC method as part of EIP-191.
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, hash) // Store into scratch space for keccak256.
mstore(0x00, "\x00\x00\x00\x00\x19Ethereum Signed Message:\n32") // 28 bytes.
result := keccak256(0x04, 0x3c) // `32 * 2 - (32 - 28) = 60 = 0x3c`.
}
}
/// @dev Returns an Ethereum Signed Message, created from `s`.
/// This produces a hash corresponding to the one signed with the
/// [`eth_sign`](https://eth.wiki/json-rpc/API#eth_sign)
/// JSON-RPC method as part of EIP-191.
/// Note: Supports lengths of `s` up to 999999 bytes.
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let sLength := mload(s)
let o := 0x20
mstore(o, "\x19Ethereum Signed Message:\n") // 26 bytes, zero-right-padded.
mstore(0x00, 0x00)
// Convert the `s.length` to ASCII decimal representation: `base10(s.length)`.
for { let temp := sLength } 1 {} {
o := sub(o, 1)
mstore8(o, add(48, mod(temp, 10)))
temp := div(temp, 10)
if iszero(temp) { break }
}
let n := sub(0x3a, o) // Header length: `26 + 32 - o`.
// Throw an out-of-offset error (consumes all gas) if the header exceeds 32 bytes.
returndatacopy(returndatasize(), returndatasize(), gt(n, 0x20))
mstore(s, or(mload(0x00), mload(n))) // Temporarily store the header.
result := keccak256(add(s, sub(0x20, n)), add(n, sLength))
mstore(s, sLength) // Restore the length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EMPTY CALLDATA HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an empty calldata bytes.
function emptySignature() internal pure returns (bytes calldata signature) {
/// @solidity memory-safe-assembly
assembly {
signature.length := 0
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 100000000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"stable-swap/=lib/stable-swap-dev/src/",
"forge-std/=lib/forge-std/src/",
"agora-std/=lib/agora-standard-solidity/src/",
"createx/=node_modules/createx/src/",
"@interfaces/=src/interfaces/",
"@utils/=src/sol-utils/",
"@swap-actions/=src/actions/stable-swap/",
"@testnet-actions/=src/actions/testnet/",
"@check-actions/=src/actions/check/",
"agora-dollar/=node_modules/agora-dollar-dev/src/",
"solady/=node_modules/solady/",
"agora-contracts/=node_modules/agora-contracts/src/contracts/",
"@chainlink/=lib/agora-standard-solidity/node_modules/@chainlink/",
"@eth-optimism/=lib/agora-standard-solidity/node_modules/@eth-optimism/",
"@layerzerolabs/=lib/layerzero-dev/node_modules/@layerzerolabs/",
"@openzeppelin/=node_modules/@openzeppelin/",
"agora-contracts-old/=node_modules/agora-contracts-old/",
"agora-dollar-dev/=node_modules/agora-dollar-dev/",
"agora-dollar-evm-dev/=lib/agora-dollar-evm-dev/src/",
"agora-standard-solidity/=lib/agora-standard-solidity/src/",
"agora-whitelist/=lib/arbitrage-bot/node_modules/agora-whitelist/src/contracts/",
"arbitrage-bot/=lib/arbitrage-bot/src/",
"contracts/=node_modules/agora-dollar-dev/src/contracts/",
"ds-test/=node_modules/ds-test/",
"hardhat-deploy/=lib/layerzero-dev/node_modules/hardhat-deploy/",
"hardhat/=lib/layerzero-dev/node_modules/hardhat/",
"interfaces/=lib/arbitrage-bot/src/interfaces/",
"layerzero-dev/=lib/layerzero-dev/contracts/",
"openzeppelin/=node_modules/createx/lib/openzeppelin-contracts/contracts/",
"script/=node_modules/agora-dollar-dev/src/script/",
"solidity-bytes-utils/=lib/agora-standard-solidity/node_modules/solidity-bytes-utils/",
"stable-swap-dev/=lib/stable-swap-dev/src/",
"test/=node_modules/agora-dollar-dev/src/test/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.