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": {
"artifacts/DEXStakingIntegration.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./AccessControlUpgradeable.sol";
import "./CoreRegistry.sol";
/**
* @title DEXStakingIntegration
* @dev کانترکت یکپارچهسازی DEX و Staking برای revenue sharing
* @notice این کانترکت درآمد DEX را جمعآوری و به staking توزیع میکند
*/
contract DEXStakingIntegration is
Initializable,
ReentrancyGuardUpgradeable,
UUPSUpgradeable,
LaxceAccessControlUpgradeable
{
using SafeERC20 for IERC20;
// ==================== CONSTANTS ====================
uint256 public constant BASIS_POINTS = 10000;
uint256 public constant REVENUE_SHARE_PERCENTAGE = 3000; // 30%
uint256 public constant STAKING_SHARE_PERCENTAGE = 7000; // 70%
// ==================== STATE VARIABLES ====================
CoreRegistry public coreRegistry;
address public dexEngine;
address public stakingManager;
address public treasuryAddress;
uint256 public totalRevenueCollected;
uint256 public totalDistributedToStaking;
uint256 public totalDistributedToTreasury;
// ==================== EVENTS ====================
event RevenueDistributed(
uint256 totalRevenue,
uint256 stakingAmount,
uint256 treasuryAmount,
uint256 timestamp
);
// ==================== INITIALIZER ====================
function initialize(
address _coreRegistry,
address _admin
) external initializer {
__ReentrancyGuard_init();
__UUPSUpgradeable_init();
SecuritySettings memory securitySettings = SecuritySettings({
emergencyDelay: 24 hours,
adminDelay: 1 hours,
emergencyMode: false,
lastEmergencyTime: 0
});
__LaxceAccessControl_init(_admin, "1.0.0", securitySettings);
coreRegistry = CoreRegistry(_coreRegistry);
}
// ==================== REVENUE FUNCTIONS ====================
function distributeRevenue(uint256 amount) external onlyRole(OPERATOR_ROLE) {
require(amount > 0, "Invalid amount");
uint256 stakingAmount = (amount * STAKING_SHARE_PERCENTAGE) / BASIS_POINTS;
uint256 treasuryAmount = amount - stakingAmount;
totalRevenueCollected += amount;
totalDistributedToStaking += stakingAmount;
totalDistributedToTreasury += treasuryAmount;
emit RevenueDistributed(amount, stakingAmount, treasuryAmount, block.timestamp);
}
// ==================== ADMIN FUNCTIONS ====================
function setAddresses(
address _dexEngine,
address _stakingManager,
address _treasury
) external onlyRole(ADMIN_ROLE) {
dexEngine = _dexEngine;
stakingManager = _stakingManager;
treasuryAddress = _treasury;
}
// ==================== VIEW FUNCTIONS ====================
function getStats() external view returns (
uint256 totalRevenue,
uint256 stakingDistributed,
uint256 treasuryDistributed
) {
return (totalRevenueCollected, totalDistributedToStaking, totalDistributedToTreasury);
}
// ==================== UPGRADE AUTHORIZATION ====================
function _authorizeUpgrade(address newImplementation)
internal
override(UUPSUpgradeable, LaxceAccessControlUpgradeable)
onlyRole(UPGRADER_ROLE)
{}
}"
},
"artifacts/CoreRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
/**
* @title CoreRegistry
* @dev رجیستری مرکزی برای تمام کانترکتهای سیستم LAXCE DEX
* @notice این کانترکت آدرسهای تمام اجزای سیستم را مدیریت میکند
*/
contract CoreRegistry is Initializable, UUPSUpgradeable, LaxceAccessControlUpgradeable {
// ==================== CONSTANTS ====================
/// @dev شناسههای کانترکتها
bytes32 public constant DEX_ENGINE = keccak256("DEX_ENGINE");
bytes32 public constant POOL_FACTORY = keccak256("POOL_FACTORY");
bytes32 public constant POOL_MANAGER = keccak256("POOL_MANAGER");
bytes32 public constant TOKEN_REGISTRY = keccak256("TOKEN_REGISTRY");
bytes32 public constant STAKING_MANAGER = keccak256("STAKING_MANAGER");
bytes32 public constant STAKING_REWARDS = keccak256("STAKING_REWARDS");
bytes32 public constant REFERRAL_MANAGER = keccak256("REFERRAL_MANAGER");
bytes32 public constant ORACLE_MANAGER = keccak256("ORACLE_MANAGER");
bytes32 public constant PRICE_ORACLE = keccak256("PRICE_ORACLE");
bytes32 public constant SECURITY_MANAGER = keccak256("SECURITY_MANAGER");
bytes32 public constant FEE_COLLECTOR = keccak256("FEE_COLLECTOR");
bytes32 public constant GOVERNANCE = keccak256("GOVERNANCE");
bytes32 public constant TREASURY = keccak256("TREASURY");
bytes32 public constant ROUTER = keccak256("ROUTER");
bytes32 public constant QUOTER = keccak256("QUOTER");
// ==================== STRUCTS ====================
struct ContractInfo {
address contractAddress; // آدرس کانترکت
string name; // نام کانترکت
string version; // نسخه کانترکت
bool isActive; // وضعیت فعال/غیرفعال
uint256 registeredAt; // زمان ثبت
uint256 lastUpdate; // آخرین بهروزرسانی
address registrar; // کسی که ثبت کرده
}
struct SystemStats {
uint256 totalContracts; // تعداد کل کانترکتها
uint256 activeContracts; // تعداد کانترکتهای فعال
uint256 lastRegistration; // آخرین ثبت
uint256 totalUpdates; // تعداد کل بهروزرسانیها
}
// ==================== STATE VARIABLES ====================
/// @dev نگاشت شناسه به اطلاعات کانترکت
mapping(bytes32 => ContractInfo) public contracts;
/// @dev نگاشت آدرس به شناسه (برای جستجوی معکوس)
mapping(address => bytes32) public addressToId;
/// @dev لیست تمام شناسهها
bytes32[] public allContractIds;
/// @dev آمار سیستم
SystemStats public systemStats;
/// @dev وابستگیهای کانترکتها (کدام کانترکت به کدام وابسته است)
mapping(bytes32 => bytes32[]) public contractDependencies;
/// @dev کانترکتهایی که به یک کانترکت خاص وابسته هستند
mapping(bytes32 => bytes32[]) public dependentContracts;
/// @dev تنظیمات integration
mapping(bytes32 => mapping(bytes32 => bool)) public integrationStatus;
// ==================== EVENTS ====================
event ContractRegistered(
bytes32 indexed contractId,
address indexed contractAddress,
string name,
string version,
address indexed registrar
);
event ContractUpdated(
bytes32 indexed contractId,
address indexed oldAddress,
address indexed newAddress,
string newVersion
);
event ContractStatusChanged(
bytes32 indexed contractId,
bool isActive,
address indexed updater
);
event DependencyAdded(
bytes32 indexed contractId,
bytes32 indexed dependsOn
);
event DependencyRemoved(
bytes32 indexed contractId,
bytes32 indexed dependsOn
);
event IntegrationStatusChanged(
bytes32 indexed contractA,
bytes32 indexed contractB,
bool integrated
);
// ==================== ERRORS ====================
error Registry__ContractAlreadyExists();
error Registry__ContractNotExists();
error Registry__InvalidAddress();
error Registry__AddressAlreadyUsed();
error Registry__CircularDependency();
error Registry__DependencyNotMet();
// ==================== INITIALIZER ====================
/**
* @dev مقداردهی اولیه
*/
function initialize(
address _deployer,
string memory _version
) external initializer {
SecuritySettings memory settings = SecuritySettings({
emergencyDelay: 24 hours,
adminDelay: 1 hours,
emergencyMode: false,
lastEmergencyTime: 0
});
__LaxceAccessControl_init(_deployer, _version, settings);
systemStats.lastRegistration = block.timestamp;
}
// ==================== CONTRACT MANAGEMENT ====================
/**
* @dev ثبت کانترکت جدید
*/
function registerContract(
bytes32 contractId,
address contractAddress,
string calldata name,
string calldata version
) external onlyRole(ADMIN_ROLE) whenNotPaused {
if (contracts[contractId].contractAddress != address(0)) {
revert Registry__ContractAlreadyExists();
}
if (contractAddress == address(0)) {
revert Registry__InvalidAddress();
}
if (addressToId[contractAddress] != bytes32(0)) {
revert Registry__AddressAlreadyUsed();
}
contracts[contractId] = ContractInfo({
contractAddress: contractAddress,
name: name,
version: version,
isActive: true,
registeredAt: block.timestamp,
lastUpdate: block.timestamp,
registrar: msg.sender
});
addressToId[contractAddress] = contractId;
allContractIds.push(contractId);
// بهروزرسانی آمار
systemStats.totalContracts++;
systemStats.activeContracts++;
systemStats.lastRegistration = block.timestamp;
emit ContractRegistered(contractId, contractAddress, name, version, msg.sender);
}
/**
* @dev بهروزرسانی آدرس کانترکت
*/
function updateContract(
bytes32 contractId,
address newAddress,
string calldata newVersion
) external onlyRole(ADMIN_ROLE) whenNotPaused {
ContractInfo storage info = contracts[contractId];
if (info.contractAddress == address(0)) {
revert Registry__ContractNotExists();
}
if (newAddress == address(0)) {
revert Registry__InvalidAddress();
}
if (addressToId[newAddress] != bytes32(0) && addressToId[newAddress] != contractId) {
revert Registry__AddressAlreadyUsed();
}
address oldAddress = info.contractAddress;
// حذف آدرس قدیمی از نگاشت معکوس
delete addressToId[oldAddress];
// بهروزرسانی اطلاعات
info.contractAddress = newAddress;
info.version = newVersion;
info.lastUpdate = block.timestamp;
// اضافه کردن آدرس جدید به نگاشت معکوس
addressToId[newAddress] = contractId;
// بهروزرسانی آمار
systemStats.totalUpdates++;
emit ContractUpdated(contractId, oldAddress, newAddress, newVersion);
}
/**
* @dev تغییر وضعیت فعال/غیرفعال کانترکت
*/
function setContractStatus(
bytes32 contractId,
bool isActive
) external onlyRole(ADMIN_ROLE) {
ContractInfo storage info = contracts[contractId];
if (info.contractAddress == address(0)) {
revert Registry__ContractNotExists();
}
bool wasActive = info.isActive;
info.isActive = isActive;
info.lastUpdate = block.timestamp;
// بهروزرسانی آمار
if (wasActive && !isActive) {
systemStats.activeContracts--;
} else if (!wasActive && isActive) {
systemStats.activeContracts++;
}
emit ContractStatusChanged(contractId, isActive, msg.sender);
}
// ==================== DEPENDENCY MANAGEMENT ====================
/**
* @dev اضافه کردن وابستگی
*/
function addDependency(
bytes32 contractId,
bytes32 dependsOn
) external onlyRole(ADMIN_ROLE) {
if (contracts[contractId].contractAddress == address(0) ||
contracts[dependsOn].contractAddress == address(0)) {
revert Registry__ContractNotExists();
}
// بررسی circular dependency
if (_hasCircularDependency(contractId, dependsOn)) {
revert Registry__CircularDependency();
}
contractDependencies[contractId].push(dependsOn);
dependentContracts[dependsOn].push(contractId);
emit DependencyAdded(contractId, dependsOn);
}
/**
* @dev حذف وابستگی
*/
function removeDependency(
bytes32 contractId,
bytes32 dependsOn
) external onlyRole(ADMIN_ROLE) {
_removeDependencyFromArray(contractDependencies[contractId], dependsOn);
_removeDependencyFromArray(dependentContracts[dependsOn], contractId);
emit DependencyRemoved(contractId, dependsOn);
}
/**
* @dev بررسی circular dependency
*/
function _hasCircularDependency(bytes32 contractId, bytes32 dependsOn) internal view returns (bool) {
// اگر dependsOn به contractId وابسته باشد، circular dependency داریم
bytes32[] memory deps = contractDependencies[dependsOn];
for (uint256 i = 0; i < deps.length; i++) {
if (deps[i] == contractId) {
return true;
}
// بررسی recursive
if (_hasCircularDependency(contractId, deps[i])) {
return true;
}
}
return false;
}
/**
* @dev حذف از آرایه وابستگیها
*/
function _removeDependencyFromArray(bytes32[] storage array, bytes32 item) internal {
for (uint256 i = 0; i < array.length; i++) {
if (array[i] == item) {
array[i] = array[array.length - 1];
array.pop();
break;
}
}
}
// ==================== INTEGRATION MANAGEMENT ====================
/**
* @dev تنظیم وضعیت integration بین دو کانترکت
*/
function setIntegrationStatus(
bytes32 contractA,
bytes32 contractB,
bool integrated
) external onlyRole(ADMIN_ROLE) {
if (contracts[contractA].contractAddress == address(0) ||
contracts[contractB].contractAddress == address(0)) {
revert Registry__ContractNotExists();
}
integrationStatus[contractA][contractB] = integrated;
integrationStatus[contractB][contractA] = integrated;
emit IntegrationStatusChanged(contractA, contractB, integrated);
}
// ==================== VIEW FUNCTIONS ====================
/**
* @dev دریافت آدرس کانترکت
*/
function getContract(bytes32 contractId) external view returns (address) {
return contracts[contractId].contractAddress;
}
/**
* @dev دریافت اطلاعات کامل کانترکت
*/
function getContractInfo(bytes32 contractId) external view returns (ContractInfo memory) {
return contracts[contractId];
}
/**
* @dev دریافت شناسه از آدرس
*/
function getContractId(address contractAddress) external view returns (bytes32) {
return addressToId[contractAddress];
}
/**
* @dev بررسی فعال بودن کانترکت
*/
function isContractActive(bytes32 contractId) external view returns (bool) {
return contracts[contractId].isActive;
}
/**
* @dev دریافت وابستگیهای کانترکت
*/
function getContractDependencies(bytes32 contractId) external view returns (bytes32[] memory) {
return contractDependencies[contractId];
}
/**
* @dev دریافت کانترکتهای وابسته
*/
function getDependentContracts(bytes32 contractId) external view returns (bytes32[] memory) {
return dependentContracts[contractId];
}
/**
* @dev بررسی وضعیت integration
*/
function areContractsIntegrated(bytes32 contractA, bytes32 contractB) external view returns (bool) {
return integrationStatus[contractA][contractB];
}
/**
* @dev دریافت تمام شناسهها
*/
function getAllContractIds() external view returns (bytes32[] memory) {
return allContractIds;
}
/**
* @dev دریافت آمار سیستم
*/
function getSystemStats() external view returns (SystemStats memory) {
return systemStats;
}
/**
* @dev بررسی سلامت سیستم
*/
function checkSystemHealth() external view returns (
bool allCoreContractsActive,
uint256 totalContracts,
uint256 activeContracts,
uint256 inactiveContracts
) {
// کانترکتهای اصلی
bytes32[] memory coreContracts = new bytes32[](6);
coreContracts[0] = DEX_ENGINE;
coreContracts[1] = POOL_FACTORY;
coreContracts[2] = TOKEN_REGISTRY;
coreContracts[3] = STAKING_MANAGER;
coreContracts[4] = ORACLE_MANAGER;
coreContracts[5] = SECURITY_MANAGER;
allCoreContractsActive = true;
for (uint256 i = 0; i < coreContracts.length; i++) {
if (!contracts[coreContracts[i]].isActive) {
allCoreContractsActive = false;
break;
}
}
totalContracts = systemStats.totalContracts;
activeContracts = systemStats.activeContracts;
inactiveContracts = totalContracts - activeContracts;
}
// ==================== UPGRADE AUTHORIZATION ====================
/**
* @dev مجوز upgrade
*/
function _authorizeUpgrade(address newImplementation)
internal
override(UUPSUpgradeable, LaxceAccessControlUpgradeable)
onlyRole(UPGRADER_ROLE)
{}
}
"
},
"artifacts/AccessControlUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
/**
* @title LaxceAccessControlUpgradeable
* @dev مدیریت کنترل دسترسی upgradeable برای تمام کانترکتهای LAXCE DEX
* @notice این کانترکت پایه سیستم مجوزها و نقشها است
*/
contract LaxceAccessControlUpgradeable is
Initializable,
AccessControlUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable,
UUPSUpgradeable
{
// ==================== ROLE DEFINITIONS ====================
/// @dev نقش مالک اصلی سیستم
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
/// @dev نقش ادمین سیستم
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
/// @dev نقش اپراتور
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
/// @dev نقش توقفکننده (در شرایط اضطراری)
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/// @dev نقش ارتقادهنده کانترکتها
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
/// @dev نقش مدیریت treasury
bytes32 public constant TREASURY_ROLE = keccak256("TREASURY_ROLE");
/// @dev نقش مدیریت Oracle
bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
/// @dev نقش مدیریت Pool
bytes32 public constant POOL_MANAGER_ROLE = keccak256("POOL_MANAGER_ROLE");
/// @dev نقش emergency (اضطراری)
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE");
/// @dev نقش مدیریت Fee
bytes32 public constant FEE_MANAGER_ROLE = keccak256("FEE_MANAGER_ROLE");
/// @dev نقش مدیریت Staking
bytes32 public constant STAKING_MANAGER_ROLE = keccak256("STAKING_MANAGER_ROLE");
/// @dev نقش مدیریت Governance
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE");
// ==================== STATE VARIABLES ====================
/// @dev آدرس deployer اولیه
address public deployer;
/// @dev تاریخ deployment
uint256 public deploymentTime;
/// @dev نسخه کانترکت
string public version;
/// @dev تنظیمات امنیتی
struct SecuritySettings {
uint256 emergencyDelay; // تاخیر برای عملیات اضطراری
uint256 adminDelay; // تاخیر برای عملیات ادمین
bool emergencyMode; // حالت اضطراری
uint256 lastEmergencyTime; // آخرین زمان فعالسازی emergency
}
SecuritySettings public securitySettings;
/// @dev لیست آدرسهای مجاز برای هر نقش
mapping(bytes32 => address[]) public roleMembers;
/// @dev آمار نقشها
mapping(bytes32 => uint256) public roleMemberCount;
/// @dev تاریخچه تغییرات نقشها
struct RoleChange {
bytes32 role;
address account;
bool granted;
uint256 timestamp;
address admin;
}
RoleChange[] public roleChanges;
/// @dev محدودیتهای زمانی برای نقشها
mapping(bytes32 => mapping(address => uint256)) public roleTimeRestrictions;
// ==================== EVENTS ====================
event SecuritySettingsUpdated(
uint256 emergencyDelay,
uint256 adminDelay,
address indexed updater
);
event EmergencyModeToggled(bool enabled, address indexed toggler);
event RoleGrantedWithTimeRestriction(
bytes32 indexed role,
address indexed account,
address indexed sender,
uint256 validUntil
);
event RoleTimeRestrictionUpdated(
bytes32 indexed role,
address indexed account,
uint256 newValidUntil
);
// ==================== ERRORS ====================
error AccessControl__EmergencyModeActive();
error AccessControl__TimeRestrictionExpired();
error AccessControl__InvalidDelay();
error AccessControl__EmergencyDelayNotMet();
error AccessControl__AdminDelayNotMet();
// ==================== MODIFIERS ====================
modifier whenNotInEmergency() {
if (securitySettings.emergencyMode) revert AccessControl__EmergencyModeActive();
_;
}
modifier withTimeRestriction(bytes32 role) {
uint256 validUntil = roleTimeRestrictions[role][msg.sender];
if (validUntil > 0 && block.timestamp > validUntil) {
revert AccessControl__TimeRestrictionExpired();
}
_;
}
modifier emergencyDelayMet() {
if (block.timestamp < securitySettings.lastEmergencyTime + securitySettings.emergencyDelay) {
revert AccessControl__EmergencyDelayNotMet();
}
_;
}
// ==================== INITIALIZER ====================
/**
* @dev مقداردهی اولیه کانترکت
*/
function __LaxceAccessControl_init(
address _deployer,
string memory _version,
SecuritySettings memory _securitySettings
) internal onlyInitializing {
__AccessControl_init();
__Pausable_init();
__ReentrancyGuard_init();
__UUPSUpgradeable_init();
deployer = _deployer;
deploymentTime = block.timestamp;
version = _version;
securitySettings = _securitySettings;
// تنظیم نقشهای اولیه
_setupInitialRoles(_deployer);
}
/**
* @dev مقداردهی اولیه برای استفاده خارجی
*/
function initialize(
address _deployer,
string memory _version,
SecuritySettings memory _securitySettings
) external initializer {
__LaxceAccessControl_init(_deployer, _version, _securitySettings);
}
// ==================== ROLE MANAGEMENT ====================
/**
* @dev اعطای نقش با محدودیت زمانی
*/
function grantRoleWithTimeRestriction(
bytes32 role,
address account,
uint256 validUntil
) external onlyRole(getRoleAdmin(role)) whenNotInEmergency {
grantRole(role, account);
if (validUntil > 0) {
roleTimeRestrictions[role][account] = validUntil;
emit RoleGrantedWithTimeRestriction(role, account, msg.sender, validUntil);
}
_updateRoleMembersList(role, account, true);
}
/**
* @dev حذف نقش
*/
function revokeRole(bytes32 role, address account)
public
override
onlyRole(getRoleAdmin(role))
whenNotInEmergency
{
super.revokeRole(role, account);
_updateRoleMembersList(role, account, false);
// حذف محدودیت زمانی
delete roleTimeRestrictions[role][account];
}
/**
* @dev بهروزرسانی محدودیت زمانی نقش
*/
function updateRoleTimeRestriction(
bytes32 role,
address account,
uint256 newValidUntil
) external onlyRole(getRoleAdmin(role)) {
require(hasRole(role, account), "Account does not have role");
roleTimeRestrictions[role][account] = newValidUntil;
emit RoleTimeRestrictionUpdated(role, account, newValidUntil);
}
/**
* @dev تنظیم نقشهای اولیه
*/
function _setupInitialRoles(address _deployer) internal {
// مالک اصلی
_grantRole(DEFAULT_ADMIN_ROLE, _deployer);
_grantRole(OWNER_ROLE, _deployer);
_grantRole(ADMIN_ROLE, _deployer);
_grantRole(UPGRADER_ROLE, _deployer);
_grantRole(EMERGENCY_ROLE, _deployer);
_grantRole(PAUSER_ROLE, _deployer);
// تنظیم role admins
_setRoleAdmin(ADMIN_ROLE, OWNER_ROLE);
_setRoleAdmin(OPERATOR_ROLE, ADMIN_ROLE);
_setRoleAdmin(TREASURY_ROLE, ADMIN_ROLE);
_setRoleAdmin(ORACLE_ROLE, ADMIN_ROLE);
_setRoleAdmin(POOL_MANAGER_ROLE, ADMIN_ROLE);
_setRoleAdmin(FEE_MANAGER_ROLE, ADMIN_ROLE);
_setRoleAdmin(STAKING_MANAGER_ROLE, ADMIN_ROLE);
_setRoleAdmin(GOVERNANCE_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, EMERGENCY_ROLE);
_setRoleAdmin(UPGRADER_ROLE, OWNER_ROLE);
}
/**
* @dev بهروزرسانی لیست اعضای نقش
*/
function _updateRoleMembersList(bytes32 role, address account, bool granted) internal {
if (granted) {
roleMembers[role].push(account);
roleMemberCount[role]++;
} else {
// حذف از لیست
address[] storage members = roleMembers[role];
for (uint256 i = 0; i < members.length; i++) {
if (members[i] == account) {
members[i] = members[members.length - 1];
members.pop();
roleMemberCount[role]--;
break;
}
}
}
// ثبت تغییر در تاریخچه
roleChanges.push(RoleChange({
role: role,
account: account,
granted: granted,
timestamp: block.timestamp,
admin: msg.sender
}));
}
// ==================== SECURITY FUNCTIONS ====================
/**
* @dev تنظیم پارامترهای امنیتی
*/
function updateSecuritySettings(
uint256 _emergencyDelay,
uint256 _adminDelay
) external onlyRole(OWNER_ROLE) {
if (_emergencyDelay < 1 hours || _adminDelay < 30 minutes) {
revert AccessControl__InvalidDelay();
}
securitySettings.emergencyDelay = _emergencyDelay;
securitySettings.adminDelay = _adminDelay;
emit SecuritySettingsUpdated(_emergencyDelay, _adminDelay, msg.sender);
}
/**
* @dev فعال/غیرفعال کردن حالت اضطراری
*/
function toggleEmergencyMode() external virtual onlyRole(EMERGENCY_ROLE) emergencyDelayMet {
securitySettings.emergencyMode = !securitySettings.emergencyMode;
securitySettings.lastEmergencyTime = block.timestamp;
emit EmergencyModeToggled(securitySettings.emergencyMode, msg.sender);
}
// ==================== PAUSE FUNCTIONS ====================
/**
* @dev توقف کانترکت
*/
function pause() external onlyRole(PAUSER_ROLE) {
_pause();
}
/**
* @dev از سرگیری کانترکت
*/
function unpause() external onlyRole(PAUSER_ROLE) {
_unpause();
}
// ==================== VIEW FUNCTIONS ====================
/**
* @dev بررسی اعتبار نقش با محدودیت زمانی
*/
function hasValidRole(bytes32 role, address account) external view returns (bool) {
if (!hasRole(role, account)) return false;
uint256 validUntil = roleTimeRestrictions[role][account];
if (validUntil > 0 && block.timestamp > validUntil) return false;
return true;
}
/**
* @dev دریافت اعضای یک نقش
*/
function getRoleMembers(bytes32 role) external view returns (address[] memory) {
return roleMembers[role];
}
/**
* @dev دریافت تعداد اعضای یک نقش
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256) {
return roleMemberCount[role];
}
/**
* @dev دریافت تاریخچه تغییرات نقشها
*/
function getRoleChangesCount() external view returns (uint256) {
return roleChanges.length;
}
/**
* @dev بررسی وضعیت emergency
*/
function isEmergencyMode() external view returns (bool) {
return securitySettings.emergencyMode;
}
// ==================== UPGRADE AUTHORIZATION ====================
/**
* @dev مجوز upgrade (فقط برای UPGRADER_ROLE)
*/
function _authorizeUpgrade(address newImplementation)
internal
virtual
override
onlyRole(UPGRADER_ROLE)
whenNotInEmergency
{}
// ==================== VERSION ====================
/**
* @dev دریافت نسخه کانترکت
*/
function getVersion() external view returns (string memory) {
return version;
}
/**
* @dev بهروزرسانی نسخه (فقط هنگام upgrade)
*/
function updateVersion(string memory _newVersion) external onlyRole(UPGRADER_ROLE) {
version = _newVersion;
}
}
"
},
"@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);
}
}
"
},
"@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);
}
"
},
"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._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 {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// 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 {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// 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) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
"
},
"@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
"
},
"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version)
Submitted on: 2025-09-19 10:41:35
Comments
Log in to comment.
No comments yet.