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/v1/router/TermMaxRouter_V1_1_1.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.27;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721Enumerable} from "@openzeppelin/contracts/interfaces/IERC721Enumerable.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 {ITermMaxMarket} from "../ITermMaxMarket.sol";
import {ITermMaxOrder} from "../ITermMaxOrder.sol";
import {SwapUnit, ISwapAdapter} from "./ISwapAdapter.sol";
import {RouterErrors} from "../errors/RouterErrors.sol";
import {RouterEvents} from "../events/RouterEvents.sol";
import {TransferUtils} from "../lib/TransferUtils.sol";
import {IFlashLoanReceiver} from "../IFlashLoanReceiver.sol";
import {IFlashRepayer} from "../tokens/IFlashRepayer.sol";
import {ITermMaxRouter} from "./ITermMaxRouter.sol";
import {IGearingToken} from "../tokens/IGearingToken.sol";
import {CurveCuts} from "../storage/TermMaxStorage.sol";
import {ISwapCallback} from "../ISwapCallback.sol";
import {Constants} from "../lib/Constants.sol";
import {MathLib} from "../lib/MathLib.sol";
import {IGtRepayer} from "./IGtRepayer.sol";
/**
* @title TermMax Router V1.1.1
* @author Term Structure Labs
* @notice Add reentrancy guard and more checks
*/
contract TermMaxRouter_V1_1_1 is
UUPSUpgradeable,
Ownable2StepUpgradeable,
PausableUpgradeable,
IFlashLoanReceiver,
IFlashRepayer,
IERC721Receiver,
ITermMaxRouter,
RouterErrors,
RouterEvents,
IGtRepayer,
ReentrancyGuardUpgradeable
{
using SafeCast for *;
using TransferUtils for IERC20;
using MathLib for uint256;
error CallbackAddressNotMatch();
enum FlashLoanType {
COLLATERAL,
DEBT
}
/// @notice whitelist mapping of adapter
mapping(address => bool) public adapterWhitelist;
uint256 private constant T_CALLBACK_ADDRESS_STORE = 1;
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 CallbackAddressNotMatch();
}
_;
}
function _authorizeUpgrade(address newImplementation) internal virtual override onlyOwner {}
function initialize(address admin) public initializer {
__ReentrancyGuard_init_unchained();
__UUPSUpgradeable_init();
__Pausable_init();
__Ownable_init(admin);
}
/**
* @inheritdoc ITermMaxRouter
*/
function setAdapterWhitelist(address adapter, bool isWhitelist) external onlyOwner {
adapterWhitelist[adapter] = isWhitelist;
emit UpdateSwapAdapterWhiteList(adapter, isWhitelist);
}
/**
* @inheritdoc ITermMaxRouter
*/
function assetsWithERC20Collateral(ITermMaxMarket market, address owner)
external
view
override
returns (IERC20[4] memory tokens, uint256[4] memory balances, address gtAddr, uint256[] memory gtIds)
{
(IERC20 ft, IERC20 xt, IGearingToken gt, address collateral, IERC20 underlying) = market.tokens();
tokens[0] = ft;
tokens[1] = xt;
tokens[2] = IERC20(collateral);
tokens[3] = underlying;
for (uint256 i = 0; i < 4; ++i) {
balances[i] = tokens[i].balanceOf(owner);
}
gtAddr = address(gt);
uint256 balance = IERC721Enumerable(gtAddr).balanceOf(owner);
gtIds = new uint256[](balance);
for (uint256 i = 0; i < balance; ++i) {
gtIds[i] = IERC721Enumerable(gtAddr).tokenOfOwnerByIndex(owner, i);
}
}
function swapExactTokenToToken(
IERC20 tokenIn,
IERC20 tokenOut,
address recipient,
ITermMaxOrder[] memory orders,
uint128[] memory tradingAmts,
uint128 minTokenOut,
uint256 deadline
) external nonReentrant whenNotPaused returns (uint256 netTokenOut) {
uint256 totalAmtIn = sum(tradingAmts);
tokenIn.safeTransferFrom(msg.sender, address(this), totalAmtIn);
netTokenOut = _swapExactTokenToToken(tokenIn, tokenOut, recipient, orders, tradingAmts, minTokenOut, deadline);
emit SwapExactTokenToToken(tokenIn, tokenOut, msg.sender, recipient, orders, tradingAmts, netTokenOut);
}
function _swapExactTokenToToken(
IERC20 tokenIn,
IERC20 tokenOut,
address recipient,
ITermMaxOrder[] memory orders,
uint128[] memory tradingAmts,
uint128 minTokenOut,
uint256 deadline
) internal returns (uint256 netTokenOut) {
if (orders.length != tradingAmts.length) revert OrdersAndAmtsLengthNotMatch();
for (uint256 i = 0; i < orders.length; ++i) {
ITermMaxOrder order = orders[i];
tokenIn.safeIncreaseAllowance(address(order), tradingAmts[i]);
netTokenOut += order.swapExactTokenToToken(tokenIn, tokenOut, recipient, tradingAmts[i], 0, deadline);
}
if (netTokenOut < minTokenOut) revert InsufficientTokenOut(address(tokenOut), netTokenOut, minTokenOut);
}
function swapTokenToExactToken(
IERC20 tokenIn,
IERC20 tokenOut,
address recipient,
ITermMaxOrder[] memory orders,
uint128[] memory tradingAmts,
uint128 maxTokenIn,
uint256 deadline
) external nonReentrant whenNotPaused returns (uint256 netTokenIn) {
tokenIn.safeTransferFrom(msg.sender, address(this), maxTokenIn);
netTokenIn = _swapTokenToExactToken(tokenIn, tokenOut, recipient, orders, tradingAmts, maxTokenIn, deadline);
tokenIn.safeTransfer(msg.sender, maxTokenIn - netTokenIn);
emit SwapTokenToExactToken(tokenIn, tokenOut, msg.sender, recipient, orders, tradingAmts, netTokenIn);
}
function _swapTokenToExactToken(
IERC20 tokenIn,
IERC20 tokenOut,
address recipient,
ITermMaxOrder[] memory orders,
uint128[] memory tradingAmts,
uint128 maxTokenIn,
uint256 deadline
) internal returns (uint256 netTokenIn) {
if (orders.length != tradingAmts.length) revert OrdersAndAmtsLengthNotMatch();
for (uint256 i = 0; i < orders.length; ++i) {
ITermMaxOrder order = orders[i];
tokenIn.safeIncreaseAllowance(address(order), maxTokenIn);
netTokenIn +=
order.swapTokenToExactToken(tokenIn, tokenOut, recipient, tradingAmts[i], maxTokenIn, deadline);
}
if (netTokenIn > maxTokenIn) revert InsufficientTokenIn(address(tokenIn), netTokenIn, maxTokenIn);
}
function sum(uint128[] memory values) internal pure returns (uint256 total) {
for (uint256 i = 0; i < values.length; ++i) {
total += values[i];
}
}
function sellTokens(
address recipient,
ITermMaxMarket market,
uint128 ftInAmt,
uint128 xtInAmt,
ITermMaxOrder[] memory orders,
uint128[] memory amtsToSellTokens,
uint128 minTokenOut,
uint256 deadline
) external nonReentrant whenNotPaused returns (uint256 netTokenOut) {
(IERC20 ft, IERC20 xt,,, IERC20 debtToken) = market.tokens();
(uint256 maxBurn, IERC20 toenToSell) = ftInAmt > xtInAmt ? (xtInAmt, ft) : (ftInAmt, xt);
ft.safeTransferFrom(msg.sender, address(this), ftInAmt);
ft.safeIncreaseAllowance(address(market), maxBurn);
xt.safeTransferFrom(msg.sender, address(this), xtInAmt);
xt.safeIncreaseAllowance(address(market), maxBurn);
market.burn(recipient, maxBurn);
netTokenOut = _swapExactTokenToToken(toenToSell, debtToken, recipient, orders, amtsToSellTokens, 0, deadline);
netTokenOut += maxBurn;
if (netTokenOut < minTokenOut) revert InsufficientTokenOut(address(debtToken), netTokenOut, minTokenOut);
emit SellTokens(market, msg.sender, recipient, ftInAmt, xtInAmt, orders, amtsToSellTokens, netTokenOut);
}
function leverageFromToken(
address recipient,
ITermMaxMarket market,
ITermMaxOrder[] memory orders,
uint128[] memory amtsToBuyXt,
uint128 minXtOut,
uint128 tokenToSwap,
uint128 maxLtv,
SwapUnit[] memory units,
uint256 deadline
) 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();
uint256 totalAmtToBuyXt = sum(amtsToBuyXt);
debtToken.safeTransferFrom(msg.sender, address(this), tokenToSwap + totalAmtToBuyXt);
netXtOut = _swapExactTokenToToken(debtToken, xt, address(this), orders, amtsToBuyXt, minXtOut, deadline);
bytes memory callbackData = abi.encode(address(gt), tokenToSwap, units, FlashLoanType.DEBT);
xt.safeIncreaseAllowance(address(market), netXtOut);
gtId = market.leverageByXt(recipient, netXtOut.toUint128(), callbackData);
(,, bytes memory collateralData) = gt.loanInfo(gtId);
(, uint128 ltv,) = gt.getLiquidationInfo(gtId);
if (ltv > maxLtv) {
revert LtvBiggerThanExpected(maxLtv, ltv);
}
emit IssueGt(market, gtId, msg.sender, recipient, tokenToSwap, netXtOut.toUint128(), ltv, collateralData);
}
/**
* @inheritdoc ITermMaxRouter
*/
function leverageFromXt(
address recipient,
ITermMaxMarket market,
uint128 xtInAmt,
uint128 tokenInAmt,
uint128 maxLtv,
SwapUnit[] memory units
) external nonReentrant whenNotPaused returns (uint256 gtId) {
assembly {
tstore(T_CALLBACK_ADDRESS_STORE, market) // set callback address
}
(, IERC20 xt, IGearingToken gt,, IERC20 debtToken) = market.tokens();
xt.safeTransferFrom(msg.sender, address(this), xtInAmt);
xt.safeIncreaseAllowance(address(market), xtInAmt);
debtToken.safeTransferFrom(msg.sender, address(this), tokenInAmt);
bytes memory callbackData = abi.encode(address(gt), tokenInAmt, units, FlashLoanType.DEBT);
gtId = market.leverageByXt(recipient, xtInAmt.toUint128(), callbackData);
(,, bytes memory collateralData) = gt.loanInfo(gtId);
(, uint128 ltv,) = gt.getLiquidationInfo(gtId);
if (ltv > maxLtv) {
revert LtvBiggerThanExpected(maxLtv, ltv);
}
emit IssueGt(market, gtId, msg.sender, recipient, tokenInAmt, xtInAmt, ltv, collateralData);
}
/**
* @inheritdoc ITermMaxRouter
*/
function leverageFromXtAndCollateral(
address recipient,
ITermMaxMarket market,
uint128 xtInAmt,
uint128 collateralInAmt,
uint128 maxLtv,
SwapUnit[] memory units
) external nonReentrant whenNotPaused returns (uint256 gtId) {
assembly {
tstore(T_CALLBACK_ADDRESS_STORE, market) // set callback address
}
(, IERC20 xt, IGearingToken gt, address collAddr,) = market.tokens();
IERC20 collateral = IERC20(collAddr);
xt.safeTransferFrom(msg.sender, address(this), xtInAmt);
xt.safeIncreaseAllowance(address(market), xtInAmt);
collateral.safeTransferFrom(msg.sender, address(this), collateralInAmt);
bytes memory callbackData = abi.encode(address(gt), 0, units, FlashLoanType.COLLATERAL);
gtId = market.leverageByXt(recipient, xtInAmt.toUint128(), callbackData);
(,, bytes memory collateralData) = gt.loanInfo(gtId);
(, uint128 ltv,) = gt.getLiquidationInfo(gtId);
if (ltv > maxLtv) {
revert LtvBiggerThanExpected(maxLtv, ltv);
}
emit IssueGt(market, gtId, msg.sender, recipient, 0, xtInAmt, ltv, collateralData);
}
/**
* @inheritdoc ITermMaxRouter
*/
function borrowTokenFromCollateral(
address recipient,
ITermMaxMarket market,
uint256 collInAmt,
ITermMaxOrder[] memory orders,
uint128[] memory tokenAmtsWantBuy,
uint128 maxDebtAmt,
uint256 deadline
) external nonReentrant whenNotPaused returns (uint256) {
(IERC20 ft,, IGearingToken gt, address collateralAddr, IERC20 debtToken) = market.tokens();
IERC20(collateralAddr).safeTransferFrom(msg.sender, address(this), collInAmt);
IERC20(collateralAddr).safeIncreaseAllowance(address(gt), collInAmt);
(uint256 gtId, uint128 ftOutAmt) = market.issueFt(address(this), maxDebtAmt, _encodeAmount(collInAmt));
gt.safeTransferFrom(address(this), recipient, gtId);
uint256 netTokenIn =
_swapTokenToExactToken(ft, debtToken, recipient, orders, tokenAmtsWantBuy, ftOutAmt, deadline);
uint256 repayAmt = ftOutAmt - netTokenIn;
if (repayAmt > 0) {
ft.safeIncreaseAllowance(address(gt), repayAmt);
gt.repay(gtId, repayAmt.toUint128(), false);
}
emit Borrow(market, gtId, msg.sender, recipient, collInAmt, ftOutAmt, netTokenIn.toUint128());
return gtId;
}
function borrowTokenFromCollateral(address recipient, ITermMaxMarket market, uint256 collInAmt, uint256 borrowAmt)
external
nonReentrant
whenNotPaused
returns (uint256)
{
(IERC20 ft, IERC20 xt, IGearingToken gt, address collateralAddr,) = market.tokens();
IERC20(collateralAddr).safeTransferFrom(msg.sender, 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, _encodeAmount(collInAmt));
gt.safeTransferFrom(address(this), recipient, gtId);
borrowAmt = borrowAmt.min(ftOutAmt);
xt.safeTransferFrom(msg.sender, address(this), borrowAmt);
ft.safeIncreaseAllowance(address(market), borrowAmt);
xt.safeIncreaseAllowance(address(market), borrowAmt);
market.burn(recipient, borrowAmt);
emit Borrow(market, gtId, msg.sender, recipient, collInAmt, debtAmt, borrowAmt.toUint128());
return gtId;
}
function borrowTokenFromGt(address recipient, ITermMaxMarket market, uint256 gtId, uint256 borrowAmt)
external
nonReentrant
whenNotPaused
{
(IERC20 ft, IERC20 xt, IGearingToken gt,,) = market.tokens();
if (gt.ownerOf(gtId) != msg.sender) {
revert GtNotOwnedBySender();
}
uint256 mintGtFeeRatio = market.mintGtFeeRatio();
uint128 debtAmt = ((borrowAmt * Constants.DECIMAL_BASE) / (Constants.DECIMAL_BASE - mintGtFeeRatio)).toUint128();
uint256 ftOutAmt = market.issueFtByExistedGt(address(this), debtAmt, gtId);
borrowAmt = borrowAmt.min(ftOutAmt);
xt.safeTransferFrom(msg.sender, address(this), borrowAmt);
ft.safeIncreaseAllowance(address(market), borrowAmt);
xt.safeIncreaseAllowance(address(market), borrowAmt);
market.burn(recipient, borrowAmt);
emit Borrow(market, gtId, msg.sender, recipient, 0, debtAmt, borrowAmt.toUint128());
}
function flashRepayFromColl(
address recipient,
ITermMaxMarket market,
uint256 gtId,
ITermMaxOrder[] memory orders,
uint128[] memory amtsToBuyFt,
bool byDebtToken,
SwapUnit[] memory units,
uint256 deadline
) external nonReentrant whenNotPaused returns (uint256 netTokenOut) {
(IERC20 ft,, IGearingToken gtToken,, IERC20 debtToken) = market.tokens();
assembly {
// set callback address
tstore(T_CALLBACK_ADDRESS_STORE, gtToken)
}
gtToken.safeTransferFrom(msg.sender, address(this), gtId, "");
gtToken.flashRepay(gtId, byDebtToken, abi.encode(orders, amtsToBuyFt, ft, units, deadline));
netTokenOut = debtToken.balanceOf(address(this));
debtToken.safeTransfer(recipient, netTokenOut);
}
function flashRepayFromColl(
address recipient,
ITermMaxMarket market,
uint256 gtId,
ITermMaxOrder[] memory orders,
uint128[] memory amtsToBuyFt,
bool byDebtToken,
uint256 expectedOutput,
SwapUnit[] memory units,
uint256 deadline
) external nonReentrant whenNotPaused returns (uint256 netTokenOut) {
(IERC20 ft,, IGearingToken gtToken,, IERC20 debtToken) = market.tokens();
assembly {
// set callback address
tstore(T_CALLBACK_ADDRESS_STORE, gtToken)
}
gtToken.safeTransferFrom(msg.sender, address(this), gtId, "");
gtToken.flashRepay(gtId, byDebtToken, abi.encode(orders, amtsToBuyFt, ft, units, deadline));
netTokenOut = debtToken.balanceOf(address(this));
if (netTokenOut < expectedOutput) {
revert InsufficientTokenOut(address(debtToken), expectedOutput, netTokenOut);
}
debtToken.safeTransfer(recipient, netTokenOut);
}
/**
* @inheritdoc ITermMaxRouter
*/
function repayByTokenThroughFt(
address recipient,
ITermMaxMarket market,
uint256 gtId,
ITermMaxOrder[] memory orders,
uint128[] memory ftAmtsWantBuy,
uint128 maxTokenIn,
uint256 deadline
) external nonReentrant whenNotPaused returns (uint256 returnAmt) {
(IERC20 ft,, IGearingToken gt,, IERC20 debtToken) = market.tokens();
debtToken.safeTransferFrom(msg.sender, address(this), maxTokenIn);
uint256 netCost =
_swapTokenToExactToken(debtToken, ft, address(this), orders, ftAmtsWantBuy, maxTokenIn, deadline);
uint256 totalFtAmt = sum(ftAmtsWantBuy);
(, uint128 repayAmt,) = gt.loanInfo(gtId);
if (totalFtAmt < repayAmt) {
repayAmt = totalFtAmt.toUint128();
}
ft.safeIncreaseAllowance(address(gt), repayAmt);
gt.repay(gtId, repayAmt, false);
returnAmt = maxTokenIn - netCost;
debtToken.safeTransfer(recipient, returnAmt);
if (totalFtAmt > repayAmt) {
ft.safeTransfer(recipient, totalFtAmt - repayAmt);
}
emit RepayByTokenThroughFt(market, gtId, msg.sender, recipient, repayAmt, returnAmt);
}
function redeemAndSwap(
address recipient,
ITermMaxMarket market,
uint256 ftAmount,
SwapUnit[] memory units,
uint256 minTokenOut
) external nonReentrant whenNotPaused returns (uint256) {
(IERC20 ft,,, address collateralAddr, IERC20 debtToken) = market.tokens();
ft.safeTransferFrom(msg.sender, address(this), ftAmount);
ft.safeIncreaseAllowance(address(market), ftAmount);
(uint256 redeemedAmt, bytes memory collateralData) = market.redeem(ftAmount, address(this));
redeemedAmt += _decodeAmount(_doSwap(collateralData, units));
if (redeemedAmt < minTokenOut) {
revert InsufficientTokenOut(address(debtToken), redeemedAmt, minTokenOut);
}
debtToken.safeTransfer(recipient, redeemedAmt);
emit RedeemAndSwap(market, ftAmount, msg.sender, recipient, redeemedAmt);
return redeemedAmt;
}
function createOrderAndDeposit(
ITermMaxMarket market,
address maker,
uint256 maxXtReserve,
ISwapCallback swapTrigger,
uint256 debtTokenToDeposit,
uint128 ftToDeposit,
uint128 xtToDeposit,
CurveCuts memory curveCuts
) external nonReentrant whenNotPaused returns (ITermMaxOrder order) {
(IERC20 ft, IERC20 xt,,, IERC20 debtToken) = market.tokens();
order = market.createOrder(maker, maxXtReserve, swapTrigger, curveCuts);
if (debtTokenToDeposit > 0) {
debtToken.safeTransferFrom(msg.sender, address(this), debtTokenToDeposit);
debtToken.safeIncreaseAllowance(address(market), debtTokenToDeposit);
market.mint(address(order), debtTokenToDeposit);
}
if (ftToDeposit > 0) {
ft.safeTransferFrom(msg.sender, address(order), ftToDeposit);
}
if (xtToDeposit > 0) {
xt.safeTransferFrom(msg.sender, address(order), xtToDeposit);
}
emit CreateOrderAndDeposit(market, order, maker, debtTokenToDeposit, ftToDeposit, xtToDeposit, curveCuts);
}
/// @dev Market flash leverage flashloan callback
function executeOperation(address, IERC20, uint256 amount, bytes memory data)
external
onlyCallbackAddress
returns (bytes memory collateralData)
{
(address gt, uint256 tokenInAmt, SwapUnit[] memory units, FlashLoanType flashLoanType) =
abi.decode(data, (address, uint256, SwapUnit[], FlashLoanType));
uint256 totalAmount = amount + tokenInAmt;
collateralData = _doSwap(abi.encode(totalAmount), units);
SwapUnit memory lastUnit = units[units.length - 1];
if (!adapterWhitelist[lastUnit.adapter]) {
revert AdapterNotWhitelisted(lastUnit.adapter);
}
if (flashLoanType == FlashLoanType.COLLATERAL) {
IERC20 collateral = IERC20(lastUnit.tokenOut);
uint256 collateralBalance = collateral.balanceOf(address(this));
collateralData = _encodeAmount(collateralBalance);
// approve all collateral if fashloan type is collateral
collateral.safeIncreaseAllowance(gt, collateralBalance);
} else if (flashLoanType == FlashLoanType.DEBT) {
bytes memory approvalData =
abi.encodeCall(ISwapAdapter.approveOutputToken, (lastUnit.tokenOut, gt, collateralData));
(bool success, bytes memory returnData) = lastUnit.adapter.delegatecall(approvalData);
if (!success) {
revert ApproveTokenFailWhenSwap(lastUnit.tokenOut, returnData);
}
}
}
function _balanceOf(IERC20 token, address account) internal view returns (uint256) {
return token.balanceOf(account);
}
function _encodeAmount(uint256 amount) internal pure returns (bytes memory) {
return abi.encode(amount);
}
function _decodeAmount(bytes memory collateralData) internal pure returns (uint256) {
return abi.decode(collateralData, (uint256));
}
/// @dev Gt flash repay flashloan callback
function executeOperation(
IERC20 repayToken,
uint128 debtAmt,
address,
bytes memory collateralData,
bytes memory callbackData
) external override onlyCallbackAddress {
(
ITermMaxOrder[] memory orders,
uint128[] memory amtsToBuyFt,
IERC20 ft,
SwapUnit[] memory units,
uint256 deadline
) = abi.decode(callbackData, (ITermMaxOrder[], uint128[], IERC20, SwapUnit[], uint256));
bytes memory outData = _doSwap(collateralData, units);
if (address(repayToken) == address(ft)) {
IERC20 debtToken = IERC20(units[units.length - 1].tokenOut);
uint256 amount = abi.decode(outData, (uint256));
_swapTokenToExactToken(debtToken, ft, address(this), orders, amtsToBuyFt, amount.toUint128(), deadline);
}
repayToken.safeIncreaseAllowance(msg.sender, debtAmt);
}
function _doSwap(bytes memory inputData, SwapUnit[] memory units) internal returns (bytes memory outData) {
if (units.length == 0) {
revert SwapUnitsIsEmpty();
}
for (uint256 i = 0; i < units.length; ++i) {
if (!adapterWhitelist[units[i].adapter]) {
revert AdapterNotWhitelisted(units[i].adapter);
}
bytes memory dataToSwap =
abi.encodeCall(ISwapAdapter.swap, (units[i].tokenIn, units[i].tokenOut, inputData, units[i].swapData));
(bool success, bytes memory returnData) = units[i].adapter.delegatecall(dataToSwap);
if (!success) {
revert SwapFailed(units[i].adapter, returnData);
}
inputData = abi.decode(returnData, (bytes));
}
outData = inputData;
}
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();
}
function repayGt(ITermMaxMarket market, uint256 gtId, uint128 maxRepayAmt, bool byDebtToken)
external
override
nonReentrant
whenNotPaused
returns (uint128 repayAmt)
{
(IERC20 ft,, IGearingToken gt,, IERC20 debtToken) = market.tokens();
(, uint128 debtAmt,) = gt.loanInfo(gtId); // Ensure gtId is valid
if (maxRepayAmt > debtAmt) {
repayAmt = debtAmt;
} else {
repayAmt = maxRepayAmt;
}
IERC20 repayToken = byDebtToken ? debtToken : ft;
repayToken.safeTransferFrom(msg.sender, address(this), repayAmt);
repayToken.safeIncreaseAllowance(address(gt), repayAmt);
gt.repay(gtId, repayAmt, byDebtToken);
}
}
"
},
"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/IERC721Enumerable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721Enumerable.sol)
pragma solidity ^0.8.20;
import {IERC721Enumerable} from "../token/ERC721/extensions/IERC721Enumerable.sol";
"
},
"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);
}
retu
Submitted on: 2025-09-25 11:23:52
Comments
Log in to comment.
No comments yet.