Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"contracts/strategy/liquidation/FlashLiquidator.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { Currency } from "@uniswap/v4-core/src/types/Currency.sol";
import { AFlashLoan } from "../../flashloan/AFlashLoan.sol";
import { ISwapper } from "../../swaps/uniswap/ISwapper.sol";
// --- Minimal interfaces (decoupled from full Aave types for easier integration) ---
interface IPriceOracleGetterLike {
function getAssetPrice(address asset) external view returns (uint256);
}
interface IPoolAddressesProviderLike {
function getPriceOracle() external view returns (address);
function getPoolDataProvider() external view returns (address);
}
interface IProtocolDataProviderLike {
function getReserveTokensAddresses(
address asset
) external view returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
function getUserReserveData(
address asset,
address user
) external view returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveConfigurationData(address asset) external view returns (
uint256 decimals,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
uint256 reserveFactor,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool isStableBorrowRateEnabled,
bool isPaused
);
function getLiquidationProtocolFee(address asset) external view returns (uint256);
}
/// @title FlashLiquidator
/// @notice Uses a flash loan in the debt token to liquidate a target Aave position, then swaps collateral to repay.
contract FlashLiquidator is AFlashLoan, ReentrancyGuard {
using SafeERC20 for IERC20;
/// @dev Swapper used for collateral -> debt swaps.
ISwapper public immutable SWAPPER;
/// @dev Config values (modifiable by owner)
uint16 public defaultCloseFactorBps = 5000; // 50% when HF ∈ [threshold, 1)
uint16 public maxCloseFactorBps = 10_000; // 100% when HF < threshold
uint256 public closeFactorHfThresholdWad = 950_000_000_000_000_000; // 0.95e18
uint16 public flashFeeBps = 10; // conservative est. for profitability calc (Aave usually 5 bps)
uint16 public slippageBps = 50; // 0.50% conservative haircut for planning
mapping(address => uint16) public liquidationBonusBps; // optional override per collateral (e.g., 10500 = +5%)
/// @dev Aave Protocol Data Provider address (must be set by owner)
address public DATA_PROVIDER;
/// @dev Temporary job slot used across the flash-loan callback.
struct Job {
address user; // Account to liquidate
address collateralToken; // Collateral to seize
address debtToken; // Debt asset to repay (and flash-borrow)
uint256 repayAmount; // Amount of debt to cover (respect close factor)
PoolKey collToDebtKey; // Route for swapping collateral -> debt
bool collateralIsToken0; // Direction flag for router
}
Job private _job;
bool private _inFlash;
uint256 private _minProfit = 1 ether; // Default 1 token minimum profit
// --- Route registry (so autoLiquidate can find how to swap collateral->debt) ---
struct Route { address collateral; address debt; PoolKey key; bool collateralIsToken0; bool exists; }
mapping(bytes32 => Route) private _routes; // key = keccak256(collateral,debt)
bytes32[] private _routeKeys; // enumerable keys for iteration
event LiquidationPlanned(address indexed user, address indexed collateral, address indexed debt, uint256 repayAmount);
event LiquidationExecuted(address indexed user, uint256 collateralSeized, uint256 debtRepaid, uint256 premiumPaid, uint256 collateralLeftover);
event LiquidationSwap(address indexed collateral, address indexed debt, uint256 exactOut, uint256 amountInUsed, uint256 seized, uint256 netLeftover);
event RouteSet(address indexed collateral, address indexed debt);
constructor(address _addressesProvider, address _swapper) AFlashLoan(_addressesProvider) {
require(_swapper != address(0), "swapper=0");
SWAPPER = ISwapper(_swapper);
}
/// @notice Initiates a flash-loan powered liquidation on `user`.
/// @param user Account to liquidate
/// @param collateralToken Collateral asset to seize
/// @param debtToken Debt asset to repay (must have liquidity for flash-loan)
/// @param repayAmount Amount of debt to cover (≤ close factor)
/// @param collToDebtKey Uniswap v4 pool key for swapping collateral -> debt
/// @param collateralIsToken0 Whether collateral is token0 in the given pool key
function liquidate(
address user,
address collateralToken,
address debtToken,
uint256 repayAmount,
PoolKey memory collToDebtKey,
bool collateralIsToken0
) public onlyOwner nonReentrant {
require(user != address(0) && collateralToken != address(0) && debtToken != address(0), "zero address");
require(repayAmount > 0, "zero repay amount");
_job = Job({
user: user,
collateralToken: collateralToken,
debtToken: debtToken,
repayAmount: repayAmount,
collToDebtKey: collToDebtKey,
collateralIsToken0: collateralIsToken0
});
emit LiquidationPlanned(user, collateralToken, debtToken, repayAmount);
_inFlash = true;
// Borrow the debt asset to perform the liquidation
requestFlashLoan(debtToken, repayAmount);
_inFlash = false;
// Clear job to avoid stale reuse
delete _job;
}
// --- Auto liquidation flow ---
/// @notice Evaluate user's health factor; if < 1, attempt to find a profitable registered route and liquidate.
/// @dev Relies on configured routes and oracle-based profitability estimate. Real profit is enforced by _minProfit at callback.
function autoLiquidate(address user) external onlyOwner {
require(user != address(0), "zero address");
// 1) Check health factor
(
, // totalCollateralBase
, // totalDebtBase
, // availableBorrowsBase
, // currentLiquidationThreshold
, // ltv
uint256 healthFactor
) = POOL.getUserAccountData(user);
// Aave v3 returns HF scaled by 1e18; compare to 1e18 threshold
require(healthFactor < 1e18, "HF>=1");
// Dynamic close factor per Aave v3 guidance
uint16 dynamicCloseFactor = healthFactor < closeFactorHfThresholdWad ? maxCloseFactorBps : defaultCloseFactorBps;
// Helpers
IPoolAddressesProviderLike provider = IPoolAddressesProviderLike(address(ADDRESSES_PROVIDER));
address dpAddr = DATA_PROVIDER;
if (dpAddr == address(0)) {
dpAddr = provider.getPoolDataProvider();
}
require(dpAddr != address(0), "data provider=0");
IProtocolDataProviderLike dp = IProtocolDataProviderLike(dpAddr);
IPriceOracleGetterLike oracle = IPriceOracleGetterLike(provider.getPriceOracle());
// Iterate known routes to find a profitable pair
// NOTE: For gas optimization in production, consider passing the route as a parameter
// instead of iterating all routes on-chain. This keeps the on-chain iteration as a fallback.
bytes32 selectedKey;
uint256 repayAmount;
bool found;
uint256 routeCount = _routeKeys.length; // Cache array length
for (uint256 i = 0; i < routeCount; i++) {
bytes32 k = _routeKeys[i];
Route memory r = _routes[k];
if (!r.exists) continue;
// Fetch user balances for the specific collateral/debt reserves
(address aToken,,) = dp.getReserveTokensAddresses(r.collateral);
if (aToken == address(0)) continue;
uint256 userCollateral = IERC20(aToken).balanceOf(user);
if (userCollateral == 0) continue;
(
uint256 currentATokenBalance,
,
,
,
,
,
,
,
bool usageAsCollateral
) = dp.getUserReserveData(r.collateral, user);
if (!usageAsCollateral || currentATokenBalance == 0) continue;
(
,
address stableDebtTokenDebt,
address variableDebtTokenDebt
) = dp.getReserveTokensAddresses(r.debt);
uint256 userDebt = 0;
if (variableDebtTokenDebt != address(0)) {
userDebt += IERC20(variableDebtTokenDebt).balanceOf(user);
}
if (stableDebtTokenDebt != address(0)) {
userDebt += IERC20(stableDebtTokenDebt).balanceOf(user);
}
if (userDebt == 0) continue;
// Determine repay amount under configured close factor
uint256 repay = (userDebt * uint256(dynamicCloseFactor)) / 10_000;
if (repay == 0) continue;
if (repay > userDebt) repay = userDebt;
// Oracle-based conservative profitability estimate (ignore bonus if none configured)
uint256 pColl = oracle.getAssetPrice(r.collateral);
uint256 pDebt = oracle.getAssetPrice(r.debt);
// Validate oracle prices are non-zero and within reasonable bounds
if (pColl == 0 || pDebt == 0) continue;
if (pColl >= type(uint128).max || pDebt >= type(uint128).max) continue;
// Decode liquidation bonus and protocol fee for effective bonus-over-notional
uint256 rawBonusBps;
uint256 protoFeeOnBonusBps = 0;
// Try/catch to be resilient across markets
try dp.getReserveConfigurationData(r.collateral) returns (
uint256 /*decimals*/, uint256 /*ltv*/, uint256 /*liqThreshold*/, uint256 liquidationBonus, uint256 /*reserveFactor*/,
bool /*usageAsCol*/ , bool /*borrowingEnabled*/, bool /*isStableBorrowRateEnabled*/, bool /*isPaused*/
) {
rawBonusBps = liquidationBonus; // e.g., 11000 means +10%
} catch { rawBonusBps = 10_000; }
// Protocol fee is applied on the bonus portion only
try dp.getLiquidationProtocolFee(r.collateral) returns (uint256 feeBps) {
protoFeeOnBonusBps = feeBps;
} catch { protoFeeOnBonusBps = 0; }
// Calculate effective liquidation bonus after protocol fee
// rawBonusBps is in form 10500 = 105% = 1.05x multiplier
uint256 effectiveBonusBps = rawBonusBps;
if (protoFeeOnBonusBps > 0 && rawBonusBps > 10_000) {
// Protocol fee only applies to the bonus portion
uint256 bonusOverBps = rawBonusBps - 10_000;
uint256 feeOnBonus = (bonusOverBps * protoFeeOnBonusBps) / 10_000;
effectiveBonusBps = rawBonusBps - feeOnBonus;
}
// Aave formula: maxCollateralToLiquidate = (debtPrice * debtToCover * liquidationBonus) / collateralPrice
// liquidationBonus is already in the form 10500 (meaning 105% = 1.05x)
uint256 seizedColl = (repay * pDebt * effectiveBonusBps) / (pColl * 10_000);
// Flash fee estimate (bps on borrowed amount)
uint256 fee = (repay * uint256(flashFeeBps)) / 10_000;
// Collateral needed to swap back to debt including a slippage haircut
uint256 neededColl = ((repay + fee) * pDebt) / pColl;
neededColl = (neededColl * (10_000 + uint256(slippageBps))) / 10_000;
if (seizedColl > neededColl) {
// Found a candidate route deemed profitable by estimate
selectedKey = k;
repayAmount = repay;
found = true;
break;
}
}
require(found, "no profitable route");
// Execute liquidation using the selected route
Route memory sel = _routes[selectedKey];
liquidate(user, sel.collateral, sel.debt, repayAmount, sel.key, sel.collateralIsToken0);
}
/// @inheritdoc AFlashLoan
function executeStrategy(
address asset,
uint256 amount,
uint256 premium,
address /*initiator*/,
bytes calldata /*params*/
) internal override returns (uint256) {
require(_inFlash, "not in flash");
Job memory j = _job;
require(asset == j.debtToken, "flash!=debt");
require(amount == j.repayAmount, "amt mismatch");
// 1) Approve Pool to pull the debt we just flash-borrowed for liquidation
IERC20(asset).forceApprove(address(POOL), amount);
// 2) Liquidate the target account; receive underlying collateral (not aTokens)
uint256 collBefore = IERC20(j.collateralToken).balanceOf(address(this));
POOL.liquidationCall(j.collateralToken, j.debtToken, j.user, amount, false);
uint256 collAfter = IERC20(j.collateralToken).balanceOf(address(this));
require(collAfter >= collBefore, "collateral balance decreased");
uint256 seized = collAfter - collBefore;
require(seized > 0, "no collateral seized");
uint256 exactOut = amount + premium;
require(exactOut <= type(uint128).max, "amount too big");
require(seized <= type(uint128).max, "seized too big");
uint256 amountInUsed;
uint256 netLeftover;
if (j.collateralToken == j.debtToken) {
// Same-asset case: the collateral we seized is the debt token; no swap needed
require(seized >= exactOut, "seized<repay");
amountInUsed = exactOut;
netLeftover = seized - exactOut;
} else {
// Calculate maximum amount of collateral we're willing to spend with slippage protection
// We need exactOut of debt token, estimate how much collateral that requires
// and add slippage buffer. The swap should use less than this.
uint256 maxAmountIn = seized; // Start with what we have
// Apply slippage protection: we expect to use less collateral than seized
// Reserve at least slippageBps% of seized as minimum profit
if (slippageBps > 0) {
uint256 minProfit = (seized * uint256(slippageBps)) / 10_000;
require(seized > minProfit + exactOut / 2, "insufficient collateral for slippage");
maxAmountIn = seized - minProfit;
}
require(maxAmountIn >= exactOut, "max collateral < debt owed");
require(maxAmountIn <= type(uint128).max, "maxAmountIn overflow");
_ensureMaxApproval(IERC20(j.collateralToken), address(SWAPPER));
amountInUsed = SWAPPER.swapExactOutputSingle(
j.collToDebtKey,
uint128(exactOut),
uint128(maxAmountIn), // Enforce slippage limit
j.collateralIsToken0,
false,
block.timestamp + 300, // 5 minute deadline for MEV protection
address(this)
);
netLeftover = seized > amountInUsed ? (seized - amountInUsed) : 0;
emit LiquidationSwap(j.collateralToken, j.debtToken, exactOut, amountInUsed, seized, netLeftover);
}
_requireMinProfit(netLeftover);
// Emit the actual profit from this liquidation
emit LiquidationExecuted(j.user, seized, amount, premium, netLeftover);
return amount + premium;
}
// --- internal helpers ---
function _ensureMaxApproval(IERC20 token, address spender) internal {
if (token.allowance(address(this), spender) < type(uint256).max) {
token.forceApprove(spender, type(uint256).max);
}
}
function _requireMinProfit(uint256 leftover) internal view {
require(leftover >= _minProfit, "profit below minimum threshold");
}
function setMinProfit(uint256 minProfit) external onlyOwner {
_minProfit = minProfit;
}
// --- config & route management ---
function setDataProvider(address dataProvider) external onlyOwner { require(dataProvider != address(0), "zero address"); DATA_PROVIDER = dataProvider; }
function setDefaultCloseFactorBps(uint16 bps) external onlyOwner { require(bps <= 10_000, "invalid bps"); defaultCloseFactorBps = bps; }
function setMaxCloseFactorBps(uint16 bps) external onlyOwner { require(bps <= 10_000, "invalid bps"); maxCloseFactorBps = bps; }
function setCloseFactorHfThresholdWad(uint256 wad) external onlyOwner { require(wad <= 1e20, "invalid threshold"); closeFactorHfThresholdWad = wad; }
// Backward compatibility: keep the old name as a proxy to set the defaultCloseFactorBps
function setCloseFactorBps(uint16 bps) external onlyOwner { require(bps <= 10_000, "invalid bps"); defaultCloseFactorBps = bps; }
function setSlippageBps(uint16 bps) external onlyOwner { require(bps <= 1_000, "invalid slippage"); slippageBps = bps; }
function setFlashFeeBps(uint16 bps) external onlyOwner { require(bps <= 1000, "invalid flash fee"); flashFeeBps = bps; }
function setLiquidationBonusBps(address collateral, uint16 bps) external onlyOwner { require(bps >= 10_000, "bonus below 100%"); liquidationBonusBps[collateral] = bps; }
function resetApproval(address token, address spender) external onlyOwner {
IERC20(token).forceApprove(spender, 0);
}
function setRoute(address collateral, address debt, PoolKey calldata key, bool collateralIsToken0) external onlyOwner {
require(collateral != address(0) && debt != address(0), "zero address");
require(collateral != debt, "collateral == debt");
address t0 = Currency.unwrap(key.currency0);
address t1 = Currency.unwrap(key.currency1);
// Validate pool key tokens are non-zero
require(t0 != address(0) && t1 != address(0), "zero pool token");
// Validate tokens match the pool key
require(
(collateral == t0 && debt == t1) || (collateral == t1 && debt == t0),
"key tokens mismatch"
);
// Validate direction flag matches actual token positions
require(collateralIsToken0 == (collateral == t0), "direction mismatch");
// Validate token ordering in pool key (Uniswap v4 requires token0 < token1)
require(t0 < t1, "invalid pool key: token0 >= token1");
bytes32 k = keccak256(abi.encodePacked(collateral, debt));
if (!_routes[k].exists) {
_routeKeys.push(k);
}
_routes[k] = Route({ collateral: collateral, debt: debt, key: key, collateralIsToken0: collateralIsToken0, exists: true });
emit RouteSet(collateral, debt);
}
function getRoute(address collateral, address debt) external view returns (Route memory) {
return _routes[keccak256(abi.encodePacked(collateral, debt))];
}
}"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 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 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @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 {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @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.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, 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 to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
"
},
"lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// 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;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = 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();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
"
},
"lib/v4-core/src/types/PoolKey.sol": {
"content": "// 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-core/src/types/Currency.sol": {
"content": "// 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)));
}
}
"
},
"contracts/flashloan/AFlashLoan.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@protocol-v3/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol";
import "@protocol-v3/contracts/interfaces/IPoolAddressesProvider.sol";
import "../ownership/MultiOwnable.sol";
/**
* @title FlashLoan
* @author antonis@typesystem.xyz
* @notice This contract is a simple example of how to receive a flash loan from Aave V3.
* It is not meant to be used in production without extensive testing and security audits.
* This version uses MultiOwnable to support multiple owners.
*/
abstract contract AFlashLoan is FlashLoanSimpleReceiverBase, MultiOwnable {
using SafeERC20 for IERC20;
error OnlyPool();
error InvalidInitiator();
event FlashLoanReceived(address indexed asset, uint256 amount, uint256 premium);
event FlashLoanRepaid(address indexed asset, uint256 amountOwed);
error EtherTransferFailed();
/**
* @dev The constructor sets the owner of the contract and the Aave Pool Addresses Provider.
* @param _addressProvider The address of the Aave V3 PoolAddressesProvider contract.
* This can be found in the Aave developer documentation for the specific network.
*/
constructor(address _addressProvider)
FlashLoanSimpleReceiverBase(IPoolAddressesProvider(_addressProvider))
{}
/**
* @dev This is the function that is called by the Aave Pool to execute the flash loan.
* @param asset The address of the asset being flash loaned.
* @param amount The amount of the asset being flash loaned.
* @param premium The fee required to be paid for the flash loan.
* @param initiator The address that initiated the flash loan.
* @param params Additional data passed to the flash loan.
* @return A boolean indicating if the flash loan was successful.
*/
function executeOperation(
address asset,
uint256 amount,
uint256 premium,
address initiator,
bytes calldata params
) external override returns (bool) {
// Ensure this is Aave Pool calling
if (msg.sender != address(POOL)) revert OnlyPool();
// Ensure we only honor loans we initiated ourselves
if (initiator != address(this)) revert InvalidInitiator();
emit FlashLoanReceived(asset, amount, premium);
// Calculate the total amount to be repaid (loaned amount + premium)
uint256 amountOwed = executeStrategy(asset, amount, premium, initiator, params);
// Expect this contract to be pre-funded to cover amount + premium.
// Approve the Aave Pool to pull the funds from this contract to repay the loan
IERC20(asset).forceApprove(address(POOL), amountOwed);
emit FlashLoanRepaid(asset, amountOwed);
return true;
}
/**
* @dev This function is meant to be implemented by child contracts.
* @param asset The address of the asset being flash loaned.
* @param amount The amount of the asset being flash loaned.
* @param premium The fee required to be paid for the flash loan.
* @param initiator The address that initiated the flash loan.
* @param params Additional data passed to the flash loan.
* @return A uint256 of the amount owed.
*/
function executeStrategy(address asset, uint256 amount, uint256 premium, address initiator, bytes calldata params) internal virtual returns (uint256);
/**
* @dev Initiates a flash loan.
* @param _token The address of the ERC20 token to be loaned.
* @param _amount The amount of the token to be loaned.
*/
function requestFlashLoan(address _token, uint256 _amount) internal onlyOwner {
// No external payer; params left empty.
bytes memory params = "";
POOL.flashLoanSimple(address(this), _token, _amount, params, 0);
}
/**
* @dev Allows the owner to withdraw any profits (in the form of the specified ERC20 token)
* from this contract.
* @param _tokenAddress The address of the ERC20 token to withdraw.
*/
function withdraw(address _tokenAddress) external onlyOwner {
address to = owners[0];
IERC20 token = IERC20(_tokenAddress);
token.safeTransfer(to, token.balanceOf(address(this)));
}
/**
* @dev Allows the owner to withdraw any ETH profits from this contract.
*/
function withdrawEth() external onlyOwner {
address payable to = payable(owners[0]);
(bool ok, ) = to.call{value: address(this).balance}("");
if (!ok) revert EtherTransferFailed();
}
/**
* @dev Receive function to accept ETH.
*/
receive() external payable {}
}
"
},
"contracts/swaps/uniswap/ISwapper.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { ISignatureTransfer } from "@uniswap/permit2/src/interfaces/ISignatureTransfer.sol";
/// @title ISwapper
/// @notice Interface mirroring all public/external methods exposed by UniswapV4Swapper
interface ISwapper {
/// @notice Approve Permit2 to pull `token` from this contract, and allow Universal Router via Permit2
function approveTokenWithPermit2(address token, uint160 amount, uint48 expiration) external;
/// @notice Swap exact input for >= min output (single v4 pool)
function swapExactInputSingle(
PoolKey memory key,
uint128 amountIn,
uint128 minAmountOut,
bool zeroForOne,
uint256 deadline,
address recipient
) external returns (uint256 amountOut);
/// @notice Swap up to `amountInMaximum` to receive exactly `amountOut` (single v4 pool)
function swapExactOutputSingle(
PoolKey memory key,
uint128 amountOut,
uint128 amountInMaximum,
bool zeroForOne,
bool unwrapOutput,
uint256 deadline,
address recipient
) external returns (uint256 amountIn);
/// @notice Simplified overload: swap exact input by providing tokens and pool params
function swapExactInputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
int24 tickSpacing,
address hooks,
uint128 amountIn,
uint128 minAmountOut,
uint256 deadline,
address recipient
) external returns (uint256 amountOut);
/// @notice Simplified overload: swap exact output by providing tokens and pool params
function swapExactOutputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
int24 tickSpacing,
address hooks,
uint128 amountOut,
uint128 amountInMaximum,
uint256 deadline,
address recipient
) external returns (uint256 amountIn);
/// @notice Swap exact input ETH for >= min output (wraps to WETH internally)
function swapExactInputSingleETH(
PoolKey memory key,
uint128 minAmountOut,
bool zeroForOne,
uint256 deadline,
address recipient
) external payable returns (uint256 amountOut);
/// @notice Swap up to `amountInMaximum` ETH to receive exactly `amountOut` (wraps to WETH internally)
function swapExactOutputSingleETH(
PoolKey memory key,
uint128 amountOut,
uint128 amountInMaximum,
bool zeroForOne,
uint256 deadline,
address recipient,
bool unwrap
) external payable returns (uint256 amountIn);
/// @notice Swap exact input using Permit2 for token transfer
function swapExactInputSingleWithPermit2(
PoolKey memory key,
uint128 amountIn,
uint128 minAmountOut,
bool zeroForOne,
uint256 deadline,
address recipient,
ISignatureTransfer.PermitTransferFrom calldata permit,
bytes calldata signature
) external returns (uint256 amountOut);
/// @notice Swap exact output using Permit2 for token transfer
function swapExactOutputSingleWithPermit2(
PoolKey memory key,
uint128 amountOut,
uint128 amountInMaximum,
bool zeroForOne,
uint256 deadline,
address recipient,
ISignatureTransfer.PermitTransferFrom calldata permit,
bytes calldata signature
) external returns (uint256 amountIn);
}"
},
"lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
"
},
"lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
Submitted on: 2025-10-17 20:44:57
Comments
Log in to comment.
No comments yet.