Description:
Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"contracts/NEBASaleV3_Staged.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./interfaces/IVestingEscrow.sol";
/**
* @title NEBA Token Sale V3 - Stage-Based with Vesting + ETH Support
* @notice Production-parity staged token sale with vesting integration
* @dev Multi-stage sale with different prices, caps, and vesting schedules
*
* Key Features:
* - 6 distinct sale stages (Seed, Community, Strategic, KOL, Public, Liquidity)
* - ETH + USDC + USDT payment methods
* - $25 USD minimum purchase (validated off-chain)
* - NO maximum per wallet/transaction
* - Stage-specific vesting schedules
* - Integration with VestingEscrow contract
* - EIP-712 signature-based purchases with paymentMethod field
*/
contract NEBASaleV3 is AccessControl, ReentrancyGuard, Pausable, EIP712 {
using SafeERC20 for IERC20;
// =============================================================
// ROLES
// =============================================================
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE");
bytes32 public constant OPERATIONS_ROLE = keccak256("OPERATIONS_ROLE");
bytes32 public constant SIGNER_ROLE = keccak256("SIGNER_ROLE");
// =============================================================
// CONSTANTS
// =============================================================
/// @notice Minimum purchase amount in USD (6 decimals) - validated off-chain
uint256 public constant MIN_USD_AMOUNT = 25 * 1e6; // $25
/// @notice USDC/USDT decimals
uint256 public constant STABLECOIN_DECIMALS = 6;
/// @notice NEBA token decimals
uint256 public constant NEBA_DECIMALS = 18;
/// @notice ETH address constant (zero address represents native ETH)
address public constant ETH_ADDRESS = address(0);
// =============================================================
// SALE STAGES
// =============================================================
enum Stage {
Seed, // 0: Off-chain/SAFT - buyEnabled = false
Community, // 1: Fjord - buyEnabled = false
Strategic, // 2: Private sale - buyEnabled = true
KOL, // 3: KOL sale - buyEnabled = true/optional
Public, // 4: Launchpads - buyEnabled = false
Liquidity // 5: LP @ TGE - out of Sales scope
}
struct StageConfig {
uint256 cap; // Total NEBA tokens available for this stage (18 decimals)
uint256 priceUSD; // Price per NEBA in USD (6 decimals)
uint256 sold; // Total NEBA tokens sold in this stage (18 decimals)
bool buyEnabled; // Whether direct purchases are enabled
uint256 tgeUnlockBps; // TGE unlock percentage in basis points (10000 = 100%)
uint256 cliffMonths; // Cliff period in months
uint256 vestingMonths; // Linear vesting period in months
bool dailyUnlock; // True for daily unlock, false for monthly
}
// =============================================================
// STATE VARIABLES
// =============================================================
/// @notice NEBA token contract
IERC20 public immutable nebaToken;
/// @notice Treasury address (receives stablecoins and ETH)
address public immutable treasury;
/// @notice VestingEscrow contract (receives vested tokens)
address public vestingEscrow;
/// @notice USDC token address
IERC20 public immutable usdc;
/// @notice USDT token address
IERC20 public immutable usdt;
/// @notice Stage configurations
mapping(Stage => StageConfig) public stages;
/// @notice Total tokens purchased by user in a specific stage
mapping(address => mapping(Stage => uint256)) public userPurchases;
/// @notice Total purchases across all stages by user
mapping(address => uint256) public totalUserPurchases;
/// @notice Total number of purchase transactions
uint256 public totalPurchaseCount;
/// @notice Nonce for signature replay protection
mapping(address => uint256) public nonces;
/// @notice Used nonces to prevent replay attacks
mapping(address => mapping(uint256 => bool)) public usedNonces;
/// @notice Maximum purchase amount per transaction (0 = no limit)
uint256 public maxPurchasePerTx;
/// @notice Minimum NEBA purchase amount (in NEBA tokens, 18 decimals)
uint256 public minPurchaseAmount;
// =============================================================
// EVENTS
// =============================================================
event TokensPurchased(
address indexed buyer,
Stage indexed stage,
string paymentMethod,
uint256 amountPaid,
uint256 nebaAmount,
uint256 timestamp
);
event StageConfigured(
Stage indexed stage,
uint256 cap,
uint256 priceUSD,
bool buyEnabled
);
event StageBuyStatusChanged(Stage indexed stage, bool buyEnabled);
event VestingEscrowUpdated(address indexed oldEscrow, address indexed newEscrow);
event EmergencyWithdrawal(address indexed token, address indexed to, uint256 amount);
// =============================================================
// ERRORS
// =============================================================
error ZeroAddressNotAllowed();
error ZeroAmountNotAllowed();
error InvalidStage();
error StageBuyingDisabled();
error StageSoldOut();
error BelowMinimumPurchase();
error InsufficientStageAllocation();
error InvalidSignature();
error SignatureExpired();
error InvalidPaymentMethod();
error InsufficientETHSent();
error VestingEscrowNotSet();
error InvalidAmountForPaymentMethod();
error NonceAlreadyUsed();
error InsufficientBalance();
error ExceedsMaxPurchasePerTx();
error BelowMinPurchaseAmount();
// =============================================================
// EIP-712 TYPES
// =============================================================
bytes32 private constant PURCHASE_TYPEHASH = keccak256(
"Purchase(address buyer,uint8 stage,string paymentMethod,uint256 amount,uint256 nebaAmount,uint256 nonce,uint256 deadline)"
);
// =============================================================
// CONSTRUCTOR
// =============================================================
constructor(
address _nebaToken,
address _treasury,
address _usdc,
address _usdt,
address _signer,
address _governanceSafe,
address _operationsSafe
) EIP712("NEBA Sale", "1") {
if (_nebaToken == address(0)) revert ZeroAddressNotAllowed();
if (_treasury == address(0)) revert ZeroAddressNotAllowed();
if (_usdc == address(0)) revert ZeroAddressNotAllowed();
if (_usdt == address(0)) revert ZeroAddressNotAllowed();
if (_signer == address(0)) revert ZeroAddressNotAllowed();
if (_governanceSafe == address(0)) revert ZeroAddressNotAllowed();
if (_operationsSafe == address(0)) revert ZeroAddressNotAllowed();
nebaToken = IERC20(_nebaToken);
treasury = _treasury;
usdc = IERC20(_usdc);
usdt = IERC20(_usdt);
// Grant roles
_grantRole(DEFAULT_ADMIN_ROLE, _governanceSafe);
_grantRole(GOVERNANCE_ROLE, _governanceSafe);
_grantRole(OPERATIONS_ROLE, _operationsSafe);
_grantRole(SIGNER_ROLE, _signer);
// Initialize stage configurations
_initializeStages();
}
// =============================================================
// STAGE INITIALIZATION
// =============================================================
/**
* @dev Initializes all sale stages with production parameters
*/
function _initializeStages() private {
// Seed: 100M NEBA @ $0.008 — OFF-CHAIN/SAFT
// Vesting: 5% @TGE / 6m cliff / 24m linear
stages[Stage.Seed] = StageConfig({
cap: 100_000_000 ether,
priceUSD: 8000, // $0.008 = 0.008 * 1,000,000 = 8,000 (6 decimals)
sold: 0,
buyEnabled: false,
tgeUnlockBps: 500, // 5%
cliffMonths: 6,
vestingMonths: 24,
dailyUnlock: false
});
// Community: 25M NEBA @ $0.010 — FJORD
// Vesting: 10% @TGE / 1m cliff / 12m daily
stages[Stage.Community] = StageConfig({
cap: 25_000_000 ether,
priceUSD: 10000, // $0.010 = 0.010 * 1,000,000 = 10,000 (6 decimals)
sold: 0,
buyEnabled: false,
tgeUnlockBps: 1000, // 10%
cliffMonths: 1,
vestingMonths: 12,
dailyUnlock: true
});
// Strategic/Private: 100M NEBA @ $0.012 — ACTIVE
// Vesting: 12.5% @TGE / 3m cliff / 6m linear
stages[Stage.Strategic] = StageConfig({
cap: 100_000_000 ether,
priceUSD: 12000, // $0.012 = 0.012 * 1,000,000 = 12,000 (6 decimals)
sold: 0,
buyEnabled: true,
tgeUnlockBps: 1250, // 12.5%
cliffMonths: 3,
vestingMonths: 6,
dailyUnlock: false
});
// KOL: 20M NEBA @ $0.015 — OPTIONAL
// Vesting: 20% @TGE / 3m cliff / 12m linear
stages[Stage.KOL] = StageConfig({
cap: 20_000_000 ether,
priceUSD: 15000, // $0.015 = 0.015 * 1,000,000 = 15,000 (6 decimals)
sold: 0,
buyEnabled: true,
tgeUnlockBps: 2000, // 20%
cliffMonths: 3,
vestingMonths: 12,
dailyUnlock: false
});
// Public: 20M NEBA @ $0.020 — LAUNCHPADS
// Vesting: 20% @TGE / 0m cliff / 6m linear
stages[Stage.Public] = StageConfig({
cap: 20_000_000 ether,
priceUSD: 20000, // $0.020 = 0.020 * 1,000,000 = 20,000 (6 decimals)
sold: 0,
buyEnabled: false,
tgeUnlockBps: 2000, // 20%
cliffMonths: 0,
vestingMonths: 6,
dailyUnlock: false
});
// Liquidity: 75M NEBA @ $0.24 — OUT OF SALES SCOPE (LP @ TGE)
stages[Stage.Liquidity] = StageConfig({
cap: 75_000_000 ether,
priceUSD: 240000, // $0.24 = 0.24 * 1,000,000 = 240,000 (6 decimals)
sold: 0,
buyEnabled: false,
tgeUnlockBps: 10000, // 100% (immediate liquidity)
cliffMonths: 0,
vestingMonths: 0,
dailyUnlock: false
});
}
// =============================================================
// PURCHASE FUNCTIONS
// =============================================================
/**
* @notice Purchase NEBA tokens with backend signature
* @dev Supports ETH, USDC, and USDT payments
* @param stage Sale stage to purchase from
* @param paymentMethod "ETH", "USDC", or "USDT"
* @param amount For ETH: wei amount (18 decimals), For USDC/USDT: USD amount (6 decimals)
* @param nebaAmount Exact NEBA tokens to receive (signed by backend)
* @param deadline Signature expiration timestamp
* @param signature Backend signature
*/
function buyTokens(
Stage stage,
string calldata paymentMethod,
uint256 amount,
uint256 nebaAmount,
uint256 deadline,
bytes calldata signature
) external payable nonReentrant whenNotPaused {
if (amount == 0) revert ZeroAmountNotAllowed();
if (block.timestamp > deadline) revert SignatureExpired();
// Verify stage exists and buying is enabled
if (uint8(stage) > uint8(Stage.Liquidity)) revert InvalidStage();
StageConfig storage stageConfig = stages[stage];
if (!stageConfig.buyEnabled) revert StageBuyingDisabled();
// Get current nonce for signature verification
uint256 currentNonce = nonces[msg.sender];
// Check if nonce has already been used (replay protection)
if (usedNonces[msg.sender][currentNonce]) revert NonceAlreadyUsed();
// Verify signature (includes paymentMethod, amount, and nebaAmount)
bytes32 structHash = keccak256(
abi.encode(
PURCHASE_TYPEHASH,
msg.sender,
uint8(stage),
keccak256(bytes(paymentMethod)),
amount,
nebaAmount,
currentNonce,
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, signature);
if (!hasRole(SIGNER_ROLE, signer)) revert InvalidSignature();
// Mark nonce as used BEFORE state changes (replay protection)
usedNonces[msg.sender][currentNonce] = true;
nonces[msg.sender]++;
// Backend has already validated:
// - $25 USD minimum
// - Correct nebaAmount calculation
// - Geo-blocking
// - KYC (email, firstName, lastName)
// Validate nebaAmount is not zero
if (nebaAmount == 0) revert ZeroAmountNotAllowed();
// Check minimum purchase amount (if set)
if (minPurchaseAmount > 0 && nebaAmount < minPurchaseAmount) {
revert BelowMinPurchaseAmount();
}
// Check maximum purchase per transaction (if set)
if (maxPurchasePerTx > 0 && nebaAmount > maxPurchasePerTx) {
revert ExceedsMaxPurchasePerTx();
}
// Check stage allocation BEFORE payment processing
if (stageConfig.sold + nebaAmount > stageConfig.cap) {
revert InsufficientStageAllocation();
}
// Process payment based on method
bytes32 methodHash = keccak256(bytes(paymentMethod));
if (methodHash == keccak256("ETH")) {
// ETH payment: amount = wei amount, msg.value must match
if (msg.value != amount) revert InsufficientETHSent();
// Pre-flight check: verify buyer sent enough ETH
if (msg.sender.balance < amount) revert InsufficientBalance();
// Transfer ETH to treasury
(bool success, ) = treasury.call{value: msg.value}("");
require(success, "ETH transfer failed");
} else if (methodHash == keccak256("USDC")) {
// USDC payment: amount = USD amount (6 decimals)
if (msg.value != 0) revert InvalidAmountForPaymentMethod();
// Pre-flight check: verify buyer has enough USDC
if (usdc.balanceOf(msg.sender) < amount) revert InsufficientBalance();
// Pre-flight check: verify buyer approved enough USDC
if (usdc.allowance(msg.sender, address(this)) < amount) revert InsufficientBalance();
// Transfer USDC from buyer to treasury
usdc.safeTransferFrom(msg.sender, treasury, amount);
} else if (methodHash == keccak256("USDT")) {
// USDT payment: amount = USD amount (6 decimals)
if (msg.value != 0) revert InvalidAmountForPaymentMethod();
// Pre-flight check: verify buyer has enough USDT
if (usdt.balanceOf(msg.sender) < amount) revert InsufficientBalance();
// Pre-flight check: verify buyer approved enough USDT
if (usdt.allowance(msg.sender, address(this)) < amount) revert InsufficientBalance();
// Transfer USDT from buyer to treasury
usdt.safeTransferFrom(msg.sender, treasury, amount);
} else {
revert InvalidPaymentMethod();
}
// Update state (BEFORE token transfers for CEI pattern)
stageConfig.sold += nebaAmount;
userPurchases[msg.sender][stage] += nebaAmount;
totalUserPurchases[msg.sender] += nebaAmount;
totalPurchaseCount++;
// Transfer NEBA tokens to VestingEscrow or buyer
if (stageConfig.vestingMonths > 0) {
// Vesting required - ensure VestingEscrow is configured
if (vestingEscrow == address(0)) revert VestingEscrowNotSet();
// Transfer tokens to vesting escrow
nebaToken.safeTransferFrom(treasury, vestingEscrow, nebaAmount);
// Create vesting schedule immediately
IVestingEscrow(vestingEscrow).createVestingSchedule(
msg.sender,
nebaAmount,
stageConfig.tgeUnlockBps,
stageConfig.cliffMonths,
stageConfig.vestingMonths,
stageConfig.dailyUnlock
);
} else {
// Direct transfer (100% TGE unlock or no vesting)
nebaToken.safeTransferFrom(treasury, msg.sender, nebaAmount);
}
emit TokensPurchased(
msg.sender,
stage,
paymentMethod,
amount,
nebaAmount,
block.timestamp
);
}
/**
* @notice Receive ETH for direct purchases
* @dev Must use buyTokens() with signature - direct ETH sends will revert
*/
receive() external payable {
// Reject direct ETH sends without buyTokens() call
revert("Use buyTokens() function");
}
// =============================================================
// GOVERNANCE FUNCTIONS
// =============================================================
/**
* @notice Configure a sale stage
* @param stage Stage to configure
* @param cap New token cap (18 decimals)
* @param priceUSD New price in USD (6 decimals)
* @param buyEnabled Whether buying is enabled
*/
function configureStage(
Stage stage,
uint256 cap,
uint256 priceUSD,
bool buyEnabled,
uint256 tgeUnlockBps,
uint256 cliffMonths,
uint256 vestingMonths,
bool dailyUnlock
) external onlyRole(GOVERNANCE_ROLE) {
if (uint8(stage) > uint8(Stage.Liquidity)) revert InvalidStage();
StageConfig storage stageConfig = stages[stage];
stageConfig.cap = cap;
stageConfig.priceUSD = priceUSD;
stageConfig.buyEnabled = buyEnabled;
stageConfig.tgeUnlockBps = tgeUnlockBps;
stageConfig.cliffMonths = cliffMonths;
stageConfig.vestingMonths = vestingMonths;
stageConfig.dailyUnlock = dailyUnlock;
emit StageConfigured(stage, cap, priceUSD, buyEnabled);
}
/**
* @notice Enable or disable buying for a stage
* @param stage Stage to modify
* @param enabled New buy status
*/
function setStageBuyStatus(
Stage stage,
bool enabled
) external onlyRole(OPERATIONS_ROLE) {
if (uint8(stage) > uint8(Stage.Liquidity)) revert InvalidStage();
stages[stage].buyEnabled = enabled;
emit StageBuyStatusChanged(stage, enabled);
}
/**
* @notice Set the VestingEscrow contract address
* @param _vestingEscrow Address of VestingEscrow contract
*/
function setVestingEscrow(address _vestingEscrow) external onlyRole(GOVERNANCE_ROLE) {
if (_vestingEscrow == address(0)) revert ZeroAddressNotAllowed();
// Verify it's a contract (not EOA)
uint256 codeSize;
assembly {
codeSize := extcodesize(_vestingEscrow)
}
require(codeSize > 0, "VestingEscrow must be a contract");
address oldEscrow = vestingEscrow;
vestingEscrow = _vestingEscrow;
emit VestingEscrowUpdated(oldEscrow, _vestingEscrow);
}
/**
* @notice Set maximum purchase amount per transaction
* @param _maxPurchase Maximum NEBA amount (18 decimals), 0 = no limit
*/
function setMaxPurchasePerTx(uint256 _maxPurchase) external onlyRole(GOVERNANCE_ROLE) {
maxPurchasePerTx = _maxPurchase;
}
/**
* @notice Set minimum purchase amount
* @param _minPurchase Minimum NEBA amount (18 decimals), 0 = no limit
*/
function setMinPurchaseAmount(uint256 _minPurchase) external onlyRole(GOVERNANCE_ROLE) {
minPurchaseAmount = _minPurchase;
}
/**
* @notice Pause the contract
*/
function pause() external onlyRole(OPERATIONS_ROLE) {
_pause();
}
/**
* @notice Unpause the contract
*/
function unpause() external onlyRole(GOVERNANCE_ROLE) {
_unpause();
}
/**
* @notice Emergency withdrawal of tokens or ETH
* @param token Token address (address(0) for ETH)
* @param to Recipient address
* @param amount Amount to withdraw
*/
function emergencyWithdraw(
address token,
address to,
uint256 amount
) external onlyRole(GOVERNANCE_ROLE) {
if (to == address(0)) revert ZeroAddressNotAllowed();
if (amount == 0) revert ZeroAmountNotAllowed();
if (token == address(0)) {
// Withdraw ETH
(bool success, ) = to.call{value: amount}("");
require(success, "ETH transfer failed");
} else {
IERC20(token).safeTransfer(to, amount);
}
emit EmergencyWithdrawal(token, to, amount);
}
// =============================================================
// VIEW FUNCTIONS
// =============================================================
/**
* @notice Get stage configuration
* @param stage Stage to query
* @return StageConfig struct
*/
function getStageConfig(Stage stage) external view returns (StageConfig memory) {
return stages[stage];
}
/**
* @notice Get remaining tokens available in a stage
* @param stage Stage to query
* @return Remaining tokens (18 decimals)
*/
function getStageRemaining(Stage stage) external view returns (uint256) {
StageConfig storage stageConfig = stages[stage];
return stageConfig.cap - stageConfig.sold;
}
/**
* @notice Calculate NEBA amount for a given USD amount
* @param stage Stage to calculate for
* @param amountUSD USD amount (6 decimals)
* @return NEBA amount (18 decimals)
*/
function calculateNebaAmount(
Stage stage,
uint256 amountUSD
) external view returns (uint256) {
StageConfig storage stageConfig = stages[stage];
return (amountUSD * 10**NEBA_DECIMALS) / stageConfig.priceUSD;
}
/**
* @notice Get user's purchase info for a specific stage
* @param user User address
* @param stage Stage to query
* @return Amount of NEBA purchased in this stage
*/
function getUserPurchaseInStage(
address user,
Stage stage
) external view returns (uint256) {
return userPurchases[user][stage];
}
/**
* @notice Get total NEBA sold across all stages
* @return Total NEBA sold (18 decimals)
*/
function getTotalSold() external view returns (uint256) {
uint256 total = 0;
for (uint8 i = 0; i <= uint8(Stage.Liquidity); i++) {
total += stages[Stage(i)].sold;
}
return total;
}
/**
* @notice Check if a stage is sold out
* @param stage Stage to check
* @return True if sold out
*/
function isStageSoldOut(Stage stage) external view returns (bool) {
StageConfig storage stageConfig = stages[stage];
return stageConfig.sold >= stageConfig.cap;
}
/**
* @notice Get minimum NEBA purchase amount for a stage
* @param stage Stage to calculate for
* @return Minimum NEBA amount (18 decimals)
*/
function getMinimumNebaForStage(Stage stage) external view returns (uint256) {
StageConfig storage stageConfig = stages[stage];
return (MIN_USD_AMOUNT * 10**NEBA_DECIMALS) / stageConfig.priceUSD;
}
/**
* @notice Get EIP-712 domain separator
* @return Domain separator hash
*/
function getDomainSeparator() external view returns (bytes32) {
return _domainSeparatorV4();
}
}
"
},
"node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
"
},
"node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
"
},
"node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
"
},
"node_modules/@openzeppelin/contracts/utils/Pausable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
"
},
"node_modules/@openzeppelin/contracts/access/AccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
"
},
"node_modules/@openzeppelin/contracts/utils/cryptography/EIP712.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.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].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable
*/
abstract contract EIP712 is IERC5267 {
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;
// slither-disable-next-line constable-states
string private _nameFallback;
// slither-disable-next-line constable-states
string private _versionFallback;
/**
* @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.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis = address(this);
}
/**
* @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 virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/// @inheritdoc IERC5267
function eip712Domain()
public
view
virtual
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)
);
}
/**
* @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.toStringWithFallback(_nameFallback);
}
/**
* @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.toStringWithFallback(_versionFallback);
}
}
"
},
"node_modules/@openzeppelin/contracts/utils/cryptography/ECDSA.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in
Submitted on: 2025-11-06 11:47:25
Comments
Log in to comment.
No comments yet.