环境是:我想实现跟V3的池子进行兑换代币,不需要走路由协议。请大佬们指点指点。 应该有大佬也有做过,求大佬们给个案例哈 在期间会碰到一些问题,比如兑换的时候,WETH是18位小数点,USDC是6位小数点,这些问题怎么解决呢
pragma solidity ^0.8.0;
import "forge-std/Test.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import "@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3Pool.sol";
import "@uniswap/v3-core/contracts/libraries/TickMath.sol";
contract UniswapV3SinglePoolSwap is Test {
Vm cheats = Vm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D);
IUniswapV3Pool V3_USDC_ETH_Pool = IUniswapV3Pool(0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640); // USDC/ETH Pool
IERC20 IUSDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDC 6位小数点
IERC20 IWETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // WETH 18位小数点
event string_uint_log(string, uint256);
event Swap(address indexed sender, uint256 amountIn, uint256 amountOut);
function setUp() public {
cheats.createSelectFork("ETH"); // fork ETH主网,
deal(address(IUSDC), address(this), 100 ether);
deal(address(IWETH), address(this), 100 ether);
}
function testexchange() public {
uint256 amountIn = 1e18;
// Get current tick
(, int24 tick,,,,,) = V3_USDC_ETH_Pool.slot0();
// Calculate amount out
uint160 sqrtPriceX96 = TickMath.getSqrtRatioAtTick(tick);
uint256 amountOut = FullMath.mulDiv(amountIn, sqrtPriceX96, 2 ** 96);
uint256 amountOutMax = FullMath.mulDiv(amountOut, 9970, 10000); // 0.3% slippage
// Approve the router to spend USDC tokens
IERC20(IUSDC).approve(address(V3_USDC_ETH_Pool), amountIn);
// Swap USDC for WETH in the Uniswap V3 pool
(uint256 amount0, uint256 amount1) =
V3_USDC_ETH_Pool.swap(address(this), true, amountIn, amountOutMax, abi.encode(""));
// Get the amount of WETH received
uint256 amountOutReceived = amount1 > 0 ? amount1 : amount0;
// Approve the router to spend WETH tokens
IERC20(IWETH).approve(address(V3_USDC_ETH_Pool), amountOutReceived);
// Swap WETH for USDC in the Uniswap V3 pool
V3_USDC_ETH_Pool.swap(address(this), false, int256(amountOutReceived), 0, abi.encode(""));
}
}