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": {
"contracts/v2/router/TermMaxRouterV2.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.27;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/interfaces/IERC721Receiver.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {
Ownable2StepUpgradeable,
OwnableUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ITermMaxMarket} from "../../v1/ITermMaxMarket.sol";
import {ITermMaxMarketV2} from "../ITermMaxMarketV2.sol";
import {SwapUnit} from "../../v1/router/ISwapAdapter.sol";
import {RouterErrors} from "../../v1/errors/RouterErrors.sol";
import {RouterEvents} from "../../v1/events/RouterEvents.sol";
import {TransferUtilsV2} from "../lib/TransferUtilsV2.sol";
import {IFlashLoanReceiver} from "../../v1/IFlashLoanReceiver.sol";
import {IFlashRepayer} from "../../v1/tokens/IFlashRepayer.sol";
import {ITermMaxRouterV2, SwapPath, FlashLoanType, FlashRepayOptions} from "./ITermMaxRouterV2.sol";
import {IGearingToken} from "../../v1/tokens/IGearingToken.sol";
import {IGearingTokenV2} from "../tokens/IGearingTokenV2.sol";
import {Constants} from "../../v1/lib/Constants.sol";
import {IERC20SwapAdapter} from "./IERC20SwapAdapter.sol";
import {IAaveV3Pool} from "../extensions/aave/IAaveV3Pool.sol";
import {ICreditDelegationToken} from "../extensions/aave/ICreditDelegationToken.sol";
import {IMorpho, Id, MarketParams, Authorization, Signature} from "../extensions/morpho/IMorpho.sol";
import {RouterErrorsV2} from "../errors/RouterErrorsV2.sol";
import {RouterEventsV2} from "../events/RouterEventsV2.sol";
import {ArrayUtilsV2} from "../lib/ArrayUtilsV2.sol";
import {IWhitelistManager} from "../access/IWhitelistManager.sol";
import {VersionV2} from "../VersionV2.sol";
/**
* @title TermMax Router V2
* @author Term Structure Labs
*/
contract TermMaxRouterV2 is
UUPSUpgradeable,
Ownable2StepUpgradeable,
PausableUpgradeable,
IFlashLoanReceiver,
IFlashRepayer,
IERC721Receiver,
ITermMaxRouterV2,
RouterErrors,
RouterEvents,
VersionV2,
ReentrancyGuardUpgradeable
{
using SafeCast for *;
using TransferUtilsV2 for IERC20;
using Math for *;
using ArrayUtilsV2 for *;
/// @notice whitelist mapping of adapter
mapping(address => bool) public adapterWhitelist;
IWhitelistManager internal whitelistManager;
uint256 private constant T_ROLLOVER_GT_RESERVE_STORE = 0;
uint256 private constant T_CALLBACK_ADDRESS_STORE = 1;
uint256 private constant T_CALLER = 2;
modifier onlyCallbackAddress() {
address callbackAddress;
assembly {
callbackAddress := tload(T_CALLBACK_ADDRESS_STORE)
// clear callback address after use
tstore(T_CALLBACK_ADDRESS_STORE, 0)
}
if (_msgSender() != callbackAddress) {
revert RouterErrorsV2.CallbackAddressNotMatch();
}
_;
}
modifier checkSwapPaths(SwapPath[] memory paths) {
if (paths.length == 0 || paths[0].units.length == 0) revert RouterErrorsV2.SwapPathsIsEmpty();
_;
}
function _authorizeUpgrade(address newImplementation) internal virtual override onlyOwner {}
function initialize(address admin, address whitelistManager_) external initializer {
__ReentrancyGuard_init_unchained();
__UUPSUpgradeable_init_unchained();
__Pausable_init_unchained();
__Ownable_init_unchained(admin);
_setWhitelistManager(whitelistManager_);
}
function initializeV2(address whitelistManager_) external reinitializer(2) {
__ReentrancyGuard_init_unchained();
_setWhitelistManager(whitelistManager_);
}
function setWhitelistManager(address whitelistManager_) external onlyOwner {
_setWhitelistManager(whitelistManager_);
}
function _setWhitelistManager(address whitelistManager_) internal {
whitelistManager = IWhitelistManager(whitelistManager_);
emit RouterEventsV2.WhitelistManagerUpdated(whitelistManager_);
}
/**
* @inheritdoc ITermMaxRouterV2
*/
function swapTokens(SwapPath[] memory paths)
external
nonReentrant
whenNotPaused
checkSwapPaths(paths)
returns (uint256[] memory)
{
return _executeSwapPaths(paths);
}
function _executeSwapPaths(SwapPath[] memory paths) internal returns (uint256[] memory netTokenOuts) {
netTokenOuts = new uint256[](paths.length);
for (uint256 i = 0; i < paths.length; ++i) {
SwapPath memory path = paths[i];
if (path.useBalanceOnchain) {
uint256 balanceOnChain = IERC20(path.units[0].tokenIn).balanceOf(address(this));
netTokenOuts[i] = _executeSwapUnits(path.recipient, balanceOnChain, path.units);
} else {
IERC20(path.units[0].tokenIn).safeTransferFrom(_msgSender(), address(this), path.inputAmount);
netTokenOuts[i] = _executeSwapUnits(path.recipient, path.inputAmount, path.units);
}
}
return netTokenOuts;
}
function _executeSwapUnits(address recipient, uint256 inputAmt, SwapUnit[] memory units)
internal
returns (uint256 outputAmt)
{
if (units.length == 0) {
revert SwapUnitsIsEmpty();
}
for (uint256 i = 0; i < units.length; ++i) {
if (units[i].tokenIn == units[i].tokenOut) {
continue;
}
if (units[i].adapter == address(0)) {
// transfer token directly if no adapter is specified
IERC20(units[i].tokenIn).safeTransfer(recipient, inputAmt);
continue;
}
_checkAdapterWhitelist(units[i].adapter);
bytes memory dataToSwap = i == units.length - 1
? abi.encodeCall(
IERC20SwapAdapter.swap, (recipient, units[i].tokenIn, units[i].tokenOut, inputAmt, units[i].swapData)
)
: abi.encodeCall(
IERC20SwapAdapter.swap,
(address(this), units[i].tokenIn, units[i].tokenOut, inputAmt, units[i].swapData)
);
(bool success, bytes memory returnData) = units[i].adapter.delegatecall(dataToSwap);
if (!success) {
revert SwapFailed(units[i].adapter, returnData);
}
inputAmt = abi.decode(returnData, (uint256));
}
outputAmt = inputAmt;
}
/**
* @inheritdoc ITermMaxRouterV2
*/
function leverage(
address recipient,
ITermMaxMarket market,
uint128 maxLtv,
bool isV1,
SwapPath[] memory inputPaths,
SwapPath memory swapXtPath,
SwapPath memory swapCollateralPath
) external nonReentrant whenNotPaused returns (uint256 gtId, uint256 netXtOut) {
assembly {
tstore(T_CALLBACK_ADDRESS_STORE, market) // set callback address
}
(, IERC20 xt, IGearingToken gt,, IERC20 debtToken) = market.tokens();
// transfer input tokens(may swap any token to debt token)
_executeSwapPaths(inputPaths);
uint256 totalDebtToken = debtToken.balanceOf(address(this));
// swap debt token to xt token if needed
if (swapXtPath.units.length != 0) {
netXtOut = _executeSwapUnits(address(this), swapXtPath.inputAmount, swapXtPath.units);
}
uint256 totalXt = xt.balanceOf(address(this));
bytes memory callbackData = abi.encode(address(gt), swapCollateralPath.units);
if (isV1) {
xt.safeIncreaseAllowance(address(market), totalXt);
gtId = market.leverageByXt(recipient, totalXt.toUint128(), callbackData);
} else {
gtId = ITermMaxMarketV2(address(market)).leverageByXt(
address(this), recipient, totalXt.toUint128(), callbackData
);
}
(,, bytes memory collateralData) = gt.loanInfo(gtId);
(, uint128 ltv,) = gt.getLiquidationInfo(gtId);
if (ltv > maxLtv) {
revert LtvBiggerThanExpected(maxLtv, ltv);
}
emit IssueGt(
market,
gtId,
_msgSender(),
recipient,
(totalDebtToken).toUint128(),
netXtOut.toUint128(),
ltv,
collateralData
);
}
function borrowTokenFromCollateral(
address recipient,
ITermMaxMarket market,
uint256 collInAmt,
uint128 maxDebtAmt,
SwapPath memory swapFtPath
) external nonReentrant whenNotPaused returns (uint256) {
(IERC20 ft,, IGearingToken gt, address collateralAddr,) = market.tokens();
IERC20(collateralAddr).safeTransferFrom(_msgSender(), address(this), collInAmt);
IERC20(collateralAddr).safeIncreaseAllowance(address(gt), collInAmt);
(uint256 gtId, uint128 ftOutAmt) = market.issueFt(address(this), maxDebtAmt, abi.encode(collInAmt));
gt.safeTransferFrom(address(this), recipient, gtId);
uint256 netTokenIn = _executeSwapUnits(swapFtPath.recipient, ftOutAmt, swapFtPath.units);
uint256 repayAmt = ftOutAmt - netTokenIn;
if (repayAmt > 0) {
ft.safeIncreaseAllowance(address(gt), repayAmt);
// repay in ft, bool false means not using debt token
gt.repay(gtId, repayAmt.toUint128(), false);
}
emit Borrow(market, gtId, _msgSender(), recipient, collInAmt, ftOutAmt, netTokenIn.toUint128());
return gtId;
}
function borrowTokenFromCollateralAndXt(
address recipient,
ITermMaxMarket market,
uint256 collInAmt,
uint256 borrowAmt,
bool isV1
) external nonReentrant whenNotPaused returns (uint256) {
(IERC20 ft, IERC20 xt, IGearingToken gt, address collateralAddr,) = market.tokens();
IERC20(collateralAddr).safeTransferFrom(_msgSender(), address(this), collInAmt);
IERC20(collateralAddr).safeIncreaseAllowance(address(gt), collInAmt);
uint256 mintGtFeeRatio = market.mintGtFeeRatio();
uint128 debtAmt = ((borrowAmt * Constants.DECIMAL_BASE) / (Constants.DECIMAL_BASE - mintGtFeeRatio)).toUint128();
(uint256 gtId, uint128 ftOutAmt) = market.issueFt(address(this), debtAmt, abi.encode(collInAmt));
gt.safeTransferFrom(address(this), recipient, gtId);
borrowAmt = borrowAmt.min(ftOutAmt);
xt.safeTransferFrom(_msgSender(), address(this), borrowAmt);
if (isV1) {
xt.safeIncreaseAllowance(address(market), borrowAmt);
ft.safeIncreaseAllowance(address(market), borrowAmt);
}
market.burn(recipient, borrowAmt);
emit Borrow(market, gtId, _msgSender(), recipient, collInAmt, debtAmt, borrowAmt.toUint128());
return gtId;
}
function flashRepayFromColl(
address recipient,
ITermMaxMarket market,
uint256 gtId,
bool byDebtToken,
uint256 expectedOutput,
bytes memory callbackData
) external nonReentrant whenNotPaused returns (uint256 netTokenOut) {
(,, IGearingToken gtToken,, IERC20 debtToken) = market.tokens();
assembly {
// set callback address
tstore(T_CALLBACK_ADDRESS_STORE, gtToken)
}
gtToken.safeTransferFrom(_msgSender(), address(this), gtId, "");
gtToken.flashRepay(gtId, byDebtToken, callbackData);
netTokenOut = debtToken.balanceOf(address(this));
if (netTokenOut < expectedOutput) {
revert InsufficientTokenOut(address(debtToken), expectedOutput, netTokenOut);
}
debtToken.safeTransfer(recipient, netTokenOut);
emit RouterEventsV2.FlashRepay(address(gtToken), gtId, netTokenOut);
}
function rolloverGt(
IGearingToken gtToken,
uint256 gtId,
IERC20 additionalAsset,
uint256 additionalAmt,
bytes memory rolloverData
) external nonReentrant whenNotPaused returns (uint256 newGtId) {
return _rolloverGt(gtToken, gtId, additionalAsset, additionalAmt, rolloverData);
}
function _rolloverGt(
IGearingToken gtToken,
uint256 gtId,
IERC20 additionalAsset,
uint256 additionalAmt,
bytes memory rolloverData
) internal returns (uint256 newGtId) {
address firstCaller = _msgSender();
assembly {
// set callback address
tstore(T_CALLBACK_ADDRESS_STORE, gtToken)
// clear ts stograge
tstore(T_ROLLOVER_GT_RESERVE_STORE, 0)
// set caller address
tstore(T_CALLER, firstCaller)
}
// additional debt/new collateral token to reduce the ltv
if (additionalAmt != 0) {
additionalAsset.safeTransferFrom(firstCaller, address(this), additionalAmt);
}
gtToken.safeTransferFrom(firstCaller, address(this), gtId, "");
gtToken.flashRepay(gtId, true, rolloverData);
assembly {
newGtId := tload(T_ROLLOVER_GT_RESERVE_STORE)
}
emit RouterEventsV2.RolloverGt(address(gtToken), gtId, newGtId, address(additionalAsset), additionalAmt);
}
/**
* @inheritdoc ITermMaxRouterV2
*/
function swapAndRepay(IGearingToken gt, uint256 gtId, uint128 repayAmt, bool byDebtToken, SwapPath[] memory paths)
external
override
nonReentrant
whenNotPaused
checkSwapPaths(paths)
returns (uint256[] memory netOutOrIns)
{
netOutOrIns = _executeSwapPaths(paths);
IERC20 repayToken = IERC20(paths[0].units[paths[0].units.length - 1].tokenOut);
repayToken.safeIncreaseAllowance(address(gt), repayAmt);
gt.repay(gtId, repayAmt, byDebtToken);
uint256 remainingRepayToken = repayToken.balanceOf(address(this));
if (remainingRepayToken != 0) {
repayToken.safeTransfer(_msgSender(), remainingRepayToken);
}
emit RouterEventsV2.SwapAndRepay(address(gt), gtId, repayAmt, remainingRepayToken);
}
/// @dev Market flash leverage flashloan callback
function executeOperation(address, IERC20, uint256, bytes memory data)
external
override
onlyCallbackAddress
returns (bytes memory collateralData)
{
(address gt, SwapUnit[] memory units) = abi.decode(data, (address, SwapUnit[]));
uint256 totalAmount = IERC20(units[0].tokenIn).balanceOf(address(this));
uint256 collateralBalance = _executeSwapUnits(address(this), totalAmount, units);
SwapUnit memory lastUnit = units[units.length - 1];
_checkAdapterWhitelist(lastUnit.adapter);
IERC20 collateral = IERC20(lastUnit.tokenOut);
collateralBalance = collateral.balanceOf(address(this));
collateral.safeIncreaseAllowance(gt, collateralBalance);
collateralData = abi.encode(collateralBalance);
}
/// @dev Gt flash repay flashloan callback
function executeOperation(
IERC20 repayToken,
uint128 repayAmt,
address,
bytes memory removedCollateralData,
bytes memory callbackData
) external override onlyCallbackAddress {
(FlashRepayOptions option, bytes memory data) = abi.decode(callbackData, (FlashRepayOptions, bytes));
if (option == FlashRepayOptions.REPAY) {
_flashRepay(data);
} else if (option == FlashRepayOptions.ROLLOVER) {
_rollover(repayToken, repayAmt, removedCollateralData, data);
} else {
address firstCaller;
assembly {
firstCaller := tload(T_CALLER)
//clear caller address after use
tstore(T_CALLER, 0)
}
if (option == FlashRepayOptions.ROLLOVER_AAVE) {
_rolloverToAave(firstCaller, repayToken, repayAmt, removedCollateralData, data);
} else if (option == FlashRepayOptions.ROLLOVER_MORPHO) {
_rolloverToMorpho(firstCaller, repayToken, repayAmt, removedCollateralData, data);
}
}
repayToken.safeIncreaseAllowance(_msgSender(), repayAmt);
}
function _flashRepay(bytes memory callbackData) internal {
// By debt token: collateral-> debt token
// By ft token: collateral-> debt token -> exact ft token
SwapPath memory repayTokenPath = abi.decode(callbackData, (SwapPath));
_executeSwapUnits(address(this), repayTokenPath.inputAmount, repayTokenPath.units);
}
function _rollover(IERC20, uint256, bytes memory, bytes memory callbackData) internal {
(
address recipient,
ITermMaxMarket market,
uint128 maxLtv,
SwapPath memory collateralPath,
SwapPath memory debtTokenPath
) = abi.decode(callbackData, (address, ITermMaxMarket, uint128, SwapPath, SwapPath));
// Do swap to get the new collateral,(the inpput amount may contains additional old collateral)
if (collateralPath.units.length != 0) {
_executeSwapUnits(address(this), collateralPath.inputAmount, collateralPath.units);
}
(IERC20 ft,, IGearingToken gt, address collateral,) = market.tokens();
// Get balances, may contain additional new collateral
uint256 newCollateralAmt = IERC20(collateral).balanceOf(address(this));
uint256 gtId;
// issue new gt to get new ft token
{
// issue new gt
uint256 mintGtFeeRatio = market.mintGtFeeRatio();
uint128 newDebtAmt = (
(debtTokenPath.inputAmount * Constants.DECIMAL_BASE) / (Constants.DECIMAL_BASE - mintGtFeeRatio)
).toUint128();
IERC20(collateral).safeIncreaseAllowance(address(gt), newCollateralAmt);
(gtId,) = market.issueFt(address(this), newDebtAmt, abi.encode(newCollateralAmt));
// transfer new gt to recipient
gt.safeTransferFrom(address(this), recipient, gtId);
}
// Swap ft to debt token to repay(swap amount + additional debt token amount should equal repay amt)
{
uint256 netFtCost = _executeSwapUnits(address(this), debtTokenPath.inputAmount, debtTokenPath.units);
// check remaining ft amount
if (debtTokenPath.inputAmount > netFtCost) {
uint256 repaidFtAmt = debtTokenPath.inputAmount - netFtCost;
ft.safeIncreaseAllowance(address(gt), repaidFtAmt);
// repay in ft, bool false means not using debt token
gt.repay(gtId, repaidFtAmt.toUint128(), false);
}
(, uint128 ltv,) = gt.getLiquidationInfo(gtId);
if (ltv > maxLtv) {
revert LtvBiggerThanExpected(maxLtv, ltv);
}
}
assembly {
tstore(T_ROLLOVER_GT_RESERVE_STORE, gtId)
}
}
function _rolloverToAave(
address caller,
IERC20 debtToken,
uint256 repayAmt,
bytes memory,
bytes memory callbackData
) internal {
(
IERC20 collateral,
IAaveV3Pool aave,
uint256 interestRateMode,
uint16 referralCode,
ICreditDelegationToken.AaveDelegationParams memory delegationParams,
SwapPath memory collateralPath
) = abi.decode(
callbackData, (IERC20, IAaveV3Pool, uint256, uint16, ICreditDelegationToken.AaveDelegationParams, SwapPath)
);
if (delegationParams.delegator != address(0)) {
// delegate with sig
delegationParams.aaveDebtToken.delegationWithSig(
delegationParams.delegator,
delegationParams.delegatee,
delegationParams.value,
delegationParams.deadline,
delegationParams.v,
delegationParams.r,
delegationParams.s
);
}
repayAmt = repayAmt - debtToken.balanceOf(address(this));
if (collateralPath.units.length > 0) {
// do swap to get the new collateral
uint256 newCollateralAmt =
_executeSwapUnits(address(this), collateral.balanceOf(address(this)), collateralPath.units);
IERC20 newCollateral = IERC20(collateralPath.units[collateralPath.units.length - 1].tokenOut);
newCollateral.safeIncreaseAllowance(address(aave), newCollateralAmt);
aave.supply(address(newCollateral), newCollateralAmt, caller, referralCode);
} else {
uint256 collateralAmt = collateral.balanceOf(address(this));
collateral.safeIncreaseAllowance(address(aave), collateralAmt);
aave.supply(address(collateral), collateralAmt, caller, referralCode);
}
aave.borrow(address(debtToken), repayAmt, interestRateMode, referralCode, caller);
}
function _rolloverToMorpho(
address caller,
IERC20 debtToken,
uint256 repayAmt,
bytes memory,
bytes memory callbackData
) internal {
(
IERC20 collateral,
IMorpho morpho,
Id marketId,
Authorization memory auth,
Signature memory sig,
SwapPath memory collateralPath
) = abi.decode(callbackData, (IERC20, IMorpho, Id, Authorization, Signature, SwapPath));
MarketParams memory marketParams = morpho.idToMarketParams(marketId);
if (auth.authorized != address(0)) {
// auth with sig
morpho.setAuthorizationWithSig(auth, sig);
}
repayAmt = repayAmt - debtToken.balanceOf(address(this));
if (collateralPath.units.length > 0) {
// do swap to get the new collateral
uint256 newCollateralAmt =
_executeSwapUnits(address(this), collateral.balanceOf(address(this)), collateralPath.units);
IERC20 newCollateral = IERC20(collateralPath.units[collateralPath.units.length - 1].tokenOut);
newCollateral.safeIncreaseAllowance(address(morpho), newCollateralAmt);
morpho.supplyCollateral(marketParams, newCollateralAmt, caller, "");
} else {
uint256 collateralAmt = collateral.balanceOf(address(this));
collateral.safeIncreaseAllowance(address(morpho), collateralAmt);
morpho.supplyCollateral(marketParams, collateralAmt, caller, "");
}
/// @dev Borrow the repay amount from morpho, share amount is 0 and receiver is the router itself
morpho.borrow(marketParams, repayAmt, 0, caller, address(this));
}
function _checkAdapterWhitelist(address adapter) internal view {
if (!whitelistManager.isWhitelisted(adapter, IWhitelistManager.ContractModule.ADAPTER)) {
revert AdapterNotWhitelisted(adapter);
}
}
function onERC721Received(address, address, uint256, bytes memory) external pure override returns (bytes4) {
return this.onERC721Received.selector;
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/token/ERC20/IERC20.sol": {
"content": "// 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);
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/interfaces/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721Receiver.sol)
pragma solidity ^0.8.20;
import {IERC721Receiver} from "../token/ERC721/IERC721Receiver.sol";
"
},
"dependencies/@openzeppelin-contracts-upgradeable-5.2.0/proxy/utils/UUPSUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
* 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);
}
}
}
"
},
"dependencies/@openzeppelin-contracts-upgradeable-5.2.0/utils/ReentrancyGuardUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
"
},
"dependencies/@openzeppelin-contracts-upgradeable-5.2.0/utils/PausableUpgradeable.sol": {
"content": "// 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());
}
}
"
},
"dependencies/@openzeppelin-contracts-upgradeable-5.2.0/access/Ownable2StepUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {OwnableUpgradeable} from "./OwnableUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable2Step
struct Ownable2StepStorage {
address _pendingOwner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable2Step")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant Ownable2StepStorageLocation = 0x237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00;
function _getOwnable2StepStorage() private pure returns (Ownable2StepStorage storage $) {
assembly {
$.slot := Ownable2StepStorageLocation
}
}
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
function __Ownable2Step_init() internal onlyInitializing {
}
function __Ownable2Step_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
return $._pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
$._pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
delete $._pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
"
},
"dependencies/@openzeppelin-contracts-5.2.0/utils/math/SafeCast.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - in
Submitted on: 2025-10-13 11:00:47
Comments
Log in to comment.
No comments yet.