Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/FixedRateMaturityVault.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
* @title FixedRateMaturityVault
* @notice Fixed-rate maturity vault with queue-based withdrawal system
* - Users deposit underlying tokens and receive fTOKEN based on fixYield
* - Contract calculates fyAmount based on fixYield and time remaining
* - Withdrawals are queued and processed by authorized processors
* - 1 fTOKEN = 1 underlying token on/after maturityxa
* - EIP-712 signed quotes with fixYield parameter
* - Two-role access control: ISSUER and WITHDRAWAL_QUEUE_PROCESSOR
*/
contract FixedRateMaturityVault is ERC20, EIP712, ReentrancyGuard {
using SafeERC20 for IERC20;
// -------- Roles --------
bytes32 public constant ISSUER_ROLE = keccak256("ISSUER_ROLE");
bytes32 public constant WITHDRAWAL_QUEUE_PROCESSOR_ROLE = keccak256("WITHDRAWAL_QUEUE_PROCESSOR_ROLE");
bytes32 public constant ASSET_MANAGER_ROLE = keccak256("ASSET_MANAGER_ROLE");
mapping(bytes32 => mapping(address => bool)) public roles;
// -------- Immutable config --------
uint256 public immutable maturityTimestamp;
IERC20 public immutable underlyingToken;
uint8 private immutable _underlyingDecimals;
// -------- Parameters (issuer-tunable) --------
address public quoteSigner; // backend signer for quotes
uint256 public faceCap; // optional max total face (totalSupply) allowed; 0 means unbounded
bool public depositsPaused; // emergency stop for new deposits
// -------- Quote validation parameters --------
uint256 public maxQuoteAge; // maximum age of quote in seconds
uint256 public minDepositAmount; // minimum deposit amount per transaction
uint256 public maxDepositAmount; // maximum deposit amount per transaction
uint256 public maxDepositPerDay; // maximum deposit per user per day
// -------- Rho routing / liquidity policy --------
address public rhoTarget; // allowlisted Rho endpoint (EOA or contract)
uint256 public minLiquidityBufferBps = 1000; // keep >=10% idle as buffer
// -------- Replay protection for quotes --------
mapping(address => mapping(uint256 => bool)) public usedNonce;
// -------- Daily deposit tracking --------
mapping(address => uint256) public dailyDeposits;
mapping(address => uint256) public lastDepositDay;
// -------- Withdrawal Queue System --------
struct WithdrawalRequest {
address user;
uint256 fyAmount;
uint256 underlyingAmount;
uint256 timestamp;
bool processed;
}
mapping(uint256 => WithdrawalRequest) public withdrawalQueue;
uint256 public queueFront; // Next request to be processed
uint256 public queueBack; // Next available slot
uint256 public pendingWithdrawals; // Total pending withdrawal amount
// -------- User withdrawal tracking --------
mapping(address => uint256) public userPendingWithdrawals;
// -------- Constants --------
uint256 public constant BPS_DENOMINATOR = 10_000;
uint256 public constant SECONDS_PER_YEAR = 365 days;
uint256 public constant DEPOSIT_BLOCK_PERIOD = 24 hours; // Block deposits 24 hours before maturity
// -------- EIP-712 Quote (updated structure) --------
bytes32 public constant QUOTE_TYPEHASH = keccak256(
"Quote(address userAddress,uint256 depositAmount,uint256 fixYield,uint256 maturityTimestamp,uint256 quoteTimestamp,uint256 nonce)"
);
// TODO: Future enhancement - range quotes for execution flexibility
// bytes32 public constant QUOTE_TYPEHASH = keccak256(
// "Quote(address userAddress,uint256 minAmount,uint256 maxAmount,uint256 fixYield,uint256 maturityTimestamp,uint256 quoteTimestamp,uint256 nonce)"
// );
// In deposit():
// require(depositAmount >= minAmount && depositAmount <= maxAmount, "amount out of range");
// -------- Events --------
event Deposit(address indexed user, uint256 tokenIn, uint256 fyMinted, uint256 nonce, uint256 fixYieldBps, uint256 quoteTimestamp);
event WithdrawalRequested(address indexed user, uint256 requestId, uint256 fyAmount, uint256 underlyingAmount);
event WithdrawalProcessed(address indexed user, uint256 requestId, uint256 underlyingAmount, address processor);
event DepositsPausedSet(bool paused);
event QuoteSignerSet(address oldSigner, address newSigner);
event FaceCapSet(uint256 oldCap, uint256 newCap);
event RoleGranted(bytes32 indexed role, address indexed account);
event RoleRevoked(bytes32 indexed role, address indexed account);
event MaxQuoteAgeSet(uint256 oldAge, uint256 newAge);
event MinDepositAmountSet(uint256 oldAmount, uint256 newAmount);
event MaxDepositAmountSet(uint256 oldAmount, uint256 newAmount);
event MaxDepositPerDaySet(uint256 oldAmount, uint256 newAmount);
event RhoTargetSet(address indexed oldTarget, address indexed newTarget);
event MinLiquidityBufferBpsSet(uint256 oldBps, uint256 newBps);
event MovedToRho(uint256 amount);
event PulledFromRho(uint256 amount);
// -------- Modifiers --------
modifier onlyRole(bytes32 role) {
require(roles[role][msg.sender], "AccessControl: caller does not have required role");
_;
}
// -------- Constructor --------
constructor(
address _underlyingToken,
uint256 _maturityTimestamp,
address _quoteSigner,
string memory nameSuffix, // e.g., "2025-06-30"
address _issuer
)
ERC20(
string(abi.encodePacked(IERC20Metadata(_underlyingToken).symbol(), " Fixed ", nameSuffix)),
string(abi.encodePacked("f", IERC20Metadata(_underlyingToken).symbol(), "-", nameSuffix))
)
EIP712("FixedRateMaturityVault", "1")
{
require(_underlyingToken != address(0), "bad underlying token");
require(_maturityTimestamp > block.timestamp, "maturity in past");
require(_quoteSigner != address(0), "bad signer");
require(_issuer != address(0), "bad issuer");
underlyingToken = IERC20(_underlyingToken);
maturityTimestamp = _maturityTimestamp;
quoteSigner = _quoteSigner;
_underlyingDecimals = IERC20Metadata(_underlyingToken).decimals();
faceCap = 0;
depositsPaused = false;
maxQuoteAge = 5 minutes;
// Scale defaults to underlying units (yUSD=6)
minDepositAmount = 100 * (10 ** _underlyingDecimals);
maxDepositAmount = 1_000 * (10 ** _underlyingDecimals);
maxDepositPerDay = 10_000 * (10 ** _underlyingDecimals);
_grantRole(ISSUER_ROLE, _issuer);
}
// -------- Role Management --------
function _grantRole(bytes32 role, address account) internal {
roles[role][account] = true;
emit RoleGranted(role, account);
}
function grantRole(bytes32 role, address account) external onlyRole(ISSUER_ROLE) {
require(account != address(0), "bad account");
_grantRole(role, account);
}
function revokeRole(bytes32 role, address account) external onlyRole(ISSUER_ROLE) {
require(account != address(0), "bad account");
roles[role][account] = false;
emit RoleRevoked(role, account);
}
function hasRole(bytes32 role, address account) external view returns (bool) {
return roles[role][account];
}
// -------- Views --------
/// @notice Current underlying token this contract holds.
function underlyingHeld() public view returns (uint256) {
return underlyingToken.balanceOf(address(this));
}
/// @notice Total liability owed by the vault right now.
/// @dev Includes outstanding fTOKEN supply + queued redemptions (burned from supply but tracked in pendingWithdrawals).
function totalLiability() external view returns (uint256) {
return totalSupply() + pendingWithdrawals;
}
/// @notice Available assets minus pending withdrawals.
function freeAssets() public view returns (uint256) {
uint256 totalAssets = underlyingHeld();
uint256 pending = pendingWithdrawals;
return totalAssets > pending ? totalAssets - pending : 0;
}
/// @notice Get queue statistics.
function getQueueStats() external view returns (uint256 front, uint256 back, uint256 pending) {
return (queueFront, queueBack, pendingWithdrawals);
}
/// @notice Get withdrawal request details.
function getWithdrawalRequest(uint256 requestId) external view returns (
address user,
uint256 fyAmount,
uint256 underlyingAmount,
uint256 timestamp,
bool processed
) {
WithdrawalRequest memory request = withdrawalQueue[requestId];
return (request.user, request.fyAmount, request.underlyingAmount, request.timestamp, request.processed);
}
/// @notice True if the given nonce has been consumed for `user`.
function quoteUsed(address user, uint256 nonce) external view returns (bool) {
return usedNonce[user][nonce];
}
/// @notice Calculate fyAmount based on fixYield and time remaining to maturity
/// @dev This is the core function that calculates the exact amount to mint
function calculateFyAmount(
uint256 depositAmount,
uint256 fixYieldBps,
uint256 quoteTimestamp
) public view returns (uint256) {
require(quoteTimestamp <= maturityTimestamp, "quote after maturity");
uint256 timeRemaining = maturityTimestamp - quoteTimestamp;
uint256 annualYieldBps = (fixYieldBps * timeRemaining) / SECONDS_PER_YEAR;
uint256 yieldAmount = (depositAmount * annualYieldBps) / BPS_DENOMINATOR;
return depositAmount + yieldAmount;
}
/// @notice Recoverable EIP-712 digest for a quote
function hashQuote(
address userAddress,
uint256 depositAmount,
uint256 fixYield,
uint256 qMaturityTimestamp,
uint256 quoteTimestamp,
uint256 nonce
) external view returns (bytes32) {
bytes32 structHash = keccak256(
abi.encode(
QUOTE_TYPEHASH,
userAddress,
depositAmount,
fixYield,
qMaturityTimestamp,
quoteTimestamp,
nonce
)
);
return _hashTypedDataV4(structHash);
}
/// @notice Check if user can deposit the given amount today.
function canDepositToday(address user, uint256 amount) external view returns (bool) {
uint256 currentDay = block.timestamp / 1 days;
// If it's a new day, reset the counter
if (lastDepositDay[user] != currentDay) {
return amount <= maxDepositPerDay;
}
// Check if adding this amount would exceed daily limit
return dailyDeposits[user] + amount <= maxDepositPerDay;
}
/// @notice Get user's remaining daily deposit allowance.
function getRemainingDailyDeposit(address user) external view returns (uint256) {
uint256 currentDay = block.timestamp / 1 days;
// If it's a new day, reset the counter
if (lastDepositDay[user] != currentDay) {
return maxDepositPerDay;
}
// Return remaining allowance
if (dailyDeposits[user] >= maxDepositPerDay) {
return 0;
}
return maxDepositPerDay - dailyDeposits[user];
}
/// @notice Check if deposits are blocked due to 24-hour pre-maturity restriction.
function isDepositBlocked() public view returns (bool) {
return block.timestamp >= maturityTimestamp - DEPOSIT_BLOCK_PERIOD;
}
/// @notice Return decimals to match underlying token
function decimals() public view override returns (uint8) {
return _underlyingDecimals;
}
// -------- Admin (issuer) controls --------
/// @notice Pause or unpause new deposits (withdrawals remain available after maturity).
function setDepositsPaused(bool paused) external onlyRole(ISSUER_ROLE) {
depositsPaused = paused;
emit DepositsPausedSet(paused);
}
/// @notice Update the trusted quote signer.
function setQuoteSigner(address newSigner) external onlyRole(ISSUER_ROLE) {
require(newSigner != address(0), "bad signer");
address old = quoteSigner;
quoteSigner = newSigner;
emit QuoteSignerSet(old, newSigner);
}
/// @notice Optional cap on total face (totalSupply). 0 disables the cap.
function setFaceCap(uint256 newCap) external onlyRole(ISSUER_ROLE) {
require(newCap == 0 || newCap >= totalSupply(), "cap < supply");
uint256 old = faceCap;
faceCap = newCap;
emit FaceCapSet(old, newCap);
}
/// @notice Set maximum age of quotes in seconds.
function setMaxQuoteAge(uint256 newAge) external onlyRole(ISSUER_ROLE) {
require(newAge > 0, "age must be > 0");
uint256 old = maxQuoteAge;
maxQuoteAge = newAge;
emit MaxQuoteAgeSet(old, newAge);
}
/// @notice Set minimum deposit amount per transaction.
function setMinDepositAmount(uint256 newAmount) external onlyRole(ISSUER_ROLE) {
require(newAmount > 0, "min = 0");
require(newAmount <= maxDepositAmount, "min > max per tx");
uint256 old = minDepositAmount;
minDepositAmount = newAmount;
emit MinDepositAmountSet(old, newAmount);
}
/// @notice Set maximum deposit amount per transaction.
function setMaxDepositAmount(uint256 newAmount) external onlyRole(ISSUER_ROLE) {
require(newAmount > minDepositAmount, "max must be > min");
require(newAmount <= maxDepositPerDay, "max per tx > max per day");
uint256 old = maxDepositAmount;
maxDepositAmount = newAmount;
emit MaxDepositAmountSet(old, newAmount);
}
/// @notice Set maximum deposit amount per user per day.
function setMaxDepositPerDay(uint256 newAmount) external onlyRole(ISSUER_ROLE) {
require(newAmount >= maxDepositAmount, "day cap < tx cap");
uint256 old = maxDepositPerDay;
maxDepositPerDay = newAmount;
emit MaxDepositPerDaySet(old, newAmount);
}
// -------- Core flows --------
/**
* @notice Deposit underlying token per a signed quote and mint fTOKEN based on fixYield.
* @dev Contract calculates fyAmount based on fixYield and time remaining to maturity.
*/
function deposit(
uint256 depositAmount,
uint256 fixYield,
uint256 qMaturityTimestamp,
uint256 quoteTimestamp,
uint256 nonce,
bytes memory signature
) external nonReentrant {
require(!depositsPaused, "deposits paused");
require(block.timestamp < maturityTimestamp, "matured");
require(!isDepositBlocked(), "deposits blocked 24h before maturity");
require(!usedNonce[msg.sender][nonce], "nonce used");
require(depositAmount > 0, "zero");
// Enhanced quote validation
require(depositAmount >= minDepositAmount, "deposit too small");
require(depositAmount <= maxDepositAmount, "deposit too large");
// Quote age validation
require(quoteTimestamp <= block.timestamp, "quote from future");
require(block.timestamp - quoteTimestamp <= maxQuoteAge, "quote too old");
// Maturity validation
require(qMaturityTimestamp == maturityTimestamp, "maturity mismatch");
// Daily deposit limit validation
uint256 currentDay = block.timestamp / 1 days;
if (lastDepositDay[msg.sender] != currentDay) {
// New day, reset counter
dailyDeposits[msg.sender] = 0;
lastDepositDay[msg.sender] = currentDay;
}
require(dailyDeposits[msg.sender] + depositAmount <= maxDepositPerDay, "daily limit exceeded");
// Verify EIP-712 signature
bytes32 structHash = keccak256(
abi.encode(
QUOTE_TYPEHASH,
msg.sender,
depositAmount, // NEW
fixYield,
qMaturityTimestamp,
quoteTimestamp,
nonce
)
);
bytes32 digest = _hashTypedDataV4(structHash);
address recovered = ECDSA.recover(digest, signature);
require(recovered == quoteSigner, "bad signer");
// CONTRACT CALCULATES fyAmount based on fixYield and current time
uint256 fyAmount = calculateFyAmount(depositAmount, fixYield, quoteTimestamp);
// Optional face cap
if (faceCap != 0) {
require(totalSupply() + fyAmount <= faceCap, "face cap");
}
// Effects
usedNonce[msg.sender][nonce] = true;
dailyDeposits[msg.sender] += depositAmount;
// Pull underlying token in full
underlyingToken.safeTransferFrom(msg.sender, address(this), depositAmount);
// Mint fTOKEN (calculated amount) to user
_mint(msg.sender, fyAmount);
emit Deposit(msg.sender, depositAmount, fyAmount, nonce, fixYield, quoteTimestamp);
}
/**
* @notice Request withdrawal of all fTOKEN for underlying token at/after maturity.
* @dev This queues the withdrawal request instead of immediate execution.
* @dev Only allows full balance withdrawal - partial withdrawals not supported after maturity.
*/
function requestWithdrawal() external nonReentrant {
require(block.timestamp >= maturityTimestamp, "not matured");
uint256 fyAmount = balanceOf(msg.sender);
require(fyAmount > 0, "no balance to withdraw");
// Burn fTOKEN immediately
_burn(msg.sender, fyAmount);
// Calculate underlying amount (1:1 at maturity)
uint256 underlyingAmount = fyAmount;
// Create withdrawal request
uint256 requestId = queueBack;
withdrawalQueue[requestId] = WithdrawalRequest({
user: msg.sender,
fyAmount: fyAmount,
underlyingAmount: underlyingAmount,
timestamp: block.timestamp,
processed: false
});
// Update queue state
queueBack++;
pendingWithdrawals += underlyingAmount;
userPendingWithdrawals[msg.sender] += underlyingAmount;
emit WithdrawalRequested(msg.sender, requestId, fyAmount, underlyingAmount);
}
/**
* @notice Process withdrawal request by authorized processor.
* @dev This function can be called by WITHDRAWAL_QUEUE_PROCESSOR_ROLE.
*/
function processWithdrawal(uint256 requestId) external nonReentrant onlyRole(WITHDRAWAL_QUEUE_PROCESSOR_ROLE) {
require(requestId == queueFront, "not next in queue");
require(requestId < queueBack, "invalid request id");
WithdrawalRequest storage request = withdrawalQueue[requestId];
require(!request.processed && request.user != address(0), "bad request");
request.processed = true;
pendingWithdrawals -= request.underlyingAmount;
userPendingWithdrawals[request.user] -= request.underlyingAmount;
underlyingToken.safeTransfer(request.user, request.underlyingAmount);
unchecked { queueFront++; }
emit WithdrawalProcessed(request.user, requestId, request.underlyingAmount, msg.sender);
}
/**
* @notice Process multiple withdrawal requests in batch.
* @dev Gas efficient way to process multiple requests.
*/
function processWithdrawalsBatch(uint256[] calldata requestIds) external nonReentrant onlyRole(WITHDRAWAL_QUEUE_PROCESSOR_ROLE) {
uint256 expected = queueFront;
for (uint256 i = 0; i < requestIds.length; ) {
uint256 requestId = requestIds[i];
require(requestId == expected, "non-contiguous batch");
require(requestId < queueBack, "invalid request id");
WithdrawalRequest storage request = withdrawalQueue[requestId];
require(!request.processed && request.user != address(0), "bad request");
request.processed = true;
pendingWithdrawals -= request.underlyingAmount;
userPendingWithdrawals[request.user] -= request.underlyingAmount;
underlyingToken.safeTransfer(request.user, request.underlyingAmount);
unchecked { ++expected; ++i; }
emit WithdrawalProcessed(request.user, requestId, request.underlyingAmount, msg.sender);
}
queueFront = expected;
}
// -------- Rho Management (Issuer + Asset Manager) --------
/// @notice Set the allowlisted Rho recipient (strategy)
function setRhoTarget(address target) external onlyRole(ISSUER_ROLE) {
require(target != address(0), "rho target=0");
address old = rhoTarget;
rhoTarget = target;
emit RhoTargetSet(old, target);
}
/// @notice Set the minimum idle liquidity buffer, in bps of liability
function setMinLiquidityBufferBps(uint256 bps) external onlyRole(ISSUER_ROLE) {
require(bps <= BPS_DENOMINATOR, "bps>100%");
uint256 old = minLiquidityBufferBps;
minLiquidityBufferBps = bps;
emit MinLiquidityBufferBpsSet(old, bps);
}
/// @notice Move free assets to the allowlisted Rho target (by Asset Manager)
/// @dev Keeps a buffer so processors/ops can service withdrawals/liquidity needs.
function moveToRho(uint256 amount) external onlyRole(ASSET_MANAGER_ROLE) nonReentrant {
require(rhoTarget != address(0), "rho not set");
require(amount > 0, "zero amount");
// Buffer against current liability
uint256 liability = totalSupply() + pendingWithdrawals;
uint256 bufferMin = (liability * minLiquidityBufferBps) / BPS_DENOMINATOR;
uint256 free = freeAssets();
require(free > bufferMin, "no free above buffer");
require(amount <= free - bufferMin, "exceeds buffer");
underlyingToken.safeTransfer(rhoTarget, amount);
emit MovedToRho(amount);
}
/// @notice Allow Rho to push underlying back into the vault
/// @dev Rho must approve(this) first; callable only by rhoTarget
function depositUnderlyingFromRho(uint256 amount) external nonReentrant {
require(msg.sender == rhoTarget, "not rho");
require(amount > 0, "zero amount");
underlyingToken.safeTransferFrom(msg.sender, address(this), amount);
emit PulledFromRho(amount);
}
// -------- Asset Management (Issuer only) --------
/**
* @notice Withdraw underlying tokens from the contract (for Rho operations).
* @dev Only ISSUER_ROLE can call this function.
* @dev Cannot withdraw more than freeAssets() to ensure vault solvency.
*/
function withdrawUnderlying(uint256 amount, address to) external onlyRole(ISSUER_ROLE) nonReentrant {
require(to != address(0), "bad recipient");
require(amount > 0, "zero amount");
require(amount <= freeAssets(), "insufficient free assets");
underlyingToken.safeTransfer(to, amount);
}
/**
* @notice Deposit underlying tokens back to the contract.
* @dev Only ISSUER_ROLE can call this function.
* @dev This is used to provide additional underlying tokens to cover yield payments.
*/
function depositUnderlying(uint256 amount) external onlyRole(ISSUER_ROLE) nonReentrant {
require(amount > 0, "zero amount");
underlyingToken.safeTransferFrom(msg.sender, address(this), amount);
}
/**
* @notice Get the vault's solvency status.
* @dev Returns true if the vault has enough underlying tokens to pay all fTOKEN at maturity.
*/
function isSolvent() external view returns (bool) {
return underlyingHeld() >= totalSupply() + pendingWithdrawals;
}
/**
* @notice Get the amount of additional underlying tokens needed for solvency.
* @dev Returns 0 if the vault is already solvent.
*/
function additionalTokensNeeded() external view returns (uint256) {
uint256 liability = totalSupply() + pendingWithdrawals;
uint256 held = underlyingHeld();
return liability > held ? liability - held : 0;
}
// -------- Internal Functions --------
/**
* @dev Override _update to prevent transfers after maturity
* This ensures fTOKEN tokens cannot be transferred after maturity for security
*/
function _update(
address from,
address to,
uint256 value
) internal virtual override {
// Allow minting and burning operations
if (from == address(0) || to == address(0)) {
super._update(from, to, value);
return;
}
// Prevent transfers after maturity for security
if (block.timestamp >= maturityTimestamp) {
revert("Bond matured - transfers not allowed");
}
super._update(from, to, value);
}
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
"
},
"lib/openzeppelin-contracts/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);
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
"
},
"lib/openzeppelin-contracts/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);
}
}
"
},
"lib/openzeppelin-contracts/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;
}
}
"
},
"lib/openzeppelin-contracts/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);
}
}
"
},
"lib/openzeppelin-contracts/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
Submitted on: 2025-10-24 19:46:08
Comments
Log in to comment.
No comments yet.