Verified contractPartialApache-2.0
PendlePTHook
Address0x265fc97e53fdb8816e9b6a67d59e592876cbdf8a
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- prague
- License
- Apache-2.0
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,639,644
- Creation transaction
- 0xfac25c962c…2e7d677d95
23 files
- src/hooks/swappers/pendle/PendlePTHook.solmain25.79 KB
- lib/modulekit/src/accounts/common/interfaces/IERC7579Account.sol5.01 KB
- lib/modulekit/src/accounts/common/lib/ModeLib.sol5.98 KB
- lib/modulekit/src/accounts/erc7579/lib/ExecutionLib.sol3.14 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.15 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- src/hooks/BaseHook.sol18.75 KB
- src/interfaces/ISuperHook.sol16.34 KB
- src/interfaces/ISuperHookSwap.sol2.72 KB
- src/libraries/HookDataDecoder.sol530 B
- src/libraries/HookDataUpdater.sol1.06 KB
- src/libraries/HookSubTypes.sol1.92 KB
- src/libraries/SwapCalldataLayout.sol2.2 KB
- src/vendor/BytesLib.sol19.29 KB
- src/vendor/pendle/IPYieldToken.sol1.86 KB
- src/vendor/pendle/IPendleMarket.sol184 B
- src/vendor/pendle/IPendleRouterV4.sol2.93 KB
- src/vendor/pendle/IStandardizedYield.sol6.67 KB
src/hooks/swappers/pendle/PendlePTHook.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
// external
import { BytesLib } from "../../../vendor/BytesLib.sol";
import { Execution } from "modulekit/accounts/erc7579/lib/ExecutionLib.sol";
import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
// Superform
import { BaseHook } from "../../BaseHook.sol";
import {
ISuperHook,
ISuperHookResult,
ISuperHookContextAware,
ISuperHookInspector,
ISuperHookInflowOutflow,
ISuperHookOutflow
} from "../../../interfaces/ISuperHook.sol";
import {
IPendleRouterV4,
ApproxParams,
TokenInput,
LimitOrderData,
TokenOutput,
SwapData,
SwapType
} from "../../../vendor/pendle/IPendleRouterV4.sol";
import { IPendleMarket } from "../../../vendor/pendle/IPendleMarket.sol";
import { IPYieldToken } from "../../../vendor/pendle/IPYieldToken.sol";
import { IStandardizedYield } from "../../../vendor/pendle/IStandardizedYield.sol";
import { HookSubTypes } from "../../../libraries/HookSubTypes.sol";
import { HookDataDecoder } from "../../../libraries/HookDataDecoder.sol";
import { HookDataUpdater } from "../../../libraries/HookDataUpdater.sol";
import { SwapCalldataLayout } from "../../../libraries/SwapCalldataLayout.sol";
import { ISuperHookSwap } from "../../../interfaces/ISuperHookSwap.sol";
/// @title PendlePTHook
/// @author Superform Labs
/// @notice Simplified Pendle hook for PT operations — derives operation type from header tokens + YT expiry
/// @dev Pure PT operations only: no auxiliary swapping or wrapping. SwapData is constructed
/// @dev internally with SwapType.NONE; any pre/post token conversion is done by adjacent hooks.
/// @dev No selector in payload. Pure AMM swaps + par redemption (no limit orders).
/// @dev Payload (Buy PT): abi.encode(ApproxParams guessPtOut)
/// @dev Payload (Sell PT): empty bytes (payload_paramLength = 0)
/// @dev Payload (Redeem PT): empty bytes (payload_paramLength = 0)
/// @dev Operation routing:
/// @dev outputToken == PT && inputToken != PT → swapExactTokenForPt (buy)
/// @dev inputToken == PT && outputToken != PT && !yt.isExpired() → swapExactPtForToken (sell)
/// @dev inputToken == PT && outputToken != PT && yt.isExpired() → redeemPyToToken (redeem)
/// @dev Note: At the exact expiry block, isExpired() returns true, routing to redeem.
/// @dev Sell and redeem payloads are identical (empty), so expiry-boundary routing is harmless.
/// @dev anything else → revert
/// @dev Header inputToken is used directly as TokenInput.tokenMintSy (buy); header outputToken is
/// @dev used directly as TokenOutput.tokenRedeemSy (sell/redeem). Native input is address(0);
/// @dev the 0xEeee… sentinel is normalized to address(0) on the buy input side.
/// @dev data layout: standard Layer 0 (52-byte header) + Layer 1 (swap params) + Layer 2 (payload)
/// @notice bytes32 yieldSourceOracleId = BytesLib.toBytes32(data, 0);
/// @notice address yieldSource = BytesLib.toAddress(data, 32);
/// @notice address inputToken = BytesLib.toAddress(data, 52);
/// @notice address outputToken = BytesLib.toAddress(data, 72);
/// @notice uint256 inputAmount = BytesLib.toUint256(data, 92);
/// @notice uint256 outputQuote = BytesLib.toUint256(data, 124);
/// @notice uint256 outputMin = BytesLib.toUint256(data, 156);
/// @notice bool usePrevHookAmount = _decodeBool(data, 188);
/// @notice uint256 payload_paramLength = BytesLib.toUint256(data, 189);
/// @notice bytes payload = BytesLib.slice(data, 221, payload_paramLength);
/// @dev Trust assumptions: same as PendleUnifiedHook
/// @dev - yieldSource (Pendle market) is trusted from the signed intent
/// @dev - readTokens() on market returns (SY, PT, YT) — a malicious market could return attacker-controlled addresses
/// @dev - Signer is responsible for only submitting known-good market addresses
contract PendlePTHook is BaseHook, ISuperHookSwap, ISuperHookContextAware, ISuperHookInflowOutflow, ISuperHookOutflow {
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev Maximum epsilon for Pendle's binary search approximation (100% in 1e18 scale)
uint256 private constant MAX_EPS = 1e18;
/// @dev Maximum iterations for Pendle's binary search approximation
uint256 private constant MAX_ITERATIONS = 256;
/// @dev Native token sentinel address
address private constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/*//////////////////////////////////////////////////////////////
DATA LAYOUT POSITIONS
//////////////////////////////////////////////////////////////*/
uint256 private constant AMOUNT_POSITION = SwapCalldataLayout.AMOUNT_POSITION;
/*//////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
IPendleRouterV4 public immutable PENDLE_ROUTER_V4;
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when the header token combination does not match any valid PT operation
error INVALID_PT_OPERATION();
/// @notice Thrown when ApproxParams epsilon exceeds MAX_EPS (1e18)
error EPS_NOT_VALID();
/// @notice Thrown when the SY address from the market is the zero address
error SY_NOT_VALID();
/// @notice Thrown when the minimum output amount is zero
error MIN_OUT_NOT_VALID();
/// @notice Thrown when the input amount is zero
error AMOUNT_IN_NOT_VALID();
/// @notice Thrown when guessMin exceeds guessMax in ApproxParams
error GUESS_PT_OUT_NOT_VALID();
/// @notice Thrown when the input token is not a valid tokenIn of the SY contract
error TOKEN_IN_NOT_LISTED();
/// @notice Thrown when the output token is not a valid tokenOut of the SY contract
error TOKEN_OUT_NOT_LISTED();
/// @notice Thrown when ApproxParams maxIteration exceeds MAX_ITERATIONS (256)
error MAX_ITERATION_NOT_VALID();
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Initializes the PendlePTHook with the Pendle Router V4 address
/// @param pendleRouterV4_ The address of the Pendle Router V4 contract
constructor(address pendleRouterV4_) BaseHook(HookType.NONACCOUNTING, HookSubTypes.PTYT) {
if (pendleRouterV4_ == address(0)) revert ADDRESS_NOT_VALID();
PENDLE_ROUTER_V4 = IPendleRouterV4(pendleRouterV4_);
}
/// @notice Human-readable name for UI display
function name() external pure override returns (string memory) {
return "Pendle PT";
}
/// @notice One-sentence description of what this hook does
function description() external pure override returns (string memory) {
return "Executes Pendle PT operations (buy, sell, or redeem)";
}
/*//////////////////////////////////////////////////////////////
VIEW METHODS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc BaseHook
function _buildHookExecutions(
address prevHook,
address account,
bytes calldata data
)
internal
view
override
returns (Execution[] memory executions)
{
address yieldSource = HookDataDecoder.extractYieldSource(data);
address headerOutputToken = BytesLib.toAddress(data, SwapCalldataLayout.OUTPUT_TOKEN_OFFSET);
// Pre-compute amounts
uint256 netTokenIn;
uint256 scaledOutputMin;
{
uint256 outputMin = BytesLib.toUint256(data, SwapCalldataLayout.OUTPUT_MIN_OFFSET);
if (outputMin == 0) revert MIN_OUT_NOT_VALID();
bool usePrevHookAmount = _decodeBool(data, SwapCalldataLayout.USE_PREV_HOOK_OFFSET);
uint256 inputAmount = BytesLib.toUint256(data, SwapCalldataLayout.INPUT_AMOUNT_OFFSET);
if (usePrevHookAmount) {
netTokenIn = ISuperHookResult(prevHook).getOutAmount(account);
scaledOutputMin = HookDataUpdater.getUpdatedOutputAmount(netTokenIn, inputAmount, outputMin);
if (scaledOutputMin == 0) revert MIN_OUT_NOT_VALID();
} else {
netTokenIn = inputAmount;
scaledOutputMin = outputMin;
}
if (netTokenIn == 0) revert AMOUNT_IN_NOT_VALID();
}
// Derive PT, YT from market — single readTokens() call, passed to builders
(address sy, address pt, address yt) = IPendleMarket(yieldSource).readTokens();
if (sy == address(0)) revert SY_NOT_VALID();
// Route based on header tokens + expiry
address headerInputToken = BytesLib.toAddress(data, SwapCalldataLayout.INPUT_TOKEN_OFFSET);
if (headerOutputToken == pt && headerInputToken != pt) {
// Buy PT: token → PT
bytes memory routingParams = data[SwapCalldataLayout.PAYLOAD_DATA_OFFSET:];
executions = _buildSwapTokenForPtExecutions(
account, yieldSource, sy, headerInputToken, netTokenIn, scaledOutputMin, routingParams
);
} else if (headerInputToken == pt && headerOutputToken != pt) {
if (!IPYieldToken(yt).isExpired()) {
// Sell PT: PT → token (AMM, pre-maturity)
executions = _buildSwapPtForTokenExecutions(
account, yieldSource, sy, pt, headerOutputToken, netTokenIn, scaledOutputMin
);
} else {
// Redeem PT: PT+YT → token (post-maturity)
executions = _buildRedeemExecutions(
account, sy, pt, yt, headerOutputToken, netTokenIn, scaledOutputMin
);
}
} else {
revert INVALID_PT_OPERATION();
}
}
/*//////////////////////////////////////////////////////////////
EXTERNAL METHODS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ISuperHookContextAware
function decodeUsePrevHookAmount(bytes memory data) external pure returns (bool) {
return _decodeBool(data, SwapCalldataLayout.USE_PREV_HOOK_OFFSET);
}
/// @inheritdoc ISuperHookInflowOutflow
function decodeAmounts(bytes memory data) external pure override returns (uint256[] memory amounts) {
amounts = new uint256[](1);
amounts[0] = BytesLib.toUint256(data, AMOUNT_POSITION);
}
/// @inheritdoc ISuperHookInflowOutflow
function amountRoles(bytes memory) external pure override returns (ISuperHookInflowOutflow.AmountMeta[] memory meta) {
meta = new ISuperHookInflowOutflow.AmountMeta[](1);
meta[0] = ISuperHookInflowOutflow.AmountMeta(ISuperHookInflowOutflow.Direction.IN, ISuperHookInflowOutflow.Denomination.TOKEN);
}
/// @inheritdoc BaseHook
function _supportsSizingInterface() internal pure override returns (bool) {
return true;
}
/// @inheritdoc ISuperHookOutflow
function replaceCalldataAmounts(
bytes memory data,
uint256[] memory amounts
)
external
pure
override
returns (bytes memory)
{
if (amounts.length != 1) revert INVALID_AMOUNTS_LENGTH();
return _replaceCalldataAmount(data, amounts[0], AMOUNT_POSITION);
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) external pure override returns (bool) {
if (interfaceId == type(ISuperHookInflowOutflow).interfaceId) return true;
if (interfaceId == type(ISuperHookOutflow).interfaceId) return true;
return interfaceId == type(IERC165).interfaceId || interfaceId == type(ISuperHook).interfaceId
|| interfaceId == type(ISuperHookResult).interfaceId
|| interfaceId == type(ISuperHookInspector).interfaceId;
}
/// @inheritdoc ISuperHookInspector
/// @dev Returns only the yieldSource (20 bytes). The market lock is direction-agnostic:
/// the market's PT may be the input (sell/redeem) or the output (buy).
function inspect(bytes calldata data) external pure override returns (bytes memory) {
return abi.encodePacked(HookDataDecoder.extractYieldSource(data));
}
// ─── ISuperHookSwap ──────────────────────────────────────────────────────
/// @inheritdoc ISuperHookSwap
function encodeSwapData(
ISuperHookSwap.SwapHeader calldata header,
bytes calldata payload
)
external
pure
override
returns (bytes memory)
{
return bytes.concat(
bytes(new bytes(SwapCalldataLayout.HEADER_SIZE)),
bytes20(header.inputToken),
bytes20(header.outputToken),
bytes32(header.inputAmount),
bytes32(header.outputQuote),
bytes32(header.outputMin),
bytes1(header.usePrevHookAmount ? uint8(1) : uint8(0)),
bytes32(payload.length),
payload
);
}
/// @inheritdoc ISuperHookSwap
function decodeInputToken(bytes calldata data) external pure override returns (address) {
return BytesLib.toAddress(data, SwapCalldataLayout.INPUT_TOKEN_OFFSET);
}
/// @inheritdoc ISuperHookSwap
function decodeOutputToken(bytes calldata data) external pure override returns (address) {
return BytesLib.toAddress(data, SwapCalldataLayout.OUTPUT_TOKEN_OFFSET);
}
/// @inheritdoc ISuperHookSwap
function decodeInputAmount(bytes calldata data) external pure override returns (uint256) {
return BytesLib.toUint256(data, SwapCalldataLayout.INPUT_AMOUNT_OFFSET);
}
/// @inheritdoc ISuperHookSwap
function decodeOutputQuote(bytes calldata data) external pure override returns (uint256) {
return BytesLib.toUint256(data, SwapCalldataLayout.OUTPUT_QUOTE_OFFSET);
}
/// @inheritdoc ISuperHookSwap
function decodeOutputMin(bytes calldata data) external pure override returns (uint256) {
return BytesLib.toUint256(data, SwapCalldataLayout.OUTPUT_MIN_OFFSET);
}
/// @inheritdoc ISuperHookSwap
function decodePayload(bytes calldata data) external pure override returns (bytes memory) {
uint256 payloadLen = BytesLib.toUint256(data, SwapCalldataLayout.PAYLOAD_LENGTH_OFFSET);
return BytesLib.slice(data, SwapCalldataLayout.PAYLOAD_DATA_OFFSET, payloadLen);
}
/*//////////////////////////////////////////////////////////////
INTERNAL METHODS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc BaseHook
function _preExecute(address, address account, bytes calldata data) internal override {
_setOutAmount(_getBalance(account, data), account);
}
/// @inheritdoc BaseHook
function _postExecute(address, address account, bytes calldata data) internal override {
_setOutAmount(_getBalance(account, data) - getOutAmount(account), account);
_setOutToken(BytesLib.toAddress(data, SwapCalldataLayout.OUTPUT_TOKEN_OFFSET), account);
}
/*//////////////////////////////////////////////////////////////
PRIVATE METHODS
//////////////////////////////////////////////////////////////*/
/// @dev Builds executions for swapExactTokenForPt (token → PT)
/// @dev routingParams: abi.encode(ApproxParams guessPtOut)
/// @param account The account executing the swap
/// @param yieldSource The Pendle market address (used as the market parameter in the router call)
/// @param sy The SY address derived from readTokens()
/// @param headerInputToken The input token from the header (used as TokenInput.tokenIn and tokenMintSy)
/// @param netTokenIn The net token input amount (may be sourced from previous hook)
/// @param scaledOutputMin The minimum acceptable PT output, scaled if using previous hook amount
/// @param routingParams ABI-encoded Pendle-specific routing parameters
/// @return executions Array of executions to send to the Pendle Router
function _buildSwapTokenForPtExecutions(
address account,
address yieldSource,
address sy,
address headerInputToken,
uint256 netTokenIn,
uint256 scaledOutputMin,
bytes memory routingParams
)
private
view
returns (Execution[] memory executions)
{
ApproxParams memory guessPtOut = abi.decode(routingParams, (ApproxParams));
if (guessPtOut.guessMin > guessPtOut.guessMax) revert GUESS_PT_OUT_NOT_VALID();
if (guessPtOut.eps > MAX_EPS) revert EPS_NOT_VALID();
if (guessPtOut.maxIteration > MAX_ITERATIONS) revert MAX_ITERATION_NOT_VALID();
// Pendle's router uses address(0) for native; normalize the 0xEeee… sentinel
bool isNativeIn = headerInputToken == address(0) || headerInputToken == NATIVE_TOKEN;
address tokenIn = isNativeIn ? address(0) : headerInputToken;
if (!IStandardizedYield(sy).isValidTokenIn(tokenIn)) revert TOKEN_IN_NOT_LISTED();
TokenInput memory input = TokenInput({
tokenIn: tokenIn,
netTokenIn: netTokenIn,
tokenMintSy: tokenIn,
pendleSwap: address(0),
swapData: SwapData({ swapType: SwapType.NONE, extRouter: address(0), extCalldata: "", needScale: false })
});
LimitOrderData memory limit; // empty — router skips the limit-order path
bytes memory routerCalldata = abi.encodeCall(
IPendleRouterV4.swapExactTokenForPt,
(account, yieldSource, scaledOutputMin, guessPtOut, input, limit)
);
if (!isNativeIn) {
// ERC20 input: approve-reset-approve + call + cleanup
executions = new Execution[](4);
executions[0] = Execution({
target: headerInputToken,
value: 0,
callData: abi.encodeCall(IERC20.approve, (address(PENDLE_ROUTER_V4), 0))
});
executions[1] = Execution({
target: headerInputToken,
value: 0,
callData: abi.encodeCall(IERC20.approve, (address(PENDLE_ROUTER_V4), netTokenIn))
});
executions[2] = Execution({
target: address(PENDLE_ROUTER_V4),
value: 0,
callData: routerCalldata
});
executions[3] = Execution({
target: headerInputToken,
value: 0,
callData: abi.encodeCall(IERC20.approve, (address(PENDLE_ROUTER_V4), 0))
});
} else {
// Native ETH input: single call with value = netTokenIn
executions = new Execution[](1);
executions[0] = Execution({
target: address(PENDLE_ROUTER_V4),
value: netTokenIn,
callData: routerCalldata
});
}
}
/// @dev Builds executions for swapExactPtForToken (PT → token, pre-maturity)
/// @dev No payload — the header outputToken is used as TokenOutput.tokenOut and tokenRedeemSy
/// @param account The account executing the swap
/// @param yieldSource The Pendle market address (used as the market parameter in the router call)
/// @param sy The SY address derived from readTokens()
/// @param pt The PT address derived from readTokens()
/// @param headerOutputToken The output token from the header (used as TokenOutput.tokenOut and tokenRedeemSy)
/// @param netTokenIn The exact PT input amount
/// @param scaledOutputMin The minimum acceptable token output, scaled if using previous hook amount
/// @return executions Array of executions (approve + swap + cleanup)
function _buildSwapPtForTokenExecutions(
address account,
address yieldSource,
address sy,
address pt,
address headerOutputToken,
uint256 netTokenIn,
uint256 scaledOutputMin
)
private
view
returns (Execution[] memory executions)
{
if (!IStandardizedYield(sy).isValidTokenOut(headerOutputToken)) revert TOKEN_OUT_NOT_LISTED();
TokenOutput memory output = TokenOutput({
tokenOut: headerOutputToken,
minTokenOut: scaledOutputMin,
tokenRedeemSy: headerOutputToken,
pendleSwap: address(0),
swapData: SwapData({ swapType: SwapType.NONE, extRouter: address(0), extCalldata: "", needScale: false })
});
LimitOrderData memory limit; // empty — router skips the limit-order path
// Approve-reset-approve + swap + cleanup for PT
executions = new Execution[](4);
executions[0] = Execution({
target: pt,
value: 0,
callData: abi.encodeCall(IERC20.approve, (address(PENDLE_ROUTER_V4), 0))
});
executions[1] = Execution({
target: pt,
value: 0,
callData: abi.encodeCall(IERC20.approve, (address(PENDLE_ROUTER_V4), netTokenIn))
});
executions[2] = Execution({
target: address(PENDLE_ROUTER_V4),
value: 0,
callData: abi.encodeCall(
IPendleRouterV4.swapExactPtForToken,
(account, yieldSource, netTokenIn, output, limit)
)
});
executions[3] = Execution({
target: pt,
value: 0,
callData: abi.encodeCall(IERC20.approve, (address(PENDLE_ROUTER_V4), 0))
});
}
/// @dev Builds executions for redeemPyToToken (PT+YT → token, post-maturity)
/// @dev No payload — the header outputToken is used as TokenOutput.tokenOut and tokenRedeemSy
/// @param account The account executing the redemption
/// @param sy The SY address derived from readTokens()
/// @param pt The PT address derived from readTokens()
/// @param yt The YT address derived from readTokens()
/// @param headerOutputToken The output token from the header (used as TokenOutput.tokenOut and tokenRedeemSy)
/// @param netTokenIn The amount of PT+YT to redeem
/// @param scaledOutputMin The minimum acceptable output token amount
/// @return executions Array of executions (approve + redeem + cleanup)
function _buildRedeemExecutions(
address account,
address sy,
address pt,
address yt,
address headerOutputToken,
uint256 netTokenIn,
uint256 scaledOutputMin
)
private
view
returns (Execution[] memory executions)
{
if (!IStandardizedYield(sy).isValidTokenOut(headerOutputToken)) revert TOKEN_OUT_NOT_LISTED();
TokenOutput memory output = TokenOutput({
tokenOut: headerOutputToken,
minTokenOut: scaledOutputMin,
tokenRedeemSy: headerOutputToken,
pendleSwap: address(0),
swapData: SwapData({ swapType: SwapType.NONE, extRouter: address(0), extCalldata: "", needScale: false })
});
executions = new Execution[](7);
executions[0] = Execution({
target: pt,
value: 0,
callData: abi.encodeCall(IERC20.approve, (address(PENDLE_ROUTER_V4), 0))
});
executions[1] = Execution({
target: pt,
value: 0,
callData: abi.encodeCall(IERC20.approve, (address(PENDLE_ROUTER_V4), netTokenIn))
});
executions[2] = Execution({
target: yt,
value: 0,
callData: abi.encodeCall(IERC20.approve, (address(PENDLE_ROUTER_V4), 0))
});
executions[3] = Execution({
target: yt,
value: 0,
callData: abi.encodeCall(IERC20.approve, (address(PENDLE_ROUTER_V4), netTokenIn))
});
executions[4] = Execution({
target: address(PENDLE_ROUTER_V4),
value: 0,
callData: abi.encodeCall(IPendleRouterV4.redeemPyToToken, (account, yt, netTokenIn, output))
});
executions[5] = Execution({
target: pt,
value: 0,
callData: abi.encodeCall(IERC20.approve, (address(PENDLE_ROUTER_V4), 0))
});
executions[6] = Execution({
target: yt,
value: 0,
callData: abi.encodeCall(IERC20.approve, (address(PENDLE_ROUTER_V4), 0))
});
}
/// @dev Gets balance of output token for the account — native ETH or ERC20
/// @param account The account to check balance for
/// @param data The hook calldata containing the output token at OUTPUT_TOKEN_OFFSET
/// @return The token balance of the account
function _getBalance(address account, bytes calldata data) private view returns (uint256) {
address outputToken = BytesLib.toAddress(data, SwapCalldataLayout.OUTPUT_TOKEN_OFFSET);
if (outputToken == address(0) || outputToken == NATIVE_TOKEN) {
return account.balance;
}
return IERC20(outputToken).balanceOf(account);
}
}
lib/modulekit/src/accounts/common/interfaces/IERC7579Account.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.23 <0.9.0;
/* solhint-disable no-unused-import */
// Types
import { CallType, ExecType, ModeCode } from "../lib/ModeLib.sol";
// Structs
struct Execution {
address target;
uint256 value;
bytes callData;
}
interface IERC7579Account {
event ModuleInstalled(uint256 moduleTypeId, address module);
event ModuleUninstalled(uint256 moduleTypeId, address module);
/**
* @dev Executes a transaction on behalf of the account.
* This function is intended to be called by ERC-4337 EntryPoint.sol
* @dev Ensure adequate authorization control: i.e. onlyEntryPointOrSelf
*
* @dev MSA MUST implement this function signature.
* If a mode is requested that is not supported by the Account, it MUST revert
* @param mode The encoded execution mode of the transaction. See ModeLib.sol for details
* @param executionCalldata The encoded execution call data
*/
function execute(ModeCode mode, bytes calldata executionCalldata) external payable;
/**
* @dev Executes a transaction on behalf of the account.
* This function is intended to be called by Executor Modules
* @dev Ensure adequate authorization control: i.e. onlyExecutorModule
*
* @dev MSA MUST implement this function signature.
* If a mode is requested that is not supported by the Account, it MUST revert
* @param mode The encoded execution mode of the transaction. See ModeLib.sol for details
* @param executionCalldata The encoded execution call data
*/
function executeFromExecutor(
ModeCode mode,
bytes calldata executionCalldata
)
external
payable
returns (bytes[] memory returnData);
/**
* @dev ERC-1271 isValidSignature
* This function is intended to be used to validate a smart account signature
* and may forward the call to a validator module
*
* @param hash The hash of the data that is signed
* @param data The data that is signed
*/
function isValidSignature(bytes32 hash, bytes calldata data) external view returns (bytes4);
/**
* @dev installs a Module of a certain type on the smart account
* @dev Implement Authorization control of your chosing
* @param moduleTypeId the module type ID according the ERC-7579 spec
* @param module the module address
* @param initData arbitrary data that may be required on the module during `onInstall`
* initialization.
*/
function installModule(
uint256 moduleTypeId,
address module,
bytes calldata initData
)
external
payable;
/**
* @dev uninstalls a Module of a certain type on the smart account
* @dev Implement Authorization control of your chosing
* @param moduleTypeId the module type ID according the ERC-7579 spec
* @param module the module address
* @param deInitData arbitrary data that may be required on the module during `onUninstall`
* de-initialization.
*/
function uninstallModule(
uint256 moduleTypeId,
address module,
bytes calldata deInitData
)
external
payable;
/**
* Function to check if the account supports a certain CallType or ExecType (see ModeLib.sol)
* @param encodedMode the encoded mode
*/
function supportsExecutionMode(ModeCode encodedMode) external view returns (bool);
/**
* Function to check if the account supports installation of a certain module type Id
* @param moduleTypeId the module type ID according the ERC-7579 spec
*/
function supportsModule(uint256 moduleTypeId) external view returns (bool);
/**
* Function to check if the account has a certain module installed
* @param moduleTypeId the module type ID according the ERC-7579 spec
* Note: keep in mind that some contracts can be multiple module types at the same time. It
* thus may be necessary to query multiple module types
* @param module the module address
* @param additionalContext additional context data that the smart account may interpret to
* identifiy conditions under which the module is installed.
* usually this is not necessary, but for some special hooks that
* are stored in mappings, this param might be needed
*/
function isModuleInstalled(
uint256 moduleTypeId,
address module,
bytes calldata additionalContext
)
external
view
returns (bool);
/**
* @dev Returns the account id of the smart account
* @return accountImplementationId the account id of the smart account
* the accountId should be structured like so:
* "vendorname.accountname.semver"
*/
function accountId() external view returns (string memory accountImplementationId);
}
lib/modulekit/src/accounts/common/lib/ModeLib.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0 <0.9.0;
/**
* @title ModeLib
* @author rhinestone | zeroknots.eth, Konrad Kopp (@kopy-kat)
* To allow smart accounts to be very simple, but allow for more complex execution, A custom mode
* encoding is used.
* Function Signature of execute function:
* function execute(ModeCode mode, bytes calldata executionCalldata) external payable;
* This allows for a single bytes32 to be used to encode the execution mode, calltype, execType and
* context.
* NOTE: Simple Account implementations only have to scope for the most significant byte. Account that
* implement
* more complex execution modes may use the entire bytes32.
*
* |--------------------------------------------------------------------|
* | CALLTYPE | EXECTYPE | UNUSED | ModeSelector | ModePayload |
* |--------------------------------------------------------------------|
* | 1 byte | 1 byte | 4 bytes | 4 bytes | 22 bytes |
* |--------------------------------------------------------------------|
*
* CALLTYPE: 1 byte
* CallType is used to determine how the executeCalldata paramter of the execute function has to be
* decoded.
* It can be either single, batch or delegatecall. In the future different calls could be added.
* CALLTYPE can be used by a validation module to determine how to decode <userOp.callData[36:]>.
*
* EXECTYPE: 1 byte
* ExecType is used to determine how the account should handle the execution.
* It can indicate if the execution should revert on failure or continue execution.
* In the future more execution modes may be added.
* Default Behavior (EXECTYPE = 0x00) is to revert on a single failed execution. If one execution in
* a batch fails, the entire batch is reverted
*
* UNUSED: 4 bytes
* Unused bytes are reserved for future use.
*
* ModeSelector: bytes4
* The "optional" mode selector can be used by account vendors, to implement custom behavior in
* their accounts.
* the way a ModeSelector is to be calculated is bytes4(keccak256("vendorname.featurename"))
* this is to prevent collisions between different vendors, while allowing innovation and the
* development of new features without coordination between ERC-7579 implementing accounts
*
* ModePayload: 22 bytes
* Mode payload is used to pass additional data to the smart account execution, this may be
* interpreted depending on the ModeSelector
*
* ExecutionCallData: n bytes
* single, delegatecall or batch exec abi.encoded as bytes
*/
// Custom type for improved developer experience
type ModeCode is bytes32;
type CallType is bytes1;
type ExecType is bytes1;
type ModeSelector is bytes4;
type ModePayload is bytes22;
// Default CallType
CallType constant CALLTYPE_SINGLE = CallType.wrap(0x00);
// Batched CallType
CallType constant CALLTYPE_BATCH = CallType.wrap(0x01);
CallType constant CALLTYPE_STATIC = CallType.wrap(0xFE);
// @dev Implementing delegatecall is OPTIONAL!
// implement delegatecall with extreme care.
CallType constant CALLTYPE_DELEGATECALL = CallType.wrap(0xFF);
// @dev default behavior is to revert on failure
// To allow very simple accounts to use mode encoding, the default behavior is to revert on failure
// Since this is value 0x00, no additional encoding is required for simple accounts
ExecType constant EXECTYPE_DEFAULT = ExecType.wrap(0x00);
// @dev account may elect to change execution behavior. For example "try exec" / "allow fail"
ExecType constant EXECTYPE_TRY = ExecType.wrap(0x01);
ModeSelector constant MODE_DEFAULT = ModeSelector.wrap(bytes4(0x00000000));
// Example declaration of a custom mode selector
ModeSelector constant MODE_OFFSET = ModeSelector.wrap(bytes4(keccak256("default.mode.offset")));
/**
* @dev ModeLib is a helper library to encode/decode ModeCodes
*/
library ModeLib {
function decode(ModeCode mode)
internal
pure
returns (
CallType _calltype,
ExecType _execType,
ModeSelector _modeSelector,
ModePayload _modePayload
)
{
// solhint-disable-next-line no-inline-assembly
assembly {
_calltype := mode
_execType := shl(8, mode)
_modeSelector := shl(48, mode)
_modePayload := shl(80, mode)
}
}
function encode(
CallType callType,
ExecType execType,
ModeSelector mode,
ModePayload payload
)
internal
pure
returns (ModeCode)
{
return ModeCode.wrap(
bytes32(
abi.encodePacked(callType, execType, bytes4(0), ModeSelector.unwrap(mode), payload)
)
);
}
function encodeSimpleBatch() internal pure returns (ModeCode mode) {
mode = encode(CALLTYPE_BATCH, EXECTYPE_DEFAULT, MODE_DEFAULT, ModePayload.wrap(0x00));
}
function encodeSimpleSingle() internal pure returns (ModeCode mode) {
mode = encode(CALLTYPE_SINGLE, EXECTYPE_DEFAULT, MODE_DEFAULT, ModePayload.wrap(0x00));
}
function getCallType(ModeCode mode) internal pure returns (CallType calltype) {
// solhint-disable-next-line no-inline-assembly
assembly {
calltype := mode
}
}
}
using { eqModeSelector as == } for ModeSelector global;
using { eqCallType as == } for CallType global;
using { neqCallType as != } for CallType global;
using { eqExecType as == } for ExecType global;
function eqCallType(CallType a, CallType b) pure returns (bool) {
return CallType.unwrap(a) == CallType.unwrap(b);
}
function neqCallType(CallType a, CallType b) pure returns (bool) {
return CallType.unwrap(a) == CallType.unwrap(b);
}
function eqExecType(ExecType a, ExecType b) pure returns (bool) {
return ExecType.unwrap(a) == ExecType.unwrap(b);
}
function eqModeSelector(ModeSelector a, ModeSelector b) pure returns (bool) {
return ModeSelector.unwrap(a) == ModeSelector.unwrap(b);
}
lib/modulekit/src/accounts/erc7579/lib/ExecutionLib.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.23 <0.9.0;
// Types
import { Execution } from "../../common/interfaces/IERC7579Account.sol";
/**
* Helper Library for decoding Execution calldata
* malloc for memory allocation is bad for gas. use this assembly instead
*/
library ExecutionLib {
error ERC7579DecodingError();
/**
* @notice Decode a batch of `Execution` executionBatch from a `bytes` calldata.
* @dev code is copied from solady's LibERC7579.sol
* https://github.com/Vectorized/solady/blob/740812cedc9a1fc11e17cb3d4569744367dedf19/src/accounts/LibERC7579.sol#L146
* Credits to Vectorized and the Solady Team
*/
function decodeBatch(bytes calldata executionCalldata)
internal
pure
returns (Execution[] calldata executionBatch)
{
/// @solidity memory-safe-assembly
assembly {
let u := calldataload(executionCalldata.offset)
let s := add(executionCalldata.offset, u)
let e := sub(add(executionCalldata.offset, executionCalldata.length), 0x20)
executionBatch.offset := add(s, 0x20)
executionBatch.length := calldataload(s)
if or(shr(64, u), gt(add(s, shl(5, executionBatch.length)), e)) {
mstore(0x00, 0xba597e7e) // `DecodingError()`.
revert(0x1c, 0x04)
}
if executionBatch.length {
// Perform bounds checks on the decoded `executionBatch`.
// Loop runs out-of-gas if `executionBatch.length` is big enough to cause overflows.
for { let i := executionBatch.length } 1 { } {
i := sub(i, 1)
let p := calldataload(add(executionBatch.offset, shl(5, i)))
let c := add(executionBatch.offset, p)
let q := calldataload(add(c, 0x40))
let o := add(c, q)
// forgefmt: disable-next-item
if or(shr(64, or(calldataload(o), or(p, q))),
or(gt(add(c, 0x40), e), gt(add(o, calldataload(o)), e))) {
mstore(0x00, 0xba597e7e) // `DecodingError()`.
revert(0x1c, 0x04)
}
if iszero(i) { break }
}
}
}
}
function encodeBatch(Execution[] memory executions)
internal
pure
returns (bytes memory callData)
{
callData = abi.encode(executions);
}
function decodeSingle(bytes calldata executionCalldata)
internal
pure
returns (address target, uint256 value, bytes calldata callData)
{
target = address(bytes20(executionCalldata[0:20]));
value = uint256(bytes32(executionCalldata[20:52]));
callData = executionCalldata[52:];
}
function encodeSingle(
address target,
uint256 value,
bytes memory callData
)
internal
pure
returns (bytes memory userOpCalldata)
{
userOpCalldata = abi.encodePacked(target, value, callData);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// 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:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
src/hooks/BaseHook.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
// External
import { Execution } from "modulekit/accounts/erc7579/lib/ExecutionLib.sol";
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
// Superform
import { HookDataDecoder } from "../libraries/HookDataDecoder.sol";
import {
ISuperHook,
ISuperHookSetter,
ISuperHookResult,
ISuperHookInspector,
ISuperHookInflowOutflow,
ISuperHookOutflow
} from "../interfaces/ISuperHook.sol";
/// @title BaseHook
/// @author Superform Labs
/// @notice Base implementation for all hooks in the Superform system
/// @dev Provides core security validation and execution flow management for hooks
/// All specialized hooks should inherit from this base contract
/// Implements the ISuperHook interface defined lifecycle methods
/// Uses a transient storage pattern for stateful execution context
abstract contract BaseHook is ISuperHook, ISuperHookSetter, ISuperHookResult, ISuperHookInspector, IERC165 {
using HookDataDecoder for bytes;
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The number of shares used by this hook's operation
/// @dev Used for accounting and tracking consumption of position shares
uint256 public transient usedShares;
/// @notice The special token address (if any) associated with this hook's operation
/// @dev May be used to track token addresses for various operations
address public transient spToken;
/// @notice The primary asset address this hook operates on
/// @dev Typically the base token or asset being processed
address public transient asset;
/// @notice Execution nonce for creating unique contexts
uint256 public transient executionNonce;
/// @notice Last execution context caller
address public transient lastCaller;
// Storage offsets for different state variables
uint256 private constant OUT_AMOUNT_OFFSET = 1;
uint256 private constant PRE_EXECUTE_MUTEX_OFFSET = 2;
uint256 private constant POST_EXECUTE_MUTEX_OFFSET = 3;
uint256 private constant OUT_TOKEN_OFFSET = 4;
/*//////////////////////////////////////////////////////////////
ENUMS
//////////////////////////////////////////////////////////////*/
/// @notice Declares how a hook handles its output (outAmount + outToken) relative to the previous hook
/// @dev TRANSFORM: Hook converts input to output (balance-diff pattern). Default.
/// PASSTHROUGH: Hook performs a side-effect only, auto-forwards prev hook's output.
/// SOURCE: Hook creates output from external state, ignores prev hook. Reserved for future use.
enum PipeMode {
TRANSFORM,
PASSTHROUGH,
SOURCE
}
/// @notice Base storage key for hook execution state
bytes32 private constant HOOK_EXECUTION_STORAGE = keccak256("hook.execution.state");
/// @notice Storage key for account context mapping
bytes32 private constant ACCOUNT_CONTEXT_STORAGE = keccak256("hook.account.context");
/// @notice The specific subtype identifier for this hook
/// @dev Used to identify specialized hook types beyond the basic HookType enum
bytes32 public immutable SUB_TYPE;
/// @notice The type of hook (NONACCOUNTING, INFLOW, OUTFLOW)
/// @dev Determines how the hook impacts accounting in the system
ISuperHook.HookType public hookType;
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when a caller attempts to execute hook methods without proper authorization
/// @dev Used by security validation to prevent unauthorized hook execution
error NOT_AUTHORIZED();
/// @notice Thrown when an amount parameter is invalid (e.g., zero or overflow)
/// @dev Used in validation checks for asset amounts and share values
error AMOUNT_NOT_VALID();
/// @notice Thrown when an address parameter is invalid (e.g., zero address)
/// @dev Used in validation checks for tokens, accounts, and other addresses
error ADDRESS_NOT_VALID();
/// @notice Thrown when a caller is not authorized to execute hook methods
/// @dev Used by security validation to prevent unauthorized hook execution
error UNAUTHORIZED_CALLER();
/// @notice Thrown when preExecute is called more than once
/// @dev Used to prevent reentrancy attacks and ensure proper execution flow
error PRE_EXECUTE_ALREADY_CALLED();
/// @notice Thrown when postExecute is called more than once
/// @dev Used to prevent reentrancy attacks and ensure proper execution flow
error POST_EXECUTE_ALREADY_CALLED();
/// @notice Thrown when a hook execution is incomplete
/// @dev Used to prevent incomplete hook execution
error INCOMPLETE_HOOK_EXECUTION();
/// @notice Thrown when trying to set outAmount after preExecute or postExecute
/// @dev Used to prevent setting outAmount after preExecute or postExecute
error CANNOT_SET_OUT_AMOUNT();
/// @notice Thrown when the amounts array length doesn't match the expected count
/// @dev Used by replaceCalldataAmounts to validate input
error INVALID_AMOUNTS_LENGTH();
/// @notice Initializes the hook with its type and subtype
/// @dev Sets immutable parameters that define the hook's behavior
/// @param hookType_ The type classification for this hook (NONACCOUNTING, INFLOW, OUTFLOW)
/// @param subType_ The specific subtype identifier for specialized hook functionality
constructor(ISuperHook.HookType hookType_, bytes32 subType_) {
hookType = hookType_;
SUB_TYPE = subType_;
}
modifier onlyLastCaller() {
if (msg.sender != lastCaller) revert UNAUTHORIZED_CALLER();
_;
}
/*//////////////////////////////////////////////////////////////
EXECUTION SECURITY
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ISuperHook
function setExecutionContext(address caller) external {
_createExecutionContext(caller);
lastCaller = msg.sender;
}
/// @dev Standard build pattern - MUST include preExecute first, postExecute last
/// @inheritdoc ISuperHook
function build(
address prevHook,
address account,
bytes calldata hookData
)
external
view
virtual
returns (Execution[] memory executions)
{
// Get hook-specific executions
Execution[] memory hookExecutions = _buildHookExecutions(prevHook, account, hookData);
// Always include pre + hook + post
executions = new Execution[](hookExecutions.length + 2);
// FIRST: preExecute
executions[0] = Execution({
target: address(this),
value: 0,
callData: abi.encodeCall(this.preExecute, (prevHook, account, hookData))
});
// MIDDLE: hook-specific operations
for (uint256 i = 0; i < hookExecutions.length; i++) {
executions[i + 1] = hookExecutions[i];
}
// LAST: postExecute
executions[executions.length - 1] = Execution({
target: address(this),
value: 0,
callData: abi.encodeCall(this.postExecute, (prevHook, account, hookData))
});
}
/// @inheritdoc ISuperHook
function preExecute(address prevHook, address account, bytes calldata data) external {
if (msg.sender != account) revert UNAUTHORIZED_CALLER();
uint256 context = _getCurrentExecutionContext(account);
if (_getPreExecuteMutex(context)) revert PRE_EXECUTE_ALREADY_CALLED();
_setPreExecuteMutex(context, true);
_preExecute(prevHook, account, data);
}
/// @inheritdoc ISuperHook
function postExecute(address prevHook, address account, bytes calldata data) external {
if (msg.sender != account) revert UNAUTHORIZED_CALLER();
uint256 context = _getCurrentExecutionContext(account);
if (_getPostExecuteMutex(context)) revert POST_EXECUTE_ALREADY_CALLED();
_setPostExecuteMutex(context, true);
_postExecute(prevHook, account, data);
}
/// @inheritdoc ISuperHookSetter
function setOutAmount(uint256 _outAmount, address caller) external {
uint256 context = _getCurrentExecutionContext(caller);
if (_getPreExecuteMutex(context) || _getPostExecuteMutex(context)) {
revert CANNOT_SET_OUT_AMOUNT();
}
bytes32 key = _makeKey(context, OUT_AMOUNT_OFFSET);
assembly ("memory-safe") {
tstore(key, _outAmount)
}
}
function getOutAmount(address caller) public view returns (uint256) {
return _getOutAmount(_getCurrentExecutionContext(caller));
}
function getOutToken(address caller) public view returns (address) {
return _getOutToken(_getCurrentExecutionContext(caller));
}
/// @inheritdoc ISuperHook
function resetExecutionState(address caller) external onlyLastCaller {
uint256 context = _getCurrentExecutionContext(caller);
if (!_getPreExecuteMutex(context) || !_getPostExecuteMutex(context)) {
revert INCOMPLETE_HOOK_EXECUTION();
}
_clearExecutionState(context);
}
/*//////////////////////////////////////////////////////////////
VIEW METHODS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ISuperHook
function subtype() external view returns (bytes32) {
return SUB_TYPE;
}
/// @inheritdoc ISuperHookInspector
function inspect(bytes calldata) external view virtual returns (bytes memory) { }
/// @inheritdoc IERC165
/// @dev Hooks that implement ISuperHookInflowOutflow/ISuperHookOutflow override
/// _supportsSizingInterface() to return true, which enables three-state detection:
/// S1: supportsInterface(ISuperHookInflowOutflow) == true → hook has sizing interface
/// S2: same as S1 but amountRoles(data).length == 0 → authoritatively sizeless
/// S3: supportsInterface(ISuperHookInflowOutflow) == false → legacy, no sizing interface
function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {
if (
interfaceId == type(ISuperHookInflowOutflow).interfaceId
|| interfaceId == type(ISuperHookOutflow).interfaceId
) {
return _supportsSizingInterface();
}
return interfaceId == type(IERC165).interfaceId || interfaceId == type(ISuperHook).interfaceId
|| interfaceId == type(ISuperHookResult).interfaceId
|| interfaceId == type(ISuperHookInspector).interfaceId;
}
/// @dev Override to return true in hooks that implement ISuperHookInflowOutflow/ISuperHookOutflow
function _supportsSizingInterface() internal pure virtual returns (bool) {
return false;
}
/*//////////////////////////////////////////////////////////////
INTERNAL METHODS
//////////////////////////////////////////////////////////////*/
/// @notice Internal implementation of build
/// @dev Abstract function to be implemented by derived hooks
/// Called during build to generate hook-specific execution sequences
/// @param prevHook The previous hook in the chain, or address(0) if first hook
/// @param account The account that operations will be performed for
/// @param data Hook-specific parameters and configuration data
/// @return executions Array of execution objects containing target, value, and callData
function _buildHookExecutions(
address prevHook,
address account,
bytes calldata data
)
internal
view
virtual
returns (Execution[] memory executions);
/// @notice Internal implementation of preExecute
/// @dev Default behavior for PASSTHROUGH hooks: auto-forward prevHook's outAmount + outToken.
/// TRANSFORM and SOURCE hooks override this entirely.
/// @param prevHook The previous hook in the chain, or address(0) if first hook
/// @param account The account that operations will be performed for
function _preExecute(address prevHook, address account, bytes calldata) internal virtual {
if (_pipeMode() == PipeMode.PASSTHROUGH && prevHook != address(0)) {
_setOutAmount(ISuperHookResult(prevHook).getOutAmount(account), account);
_setOutToken(ISuperHookResult(prevHook).getOutToken(account), account);
}
}
/// @notice Internal implementation of postExecute
/// @dev Abstract function to be implemented by derived hooks
/// Called after execution to finalize the hook's state and set output values
/// Typically calculates final results and sets outAmount, usedShares, etc.
/// May perform additional validations on execution results
/// @param prevHook The previous hook in the chain, or address(0) if first hook
/// @param account The account operations were performed for
/// @param data Hook-specific parameters and configuration data
function _postExecute(address prevHook, address account, bytes calldata data) internal virtual { }
/// @notice Decodes a boolean value from a byte array at the specified offset
/// @dev Helper function for extracting boolean values from packed data
/// Used when parsing hook-specific data parameters
/// @param data The byte array containing the encoded data
/// @param offset The position in the array to read from
/// @return The decoded boolean value (true if byte is non-zero)
function _decodeBool(bytes memory data, uint256 offset) internal pure returns (bool) {
return data[offset] != 0;
}
/// @notice Replaces an amount value within a byte array at the specified offset
/// @dev Used to modify hook calldata for amount adjustments without full re-encoding
/// Particularly useful for modifying amounts in multi-hook execution chains
/// Directly modifies the bytes in-place for gas efficiency
/// @param data The original byte array containing encoded calldata
/// @param amount The new amount value to insert
/// @param offset The position in the array where the amount starts
/// @return The modified byte array with the replaced amount
function _replaceCalldataAmount(
bytes memory data,
uint256 amount,
uint256 offset
)
internal
pure
returns (bytes memory)
{
bytes memory newAmountEncoded = abi.encodePacked(amount);
for (uint256 i; i < 32; ++i) {
data[offset + i] = newAmountEncoded[i];
}
return data;
}
/// @notice Declares the pipe semantics for this hook
/// @dev Override to return PASSTHROUGH for side-effect-only hooks.
/// Default: TRANSFORM. Inlined by the compiler (pure virtual).
function _pipeMode() internal pure virtual returns (PipeMode) {
return PipeMode.TRANSFORM;
}
/// @notice Sets the output token address for this hook execution
/// @param token The output token address
/// @param caller The caller address for context identification
function _setOutToken(address token, address caller) internal {
uint256 context = _getCurrentExecutionContext(caller);
bytes32 key = _makeKey(context, OUT_TOKEN_OFFSET);
assembly ("memory-safe") {
tstore(key, token)
}
}
function _makeAccountContextKey(address account) private pure returns (bytes32) {
return keccak256(abi.encodePacked(ACCOUNT_CONTEXT_STORAGE, account));
}
function _createExecutionContext(address caller) private returns (uint256) {
// Always increment nonce for new execution context
executionNonce++;
bytes32 key = _makeAccountContextKey(caller);
// Store this context for the current caller
uint256 currentNonce = executionNonce; // Load into local variable for assembly
assembly ("memory-safe") {
tstore(key, currentNonce)
}
return executionNonce;
}
function _getCurrentExecutionContext(address caller) private view returns (uint256 context) {
bytes32 key = _makeAccountContextKey(caller);
assembly ("memory-safe") {
context := tload(key)
}
}
function _makeKey(uint256 context, uint256 offset) private pure returns (bytes32) {
return keccak256(abi.encodePacked(HOOK_EXECUTION_STORAGE, context, offset));
}
function _getOutAmount(uint256 context) private view returns (uint256 value) {
bytes32 key = _makeKey(context, OUT_AMOUNT_OFFSET);
assembly ("memory-safe") {
value := tload(key)
}
}
function _getOutToken(uint256 context) private view returns (address value) {
bytes32 key = _makeKey(context, OUT_TOKEN_OFFSET);
assembly ("memory-safe") {
value := tload(key)
}
}
function _setOutAmount(uint256 value, address caller) internal {
uint256 context = _getCurrentExecutionContext(caller);
bytes32 key = _makeKey(context, OUT_AMOUNT_OFFSET);
assembly ("memory-safe") {
tstore(key, value)
}
}
function _getPreExecuteMutex(uint256 context) private view returns (bool value) {
bytes32 key = _makeKey(context, PRE_EXECUTE_MUTEX_OFFSET);
assembly ("memory-safe") {
value := tload(key)
}
}
function _setPreExecuteMutex(uint256 context, bool value) private {
bytes32 key = _makeKey(context, PRE_EXECUTE_MUTEX_OFFSET);
assembly ("memory-safe") {
tstore(key, value)
}
}
function _getPostExecuteMutex(uint256 context) private view returns (bool value) {
bytes32 key = _makeKey(context, POST_EXECUTE_MUTEX_OFFSET);
assembly ("memory-safe") {
value := tload(key)
}
}
function _setPostExecuteMutex(uint256 context, bool value) private {
bytes32 key = _makeKey(context, POST_EXECUTE_MUTEX_OFFSET);
assembly ("memory-safe") {
tstore(key, value)
}
}
function _clearExecutionState(uint256 context) private {
_setPreExecuteMutex(context, false);
_setPostExecuteMutex(context, false);
}
}
src/interfaces/ISuperHook.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
// external
import { Execution } from "modulekit/accounts/erc7579/lib/ExecutionLib.sol";
/**
* @title SuperHook System
* @author Superform Labs
* @notice The hook system provides a modular and composable way to execute operations on assets
* @dev The hook system architecture consists of several interfaces that work together:
* - ISuperHook: The base interface all hooks implement, with lifecycle methods
* - ISuperHookResult: Provides execution results and output information
* - Specialized interfaces (ISuperHookOutflow, ISuperHookLoans, etc.) for specific behaviors
*
* Hooks are executed in sequence, where each hook can access the results from previous hooks.
* The three main types of hooks are:
* - NONACCOUNTING: Utility hooks that don't update the accounting system
* - INFLOW: Hooks that process deposits or additions to positions
* - OUTFLOW: Hooks that process withdrawals or reductions to positions
*/
interface ISuperLockableHook {
/// @notice The vault bank address used to lock SuperPositions
/// @dev Only relevant for cross-chain operations where positions are locked
/// @return The vault bank address, or address(0) if not applicable
function vaultBank() external view returns (address);
/// @notice The destination chain ID for cross-chain operations
/// @dev Used to identify the target chain for cross-chain position transfers
/// @return The destination chain ID, or 0 if not a cross-chain operation
function dstChainId() external view returns (uint256);
}
interface ISuperHookSetter {
/// @notice Sets the output amount for the hook
/// @dev Used for updating `outAmount` when fees were deducted
/// @param outAmount The amount of tokens processed by the hook
/// @param caller The caller address for context identification
function setOutAmount(uint256 outAmount, address caller) external;
}
/// @title ISuperHookInspector
/// @author Superform Labs
/// @notice Interface for the SuperHookInspector contract that manages hook inspection
interface ISuperHookInspector {
/// @notice Inspect the hook
/// @param data The hook data to inspect
/// @return argsEncoded The arguments of the hook encoded
function inspect(bytes calldata data) external view returns (bytes memory argsEncoded);
}
/// @title ISuperHookResult
/// @author Superform Labs
/// @notice Interface that exposes the result of a hook execution
/// @dev All hooks must implement this interface to provide standardized access to execution results.
/// These results are used by subsequent hooks in the execution chain and by the executor.
interface ISuperHookResult {
/*//////////////////////////////////////////////////////////////
VIEW METHODS
//////////////////////////////////////////////////////////////*/
/// @notice The type of hook
/// @dev Used to determine how accounting should process this hook's results
/// @return The hook type (NONACCOUNTING, INFLOW, or OUTFLOW)
function hookType() external view returns (ISuperHook.HookType);
/// @notice The SuperPosition (SP) token associated with this hook
/// @dev For vault hooks, this would be the tokenized position representing shares
/// @return The address of the SP token, or address(0) if not applicable
function spToken() external view returns (address);
/// @notice The underlying asset token being processed
/// @dev For most hooks, this is the actual token being deposited or withdrawn
/// @return The address of the asset token, or address(0) for native assets
function asset() external view returns (address);
/// @notice The amount of tokens processed by the hook in a given caller context, subject to fees after update
/// @dev This is the primary output value used by subsequent hooks
/// @param caller The caller address for context identification
/// @return The amount of tokens (assets or shares) processed
function getOutAmount(address caller) external view returns (uint256);
/// @notice The output token address produced by the hook in a given caller context
/// @dev Used by subsequent hooks to determine what token the previous hook produced
/// PASSTHROUGH hooks auto-forward the previous hook's outToken
/// TRANSFORM hooks set this to their specific output token
/// @param caller The caller address for context identification
/// @return The address of the output token, or address(0) if not set
function getOutToken(address caller) external view returns (address);
}
/// @title ISuperHookContextAware
/// @author Superform Labs
/// @notice Interface for hooks that can use previous hook results in their execution
/// @dev Enables contextual awareness and data flow between hooks in a chain
interface ISuperHookContextAware {
/// @notice Determines if this hook should use the amount from the previous hook
/// @dev Used to create hook chains where output from one hook becomes input to the next
/// @param data The hook-specific data containing configuration
/// @return True if the hook should use the previous hook's output amount
function decodeUsePrevHookAmount(bytes memory data) external pure returns (bool);
}
/// @title ISuperHookInflowOutflow
/// @author Superform Labs
/// @notice Interface for hooks that handle both inflows and outflows
/// @dev Provides standardized amount extraction for both deposit and withdrawal operations
interface ISuperHookInflowOutflow {
/// @notice Direction of an amount slot
/// @dev IN = primary amount the OMS sizes (intent amount)
/// OUT = secondary derived amount (e.g. borrow amount in supply-and-borrow)
enum Direction {
IN,
OUT
}
/// @notice Denomination of an amount slot
/// @dev TOKEN = raw ERC-20 amount (swaps, bridges, transfers, loan operations)
/// ASSETS = underlying asset amount (vault deposits, ERC-4626/7540 withdraw)
/// SHARES = vault share amount (vault redeems, ERC-4626/7540 requestRedeem)
enum Denomination {
TOKEN,
ASSETS,
SHARES
}
/// @notice Per-slot metadata: direction + denomination
/// @dev Aligned 1:1 with the array from decodeAmounts.
/// A slot belongs in decodeAmounts/amountRoles iff the OMS can rewrite it
/// at execution time without invalidating any commitment (signature or proof)
/// embedded in the same data.
struct AmountMeta {
Direction dir;
Denomination denom;
}
/// @notice Extracts all amounts from the hook's calldata
/// @dev Used to determine the quantity of assets or shares being processed
/// @param data The hook-specific calldata
/// @return amounts Array of amounts (length 1 for single-amount hooks, 2+ for compound hooks)
function decodeAmounts(bytes memory data) external pure returns (uint256[] memory amounts);
/// @notice Returns per-slot metadata (direction + denomination) for each amount
/// @dev Must return an array of the same length as decodeAmounts(data).
/// Enables the OMS to know which slots to size (IN vs OUT) and in what
/// denomination (TOKEN vs ASSETS vs SHARES).
/// Takes data so variable-count hooks can return the correct number of slots.
/// @param data The hook-specific calldata (same as passed to decodeAmounts)
/// @return meta Array of AmountMeta structs aligned index-by-index with decodeAmounts
function amountRoles(bytes memory data) external pure returns (AmountMeta[] memory meta);
}
/// @title ISuperHookOutflow
/// @author Superform Labs
/// @notice Interface for hooks that specifically handle outflows (withdrawals)
/// @dev Provides additional functionality needed only for outflow operations
interface ISuperHookOutflow {
/// @notice Replace amounts in the calldata
/// @param data The data to replace amounts in
/// @param amounts The amounts to replace (must match length from decodeAmounts)
/// @return The data with replaced amounts
function replaceCalldataAmounts(
bytes memory data,
uint256[] memory amounts
)
external
pure
returns (bytes memory);
}
/// @title ISuperHookResultOutflow
/// @author Superform Labs
/// @notice Extended result interface for outflow hook operations
/// @dev Extends the base result interface with outflow-specific information
interface ISuperHookResultOutflow is ISuperHookResult {
/// @notice The amount of shares consumed during outflow processing
/// @dev Used for cost basis calculation in the accounting system
/// @return The amount of shares consumed from the user's position
function usedShares() external view returns (uint256);
}
/// @title ISuperHookLoans
/// @author Superform Labs
/// @notice Interface for hooks that interact with lending protocols
/// @dev Extends context awareness to enable loan operations within hook chains
interface ISuperHookLoans is ISuperHookContextAware {
/// @notice Gets the address of the token being borrowed
/// @dev Used to identify which asset is being borrowed from the lending protocol
/// @param data The hook-specific data containing loan information
/// @return The address of the borrowed token
function getLoanTokenAddress(bytes memory data) external pure returns (address);
/// @notice Gets the address of the token used as collateral
/// @dev Used to identify which asset is being used to secure the loan
/// @param data The hook-specific data containing collateral information
/// @return The address of the collateral token
function getCollateralTokenAddress(bytes memory data) external view returns (address);
/// @notice Gets the current loan token balance for an account
/// @dev Used to track outstanding loan amounts
/// @param account The account to check the loan balance for
/// @param data The hook-specific data containing loan parameters
/// @return The amount of tokens currently borrowed
function getLoanTokenBalance(address account, bytes memory data) external view returns (uint256);
/// @notice Gets the current collateral token balance for an account
/// @dev Used to track collateral positions
/// @param account The account to check the collateral balance for
/// @param data The hook-specific data containing collateral parameters
/// @return The amount of tokens currently used as collateral
function getCollateralTokenBalance(address account, bytes memory data) external view returns (uint256);
}
/// @title ISuperHookAsyncCancelations
/// @author Superform Labs
/// @notice Interface for hooks that can cancel asynchronous operations
/// @dev Used to handle cancellation of pending operations that haven't completed
interface ISuperHookAsyncCancelations {
/// @notice Types of cancellations that can be performed
/// @dev Distinguishes between different operation types that can be canceled
enum CancelationType {
NONE, // Not a cancelation hook
INFLOW, // Cancels a pending deposit operation
OUTFLOW // Cancels a pending withdrawal operation
}
/// @notice Identifies the type of async operation this hook can cancel
/// @dev Used to verify the hook is appropriate for the operation being canceled
/// @return asyncType The type of cancellation this hook performs
function isAsyncCancelHook() external pure returns (CancelationType asyncType);
}
/// @title ISuperHook
/// @author Superform Labs
/// @notice The core hook interface that all hooks must implement
/// @dev Defines the lifecycle methods and execution flow for the hook system
/// Hooks are executed in sequence with results passed between them
interface ISuperHook {
/*//////////////////////////////////////////////////////////////
ENUMS
//////////////////////////////////////////////////////////////*/
/// @notice Defines the possible types of hooks in the system
/// @dev Used to determine how the hook affects accounting and what operations it performs
enum HookType {
NONACCOUNTING, // Hook doesn't affect accounting (e.g., a swap or bridge)
INFLOW, // Hook processes deposits or positions being added
OUTFLOW // Hook processes withdrawals or positions being removed
}
/*//////////////////////////////////////////////////////////////
VIEW METHODS
//////////////////////////////////////////////////////////////*/
/// @notice Builds the execution array for the hook operation
/// @dev This is the core method where hooks define their on-chain interactions
/// The returned executions are a sequence of contract calls to perform
/// No state changes should occur in this method
/// @param prevHook The address of the previous hook in the chain, or address(0) if first
/// @param account The account to perform executions for (usually an ERC7579 account)
/// @param data The hook-specific parameters and configuration data
/// @return executions Array of Execution structs defining calls to make
function build(
address prevHook,
address account,
bytes calldata data
)
external
view
returns (Execution[] memory executions);
/*//////////////////////////////////////////////////////////////
PUBLIC METHODS
//////////////////////////////////////////////////////////////*/
/// @notice Prepares the hook for execution
/// @dev Called before the main execution, used to validate inputs and set execution context
/// This method may perform state changes to set up the hook's execution state
/// @param prevHook The address of the previous hook in the chain, or address(0) if first
/// @param account The account to perform operations for
/// @param data The hook-specific parameters and configuration data
function preExecute(address prevHook, address account, bytes memory data) external;
/// @notice Finalizes the hook after execution
/// @dev Called after the main execution, used to update hook state and calculate results
/// Sets output values (outAmount, usedShares, etc.) for subsequent hooks
/// @param prevHook The address of the previous hook in the chain, or address(0) if first
/// @param account The account operations were performed for
/// @param data The hook-specific parameters and configuration data
function postExecute(address prevHook, address account, bytes memory data) external;
/// @notice Human-readable name for UI display
/// @return The hook's friendly name
function name() external pure returns (string memory);
/// @notice One-sentence description of what this hook does
/// @return A human-readable description for UI display
function description() external pure returns (string memory);
/// @notice Returns the specific subtype identification for this hook
/// @dev Used to categorize hooks beyond the basic HookType
/// For example, a hook might be of type INFLOW but subtype VAULT_DEPOSIT
/// @return A bytes32 identifier for the specific hook functionality
function subtype() external view returns (bytes32);
/// @notice Resets hook mutexes
/// @param caller The caller address for context identification
function resetExecutionState(address caller) external;
/// @notice Sets the caller address that initiated the execution
/// @dev Used for security validation between preExecute and postExecute calls
/// @param caller The caller address for context identification
function setExecutionContext(address caller) external;
/// @notice Returns the execution nonce for the current execution context
/// @dev Used to ensure unique execution contexts and prevent replay attacks
/// @return The execution nonce
function executionNonce() external view returns (uint256);
/// @notice Returns the last caller registered by `setExecutionContext`
/// @return The last caller address
function lastCaller() external view returns (address);
}
src/interfaces/ISuperHookSwap.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
/// @title ISuperHookSwap
/// @author Superform Labs
/// @notice Interface for the Layer 1 standard swap calldata layout
/// @dev All SWAP-subtype hooks must implement this interface
/// @dev Layout (absolute byte offsets within full hook data):
/// [0:52] Layer 0: zero-filled 52-byte strategy header
/// [52:72] inputToken (address, 20 bytes)
/// [72:92] outputToken (address, 20 bytes)
/// [92:124] inputAmount (uint256, 32 bytes)
/// [124:156] outputQuote (uint256, 32 bytes)
/// [156:188] outputMin (uint256, 32 bytes)
/// [188:189] usePrevHookAmount (bool, 1 byte)
/// [189:221] payloadLength (uint256, 32 bytes)
/// [221+] payload — protocol-specific Layer 2 bytes (variable)
interface ISuperHookSwap {
/// @notice Packed Layer 1 header fields for encoding swap hook data
struct SwapHeader {
address inputToken;
address outputToken;
uint256 inputAmount;
uint256 outputQuote;
uint256 outputMin;
bool usePrevHookAmount;
}
/// @notice Encode the full hook calldata from a Layer 1 header and a protocol-specific payload
/// @param header The standardised Layer 1 fields
/// @param payload Protocol-specific Layer 2 bytes (may be empty)
/// @return data The complete encoded calldata: 52-byte zero prefix + Layer 1 + Layer 2
function encodeSwapData(SwapHeader calldata header, bytes calldata payload) external pure returns (bytes memory data);
/// @notice Decode the input token address from hook calldata (offset 52)
function decodeInputToken(bytes calldata data) external pure returns (address);
/// @notice Decode the output token address from hook calldata (offset 72)
function decodeOutputToken(bytes calldata data) external pure returns (address);
/// @notice Decode the input amount from hook calldata (offset 92)
function decodeInputAmount(bytes calldata data) external pure returns (uint256);
/// @notice Decode the output quote from hook calldata (offset 124)
/// @dev Represents the aggregator-quoted expected output; equals outputMin for AMM hooks
function decodeOutputQuote(bytes calldata data) external pure returns (uint256);
/// @notice Decode the minimum acceptable output from hook calldata (offset 156)
function decodeOutputMin(bytes calldata data) external pure returns (uint256);
/// @notice Decode the protocol-specific payload from hook calldata (starting at offset 221)
/// @dev payloadLength is read from offset 189 to know how many bytes to return
function decodePayload(bytes calldata data) external pure returns (bytes memory);
}
src/libraries/HookDataDecoder.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
import { BytesLib } from "../vendor/BytesLib.sol";
/// @title HookDataDecoder
/// @author Superform Labs
/// @notice Library for decoding hook data
library HookDataDecoder {
function extractYieldSourceOracleId(bytes memory data) internal pure returns (bytes32) {
return bytes32(BytesLib.slice(data, 0, 32));
}
function extractYieldSource(bytes memory data) internal pure returns (address) {
return BytesLib.toAddress(data, 32);
}
}
src/libraries/HookDataUpdater.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
library HookDataUpdater {
uint256 private constant PRECISION = 1e5;
function getUpdatedOutputAmount(
uint256 amount,
uint256 _prevAmount,
uint256 outputAmount
)
internal
pure
returns (uint256)
{
if (_prevAmount == 0) return outputAmount;
if (amount != _prevAmount) {
if (amount > _prevAmount) {
uint256 percentIncrease = Math.mulDiv(amount - _prevAmount, PRECISION, _prevAmount);
outputAmount = outputAmount + Math.mulDiv(outputAmount, percentIncrease, PRECISION);
} else {
uint256 percentDecrease = Math.mulDiv(_prevAmount - amount, PRECISION, _prevAmount);
uint256 decreaseAmount = Math.mulDiv(outputAmount, percentDecrease, PRECISION);
outputAmount = outputAmount - decreaseAmount;
}
}
return outputAmount;
}
}
src/libraries/HookSubTypes.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
/// @title HookSubTypes
/// @author Superform Labs
/// @notice Library for hook subtypes
library HookSubTypes {
bytes32 public constant BRIDGE = keccak256(bytes("Bridge"));
bytes32 public constant CANCEL_DEPOSIT = keccak256(bytes("CancelDeposit"));
bytes32 public constant CANCEL_DEPOSIT_REQUEST = keccak256(bytes("CancelDepositRequest"));
bytes32 public constant CANCEL_REDEEM = keccak256(bytes("CancelRedeem"));
bytes32 public constant CANCEL_REDEEM_REQUEST = keccak256(bytes("CancelRedeemRequest"));
bytes32 public constant CLAIM = keccak256(bytes("Claim"));
bytes32 public constant CLAIM_CANCEL_DEPOSIT_REQUEST = keccak256(bytes("ClaimCancelDepositRequest"));
bytes32 public constant CLAIM_CANCEL_REDEEM_REQUEST = keccak256(bytes("ClaimCancelRedeemRequest"));
bytes32 public constant COOLDOWN = keccak256(bytes("Cooldown"));
bytes32 public constant ETHENA = keccak256(bytes("Ethena"));
bytes32 public constant ERC4626 = keccak256(bytes("ERC4626"));
bytes32 public constant ERC5115 = keccak256(bytes("ERC5115"));
bytes32 public constant ERC7540 = keccak256(bytes("ERC7540"));
bytes32 public constant LOAN = keccak256(bytes("Loan"));
bytes32 public constant LOAN_REPAY = keccak256(bytes("LoanRepay"));
bytes32 public constant MISC = keccak256(bytes("Misc"));
bytes32 public constant STAKE = keccak256(bytes("Stake"));
bytes32 public constant SWAP = keccak256(bytes("Swap"));
bytes32 public constant TOKEN = keccak256(bytes("Token"));
bytes32 public constant UNSTAKE = keccak256(bytes("Unstake"));
bytes32 public constant PTYT = keccak256(bytes("PTYT"));
bytes32 public constant VAULT_BANK = keccak256(bytes("VaultBank"));
function getHookSubType(string memory hookSubtype) internal pure returns (bytes32) {
return keccak256(bytes(hookSubtype));
}
}
src/libraries/SwapCalldataLayout.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
/// @title SwapCalldataLayout
/// @author Superform Labs
/// @notice Shared byte-offset constants for the Layer 1 swap calldata standard
/// @dev Imported by all SWAP-subtype hooks; eliminates magic numbers across the hook family
library SwapCalldataLayout {
// ─── Layer 0: zero-filled strategy header ───────────────────────────────
uint256 internal constant HEADER_SIZE = 52;
// ─── Layer 1: standard swap tail — fixed absolute offsets ───────────────
/// @dev address inputToken (20 bytes)
uint256 internal constant INPUT_TOKEN_OFFSET = 52;
/// @dev address outputToken (20 bytes)
uint256 internal constant OUTPUT_TOKEN_OFFSET = 72;
/// @dev uint256 inputAmount (32 bytes) — the OMS-controlled sizing amount
uint256 internal constant INPUT_AMOUNT_OFFSET = 92;
/// @dev uint256 outputQuote (32 bytes) — aggregator quote; equals outputMin for AMM hooks
uint256 internal constant OUTPUT_QUOTE_OFFSET = 124;
/// @dev uint256 outputMin (32 bytes) — minimum acceptable output (slippage guard)
uint256 internal constant OUTPUT_MIN_OFFSET = 156;
/// @dev bool usePrevHookAmount (1 byte)
uint256 internal constant USE_PREV_HOOK_OFFSET = 188;
/// @dev uint256 payloadLength (32 bytes) — byte length of the Layer 2 payload that follows
uint256 internal constant PAYLOAD_LENGTH_OFFSET = 189;
/// @dev bytes payload start — protocol-specific Layer 2 data (variable length)
uint256 internal constant PAYLOAD_DATA_OFFSET = 221;
// ─── Derived constants ───────────────────────────────────────────────────
/// @notice Minimum valid data length for any swap hook (Layer 0 + full Layer 1, no payload)
uint256 internal constant MIN_DATA_LENGTH = 221;
/// @notice Alias kept for compatibility with ISuperHookInflowOutflow / ISuperHookOutflow callers
uint256 internal constant AMOUNT_POSITION = INPUT_AMOUNT_OFFSET; // = 92
}
src/vendor/BytesLib.sol
// SPDX-License-Identifier: Unlicense
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity 0.8.30;
library BytesLib {
function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {
bytes memory tempBytes;
assembly ("memory-safe") {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for { let cc := add(_postBytes, 0x20) } lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} { mstore(mc, mload(cc)) }
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(
0x40,
and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
)
)
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly ("memory-safe") {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes.slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes.slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} { sstore(sc, mload(mc)) }
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} { sstore(sc, mload(mc)) }
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {
// We're using the unchecked block below because otherwise execution ends
// with the native overflow error code.
unchecked {
require(_length + 31 >= _length, "slice_overflow");
}
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly ("memory-safe") {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} { mstore(mc, mload(cc)) }
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly ("memory-safe") {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_bytes.length >= _start + 1, "toUint8_outOfBounds");
uint8 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
uint16 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
uint32 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
uint64 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
uint96 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
uint128 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
uint256 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
bytes32 tempBytes32;
assembly ("memory-safe") {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly ("memory-safe") {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for { let cc := add(_postBytes, 0x20) }
// the next line is the loop condition:
// while(uint256(mc < end) + cb == 2)
eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
bool success = true;
assembly ("memory-safe") {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes.slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint256(mc < end) + cb == 2)
for { } eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
src/vendor/pendle/IPYieldToken.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity ^0.8.0;
/// @title IPYieldToken
/// @notice Minimal interface for Pendle Yield Token (YT) needed for hook operations
/// @dev Full interface at lib/pendle-core-v2-public/contracts/interfaces/IPYieldToken.sol
interface IPYieldToken {
/// @notice Returns the address of the Standardized Yield (SY) token
function SY() external view returns (address);
/// @notice Returns the address of the Principal Token (PT)
function PT() external view returns (address);
/// @notice Returns the expiry timestamp of the YT
function expiry() external view returns (uint256);
/// @notice Returns whether the YT has expired
function isExpired() external view returns (bool);
}
src/vendor/pendle/IPendleMarket.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.30;
interface IPendleMarket {
function readTokens() external view returns (address sy, address pt, address yt);
}
src/vendor/pendle/IPendleRouterV4.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.30;
struct ApproxParams {
uint256 guessMin;
uint256 guessMax;
uint256 guessOffchain;
uint256 maxIteration;
uint256 eps;
}
struct TokenInput {
address tokenIn;
uint256 netTokenIn;
address tokenMintSy;
address pendleSwap;
SwapData swapData;
}
struct LimitOrderData {
address limitRouter;
uint256 epsSkipMarket;
FillOrderParams[] normalFills;
FillOrderParams[] flashFills;
bytes optData;
}
struct FillOrderParams {
Order order;
bytes signature;
uint256 makingAmount;
}
struct Order {
uint256 salt;
uint256 expiry;
uint256 nonce;
OrderType orderType;
address token;
address YT;
address maker;
address receiver;
uint256 makingAmount;
uint256 lnImpliedRate;
uint256 failSafeRate;
bytes permit;
}
struct SwapData {
SwapType swapType;
address extRouter;
bytes extCalldata;
bool needScale;
}
struct TokenOutput {
address tokenOut;
uint256 minTokenOut;
address tokenRedeemSy;
address pendleSwap;
SwapData swapData;
}
enum OrderType {
SY_FOR_PT,
PT_FOR_SY,
SY_FOR_YT,
YT_FOR_SY
}
enum SwapType {
NONE,
KYBERSWAP,
ODOS,
// ETH_WETH not used in Aggregator
ETH_WETH,
OKX,
ONE_INCH,
RESERVE_1,
RESERVE_2,
RESERVE_3,
RESERVE_4,
RESERVE_5
}
interface IPendleRouterV4 {
function swapExactTokenForPt(
address receiver,
address market,
uint256 minPtOut,
ApproxParams calldata guessPtOut,
TokenInput calldata input,
LimitOrderData calldata limit
)
external
payable
returns (uint256 netPtOut, uint256 netSyFee, uint256 netSyInterm);
function swapExactPtForToken(
address receiver,
address market,
uint256 exactPtIn,
TokenOutput calldata output,
LimitOrderData calldata limit
)
external
returns (uint256 netTokenOut, uint256 netSyFee, uint256 netSyInterm);
function redeemPyToToken(
address receiver,
address YT,
uint256 netPyIn,
TokenOutput calldata output
)
external
returns (uint256 netTokenOut, uint256 netSyInterm);
function mintPyFromToken(
address receiver,
address YT,
uint256 minPyOut,
TokenInput calldata input
)
external
payable
returns (uint256 netPtOut, uint256 netSyInterm);
/// @dev Creates a TokenOutput struct without using any swap aggregator
/// @param tokenOut must be one of the SY's tokens out (obtain via `IStandardizedYield#getTokensOut`)
/// @param minTokenOut minimum amount of token out
function createTokenOutputSimple(
address tokenOut,
uint256 minTokenOut
)
external
pure
returns (TokenOutput memory);
}
src/vendor/pendle/IStandardizedYield.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
interface IStandardizedYield is IERC20Metadata {
/// @dev Emitted when any base tokens is deposited to mint shares
event Deposit(
address indexed caller,
address indexed receiver,
address indexed tokenIn,
uint256 amountDeposited,
uint256 amountSyOut
);
/// @dev Emitted when any shares are redeemed for base tokens
event Redeem(
address indexed caller,
address indexed receiver,
address indexed tokenOut,
uint256 amountSyToRedeem,
uint256 amountTokenOut
);
/// @dev check `assetInfo()` for more information
enum AssetType {
TOKEN,
LIQUIDITY
}
/// @dev Emitted when (`user`) claims their rewards
event ClaimRewards(address indexed user, address[] rewardTokens, uint256[] rewardAmounts);
/**
* @notice mints an amount of shares by depositing a base token.
* @param receiver shares recipient address
* @param tokenIn address of the base tokens to mint shares
* @param amountTokenToDeposit amount of base tokens to be transferred from (`msg.sender`)
* @param minSharesOut reverts if amount of shares minted is lower than this
* @return amountSharesOut amount of shares minted
* @dev Emits a {Deposit} event
*
* Requirements:
* - (`tokenIn`) must be a valid base token.
*/
function deposit(
address receiver,
address tokenIn,
uint256 amountTokenToDeposit,
uint256 minSharesOut
)
external
payable
returns (uint256 amountSharesOut);
/**
* @notice redeems an amount of base tokens by burning some shares
* @param receiver recipient address
* @param amountSharesToRedeem amount of shares to be burned
* @param tokenOut address of the base token to be redeemed
* @param minTokenOut reverts if amount of base token redeemed is lower than this
* @param burnFromInternalBalance if true, burns from balance of `address(this)`, otherwise burns from `msg.sender`
* @return amountTokenOut amount of base tokens redeemed
* @dev Emits a {Redeem} event
*
* Requirements:
* - (`tokenOut`) must be a valid base token.
*/
function redeem(
address receiver,
uint256 amountSharesToRedeem,
address tokenOut,
uint256 minTokenOut,
bool burnFromInternalBalance
)
external
returns (uint256 amountTokenOut);
/**
* @notice exchangeRate * syBalance / 1e18 must return the asset balance of the account
* @notice vice-versa, if a user uses some amount of tokens equivalent to X asset, the amount of sy
* he can mint must be X * exchangeRate / 1e18
* @dev SYUtils's assetToSy & syToAsset should be used instead of raw multiplication
* & division
*/
function exchangeRate() external view returns (uint256 res);
/**
* @notice claims reward for (`user`)
* @param user the user receiving their rewards
* @return rewardAmounts an array of reward amounts in the same order as `getRewardTokens`
* @dev
* Emits a `ClaimRewards` event
* See {getRewardTokens} for list of reward tokens
*/
function claimRewards(address user) external returns (uint256[] memory rewardAmounts);
/**
* @notice get the amount of unclaimed rewards for (`user`)
* @param user the user to check for
* @return rewardAmounts an array of reward amounts in the same order as `getRewardTokens`
*/
function accruedRewards(address user) external view returns (uint256[] memory rewardAmounts);
function rewardIndexesCurrent() external returns (uint256[] memory indexes);
function rewardIndexesStored() external view returns (uint256[] memory indexes);
/**
* @notice returns the list of reward token addresses
*/
function getRewardTokens() external view returns (address[] memory);
/**
* @notice returns the address of the underlying yield token
*/
function yieldToken() external view returns (address);
/**
* @notice returns all tokens that can mint this SY
*/
function getTokensIn() external view returns (address[] memory res);
/**
* @notice returns all tokens that can be redeemed by this SY
*/
function getTokensOut() external view returns (address[] memory res);
function isValidTokenIn(address token) external view returns (bool);
function isValidTokenOut(address token) external view returns (bool);
function previewDeposit(
address tokenIn,
uint256 amountTokenToDeposit
)
external
view
returns (uint256 amountSharesOut);
function previewRedeem(
address tokenOut,
uint256 amountSharesToRedeem
)
external
view
returns (uint256 amountTokenOut);
/**
* @notice This function contains information to interpret what the asset is
* @return assetType the type of the asset (0 for ERC20 tokens, 1 for AMM liquidity tokens,
* 2 for bridged yield bearing tokens like wstETH, rETH on Arbi whose the underlying asset doesn't exist on the
* chain)
* @return assetAddress the address of the asset
* @return assetDecimals the decimals of the asset
*/
function assetInfo() external view returns (AssetType assetType, address assetAddress, uint8 assetDecimals);
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"excessivelySafeCall/=lib/ExcessivelySafeCall/src/",
"modulekit/=lib/modulekit/src/",
"@prb/math/=lib/modulekit/node_modules/@prb/math/src/",
"@solady/=lib/solady/",
"@account-abstraction/=lib/modulekit/node_modules/account-abstraction/contracts/",
"@ERC4337/=lib/modulekit/node_modules/@ERC4337/",
"@pigeon/=lib/pigeon/src/",
"@surl/=lib/surl/src/",
"@stringutils/=lib/solidity-stringutils/src/",
"@pendle/=lib/pendle-core-v2-public/contracts/",
"@safe/=lib/safe-smart-account/contracts/",
"@safe7579/=lib/safe7579/src/",
"@nexus/=lib/nexus/contracts/",
"sentinellist/=lib/nexus/node_modules/sentinellist/src/",
"solady/=lib/nexus/node_modules/solady/src/",
"solarray/=lib/nexus/node_modules/solarray/src/",
"account-abstraction/=lib/modulekit/node_modules/@ERC4337/account-abstraction/contracts/",
"account-abstraction-v0.6/=lib/modulekit/node_modules/@ERC4337/account-abstraction-v0.6/contracts/",
"excessively-safe-call/=lib/ExcessivelySafeCall/src/",
"composability/=lib/nexus/node_modules/@biconomy/composability/contracts/",
"erc7739Validator/=lib/nexus/node_modules/erc7739-validator-base/src/",
"test/mock_fiattoken/=lib/evm-gateway-contracts/test/mock_fiattoken/",
"@rhinestone/erc4337-validation/=lib/modulekit/node_modules/@rhinestone/erc4337-validation/",
"erc4337-validation/=lib/modulekit/node_modules/@rhinestone/erc4337-validation/src/",
"forge-std/=lib/modulekit/node_modules/forge-std/src/",
"rhinestone/checknsignatures/=lib/checknsignatures/",
"evm-gateway/=lib/evm-gateway-contracts/src/",
"lib/evm-gateway-contracts:src/=lib/evm-gateway-contracts/src/",
"lib/evm-gateway-contracts:test/=lib/evm-gateway-contracts/test/",
"v4-core/=lib/v4-core/src/",
"@biconomy/=lib/nexus/node_modules/@biconomy/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@erc7579/=lib/nexus/node_modules/@erc7579/",
"@gnosis.pm/=lib/nexus/node_modules/@gnosis.pm/",
"@memview-sol/=lib/evm-gateway-contracts/lib/memview-sol/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/contracts/",
"@safe-global/=lib/nexus/node_modules/@safe-global/",
"@zerodev/=lib/nexus/node_modules/@zerodev/",
"ExcessivelySafeCall/=lib/ExcessivelySafeCall/src/",
"checknsignatures/=lib/checknsignatures/src/",
"ds-test/=lib/nexus/node_modules/ds-test/",
"enumerableset4337/=lib/nexus/node_modules/erc7739-validator-base/node_modules/@erc7579/enumerablemap4337/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"erc7579/=lib/nexus/node_modules/erc7579/",
"erc7739-validator-base/=lib/nexus/node_modules/erc7739-validator-base/",
"eth-gas-reporter/=lib/nexus/node_modules/eth-gas-reporter/",
"evm-gateway-contracts/=lib/evm-gateway-contracts/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat-deploy/=lib/nexus/node_modules/hardhat-deploy/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"kernel/=lib/nexus/node_modules/erc7739-validator-base/node_modules/@zerodev/kernel/src/",
"memview-sol/=lib/evm-gateway-contracts/lib/memview-sol/contracts/",
"module-bases/=lib/safe7579/node_modules/@rhinestone/module-bases/src/",
"nexus/=lib/nexus/",
"openzeppelin-contracts-upgradeable/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"pendle-core-v2-public/=lib/pendle-core-v2-public/contracts/",
"pigeon/=lib/pigeon/src/",
"prep/=lib/nexus/node_modules/prep/",
"safe-smart-account/=lib/safe-smart-account/",
"safe7579/=lib/safe7579/",
"solidity-stringutils/=lib/solidity-stringutils/",
"solmate/=lib/v4-core/lib/solmate/",
"surl/=lib/surl/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.