精确数量交换
精确输入交换 (Exact Input)
基本概念
实现方式
代币到代币的精确输入
async function swapExactTokensForTokens(
tokenIn,
tokenOut,
amountIn,
slippagePercent,
userAddress,
signer
) {
const router = new ethers.Contract(ROUTER_ADDRESS, routerABI, signer);
// 1. 查询预期输出
const path = [tokenIn, tokenOut];
const fees = [100]; // 1%费率
const amounts = await router.getAmountsOut(amountIn, path, fees);
const expectedOutput = amounts[1];
// 2. 计算最小输出(滑点保护)
const slippageBps = Math.floor(slippagePercent * 100); // 转换为基点
const amountOutMin = expectedOutput.mul(10000 - slippageBps).div(10000);
// 3. 设置截止时间
const deadline = Math.floor(Date.now() / 1000) + 60 * 20; // 20分钟
// 4. 执行交换
const tx = await router.swapExactTokensForTokens(
amountIn,
amountOutMin,
path,
fees,
userAddress,
ethers.constants.AddressZero, // 无推荐人
deadline
);
console.log("精确输入交换已提交:", tx.hash);
const receipt = await tx.wait();
return {
transactionHash: tx.hash,
blockNumber: receipt.blockNumber,
expectedOutput,
actualOutput: await getActualOutput(receipt) // 从事件中解析实际输出
};
}JU到代币的精确输入
代币到JU的精确输入
精确输出交换 (Exact Output)
基本概念
实现方式
代币到代币的精确输出
JU到代币的精确输出
代币到JU的精确输出
高级功能
多跳精确交换
批量精确交换
价格计算和预览
精确输入价格预览
精确输出价格预览
价格影响计算
实用工具函数
交换结果解析
滑点计算器
最佳实践
1. 交换模式选择
2. 动态滑点调整
3. 交换前验证
Last updated