Contract Name:
DhaiSwapper
Contract Source Code:
<i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @notice Minimal interfaces for Uniswap v3 SwapRouter and WETH9 to avoid external deps
interface ISwapRouterV3 {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
}
interface IWETH9Minimal {
function deposit() external payable;
function approve(address spender, uint256 value) external returns (bool);
}
/// @title ETH->DAI Uniswap v3 Swapper
/// @notice Single-function contract: accepts native ETH, swaps for DAI via Uniswap v3, sends DAI to caller
contract DhaiSwapper {
ISwapRouterV3 public immutable swapRouter;
address public immutable WETH9;
address public immutable DAI;
uint24 public immutable poolFee;
event Swap(address indexed sender, uint256 amountIn, uint256 amountout);
constructor(address _swapRouter, address _weth9, address _dai, uint24 _poolFee) {
require(_swapRouter != address(0) && _weth9 != address(0) && _dai != address(0), "ZERO_ADDR");
swapRouter = ISwapRouterV3(_swapRouter);
WETH9 = _weth9;
DAI = _dai;
poolFee = _poolFee; // e.g. 500, 3000, or 10000
// set a one-time infinite approval so swaps don't waste gas re-approving
require(IWETH9Minimal(WETH9).approve(address(swapRouter), type(uint256).max), "APPROVE_INIT_FAIL");
}
/// @notice Swap exact ETH sent for DAI and send DAI to msg.sender
/// @param minDaiOut Minimum DAI expected (slippage protection)
/// @return amountOut The amount of DAI received
function swapExactEthForDai(uint256 minDaiOut) external payable returns (uint256 amountOut) {
amountOut = _swapExactEthForDaiTo(msg.sender, msg.value, minDaiOut);
}
/// @dev Internal helper used by both the explicit function and the receive() handler
function _swapExactEthForDaiTo(address recipient, uint256 amountIn, uint256 minOut)
internal
returns (uint256 amountOut)
{
require(amountIn > 0, "NO_ETH");
IWETH9Minimal(WETH9).deposit{value: amountIn}();
amountOut = swapRouter.exactInputSingle(
ISwapRouterV3.ExactInputSingleParams({
tokenIn: WETH9,
tokenOut: DAI,
fee: poolFee,
recipient: recipient,
deadline: block.timestamp,
amountIn: amountIn,
amountOutMinimum: minOut,
sqrtPriceLimitX96: 0
})
);
emit Swap(recipient, amountIn, amountOut);
}
/// @notice Auto-swap on plain ETH receives and send DAI back to the sender
receive() external payable {
if (msg.value == 0) return;
_swapExactEthForDaiTo(msg.sender, msg.value, 0);
}
}