精确数量交换

JAMM DEX支持两种精确数量交换模式:精确输入(Exact Input)和精确输出(Exact Output)。这两种模式满足不同的交易需求,让用户能够精确控制交换的输入或输出数量。

精确输入交换 (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