Verified contractExactMIT
ObsidianAaveProxy
Address0x0d9a211aba11d3cd025dfbd88ec37ec944d50087
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.20
- Same code
Only this contract
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,464,909
- Creation transaction
- 0xb01b4ff5b0…879c306b45
12 files
- contracts/ObsidianAaveProxy.solmain13.86 KB
- @openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- @openzeppelin/contracts/interfaces/IERC165.sol193 B
- @openzeppelin/contracts/interfaces/IERC20.sol182 B
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol13.31 KB
- @openzeppelin/contracts/utils/ReentrancyGuard.sol4.77 KB
- @openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
- @openzeppelin/contracts/utils/cryptography/ECDSA.sol12.15 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 B
- contracts/ObsidianProxyBase.sol12.01 KB
- contracts/ObsidianSwapExecutor.sol2.63 KB
contracts/ObsidianAaveProxy.sol
// 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 {ObsidianProxyBase} from "./ObsidianProxyBase.sol";
import {ObsidianSwapExecutor} from "./ObsidianSwapExecutor.sol";
// Aave V3 Pool.getReserveData() return shape (unchanged across V3.0 - V3.4)
struct ReserveDataLegacy {
uint256 configuration;
uint128 liquidityIndex;
uint128 currentLiquidityRate;
uint128 variableBorrowIndex;
uint128 currentVariableBorrowRate;
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
uint16 id;
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
address interestRateStrategyAddress;
uint128 accruedToTreasury;
uint128 unbacked;
uint128 isolationModeTotalDebt;
}
interface IAavePool {
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata interestRateModes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
function flashLoanSimple(address receiverAddress, address asset, uint256 amount, bytes calldata params, uint16 referralCode) external;
function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
function repay(address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf) external returns (uint256);
function withdraw(address asset, uint256 amount, address to) external returns (uint256);
function getReserveData(address asset) external view returns (ReserveDataLegacy memory);
}
/**
* @title ObsidianAaveProxy (v2)
* @notice Opens and closes leveraged loops on an Aave V3 pool (or an Aave V3 fork) in one transaction each.
*
* loop: flash-borrow the loan asset with interestRateMode 2 (the debt is opened directly on the
* user at the end, no flash-loan fee), take the opening fee, swap the rest to the
* collateral, supply everything on behalf of the user.
* unloop: flash-loan the loan asset, repay the user's debt, pull the user's aTokens, withdraw,
* swap the collateral back, repay the flash loan, refund the rest. No fee.
*
* Security model (lessons of the June 2026 exploit of the first Morpho proxy):
* - The contract only ever acts for msg.sender: the user is never a parameter.
* - No standing permission is needed: the app asks for EXACT amounts (collateral approval, credit
* delegation, aToken approval), all consumed by the same transaction.
* - The router call never runs from this contract: it runs in ObsidianSwapExecutor, which nobody
* approves or delegates to. Even a rogue allowlisted router cannot reach a permission given here.
* - The swap target must be allowlisted, and is never the pool or a token of the market (checked at
* every call). New targets wait TARGET_DELAY; removing a target and pausing are immediate.
* - Minimum swap outputs are enforced here, not only inside the router's calldata.
* - Opening fee: see ObsidianProxyBase (hard cap, signed rates can only lower it, user's maxFeeBps).
*/
contract ObsidianAaveProxy is ObsidianProxyBase {
using SafeERC20 for IERC20;
IAavePool public immutable pool;
// Single-use ticket for the flash-loan callback: armed by loop()/unloop() right before calling
// the pool, consumed by the callback. A callback reached any other way (spoofed flash loan,
// re-entry from a swap router) finds it unarmed. Defense in depth on top of initiator == this.
uint8 private _expectedOp;
uint8 private constant OP_LOOP = 1;
uint8 private constant OP_UNLOOP = 2;
struct LoopParams {
address collateralAsset;
address loanAsset;
uint256 initialCollateralAmount; // pulled from the user (exact approval)
uint256 borrowAmount; // debt opened on the user (exact credit delegation), fee included
uint256 minCollateralOut; // minimum collateral obtained by the swap
uint256 maxFeeBps; // the highest opening fee rate the user accepts
address swapTarget;
address targetToApprove; // address(0) = swapTarget
bytes swapData; // swaps borrowAmount minus the fee
}
struct UnloopParams {
address collateralAsset;
address loanAsset;
uint256 flashAmount; // >= debt to repay (repay is capped at the actual debt)
uint256 withdrawCollateralAmount; // aTokens pulled from the user (exact approval)
uint256 minLoanOut; // minimum loan asset obtained by the swap
address swapTarget;
address targetToApprove;
bytes swapData;
}
struct Callback {
uint8 op;
address user;
address collateral;
address loan;
address aCollateral;
uint256 amount; // loop: opening fee; unloop: aTokens to pull
uint256 feeBps; // loop: rate of that fee
uint256 minOut;
address swapTarget;
address spender;
bytes swapData;
}
error NotPool();
error NotSelf();
event Looped(address indexed user, address indexed collateral, address indexed loan, uint256 borrowed, uint256 collateralSupplied);
event Unlooped(address indexed user, address indexed collateral, address indexed loan, uint256 repaid, uint256 collateralWithdrawn);
constructor(
address _pool,
address[] memory initialTargets,
ObsidianSwapExecutor _executor,
address _feeRecipient,
address _feeSigner,
uint16 _defaultFeeBps
) ObsidianProxyBase("ObsidianAaveProxy", _pool, initialTargets, _executor, _feeRecipient, _feeSigner, _defaultFeeBps) {
pool = IAavePool(_pool);
}
function _core() internal view override returns (address) {
return address(pool);
}
/// Market key signed in a FeeQuote for this pair
function marketKey(address collateralAsset, address loanAsset) public pure returns (bytes32) {
return keccak256(abi.encode(collateralAsset, loanAsset));
}
// ── Loop ─────────────────────────────────────────────────────────────
function loop(LoopParams calldata p, FeeQuote calldata q) external nonReentrant whenNotPaused {
// minCollateralOut > 0: a swap that returns nothing (malicious or broken router) can never
// leave the user with fresh debt and no collateral for it
if (p.borrowAmount == 0 || p.minCollateralOut == 0 || p.collateralAsset == p.loanAsset) revert BadParams();
(address aCollateral, address spender) = _validate(p.collateralAsset, p.loanAsset, p.swapTarget, p.targetToApprove);
(uint256 feeBps, uint256 fee) =
_openFee(marketKey(p.collateralAsset, p.loanAsset), p.initialCollateralAmount, p.borrowAmount, p.maxFeeBps, q);
if (p.initialCollateralAmount > 0) {
IERC20(p.collateralAsset).safeTransferFrom(msg.sender, address(this), p.initialCollateralAmount);
}
bytes memory data = abi.encode(Callback({
op: OP_LOOP, user: msg.sender, collateral: p.collateralAsset, loan: p.loanAsset, aCollateral: aCollateral,
amount: fee, feeBps: feeBps, minOut: p.minCollateralOut, swapTarget: p.swapTarget, spender: spender, swapData: p.swapData
}));
address[] memory assets = new address[](1);
uint256[] memory amounts = new uint256[](1);
uint256[] memory modes = new uint256[](1);
assets[0] = p.loanAsset;
amounts[0] = p.borrowAmount;
modes[0] = 2; // variable debt opened on msg.sender (needs their credit delegation to this contract)
_expectedOp = OP_LOOP;
pool.flashLoan(address(this), assets, amounts, modes, msg.sender, data, 0);
if (_expectedOp != 0) revert UnexpectedCallback(); // the pool must have called back exactly once
_refund(p.collateralAsset, msg.sender);
_refund(p.loanAsset, msg.sender);
}
/// @dev Aave flashLoan callback (loop). The debt is opened by the pool after this returns.
function executeOperation(
address[] calldata,
uint256[] calldata amounts,
uint256[] calldata,
address initiator,
bytes calldata params
) external returns (bool) {
if (msg.sender != address(pool)) revert NotPool();
if (initiator != address(this)) revert NotSelf();
if (_expectedOp != OP_LOOP) revert UnexpectedCallback();
_expectedOp = 0;
Callback memory c = abi.decode(params, (Callback));
if (c.op != OP_LOOP) revert BadParams();
_chargeFee(c.user, c.loan, c.amount, c.feeBps);
uint256 before = IERC20(c.collateral).balanceOf(address(this));
_swap(c.loan, c.collateral, amounts[0] - c.amount, c.swapTarget, c.spender, c.swapData);
uint256 total = IERC20(c.collateral).balanceOf(address(this));
if (total - before < c.minOut) revert InsufficientOutput();
IERC20(c.collateral).forceApprove(address(pool), total);
pool.supply(c.collateral, total, c.user, 0);
emit Looped(c.user, c.collateral, c.loan, amounts[0], total);
return true;
}
// ── Unloop ───────────────────────────────────────────────────────────
function unloop(UnloopParams calldata p) external nonReentrant whenNotPaused {
if (p.flashAmount == 0 || p.withdrawCollateralAmount == 0 || p.minLoanOut == 0 || p.collateralAsset == p.loanAsset) revert BadParams();
(address aCollateral, address spender) = _validate(p.collateralAsset, p.loanAsset, p.swapTarget, p.targetToApprove);
bytes memory data = abi.encode(Callback({
op: OP_UNLOOP, user: msg.sender, collateral: p.collateralAsset, loan: p.loanAsset, aCollateral: aCollateral,
amount: p.withdrawCollateralAmount, feeBps: 0, minOut: p.minLoanOut, swapTarget: p.swapTarget, spender: spender, swapData: p.swapData
}));
_expectedOp = OP_UNLOOP;
pool.flashLoanSimple(address(this), p.loanAsset, p.flashAmount, data, 0);
if (_expectedOp != 0) revert UnexpectedCallback();
_refund(p.collateralAsset, msg.sender);
_refund(p.loanAsset, msg.sender);
_refund(aCollateral, msg.sender);
}
/// @dev Aave flashLoanSimple callback (unloop). The pool pulls amount + premium after this returns.
function executeOperation(
address asset,
uint256 amount,
uint256 premium,
address initiator,
bytes calldata params
) external returns (bool) {
if (msg.sender != address(pool)) revert NotPool();
if (initiator != address(this)) revert NotSelf();
if (_expectedOp != OP_UNLOOP) revert UnexpectedCallback();
_expectedOp = 0;
Callback memory c = abi.decode(params, (Callback));
if (c.op != OP_UNLOOP || asset != c.loan) revert BadParams();
// 1. Repay the user's variable debt (Aave caps the repayment at the actual debt)
IERC20(c.loan).forceApprove(address(pool), amount);
uint256 repaid = pool.repay(c.loan, amount, 2, c.user);
IERC20(c.loan).forceApprove(address(pool), 0);
// 2. Take the user's aTokens (exact approval; Aave checks their health factor on transfer) and redeem them
IERC20(c.aCollateral).safeTransferFrom(c.user, address(this), c.amount);
uint256 withdrawn = pool.withdraw(c.collateral, type(uint256).max, address(this));
// 3. Swap the collateral back to the loan asset
uint256 before = IERC20(c.loan).balanceOf(address(this));
_swap(c.collateral, c.loan, IERC20(c.collateral).balanceOf(address(this)), c.swapTarget, c.spender, c.swapData);
uint256 afterSwap = IERC20(c.loan).balanceOf(address(this));
if (afterSwap - before < c.minOut) revert InsufficientOutput();
if (afterSwap < amount + premium) revert InsufficientOutput();
// 4. Let the pool pull the flash loan back
IERC20(c.loan).forceApprove(address(pool), amount + premium);
emit Unlooped(c.user, c.collateral, c.loan, repaid, withdrawn);
return true;
}
// ── Internals ────────────────────────────────────────────────────────
/// @dev Allowlisted, and never one of the addresses that would let a swap call move user funds or debt
function _validate(address collateral, address loan, address swapTarget, address targetToApprove)
internal
view
returns (address aCollateral, address spender)
{
ReserveDataLegacy memory rc = pool.getReserveData(collateral);
ReserveDataLegacy memory rl = pool.getReserveData(loan);
if (rc.aTokenAddress == address(0) || rl.variableDebtTokenAddress == address(0)) revert BadParams();
spender = _allowedSpender(swapTarget, targetToApprove);
address[8] memory forbidden = [
address(pool), collateral, loan,
rc.aTokenAddress, rc.variableDebtTokenAddress,
rl.aTokenAddress, rl.variableDebtTokenAddress,
address(this)
];
for (uint256 i = 0; i < forbidden.length; i++) {
if (swapTarget == forbidden[i] || spender == forbidden[i]) revert ForbiddenSwapTarget();
}
aCollateral = rc.aTokenAddress;
}
}
@openzeppelin/contracts/interfaces/IERC1363.sol
// 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);
}
@openzeppelin/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
@openzeppelin/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
@openzeppelin/contracts/token/ERC20/IERC20.sol
// 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);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.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)
}
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.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;
}
}
@openzeppelin/contracts/utils/StorageSlot.sol
// 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) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
@openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature is invalid.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
*
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Variant of {tryRecover} that takes a signature in calldata
*/
function tryRecoverCalldata(
bytes32 hash,
bytes calldata signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, calldata slices would work here, but are
// significantly more expensive (length check) than using calldataload in assembly.
assembly ("memory-safe") {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Variant of {recover} that takes a signature in calldata
*/
function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Parse a signature into its `v`, `r` and `s` components. Supports 65-byte and 64-byte (ERC-2098)
* formats. Returns (0,0,0) for invalid signatures.
*
* For 64-byte signatures, `v` is automatically normalized to 27 or 28.
* For 65-byte signatures, `v` is returned as-is and MUST already be 27 or 28 for use with ecrecover.
*
* Consider validating the result before use, or use {tryRecover}/{recover} which perform full validation.
*/
function parse(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch mload(signature)
// - case 65: r,s,v signature (standard)
case 65 {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Variant of {parse} that takes a signature in calldata
*/
function parseCalldata(bytes calldata signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch signature.length
// - case 65: r,s,v signature (standard)
case 65 {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
r := calldataload(signature.offset)
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
contracts/ObsidianProxyBase.sol
// 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 {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {ObsidianSwapExecutor} from "./ObsidianSwapExecutor.sol";
/**
* @title ObsidianProxyBase
* @notice What the Aave and Morpho loop proxies share: owner controls, the swap-router allowlist,
* the opening fee, and the swap itself (always run by a separate ObsidianSwapExecutor).
*
* Opening fee (loops only; closing, repaying and deleveraging are always free):
* - taken in the borrowed token, on the borrowed amount, before the swap, and sent straight to
* feeRecipient (nothing is kept in the proxy);
* - rate = defaultFeeBps, or a lower rate signed by feeSigner for this user, market and amounts
* (EIP-712 FeeQuote, valid until its deadline). A signature can only LOWER the fee: a leaked
* signing key can let someone pay less, never make anyone pay more or touch any funds;
* - never above MAX_FEE_BPS (hard-coded), and never above the maxFeeBps the user sends with the
* transaction (the rate the app showed them): raising the default cannot surprise a pending loop.
*/
abstract contract ObsidianProxyBase is ReentrancyGuard {
using SafeERC20 for IERC20;
// ── Owner and switches ──────────────────────────────────────────────
address public owner;
address public pendingOwner;
bool public paused;
// ── Swap routers ────────────────────────────────────────────────────
/// A proposed router can be activated TARGET_DELAY after its proposal, and only during the
/// TARGET_WINDOW that follows (an old proposal cannot be activated by surprise later).
uint256 public constant TARGET_DELAY = 2 days;
uint256 public constant TARGET_WINDOW = 7 days;
mapping(address => bool) public allowedSwapTargets;
mapping(address => uint256) public swapTargetActivatesAt; // proposed target -> earliest activation
ObsidianSwapExecutor public immutable executor;
// ── Opening fee ─────────────────────────────────────────────────────
uint256 public constant MAX_FEE_BPS = 20; // 0.20 % of the borrowed amount, ever
address public feeRecipient;
uint16 public defaultFeeBps;
address public feeSigner; // address(0) = no signed rate accepted (everyone pays defaultFeeBps)
/// A rate signed by feeSigner. deadline == 0: no quote, defaultFeeBps applies.
struct FeeQuote {
uint256 feeBps;
uint256 deadline;
bytes signature;
}
bytes32 private constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 public constant FEE_QUOTE_TYPEHASH = keccak256(
"FeeQuote(address user,bytes32 market,uint256 initialCollateralAmount,uint256 borrowAmount,uint256 feeBps,uint256 deadline)"
);
bytes32 private constant VERSION_HASH = keccak256("2");
bytes32 private immutable _NAME_HASH;
error NotOwner();
error Paused();
error BadParams();
error UntrustedSwapTarget();
error ForbiddenSwapTarget();
error TargetNotReady();
error InsufficientOutput();
error UnexpectedCallback();
error BadFeeQuote();
error FeeQuoteExpired();
error FeeTooHigh();
event SwapTargetProposed(address indexed target, uint256 activatesAt);
event SwapTargetActivated(address indexed target);
event SwapTargetRemoved(address indexed target);
event PausedSet(bool paused);
event OwnershipTransferStarted(address indexed newOwner);
event OwnershipTransferred(address indexed newOwner);
event FeeRecipientSet(address indexed recipient);
event FeeSignerSet(address indexed signer);
event DefaultFeeSet(uint256 feeBps);
event FeeCharged(address indexed user, address indexed token, uint256 amount, uint256 feeBps, address recipient);
/// @param core the lending protocol (Aave pool / Morpho Blue): never usable as a swap target
constructor(
string memory name,
address core,
address[] memory initialTargets,
ObsidianSwapExecutor _executor,
address _feeRecipient,
address _feeSigner,
uint16 _defaultFeeBps
) {
if (core.code.length == 0 || _executor.proxy() != address(this)) revert BadParams();
_NAME_HASH = keccak256(bytes(name));
executor = _executor;
owner = msg.sender;
_setFeeRecipient(_feeRecipient);
_setFeeSigner(_feeSigner);
_setDefaultFee(_defaultFeeBps);
// Seeded at deployment (public in the deploy tx, before anyone grants anything): no delay
for (uint256 i = 0; i < initialTargets.length; i++) {
_checkTargetShape(initialTargets[i], core, address(_executor));
allowedSwapTargets[initialTargets[i]] = true;
emit SwapTargetActivated(initialTargets[i]);
}
}
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
modifier whenNotPaused() {
if (paused) revert Paused();
_;
}
/// The lending protocol of this proxy
function _core() internal view virtual returns (address);
// ── Admin ────────────────────────────────────────────────────────────
function proposeSwapTarget(address target) external onlyOwner {
_checkTargetShape(target, _core(), address(executor));
uint256 at = block.timestamp + TARGET_DELAY;
swapTargetActivatesAt[target] = at;
emit SwapTargetProposed(target, at);
}
function activateSwapTarget(address target) external onlyOwner {
uint256 at = swapTargetActivatesAt[target];
if (at == 0 || block.timestamp < at || block.timestamp > at + TARGET_WINDOW) revert TargetNotReady();
delete swapTargetActivatesAt[target];
allowedSwapTargets[target] = true;
emit SwapTargetActivated(target);
}
function removeSwapTarget(address target) external onlyOwner {
allowedSwapTargets[target] = false;
delete swapTargetActivatesAt[target];
emit SwapTargetRemoved(target);
}
function setPaused(bool _paused) external onlyOwner {
paused = _paused;
emit PausedSet(_paused);
}
function transferOwnership(address newOwner) external onlyOwner {
pendingOwner = newOwner;
emit OwnershipTransferStarted(newOwner);
}
function acceptOwnership() external {
if (msg.sender != pendingOwner) revert NotOwner();
owner = pendingOwner;
pendingOwner = address(0);
emit OwnershipTransferred(owner);
}
function setFeeRecipient(address recipient) external onlyOwner {
_setFeeRecipient(recipient);
}
function setFeeSigner(address signer) external onlyOwner {
_setFeeSigner(signer);
}
function setDefaultFeeBps(uint16 feeBps) external onlyOwner {
_setDefaultFee(feeBps);
}
function _setFeeRecipient(address recipient) private {
if (recipient == address(0) || recipient == address(this)) revert BadParams();
feeRecipient = recipient;
emit FeeRecipientSet(recipient);
}
function _setFeeSigner(address signer) private {
feeSigner = signer;
emit FeeSignerSet(signer);
}
function _setDefaultFee(uint16 feeBps) private {
if (feeBps > MAX_FEE_BPS) revert FeeTooHigh();
defaultFeeBps = feeBps;
emit DefaultFeeSet(feeBps);
}
// ── Opening fee ──────────────────────────────────────────────────────
/// EIP-712 digest feeSigner signs: domain {name, version "2", chainId, verifyingContract = this proxy}
function feeQuoteDigest(
address user,
bytes32 market,
uint256 initialCollateralAmount,
uint256 borrowAmount,
uint256 feeBps,
uint256 deadline
) public view returns (bytes32) {
bytes32 domain = keccak256(abi.encode(DOMAIN_TYPEHASH, _NAME_HASH, VERSION_HASH, block.chainid, address(this)));
bytes32 structHash = keccak256(
abi.encode(FEE_QUOTE_TYPEHASH, user, market, initialCollateralAmount, borrowAmount, feeBps, deadline)
);
return keccak256(abi.encodePacked("\x19\x01", domain, structHash));
}
/// Rate and amount of msg.sender's opening fee. Reverts on an invalid or expired quote, and when
/// the rate would be above what the user accepted (maxFeeBps).
function _openFee(bytes32 market, uint256 initialCollateralAmount, uint256 borrowAmount, uint256 maxFeeBps, FeeQuote calldata q)
internal
view
returns (uint256 bps, uint256 fee)
{
bps = defaultFeeBps;
if (q.deadline != 0) {
if (block.timestamp > q.deadline) revert FeeQuoteExpired();
address signer = feeSigner;
(address got, ECDSA.RecoverError err,) = ECDSA.tryRecoverCalldata(
feeQuoteDigest(msg.sender, market, initialCollateralAmount, borrowAmount, q.feeBps, q.deadline), q.signature
);
if (signer == address(0) || err != ECDSA.RecoverError.NoError || got != signer) revert BadFeeQuote();
if (q.feeBps < bps) bps = q.feeBps; // a signed rate only ever lowers the fee
}
if (bps > maxFeeBps) revert FeeTooHigh();
fee = (borrowAmount * bps) / 10_000;
}
function _chargeFee(address user, address token, uint256 fee, uint256 bps) internal {
if (fee == 0) return;
address to = feeRecipient;
IERC20(token).safeTransfer(to, fee);
emit FeeCharged(user, token, fee, bps, to);
}
// ── Swap ─────────────────────────────────────────────────────────────
/// Allowlisted router and spender (protocol-specific forbidden addresses are checked by the proxy)
function _allowedSpender(address swapTarget, address targetToApprove) internal view returns (address spender) {
spender = targetToApprove == address(0) ? swapTarget : targetToApprove;
if (!allowedSwapTargets[swapTarget] || !allowedSwapTargets[spender]) revert UntrustedSwapTarget();
}
function _checkTargetShape(address target, address core, address exec) internal view {
if (target == address(0) || target == core || target == address(this) || target == exec || target.code.length == 0) {
revert ForbiddenSwapTarget();
}
}
/// Hands `amountIn` of tokenIn to the executor, which swaps it and returns everything it holds
/// of both tokens. Callers measure what they received and enforce their minimum.
function _swap(address tokenIn, address tokenOut, uint256 amountIn, address target, address spender, bytes memory data) internal {
IERC20(tokenIn).safeTransfer(address(executor), amountIn);
executor.swap(tokenIn, tokenOut, target, spender, data);
}
function _refund(address token, address user) internal {
uint256 bal = IERC20(token).balanceOf(address(this));
if (bal > 0) IERC20(token).safeTransfer(user, bal);
}
// No receive()/fallback: plain native-token transfers to the proxies revert.
}
contracts/ObsidianSwapExecutor.sol
// 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";
/**
* @title ObsidianSwapExecutor
* @notice Runs the swaps of ONE Obsidian loop proxy, from an address nobody has given anything to.
*
* The proxy checks the router (allowlist, forbidden targets), sends the swap input here and calls
* swap(). This contract approves the router's spender for exactly what it holds, calls the router,
* and sends everything it holds of both tokens back to the proxy.
*
* Why a separate contract: users give their approvals, Aave credit delegations and Morpho
* authorizations to the PROXY. The router's calldata is chosen by whoever sends the transaction, so
* it must never run from the proxy's address. From here, whatever the calldata does, it can only
* move this swap's own input: nobody ever approves, delegates to or authorizes this contract.
*
* Nothing stays here between transactions. Only the proxy that deployed the pair can call swap().
*/
contract ObsidianSwapExecutor {
using SafeERC20 for IERC20;
/// The only caller. Set at deployment to the proxy's address (computed before the proxy exists);
/// the proxy's constructor refuses an executor that does not point back to it.
address public immutable proxy;
error NotProxy();
error SwapFailed();
constructor(address _proxy) {
proxy = _proxy;
}
/// Swaps this contract's whole tokenIn balance through `target`, then returns all tokenOut and any
/// tokenIn left to the proxy. The proxy measures what it received and enforces the minimum.
function swap(address tokenIn, address tokenOut, address target, address spender, bytes calldata data) external {
if (msg.sender != proxy) revert NotProxy();
IERC20(tokenIn).forceApprove(spender, IERC20(tokenIn).balanceOf(address(this)));
(bool ok, bytes memory ret) = target.call(data);
if (!ok) {
if (ret.length > 0) {
assembly {
revert(add(ret, 32), mload(ret))
}
}
revert SwapFailed();
}
IERC20(tokenIn).forceApprove(spender, 0);
_sendBack(tokenOut);
_sendBack(tokenIn);
}
function _sendBack(address token) private {
uint256 bal = IERC20(token).balanceOf(address(this));
if (bal > 0) IERC20(token).safeTransfer(proxy, bal);
}
// No receive()/fallback: plain native-token transfers to this contract revert.
}
Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.