Verified contractExactMIT
Liquidity
Address0x6d8f4dbba1e85ed4f86147019aad5f23ede85527
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.27
- Same code
1 more contract
Details
- Compiler
- solc 0.8.27+commit.40a35a09
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 22,549,811
- Creation transaction
- 0xb578044dda…45aa796c06
- Main copy (most transactions)
- 0x0fe3e601…cea1ebf0
36 files
- contracts/liquidity/Liquidity.solmain25.19 KB
- @openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol8.28 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol8.91 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol6.6 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.19 KB
- @openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol3.86 KB
- @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol1.18 KB
- @openzeppelin/contracts/access/IAccessControl.sol3.34 KB
- @openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- @openzeppelin/contracts/interfaces/IERC165.sol192 B
- @openzeppelin/contracts/interfaces/IERC1967.sol636 B
- @openzeppelin/contracts/interfaces/IERC20.sol181 B
- @openzeppelin/contracts/interfaces/draft-IERC1822.sol881 B
- @openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol6.24 KB
- @openzeppelin/contracts/proxy/beacon/IBeacon.sol472 B
- @openzeppelin/contracts/token/ERC1155/IERC1155.sol4.72 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol9.44 KB
- @openzeppelin/contracts/token/ERC721/IERC721.sol4.93 KB
- @openzeppelin/contracts/utils/Address.sol6.03 KB
- @openzeppelin/contracts/utils/Errors.sol896 B
- @openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol870 B
- @scroll-tech/contracts/L1/IL1ScrollMessenger.sol2.9 KB
- @scroll-tech/contracts/libraries/IScrollMessenger.sol2.79 KB
- contracts/common/DepositLib.sol1.42 KB
- contracts/common/WithdrawalLib.sol1.36 KB
- contracts/contribution/IContribution.sol2.76 KB
- contracts/liquidity/ILiquidity.sol14.48 KB
- contracts/liquidity/ITokenData.sol2.82 KB
- contracts/liquidity/TokenData.sol5.96 KB
- contracts/liquidity/lib/DepositLimit.sol4.66 KB
- contracts/liquidity/lib/DepositQueueLib.sol4.45 KB
- contracts/liquidity/lib/ERC20CallOptionalLib.sol1.43 KB
- contracts/permitter/IPermitter.sol1.07 KB
- contracts/rollup/IRollup.sol8.91 KB
contracts/liquidity/Liquidity.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;
/**
* @title Liquidity Contract
* @notice This contract manages deposits and withdrawals of various token types (Native, ERC20, ERC721, ERC1155).
* @dev Handles deposit queuing, withdrawal processing, fee collection, and AML/eligibility checks.
*/
import {ILiquidity} from "./ILiquidity.sol";
import {IRollup} from "../rollup/IRollup.sol";
import {IContribution} from "../contribution/IContribution.sol";
import {IPermitter} from "../permitter/IPermitter.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {IL1ScrollMessenger} from "@scroll-tech/contracts/L1/IL1ScrollMessenger.sol";
import {TokenData} from "./TokenData.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {DepositLib} from "../common/DepositLib.sol";
import {WithdrawalLib} from "../common/WithdrawalLib.sol";
import {DepositQueueLib} from "./lib/DepositQueueLib.sol";
import {ERC20CallOptionalLib} from "./lib/ERC20CallOptionalLib.sol";
import {DepositLimit} from "./lib/DepositLimit.sol";
contract Liquidity is
TokenData,
PausableUpgradeable,
UUPSUpgradeable,
AccessControlUpgradeable,
ILiquidity
{
using SafeERC20 for IERC20;
using ERC20CallOptionalLib for IERC20;
using DepositLib for DepositLib.Deposit;
using WithdrawalLib for WithdrawalLib.Withdrawal;
using DepositQueueLib for DepositQueueLib.DepositQueue;
/// @notice Relayer role constant
bytes32 public constant RELAYER = keccak256("RELAYER");
/// @notice Withdrawal role constant
bytes32 public constant WITHDRAWAL = keccak256("WITHDRAWAL");
/// @notice Withdrawal fee ratio limit
/// @dev 1bp = 0.01%
uint256 public constant WITHDRAWAL_FEE_RATIO_LIMIT = 1500;
/// @notice Maximum number of deposits that can be relayed in a single transaction
/// @dev This limit prevents situations where too many deposits are relayed to L2 simultaneously,
/// @dev which could exceed the L2 block gas limit and cause transaction failures.
uint256 public constant RELAY_LIMIT = 450;
/// @notice Deployment time which is used to calculate the deposit limit
uint256 public deploymentTime;
/// @notice Address of the L1 ScrollMessenger contract
IL1ScrollMessenger public l1ScrollMessenger;
/// @notice Address of the Contribution contract
IContribution public contribution;
/// @notice Address of the Rollup contract
address public rollup;
/// @notice Address of the AML Permitter contract
/// @dev If not set, we skip AML check
IPermitter public amlPermitter;
/// @notice Address of the Circulation Permitter contract
/// @dev If not set, we skip eligibility permission check
IPermitter public eligibilityPermitter;
/// @notice Mapping of withdrawal hashes to their timestamp when they became claimable
/// @dev A value of 0 means the withdrawal is not claimable
mapping(bytes32 => uint256) public claimableWithdrawals;
/// @notice Withdrawal fee ratio for each token index
/// @dev 1bp = 0.01%
mapping(uint32 => uint256) public withdrawalFeeRatio;
/// @notice Mapping of token index to the total amount of withdrawal fees collected
/// @dev Used to track fees that can be withdrawn by the admin
mapping(uint32 => uint256) public collectedWithdrawalFees;
/// @notice Mapping of deposit hashes to a boolean indicating whether the deposit hash exists
/// @dev Used to prevent duplicate deposits with the same parameters
mapping(bytes32 => bool) public doesDepositHashExist;
/// @notice Deposit information queue that tracks all deposits
/// @dev Used to manage the order and state of deposits
DepositQueueLib.DepositQueue private depositQueue;
/**
* @notice Modifier to restrict access to only the withdrawal role through the L1ScrollMessenger
* @dev Ensures the function is called via the L1ScrollMessenger and the cross-domain sender has the WITHDRAWAL role
*/
modifier onlyWithdrawalRole() {
IL1ScrollMessenger l1ScrollMessengerCached = l1ScrollMessenger;
if (_msgSender() != address(l1ScrollMessengerCached)) {
revert SenderIsNotScrollMessenger();
}
if (
!hasRole(WITHDRAWAL, l1ScrollMessengerCached.xDomainMessageSender())
) {
revert InvalidWithdrawalAddress();
}
_;
}
/**
* @notice Modifier to check if a deposit can be canceled
* @dev Verifies the caller is the original sender, the deposit hash matches, and the deposit hasn't been relayed
* @param depositId The ID of the deposit to cancel
* @param deposit The deposit data structure
*/
modifier canCancelDeposit(
uint256 depositId,
DepositLib.Deposit memory deposit
) {
DepositQueueLib.DepositData memory depositData = depositQueue
.depositData[depositId];
if (depositData.sender != _msgSender()) {
revert OnlySenderCanCancelDeposit();
}
bytes32 depositHash = deposit.getHash();
if (depositData.depositHash != depositHash) {
revert InvalidDepositHash(depositData.depositHash, depositHash);
}
if (depositId <= getLastRelayedDepositId()) {
revert AlreadyRelayed();
}
_;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/// @notice Initializes the contract with required addresses and parameters
/// @param _admin The address that will have admin privileges
/// @param _l1ScrollMessenger The address of the L1ScrollMessenger contract
/// @param _rollup The address of the Rollup contract
/// @param _withdrawal The address that will have withdrawal privileges
/// @param _claim The address that will have claim privileges
/// @param _relayer The address that will have relayer privileges
/// @param _contribution The address of the Contribution contract
/// @param initialERC20Tokens Initial list of ERC20 token addresses to support
function initialize(
address _admin,
address _l1ScrollMessenger,
address _rollup,
address _withdrawal,
address _claim,
address _relayer,
address _contribution,
address[] memory initialERC20Tokens
) external initializer {
if (
_admin == address(0) ||
_l1ScrollMessenger == address(0) ||
_rollup == address(0) ||
_withdrawal == address(0) ||
_claim == address(0) ||
_relayer == address(0) ||
_contribution == address(0)
) {
revert AddressZero();
}
_grantRole(DEFAULT_ADMIN_ROLE, _admin);
_grantRole(RELAYER, _relayer);
_grantRole(WITHDRAWAL, _withdrawal);
_grantRole(WITHDRAWAL, _claim);
__UUPSUpgradeable_init();
__AccessControl_init();
__TokenData_init(initialERC20Tokens);
__Pausable_init();
depositQueue.initialize();
l1ScrollMessenger = IL1ScrollMessenger(_l1ScrollMessenger);
contribution = IContribution(_contribution);
rollup = _rollup;
// Set deployment time to the next day
deploymentTime = (block.timestamp / 1 days + 1) * 1 days;
}
/**
* @notice Sets the AML and eligibility permitter contract addresses
* @dev Only callable by the admin role
* @param _amlPermitter The address of the AML permitter contract
* @param _eligibilityPermitter The address of the eligibility permitter contract
*/
function setPermitter(
address _amlPermitter,
address _eligibilityPermitter
) external onlyRole(DEFAULT_ADMIN_ROLE) {
amlPermitter = IPermitter(_amlPermitter);
eligibilityPermitter = IPermitter(_eligibilityPermitter);
emit PermitterSet(_amlPermitter, _eligibilityPermitter);
}
/**
* @notice Sets the withdrawal fee ratio for a specific token
* @dev Only callable by the admin role. Fee ratio is in basis points (1bp = 0.01%)
* @param tokenIndex The index of the token to set the fee ratio for
* @param feeRatio The fee ratio to set (in basis points, max 1500 = 15%)
*/
function setWithdrawalFeeRatio(
uint32 tokenIndex,
uint256 feeRatio
) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (feeRatio > WITHDRAWAL_FEE_RATIO_LIMIT) {
revert WithdrawalFeeRatioExceedsLimit();
}
withdrawalFeeRatio[tokenIndex] = feeRatio;
emit WithdrawalFeeRatioSet(tokenIndex, feeRatio);
}
/**
* @notice Withdraws collected fees for specified tokens to a recipient address
* @dev Only callable by the admin role. Skips tokens with zero fees
* @param recipient The address to receive the withdrawn fees
* @param tokenIndices Array of token indices to withdraw fees for
*/
function withdrawCollectedFees(
address recipient,
uint32[] calldata tokenIndices
) external onlyRole(DEFAULT_ADMIN_ROLE) {
for (uint256 i = 0; i < tokenIndices.length; i++) {
uint32 tokenIndex = tokenIndices[i];
uint256 fee = collectedWithdrawalFees[tokenIndex];
if (fee == 0) {
continue;
}
collectedWithdrawalFees[tokenIndex] = 0;
TokenInfo memory tokenInfo = getTokenInfo(tokenIndex);
_sendToken(
tokenInfo.tokenType,
tokenInfo.tokenAddress,
recipient,
fee,
tokenInfo.tokenId
);
emit WithdrawalFeeWithdrawn(recipient, tokenIndex, fee);
}
}
/**
* @notice Pauses all deposit operations
* @dev Only callable by the admin role
*/
function pauseDeposits() external onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
/**
* @notice Unpauses all deposit operations
* @dev Only callable by the admin role
*/
function unpauseDeposits() external onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
function depositNativeToken(
bytes32 recipientSaltHash,
bytes calldata amlPermission,
bytes calldata eligibilityPermission
) external payable whenNotPaused {
if (msg.value == 0) {
revert TriedToDepositZero();
}
uint32 tokenIndex = getNativeTokenIndex();
bytes memory encodedData = abi.encodeWithSignature(
"depositNativeToken(bytes32)",
recipientSaltHash
);
_deposit(
_msgSender(),
recipientSaltHash,
tokenIndex,
msg.value,
encodedData,
amlPermission,
eligibilityPermission
);
}
function depositERC20(
address tokenAddress,
bytes32 recipientSaltHash,
uint256 amount,
bytes calldata amlPermission,
bytes calldata eligibilityPermission
) external whenNotPaused {
if (amount == 0) {
revert TriedToDepositZero();
}
IERC20(tokenAddress).safeTransferFrom(
_msgSender(),
address(this),
amount
);
uint32 tokenIndex = _getOrCreateTokenIndex(
TokenType.ERC20,
tokenAddress,
0
);
bytes memory encodedData = abi.encodeWithSignature(
"depositERC20(address,bytes32,uint256)",
tokenAddress,
recipientSaltHash,
amount
);
_deposit(
_msgSender(),
recipientSaltHash,
tokenIndex,
amount,
encodedData,
amlPermission,
eligibilityPermission
);
}
function depositERC721(
address tokenAddress,
bytes32 recipientSaltHash,
uint256 tokenId,
bytes calldata amlPermission,
bytes calldata eligibilityPermission
) external whenNotPaused {
IERC721(tokenAddress).transferFrom(
_msgSender(),
address(this),
tokenId
);
uint32 tokenIndex = _getOrCreateTokenIndex(
TokenType.ERC721,
tokenAddress,
tokenId
);
bytes memory encodedData = abi.encodeWithSignature(
"depositERC721(address,bytes32,uint256)",
tokenAddress,
recipientSaltHash,
tokenId
);
_deposit(
_msgSender(),
recipientSaltHash,
tokenIndex,
1,
encodedData,
amlPermission,
eligibilityPermission
);
}
function depositERC1155(
address tokenAddress,
bytes32 recipientSaltHash,
uint256 tokenId,
uint256 amount,
bytes calldata amlPermission,
bytes calldata eligibilityPermission
) external whenNotPaused {
if (amount == 0) {
revert TriedToDepositZero();
}
IERC1155(tokenAddress).safeTransferFrom(
_msgSender(),
address(this),
tokenId,
amount,
bytes("")
);
uint32 tokenIndex = _getOrCreateTokenIndex(
TokenType.ERC1155,
tokenAddress,
tokenId
);
bytes memory encodedData = abi.encodeWithSignature(
"depositERC1155(address,bytes32,uint256,uint256)",
tokenAddress,
recipientSaltHash,
tokenId,
amount
);
_deposit(
_msgSender(),
recipientSaltHash,
tokenIndex,
amount,
encodedData,
amlPermission,
eligibilityPermission
);
}
function relayDeposits(
uint256 upToDepositId,
uint256 gasLimit
) external payable onlyRole(RELAYER) {
bytes32[] memory depositHashes = depositQueue.batchDequeue(
upToDepositId
);
if (depositHashes.length > RELAY_LIMIT) {
revert RelayLimitExceeded();
}
bytes memory message = abi.encodeWithSelector(
IRollup.processDeposits.selector,
upToDepositId,
depositHashes
);
l1ScrollMessenger.sendMessage{value: msg.value}(
rollup,
0,
message,
gasLimit,
_msgSender()
);
emit DepositsRelayed(upToDepositId, gasLimit, message);
}
function claimWithdrawals(
WithdrawalLib.Withdrawal[] calldata withdrawals
) external {
for (uint256 i = 0; i < withdrawals.length; i++) {
WithdrawalLib.Withdrawal memory w = withdrawals[i];
bytes32 withdrawalHash = w.getHash();
if (claimableWithdrawals[withdrawalHash] == 0) {
revert WithdrawalNotFound(withdrawalHash);
}
uint256 fee = _getWithdrawalFee(w.tokenIndex, w.amount);
uint256 amountAfterFee = w.amount - fee;
TokenInfo memory tokenInfo = getTokenInfo(w.tokenIndex);
delete claimableWithdrawals[withdrawalHash];
_sendToken(
tokenInfo.tokenType,
tokenInfo.tokenAddress,
w.recipient,
amountAfterFee,
tokenInfo.tokenId
);
emit ClaimedWithdrawal(w.recipient, withdrawalHash);
if (fee > 0) {
collectedWithdrawalFees[w.tokenIndex] += fee;
emit WithdrawalFeeCollected(w.tokenIndex, fee);
}
}
}
function cancelDeposit(
uint256 depositId,
DepositLib.Deposit calldata deposit
) external canCancelDeposit(depositId, deposit) {
DepositQueueLib.DepositData memory depositData = depositQueue
.deleteDeposit(depositId);
TokenInfo memory tokenInfo = getTokenInfo(deposit.tokenIndex);
_sendToken(
tokenInfo.tokenType,
tokenInfo.tokenAddress,
depositData.sender,
deposit.amount,
tokenInfo.tokenId
);
emit DepositCanceled(depositId);
}
/**
* @notice Internal function to handle the deposit process for all token types
* @dev Validates permissions, checks deposit limits, creates deposit hash, and enqueues the deposit
* @param sender The address making the deposit
* @param recipientSaltHash The hash of the recipient's address and a secret salt
* @param tokenIndex The index of the token being deposited
* @param amount The amount of tokens being deposited
* @param encodedData The encoded function call data for permission validation
* @param amlPermission The data to verify AML check
* @param eligibilityPermission The data to verify eligibility check
*/
function _deposit(
address sender,
bytes32 recipientSaltHash,
uint32 tokenIndex,
uint256 amount,
bytes memory encodedData,
bytes memory amlPermission,
bytes memory eligibilityPermission
) private {
_validateAmlPermission(encodedData, amlPermission);
bool isEligible = _validateEligibilityPermission(
encodedData,
eligibilityPermission
);
uint256 depositLimit = DepositLimit.getDepositLimit(
tokenIndex,
deploymentTime
);
if (amount > depositLimit) {
revert DepositAmountExceedsLimit(amount, depositLimit);
}
bytes32 depositHash = DepositLib
.Deposit(sender, recipientSaltHash, amount, tokenIndex, isEligible)
.getHash();
if (doesDepositHashExist[depositHash]) {
revert DepositHashAlreadyExists(depositHash);
}
doesDepositHashExist[depositHash] = true;
uint256 depositId = depositQueue.enqueue(depositHash, sender);
emit Deposited(
depositId,
sender,
recipientSaltHash,
tokenIndex,
amount,
isEligible,
block.timestamp
);
}
/**
* @notice Internal function to send tokens to a recipient
* @dev Handles different token types (Native, ERC20, ERC721, ERC1155)
* @param tokenType The type of token to send
* @param token The token contract address (not used for native tokens)
* @param recipient The address to receive the tokens
* @param amount The amount of tokens to send
* @param tokenId The token ID (used for ERC721 and ERC1155)
*/
function _sendToken(
TokenType tokenType,
address token,
address recipient,
uint256 amount,
uint256 tokenId
) private {
if (tokenType == TokenType.NATIVE) {
payable(recipient).transfer(amount);
} else if (tokenType == TokenType.ERC20) {
IERC20(token).safeTransfer(recipient, amount);
} else if (tokenType == TokenType.ERC721) {
IERC721(token).transferFrom(address(this), recipient, tokenId);
} else {
IERC1155(token).safeTransferFrom(
address(this),
recipient,
tokenId,
amount,
bytes("")
);
}
}
/**
* @notice Processes both direct withdrawals and claimable withdrawals
* @dev Only callable by addresses with the WITHDRAWAL role through the L1ScrollMessenger
* @param withdrawals Array of direct withdrawals to process
* @param withdrawalHashes Array of withdrawal hashes to mark as claimable
*/
function processWithdrawals(
WithdrawalLib.Withdrawal[] calldata withdrawals,
bytes32[] calldata withdrawalHashes
) external onlyWithdrawalRole {
_processDirectWithdrawals(withdrawals);
_processClaimableWithdrawals(withdrawalHashes);
}
/**
* @notice Processes direct withdrawals that can be sent directly to recipients
* @dev Attempts to send tokens directly to recipients, records contributions for gas payers
* @param withdrawals Array of withdrawals to process directly
*/
function _processDirectWithdrawals(
WithdrawalLib.Withdrawal[] calldata withdrawals
) private {
for (uint256 i = 0; i < withdrawals.length; i++) {
_processDirectWithdrawal(withdrawals[i]);
}
if (withdrawals.length > 0) {
// In the ScrollMessenger, it is not possible to identify the person who relayed the message.
// Here we consider tx.origin as the gas payer and record their contribution accordingly.
// However, this approach can be problematic in cases of sponsored transactions or meta transactions,
// where the actual gas payer may differ from tx.origin.
contribution.recordContribution(
keccak256("PROCESS_DIRECT_WITHDRAWALS"),
// solhint-disable-next-line avoid-tx-origin
tx.origin, // msg.sender is ScrollMessenger, so we use tx.origin
withdrawals.length
);
}
}
/**
* @notice Processes a single direct withdrawal
* @dev Attempts to send tokens directly to the recipient, collects fees, and handles failures
* @param withdrawal_ The withdrawal to process
*/
function _processDirectWithdrawal(
WithdrawalLib.Withdrawal memory withdrawal_
) internal {
TokenInfo memory tokenInfo = getTokenInfo(withdrawal_.tokenIndex);
uint256 fee = _getWithdrawalFee(
withdrawal_.tokenIndex,
withdrawal_.amount
);
uint256 amountAfterFee = withdrawal_.amount - fee;
bool result = true;
if (tokenInfo.tokenType == TokenType.NATIVE) {
// solhint-disable-next-line check-send-result
bool success = payable(withdrawal_.recipient).send(amountAfterFee);
result = success;
} else if (tokenInfo.tokenType == TokenType.ERC20) {
bytes memory transferCall = abi.encodeWithSelector(
IERC20(tokenInfo.tokenAddress).transfer.selector,
withdrawal_.recipient,
amountAfterFee
);
result = IERC20(tokenInfo.tokenAddress).callOptionalReturnBool(
transferCall
);
} else {
// ERC721 and ERC1155 tokens are not supported for direct withdrawals
result = false;
}
if (result) {
emit DirectWithdrawalSuccessed(
withdrawal_.getHash(),
withdrawal_.recipient
);
if (fee > 0) {
// solhint-disable-next-line reentrancy
collectedWithdrawalFees[withdrawal_.tokenIndex] += fee;
emit WithdrawalFeeCollected(withdrawal_.tokenIndex, fee);
}
} else {
bytes32 withdrawalHash = withdrawal_.getHash();
// solhint-disable-next-line reentrancy
claimableWithdrawals[withdrawalHash] = block.timestamp;
emit DirectWithdrawalFailed(withdrawalHash, withdrawal_);
emit WithdrawalClaimable(withdrawalHash);
}
}
/**
* @notice Marks withdrawals as claimable
* @dev Sets the timestamp when withdrawals became claimable and records contributions
* @param withdrawalHashes Array of withdrawal hashes to mark as claimable
*/
function _processClaimableWithdrawals(
bytes32[] calldata withdrawalHashes
) private {
for (uint256 i = 0; i < withdrawalHashes.length; i++) {
claimableWithdrawals[withdrawalHashes[i]] = block.timestamp;
emit WithdrawalClaimable(withdrawalHashes[i]);
}
if (withdrawalHashes.length > 0) {
contribution.recordContribution(
keccak256("PROCESS_CLAIMABLE_WITHDRAWALS"),
// solhint-disable-next-line avoid-tx-origin
tx.origin, // msg.sender is ScrollMessenger, so we use tx.origin
withdrawalHashes.length
);
}
}
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) external pure returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @notice Validates the AML permission for a deposit
* @dev Skips validation if no AML permitter is set
* @param encodedData The encoded function call data
* @param amlPermission The data to verify AML check
*/
function _validateAmlPermission(
bytes memory encodedData,
bytes memory amlPermission
) private {
IPermitter amlPermitterCached = amlPermitter;
if (address(amlPermitterCached) == address(0)) {
// if aml permitter is not set, skip aml check
return;
}
bool result = amlPermitterCached.permit(
_msgSender(),
msg.value,
encodedData,
amlPermission
);
if (!result) {
revert AmlValidationFailed();
}
return;
}
/**
* @notice Validates the eligibility permission for a deposit
* @dev Skips validation if no eligibility permitter is set
* @param encodedData The encoded function call data
* @param eligibilityPermission The data to verify eligibility check
* @return bool True if the deposit is eligible, false otherwise
*/
function _validateEligibilityPermission(
bytes memory encodedData,
bytes memory eligibilityPermission
) private returns (bool) {
IPermitter eligibilityPermitterCached = eligibilityPermitter;
if (address(eligibilityPermitterCached) == address(0)) {
// if eligibility permitter is not set, skip eligibility check
return true;
}
if (eligibilityPermission.length == 0) {
// if eligibility permitter is set but permission doesn't returned, return false.
return false;
}
bool result = eligibilityPermitterCached.permit(
_msgSender(),
msg.value,
encodedData,
eligibilityPermission
);
if (!result) {
revert EligibilityValidationFailed();
}
return true;
}
/**
* @notice Calculates the withdrawal fee for a given token and amount
* @dev Fee is calculated as (amount * feeRatio) / 10000
* @param tokenIndex The index of the token
* @param amount The amount being withdrawn
* @return uint256 The calculated fee amount
*/
function _getWithdrawalFee(
uint32 tokenIndex,
uint256 amount
) private view returns (uint256) {
uint256 feeRatio = withdrawalFeeRatio[tokenIndex];
return (amount * feeRatio) / 10000;
}
function isDepositValid(
uint256 depositId,
bytes32 recipientSaltHash,
uint32 tokenIndex,
uint256 amount,
bool isEligible,
address sender
) external view returns (bool) {
DepositQueueLib.DepositData memory depositData = depositQueue
.depositData[depositId];
bytes32 depositHash = DepositLib
.Deposit(sender, recipientSaltHash, amount, tokenIndex, isEligible)
.getHash();
if (depositData.depositHash != depositHash) {
return false;
}
if (depositData.sender != sender) {
return false;
}
return true;
}
function getDepositData(
uint256 depositId
) external view returns (DepositQueueLib.DepositData memory) {
return depositQueue.depositData[depositId];
}
function getDepositDataBatch(
uint256[] memory depositIds
) external view returns (DepositQueueLib.DepositData[] memory) {
DepositQueueLib.DepositData[]
memory depositData = new DepositQueueLib.DepositData[](
depositIds.length
);
for (uint256 i = 0; i < depositIds.length; i++) {
depositData[i] = depositQueue.depositData[depositIds[i]];
}
return depositData;
}
function getDepositDataHash(
uint256 depositId
) external view returns (bytes32) {
return depositQueue.depositData[depositId].depositHash;
}
function getLastRelayedDepositId() public view returns (uint256) {
return depositQueue.front - 1;
}
function getLastDepositId() external view returns (uint256) {
return depositQueue.depositData.length - 1;
}
/**
* @notice Authorizes an upgrade to the implementation
* @dev Only callable by the admin role
* @param newImplementation The address of the new implementation
*/
function _authorizeUpgrade(
address newImplementation
) internal override onlyRole(DEFAULT_ADMIN_ROLE) {}
}
@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
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.
* See {_onlyProxy}.
*/
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/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}
@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
@openzeppelin/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
@openzeppelin/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
@openzeppelin/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
@openzeppelin/contracts/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
@openzeppelin/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
@openzeppelin/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* 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.
*/
function proxiableUUID() external view returns (bytes32);
}
@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
@openzeppelin/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
@openzeppelin/contracts/token/ERC1155/IERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[ERC].
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the value of tokens of token type `id` owned by `account`.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] calldata accounts,
uint256[] calldata ids
) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the zero address.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.
*
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
* to an untrusted contract, when invoking {onERC1155Received} on the receiver.
* Ensure to follow the checks-effects-interactions pattern and consider employing
* reentrancy guards when interacting with untrusted contracts.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `value` amount.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
* to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver.
* Ensure to follow the checks-effects-interactions pattern and consider employing
* reentrancy guards when interacting with untrusted contracts.
*
* Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
*
* Requirements:
*
* - `ids` and `values` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external;
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.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 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/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
@openzeppelin/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
@scroll-tech/contracts/L1/IL1ScrollMessenger.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IScrollMessenger} from "../libraries/IScrollMessenger.sol";
interface IL1ScrollMessenger is IScrollMessenger {
/**********
* Events *
**********/
/// @notice Emitted when the maximum number of times each message can be replayed is updated.
/// @param oldMaxReplayTimes The old maximum number of times each message can be replayed.
/// @param newMaxReplayTimes The new maximum number of times each message can be replayed.
event UpdateMaxReplayTimes(uint256 oldMaxReplayTimes, uint256 newMaxReplayTimes);
/***********
* Structs *
***********/
struct L2MessageProof {
// The index of the batch where the message belongs to.
uint256 batchIndex;
// Concatenation of merkle proof for withdraw merkle trie.
bytes merkleProof;
}
/*****************************
* Public Mutating Functions *
*****************************/
/// @notice Relay a L2 => L1 message with message proof.
/// @param from The address of the sender of the message.
/// @param to The address of the recipient of the message.
/// @param value The msg.value passed to the message call.
/// @param nonce The nonce of the message to avoid replay attack.
/// @param message The content of the message.
/// @param proof The proof used to verify the correctness of the transaction.
function relayMessageWithProof(
address from,
address to,
uint256 value,
uint256 nonce,
bytes memory message,
L2MessageProof memory proof
) external;
/// @notice Replay an existing message.
/// @param from The address of the sender of the message.
/// @param to The address of the recipient of the message.
/// @param value The msg.value passed to the message call.
/// @param messageNonce The nonce for the message to replay.
/// @param message The content of the message.
/// @param newGasLimit New gas limit to be used for this message.
/// @param refundAddress The address of account who will receive the refunded fee.
function replayMessage(
address from,
address to,
uint256 value,
uint256 messageNonce,
bytes memory message,
uint32 newGasLimit,
address refundAddress
) external payable;
/// @notice Drop a skipped message.
/// @param from The address of the sender of the message.
/// @param to The address of the recipient of the message.
/// @param value The msg.value passed to the message call.
/// @param messageNonce The nonce for the message to drop.
/// @param message The content of the message.
function dropMessage(
address from,
address to,
uint256 value,
uint256 messageNonce,
bytes memory message
) external;
}
@scroll-tech/contracts/libraries/IScrollMessenger.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface IScrollMessenger {
/**********
* Events *
**********/
/// @notice Emitted when a cross domain message is sent.
/// @param sender The address of the sender who initiates the message.
/// @param target The address of target contract to call.
/// @param value The amount of value passed to the target contract.
/// @param messageNonce The nonce of the message.
/// @param gasLimit The optional gas limit passed to L1 or L2.
/// @param message The calldata passed to the target contract.
event SentMessage(
address indexed sender,
address indexed target,
uint256 value,
uint256 messageNonce,
uint256 gasLimit,
bytes message
);
/// @notice Emitted when a cross domain message is relayed successfully.
/// @param messageHash The hash of the message.
event RelayedMessage(bytes32 indexed messageHash);
/// @notice Emitted when a cross domain message is failed to relay.
/// @param messageHash The hash of the message.
event FailedRelayedMessage(bytes32 indexed messageHash);
/**********
* Errors *
**********/
/// @dev Thrown when the given address is `address(0)`.
error ErrorZeroAddress();
/*************************
* Public View Functions *
*************************/
/// @notice Return the sender of a cross domain message.
function xDomainMessageSender() external view returns (address);
/*****************************
* Public Mutating Functions *
*****************************/
/// @notice Send cross chain message from L1 to L2 or L2 to L1.
/// @param target The address of account who receive the message.
/// @param value The amount of ether passed when call target contract.
/// @param message The content of the message.
/// @param gasLimit Gas limit required to complete the message relay on corresponding chain.
function sendMessage(
address target,
uint256 value,
bytes calldata message,
uint256 gasLimit
) external payable;
/// @notice Send cross chain message from L1 to L2 or L2 to L1.
/// @param target The address of account who receive the message.
/// @param value The amount of ether passed when call target contract.
/// @param message The content of the message.
/// @param gasLimit Gas limit required to complete the message relay on corresponding chain.
/// @param refundAddress The address of account who will receive the refunded fee.
function sendMessage(
address target,
uint256 value,
bytes calldata message,
uint256 gasLimit,
address refundAddress
) external payable;
}
contracts/common/DepositLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;
/**
* @title DepositLib
* @notice Library for handling deposit operations and data structures
* @dev Provides utilities for working with deposits in the Intmax2 protocol
*/
library DepositLib {
/**
* @notice Represents a deposit in the Deposit tree
* @dev This struct is used as a leaf in the Deposit Merkle tree
* @param depositor The address of the depositor (L1 address)
* @param recipientSaltHash The hash of the recipient's intmax2 address and a private salt
* @param amount The amount of tokens being deposited
* @param tokenIndex The index of the token being deposited
* @param isEligible Whether the deposit is eligible for mining rewards
*/
struct Deposit {
address depositor;
bytes32 recipientSaltHash;
uint256 amount;
uint32 tokenIndex;
bool isEligible;
}
/**
* @notice Calculates the hash of a Deposit struct
* @dev Uses keccak256 to hash the packed encoding of all deposit fields
* @param deposit The Deposit struct to be hashed
* @return bytes32 The calculated hash of the Deposit, used as a leaf in the Deposit tree
*/
function getHash(Deposit memory deposit) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
deposit.depositor,
deposit.recipientSaltHash,
deposit.amount,
deposit.tokenIndex,
uint32(deposit.isEligible ? 1 : 0)
)
);
}
}
contracts/common/WithdrawalLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;
/**
* @title WithdrawalLib
* @notice Library for handling withdrawal operations and data structures
* @dev Provides utilities for working with withdrawals in the Intmax2 protocol
*/
library WithdrawalLib {
/**
* @notice Represents a withdrawal operation in the Intmax2 protocol
* @dev Contains all necessary information to process a withdrawal from L2 to L1
* @param recipient The L1 address of the recipient of the withdrawal
* @param tokenIndex The index of the token being withdrawn
* @param amount The amount of tokens being withdrawn
* @param nullifier A unique identifier to prevent double-spending, derived from the withdrawal note
*/
struct Withdrawal {
address recipient;
uint32 tokenIndex;
uint256 amount;
bytes32 nullifier;
}
/**
* @notice Calculates the hash of a Withdrawal struct
* @dev Uses keccak256 to hash the packed encoding of all withdrawal fields
* @param withdrawal The Withdrawal struct to be hashed
* @return bytes32 The calculated hash of the Withdrawal, used for verification
*/
function getHash(
Withdrawal memory withdrawal
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
withdrawal.recipient,
withdrawal.tokenIndex,
withdrawal.amount,
withdrawal.nullifier
)
);
}
}
contracts/contribution/IContribution.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;
/**
* @title IContribution
* @notice Interface for the Contribution contract that tracks user contributions across different periods
* @dev This interface defines the methods and events for recording and querying contributions
*/
interface IContribution {
/**
* @notice Error thrown when attempting to initialize with a zero period interval
* @dev This error is used to prevent invalid period configurations
*/
error PeriodIntervalZero();
/**
* @notice Emitted when a contribution is recorded
* @param periodNumber The number of the period when the contribution was recorded
* @param tag The tag associated with the contribution (used for categorization)
* @param user The address of the user making the contribution
* @param amount The amount of the contribution
*/
event ContributionRecorded(
uint256 indexed periodNumber,
bytes32 indexed tag,
address indexed user,
uint256 amount
);
/**
* @notice Gets the current period number based on the current timestamp
* @dev Calculated as (current_timestamp - start_timestamp) / period_interval
* @return The current period number
*/
function getCurrentPeriod() external view returns (uint256);
/**
* @notice Records a contribution for a specific tag and user
* @dev Can only be called by addresses with the CONTRIBUTOR role
* @param tag The tag associated with the contribution (used for categorization)
* @param user The address of the user making the contribution
* @param amount The amount of contribution to record
*/
function recordContribution(
bytes32 tag,
address user,
uint256 amount
) external;
/**
* @notice Returns the total contribution for a specific tag in the specified period
* @dev Aggregates all user contributions for the given tag and period
* @param period The period number for which the contribution is being queried
* @param tag The tag (as bytes32) for which the contribution is being queried
* @return The total contribution amount for the specified period and tag
*/
function totalContributions(
uint256 period,
bytes32 tag
) external view returns (uint256);
/**
* @notice Returns the contribution of a specific user for a tag in the specified period
* @dev Retrieves individual user contribution data
* @param period The period number for which the contribution is being queried
* @param tag The tag (as bytes32) for which the contribution is being queried
* @param user The address of the user whose contribution is being queried
* @return The contribution amount for the specified user, period, and tag
*/
function userContributions(
uint256 period,
bytes32 tag,
address user
) external view returns (uint256);
}
contracts/liquidity/ILiquidity.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;
import {DepositLib} from "../common/DepositLib.sol";
import {WithdrawalLib} from "../common/WithdrawalLib.sol";
import {DepositQueueLib} from "./lib/DepositQueueLib.sol";
/**
* @title Liquidity Interface
* @notice Interface for the Liquidity contract that manages deposits and withdrawals of various token types
* between Layer 1 and Layer 2 in the Intmax2 protocol
*/
interface ILiquidity {
/**
* @notice address is zero address
*/
error AddressZero();
/**
* @notice Error thrown when someone other than the original depositor tries to cancel a deposit
*/
error OnlySenderCanCancelDeposit();
/**
* @notice Error thrown when the provided deposit hash doesn't match the calculated hash during cancellation
* @param depositDataHash The hash from the deposit data
* @param calculatedHash The hash calculated from given input
*/
error InvalidDepositHash(bytes32 depositDataHash, bytes32 calculatedHash);
/**
* @notice Error thrown when the sender is not the Scroll Messenger in onlyWithdrawal context
*/
error SenderIsNotScrollMessenger();
/**
* @notice Error thrown when the withdrawal contract address is not set
*/
error WithdrawalAddressNotSet();
/**
* @notice Error thrown when the xDomainMessageSender of the Scroll Messenger doesn't match the withdrawal contract address
*/
error InvalidWithdrawalAddress();
/**
* @notice Error thrown when trying to claim a non-existent withdrawal
* @param withdrawalHash The hash of the withdrawal that wasn't found
*/
error WithdrawalNotFound(bytes32 withdrawalHash);
/**
* @notice Error thrown when trying to deposit zero amount of native/ERC20/ERC1155 tokens
*/
error TriedToDepositZero();
/**
* @notice Error thrown when already relayed deposits
*/
error AlreadyRelayed();
/**
* @notice Error thrown when the relayer tries to relay deposits that exceed the limit
* @dev Prevent relaying too many deposits to L2 and causing transaction failures on L2
*/
error RelayLimitExceeded();
/**
* @notice Error thrown when the deposit hash already exists
* @dev Used to prevent duplicate deposits with the same parameters
*/
error DepositHashAlreadyExists(bytes32 depositHash);
/**
* @notice Error thrown when the deposit amount exceeds the limit
* @param depositAmount The amount that was attempted to be deposited
* @param limit The maximum allowed deposit amount
*/
error DepositAmountExceedsLimit(uint256 depositAmount, uint256 limit);
/**
* @notice Error thrown when AML validation fails
*/
error AmlValidationFailed();
/**
* @notice Error thrown when eligibility validation fails
*/
error EligibilityValidationFailed();
/**
* @notice Error thrown when the admin tries to set fee more than WITHDRAWAL_FEE_RATIO_LIMIT
*/
error WithdrawalFeeRatioExceedsLimit();
/**
* @notice Event emitted when a deposit is made
* @param depositId The unique identifier for the deposit
* @param sender The address that made the deposit
* @param recipientSaltHash The hash of the recipient's intmax2 address (BLS public key) and a secret salt
* @param tokenIndex The index of the token being deposited
* @param amount The amount of tokens deposited
* @param isEligible if true, the deposit is eligible
* @param depositedAt The timestamp of the deposit
*/
event Deposited(
uint256 indexed depositId,
address indexed sender,
bytes32 indexed recipientSaltHash,
uint32 tokenIndex,
uint256 amount,
bool isEligible,
uint256 depositedAt
);
/**
* @notice Event emitted when deposits are relayed
* @param upToDepositId The highest deposit ID that was relayed
* @param gasLimit The gas limit for the L2 transaction
* @param message Additional message data
*/
event DepositsRelayed(
uint256 indexed upToDepositId,
uint256 gasLimit,
bytes message
);
/**
* @notice Event emitted when a deposit is canceled
* @param depositId The ID of the canceled deposit
*/
event DepositCanceled(uint256 indexed depositId);
/**
* @notice Event emitted when a withdrawal becomes claimable
* @param withdrawalHash The hash of the claimable withdrawal
*/
event WithdrawalClaimable(bytes32 indexed withdrawalHash);
/**
* @notice Event emitted when a direct withdrawal succeeds
* @param withdrawalHash The hash of the successful withdrawal
* @param recipient The address that received the withdrawal
*/
event DirectWithdrawalSuccessed(
bytes32 indexed withdrawalHash,
address indexed recipient
);
/**
* @notice Event emitted when a direct withdrawal fails, and the funds become claimable
* @param withdrawalHash The hash of the failed withdrawal
* @param withdrawal The withdrawal data
*/
event DirectWithdrawalFailed(
bytes32 indexed withdrawalHash,
WithdrawalLib.Withdrawal withdrawal
);
/**
* @notice Event emitted when a withdrawal is claimed
* @param recipient The address that claimed the withdrawal
* @param withdrawalHash The hash of the claimed withdrawal
*/
event ClaimedWithdrawal(
address indexed recipient,
bytes32 indexed withdrawalHash
);
/**
* @notice Event emitted when withdrawal fee is collected
* @param token The index of the token
* @param amount The amount of tokens collected
*/
event WithdrawalFeeCollected(uint32 indexed token, uint256 amount);
/**
* @notice Event emitted when withdrawal fee are withdrawn
* @param recipient The address that claimed the fees
* @param token The index of the token
* @param amount The amount of tokens claimed
*/
event WithdrawalFeeWithdrawn(
address indexed recipient,
uint32 indexed token,
uint256 amount
);
/**
* @notice Event emitted when permitter addresses are set
* @param amlPermitter The address of the AML permitter contract
* @param eligibilityPermitter The address of the eligibility permitter contract
*/
event PermitterSet(
address indexed amlPermitter,
address indexed eligibilityPermitter
);
/**
* @notice Event emitted when the withdrawal fee ratio is set
* @param tokenIndex The index of the token
* @param feeRatio The withdrawal fee ratio for the token (in basis points)
*/
event WithdrawalFeeRatioSet(uint32 indexed tokenIndex, uint256 feeRatio);
/**
* @notice Pauses all deposit operations
* @dev Only callable by the admin role
*/
function pauseDeposits() external;
/**
* @notice Unpauses all deposit operations
* @dev Only callable by the admin role
*/
function unpauseDeposits() external;
/**
* @notice Sets the AML and eligibility permitter contract addresses
* @dev Only callable by the admin role
* @param _amlPermitter The address of the AML permitter contract
* @param _eligibilityPermitter The address of the eligibility permitter contract
*/
function setPermitter(
address _amlPermitter,
address _eligibilityPermitter
) external;
/**
* @notice Sets the withdrawal fee ratio for a specific token
* @dev Only callable by the admin role. Fee ratio is in basis points (1bp = 0.01%)
* @param tokenIndex The index of the token to set the fee ratio for
* @param feeRatio The fee ratio to set (in basis points, max 1500 = 15%)
*/
function setWithdrawalFeeRatio(
uint32 tokenIndex,
uint256 feeRatio
) external;
/**
* @notice Withdraws collected fees for specified tokens to a recipient address
* @dev Only callable by the admin role. Skips tokens with zero fees
* @param recipient The address to receive the withdrawn fees
* @param tokenIndices Array of token indices to withdraw fees for
*/
function withdrawCollectedFees(
address recipient,
uint32[] calldata tokenIndices
) external;
/**
* @notice Deposit native token (ETH) to Intmax
* @dev The deposit amount is taken from msg.value, recipientSaltHash is the Poseidon hash of the intmax2 address (32 bytes) and a secret salt
* @param recipientSaltHash The hash of the recipient's intmax2 address and a secret salt
* @param amlPermission The data to verify AML check
* @param eligibilityPermission The data to verify eligibility check
*/
function depositNativeToken(
bytes32 recipientSaltHash,
bytes calldata amlPermission,
bytes calldata eligibilityPermission
) external payable;
/**
* @notice Deposit a specified amount of ERC20 token to Intmax
* @dev Requires prior approval for this contract to spend the tokens
* @dev recipientSaltHash is the Poseidon hash of the intmax2 address (32 bytes) and a secret salt
* @param tokenAddress The address of the ERC20 token contract
* @param recipientSaltHash The hash of the recipient's address and a secret salt
* @param amount The amount of tokens to deposit
* @param amlPermission The data to verify AML check
* @param eligibilityPermission The data to verify eligibility check
*/
function depositERC20(
address tokenAddress,
bytes32 recipientSaltHash,
uint256 amount,
bytes calldata amlPermission,
bytes calldata eligibilityPermission
) external;
/**
* @notice Deposit an ERC721 token to Intmax
* @dev Requires prior approval for this contract to transfer the token
* @param tokenAddress The address of the ERC721 token contract
* @param recipientSaltHash The hash of the recipient's address and a secret salt
* @param tokenId The ID of the token to deposit
* @param amlPermission The data to verify AML check
* @param eligibilityPermission The data to verify eligibility check
*/
function depositERC721(
address tokenAddress,
bytes32 recipientSaltHash,
uint256 tokenId,
bytes calldata amlPermission,
bytes calldata eligibilityPermission
) external;
/**
* @notice Deposit a specified amount of ERC1155 tokens to Intmax
* @dev Requires prior approval for this contract to transfer the tokens
* @param tokenAddress The address of the ERC1155 token contract
* @param recipientSaltHash The hash of the recipient's address and a secret salt
* @param tokenId The ID of the token to deposit
* @param amount The amount of tokens to deposit
* @param amlPermission The data to verify AML check
* @param eligibilityPermission The data to verify eligibility check
*/
function depositERC1155(
address tokenAddress,
bytes32 recipientSaltHash,
uint256 tokenId,
uint256 amount,
bytes calldata amlPermission,
bytes calldata eligibilityPermission
) external;
/**
* @notice Relays deposits from Layer 1 to Intmax
* @dev Only callable by addresses with the RELAYER role. The msg.value is used to pay for the L2 gas
* @param upToDepositId The upper limit of the Deposit ID that will be relayed
* @param gasLimit The gas limit for the L2 transaction
*/
function relayDeposits(
uint256 upToDepositId,
uint256 gasLimit
) external payable;
/**
* @notice Cancels a deposit that hasn't been relayed yet
* @dev Only the original sender can cancel their deposit, and only if it hasn't been relayed
* @param depositId The ID of the deposit to cancel
* @param deposit The deposit data structure containing the original deposit details
*/
function cancelDeposit(
uint256 depositId,
DepositLib.Deposit calldata deposit
) external;
/**
* @notice Processes withdrawals from Layer 2 to Layer 1
* @dev Only callable by addresses with the WITHDRAWAL role through the L1ScrollMessenger
* @param withdrawals Array of direct withdrawals to process immediately
* @param withdrawalHashes Array of withdrawal hashes to mark as claimable (for non-direct withdrawals)
*/
function processWithdrawals(
WithdrawalLib.Withdrawal[] calldata withdrawals,
bytes32[] calldata withdrawalHashes
) external;
/**
* @notice Get the ID of the last deposit relayed to Layer 2
* @dev This ID represents the highest deposit that has been successfully relayed
* @return The ID of the last relayed deposit
*/
function getLastRelayedDepositId() external view returns (uint256);
/**
* @notice Get the ID of the last deposit made to Layer 2
* @dev This ID represents the highest deposit that has been created, whether relayed or not
* @return The ID of the last deposit
*/
function getLastDepositId() external view returns (uint256);
/**
* @notice Get deposit data for a given deposit ID
* @param depositId The ID of the deposit to query
* @return The deposit data structure containing sender and deposit hash
*/
function getDepositData(
uint256 depositId
) external view returns (DepositQueueLib.DepositData memory);
/**
* @notice Get deposit data for multiple deposit IDs in a single call
* @param depositIds Array of deposit IDs to query
* @return Array of deposit data structures corresponding to the requested IDs
*/
function getDepositDataBatch(
uint256[] memory depositIds
) external view returns (DepositQueueLib.DepositData[] memory);
/**
* @notice Get the deposit hash for a given deposit ID
* @param depositId The ID of the deposit to query
* @return The hash of the deposit data
*/
function getDepositDataHash(
uint256 depositId
) external view returns (bytes32);
/**
* @notice Claim withdrawals for tokens that couldn't be processed through direct withdrawals
* @dev Used for ERC721, ERC1155, or failed direct withdrawals of native/ERC20 tokens
* @param withdrawals Array of withdrawals to claim
*/
function claimWithdrawals(
WithdrawalLib.Withdrawal[] calldata withdrawals
) external;
/**
* @notice Check if a deposit is valid by comparing its parameters with stored data
* @param depositId The ID of the deposit to validate
* @param recipientSaltHash The hash of the recipient's intmax2 address and a secret salt
* @param tokenIndex The index of the token being deposited
* @param amount The amount of tokens deposited
* @param isEligible Whether the deposit is eligible for mining rewards
* @param sender The address that made the deposit
* @return True if the deposit is valid, false otherwise
*/
function isDepositValid(
uint256 depositId,
bytes32 recipientSaltHash,
uint32 tokenIndex,
uint256 amount,
bool isEligible,
address sender
) external view returns (bool);
/**
* @notice ERC1155 token receiver function required for this contract to receive ERC1155 tokens
* @dev Implements the IERC1155Receiver interface
* @return bytes4 The function selector to indicate support for ERC1155 token receiving
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) external pure returns (bytes4);
}
contracts/liquidity/ITokenData.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;
/**
* @title Token Data Interface
* @notice Interface for managing token information and indices in the Intmax2 protocol
* @dev Provides functions to store, retrieve, and manage different token types (Native, ERC20, ERC721, ERC1155)
*/
interface ITokenData {
/// @notice Error thrown when attempting to use a zero address for a non-native token
/// @dev Native tokens use address(0), but other token types must have a valid contract address
error TokenAddressIsZero();
/**
* @notice Enum representing different token types supported by the protocol
* @dev Used to determine how to handle each token type during deposits and withdrawals
*/
enum TokenType {
NATIVE, // ETH or native chain currency
ERC20, // Fungible tokens following the ERC20 standard
ERC721, // Non-fungible tokens following the ERC721 standard
ERC1155 // Semi-fungible tokens following the ERC1155 standard
}
/**
* @notice Struct containing information about a token
* @dev Used to store all necessary information to identify and handle a token
* @param tokenType The type of the token (NATIVE, ERC20, ERC721, ERC1155)
* @param tokenAddress The address of the token contract (zero address for native tokens)
* @param tokenId The ID of the token (used for ERC721 and ERC1155, ignored for NATIVE and ERC20)
*/
struct TokenInfo {
TokenType tokenType;
address tokenAddress;
uint256 tokenId;
}
/**
* @notice Retrieves token information for a given token index
* @dev Token indices are assigned sequentially as new tokens are added to the system
* @param tokenIndex The index of the token to retrieve information for
* @return TokenInfo struct containing the token's type, address, and ID
*/
function getTokenInfo(
uint32 tokenIndex
) external view returns (TokenInfo memory);
/**
* @notice Retrieves the token index for given token parameters
* @dev Used to look up a token's index based on its identifying information
* @param tokenType The type of the token (NATIVE, ERC20, ERC721, ERC1155)
* @param tokenAddress The address of the token contract (zero address for native tokens)
* @param tokenId The ID of the token (used for ERC721 and ERC1155, ignored for NATIVE and ERC20)
* @return bool Indicating whether the token index was found (true) or not (false)
* @return uint32 The index of the token if found, 0 if not found
*/
function getTokenIndex(
TokenType tokenType,
address tokenAddress,
uint256 tokenId
) external view returns (bool, uint32);
/**
* @notice Retrieves the index of the native token (ETH)
* @dev The native token is always at index 0 in the system
* @return uint32 The index of the native token (always 0)
*/
function getNativeTokenIndex() external view returns (uint32);
}
contracts/liquidity/TokenData.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;
import {ITokenData} from "./ITokenData.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @title Token Data Contract
* @notice Abstract contract for managing token information and indices in the Intmax2 protocol
* @dev Implements the ITokenData interface and provides storage and functionality for tracking
* different token types (Native, ERC20, ERC721, ERC1155)
*/
abstract contract TokenData is Initializable, ITokenData {
/**
* @notice Native currency (ETH) address constant
* @dev Used as a key in mappings to represent the native token
*/
address private constant NATIVE_CURRENCY_ADDRESS = address(0);
/**
* @notice Array of all token information stored in the system
* @dev Index in this array corresponds to the token index used throughout the protocol
*/
TokenInfo[] private tokenInfoList;
/**
* @notice Mapping from token address to token index for fungible tokens (NATIVE and ERC20)
* @dev For fungible tokens, the tokenId is not relevant for indexing
*/
mapping(address => uint32) private fungibleTokenIndexMap;
/**
* @notice Mapping from token address and token ID to token index for non-fungible tokens (ERC721 and ERC1155)
* @dev For non-fungible tokens, both address and ID are needed for indexing
*/
mapping(address => mapping(uint256 => uint32))
private nonFungibleTokenIndexMap;
/**
* @notice Initializes the TokenData contract with native token and initial ERC20 tokens
* @dev Called during contract initialization to set up the token indices
* @param initialERC20Tokens Array of ERC20 token addresses to initialize with
*/
// solhint-disable-next-line func-name-mixedcase
function __TokenData_init(
address[] memory initialERC20Tokens
) internal onlyInitializing {
_createTokenIndex(TokenType.NATIVE, NATIVE_CURRENCY_ADDRESS, 0);
for (uint256 i = 0; i < initialERC20Tokens.length; i++) {
_createTokenIndex(TokenType.ERC20, initialERC20Tokens[i], 0);
}
}
/**
* @notice Gets the token index for a token, creating a new index if it doesn't exist
* @dev Used during deposit operations to ensure all tokens have an index
* @param tokenType The type of the token (NATIVE, ERC20, ERC721, ERC1155)
* @param tokenAddress The address of the token contract (zero address for native tokens)
* @param tokenId The ID of the token (used for ERC721 and ERC1155)
* @return uint32 The index of the token (either existing or newly created)
*/
function _getOrCreateTokenIndex(
TokenType tokenType,
address tokenAddress,
uint256 tokenId
) internal returns (uint32) {
(bool ok, uint32 tokenIndex) = getTokenIndex(
tokenType,
tokenAddress,
tokenId
);
if (ok) {
return tokenIndex;
}
return _createTokenIndex(tokenType, tokenAddress, tokenId);
}
/**
* @notice Retrieves the index of the native token (ETH)
* @dev The native token is always at index 0 in the system
* @return uint32 The index of the native token (always 0)
*/
function getNativeTokenIndex() public pure returns (uint32) {
// fungibleTokenIndexMap[NATIVE_CURRENCY_ADDRESS] = 0
return 0;
}
/**
* @notice Creates a new token index for a token
* @dev Adds the token to the tokenInfoList and updates the appropriate mapping
* @param tokenType The type of the token (NATIVE, ERC20, ERC721, ERC1155)
* @param tokenAddress The address of the token contract (zero address for native tokens)
* @param tokenId The ID of the token (used for ERC721 and ERC1155)
* @return uint32 The newly created token index
*/
function _createTokenIndex(
TokenType tokenType,
address tokenAddress,
uint256 tokenId
) private returns (uint32) {
uint32 tokenIndex = uint32(tokenInfoList.length);
tokenInfoList.push(TokenInfo(tokenType, tokenAddress, tokenId));
if (tokenType == TokenType.NATIVE) {
fungibleTokenIndexMap[NATIVE_CURRENCY_ADDRESS] = tokenIndex;
return tokenIndex;
}
if (tokenAddress == address(0)) {
revert TokenAddressIsZero();
}
if (tokenType == TokenType.ERC20) {
fungibleTokenIndexMap[tokenAddress] = tokenIndex;
return tokenIndex;
}
// ERC721 or ERC1155
nonFungibleTokenIndexMap[tokenAddress][tokenId] = tokenIndex;
return tokenIndex;
}
/**
* @notice Retrieves the token index for given token parameters
* @dev Checks the appropriate mapping based on token type
* @param tokenType The type of the token (NATIVE, ERC20, ERC721, ERC1155)
* @param tokenAddress The address of the token contract (zero address for native tokens)
* @param tokenId The ID of the token (used for ERC721 and ERC1155)
* @return bool Indicating whether the token index was found (true) or not (false)
* @return uint32 The index of the token if found, 0 if not found
*/
function getTokenIndex(
TokenType tokenType,
address tokenAddress,
uint256 tokenId
) public view returns (bool, uint32) {
if (tokenType == TokenType.NATIVE) {
// fungibleTokenIndexMap[NATIVE_CURRENCY_ADDRESS] = 0
return (true, 0);
}
if (tokenAddress == address(0)) {
revert TokenAddressIsZero();
}
if (tokenType == TokenType.ERC20) {
uint32 tokenIndex = fungibleTokenIndexMap[tokenAddress];
if (tokenIndex != 0) {
return (true, tokenIndex);
}
}
if (tokenType == TokenType.ERC721 || tokenType == TokenType.ERC1155) {
uint32 tokenIndex = nonFungibleTokenIndexMap[tokenAddress][tokenId];
if (tokenIndex != 0) {
return (true, tokenIndex);
}
}
return (false, 0);
}
/**
* @notice Retrieves token information for a given token index
* @dev Returns the TokenInfo struct from the tokenInfoList array
* @param tokenIndex The index of the token to retrieve information for
* @return TokenInfo struct containing the token's type, address, and ID
*/
function getTokenInfo(
uint32 tokenIndex
) public view returns (TokenInfo memory) {
return tokenInfoList[tokenIndex];
}
}
contracts/liquidity/lib/DepositLimit.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;
/**
* @title Deposit Limit Library
* @notice A library for managing deposit limits for different tokens over time
* @dev Implements a time-based deposit limit system that increases limits for specific tokens
* as time passes from the deployment date
*/
library DepositLimit {
/**
* @notice Token index constants for supported tokens
* @dev These indices must match the indices used in the TokenData contract
*/
uint8 internal constant ETH_INDEX = 0;
uint8 internal constant WBTC_INDEX = 2;
uint8 internal constant USDC_INDEX = 3;
/**
* @notice Time period constants in days from deployment
* @dev Used to determine which deposit limit applies based on elapsed time
*/
uint16 internal constant PERIOD_1 = 182; // 0.5 years (6 months)
uint16 internal constant PERIOD_2 = 364; // 1 year
uint16 internal constant PERIOD_3 = 546; // 1.5 years (18 months)
uint16 internal constant PERIOD_4 = 728; // 2 years
/**
* @notice ETH deposit limits for different time periods
* @dev Values in wei (1 ether = 10^18 wei)
*/
uint256 internal constant ETH_LIMIT_0 = 100 ether; // Initial to 6 months: 100 ETH
uint256 internal constant ETH_LIMIT_1 = 500 ether; // 6 months to 1 year: 500 ETH
uint256 internal constant ETH_LIMIT_2 = 1000 ether; // 1 year to 1.5 years: 1,000 ETH
uint256 internal constant ETH_LIMIT_3 = 5000 ether; // 1.5 years to 2 years: 5,000 ETH
uint256 internal constant ETH_LIMIT_4 = 10000 ether; // After 2 years: 10,000 ETH
/**
* @notice WBTC deposit limits for different time periods
* @dev Values in satoshi (1 BTC = 10^8 satoshi)
*/
uint256 internal constant WBTC_LIMIT_0 = 500000000; // Initial to 6 months: 5 BTC
uint256 internal constant WBTC_LIMIT_1 = 1000000000; // 6 months to 1 year: 10 BTC
uint256 internal constant WBTC_LIMIT_2 = 5000000000; // 1 year to 1.5 years: 50 BTC
uint256 internal constant WBTC_LIMIT_3 = 10000000000; // 1.5 years to 2 years: 100 BTC
uint256 internal constant WBTC_LIMIT_4 = 50000000000; // After 2 years: 500 BTC
/**
* @notice USDC deposit limits for different time periods
* @dev Values in USDC atomic units (1 USDC = 10^6 units)
*/
uint256 internal constant USDC_LIMIT_0 = 500000000000; // Initial to 6 months: 500,000 USDC
uint256 internal constant USDC_LIMIT_1 = 1000000000000; // 6 months to 1 year: 1,000,000 USDC
uint256 internal constant USDC_LIMIT_2 = 5000000000000; // 1 year to 1.5 years: 5,000,000 USDC
uint256 internal constant USDC_LIMIT_3 = 10000000000000; // 1.5 years to 2 years: 10,000,000 USDC
uint256 internal constant USDC_LIMIT_4 = 50000000000000; // After 2 years: 50,000,000 USDC
/**
* @notice Returns the current deposit limit for a token based on time elapsed since deployment
* @dev For tokens other than ETH, WBTC, and USDC, returns the maximum possible uint256 value
* @param tokenIndex The index of the token to get the deposit limit for
* @param deploymentTime The timestamp when the contract was deployed (used as the starting point)
* @return limit The current deposit limit for the specified token
*/
function getDepositLimit(
uint32 tokenIndex,
uint256 deploymentTime
) internal view returns (uint256 limit) {
if (
tokenIndex != ETH_INDEX &&
tokenIndex != WBTC_INDEX &&
tokenIndex != USDC_INDEX
) {
return type(uint256).max;
}
if (block.timestamp < deploymentTime) {
if (tokenIndex == ETH_INDEX) return ETH_LIMIT_0;
if (tokenIndex == WBTC_INDEX) return WBTC_LIMIT_0;
return USDC_LIMIT_0;
}
uint256 daysElapsed = (block.timestamp - deploymentTime) / 1 days;
// Determine period index
uint8 periodIndex;
if (daysElapsed >= PERIOD_4) periodIndex = 4;
else if (daysElapsed >= PERIOD_3) periodIndex = 3;
else if (daysElapsed >= PERIOD_2) periodIndex = 2;
else if (daysElapsed >= PERIOD_1) periodIndex = 1;
else periodIndex = 0;
// Return limit based on token type and period
if (tokenIndex == ETH_INDEX) {
if (periodIndex == 0) return ETH_LIMIT_0;
if (periodIndex == 1) return ETH_LIMIT_1;
if (periodIndex == 2) return ETH_LIMIT_2;
if (periodIndex == 3) return ETH_LIMIT_3;
return ETH_LIMIT_4;
} else if (tokenIndex == WBTC_INDEX) {
if (periodIndex == 0) return WBTC_LIMIT_0;
if (periodIndex == 1) return WBTC_LIMIT_1;
if (periodIndex == 2) return WBTC_LIMIT_2;
if (periodIndex == 3) return WBTC_LIMIT_3;
return WBTC_LIMIT_4;
} else {
if (periodIndex == 0) return USDC_LIMIT_0;
if (periodIndex == 1) return USDC_LIMIT_1;
if (periodIndex == 2) return USDC_LIMIT_2;
if (periodIndex == 3) return USDC_LIMIT_3;
return USDC_LIMIT_4;
}
}
}
contracts/liquidity/lib/DepositQueueLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;
/**
* @title Deposit Queue Library
* @notice A library for managing a queue of pending deposits in the Liquidity contract
* @dev Implements a queue data structure with enqueue, dequeue, and delete operations
* to track deposits that are waiting to be relayed to Layer 2
*/
library DepositQueueLib {
/**
* @notice Error thrown when trying to relay deposits outside the valid queue range
* @param upToDepositId The requested deposit ID that is out of range
* @param firstDepositId The first valid deposit ID in the queue
* @param lastDepositId The last valid deposit ID in the queue
*/
error OutOfRange(
uint256 upToDepositId,
uint256 firstDepositId,
uint256 lastDepositId
);
/**
* @notice Represents a queue of pending deposits
* @param depositData Array of deposits that are pending relay to Layer 2
* @param front Index of the first element in the queue (the next deposit to be relayed)
*/
struct DepositQueue {
DepositData[] depositData;
uint256 front;
}
/**
* @notice Represents data for a single deposit
* @dev Stores minimal information needed to track and validate deposits
* @param depositHash The hash of the deposit data (includes recipient, amount, token, etc.)
* @param sender The address of the depositor (used for cancellation authorization)
*/
struct DepositData {
bytes32 depositHash;
address sender;
}
/**
* @notice Initializes the deposit queue
* @dev Pushes a dummy element to make the queue 1-indexed for easier tracking
* @param depositQueue The storage reference to the DepositQueue struct to initialize
*/
function initialize(DepositQueue storage depositQueue) internal {
depositQueue.depositData.push(DepositData(0, address(0)));
depositQueue.front = 1;
}
/**
* @notice Adds a new deposit to the queue
* @dev The deposit ID is the index in the depositData array
* @param depositQueue The storage reference to the DepositQueue struct
* @param depositHash The hash of the deposit data
* @param sender The address of the depositor
* @return depositId The ID of the newly added deposit (used for tracking and cancellation)
*/
function enqueue(
DepositQueue storage depositQueue,
bytes32 depositHash,
address sender
) internal returns (uint256 depositId) {
depositId = depositQueue.depositData.length;
depositQueue.depositData.push(DepositData(depositHash, sender));
}
/**
* @notice Deletes a deposit from the queue (used for cancellation)
* @dev Doesn't actually remove the element from the array, just clears its data
* @param depositQueue The storage reference to the DepositQueue struct
* @param depositId The ID of the deposit to be deleted
* @return depositData The data of the deleted deposit (returned for event emission)
*/
function deleteDeposit(
DepositQueue storage depositQueue,
uint256 depositId
) internal returns (DepositData memory depositData) {
depositData = depositQueue.depositData[depositId];
delete depositQueue.depositData[depositId];
}
/**
* @notice Processes deposits in the queue for relay to Layer 2
* @dev Collects valid deposit hashes from front to upToDepositId and advances the queue
* @dev Skips deposits that have been deleted (sender address is zero)
* @param depositQueue The storage reference to the DepositQueue struct
* @param upToDepositId The upper bound deposit ID to process
* @return An array of deposit hashes to be relayed to Layer 2
*/
function batchDequeue(
DepositQueue storage depositQueue,
uint256 upToDepositId
) internal returns (bytes32[] memory) {
uint256 front = depositQueue.front;
if (
upToDepositId >= depositQueue.depositData.length ||
upToDepositId < front
) {
revert OutOfRange(
upToDepositId,
front,
depositQueue.depositData.length - 1
);
}
uint256 counter = 0;
for (uint256 i = front; i <= upToDepositId; i++) {
if (depositQueue.depositData[i].sender == address(0)) {
continue;
}
counter++;
}
bytes32[] memory depositHashes = new bytes32[](counter);
uint256 depositHashesIndex = 0;
for (uint256 i = front; i <= upToDepositId; i++) {
if (depositQueue.depositData[i].sender == address(0)) {
continue;
}
depositHashes[depositHashesIndex] = depositQueue
.depositData[i]
.depositHash;
depositHashesIndex++;
}
depositQueue.front = upToDepositId + 1;
return depositHashes;
}
}
contracts/liquidity/lib/ERC20CallOptionalLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 Call Optional Library
* @notice A library for safely handling ERC20 token transfers that may not conform to the ERC20 standard
* @dev Some ERC20 tokens don't revert on failure or don't return a boolean value as specified in the standard.
* This library handles these non-standard implementations safely.
*/
library ERC20CallOptionalLib {
/**
* @notice Makes a low-level call to an ERC20 token contract and safely handles various return value scenarios
* @dev Inspired by OpenZeppelin's SafeERC20 _callOptionalReturnBool function
* @dev Handles three cases:
* 1. Token returns true/false as per ERC20 spec
* 2. Token returns nothing (empty return data)
* 3. Token doesn't revert but returns non-boolean data
* @param token The ERC20 token contract to call
* @param data The call data (typically a transfer or transferFrom function call)
* @return bool True if the call was successful, false otherwise
*/
function callOptionalReturnBool(
IERC20 token,
bytes memory data
) internal returns (bool) {
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
return
success &&
(returndata.length == 0 || abi.decode(returndata, (bool))) &&
address(token).code.length > 0;
}
}
contracts/permitter/IPermitter.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;
/**
* @title IPermitter
* @notice Interface for permission validation contracts that authorize user actions
* @dev This interface defines the method for validating if a user has permission to execute a specific action
*/
interface IPermitter {
/**
* @notice Validates if a user has the right to execute a specified action
* @dev This function is called to check permissions before executing protected operations
* @param user The address of the user attempting the action
* @param value The msg.value of the transaction being authorized
* @param encodedData The encoded function call data of the action that user wants to execute
* @param permission The permission data that proves user authorization (format depends on implementation)
* @return authorized Returns true if the user is authorized to perform the action, false otherwise
*/
function permit(
address user,
uint256 value,
bytes calldata encodedData,
bytes calldata permission
) external returns (bool authorized);
}
contracts/rollup/IRollup.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;
/**
* @title IRollup
* @notice Interface for the Intmax2 L2 rollup contract
* @dev Defines the external functions, events, and errors for the Rollup contract
*/
interface IRollup {
/**
* @notice Error thrown when a required address parameter is the zero address
* @dev Used in initialize function to validate address parameters
*/
error AddressZero();
/**
* @notice Error thrown when a non-ScrollMessenger calls a function restricted to ScrollMessenger
* @dev Used to enforce cross-chain message security
*/
error OnlyScrollMessenger();
/**
* @notice Error thrown when the xDomainMessageSender in ScrollMessenger is not the liquidity contract
* @dev Used to ensure only the authorized Liquidity contract can send cross-chain messages
*/
error OnlyLiquidity();
/**
* @notice Error thrown when the number of public keys exceeds 128
* @dev Used to limit the size of registration blocks
*/
error TooManySenderPublicKeys();
/**
* @notice Error thrown when the number of account IDs exceeds 128
* @dev Used to limit the size of non-registration blocks
*/
error TooManyAccountIds();
/**
* @notice Error thrown when the length of account IDs bytes is not a multiple of 5
* @dev Each account ID must be exactly 5 bytes
*/
error SenderAccountIdsInvalidLength();
/**
* @notice Error thrown when the posted block fails the pairing test
* @dev Indicates an invalid signature or incorrect message point
*/
error PairingCheckFailed();
/**
* @notice Error thrown when the specified block number is greater than the latest block number
* @dev Used in getBlockHash to prevent accessing non-existent blocks
*/
error BlockNumberOutOfRange();
/**
* @notice Error thrown when the fee for the rate limiter is insufficient
* @dev The msg.value must cover the penalty calculated by the rate limiter
*/
error InsufficientPenaltyFee();
/**
* @notice Error thrown when the expiry timestamp is in the past
* @dev Block expiry timestamps must be in the future or zero (no expiry)
*/
error Expired();
/**
* @notice Error thrown when the given nonce is less than the current nonce
* @dev Nonces must be monotonically increasing to prevent replay attacks
*/
error InvalidNonce();
/**
* @notice Event emitted when deposits bridged from the liquidity contract are processed
* @dev Triggered when the processDeposits function is called by the Liquidity contract
* @param lastProcessedDepositId The ID of the last processed deposit
* @param depositTreeRoot The new root of the deposit tree after processing
*/
event DepositsProcessed(
uint256 indexed lastProcessedDepositId,
bytes32 depositTreeRoot
);
/**
* @notice Event emitted when a deposit is inserted into the deposit tree
* @dev Emitted for each deposit processed in the processDeposits function
* @param depositIndex The index of the deposit in the deposit tree
* @param depositHash The hash of the deposit data
*/
event DepositLeafInserted(
uint32 indexed depositIndex,
bytes32 indexed depositHash
);
/**
* @notice Event emitted when a new block is posted to the rollup chain
* @dev Contains all essential information about the newly posted block
* @param prevBlockHash The hash of the previous block in the chain
* @param blockBuilder The address of the block builder who submitted the block
* @param timestamp The timestamp when the block was posted
* @param blockNumber The sequential number of the posted block
* @param depositTreeRoot The root of the deposit tree at the time of block posting
* @param signatureHash The hash of the block signature data
*/
event BlockPosted(
bytes32 indexed prevBlockHash,
address indexed blockBuilder,
uint64 timestamp,
uint256 blockNumber,
bytes32 depositTreeRoot,
bytes32 signatureHash
);
/**
* @notice Struct to store block data to avoid stack too deep errors
* @dev Used in the internal _postBlock function to organize block parameters
* @param isRegistrationBlock Whether the block is a registration block (true) or non-registration block (false)
* @param txTreeRoot The root of the transaction Merkle tree
* @param expiry The expiry timestamp of the tx tree root (0 means no expiry)
* @param builderAddress The address of the block builder who submitted the block
* @param builderNonce The nonce of the block builder (for replay protection)
* @param senderFlags Flags indicating whether senders' signatures are included in the aggregated signature
*/
struct BlockPostData {
bool isRegistrationBlock;
bytes32 txTreeRoot;
uint64 expiry;
address builderAddress;
uint32 builderNonce;
bytes16 senderFlags;
}
/**
* @notice Posts a registration block for senders' first transactions
* @dev Registration blocks include the public keys of new senders
* @param txTreeRoot The root of the transaction Merkle tree
* @param expiry The expiry timestamp of the tx tree root (0 means no expiry)
* @param builderNonce The registration block nonce of the block builder
* @param senderFlags Flags indicating which senders' signatures are included
* @param aggregatedPublicKey The aggregated public key for signature verification
* @param aggregatedSignature The aggregated signature of all participating senders
* @param messagePoint The hash of the tx tree root mapped to G2 curve point
* @param senderPublicKeys Array of public keys for new senders (max 128)
*/
function postRegistrationBlock(
bytes32 txTreeRoot,
uint64 expiry,
uint32 builderNonce,
bytes16 senderFlags,
bytes32[2] calldata aggregatedPublicKey,
bytes32[4] calldata aggregatedSignature,
bytes32[4] calldata messagePoint,
uint256[] calldata senderPublicKeys
) external payable;
/**
* @notice Posts a non-registration block for senders' subsequent transactions
* @dev Non-registration blocks use account IDs instead of full public keys
* @param txTreeRoot The root of the transaction Merkle tree
* @param expiry The expiry timestamp of the tx tree root (0 means no expiry)
* @param builderNonce The non-registration block nonce of the block builder
* @param senderFlags Flags indicating which senders' signatures are included
* @param aggregatedPublicKey The aggregated public key for signature verification
* @param aggregatedSignature The aggregated signature of all participating senders
* @param messagePoint The hash of the tx tree root mapped to G2 curve point
* @param publicKeysHash The hash of the public keys used in this block
* @param senderAccountIds Byte array of account IDs (5 bytes per account)
*/
function postNonRegistrationBlock(
bytes32 txTreeRoot,
uint64 expiry,
uint32 builderNonce,
bytes16 senderFlags,
bytes32[2] calldata aggregatedPublicKey,
bytes32[4] calldata aggregatedSignature,
bytes32[4] calldata messagePoint,
bytes32 publicKeysHash,
bytes calldata senderAccountIds
) external payable;
/**
* @notice Sets the rate limiter constants for the rollup chain
* @dev Can only be called by the contract owner
* @param thresholdInterval The threshold block submission interval in seconds
* @param alpha The alpha value for the exponential moving average
* @param k The penalty coefficient for the rate limiter
*/
function setRateLimitConstants(
uint256 thresholdInterval,
uint256 alpha,
uint256 k
) external;
/**
* @notice Withdraws accumulated penalty fees from the Rollup contract
* @dev Only the contract owner can call this function
* @param to The address to which the penalty fees will be transferred
*/
function withdrawPenaltyFee(address to) external;
/**
* @notice Processes deposits from the Liquidity contract
* @dev Can only be called by the Liquidity contract via Scroll Messenger
* @param lastProcessedDepositId The ID of the last processed deposit
* @param depositHashes Array of hashes for the deposits to be processed
*/
function processDeposits(
uint256 lastProcessedDepositId,
bytes32[] calldata depositHashes
) external;
/**
* @notice Gets the block number of the latest posted block
* @dev Returns the highest block number in the rollup chain
* @return The latest block number (zero-based)
*/
function getLatestBlockNumber() external view returns (uint32);
/**
* @notice Gets the current penalty fee required by the rate limiter
* @dev Calculated based on the exponential moving average of block intervals
* @return The penalty fee in wei required for the next block submission
*/
function getPenalty() external view returns (uint256);
/**
* @notice Gets the block hash for a specific block number
* @dev Reverts if the block number is out of range
* @param blockNumber The block number to query
* @return The hash of the specified block
*/
function getBlockHash(uint32 blockNumber) external view returns (bytes32);
}
Compiler settingsShow
{
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.