Verified contractExactMIT
InventoryV3PrincipalSandwichExecutor
Address0xf1610d71ea4e439eb35aab94d845a143a6b41cbb
- Balance
0 ETH
- Transactions
53
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,821,857
- Creation transaction
- 0xe84ab22cbe…7bf0405047
2 files
- src/InventoryV3PrincipalSandwichExecutor.solmain16.15 KB
- src/AtomicV2Arbitrage.sol6.79 KB
src/InventoryV3PrincipalSandwichExecutor.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20Minimal} from "./AtomicV2Arbitrage.sol";
interface IV3FactoryPrincipalSandwich {
function getPool(address tokenA, address tokenB, uint24 fee)
external
view
returns (address pool);
}
interface IV3PoolPrincipalSandwich {
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
}
interface IV3SwapCallbackPrincipalSandwich {
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
contract InventoryV3PrincipalSandwichExecutor is
IV3SwapCallbackPrincipalSandwich
{
bytes32 private constant EXECUTION_LOCK_SLOT =
keccak256("protector.principal-sandwich.execution-lock");
bytes32 private constant CALLBACK_STAGE_SLOT =
keccak256("protector.principal-sandwich.callback-stage");
bytes32 private constant CALLBACK_POOL_SLOT =
keccak256("protector.principal-sandwich.callback-pool");
bytes32 private constant CALLBACK_HASH_SLOT =
keccak256("protector.principal-sandwich.callback-hash");
struct Route {
bytes32 commitment;
bytes32 victimTransactionHash;
bytes32 anchorBlockHash;
address inventoryToken;
address quoteToken;
uint24 fee;
uint256 quoteAmountOut;
uint256 maxInventoryIn;
uint256 maxQuoteIn;
uint256 minimumQuoteProfit;
uint256 baselineInventory;
uint256 baselineQuote;
uint256 nonce;
uint256 deadline;
uint256 targetBlock;
uint160 frontSqrtPriceLimitX96;
uint160 backSqrtPriceLimitX96;
}
struct CallbackData {
bytes32 commitment;
address pool;
address tokenIn;
address tokenOut;
uint256 amountOut;
uint256 maxAmountIn;
uint8 stage;
}
address public owner;
address public immutable v3Factory;
uint256 public nextNonce = 1;
bytes32 public activeCommitment;
uint256 public activeInventorySpent;
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
event TokenWithdrawn(address indexed token, uint256 amount);
event PositionCancelled(bytes32 indexed commitment, uint256 indexed nonce);
event FrontRunExecuted(
bytes32 indexed commitment,
uint256 indexed nonce,
address indexed inventoryToken,
address quoteToken,
uint256 inventorySpent,
uint256 quoteAcquired
);
event BackRunExecuted(
bytes32 indexed commitment,
uint256 indexed nonce,
address indexed inventoryToken,
address quoteToken,
uint256 inventoryRestored,
uint256 quoteSpent,
uint256 quoteProfit
);
modifier onlyOwner() {
require(msg.sender == owner, "ONLY_OWNER");
_;
}
modifier nonReentrant() {
require(_transient(EXECUTION_LOCK_SLOT) == bytes32(0), "REENTRANCY");
_setTransient(EXECUTION_LOCK_SLOT, bytes32(uint256(1)));
_;
_setTransient(EXECUTION_LOCK_SLOT, bytes32(0));
}
constructor(address initialOwner, address initialV3Factory) {
require(
initialOwner != address(0) && initialV3Factory.code.length > 0,
"BAD_CONSTRUCTOR"
);
owner = initialOwner;
v3Factory = initialV3Factory;
}
function setOwner(address newOwner) external onlyOwner {
require(newOwner != address(0), "ZERO_OWNER");
emit OwnerChanged(owner, newOwner);
owner = newOwner;
}
function computeCommitment(Route calldata route)
public
view
returns (bytes32)
{
bytes32 identityHash = keccak256(
abi.encode(
route.victimTransactionHash,
route.anchorBlockHash,
route.inventoryToken,
route.quoteToken,
route.fee,
route.nonce,
route.targetBlock
)
);
bytes32 economicsHash = keccak256(
abi.encode(
route.quoteAmountOut,
route.maxInventoryIn,
route.maxQuoteIn,
route.minimumQuoteProfit,
route.baselineInventory,
route.baselineQuote,
route.deadline,
route.frontSqrtPriceLimitX96,
route.backSqrtPriceLimitX96
)
);
return keccak256(
abi.encode(
address(this),
block.chainid,
identityHash,
economicsHash
)
);
}
function frontRun(Route calldata route)
external
onlyOwner
nonReentrant
returns (uint256 inventorySpent, uint256 quoteAcquired)
{
require(activeCommitment == bytes32(0), "POSITION_ACTIVE");
_validateRoute(route);
require(route.nonce == nextNonce, "NONCE_MISMATCH");
_validateAnchor(route);
require(route.commitment == computeCommitment(route), "BAD_COMMITMENT");
require(
_balance(route.inventoryToken) == route.baselineInventory
&& _balance(route.quoteToken) == route.baselineQuote,
"BASELINE_CHANGED"
);
require(route.baselineInventory >= route.maxInventoryIn, "INVENTORY_LOW");
activeCommitment = route.commitment;
uint256 inventoryBefore = route.baselineInventory;
uint256 quoteBefore = route.baselineQuote;
(inventorySpent, quoteAcquired) = _frontExactOutput(route);
require(
inventorySpent == inventoryBefore - _balance(route.inventoryToken)
&& quoteAcquired == _balance(route.quoteToken) - quoteBefore
&& quoteAcquired == route.quoteAmountOut,
"FRONT_ACCOUNTING"
);
activeInventorySpent = inventorySpent;
nextNonce = route.nonce + 1;
emit FrontRunExecuted(
route.commitment,
route.nonce,
route.inventoryToken,
route.quoteToken,
inventorySpent,
quoteAcquired
);
}
function backRun(Route calldata route)
external
onlyOwner
nonReentrant
returns (uint256 quoteSpent, uint256 quoteProfit)
{
require(activeCommitment == route.commitment, "COMMITMENT_MISMATCH");
require(route.commitment != bytes32(0), "NO_POSITION");
_validateRoute(route);
_validateAnchor(route);
require(route.commitment == computeCommitment(route), "BAD_COMMITMENT");
uint256 inventorySpent = activeInventorySpent;
uint256 quoteBefore = _balance(route.quoteToken);
require(
_balance(route.inventoryToken)
== route.baselineInventory - inventorySpent
&& quoteBefore
>= route.baselineQuote + route.quoteAmountOut,
"POSITION_BALANCE_CHANGED"
);
require(
route.maxQuoteIn <= route.quoteAmountOut,
"QUOTE_LIMIT_EXCEEDS_ACQUIRED"
);
(quoteSpent,) = _backExactOutput(route, inventorySpent);
require(
_balance(route.inventoryToken) == route.baselineInventory,
"PRINCIPAL_NOT_RESTORED"
);
uint256 quoteAfter = _balance(route.quoteToken);
require(
quoteSpent <= route.quoteAmountOut
&& quoteAfter == quoteBefore - quoteSpent,
"QUOTE_ACCOUNTING"
);
quoteProfit = route.quoteAmountOut - quoteSpent;
require(quoteProfit >= route.minimumQuoteProfit, "QUOTE_PROFIT_FLOOR");
_clearPosition();
emit BackRunExecuted(
route.commitment,
route.nonce,
route.inventoryToken,
route.quoteToken,
inventorySpent,
quoteSpent,
quoteProfit
);
}
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external {
require(
_transient(EXECUTION_LOCK_SLOT) != bytes32(0)
&& _callbackStage() != 0,
"NO_CALLBACK"
);
CallbackData memory callback = abi.decode(data, (CallbackData));
require(
callback.commitment == activeCommitment
&& callback.stage == _callbackStage()
&& callback.pool == _callbackPool()
&& msg.sender == _callbackPool()
&& keccak256(data) == _callbackHash(),
"UNAUTHORIZED_CALLBACK"
);
(uint256 amountIn, uint256 amountOut) = _deltas(
callback.tokenIn,
callback.tokenOut,
amount0Delta,
amount1Delta
);
require(
amountOut == callback.amountOut
&& amountIn <= callback.maxAmountIn,
"CALLBACK_AMOUNTS"
);
_clearCallback();
_safeTransfer(callback.tokenIn, msg.sender, amountIn);
}
function cancelExpiredPosition(Route calldata route)
external
onlyOwner
nonReentrant
{
require(activeCommitment == route.commitment, "COMMITMENT_MISMATCH");
require(route.commitment == computeCommitment(route), "BAD_COMMITMENT");
require(block.timestamp > route.deadline, "POSITION_NOT_EXPIRED");
_clearPosition();
emit PositionCancelled(route.commitment, route.nonce);
}
function withdrawToken(address token, uint256 amount)
external
onlyOwner
nonReentrant
{
require(activeCommitment == bytes32(0), "POSITION_ACTIVE");
_safeTransfer(token, owner, amount);
emit TokenWithdrawn(token, amount);
}
function _frontExactOutput(Route calldata route)
private
returns (uint256 amountIn, uint256 measuredOut)
{
address pool = IV3FactoryPrincipalSandwich(v3Factory).getPool(
route.inventoryToken,
route.quoteToken,
route.fee
);
require(pool != address(0), "POOL_MISSING");
CallbackData memory callback = CallbackData(
route.commitment,
pool,
route.inventoryToken,
route.quoteToken,
route.quoteAmountOut,
route.maxInventoryIn,
1
);
return _exactOutput(callback, route.frontSqrtPriceLimitX96);
}
function _backExactOutput(Route calldata route, uint256 inventorySpent)
private
returns (uint256 amountIn, uint256 measuredOut)
{
address pool = IV3FactoryPrincipalSandwich(v3Factory).getPool(
route.quoteToken,
route.inventoryToken,
route.fee
);
require(pool != address(0), "POOL_MISSING");
CallbackData memory callback = CallbackData(
route.commitment,
pool,
route.quoteToken,
route.inventoryToken,
inventorySpent,
route.maxQuoteIn,
2
);
return _exactOutput(callback, route.backSqrtPriceLimitX96);
}
function _exactOutput(
CallbackData memory callback,
uint160 sqrtPriceLimitX96
) private returns (uint256 amountIn, uint256 measuredOut) {
require(
callback.amountOut <= uint256(type(int256).max),
"OUTPUT_OVERFLOW"
);
_setTransient(CALLBACK_STAGE_SLOT, bytes32(uint256(callback.stage)));
_setTransient(
CALLBACK_POOL_SLOT,
bytes32(uint256(uint160(callback.pool)))
);
bytes memory encoded = abi.encode(callback);
_setTransient(CALLBACK_HASH_SLOT, keccak256(encoded));
uint256 inputBefore = _balance(callback.tokenIn);
uint256 outputBefore = _balance(callback.tokenOut);
IV3PoolPrincipalSandwich(callback.pool).swap(
address(this),
callback.tokenIn < callback.tokenOut,
-int256(callback.amountOut),
sqrtPriceLimitX96,
encoded
);
require(
_callbackStage() == 0
&& _callbackPool() == address(0)
&& _callbackHash() == bytes32(0),
"CALLBACK_NOT_CONSUMED"
);
amountIn = inputBefore - _balance(callback.tokenIn);
measuredOut = _balance(callback.tokenOut) - outputBefore;
require(
amountIn <= callback.maxAmountIn
&& measuredOut == callback.amountOut,
"SWAP_ACCOUNTING"
);
}
function _deltas(
address tokenIn,
address tokenOut,
int256 amount0Delta,
int256 amount1Delta
) private pure returns (uint256 amountIn, uint256 amountOut) {
int256 inputDelta = tokenIn < tokenOut ? amount0Delta : amount1Delta;
int256 outputDelta = tokenIn < tokenOut ? amount1Delta : amount0Delta;
require(inputDelta > 0 && outputDelta < 0, "BAD_DELTAS");
amountIn = uint256(inputDelta);
amountOut = uint256(-outputDelta);
}
function _validateRoute(Route calldata route) private view {
require(
route.victimTransactionHash != bytes32(0)
&& route.anchorBlockHash != bytes32(0)
&& route.inventoryToken.code.length > 0
&& route.quoteToken.code.length > 0
&& route.inventoryToken != route.quoteToken
&& route.fee > 0
&& route.fee < 1_000_000
&& route.quoteAmountOut > 0
&& route.maxInventoryIn > 0
&& route.maxQuoteIn > 0
&& route.maxQuoteIn <= route.quoteAmountOut
&& route.minimumQuoteProfit > 0
&& route.nonce > 0
&& route.deadline >= block.timestamp
&& route.targetBlock > 0
&& route.frontSqrtPriceLimitX96 > 0
&& route.backSqrtPriceLimitX96 > 0,
"BAD_ROUTE"
);
}
function _validateAnchor(Route calldata route) private view {
require(route.targetBlock == block.number, "WRONG_BLOCK");
require(
blockhash(block.number - 1) == route.anchorBlockHash,
"ANCHOR_BLOCK_MISMATCH"
);
}
function _clearCallback() private {
_setTransient(CALLBACK_STAGE_SLOT, bytes32(0));
_setTransient(CALLBACK_POOL_SLOT, bytes32(0));
_setTransient(CALLBACK_HASH_SLOT, bytes32(0));
}
function _clearPosition() private {
activeCommitment = bytes32(0);
activeInventorySpent = 0;
}
function _callbackStage() private view returns (uint8) {
return uint8(uint256(_transient(CALLBACK_STAGE_SLOT)));
}
function _callbackPool() private view returns (address) {
return address(uint160(uint256(_transient(CALLBACK_POOL_SLOT))));
}
function _callbackHash() private view returns (bytes32) {
return _transient(CALLBACK_HASH_SLOT);
}
function _transient(bytes32 slot) private view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
function _setTransient(bytes32 slot, bytes32 value) private {
assembly ("memory-safe") {
tstore(slot, value)
}
}
function _balance(address token) private view returns (uint256) {
return IERC20Minimal(token).balanceOf(address(this));
}
function _safeTransfer(address token, address recipient, uint256 amount)
private
{
(bool success, bytes memory result) = token.call(
abi.encodeWithSelector(IERC20Minimal.transfer.selector, recipient, amount)
);
require(
success && (result.length == 0 || abi.decode(result, (bool))),
"TOKEN_TRANSFER_FAILED"
);
}
}
src/AtomicV2Arbitrage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface IERC20Minimal {
function balanceOf(address account) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount) external returns (bool);
}
interface IUniswapV2RouterMinimal {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
abstract contract OwnedArbitrageBase {
address public owner;
mapping(address => bool) public allowedRouter;
uint256 private locked = 1;
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
event RouterAllowed(address indexed router, bool allowed);
event TokenWithdrawn(address indexed token, uint256 amount);
modifier onlyOwner() {
require(msg.sender == owner, "ONLY_OWNER");
_;
}
modifier nonReentrant() {
require(locked == 1, "REENTRANCY");
locked = 2;
_;
locked = 1;
}
constructor(address initialOwner) {
require(initialOwner != address(0), "ZERO_OWNER");
owner = initialOwner;
}
function setOwner(address newOwner) external onlyOwner {
require(newOwner != address(0), "ZERO_OWNER");
emit OwnerChanged(owner, newOwner);
owner = newOwner;
}
function setRouter(address router, bool allowed) external onlyOwner {
require(router != address(0), "ZERO_ROUTER");
allowedRouter[router] = allowed;
emit RouterAllowed(router, allowed);
}
function withdrawToken(address token, uint256 amount) external virtual onlyOwner {
_safeTransfer(token, owner, amount);
emit TokenWithdrawn(token, amount);
}
function _validateRoute(
address asset,
address firstRouter,
address secondRouter,
address[] memory firstPath,
address[] memory secondPath,
uint256 deadline
) internal view {
require(allowedRouter[firstRouter], "FIRST_ROUTER_NOT_ALLOWED");
require(allowedRouter[secondRouter], "SECOND_ROUTER_NOT_ALLOWED");
require(firstPath.length >= 2 && secondPath.length >= 2, "SHORT_PATH");
require(firstPath[0] == asset, "FIRST_PATH_ASSET");
require(
firstPath[firstPath.length - 1] == secondPath[0],
"PATH_DISCONTINUITY"
);
require(secondPath[secondPath.length - 1] == asset, "SECOND_PATH_ASSET");
require(deadline >= block.timestamp, "EXPIRED");
}
function _runTwoRouterSwap(
address firstRouter,
address secondRouter,
address[] memory firstPath,
address[] memory secondPath,
uint256 amountIn,
uint256 minIntermediate,
uint256 minReturn,
uint256 deadline
) internal returns (uint256 returnedAmount) {
_forceApprove(firstPath[0], firstRouter, amountIn);
uint256[] memory firstAmounts = IUniswapV2RouterMinimal(firstRouter)
.swapExactTokensForTokens(
amountIn,
minIntermediate,
firstPath,
address(this),
deadline
);
uint256 intermediate = firstAmounts[firstAmounts.length - 1];
_forceApprove(secondPath[0], secondRouter, intermediate);
uint256[] memory secondAmounts = IUniswapV2RouterMinimal(secondRouter)
.swapExactTokensForTokens(
intermediate,
minReturn,
secondPath,
address(this),
deadline
);
returnedAmount = secondAmounts[secondAmounts.length - 1];
}
function _forceApprove(address token, address spender, uint256 amount) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, 0)
);
_callOptionalReturn(
token,
abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, amount)
);
}
function _safeTransfer(address token, address to, uint256 amount) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(IERC20Minimal.transfer.selector, to, amount)
);
}
function _callOptionalReturn(address token, bytes memory data) private {
(bool success, bytes memory result) = token.call(data);
require(
success && (result.length == 0 || abi.decode(result, (bool))),
"TOKEN_CALL_FAILED"
);
}
}
contract AtomicV2Arbitrage is OwnedArbitrageBase {
struct Route {
address asset;
address firstRouter;
address secondRouter;
address[] firstPath;
address[] secondPath;
uint256 amountIn;
uint256 minIntermediate;
uint256 minReturn;
uint256 minProfit;
uint256 deadline;
}
event ArbitrageExecuted(
address indexed asset,
address indexed firstRouter,
address indexed secondRouter,
uint256 amountIn,
uint256 returnedAmount,
uint256 profit
);
constructor(address initialOwner) OwnedArbitrageBase(initialOwner) {}
function execute(Route calldata route)
external
onlyOwner
nonReentrant
returns (uint256 profit)
{
require(route.amountIn > 0, "ZERO_INPUT");
require(route.minProfit > 0, "ZERO_MIN_PROFIT");
_validateRoute(
route.asset,
route.firstRouter,
route.secondRouter,
route.firstPath,
route.secondPath,
route.deadline
);
uint256 startingBalance = IERC20Minimal(route.asset).balanceOf(
address(this)
);
require(startingBalance >= route.amountIn, "INSUFFICIENT_INVENTORY");
uint256 returnedAmount = _runTwoRouterSwap(
route.firstRouter,
route.secondRouter,
route.firstPath,
route.secondPath,
route.amountIn,
route.minIntermediate,
route.minReturn,
route.deadline
);
uint256 endingBalance = IERC20Minimal(route.asset).balanceOf(address(this));
require(
endingBalance >= startingBalance + route.minProfit,
"MIN_PROFIT_NOT_MET"
);
profit = endingBalance - startingBalance;
emit ArbitrageExecuted(
route.asset,
route.firstRouter,
route.secondRouter,
route.amountIn,
returnedAmount,
profit
);
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.