Verified contractPartialBUSL-1.1
StrategySwapAndPark
Address0x7e3889d000a71b3bbd7f6e2d2b5265faed5f4ce0
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 22,874,044
- Creation transaction
- 0x1a4ae1d764…bb59346bd3
- Libraries
- contracts/libraries/SwapLibrary.sol:SwapLibrary0xf60f…dc4b2f
62 files
- contracts/core/strategies/StrategySwapAndPark.solmain3.91 KB
- contracts/core/Constants.sol1.35 KB
- contracts/core/GovernableOwnable.sol1.99 KB
- contracts/core/hooks/swappers/UseUniV2Swapper.sol4.14 KB
- contracts/core/hooks/swappers/UseUnifiedSwapper.sol6.75 KB
- contracts/core/strategies/StrategySwapAnd.sol15.41 KB
- contracts/interfaces/aerodrome/ISwapRouter.sol3.65 KB
- contracts/interfaces/core/IOracle.sol1.47 KB
- contracts/interfaces/core/IStrategy.sol3.04 KB
- contracts/interfaces/core/ISwapHandler.sol1.39 KB
- contracts/interfaces/curve/ICurveRouterNG.sol3.44 KB
- contracts/interfaces/uniswap/v2/IUniswapV2Router01.sol3.65 KB
- contracts/interfaces/uniswap/v2/IUniswapV2Router02.sol1.3 KB
- contracts/interfaces/uniswap/v3/IV3SwapRouter.sol3.61 KB
- contracts/libraries/AerodromeLibrary.sol2.76 KB
- contracts/libraries/CurveFiLibrary.sol14.18 KB
- contracts/libraries/MathLibrary.sol5.63 KB
- contracts/libraries/SwapLibrary.sol3.21 KB
- contracts/libraries/UniV2Library.sol4.52 KB
- contracts/libraries/UniV3Library.sol2.9 KB
- contracts/libraries/UniV4Library.sol6.27 KB
- lib/permit2/src/interfaces/IAllowanceTransfer.sol7.7 KB
- lib/permit2/src/interfaces/IEIP712.sol144 B
- lib/permit2/src/interfaces/IPermit2.sol548 B
- lib/permit2/src/interfaces/ISignatureTransfer.sol6.88 KB
- lib/universal-router/contracts/interfaces/IUniversalRouter.sol1.17 KB
- lib/universal-router/contracts/libraries/Commands.sol1.85 KB
- lib/v4-core/src/interfaces/IExtsload.sol1.02 KB
- lib/v4-core/src/interfaces/IExttload.sol699 B
- lib/v4-core/src/interfaces/IHooks.sol8.3 KB
- lib/v4-core/src/interfaces/IPoolManager.sol13.45 KB
- lib/v4-core/src/interfaces/IProtocolFees.sol2.49 KB
- lib/v4-core/src/interfaces/external/IERC20Minimal.sol3.04 KB
- lib/v4-core/src/interfaces/external/IERC6909Claims.sol3.16 KB
- lib/v4-core/src/libraries/CustomRevert.sol5.17 KB
- lib/v4-core/src/libraries/SafeCast.sol2.27 KB
- lib/v4-core/src/types/BalanceDelta.sol2.34 KB
- lib/v4-core/src/types/BeforeSwapDelta.sol1.47 KB
- lib/v4-core/src/types/Currency.sol5.46 KB
- lib/v4-core/src/types/PoolId.sol539 B
- lib/v4-core/src/types/PoolKey.sol805 B
- lib/v4-periphery/src/interfaces/IImmutableState.sol365 B
- lib/v4-periphery/src/interfaces/IV4Router.sol1.64 KB
- lib/v4-periphery/src/libraries/Actions.sol2.03 KB
- lib/v4-periphery/src/libraries/PathKey.sol1.37 KB
- node_modules/@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol3.17 KB
- node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.64 KB
- node_modules/@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol3.68 KB
- node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol13.49 KB
- node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol2.75 KB
- node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol716 B
- node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol3.81 KB
- node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol7.1 KB
- node_modules/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol9.38 KB
- node_modules/@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.48 KB
- node_modules/@openzeppelin/contracts/access/Ownable.sol2.62 KB
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.74 KB
- node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol6.94 KB
- node_modules/@openzeppelin/contracts/utils/Address.sol9.36 KB
- node_modules/@openzeppelin/contracts/utils/Context.sol962 B
contracts/core/strategies/StrategySwapAndPark.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import { StrategySwapAnd } from "./StrategySwapAnd.sol";
import { IERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import { SafeERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import { IOracle } from "../../interfaces/core/IOracle.sol";
/**
* @title StrategySwapAndPark
* @notice A strategy that swaps between two assets and parks the output asset
* @dev This strategy extends StrategySwapAnd and implements parking functionality
* @dev It provides gas-efficient operations by avoiding external contract calls
* @dev The output asset is simply held in the contract without generating yield
*/
contract StrategySwapAndPark is StrategySwapAnd {
using SafeERC20Upgradeable for IERC20Upgradeable;
error ZeroAddress();
error ZeroAmount();
error InsufficientBalance();
// Output Asset (the asset being parked)
IERC20Upgradeable private _outputAsset;
// Track deployed amount in output asset
uint256 private _deployedAmountOutput;
// Gap for future upgrades
uint256[50] private __gap;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @notice Initializes the SwapAndPark contract
* @param initialOwner The address that will own the contract
* @param initialGovernor The address that will govern the contract
* @param iAsset The input asset token
* @param outputAsset_ The output asset token to be parked
* @param iOracle The oracle that provides price data for the asset pair (price precision is 18 decimals)
*/
function initialize(
address initialOwner,
address initialGovernor,
IERC20Upgradeable iAsset,
IERC20Upgradeable outputAsset_,
IOracle iOracle
) public initializer {
// Validate that the output asset is not a zero address
if (address(outputAsset_) == address(0)) revert ZeroAddress();
// Initialize the base StrategySwapAnd contract
super.initialize(initialOwner, initialGovernor, iAsset, iOracle);
// Set the output asset
_outputAsset = outputAsset_;
}
/**
* @notice Returns the address of the output asset
* @return The address of the output asset
*/
function outputAsset() public view override returns (address) {
return address(_outputAsset);
}
/**
* @notice Deploys assets to the parking strategy (simply holds the assets)
* @param amount The amount of output asset to deploy
* @return deployedAmount The amount actually deployed (same as input)
*/
function strategyDeploy(uint256 amount) internal override returns (uint256 deployedAmount) {
if (amount == 0) revert ZeroAmount();
// Simply track the deployed amount - assets are already in the contract from the swap
_deployedAmountOutput += amount;
deployedAmount = amount;
}
/**
* @notice Undeploys assets from the parking strategy
* @param amount The amount of output asset to undeploy
* @return undeployedAmount The amount actually undeployed
*/
function strategyUndeploy(uint256 amount) internal override returns (uint256 undeployedAmount) {
if (amount == 0) revert ZeroAmount();
if (amount > _deployedAmountOutput) revert InsufficientBalance();
// Update the deployed amount
_deployedAmountOutput -= amount;
undeployedAmount = amount;
}
/**
* @notice Gets total assets from the parking strategy
* @return assets The total assets in output asset terms
*/
function strategyTotalAssets() internal view override returns (uint256 assets) {
return _deployedAmountOutput;
}
/**
* @notice Gets the deployed amount in output asset terms
* @return The deployed amount in output asset
*/
function deployedAmountOutput() external view returns (uint256) {
return _deployedAmountOutput;
}
}contracts/core/Constants.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/**
* @title These are global constants used by other contracts
*/
/**
* @dev Constant representing the maximum allowed loan-to-value ratio.
*
* This constant holds the value 1e9, representing the maximum allowed loan-to-value ratio as 100%.
* It is used to limit the loan-to-value ratio for specific processes.
*/
uint256 constant MAX_LOAN_TO_VALUE = 1e9; // 100%
/**
* @dev Constant representing the maximum allowed number of loops.
*
* This constant holds the value 20, representing the maximum allowed number of loops.
* It is used to limit the number of loops for a specific process.
*/
uint8 constant MAX_LOOPS = 20; // 100%
/**
* @dev Constant representing the precision for percentage values.
*
* This constant holds the value 1e9, representing the precision for percentage values.
* It is used for calculations involving percentage precision.
*/
uint256 constant PERCENTAGE_PRECISION = 1e9;
address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
bytes32 constant ADMIN_ROLE = 0x00;
bytes32 constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 constant VAULT_MANAGER_ROLE = keccak256("VAULT_MANAGER_ROLE");
bytes32 constant PROCESSOR_ROLE = keccak256("PROCESSOR_ROLE");
bytes32 constant PRICE_UPDATER_ROLE = keccak256("PRICE_UPDATER_ROLE");
contracts/core/GovernableOwnable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
/**
* @title An Upgradable GovernableOwnable Contract
*
* @author Chef Kenji <[email protected]>
* @author Chef Kal-EL <[email protected]>
*
* @dev A Contract that could have an independent owner and governor
*
* This is quite usesufull when you dont need to have more than 2 roles on a contract
*
*/
contract GovernableOwnable is OwnableUpgradeable {
address private _governor;
error GovernorUnauthorized(address caller);
error InvalidGovernorAddress();
event GovernshipTransferred(address indexed previousGovernor, address indexed newGovernor);
uint256[49] private __gap;
function _initializeGovernableOwnable(
address initialOwner,
address initialGovernor
) internal onlyInitializing {
_transferOwnership(initialOwner);
_transferGovernorship(initialGovernor);
}
/**
* Modifier that checks if the caller is governor
*/
modifier onlyGovernor() {
_checkGovernor();
_;
}
/**
* Gets the Governor of the contrat
*/
function governor() public view virtual returns (address) {
return _governor;
}
/**
* @dev Internal function to verify the caller is the controller
* @notice Reverts if the caller is not the controller
*/
function _checkGovernor() internal view virtual {
if (msg.sender != _governor) {
revert GovernorUnauthorized(msg.sender);
}
}
/**
* Changes the contract Governor
* @param _newGovernor the new Governor addres
*/
function transferGovernorship(address _newGovernor) public virtual onlyGovernor {
if (_newGovernor == address(0)) revert InvalidGovernorAddress();
_transferGovernorship(_newGovernor);
}
function _transferGovernorship(address newGovernor) internal virtual {
emit GovernshipTransferred(_governor, newGovernor);
_governor = newGovernor;
}
}
contracts/core/hooks/swappers/UseUniV2Swapper.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import { IUniswapV2Router02 } from "../../../interfaces/uniswap/v2/IUniswapV2Router02.sol";
import { ISwapHandler } from "../../../interfaces/core/ISwapHandler.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { UniV2Library } from "../../../libraries/UniV2Library.sol";
/**
* @title UseUniV2Swapper
*
* @dev Abstract contract to integrate the use of Uniswap V2
* Provides functions to initialize, access and swap
* It allows any contract to swap an ERC-20 for another ERC-20 with a fixed
* input amount or a fixed output amount of tokens.
*
* @author Chef Kenji <[email protected]>
* @author Chef Kal-El <[email protected]>
*/
abstract contract UseUniV2Swapper is ISwapHandler {
using SafeERC20 for IERC20;
error InvalidV2RouterContract();
error FailedToApproveAllowance();
/// @dev Storage slot for the UniswapV2 router address
/// @dev bytes32(uint256(keccak256('bakerfi.storage.UseUniV2Swapper.v2UniRouter')) - 1)
bytes32 private constant _V2_UNI_ROUTER_SLOT =
0x47b2c96b5499f1e2d1a7c2ef4c1a5a1e0d4a0c2e4b6d8f0a2c4e6f8a0c2e4b6d;
/**
* @dev Initialize the Uniswap V2 Swapper
*/
function _initUseUniV2Swapper(IUniswapV2Router02 iV2UniRouter) internal {
if (address(iV2UniRouter) == address(0)) revert InvalidV2RouterContract();
assembly {
sstore(_V2_UNI_ROUTER_SLOT, iV2UniRouter)
}
}
/**
* @notice Returns the Uniswap V2 Router from the storage slot
*/
function v2UniRouter() internal view returns (IUniswapV2Router02) {
address router;
assembly {
router := sload(_V2_UNI_ROUTER_SLOT)
}
return IUniswapV2Router02(router);
}
/**
* @inheritdoc ISwapHandler
*/
/**
* @notice Executes a token swap on Uniswap V2 using the Uniswap V2 Router
* @dev This function allows for two types of swaps:
* - Exact Input: The user specifies the amount of input tokens to swap, and the function calculates
* the minimum amount of output tokens to receive.
* - Exact Output: The user specifies the desired amount of output tokens, and the function calculates
* the maximum amount of input tokens that can be used for the swap.
*
* @param params A struct containing the parameters for the swap, including:
* - underlyingIn: The address of the token being sold.
* - underlyingOut: The address of the token being bought.
* - mode: The type of swap (0 for exact input, 1 for exact output).
* - amountIn: The amount of the input token to sell (exact value for exact input, maximum for exact output).
* - amountOut: The amount of the output token to buy (exact value for exact output, minimum for exact input).
*
* @return amountIn The actual amount of input tokens used in the swap.
* @return amountOut The actual amount of output tokens received from the swap.
*
* @dev Reverts if:
* - The input or output token address is invalid.
* - The swap fails (i.e., the output amount is zero).
*/
function swap(
ISwapHandler.SwapParams memory params
) internal virtual override returns (uint256 amountIn, uint256 amountOut) {
return UniV2Library.swapUniV2(v2UniRouter(), params);
}
/**
* @dev Allow the router to spend the input token
*/
function _allowRouterSpend(IERC20 token, uint256 amount) internal virtual {
if (!token.approve(address(v2UniRouter()), amount)) revert FailedToApproveAllowance();
}
}
/**
* @dev Mock contract to test the UseUniV2Swapper
*/
contract UseUniV2SwapperMock is UseUniV2Swapper {
/**
* @dev Initialize the UseUniV2SwapperMock
*/
constructor(IUniswapV2Router02 iV2UniRouter) {
_initUseUniV2Swapper(iV2UniRouter);
}
/**
* @notice Mock function to test the swap function
*/
function test__swap(
ISwapHandler.SwapParams memory params
) external returns (uint256 amountIn, uint256 amountOut) {
return swap(params);
}
}
contracts/core/hooks/swappers/UseUnifiedSwapper.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import { ISwapHandler } from "../../../interfaces/core/ISwapHandler.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IPermit2 } from "@uniswap/permit2/src/interfaces/IPermit2.sol";
import { ICurveRouterNG } from "../../../interfaces/curve/ICurveRouterNG.sol";
import { SwapLibrary } from "../../../libraries/SwapLibrary.sol";
/**
* @title UseUnifiedSwapper
*
* @notice A contract that allows to swap tokens using different implementations of the swapper
*
* Supports Uniswap V3, Curve, Uniswap V2, and Aerodrome
*
* Manages authorized routes for swaps acting as a unified swap router for different swap implementations.
* Integrating multiple DEX protocols (Uniswap V2, V3, and Aerodrome)
*
* It prevens memory layout collisions on upgrades
*
* @author Chef Kenji <[email protected]>
* @author Chef Kal-El <[email protected]>
*/
abstract contract UseUnifiedSwapper is ISwapHandler {
using SafeERC20 for IERC20;
error InvalidRouter();
error RouteAlreadyAuthorized();
error RouteNotAuthorized();
error FailedToApproveAllowance();
event RouteEnabled(
address indexed tokenIn,
address indexed tokenOut,
SwapLibrary.RouteInfo routeInfo
);
event RouteDisabled(
address indexed tokenIn,
address indexed tokenOut,
SwapLibrary.RouteInfo routeInfo
);
// Route mapping for an input token to an output token
mapping(address => mapping(address => SwapLibrary.RouteInfo)) private _routes;
/**
* @notice Enables a route for a given pair of tokens
* @param tokenIn The input token address
* @param tokenOut The output token address
* @param routeInfo The route information
*/
function _enableRoute(
address tokenIn,
address tokenOut,
SwapLibrary.RouteInfo memory routeInfo,
bool bidirectional
) internal {
// Check if the route is already authorized
if (_routes[tokenIn][tokenOut].provider != SwapLibrary.SwapProvider.NONE) {
revert RouteAlreadyAuthorized();
}
// Check if the route is already authorized in the reverse direction
if (bidirectional && _routes[tokenOut][tokenIn].provider != SwapLibrary.SwapProvider.NONE) {
revert RouteAlreadyAuthorized();
}
if (routeInfo.provider == SwapLibrary.SwapProvider.UNIV4) {
(, , address permit2) = abi.decode(routeInfo.customData, (uint24, int24, address));
IERC20(tokenIn).approve(permit2, type(uint256).max);
IERC20(tokenOut).approve(permit2, type(uint256).max);
}
_routes[tokenIn][tokenOut] = routeInfo;
emit RouteEnabled(tokenIn, tokenOut, routeInfo);
if (bidirectional) {
_routes[tokenOut][tokenIn] = routeInfo;
emit RouteEnabled(tokenOut, tokenIn, routeInfo);
}
}
/**
* @notice Disables a route for a given pair of tokens
* @param tokenIn The input token address
* @param tokenOut The output token address
*/
function _disableRoute(address tokenIn, address tokenOut, bool bidirectional) internal {
// Check if the route is authorized
if (_routes[tokenIn][tokenOut].provider == SwapLibrary.SwapProvider.NONE) {
revert RouteNotAuthorized();
}
// Check if the route is authorized in the reverse direction
if (bidirectional && _routes[tokenOut][tokenIn].provider == SwapLibrary.SwapProvider.NONE) {
revert RouteNotAuthorized();
}
// Check if the route is a UNIV4 route
if (_routes[tokenIn][tokenOut].provider == SwapLibrary.SwapProvider.UNIV4) {
(, , address permit2) = abi.decode(
_routes[tokenIn][tokenOut].customData,
(uint24, int24, address)
);
IERC20(tokenIn).approve(permit2, 0);
IERC20(tokenOut).approve(permit2, 0);
}
// Set the route information to none
_routes[tokenIn][tokenOut].provider = SwapLibrary.SwapProvider.NONE;
emit RouteDisabled(tokenIn, tokenOut, _routes[tokenIn][tokenOut]);
if (bidirectional) {
_routes[tokenOut][tokenIn].provider = SwapLibrary.SwapProvider.NONE;
emit RouteDisabled(tokenOut, tokenIn, _routes[tokenOut][tokenIn]);
}
}
/**
* @notice Checks if a route is authorized for a given pair of tokens
* @param tokenIn The input token address
* @param tokenOut The output token address
* @return true if the route is authorized, false otherwise
*/
function isRouteEnabled(address tokenIn, address tokenOut) public view returns (bool) {
return _getRoute(tokenIn, tokenOut).provider != SwapLibrary.SwapProvider.NONE;
}
function _getRoute(
address tokenIn,
address tokenOut
) internal view returns (SwapLibrary.RouteInfo memory) {
return _routes[tokenIn][tokenOut];
}
/**
* @inheritdoc ISwapHandler
* @notice The swap function is responsible for executing token swaps based on the authorized routes.
* It retrieves the route information, checks if the route is authorized, and then determines
* the appropriate swap pro
* -+
* vider to execute the swap. The function handles swaps for Uniswap V2,
* Uniswap V3, and Curve, encoding the necessary parameters for the Curve swap.
*/
function swap(
SwapParams memory params
) internal virtual override returns (uint256 amountIn, uint256 amountOut) {
// Retrieve the route information using the storage getter
SwapLibrary.RouteInfo memory routeInfo = _getRoute(params.underlyingIn, params.underlyingOut);
// Check if the route is authorized; if not, revert the transaction with an error
return SwapLibrary.swap(routeInfo, params);
}
}
/**
* @title UseUnifiedSwapperMock
* @notice A mock contract for testing the UseUnifiedSwapper contract
*/
contract UseUnifiedSwapperMock is UseUnifiedSwapper, Ownable {
constructor() {
_transferOwnership(msg.sender);
}
/**
* @notice Tests the swap function
* @param params The swap parameters
* @return amountIn The amount of input tokens used in the swap
* @return amountOut The amount of output tokens received from the swap
*/
function test__swap(
SwapParams memory params
) external returns (uint256 amountIn, uint256 amountOut) {
return UseUnifiedSwapper.swap(params);
}
function enableRoute(
address tokenIn,
address tokenOut,
SwapLibrary.RouteInfo memory routeInfo,
bool bidirectional
) external onlyOwner {
_enableRoute(tokenIn, tokenOut, routeInfo, bidirectional);
}
function disableRoute(address tokenIn, address tokenOut, bool bidirectional) external onlyOwner {
_disableRoute(tokenIn, tokenOut, bidirectional);
}
}
contracts/core/strategies/StrategySwapAnd.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import { UseUniV2Swapper } from "../hooks/swappers/UseUniV2Swapper.sol";
import { IUniswapV2Router02 } from "../../interfaces/uniswap/v2/IUniswapV2Router02.sol";
import { IERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IOracle } from "../../interfaces/core/IOracle.sol";
import { ISwapHandler } from "../../interfaces/core/ISwapHandler.sol";
import { UseUnifiedSwapper } from "../hooks/swappers/UseUnifiedSwapper.sol";
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import { IStrategy } from "../../interfaces/core/IStrategy.sol";
import { PERCENTAGE_PRECISION } from "../Constants.sol";
import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import { MathLibrary } from "../../libraries/MathLibrary.sol";
import { SafeERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import { SwapLibrary } from "../../libraries/SwapLibrary.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { GovernableOwnable } from "../GovernableOwnable.sol";
/**
* @title StrategySwapAnd
* @notice An abstract strategy that swaps between two assets using a meta-swap approach
* @dev This strategy uses a unified swapper to swap between two assets with different decimals
* @dev It properly handles decimal conversions by normalizing to 18 decimals for price calculations
* @dev Price precision from oracle is always assumed to be 18 decimals
* @dev It also implements a reentrancy guard to prevent reentrancy attacks
* @dev Derived classes must implement the core strategy functions for gas efficiency
*/
abstract contract StrategySwapAnd is
Initializable,
UseUnifiedSwapper,
ReentrancyGuardUpgradeable,
IStrategy,
GovernableOwnable
{
using SafeERC20Upgradeable for IERC20Upgradeable;
error SlippageExceeded();
error InvalidConfiguration();
error InvalidAmount();
error FailedToApproveAllowanceFor();
error InvalidSlippage();
error InvalidPrice();
event OracleMaxAgeUpdated(uint256 newMaxAge);
event MaxSlippageUpdated(uint256 newMaxSlippage);
event OracleUpdated(address newOracle);
event RouteUpdated(SwapLibrary.SwapProvider provider, address router, bytes customData);
uint256 public constant DEFAULT_MAX_SLIPPAGE = 1e7; //1%
uint256 public constant DEFAULT_ORACLE_MAX_AGE = 10 minutes;
// Input Asset
IERC20Upgradeable internal _iasset;
// Oracle UnderlyingAsset/Asset, Ratio Ex: sUSDS/USDC
IOracle private _oracle;
// Max Slippage 10000 = 100%
uint256 private _maxSlippage; //1%
// Deployed Amount in iAsset Value
uint256 private _deployedAmount;
// Oracle Max Age
uint256 private _oracleMaxAge;
// Gap for future upgrades
uint256[45] private __gap;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @notice Initializes the StrategySwapAnd contract
* @param initialOwner The address that will own the contract
* @param initialGovernor The address that will govern the contract
* @param iAsset The input asset token
* @param iOracle The oracle that provides price data for the asset pair (price precision is 18 decimals)
* @dev Automatically detects and stores decimals for both input and output assets for proper conversion
*/
function initialize(
address initialOwner,
address initialGovernor,
IERC20Upgradeable iAsset,
IOracle iOracle // Oracle UnderlyingAsset/Asset
) public initializer {
_initializeGovernableOwnable(initialOwner, initialGovernor);
// Validate that none of the critical addresses are zero addresses
if (
address(iAsset) == address(0) ||
address(iOracle) == address(0)
) revert InvalidConfiguration();
_maxSlippage = DEFAULT_MAX_SLIPPAGE;
_oracleMaxAge = DEFAULT_ORACLE_MAX_AGE;
// Set the input asset (token being swapped from)
_iasset = iAsset;
// Set the oracle that will provide price information for the asset pair
_oracle = iOracle;
// Transfer ownership to the specified initial owner
_transferOwnership(initialOwner);
}
/**
* @notice Updates the swap route between input and output assets
* @param routeInfo The new route configuration
*/
function setRoute(
SwapLibrary.RouteInfo memory routeInfo,
bool inDirection
) external onlyGovernor {
if (inDirection) {
_enableRoute(address(_iasset), address(outputAsset()), routeInfo, false);
} else {
_enableRoute(address(outputAsset()), address(_iasset), routeInfo, false);
}
}
function getRoute() external view returns (SwapLibrary.RouteInfo memory) {
return _getRoute(address(_iasset), address(outputAsset()));
}
/**
* @notice Returns the address of the output asset
* @return The address of the output asset
*/
function outputAsset() public view virtual returns (address);
/**
* @notice Returns the address of the input asset
* @return The address of the input asset
* @dev Implements the IStrategy interface
*/
function asset() external view override returns (address) {
return address(_iasset);
}
/**
* @notice Set the max slippage tolerance for swaps
* @param maxSlippage_ The max slippage value (10000 = 100%)
*/
function setMaxSlippage(uint256 maxSlippage_) external onlyGovernor {
if (maxSlippage_ > PERCENTAGE_PRECISION) revert InvalidSlippage();
_maxSlippage = maxSlippage_;
emit MaxSlippageUpdated(maxSlippage_);
}
/**
* @notice Get the current max slippage tolerance
* @return The current max slippage value
*/
function maxSlippage() external view returns (uint256) {
return _maxSlippage;
}
/**
* @notice Get the address of the oracle used for price data
* @return The address of the oracle contract
*/
function oracle() external view returns (address) {
return address(_oracle);
}
/**
* @notice Calculates the total assets managed by this strategy in terms of the input asset
* @return amount_ The total value in input asset terms
*/
function _totalAssets() internal view returns (uint256 amount_) {
uint256 outBalance = strategyTotalAssets();
amount_ = _convertFromUnderlying(IOracle.PriceOptions({ maxAge: 0, maxConf: 0 }), outBalance);
return amount_;
}
/**
* @notice Returns the total assets managed by this strategy
* @return The total value in input asset terms
* @dev Implements the IStrategy interface
*/
function totalAssets() external view override returns (uint256) {
return _totalAssets();
}
/**
* @notice Harvests any profits or losses from the strategy
* @return balanceChange The net change in balance (positive for profit, negative for loss)
* @dev Implements the IStrategy interface
*/
function harvest() public override onlyOwner nonReentrant returns (int256 balanceChange) {
return _harvest();
}
/**
* @notice Internal function to harvest profits or losses
* @return balanceChange The net change in balance (positive for profit, negative for loss)
*/
function _harvest() private returns (int256 balanceChange) {
uint256 newBalance = _totalAssets();
balanceChange = int256(newBalance) - int256(_deployedAmount);
if (balanceChange > 0) {
emit StrategyProfit(uint256(balanceChange));
} else if (balanceChange < 0) {
emit StrategyLoss(uint256(-balanceChange));
}
if (balanceChange != 0) {
emit StrategyAmountUpdate(newBalance);
}
_deployedAmount = newBalance;
}
/**
* @notice Converts an amount of input asset to the equivalent amount of output asset
* @param options The oracle price options
* @param amount The amount of input asset to convert
* @return amountOut_ The equivalent amount in output asset
*/
function _convertToUnderlying(
IOracle.PriceOptions memory options,
uint256 amount
) internal view returns (uint256 amountOut_) {
IOracle.Price memory price = _oracle.getSafeLatestPrice(options);
if (price.price == 0) revert InvalidPrice();
amountOut_ = (amount * _oracle.getPrecision()) / price.price;
}
/**
* @notice Converts an amount of output asset to the equivalent amount of input asset
* @param options The oracle price options
* @param amount The amount of output asset to convert
* @return amountOut_ The equivalent amount in input asset
*/
function _convertFromUnderlying(
IOracle.PriceOptions memory options,
uint256 amount
) internal view returns (uint256 amountOut_) {
IOracle.Price memory price = _oracle.getSafeLatestPrice(options);
if (price.price == 0) revert InvalidPrice();
amountOut_ = (amount * price.price) / _oracle.getPrecision();
}
/**
* @notice Deploys capital by swapping input asset for output asset
* @param amount The amount of input asset to deploy
* @return amountDeployed The amount of input asset actually used
* @dev Implements the IStrategy interface
*/
function deploy(
uint256 amount
) external override nonReentrant onlyOwner returns (uint256 amountDeployed) {
// Revert if the amount is zero
if (amount == 0) revert InvalidAmount();
_harvest();
// Set up oracle price options with a maximum age of 1 hour and no confidence threshold
IOracle.PriceOptions memory options = IOracle.PriceOptions({
maxAge: _oracleMaxAge,
maxConf: 0
});
// Transfer the input asset from the sender to this contract
IERC20Upgradeable(_iasset).safeTransferFrom(msg.sender, address(this), amount);
// Calculate the expected output amount based on oracle price
uint256 calculatedAmountOut = _convertToUnderlying(options, amount);
// Apply slippage tolerance to calculate minimum acceptable output
uint256 minAmountOut = (calculatedAmountOut * (PERCENTAGE_PRECISION - _maxSlippage)) /
PERCENTAGE_PRECISION;
// Execute the swap from input asset to output asset
(, uint256 amountOut) = swap(
ISwapHandler.SwapParams({
underlyingIn: address(_iasset),
underlyingOut: address(outputAsset()),
amountIn: amount,
amountOut: minAmountOut,
mode: ISwapHandler.SwapType.EXACT_INPUT,
payload: ""
})
);
// Ensure the received amount meets the minimum threshold
if (amountOut < minAmountOut) revert SlippageExceeded();
// Deploy to the underlying strategy
uint256 deployedAmount = strategyDeploy(amountOut);
// Validate that the deployed amount meets expectations
if (
deployedAmount < (amountOut * (PERCENTAGE_PRECISION - _maxSlippage)) / PERCENTAGE_PRECISION
) {
revert SlippageExceeded();
}
// Since we are deploying the input asset and using exact input, the amount deployed is the amount in
amountDeployed = amount;
// Update the total deployed amount with the deployed capital
_deployedAmount = _totalAssets();
// Emit event to log the deployment action
emit StrategyDeploy(msg.sender, amountDeployed);
// Emit event to log the updated deployed amount
emit StrategyAmountUpdate(_deployedAmount);
}
/**
* @notice Undeploys capital by swapping output asset back to input asset
* @param amount The amount of input asset value to undeploy
* @return undeployedAmount_ The amount of input asset value that was undeployed
* @dev Implements the IStrategy interface
*/
function undeploy(
uint256 amount
) external override nonReentrant onlyOwner returns (uint256 undeployedAmount_) {
if (amount == 0) revert InvalidAmount();
// Harvest the strategy before undeploying
_harvest();
// Revert if the amount is greater than the total assets
if (amount > _totalAssets()) revert InvalidAmount();
// Set up oracle price options with a maximum age of 1 hour and no confidence threshold
IOracle.PriceOptions memory options = IOracle.PriceOptions({
maxAge: _oracleMaxAge,
maxConf: 100
});
// Undeploy from underlying strategy
uint256 toUndeploy = _convertToUnderlying(options, amount);
// Undeploy from underlying strategy
uint256 undeployedAmount = strategyUndeploy(toUndeploy);
// Validate that the undeployed amount meets slippage expectations
if (
undeployedAmount < (toUndeploy * (PERCENTAGE_PRECISION - _maxSlippage)) / PERCENTAGE_PRECISION
) {
revert SlippageExceeded();
}
// Convert the undeployed amount to the asset
uint256 calculatedAmountOut = _convertFromUnderlying(options, undeployedAmount);
// Calculate the minimum amount out based on the slippage
uint256 minAmountOut = (calculatedAmountOut * (PERCENTAGE_PRECISION - _maxSlippage)) /
PERCENTAGE_PRECISION;
(, uint256 amountOut) = swap(
ISwapHandler.SwapParams({
underlyingIn: address(outputAsset()),
underlyingOut: address(_iasset),
amountIn: undeployedAmount,
amountOut: minAmountOut,
mode: ISwapHandler.SwapType.EXACT_INPUT,
payload: ""
})
);
if (amountOut < minAmountOut) revert SlippageExceeded();
// Recalculate the total assets to ensure accurate accounting after the swap and transfer
// This accounts for slippage, fees, and any other discrepancies between expected and actual amounts
_deployedAmount = _totalAssets();
undeployedAmount_ = amountOut;
IERC20Upgradeable(_iasset).safeTransfer(msg.sender, amountOut);
emit StrategyUndeploy(msg.sender, amount);
emit StrategyAmountUpdate(_deployedAmount);
}
/**
* @notice Sets the maximum age for oracle price data
* @param maxAge The maximum age in seconds
*/
function setOracleMaxAge(uint256 maxAge) external onlyGovernor {
_oracleMaxAge = maxAge;
emit OracleMaxAgeUpdated(maxAge);
}
function setOracle(IOracle newOracle) external onlyGovernor {
_oracle = newOracle;
emit OracleUpdated(address(newOracle));
}
/**
* @notice Gets the current maximum age for oracle price data
* @return The current maximum age in seconds
*/
function oracleMaxAge() external view returns (uint256) {
return _oracleMaxAge;
}
/**
* @notice Abstract function to deploy assets to the underlying strategy
* @param amount The amount of output asset to deploy
* @return deployedAmount The amount actually deployed
*/
function strategyDeploy(uint256 amount) internal virtual returns (uint256 deployedAmount);
/**
* @notice Abstract function to undeploy assets from the underlying strategy
* @param amount The amount of output asset to undeploy
* @return undeployedAmount The amount actually undeployed
*/
function strategyUndeploy(uint256 amount) internal virtual returns (uint256 undeployedAmount);
/**
* @notice Abstract function to get total assets from the underlying strategy
* @return assets The total assets in output asset terms
*/
function strategyTotalAssets() internal view virtual returns (uint256 assets);
}
contracts/interfaces/aerodrome/ISwapRouter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Callback for ICLPoolActions#swap
/// @notice Any contract that calls ICLPoolActions#swap must implement this interface
interface ICLSwapCallback {
/// @notice Called to `msg.sender` after executing a swap via ICLPool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a CLPool deployed by the canonical CLFactory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the ICLPoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via CL
interface ISwapRouter is ICLSwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
int24 tickSpacing;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(
ExactInputSingleParams calldata params
) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(
ExactInputParams calldata params
) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
int24 tickSpacing;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(
ExactOutputSingleParams calldata params
) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(
ExactOutputParams calldata params
) external payable returns (uint256 amountIn);
}
contracts/interfaces/core/IOracle.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/**
* @title IOracle
*
* @author Chef Kenji <[email protected]>
* @author Chef Kal-EL <[email protected]>
*
* @dev Interface for an Oracle providing price information with a precision.
*/
abstract contract IOracle {
struct Price {
uint256 price;
uint256 lastUpdate;
}
struct PriceOptions {
uint256 maxAge;
uint256 maxConf;
}
error PriceOutdated();
/**
* @notice Retrieves the precision of the price information provided by the Oracle.
* @dev This function is view-only and does not modify the state of the contract.
* @return The precision of the Oracle's price information as a uint256.
*/
function getPrecision() public view virtual returns (uint256);
/**
* @notice Retrieves the latest price information from the Oracle.
* @dev This function is view-only and does not modify the state of the contract.
* @return The latest price from the Oracle as a uint256.
*/
function getLatestPrice() public view virtual returns (Price memory);
/**
* @notice Retrieves the latest price information from the Oracle and reverts whern the price
* is outdated
* @dev This function is view-only and does not modify the state of the contract.
* @return The latest price from the Oracle as a uint256.
*/
function getSafeLatestPrice(
PriceOptions memory priceOptions
) public view virtual returns (Price memory);
}
contracts/interfaces/core/IStrategy.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import { IOracle } from "./IOracle.sol";
/**
* @title Strategy Inteface to deploy and ERC-20 on an investment strategy
*
* @author Chef Kenji <[email protected]>
* @author Chef Kal-EL <[email protected]>
*
* @notice Deploys an Any Standard ERC-20 and harvests yield
*/
interface IStrategy {
/**
* @dev Emitted when a strategy is deployed.
*
* This event provides information about the address deploying the strategy and the deployed amount.
*
* @param from The address deploying the strategy.
* @param amount The amount deployed in the strategy.
*/
event StrategyDeploy(address indexed from, uint256 indexed amount);
/**
* @dev Emitted when a strategy is undeployed.
*
* This event provides information about the address undeploying the strategy and the undeployed amount.
*
* @param from The address undeploying the strategy.
* @param amount The amount undeployed from the strategy.
*/
event StrategyUndeploy(address indexed from, uint256 indexed amount);
/**
* @dev Emitted when a strategy generates a profit.
*
* This event provides information about the profit amount generated by the strategy.
*
* @param amount The profit amount generated by the strategy.
*/
event StrategyProfit(uint256 indexed amount);
/**
* @dev Emitted when a strategy incurs a loss.
*
* This event provides information about the loss amount incurred by the strategy.
*
* @param amount The loss amount incurred by the strategy.
*/
event StrategyLoss(uint256 indexed amount);
/**
* @dev Emitted when a strategy's deployed amount is updated.
*
* This event provides information about the new deployment amount of the strategy.
*
* @param newDeployment The new deployment amount of the strategy.
*/
event StrategyAmountUpdate(uint256 indexed newDeployment);
/**
* @dev Deploys funds in the AAVEv3 strategy
*
* @return deployedAmount The amount deployed in the AAVEv3 strategy after leveraging.
*
*/
function deploy(uint256 amount) external returns (uint256 deployedAmount);
/**
* @notice Harvests the strategy by yield and rebalances the strategy
*
* @return balanceChange The change in strategy balance as an int256 value.
*/
function harvest() external returns (int256 balanceChange);
/**
* @dev Initiates the undeployment process by adjusting the contract's position and performing a flash loan.
*
* @param amount The amount of ETH to undeploy.
* @return undeployedAmount The actual undeployed amount of ETH.
*/
function undeploy(uint256 amount) external returns (uint256 undeployedAmount);
/**
* @dev Retrieves the total owned assets by the Strategy in
*
* @return assets The total owned assets in the strategy.
*/
function totalAssets() external view returns (uint256 assets);
/**
* The Asset deployed on this strategy
*/
function asset() external view returns (address);
}
contracts/interfaces/core/ISwapHandler.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/**
* @title Generic Swapper Handler
*
* @author Chef Kenji <[email protected]>
* @author Chef Kal-EL <[email protected]>
*
* @dev A contract that converts one token to another
*/
abstract contract ISwapHandler {
error InvalidInputToken();
error InvalidOutputToken();
error SwapFailed();
/// @notice Params for swaps using SwapHub contract and swap handlers
/// @param underlyingIn sold token address
/// @param underlyingOut bought token address
/// @param mode type of the swap: 0 for exact input, 1 for exact output
/// @param amountIn amount of token to sell. Exact value for exact input, maximum for exact output
/// @param amountOut amount of token to buy. Exact value for exact output, minimum for exact input
/// @param payload multi-purpose byte param. The usage depends on the swap handler implementation
struct SwapParams {
address underlyingIn;
address underlyingOut;
SwapType mode;
uint256 amountIn;
uint256 amountOut;
bytes payload;
}
// @notice The type of swap
enum SwapType {
EXACT_INPUT,
EXACT_OUTPUT
}
/// @notice Execute a trade on the swap handler
/// @param params struct defining the requested trade
function swap(
SwapParams memory params
) internal virtual returns (uint256 amountIn, uint256 amountOut);
}
contracts/interfaces/curve/ICurveRouterNG.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/**
* @title ICurveRouterNG
*
* @dev Interface for the Curve Finance Router
*
* @author Chef Kenji <[email protected]>
* @author Chef Kal-El <[email protected]>
*/
interface ICurveRouterNG {
/**
* @notice Exchange Curve function
* @param route The route of the swap
* @param swapParams The swap parameters
* @param amountIn The amount of tokens to swap
* @param amountOutMin The minimum amount of tokens to receive
* @param pools The receivers of the swap
* @param receiverAddress The address of the receiver
*
* Swap parameters are defined in a multidimensional array which provides essential information about
* which tokens to swap using a specified pool.
* The array structure includes the following elements: [i, j, swap_type, pool_type, n_coins].
*
* i = index of the token to swap from
* j = index of the token to swap to
* n
*
* swap_type Description
* 1 Standard token exchange
* 2 Underlying token exchange_underlying
* 3 Underlying exchange via zap for factory stable metapools and crypto-meta pools (exchange_underlying for stable, exchange in zap for crypto)
* 4 Coin to LP token "exchange" (effectively add_liquidity)
* 5 Lending pool underlying coin to LP token "exchange" (effectively add_liquidity)
* 6 LP token to coin "exchange" (effectively remove_liquidity_one_coin)
* 7 LP token to lending or fake pool underlying coin "exchange" (effectively remove_liquidity_one_coin)
* 8 Specialized swaps like ETH <-> WETH, ETH -> stETH or frxETH, and cross-liquidity between staked tokens (e.g., stETH <-> wstETH, frxETH <-> sfrxETH)
* 9 SNX-related swaps (e.g., sUSD, sEUR, sETH, sBTC)
*
* pool_type Description
* 1 Stable pools using the Stableswap algorithm
* 2 Two-coin Crypto pools using the Cryptoswap algorithm
* 3 Tricrypto pools with three coins using the Cryptoswap algorithm
* 4 Llamma pools, typically used in crvUSD and lending markets
*
*/
function exchange(
address[11] memory route,
uint256[5][5] memory swapParams,
uint256 amountIn,
uint256 amountOutMin,
address[5] memory pools,
address receiverAddress
) external payable returns (uint256);
/**
* @notice Function to calculate the amount of final output tokens received when performing an exchange.
* @param route The route of the swap
* @param swapParams The swap parameters
* @param amount The desired amount of output tokens
* @param pools The pools to use for the swap
*/
function get_dy(
address[11] memory route,
uint256[5][5] memory swapParams,
uint256 amount,
address[5] memory pools
) external view returns (uint256);
/**
* @notice Function to calculate the amount of input tokens required to receive the desired amount of output tokens.
* @param route The route of the swap
* @param swapParams The swap parameters
* @param amountOut The desired amount of output tokens
* @param pools The pools to use for the swap
* @param basePools The base pools to use for the swap
* @param baseTokens The base tokens to use for the swap
*/
function get_dx(
address[11] memory route,
uint256[5][5] memory swapParams,
uint256 amountOut,
address[5] memory pools,
address[5] memory basePools,
address[5] memory baseTokens
) external view returns (uint256);
}
contracts/interfaces/uniswap/v2/IUniswapV2Router01.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(
uint256 amountIn,
address[] calldata path
) external view returns (uint256[] memory amounts);
function getAmountsIn(
uint256 amountOut,
address[] calldata path
) external view returns (uint256[] memory amounts);
}
contracts/interfaces/uniswap/v2/IUniswapV2Router02.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.6.2;
import { IUniswapV2Router01 } from "./IUniswapV2Router01.sol";
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
contracts/interfaces/uniswap/v3/IV3SwapRouter.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.24;
// Adapted version from
// https://github.com/Uniswap/swap-router-contracts/blob/v1.1.0/contracts/interfaces/IV3SwapRouter.sol
// Using Uniswap Router 02
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IV3SwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(
ExactInputSingleParams calldata params
) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(
ExactInputParams calldata params
) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(
ExactOutputSingleParams calldata params
) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(
ExactOutputParams calldata params
) external payable returns (uint256 amountIn);
}
contracts/libraries/AerodromeLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import { ISwapRouter } from "../interfaces/aerodrome/ISwapRouter.sol";
import { ISwapHandler } from "../interfaces/core/ISwapHandler.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title AerodromeLibrary
* @author Chef Kenji <[email protected]>
*
* @dev Library for handling Aerodrome swaps
*/
library AerodromeLibrary {
using SafeERC20 for IERC20;
error InvalidInputToken();
error InvalidOutputToken();
error SwapFailed();
error NotSupported();
error FailedToApproveAllowance();
/**
* @notice Swaps tokens using Uniswap V2
* @param router The Uniswap V2 Router address
* @param params The swap parameters
* @return amountIn The actual input amount
* @return amountOut The actual output amount
*/
function swapAerodrome(
ISwapRouter router,
ISwapHandler.SwapParams memory params
) internal returns (uint256 amountIn, uint256 amountOut) {
// Validate input token address
if (params.underlyingIn == address(0)) revert InvalidInputToken();
// Validate output token address
if (params.underlyingOut == address(0)) revert InvalidOutputToken();
int24 tickspacing = abi.decode(params.payload, (int24));
// Handle Exact Input swaps
if (params.mode == ISwapHandler.SwapType.EXACT_INPUT) {
amountIn = params.amountIn; // Set the input amount
// Execute the swap using the Uniswap V3 router
amountOut = router.exactInputSingle(
ISwapRouter.ExactInputSingleParams({
tokenIn: params.underlyingIn,
tokenOut: params.underlyingOut,
amountIn: amountIn,
amountOutMinimum: params.amountOut,
tickSpacing: tickspacing,
recipient: address(this),
deadline: block.timestamp,
sqrtPriceLimitX96: 0
})
);
// Check if the swap was successful
if (amountOut == 0) {
revert SwapFailed(); // Revert if the output amount is zero
}
// Handle Exact Output swaps
} else if (params.mode == ISwapHandler.SwapType.EXACT_OUTPUT) {
amountOut = params.amountOut; // Set the expected output amount
// Execute the swap using the Uniswap V3 router
amountIn = router.exactOutputSingle(
ISwapRouter.ExactOutputSingleParams({
tokenIn: params.underlyingIn,
tokenOut: params.underlyingOut,
tickSpacing: tickspacing,
recipient: address(this),
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: params.amountIn,
sqrtPriceLimitX96: 0
})
);
}
}
}
contracts/libraries/CurveFiLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import { ISwapHandler } from "../interfaces/core/ISwapHandler.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ICurveRouterNG } from "../interfaces/curve/ICurveRouterNG.sol";
/**
* @title CurveFiLibrary
* @dev Library for executing token swaps using Curve Finance Router NG
*
* This library provides functionality to perform both single-hop and multi-hop token swaps
* through Curve Finance's Router NG contract. It supports two swap modes:
* - EXACT_INPUT: Swap an exact amount of input tokens for a minimum amount of output tokens
* - EXACT_OUTPUT: Receive an exact amount of output tokens by providing sufficient input tokens
*
* The library handles ETH and ERC20 token swaps, with proper allowance management and
* slippage protection through tolerance mechanisms.
*
* @author Chef Kenji <[email protected]>
*/
library CurveFiLibrary {
using SafeERC20 for IERC20;
/// @dev Special address used to represent ETH in Curve Finance protocols
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Tolerance for rounding issues in EXACT_OUTPUT swaps (0.1% = 10 basis points)
/// This helps account for minor discrepancies due to blockchain state changes between
/// quote calculation and actual execution
uint256 public constant ROUNDING_TOLERANCE_BPS = 10;
/// @dev Total basis points for percentage calculations (100% = 10000 basis points)
uint256 public constant BASIS_POINTS = 10000;
/// @dev Thrown when the contract has insufficient balance for the requested operation
error InsufficientBalance();
/// @dev Thrown when an unsupported swap type is requested
error UnsupportedSwapType();
/// @dev Thrown when token allowance approval fails
error FailedToApproveAllowance();
/// @dev Thrown when route length is invalid
error InvalidRouteLength();
/// @dev Thrown when pools length is invalid
error InvalidPoolsLength();
/**
* @notice Encodes a 5x5 swapParams matrix into a single uint256 for gas optimization
* @dev Each parameter is stored as uint8 (8 bits), so 5 params per row = 40 bits
* 5 rows = 200 bits, which fits comfortably in a uint256
*
* @param swapParams The 5x5 matrix of swap parameters
* @return encoded The encoded uint256 containing all swap parameters
*/
function encodeSwapParams(uint256[5][5] memory swapParams) internal pure returns (uint256 encoded) {
for (uint256 i = 0; i < 5; i++) {
for (uint256 j = 0; j < 5; j++) {
// Each parameter is 8 bits, so we shift by 8 * (i * 5 + j) bits
// This packs them sequentially: row0[0-4], row1[0-4], ..., row4[0-4]
encoded |= (swapParams[i][j] & 0xFF) << (8 * (i * 5 + j));
}
}
}
/**
* @notice Decodes a single uint256 back into a 5x5 swapParams matrix
* @dev Extracts each uint8 parameter from the packed uint256
*
* @param encoded The encoded uint256 containing all swap parameters
* @return swapParams The decoded 5x5 matrix of swap parameters
*/
function decodeSwapParams(uint256 encoded) internal pure returns (uint256[5][5] memory swapParams) {
for (uint256 i = 0; i < 5; i++) {
for (uint256 j = 0; j < 5; j++) {
// Extract each 8-bit parameter from the packed uint256
swapParams[i][j] = (encoded >> (8 * (i * 5 + j))) & 0xFF;
}
}
}
/**
* @notice Optimized encoding for variable-length routes and pools
* @dev This function creates a more compact payload by only encoding the used route and pool slots
* Format: (uint8 routeLength, uint8 poolsLength, address[] route, uint256 encodedSwapParams, address[] pools)
*
* @param route Array of addresses representing the swap route (only used slots)
* @param swapParams 2D array containing parameters for each swap hop
* @param pools Array of pool addresses for each hop (only used slots)
* @return encodedPayload The optimized encoded payload
*/
function encodeOptimizedPayload(
address[] memory route,
uint256[5][5] memory swapParams,
address[] memory pools
) internal pure returns (bytes memory encodedPayload) {
if (route.length == 0 || route.length > 11) revert InvalidRouteLength();
if (pools.length == 0 || pools.length > 5) revert InvalidPoolsLength();
if (pools.length * 2 + 1 != route.length) revert InvalidRouteLength(); // route should be token->pool->token->pool->...
uint256 encodedSwapParams = encodeSwapParams(swapParams);
return abi.encode(
uint8(route.length),
uint8(pools.length),
route,
encodedSwapParams,
pools
);
}
/**
* @notice Decodes an optimized payload back into route, swapParams, and pools
* @dev This function decodes the compact payload format
*
* @param payload The optimized encoded payload
* @return route Array of addresses representing the swap route
* @return swapParams The decoded 5x5 matrix of swap parameters
* @return pools Array of pool addresses for each hop
*/
function decodeOptimizedPayload(
bytes memory payload
) internal pure returns (
address[] memory route,
uint256[5][5] memory swapParams,
address[] memory pools
) {
(
uint8 routeLength,
uint8 poolsLength,
address[] memory decodedRoute,
uint256 encodedSwapParams,
address[] memory decodedPools
) = abi.decode(payload, (uint8, uint8, address[], uint256, address[]));
route = decodedRoute;
swapParams = decodeSwapParams(encodedSwapParams);
pools = decodedPools;
}
/**
* @notice Converts a compact route to the full 11-slot format required by Curve Router
* @dev Pads the route with address(0) to fill all 11 slots
*
* @param compactRoute The compact route array
* @return fullRoute The full 11-slot route array
*/
function expandRoute(address[] memory compactRoute) internal pure returns (address[11] memory fullRoute) {
for (uint256 i = 0; i < compactRoute.length && i < 11; i++) {
fullRoute[i] = compactRoute[i];
}
// Remaining slots are already address(0) by default
}
/**
* @notice Converts a compact pools array to the full 5-slot format required by Curve Router
* @dev Pads the pools with address(0) to fill all 5 slots
*
* @param compactPools The compact pools array
* @return fullPools The full 5-slot pools array
*/
function expandPools(address[] memory compactPools) internal pure returns (address[5] memory fullPools) {
for (uint256 i = 0; i < compactPools.length && i < 5; i++) {
fullPools[i] = compactPools[i];
}
// Remaining slots are already address(0) by default
}
/**
* @notice Executes a token swap using the Curve Router NG (Optimized format)
* @dev This is the main entry point for Curve Finance swaps using optimized encoding
*
* @param router The Curve Router NG contract instance
* @param params Swap parameters containing:
* - underlyingIn: Address of input token (use ETH_ADDRESS for ETH)
* - underlyingOut: Address of output token (use ETH_ADDRESS for ETH)
* - mode: Swap type (EXACT_INPUT or EXACT_OUTPUT)
* - amountIn: Amount of input tokens (for EXACT_INPUT) or max input (for EXACT_OUTPUT)
* - amountOut: Minimum output (for EXACT_INPUT) or exact output (for EXACT_OUTPUT)
* - payload: ABI-encoded (uint8 routeLength, uint8 poolsLength, address[] route, uint256 encodedSwapParams, address[] pools)
*
* @return amountIn The actual amount of input tokens used in the swap
* @return amountOut The actual amount of output tokens received from the swap
*/
function swapCurveFi(
ICurveRouterNG router,
ISwapHandler.SwapParams memory params
) internal returns (uint256 amountIn, uint256 amountOut) {
if (params.underlyingIn == address(0)) revert ISwapHandler.InvalidInputToken();
if (params.underlyingOut == address(0)) revert ISwapHandler.InvalidOutputToken();
// Decode the optimized payload
(
address[] memory compactRoute,
uint256[5][5] memory swapParams,
address[] memory compactPools
) = decodeOptimizedPayload(params.payload);
// Expand to full format required by Curve Router
address[11] memory route = expandRoute(compactRoute);
address[5] memory pools = expandPools(compactPools);
return _executeCurveFiSwap(router, route, swapParams, pools, params);
}
/**
* @notice Internal function that executes the actual Curve Finance swap
* @dev This function handles both EXACT_INPUT and EXACT_OUTPUT swap modes with proper
* allowance management, slippage protection, and error handling.
*
* For EXACT_INPUT swaps:
* - Uses the specified input amount
* - Ensures output meets minimum requirements
* - Reverts if slippage is too high
*
* For EXACT_OUTPUT swaps:
* - Calculates required input amount using get_dx
* - Applies tolerance for rounding issues
* - Ensures sufficient input tokens are available
*
* @param router The Curve Router NG contract instance
* @param route Array of addresses representing the swap route (max 11 addresses)
* Format: [token0, pool0, token1, pool1, token2, ...]
* @param swapParams 2D array containing parameters for each swap hop (max 5 hops)
* Each row: [i, j, swap_type, pool_type, n_coins] where:
* - i: Input token index in the pool
* - j: Output token index in the pool
* - swap_type: Type of swap (1 for standard)
* - pool_type: Pool implementation type
* - n_coins: Number of coins in the pool
* @param pools Array of pool addresses for each hop (max 5 pools)
* @param params The original swap parameters from the caller
*
* @return amountIn The actual amount of input tokens used in the swap
* @return amountOut The actual amount of output tokens received from the swap
*
* @custom:security This function includes several safety checks:
* - Validates input/output amounts against limits
* - Applies rounding tolerance for EXACT_OUTPUT swaps
* - Properly manages token allowances
* - Handles both ETH and ERC20 tokens
*/
function _executeCurveFiSwap(
ICurveRouterNG router,
address[11] memory route,
uint256[5][5] memory swapParams,
address[5] memory pools,
ISwapHandler.SwapParams memory params
) internal returns (uint256 amountIn, uint256 amountOut) {
// Handle EXACT_INPUT swap mode
if (params.mode == ISwapHandler.SwapType.EXACT_INPUT) {
// Determine the amount of input tokens (ETH uses msg.value, ERC20 uses params.amountIn)
amountIn = params.underlyingIn == ETH_ADDRESS ? msg.value : params.amountIn;
// Approve the input token for the Curve Router (skip for ETH)
if (params.underlyingIn != ETH_ADDRESS) {
// Reset allowance to 0 first, then set to required amount
// This prevents issues with tokens that require 0 allowance before setting new value
IERC20(params.underlyingIn).forceApprove(address(router), amountIn);
}
// Execute the swap using the Curve Router
// For ETH swaps, send ETH value; for ERC20 swaps, value is 0
uint256 ethValue = params.underlyingIn == ETH_ADDRESS ? amountIn : 0;
amountOut = router.exchange{ value: ethValue }(
route,
swapParams,
amountIn,
params.amountOut, // Minimum output amount
pools,
address(this)
);
// Verify that we received at least the minimum expected output
if (amountOut < params.amountOut) {
revert ISwapHandler.SwapFailed(); // Revert if the swap failed
}
// Handle EXACT_OUTPUT swap mode
} else if (params.mode == ISwapHandler.SwapType.EXACT_OUTPUT) {
// Declare arrays for base pools and tokens (required by get_dx function)
address[5] memory basePools;
address[5] memory baseTokens;
// Calculate the required input amount for the desired output using Curve's get_dx function
// This queries the current state to determine how much input is needed
amountIn = router.get_dx(route, swapParams, params.amountOut, pools, basePools, baseTokens);
// Verify that we have sufficient input tokens available
if (
(params.underlyingIn == ETH_ADDRESS && amountIn > msg.value) ||
(params.underlyingIn != ETH_ADDRESS && amountIn > params.amountIn)
) {
revert ISwapHandler.SwapFailed(); // Revert if insufficient input amount
}
// Approve the input token for the Curve Router (skip for ETH)
if (params.underlyingIn != ETH_ADDRESS) {
IERC20(params.underlyingIn).forceApprove(address(router), amountIn);
}
// Execute the swap using the Curve Router
// Note: For EXACT_OUTPUT, we use msg.value for ETH (which should cover amountIn)
// and set minimum output to 0 since we're targeting exact output
amountOut = router.exchange{ value: msg.value }(
route,
swapParams,
amountIn,
0, // No minimum since we're doing exact output
pools,
address(this)
);
// Apply tolerance for rounding issues in EXACT_OUTPUT swaps
// Blockchain state can change between get_dx call and actual execution
uint256 tolerance = (params.amountOut * ROUNDING_TOLERANCE_BPS) / BASIS_POINTS;
uint256 minAcceptableAmount = params.amountOut > tolerance ? params.amountOut - tolerance : 0;
// Verify that the output amount is within acceptable tolerance
if (amountOut < minAcceptableAmount) {
revert ISwapHandler.SwapFailed(); // Revert if the swap failed beyond tolerance
}
} else {
// Unsupported swap mode
revert UnsupportedSwapType(); // Revert if the swap type is unsupported
}
}
}
contracts/libraries/MathLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/**
* @title MathLibrary
* @author Chef Kenji <[email protected]>
* @dev Library for handling mathematical operations
*/
library MathLibrary {
error InvalidDivDenominator();
error OverflowDetected();
uint256 private constant MAX_DIFFERENCE_DECIMALS = 64;
/**
* @notice Converts a value from one decimal precision to another.
* @dev This function converts a `value` from a `from` decimal precision to a `to` decimal precision.
* It checks for overflow and reverts if the conversion would cause an overflow.
* @param value The numerical value to convert.
* @param from The current decimal precision of the `value`.
* @param to The target decimal precision to convert to.
* @return converted The value converted to the target decimal precision.
* @custom:throws OverflowDetected if the difference between `from` and `to` is greater than or equal to `MAX_DIFFERENCE_DECIMALS`.
* @custom:throws OverflowDetected if the multiplication required to increase precision would cause an overflow.
*/
function toDecimals(
uint256 value,
uint8 from,
uint8 to
) internal pure returns (uint256 converted) {
if (from > to) {
if (from - to >= MAX_DIFFERENCE_DECIMALS) revert OverflowDetected();
converted = value / (10 ** (from - to));
} else if (to > from) {
if (to - from >= MAX_DIFFERENCE_DECIMALS) revert OverflowDetected();
uint256 factor = 10 ** (to - from);
if (value > type(uint256).max / factor) revert OverflowDetected();
converted = value * factor;
} else {
converted = value;
}
}
/**
* @dev Multiplies two unsigned integers `x` and `y`, then divides the result by `denominator`
* and returns the result either rounded up or down based on the `roundUp` flag.
*
* @notice This function provides an option to round the division result up or down.
* If `roundUp` is true, the function rounds up using the `mulDivUp` function;
* otherwise, it rounds down using the `mulDivDown` function.
* If `denominator` is zero, the function reverts with an `InvalidDivDenominator` error.
*
* @param x The first multiplicand as an unsigned integer.
* @param y The second multiplicand as an unsigned integer.
* @param denominator The divisor as an unsigned integer. Must not be zero.
* @param roundUp A boolean flag indicating whether to round up or down.
*
* @return The result of the multiplication and division, rounded up or down based on `roundUp`.
*
* @custom:error InvalidDivDenominator Thrown if `denominator` is zero.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
bool roundUp
) internal pure returns (uint256) {
return roundUp ? mulDivUp(x, y, denominator) : mulDivDown(x, y, denominator);
}
/**
* @dev Multiplies two unsigned integers `x` and `y`, then divides the result by `denominator`
* and rounds the result up towards the next integer.
*
* @notice This function performs multiplication followed by division and rounds the result up towards
* the next integer. If either `x` or `y` is zero, the function returns 0.
* If `denominator` is zero, the function reverts with an `InvalidDivDenominator` error.
*
* @param x The first multiplicand as an unsigned integer.
* @param y The second multiplicand as an unsigned integer.
* @param denominator The divisor as an unsigned integer. Must not be zero.
*
* @return The result of the multiplication and division, rounded up towards the next integer.
*
* @custom:error InvalidDivDenominator Thrown if `denominator` is zero.
*/
function mulDivUp(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256) {
uint256 product = x * y;
// Not Allowed Division by 0
if (denominator == 0) revert InvalidDivDenominator();
if (x == 0 || y == 0) {
return 0;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return 1 + (product - 1) / denominator;
}
}
/**
* @dev Multiplies two unsigned integers `x` and `y`, then divides the result by `denominator` with truncation towards zero.
* The function returns the result of the division.
*
* @notice This function performs multiplication followed by division. It truncates the result towards zero.
* If either `x` or `y` is zero, the function returns 0.
* If `denominator` is zero, the function reverts with an `InvalidDivDenominator` error.
*
* @param x The first multiplicand as an unsigned integer.
* @param y The second multiplicand as an unsigned integer.
* @param denominator The divisor as an unsigned integer. Must not be zero.
*
* @return The result of `(x * y) / denominator`, truncated towards zero.
*
* @custom:error InvalidDivDenominator Thrown if `denominator` is zero.
*/
function mulDivDown(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256) {
uint256 product = x * y;
// Not Allowed: Division by 0
if (denominator == 0) revert InvalidDivDenominator();
if (x == 0 || y == 0) {
return 0;
} else {
// Division down simply divides the product by the denominator
// and truncates towards zero (which is the default behavior of division in Solidity).
return product / denominator;
}
}
}
contracts/libraries/SwapLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import { CurveFiLibrary } from "./CurveFiLibrary.sol";
import { UniV4Library } from "./UniV4Library.sol";
import { UniV2Library } from "./UniV2Library.sol";
import { UniV3Library } from "./UniV3Library.sol";
import { AerodromeLibrary } from "./AerodromeLibrary.sol";
import { ISwapHandler } from "../interfaces/core/ISwapHandler.sol";
import { IV3SwapRouter } from "../interfaces/uniswap/v3/IV3SwapRouter.sol";
import { IUniswapV2Router02 } from "../interfaces/uniswap/v2/IUniswapV2Router02.sol";
import { ISwapRouter } from "../interfaces/aerodrome/ISwapRouter.sol";
import { IUniversalRouter } from "@uniswap/universal-router/contracts/interfaces/IUniversalRouter.sol";
import { ICurveRouterNG } from "../interfaces/curve/ICurveRouterNG.sol";
library SwapLibrary {
error InvalidProvider();
/**
* @notice The provider of the swap
*/
enum SwapProvider {
NONE,
UNIV3,
UNIV2,
AERODROME,
UNIV4,
CURVE
}
/**
* @notice The information about a route
*/
struct RouteInfo {
SwapProvider provider; // 1byte one, UniswapV3, UniswapV2, Aerodrome
address router; // Protocol Router
bytes customData;
}
/**
* @notice The swap function is responsible for executing token swaps based on the authorized routes.
* It retrieves the route information, checks if the route is authorized, and then determines
* the appropriate swap pro
* -+
* vider to execute the swap. The function handles swaps for Uniswap V2,
* Uniswap V3, and Curve, encoding the necessary parameters for the Curve swap.
*/
function swap(
RouteInfo memory routeInfo,
ISwapHandler.SwapParams memory params
) public returns (uint256 amountIn, uint256 amountOut) {
// Check if the route is authorized; if not, revert the transaction with an error
if (routeInfo.provider == SwapProvider.NONE) revert InvalidProvider();
// Determine the swap provider based on the route information
if (routeInfo.provider == SwapProvider.UNIV3) {
// If the provider is Uniswap V3, set the fee tier for the swap parameters
params.payload = routeInfo.customData;
// Execute the swap using the Uniswap V3 swapper and return the result
return UniV3Library.swapUniV3(IV3SwapRouter(routeInfo.router), params);
} else if (routeInfo.provider == SwapProvider.UNIV2) {
// If the provider is Uniswap V2, execute the swap using the Uniswap V2 swapper and return the result
return UniV2Library.swapUniV2(IUniswapV2Router02(routeInfo.router), params);
} else if (routeInfo.provider == SwapProvider.AERODROME) {
params.payload = routeInfo.customData;
return AerodromeLibrary.swapAerodrome(ISwapRouter(routeInfo.router), params);
} else if (routeInfo.provider == SwapProvider.UNIV4) {
params.payload = routeInfo.customData;
return UniV4Library.swapUniV4(IUniversalRouter(routeInfo.router), params);
} else if (routeInfo.provider == SwapProvider.CURVE) {
params.payload = routeInfo.customData;
return CurveFiLibrary.swapCurveFi(ICurveRouterNG(routeInfo.router), params);
} else {
revert InvalidProvider();
}
}
}
contracts/libraries/UniV2Library.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import { IUniswapV2Router02 } from "../interfaces/uniswap/v2/IUniswapV2Router02.sol";
import { ISwapHandler } from "../interfaces/core/ISwapHandler.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title UniV2Library
* @author Chef Kenji <[email protected]>
* @dev Library for handling Uniswap V2 swaps
*/
library UniV2Library {
using SafeERC20 for IERC20;
error InvalidInputToken();
error InvalidOutputToken();
error SwapFailed();
error FailedToApproveAllowance();
/**
* @notice Swaps tokens using Uniswap V2
* @param router The Uniswap V2 Router address
* @param params The swap parameters
* @return amountIn The actual input amount
* @return amountOut The actual output amount
*/
function swapUniV2(
IUniswapV2Router02 router,
ISwapHandler.SwapParams memory params
) internal returns (uint256 amountIn, uint256 amountOut) {
// Check if the input token address is valid
if (params.underlyingIn == address(0)) revert InvalidInputToken();
// Check if the output token address is valid
if (params.underlyingOut == address(0)) revert InvalidOutputToken();
// Create an array to hold the path for the Uniswap V2 swap
address[] memory path = new address[](2);
path[0] = params.underlyingIn; // Set the first element of the path to the input token
path[1] = params.underlyingOut; // Set the second element of the path to the output token
// Approve the router to spend the input token
IERC20(params.underlyingIn).approve(address(router), params.amountIn);
// Handle the case for Exact Input swaps
if (params.mode == ISwapHandler.SwapType.EXACT_INPUT) {
// Allow the Uniswap router to spend the specified amount of the input token
if (!IERC20(params.underlyingIn).approve(address(router), params.amountIn)) {
revert FailedToApproveAllowance();
}
// Determine the minimum amount of output tokens to receive
uint256 amountOutMin = 0;
if (params.amountOut > 0) {
amountOutMin = params.amountOut; // Use the specified minimum amount if provided
} else {
// Calculate the expected output amount based on the input amount
uint256[] memory amountsOut = router.getAmountsOut(params.amountIn, path);
amountOutMin = amountsOut[amountsOut.length - 1]; // Get the last amount in the array as the minimum output
}
// Execute the swap on Uniswap V2
amountIn = params.amountIn; // Set the amountIn to the input amount
uint256[] memory amounts = router.swapExactTokensForTokens(
amountIn,
amountOutMin,
path,
address(this), // Send the output tokens to this contract
block.timestamp // Set the deadline for the swap to the current block timestamp
);
amountOut = amounts[amounts.length - 1]; // Get the actual output amount from the swap
// Handle the case for Exact Output swaps
} else if (params.mode == ISwapHandler.SwapType.EXACT_OUTPUT) {
amountOut = params.amountOut; // Set the expected output amount
uint256 amountInMax = 0; // Initialize the maximum input amount
// If no input amount is specified, calculate the required input amount for the desired output
if (params.amountIn == 0) {
uint256[] memory amountsIn = router.getAmountsIn(amountOut, path);
amountInMax = amountsIn[0]; // Get the required input amount from the calculation
} else {
amountInMax = params.amountIn; // Use the specified maximum input amount
}
// Allow the Uniswap router to spend the maximum input amount
if (!IERC20(params.underlyingIn).approve(address(router), amountInMax)) {
revert FailedToApproveAllowance();
}
// Execute the swap on Uniswap V2 for exact output
uint256[] memory amounts = router.swapTokensForExactTokens(
amountOut,
amountInMax,
path,
address(this), // Send the output tokens to this contract
block.timestamp // Set the deadline for the swap to the current block timestamp
);
amountIn = amounts[0]; // Get the actual input amount used in the swap
}
// If the output amount is zero, the swap has failed
if (amountOut == 0) {
revert SwapFailed(); // Revert the transaction with a failure error
}
}
}
contracts/libraries/UniV3Library.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import { IV3SwapRouter } from "../interfaces/uniswap/v3/IV3SwapRouter.sol";
import { ISwapHandler } from "../interfaces/core/ISwapHandler.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title UniV3Library
* @author Chef Kenji <[email protected]>
* @dev Library for handling Uniswap V3 swaps
*/
library UniV3Library {
using SafeERC20 for IERC20;
error InvalidInputToken();
error InvalidOutputToken();
error InvalidFeeTier();
error SwapFailed();
error FailedToApproveAllowance();
/**
* @notice Swaps tokens using Uniswap V3
* @param router The Uniswap V3 Router address
* @param params The swap parameters
* @return amountIn The actual input amount
* @return amountOut The actual output amount
*/
function swapUniV3(
IV3SwapRouter router,
ISwapHandler.SwapParams memory params
) internal returns (uint256 amountIn, uint256 amountOut) {
// Validate input token address
if (params.underlyingIn == address(0)) revert InvalidInputToken();
// Validate output token address
if (params.underlyingOut == address(0)) revert InvalidOutputToken();
// Validate fee tier
uint24 fee = abi.decode(params.payload, (uint24));
if (fee == 0) revert InvalidFeeTier();
// Approve the router to spend the input token
if (!IERC20(params.underlyingIn).approve(address(router), params.amountIn)) {
revert FailedToApproveAllowance();
}
// Handle Exact Input swaps
if (params.mode == ISwapHandler.SwapType.EXACT_INPUT) {
amountIn = params.amountIn; // Set the input amount
// Execute the swap using the Uniswap V3 router
amountOut = router.exactInputSingle(
IV3SwapRouter.ExactInputSingleParams({
tokenIn: params.underlyingIn,
tokenOut: params.underlyingOut,
amountIn: amountIn,
amountOutMinimum: params.amountOut,
fee: fee,
recipient: address(this),
sqrtPriceLimitX96: 0
})
);
// Check if the swap was successful
if (amountOut == 0) {
revert SwapFailed(); // Revert if the output amount is zero
}
// Handle Exact Output swaps
} else if (params.mode == ISwapHandler.SwapType.EXACT_OUTPUT) {
amountOut = params.amountOut; // Set the expected output amount
// Execute the swap using the Uniswap V3 router
amountIn = router.exactOutputSingle(
IV3SwapRouter.ExactOutputSingleParams({
tokenIn: params.underlyingIn,
tokenOut: params.underlyingOut,
fee: fee,
recipient: address(this),
amountOut: amountOut,
amountInMaximum: params.amountIn,
sqrtPriceLimitX96: 0
})
);
}
}
}
contracts/libraries/UniV4Library.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import { ISwapHandler } from "../interfaces/core/ISwapHandler.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { IHooks } from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import { Currency } from "@uniswap/v4-core/src/types/Currency.sol";
import { IUniversalRouter } from "@uniswap/universal-router/contracts/interfaces/IUniversalRouter.sol";
import { IV4Router } from "@uniswap/v4-periphery/src/interfaces/IV4Router.sol";
import { Actions } from "@uniswap/v4-periphery/src/libraries/Actions.sol";
import { Commands } from "@uniswap/universal-router/contracts/libraries/Commands.sol";
import { IPermit2 } from "@uniswap/permit2/src/interfaces/IPermit2.sol";
/**
* @title UniV4Library
* @author Chef Kenji <[email protected]>
* @dev Library for handling Uniswap V4 swaps
*/
library UniV4Library {
using SafeERC20 for IERC20;
error InvalidInputToken();
error InvalidOutputToken();
error InvalidFeeTier();
error SwapFailed();
error InvalidSwapType();
error InvalidTickSpacing();
function _prepareSwap(
IUniversalRouter router,
address permit2,
PoolKey memory poolKey,
ISwapHandler.SwapParams memory params
) internal returns (bytes memory commands, bytes[] memory inputs) {
// Step 5: Prepare the Universal Router command sequence
// Encode the sequence of actions to perform
uint256 swapAction;
commands = abi.encodePacked(uint8(Commands.V4_SWAP));
inputs = new bytes[](1);
bytes[] memory inputParams = new bytes[](3);
// Determine swap direction based on token addresses
bool zeroForOne = params.underlyingIn < params.underlyingOut;
if (params.mode == ISwapHandler.SwapType.EXACT_INPUT) {
swapAction = Actions.SWAP_EXACT_IN_SINGLE;
inputParams[0] = abi.encode(
IV4Router.ExactInputSingleParams({
poolKey: poolKey,
zeroForOne: zeroForOne,
amountIn: uint128(params.amountIn),
amountOutMinimum: uint128(params.amountOut),
hookData: bytes("")
})
);
} else if (params.mode == ISwapHandler.SwapType.EXACT_OUTPUT) {
swapAction = Actions.SWAP_EXACT_OUT_SINGLE;
inputParams[0] = abi.encode(
IV4Router.ExactOutputSingleParams({
poolKey: poolKey,
zeroForOne: zeroForOne,
amountOut: uint128(params.amountOut),
amountInMaximum: uint128(params.amountIn),
hookData: bytes("")
})
);
}
// Approve the input token for the permit2 contract
IPermit2(permit2).approve(
params.underlyingIn,
address(router),
uint160(params.amountIn),
uint48(block.timestamp + 90)
);
bytes memory actions = abi.encodePacked(
uint8(swapAction),
uint8(Actions.SETTLE_ALL),
uint8(Actions.TAKE_ALL)
);
// Parameters for SETTLE_ALL action - specify which token to settle and how much
inputParams[1] = abi.encode(Currency.wrap(params.underlyingIn), params.amountIn);
// Parameters for TAKE_ALL action - specify which token to take and minimum amount
inputParams[2] = abi.encode(Currency.wrap(params.underlyingOut), params.amountOut);
// Step 7: Combine actions and parameters into router inputs
inputs[0] = abi.encode(actions, inputParams);
}
function _preparePoolKey(
ISwapHandler.SwapParams memory params,
uint24 fee,
int24 tickSpacing
) internal pure returns (PoolKey memory key) {
// Step 2: Determine the pool currencies in the correct order
// Uniswap V4 requires currencies to be sorted (lower address first)
Currency currency0 = params.underlyingOut > params.underlyingIn
? Currency.wrap(params.underlyingIn)
: Currency.wrap(params.underlyingOut);
Currency currency1 = params.underlyingOut > params.underlyingIn
? Currency.wrap(params.underlyingOut)
: Currency.wrap(params.underlyingIn);
// Step 3: Create the pool key for the token pair
key = PoolKey({
currency0: currency0,
currency1: currency1,
fee: fee,
tickSpacing: tickSpacing,
hooks: IHooks(address(0)) // No hooks for basic swaps
});
}
/**
* @notice Swaps tokens using Uniswap V4
* @param router The Universal Router address
* @param params The swap parameters
* @return amountIn The actual input amount
* @return amountOut The actual output amount
*/
function swapUniV4(
IUniversalRouter router,
ISwapHandler.SwapParams memory params
) internal returns (uint256 amountIn, uint256 amountOut) {
// Ensure the input token address is valid
if (params.underlyingIn == address(0)) revert InvalidInputToken();
// Ensure the output token address is valid
if (params.underlyingOut == address(0)) revert InvalidOutputToken();
// Extract fee and tickSpacing from the payload and validate
(uint24 fee, int24 tickSpacing, address permit2) = abi.decode(
params.payload,
(uint24, int24, address)
);
// Validate fee tier
if (fee == 0) revert InvalidFeeTier();
// Validate tick spacing
if (tickSpacing == 0) revert InvalidTickSpacing();
// Step 4: Set up swap parameters based on swap type
(bytes memory commands, bytes[] memory inputs) = _prepareSwap(
router,
permit2,
_preparePoolKey(params, fee, tickSpacing),
params
);
// Record balance before swap for comparison
uint256 balanceBeforeInput = IERC20(params.underlyingIn).balanceOf(address(this));
uint256 balanceBeforeOutput = IERC20(params.underlyingOut).balanceOf(address(this));
// Execute the swap through the Universal Router
router.execute(commands, inputs, block.timestamp + 60);
// Record balance after swap
uint256 balanceAfterInput = IERC20(params.underlyingIn).balanceOf(address(this));
uint256 balanceAfterOutput = IERC20(params.underlyingOut).balanceOf(address(this));
// Update the effective amount in and amount out
amountOut = balanceAfterOutput - balanceBeforeOutput;
amountIn = balanceBeforeInput - balanceAfterInput;
}
}
lib/permit2/src/interfaces/IAllowanceTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IEIP712} from "./IEIP712.sol";
/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
/// @notice Thrown when an allowance on a token has expired.
/// @param deadline The timestamp at which the allowed amount is no longer valid
error AllowanceExpired(uint256 deadline);
/// @notice Thrown when an allowance on a token has been depleted.
/// @param amount The maximum amount allowed
error InsufficientAllowance(uint256 amount);
/// @notice Thrown when too many nonces are invalidated.
error ExcessiveInvalidation();
/// @notice Emits an event when the owner successfully invalidates an ordered nonce.
event NonceInvalidation(
address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
);
/// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
event Approval(
address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
);
/// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
event Permit(
address indexed owner,
address indexed token,
address indexed spender,
uint160 amount,
uint48 expiration,
uint48 nonce
);
/// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
event Lockdown(address indexed owner, address token, address spender);
/// @notice The permit data for a token
struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice The permit message signed for a single token allowance
struct PermitSingle {
// the permit data for a single token alownce
PermitDetails details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The permit message signed for multiple token allowances
struct PermitBatch {
// the permit data for multiple token allowances
PermitDetails[] details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The saved permissions
/// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
/// @dev Setting amount to type(uint160).max sets an unlimited approval
struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice A token spender pair.
struct TokenSpenderPair {
// the token the spender is approved
address token;
// the spender address
address spender;
}
/// @notice Details for a token transfer.
struct AllowanceTransferDetails {
// the owner of the token
address from;
// the recipient of the token
address to;
// the amount of the token
uint160 amount;
// the token to be transferred
address token;
}
/// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
/// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
/// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
function allowance(address user, address token, address spender)
external
view
returns (uint160 amount, uint48 expiration, uint48 nonce);
/// @notice Approves the spender to use up to amount of the specified token up until the expiration
/// @param token The token to approve
/// @param spender The spender address to approve
/// @param amount The approved amount of the token
/// @param expiration The timestamp at which the approval is no longer valid
/// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
/// @dev Setting amount to type(uint160).max sets an unlimited approval
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
/// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitSingle Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;
/// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitBatch Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;
/// @notice Transfer approved tokens from one address to another
/// @param from The address to transfer from
/// @param to The address of the recipient
/// @param amount The amount of the token to transfer
/// @param token The token address to transfer
/// @dev Requires the from address to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(address from, address to, uint160 amount, address token) external;
/// @notice Transfer approved tokens in a batch
/// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
/// @dev Requires the from addresses to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;
/// @notice Enables performing a "lockdown" of the sender's Permit2 identity
/// by batch revoking approvals
/// @param approvals Array of approvals to revoke.
function lockdown(TokenSpenderPair[] calldata approvals) external;
/// @notice Invalidate nonces for a given (token, spender) pair
/// @param token The token to invalidate nonces for
/// @param spender The spender to invalidate nonces for
/// @param newNonce The new nonce to set. Invalidates all nonces less than it.
/// @dev Can't invalidate more than 2**16 nonces per transaction.
function invalidateNonces(address token, address spender, uint48 newNonce) external;
}
lib/permit2/src/interfaces/IEIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IEIP712 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/permit2/src/interfaces/IPermit2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ISignatureTransfer} from "./ISignatureTransfer.sol";
import {IAllowanceTransfer} from "./IAllowanceTransfer.sol";
/// @notice Permit2 handles signature-based transfers in SignatureTransfer and allowance-based transfers in AllowanceTransfer.
/// @dev Users must approve Permit2 before calling any of the transfer functions.
interface IPermit2 is ISignatureTransfer, IAllowanceTransfer {
// IPermit2 unifies the two interfaces so users have maximal flexibility with their approval.
}
lib/permit2/src/interfaces/ISignatureTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IEIP712} from "./IEIP712.sol";
/// @title SignatureTransfer
/// @notice Handles ERC20 token transfers through signature based actions
/// @dev Requires user's token approval on the Permit2 contract
interface ISignatureTransfer is IEIP712 {
/// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount
/// @param maxAmount The maximum amount a spender can request to transfer
error InvalidAmount(uint256 maxAmount);
/// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred
/// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred
error LengthMismatch();
/// @notice Emits an event when the owner successfully invalidates an unordered nonce.
event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask);
/// @notice The token and amount details for a transfer signed in the permit transfer signature
struct TokenPermissions {
// ERC20 token address
address token;
// the maximum amount that can be spent
uint256 amount;
}
/// @notice The signed permit message for a single token transfer
struct PermitTransferFrom {
TokenPermissions permitted;
// a unique value for every token owner's signature to prevent signature replays
uint256 nonce;
// deadline on the permit signature
uint256 deadline;
}
/// @notice Specifies the recipient address and amount for batched transfers.
/// @dev Recipients and amounts correspond to the index of the signed token permissions array.
/// @dev Reverts if the requested amount is greater than the permitted signed amount.
struct SignatureTransferDetails {
// recipient address
address to;
// spender requested amount
uint256 requestedAmount;
}
/// @notice Used to reconstruct the signed permit message for multiple token transfers
/// @dev Do not need to pass in spender address as it is required that it is msg.sender
/// @dev Note that a user still signs over a spender address
struct PermitBatchTransferFrom {
// the tokens and corresponding amounts permitted for a transfer
TokenPermissions[] permitted;
// a unique value for every token owner's signature to prevent signature replays
uint256 nonce;
// deadline on the permit signature
uint256 deadline;
}
/// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection
/// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order
/// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce
/// @dev It returns a uint256 bitmap
/// @dev The index, or wordPosition is capped at type(uint248).max
function nonceBitmap(address, uint256) external view returns (uint256);
/// @notice Transfers a token using a signed permit message
/// @dev Reverts if the requested amount is greater than the permitted signed amount
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails The spender's requested transfer details for the permitted token
/// @param signature The signature to verify
function permitTransferFrom(
PermitTransferFrom memory permit,
SignatureTransferDetails calldata transferDetails,
address owner,
bytes calldata signature
) external;
/// @notice Transfers a token using a signed permit message
/// @notice Includes extra data provided by the caller to verify signature over
/// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
/// @dev Reverts if the requested amount is greater than the permitted signed amount
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails The spender's requested transfer details for the permitted token
/// @param witness Extra data to include when checking the user signature
/// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
/// @param signature The signature to verify
function permitWitnessTransferFrom(
PermitTransferFrom memory permit,
SignatureTransferDetails calldata transferDetails,
address owner,
bytes32 witness,
string calldata witnessTypeString,
bytes calldata signature
) external;
/// @notice Transfers multiple tokens using a signed permit message
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails Specifies the recipient and requested amount for the token transfer
/// @param signature The signature to verify
function permitTransferFrom(
PermitBatchTransferFrom memory permit,
SignatureTransferDetails[] calldata transferDetails,
address owner,
bytes calldata signature
) external;
/// @notice Transfers multiple tokens using a signed permit message
/// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
/// @notice Includes extra data provided by the caller to verify signature over
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails Specifies the recipient and requested amount for the token transfer
/// @param witness Extra data to include when checking the user signature
/// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
/// @param signature The signature to verify
function permitWitnessTransferFrom(
PermitBatchTransferFrom memory permit,
SignatureTransferDetails[] calldata transferDetails,
address owner,
bytes32 witness,
string calldata witnessTypeString,
bytes calldata signature
) external;
/// @notice Invalidates the bits specified in mask for the bitmap at the word position
/// @dev The wordPos is maxed at type(uint248).max
/// @param wordPos A number to index the nonceBitmap at
/// @param mask A bitmap masked against msg.sender's current bitmap at the word position
function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external;
}
lib/universal-router/contracts/interfaces/IUniversalRouter.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.24;
interface IUniversalRouter {
/// @notice Thrown when a required command has failed
error ExecutionFailed(uint256 commandIndex, bytes message);
/// @notice Thrown when attempting to send ETH directly to the contract
error ETHNotAccepted();
/// @notice Thrown when executing commands with an expired deadline
error TransactionDeadlinePassed();
/// @notice Thrown when attempting to execute commands and an incorrect number of inputs are provided
error LengthMismatch();
// @notice Thrown when an address that isn't WETH tries to send ETH to the router without calldata
error InvalidEthSender();
/// @notice Executes encoded commands along with provided inputs. Reverts if deadline has expired.
/// @param commands A set of concatenated commands, each 1 byte in length
/// @param inputs An array of byte strings containing abi encoded inputs for each command
/// @param deadline The deadline by which the transaction must be executed
function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline) external payable;
}
lib/universal-router/contracts/libraries/Commands.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.24;
/// @title Commands
/// @notice Command Flags used to decode commands
library Commands {
// Masks to extract certain bits of commands
bytes1 internal constant FLAG_ALLOW_REVERT = 0x80;
bytes1 internal constant COMMAND_TYPE_MASK = 0x3f;
// Command Types. Maximum supported command at this moment is 0x3f.
// The commands are executed in nested if blocks to minimise gas consumption
// Command Types where value<=0x07, executed in the first nested-if block
uint256 constant V3_SWAP_EXACT_IN = 0x00;
uint256 constant V3_SWAP_EXACT_OUT = 0x01;
uint256 constant PERMIT2_TRANSFER_FROM = 0x02;
uint256 constant PERMIT2_PERMIT_BATCH = 0x03;
uint256 constant SWEEP = 0x04;
uint256 constant TRANSFER = 0x05;
uint256 constant PAY_PORTION = 0x06;
// COMMAND_PLACEHOLDER = 0x07;
// Command Types where 0x08<=value<=0x0f, executed in the second nested-if block
uint256 constant V2_SWAP_EXACT_IN = 0x08;
uint256 constant V2_SWAP_EXACT_OUT = 0x09;
uint256 constant PERMIT2_PERMIT = 0x0a;
uint256 constant WRAP_ETH = 0x0b;
uint256 constant UNWRAP_WETH = 0x0c;
uint256 constant PERMIT2_TRANSFER_FROM_BATCH = 0x0d;
uint256 constant BALANCE_CHECK_ERC20 = 0x0e;
// COMMAND_PLACEHOLDER = 0x0f;
// Command Types where 0x10<=value<=0x20, executed in the third nested-if block
uint256 constant V4_SWAP = 0x10;
uint256 constant V3_POSITION_MANAGER_PERMIT = 0x11;
uint256 constant V3_POSITION_MANAGER_CALL = 0x12;
uint256 constant V4_INITIALIZE_POOL = 0x13;
uint256 constant V4_POSITION_MANAGER_CALL = 0x14;
// COMMAND_PLACEHOLDER = 0x15 -> 0x20
// Command Types where 0x21<=value<=0x3f
uint256 constant EXECUTE_SUB_PLAN = 0x21;
// COMMAND_PLACEHOLDER for 0x22 to 0x3f
}
lib/v4-core/src/interfaces/IExtsload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
lib/v4-core/src/interfaces/IExttload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
lib/v4-core/src/interfaces/IHooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IPoolManager} from "./IPoolManager.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
bytes calldata hookData
) external returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}
lib/v4-core/src/interfaces/IPoolManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
/// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
/// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
/// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}
lib/v4-core/src/interfaces/IProtocolFees.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}
lib/v4-core/src/interfaces/external/IERC20Minimal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
lib/v4-core/src/interfaces/external/IERC6909Claims.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}
lib/v4-core/src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
lib/v4-core/src/libraries/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}
lib/v4-core/src/types/BalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
lib/v4-core/src/types/BeforeSwapDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}
lib/v4-core/src/types/Currency.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
lib/v4-core/src/types/PoolId.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}
lib/v4-core/src/types/PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}
lib/v4-periphery/src/interfaces/IImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
/// @title IImmutableState
/// @notice Interface for the ImmutableState contract
interface IImmutableState {
/// @notice The Uniswap v4 PoolManager contract
function poolManager() external view returns (IPoolManager);
}
lib/v4-periphery/src/interfaces/IV4Router.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {PathKey} from "../libraries/PathKey.sol";
import {IImmutableState} from "./IImmutableState.sol";
/// @title IV4Router
/// @notice Interface for the V4Router contract
interface IV4Router is IImmutableState {
/// @notice Emitted when an exactInput swap does not receive its minAmountOut
error V4TooLittleReceived(uint256 minAmountOutReceived, uint256 amountReceived);
/// @notice Emitted when an exactOutput is asked for more than its maxAmountIn
error V4TooMuchRequested(uint256 maxAmountInRequested, uint256 amountRequested);
/// @notice Parameters for a single-hop exact-input swap
struct ExactInputSingleParams {
PoolKey poolKey;
bool zeroForOne;
uint128 amountIn;
uint128 amountOutMinimum;
bytes hookData;
}
/// @notice Parameters for a multi-hop exact-input swap
struct ExactInputParams {
Currency currencyIn;
PathKey[] path;
uint128 amountIn;
uint128 amountOutMinimum;
}
/// @notice Parameters for a single-hop exact-output swap
struct ExactOutputSingleParams {
PoolKey poolKey;
bool zeroForOne;
uint128 amountOut;
uint128 amountInMaximum;
bytes hookData;
}
/// @notice Parameters for a multi-hop exact-output swap
struct ExactOutputParams {
Currency currencyOut;
PathKey[] path;
uint128 amountOut;
uint128 amountInMaximum;
}
}
lib/v4-periphery/src/libraries/Actions.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Library to define different pool actions.
/// @dev These are suggested common commands, however additional commands should be defined as required
/// Some of these actions are not supported in the Router contracts or Position Manager contracts, but are left as they may be helpful commands for other peripheral contracts.
library Actions {
// pool actions
// liquidity actions
uint256 internal constant INCREASE_LIQUIDITY = 0x00;
uint256 internal constant DECREASE_LIQUIDITY = 0x01;
uint256 internal constant MINT_POSITION = 0x02;
uint256 internal constant BURN_POSITION = 0x03;
uint256 internal constant INCREASE_LIQUIDITY_FROM_DELTAS = 0x04;
uint256 internal constant MINT_POSITION_FROM_DELTAS = 0x05;
// swapping
uint256 internal constant SWAP_EXACT_IN_SINGLE = 0x06;
uint256 internal constant SWAP_EXACT_IN = 0x07;
uint256 internal constant SWAP_EXACT_OUT_SINGLE = 0x08;
uint256 internal constant SWAP_EXACT_OUT = 0x09;
// donate
// note this is not supported in the position manager or router
uint256 internal constant DONATE = 0x0a;
// closing deltas on the pool manager
// settling
uint256 internal constant SETTLE = 0x0b;
uint256 internal constant SETTLE_ALL = 0x0c;
uint256 internal constant SETTLE_PAIR = 0x0d;
// taking
uint256 internal constant TAKE = 0x0e;
uint256 internal constant TAKE_ALL = 0x0f;
uint256 internal constant TAKE_PORTION = 0x10;
uint256 internal constant TAKE_PAIR = 0x11;
uint256 internal constant CLOSE_CURRENCY = 0x12;
uint256 internal constant CLEAR_OR_TAKE = 0x13;
uint256 internal constant SWEEP = 0x14;
uint256 internal constant WRAP = 0x15;
uint256 internal constant UNWRAP = 0x16;
// minting/burning 6909s to close deltas
// note this is not supported in the position manager or router
uint256 internal constant MINT_6909 = 0x17;
uint256 internal constant BURN_6909 = 0x18;
}
lib/v4-periphery/src/libraries/PathKey.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
struct PathKey {
Currency intermediateCurrency;
uint24 fee;
int24 tickSpacing;
IHooks hooks;
bytes hookData;
}
using PathKeyLibrary for PathKey global;
/// @title PathKey Library
/// @notice Functions for working with PathKeys
library PathKeyLibrary {
/// @notice Get the pool and swap direction for a given PathKey
/// @param params the given PathKey
/// @param currencyIn the input currency
/// @return poolKey the pool key of the swap
/// @return zeroForOne the direction of the swap, true if currency0 is being swapped for currency1
function getPoolAndSwapDirection(PathKey calldata params, Currency currencyIn)
internal
pure
returns (PoolKey memory poolKey, bool zeroForOne)
{
Currency currencyOut = params.intermediateCurrency;
(Currency currency0, Currency currency1) =
currencyIn < currencyOut ? (currencyIn, currencyOut) : (currencyOut, currencyIn);
zeroForOne = currencyIn == currency0;
poolKey = PoolKey(currency0, currency1, params.fee, params.tickSpacing, params.hooks);
}
}
node_modules/@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
node_modules/@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}
node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @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);
}
node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && AddressUpgradeable.isContract(address(token));
}
}
node_modules/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
node_modules/@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
node_modules/@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}
node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
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);
}
node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
node_modules/@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
node_modules/@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"contracts/libraries/SwapLibrary.sol": {
"SwapLibrary": "0xf60F1aA5009Aa945833aB24A96E1Dfb759dc4B2F"
}
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@uniswap/v4-periphery/=lib/v4-periphery/",
"@uniswap/v4-core/=lib/v4-core/",
"@uniswap/universal-router/=lib/universal-router/",
"@uniswap/permit2/=lib/permit2/",
"@aave/=node_modules/@aave/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@morpho-org/=node_modules/@morpho-org/",
"@openzeppelin/=node_modules/@openzeppelin/",
"@uniswap/v2-core/=lib/universal-router/node_modules/@uniswap/v2-core/",
"@uniswap/v3-core/=lib/universal-router/node_modules/@uniswap/v3-core/",
"@uniswap/v3-periphery/=lib/universal-router/lib/v3-periphery/",
"ds-test/=lib/universal-router/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"eth-gas-reporter/=node_modules/eth-gas-reporter/",
"forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
"forge-std/=lib/forge-std/src/",
"hardhat/=node_modules/hardhat/",
"openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"permit2/=lib/permit2/",
"solmate/=lib/universal-router/lib/solmate/",
"universal-router/=lib/universal-router/",
"v3-periphery/=lib/universal-router/lib/v3-periphery/contracts/",
"v4-core/=lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.