Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/WithdrawController.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
import {IWithdrawController} from "./interfaces/IWithdrawController.sol";
import {IAccessRegistry} from "./interfaces/IAccessRegistry.sol";
import {IOracleRegistry} from "./interfaces/IOracleRegistry.sol";
import {IParamRegistry} from "./interfaces/IParamRegistry.sol";
import {IAssetsRouter} from "./interfaces/IAssetsRouter.sol";
import {Errors} from "./libraries/Errors.sol";
import {NormalizationLib} from "./libraries/NormalizationLib.sol";
import {Constants} from "./common/Constants.sol";
import {Token} from "./Token.sol";
/// @title WithdrawController
/// @author luoyhang003
/// @notice Handles withdrawal requests, processing, reviewing, rejection, and completion.
/// @dev Integrates with AccessRegistry for whitelisting, OracleRegistry for pricing,
/// ParamRegistry for fee/limit parameters, and AssetsRouter for asset routing.
/// Implements a multi-step withdrawal lifecycle controlled by admin/operator roles.
/// @dev
/// The withdrawal process transitions between the following states:
///
/// ┌───────────────────────────────────────────────────────────┐
/// │ STATE FLOW │
/// └───────────────────────────────────────────────────────────┘
///
/// REQUESTED
/// - Initial state after a user submits a withdrawal request.
/// - Shares are transferred into the contract.
/// - Can be cancelled by the user → CANCELLED.
/// - Can be rejected by the operator → REJECTED.
///
/// CANCELLED (Terminal)
/// - User cancels their withdrawal request.
/// - Shares are returned to the requester.
///
/// PROCESSING
/// - Operator marks withdrawal as processing with reference oracle prices.
/// - Represents that withdrawal is acknowledged and being handled.
/// - Can transition to:
/// → REVIEWING (manual check required)
/// → PROCESSED (ready for completion)
///
/// REVIEWING
/// - Withdrawal under operator review.
/// - Can transition to:
/// → FORFEITED (shares penalized, sent to treasury)
/// → PROCESSED (approved and ready for completion)
///
/// REJECTED (Terminal)
/// - Operator rejects the withdrawal request.
/// - Original shares are refunded to the requester.
///
/// FORFEITED (Terminal)
/// - Withdrawal is penalized.
/// - Requester’s shares are transferred to the forfeit treasury.
///
/// PROCESSED
/// - Withdrawal has been validated and priced.
/// - Awaiting user to call `completeWithdrawal`.
///
/// COMPLETED (Terminal)
/// - Finalized state after user completes withdrawal.
/// - Shares are burned.
/// - Corresponding assets are transferred to the requester.
///
/// ┌───────────────────────────────────────────────────────────┐
/// │ STATE TRANSITIONS SUMMARY │
/// └───────────────────────────────────────────────────────────┘
///
/// REQUESTED ── cancelWithdrawal ────▶ CANCELLED(terminal)
/// │
/// └─────── markAsProcessing ────▶ PROCESSING
/// │
/// └─────── markAsRejected ──────▶ REJECTED(terminal)
///
/// PROCESSING ─ markAsReviewing ─────▶ REVIEWING
/// │
/// └─────── markAsProcessed ─────▶ PROCESSED
///
/// REVIEWING ── markAsForfeited ─────▶ FORFEITED(terminal)
/// │
/// └─────── markAsProcessed ─────▶ PROCESSED
///
/// PROCESSED ── completeWithdrawal ──▶ COMPLETED(terminal)
///
/// @custom:terminal CANCELLED, REJECTED, FORFEITED, and COMPLETED are terminal states.
///
contract WithdrawController is
IWithdrawController,
AccessControl,
ReentrancyGuard,
Constants
{
using Math for uint256;
using NormalizationLib for uint256;
/*//////////////////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////////////////*/
/// @notice Role allowed to manage WithdrawController
/// @dev Calculated as keccak256("WITHDRAWAL_ADMIN_ROLE").
bytes32 public constant WITHDRAWAL_ADMIN_ROLE =
keccak256("WITHDRAWAL_ADMIN_ROLE");
/// @notice Role allowed to operate WithdrawController
/// @dev Calculated as keccak256("WITHDRAWAL_OPERATOR_ROLE").
bytes32 public constant WITHDRAWAL_OPERATOR_ROLE =
keccak256("WITHDRAWAL_OPERATOR_ROLE");
/// @notice ERC20 share token representing ownership in the vault
Token public immutable shareToken;
/// @notice Registry managing whitelisted users for withdrawal access
IAccessRegistry public accessRegistry;
/// @notice Registry providing oracle-based pricing for vault tokens and assets
IOracleRegistry public oracleRegistry;
/// @notice Registry holding fee rates, withdrawal caps, and forfeit/fee recipient
IParamRegistry public paramRegistry;
/// @notice Router responsible for routing assets to destinations
IAssetsRouter public assetsRouter;
/// @notice List of supported withdrawal assets
address[] public withdrawalAssets;
/// @notice Stores all withdrawal receipts (requests + state tracking)
WithdrawalReceipt[] public withdrawalReceipts;
/// @notice Mapping of supported withdrawal asset status
mapping(address => bool) public isWithdrawalAsset;
/// @notice Cached decimals for each withdrawal asset
mapping(address => uint8) public tokenDecimals;
/*//////////////////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////////////////*/
/// @notice Deploys WithdrawController with initial configs.
/// @param _defaultAdmin Address granted DEFAULT_ADMIN_ROLE.
/// @param _adminRole Address granted WITHDRAWAL_ADMIN_ROLE.
/// @param _operatorRole Address granted WITHDRAWAL_OPERATOR_ROLE.
/// @param _shareToken ERC20 share token used for withdrawals.
/// @param _accessRegistry Registry of whitelisted users.
/// @param _oracleRegistry Registry for asset/oracle prices.
/// @param _paramRegistry Registry for fees and limits.
/// @param _assetsRouter Router contract for asset routing.
/// @param _withdrawalAssets Initial list of supported withdrawal assets.
/// @dev Validates input addresses, registers assets, and stores decimals.
constructor(
address _defaultAdmin,
address _adminRole,
address _operatorRole,
address _shareToken,
address _accessRegistry,
address _oracleRegistry,
address _paramRegistry,
address _assetsRouter,
address[] memory _withdrawalAssets
) {
if (
_defaultAdmin == address(0) ||
_adminRole == address(0) ||
_operatorRole == address(0) ||
_shareToken == address(0) ||
_accessRegistry == address(0) ||
_oracleRegistry == address(0) ||
_paramRegistry == address(0) ||
_assetsRouter == address(0)
) revert Errors.ZeroAddress();
_grantRole(DEFAULT_ADMIN_ROLE, _defaultAdmin);
_grantRole(WITHDRAWAL_ADMIN_ROLE, _adminRole);
_grantRole(WITHDRAWAL_OPERATOR_ROLE, _operatorRole);
shareToken = Token(_shareToken);
accessRegistry = IAccessRegistry(_accessRegistry);
oracleRegistry = IOracleRegistry(_oracleRegistry);
paramRegistry = IParamRegistry(_paramRegistry);
assetsRouter = IAssetsRouter(_assetsRouter);
uint256 i;
uint256 length = _withdrawalAssets.length;
for (i; i < length; i++) {
address asset = _withdrawalAssets[i];
if (asset == _shareToken) revert Errors.ConflictiveToken();
if (asset == address(0)) revert Errors.ZeroAddress();
if (oracleRegistry.getOracle(asset) == address(0))
revert Errors.InvalidOracle();
isWithdrawalAsset[asset] = true;
withdrawalAssets.push(asset);
uint8 decimals = ERC20(asset).decimals();
if (decimals > 18) revert Errors.InvalidDecimals();
tokenDecimals[asset] = decimals;
emit WithdrawalAssetAdded(asset);
}
}
/*//////////////////////////////////////////////////////////////////////////
WITHDRAWAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Request withdrawal of a specific asset by burning shares.
/// @param _requestToken Asset to withdraw into.
/// @param _shares Number of shares to redeem.
/// @dev User must be whitelisted. Generates a withdrawal receipt.
function requestWithdrawal(
address _requestToken,
uint256 _shares
) external {
if (!accessRegistry.isWhitelisted(msg.sender))
revert Errors.UserNotWhitelisted();
_requestWithdrawal(_requestToken, _shares);
}
/// @notice Batch request withdrawals across multiple assets.
/// @param _requestTokens List of withdrawal asset addresses.
/// @param _shares Corresponding share amounts per asset.
/// @dev Lengths must match. Generates multiple withdrawal receipts.
function requestWithdrawals(
address[] memory _requestTokens,
uint256[] memory _shares
) external {
if (!accessRegistry.isWhitelisted(msg.sender))
revert Errors.UserNotWhitelisted();
uint256 length = _requestTokens.length;
if (length == 0 || _shares.length == 0 || length != _shares.length)
revert Errors.InvalidArrayLength();
uint256 i;
for (i; i < length; i++) {
_requestWithdrawal(_requestTokens[i], _shares[i]);
}
}
/// @notice Cancel a single pending withdrawal request.
/// @param _id Receipt ID of the withdrawal request.
/// @dev Only the original requester can cancel. Shares are refunded.
function cancelWithdrawal(uint256 _id) external {
_cancelWithdrawal(_id);
}
/// @notice Batch cancel withdrawal requests.
/// @param _ids An array of receipt IDs of the withdrawal requests.
/// @dev Only the original requester can cancel. Shares are refunded.
function cancelWithdrawals(uint256[] memory _ids) external {
uint256 length = _ids.length;
if (length == 0) revert Errors.InvalidArrayLength();
uint256 i;
for (i; i < length; i++) {
_cancelWithdrawal(_ids[i]);
}
}
/// @notice Complete a withdrawal once processed.
/// @param _id Receipt ID of withdrawal.
/// @dev Burns shares, transfers asset to user, applies fees.
function completeWithdrawal(uint256 _id) external {
_completeWithdrawal(_id);
}
/// @notice Batch complete withdrawals.
/// @param _ids An array of receipt IDs of withdrawals.
/// @dev Burns shares, transfers asset to user, applies fees.
function completeWithdrawals(uint256[] memory _ids) external {
uint256 length = _ids.length;
if (length == 0) revert Errors.InvalidArrayLength();
uint256 i;
for (i; i < length; i++) {
_completeWithdrawal(_ids[i]);
}
}
/*//////////////////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Returns total number of withdrawal receipts created.
/// @return length_ Total number of withdrawal receipts.
function getWithdrawalReceiptsLength()
external
view
returns (uint256 length_)
{
return withdrawalReceipts.length;
}
/// @notice Paginates withdrawal receipts.
/// @param _offset Start index in array.
/// @param _limit Number of receipts to fetch.
/// @return receipts_ List of withdrawal receipts within range.
function getWithdrawalReceipts(
uint256 _offset,
uint256 _limit
) external view returns (WithdrawalReceipt[] memory receipts_) {
uint256 length = withdrawalReceipts.length;
if (_offset >= length) revert Errors.IndexOutOfBounds();
if (_limit == 0) revert Errors.ZeroAmount();
uint256 end = _offset + _limit;
if (end > length) end = length;
receipts_ = new WithdrawalReceipt[](end - _offset);
for (uint256 i = 0; i < end - _offset; i++) {
receipts_[i] = withdrawalReceipts[_offset + i];
}
}
/*//////////////////////////////////////////////////////////////////////////
WITHDRAWAL PROCESS FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Mark receipts as `PROCESSING` with reference prices.
/// @param _ids Array of receipt IDs.
/// @param _priceIndex Oracle price index to use.
/// @param _isCompleted Whether all are finalized as `PROCESSING`.
/// @dev Operator-only. Sets asset and share prices in receipt.
function markAsProcessing(
uint256[] memory _ids,
uint256 _priceIndex,
bool _isCompleted
) external onlyRole(WITHDRAWAL_OPERATOR_ROLE) {
uint256 length = _ids.length;
if (length == 0) revert Errors.InvalidArrayLength();
uint256 shareTokenPrice = oracleRegistry.getVaultTokenCutOffPrice(
_priceIndex
);
uint256 i;
for (i; i < length; i++) {
uint256 id = _ids[i];
if (id >= withdrawalReceipts.length)
revert Errors.IndexOutOfBounds();
WithdrawalReceipt storage receipt = withdrawalReceipts[id];
if (receipt.status != WITHDRAWAL_STATUS.REQUESTED)
revert Errors.InvalidReceiptStatus();
uint256 requestAssetPrice = oracleRegistry.getCutOffPrice(
receipt.requestAsset,
_priceIndex
);
receipt.shareTokenPrice = shareTokenPrice;
receipt.requestAssetPrice = requestAssetPrice;
receipt.status = WITHDRAWAL_STATUS.PROCESSING;
emit WithdrawalProcessing(shareTokenPrice, requestAssetPrice, id);
}
if (_isCompleted) emit AllMarkedAsProcessing();
}
/// @notice Emit event to notify server that all receipts are finalized as `PROCESSING`.
function markAsProcessingComplete()
external
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
{
emit AllMarkedAsProcessing();
}
/// @notice Mark receipts as `PROCESSED`, ready for completion.
/// @param _ids Array of receipt IDs.
function markAsProcessed(
uint256[] memory _ids
) external onlyRole(WITHDRAWAL_OPERATOR_ROLE) {
uint256 length = _ids.length;
if (length == 0) revert Errors.InvalidArrayLength();
uint256 i;
for (i; i < length; i++) {
uint256 id = _ids[i];
if (id >= withdrawalReceipts.length)
revert Errors.IndexOutOfBounds();
WithdrawalReceipt storage receipt = withdrawalReceipts[id];
if (
receipt.status != WITHDRAWAL_STATUS.PROCESSING &&
receipt.status != WITHDRAWAL_STATUS.REVIEWING
) revert Errors.InvalidReceiptStatus();
receipt.status = WITHDRAWAL_STATUS.PROCESSED;
emit WithdrawalProcessed(id);
}
}
/// @notice Move receipts to `REVIEWING` state.
/// @param _ids Array of receipt IDs.
function markAsReviewing(
uint256[] memory _ids
) external onlyRole(WITHDRAWAL_OPERATOR_ROLE) {
uint256 length = _ids.length;
if (length == 0) revert Errors.InvalidArrayLength();
uint256 i;
for (i; i < length; i++) {
uint256 id = _ids[i];
if (id >= withdrawalReceipts.length)
revert Errors.IndexOutOfBounds();
WithdrawalReceipt storage receipt = withdrawalReceipts[id];
if (receipt.status != WITHDRAWAL_STATUS.PROCESSING)
revert Errors.InvalidReceiptStatus();
receipt.status = WITHDRAWAL_STATUS.REVIEWING;
emit WithdrawalReviewing(id);
}
}
/// @notice Reject withdrawal requests under review.
/// @param _ids Array of receipt IDs.
/// @dev Returns original shares to user.
function markAsRejected(
uint256[] memory _ids
) external onlyRole(WITHDRAWAL_OPERATOR_ROLE) {
uint256 length = _ids.length;
if (length == 0) revert Errors.InvalidArrayLength();
uint256 i;
for (i; i < length; i++) {
uint256 id = _ids[i];
if (id >= withdrawalReceipts.length)
revert Errors.IndexOutOfBounds();
WithdrawalReceipt storage receipt = withdrawalReceipts[id];
if (receipt.status != WITHDRAWAL_STATUS.REQUESTED)
revert Errors.InvalidReceiptStatus();
TransferHelper.safeTransfer(
address(shareToken),
receipt.requester,
receipt.requestShares
);
receipt.status = WITHDRAWAL_STATUS.REJECTED;
emit WithdrawalRejected(id);
}
}
/// @notice Forfeit withdrawals under review.
/// @param _ids Array of receipt IDs.
/// @dev Redirects shares to treasury (penalty).
function markAsForfeited(
uint256[] memory _ids
) external onlyRole(WITHDRAWAL_OPERATOR_ROLE) {
uint256 length = _ids.length;
if (length == 0) revert Errors.InvalidArrayLength();
uint256 i;
for (i; i < length; i++) {
uint256 id = _ids[i];
if (id >= withdrawalReceipts.length)
revert Errors.IndexOutOfBounds();
WithdrawalReceipt storage receipt = withdrawalReceipts[id];
if (receipt.status != WITHDRAWAL_STATUS.REVIEWING)
revert Errors.InvalidReceiptStatus();
TransferHelper.safeTransfer(
address(shareToken),
paramRegistry.getForfeitTreasury(),
receipt.requestShares
);
receipt.status = WITHDRAWAL_STATUS.FORFEITED;
emit WithdrawalForfeited(id);
}
}
/// @notice Repays assets back into the controller (usually for liquidity replenishment).
/// @param _assets Array of ERC20 token addresses to repay.
/// @param _amounts Array of amounts to repay for each corresponding asset.
/// @dev Callable only by WITHDRAWAL_OPERATOR_ROLE.
/// Lengths of `_assets` and `_amounts` must match and be > 0.
/// Ensures asset is supported and amount is nonzero.
/// Tokens are transferred from operator to this contract.
function repayAssets(
address[] memory _assets,
uint256[] memory _amounts
) external onlyRole(WITHDRAWAL_OPERATOR_ROLE) {
uint256 length = _assets.length;
if (length == 0 || _amounts.length == 0 || length != _amounts.length)
revert Errors.InvalidArrayLength();
uint256 i;
for (i; i < length; i++) {
address asset = _assets[i];
uint256 amount = _amounts[i];
if (!isWithdrawalAsset[asset]) revert Errors.UnsupportedAsset();
if (amount == 0) revert Errors.ZeroAmount();
TransferHelper.safeTransferFrom(
asset,
msg.sender,
address(this),
amount
);
emit AssetRepaid(asset, amount);
}
}
/*//////////////////////////////////////////////////////////////////////////
ADMIN FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Adds a new supported withdrawal asset.
/// @param _asset ERC20 token address to be added as a withdrawal option.
/// @dev Callable only by WITHDRAWAL_ADMIN_ROLE.
/// Requires a valid oracle registered for `_asset`.
/// Stores token decimals (must be ≤ 18).
/// Emits {WithdrawalAssetAdded}.
function addWithdrawalAsset(
address _asset
) external onlyRole(WITHDRAWAL_ADMIN_ROLE) {
if (withdrawalAssets.length >= paramRegistry.getArrayLengthLimit())
revert Errors.ExceedArrayLengthLimit();
if (_asset == address(0)) revert Errors.ZeroAddress();
if (_asset == address(shareToken)) revert Errors.ConflictiveToken();
if (isWithdrawalAsset[_asset]) revert Errors.AssetAlreadyAdded();
if (oracleRegistry.getOracle(_asset) == address(0))
revert Errors.InvalidOracle();
isWithdrawalAsset[_asset] = true;
withdrawalAssets.push(_asset);
uint8 decimals = ERC20(_asset).decimals();
if (decimals > 18) revert Errors.InvalidDecimals();
tokenDecimals[_asset] = decimals;
emit WithdrawalAssetAdded(_asset);
}
/// @notice Removes an existing withdrawal asset from the supported list.
/// @param _asset ERC20 token address to remove.
/// @dev Callable only by WITHDRAWAL_ADMIN_ROLE.
/// Reverts if `_asset` is not currently supported.
/// Updates mapping and storage list.
/// Emits {WithdrawalAssetRemoved}.
function removeWithdrawalAsset(
address _asset
) external onlyRole(WITHDRAWAL_ADMIN_ROLE) {
if (_asset == address(0)) revert Errors.ZeroAddress();
if (!isWithdrawalAsset[_asset]) revert Errors.AssetAlreadyRemoved();
uint256 length = withdrawalAssets.length;
uint256 i;
for (i; i < length; i++) {
if (withdrawalAssets[i] == _asset) {
withdrawalAssets[i] = withdrawalAssets[length - 1];
withdrawalAssets.pop();
break;
}
}
isWithdrawalAsset[_asset] = false;
emit WithdrawalAssetRemoved(_asset);
}
/// @notice Force routes a specific amount of an asset through the AssetsRouter.
/// @param _asset ERC20 token address to route.
/// @param _amount Amount of `_asset` to route.
/// @dev Callable only by WITHDRAWAL_ADMIN_ROLE.
/// Typically used in emergencies or manual corrections.
/// Resets and re-approves allowance before routing.
function forceRouteAssets(
address _asset,
uint256 _amount
) external onlyRole(WITHDRAWAL_ADMIN_ROLE) {
if (_asset == address(0)) revert Errors.ZeroAddress();
if (_amount == 0) revert Errors.ZeroAmount();
TransferHelper.safeApprove(_asset, address(assetsRouter), 0);
TransferHelper.safeApprove(_asset, address(assetsRouter), _amount);
assetsRouter.route(_asset, _amount);
emit ForceRouteAssets(_asset, _amount);
}
/// @notice Updates the AssetsRouter contract used for routing assets.
/// @param _assetsRouter Address of the new AssetsRouter contract.
/// @dev Callable only by WITHDRAWAL_ADMIN_ROLE.
/// Emits {SetAssetsRouter}.
/// Does not reset allowances for all assets (admin must manage separately if needed).
function setAssetsRouter(
address _assetsRouter
) external onlyRole(WITHDRAWAL_ADMIN_ROLE) {
if (_assetsRouter == address(0)) revert Errors.ZeroAddress();
emit SetAssetsRouter(address(assetsRouter), _assetsRouter);
assetsRouter = IAssetsRouter(_assetsRouter);
}
/*//////////////////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Internal logic for handling withdrawal requests.
/// Transfers shares from user, creates a withdrawal receipt,
/// applies fee rate from ParamRegistry, and marks status as REQUESTED.
/// @param _requestToken Address of the withdrawal asset requested.
/// @param _shares Amount of shares to redeem.
/// @notice Emits {WithdrawalRequested}.
/// @custom:reverts if user provides zero shares, unsupported asset, or withdraw is paused.
function _requestWithdrawal(
address _requestToken,
uint256 _shares
) internal nonReentrant {
if (_shares == 0) revert Errors.RequestZeroShare();
if (!isWithdrawalAsset[_requestToken]) revert Errors.UnsupportedAsset();
if (!paramRegistry.getRedeemEnabled(_requestToken))
revert Errors.WithdrawPaused();
TransferHelper.safeTransferFrom(
address(shareToken),
msg.sender,
address(this),
_shares
);
WithdrawalReceipt memory withdrawalReceipt;
withdrawalReceipt.requester = msg.sender;
withdrawalReceipt.requestAsset = _requestToken;
withdrawalReceipt.requestShares = _shares;
withdrawalReceipt.feeRate = paramRegistry.getRedeemFeeRate(
_requestToken
);
withdrawalReceipt.status = WITHDRAWAL_STATUS.REQUESTED;
emit WithdrawalRequested(
msg.sender,
_requestToken,
_shares,
withdrawalReceipts.length
);
withdrawalReceipts.push(withdrawalReceipt);
}
/// @dev Internal logic for cancelling a withdrawal request.
/// Refunds shares to requester and updates receipt status.
/// @param _id ID of the withdrawal receipt to cancel.
/// @notice Emits {WithdrawalCancelled}.
/// @custom:reverts if caller is not requester or status is not REQUESTED.
function _cancelWithdrawal(uint256 _id) internal {
if (_id >= withdrawalReceipts.length) revert Errors.IndexOutOfBounds();
WithdrawalReceipt storage receipt = withdrawalReceipts[_id];
address requester = receipt.requester;
uint256 requestShares = receipt.requestShares;
if (requester != msg.sender) revert Errors.NotRequester();
if (receipt.status != WITHDRAWAL_STATUS.REQUESTED)
revert Errors.InvalidReceiptStatus();
TransferHelper.safeTransfer(
address(shareToken),
requester,
requestShares
);
receipt.status = WITHDRAWAL_STATUS.CANCELLED;
emit WithdrawalCancelled(requester, requestShares, _id);
}
/// @dev Internal logic for completing withdrawals after being processed.
/// Calculates withdrawn amount using oracle prices, applies fee,
/// burns shares, and transfers assets to requester.
/// @param _id ID of the withdrawal receipt to complete.
/// @notice Emits {WithdrawalCompleted}.
/// @custom:reverts if receipt is not PROCESSED.
function _completeWithdrawal(uint256 _id) internal nonReentrant {
if (_id >= withdrawalReceipts.length) revert Errors.IndexOutOfBounds();
WithdrawalReceipt storage receipt = withdrawalReceipts[_id];
address requester = receipt.requester;
address requestAsset = receipt.requestAsset;
uint256 requestShares = receipt.requestShares;
uint256 feeRate = receipt.feeRate;
if (msg.sender != requester) revert Errors.NotRequester();
if (accessRegistry.isBlacklisted(requester))
revert Errors.UserBlacklisted();
if (receipt.status != WITHDRAWAL_STATUS.PROCESSED)
revert Errors.InvalidReceiptStatus();
uint256 withdrawnAmount = requestShares
.mulDiv(
receipt.shareTokenPrice,
receipt.requestAssetPrice,
Math.Rounding.Floor
)
.denormalize(tokenDecimals[requestAsset]);
uint256 fee;
if (feeRate > 0) {
fee = withdrawnAmount.mulDiv(
feeRate,
FEE_DENOMINATOR,
Math.Rounding.Ceil
);
TransferHelper.safeTransfer(
requestAsset,
paramRegistry.getFeeRecipient(),
fee
);
withdrawnAmount -= fee;
}
shareToken.burn(requestShares);
TransferHelper.safeTransfer(requestAsset, requester, withdrawnAmount);
receipt.status = WITHDRAWAL_STATUS.COMPLETED;
emit WithdrawalCompleted(
requester,
requestAsset,
withdrawnAmount,
fee,
_id
);
}
}
"
},
"lib/openzeppelin-contracts/contracts/access/AccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
"
},
"lib/openzeppelin-contracts/contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool succes
Submitted on: 2025-10-23 16:40:14
Comments
Log in to comment.
No comments yet.