Stack Overflow 社区您好,
我正在使用 Uniswap V3 和 ethers.js 在基础 Layer2 网络中交换代币。我已经使用approve函数成功批准了交易,但是当我尝试使用exactInputSingle执行交换时,我遇到了“警告!在合约执行期间遇到错误[执行恢复]”错误。
这是我的代码的简化版本:
import { getPoolImmutables, getPoolState } from './utils';
const { ethers } = require('ethers');
const { abi: IUniswapV3PoolABI } = require('@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json');
const SwapRouterABI = require('./routerabi.json');
const ERC20ABI = require('./abi.json');
const QUICKNODE_HTTP_ENDPOINT = 'https://sepolia.base.org';
const WALLET_ADDRESS = '';
const WALLET_SECRET = '';
const provider = new ethers.providers.JsonRpcProvider(QUICKNODE_HTTP_ENDPOINT);
const poolAddress = '0x7516D071921973fDFf29C071f42d21C227CF5740';
const swapRouterAddress = '0x050E797f3625EC8785265e1d9BDd4799b97528A1';
async function main() {
const poolContract = new ethers.Contract(poolAddress, IUniswapV3PoolABI, provider);
const immutables = await getPoolImmutables(poolContract);
const state = await getPoolState(poolContract);
const wallet = new ethers.Wallet(WALLET_SECRET);
const connectedWallet = wallet.connect(provider);
const swapRouterContract = new ethers.Contract(swapRouterAddress, SwapRouterABI, provider);
const inputAmount = 0.09;
const amountIn = ethers.utils.parseUnits(inputAmount.toString(), 18);
const approvalAmount = (amountIn * 10).toString();
const tokenContract0 = new ethers.Contract(immutables.token1, ERC20ABI, provider);
const approvalResponse = await tokenContract0
.connect(connectedWallet)
.approve(swapRouterAddress, approvalAmount);
const params = {
tokenIn: immutables.token1,
tokenOut: immutables.token0,
fee: immutables.fee,
recipient: WALLET_ADDRESS,
deadline: Math.floor(Date.now() / 1000) + 60 * 10,
amountIn: '0x013fbe85edc90000',
amountOutMinimum: 0,
sqrtPriceLimitX96: 0,
nounce: await connectedWallet.getTransactionCount(),
};
const transaction = swapRouterContract
.connect(connectedWallet)
.exactInputSingle(params, {
gasLimit: ethers.utils.hexlify(1000000),
gasPrice: ethers.utils.parseUnits('10', 'gwei'),
})
.then((transaction: any) => {
console.log(transaction);
});
}
main();
我怀疑我可能需要使用执行函数,但我不确定如何做到这一点或者这是否是正确的方法。
任何有关如何使用 ethers.js 在基础 Layer2 网络上的 Uniswap V3 池中正确执行交换的任何指导将不胜感激。
谢谢!
这是
params
结构
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
没有
nonce
(您输入了 nounce)。
另外
amountIn
请输入我们uint256
。你已经正确定义了
const amountIn = ethers.utils.parseUnits(inputAmount.toString(), 18);
但是在函数调用中你正在传递
amountIn: '0x013fbe85edc90000',
应该是
amountIn: amountIn