You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现UniswapV3多跳兑换机器人的动态余额止损退出逻辑

解决方案:动态计算余额阈值适配任意初始余额

要解决硬编码阈值无法适配不同初始余额的问题,只需要在循环启动前获取当前账户的初始DAI余额,动态计算出初始余额90%的阈值,再用这个阈值作为停止条件即可。以下是修改后的完整代码:

const { expect } = require("chai");
const { ethers, network} = require('hardhat')


const DAI = '0x6B175474E89094C44Da98b954EedeAC495271d0F';
const DAI_WHALE = '0xF977814e90dA44bFA03b6295A0616a897441aceC';

function waitforme(milisec) {
  return new Promise(resolve => {
      setTimeout(() => { resolve('') }, milisec);
  })
}

describe("SwapExamples", () => {
  let swapExamples
  let dai
  let whale
  let accounts
  before(async () => {
    
    const SwapExamples = await ethers.getContractFactory("SwapExamples")
    swapExamples = await SwapExamples.deploy()
    await swapExamples.deployed()

    dai = await ethers.getContractAt("IERC20", DAI)
    whale = await ethers.getSigner(DAI_WHALE)
    accounts = await ethers.getSigners()

    await network.provider.request({
      method: "hardhat_impersonateAccount",
      params: [DAI_WHALE],
    })

    
  })

  it("unlock account", async () => {
    const amount = 100n * 10n ** 18n

    console.log("DAI balance of whale", await dai.balanceOf(DAI_WHALE))
    expect(await dai.balanceOf(DAI_WHALE)).to.gte(amount)

    await dai.connect(whale).transfer(accounts[0].address, amount)

    console.log(
      "DAI balance of account",
      await dai.balanceOf(accounts[0].address)
    )
  })

it("swapExactInputMultihop", async () => {
  // 获取初始DAI余额,作为阈值计算基准
  const initialBalance = await dai.balanceOf(accounts[0].address)
  // 计算初始余额的90%作为停止阈值(用BigInt运算避免精度丢失)
  const thresholdBalance = initialBalance.mul(90n).div(100n)
 
  for (let i = 0; i < 111; i++) {
    // 用动态阈值替换硬编码数值
    if ( await dai.balanceOf(accounts[0].address) <= thresholdBalance) { break;}
    const amountIn = await dai.balanceOf(accounts[0].address)

    await dai.approve(swapExamples.address, amountIn)
    // 执行多跳兑换
    await swapExamples.swapExactInputMultihop(amountIn)
    
    console.log("DAI balance", await dai.balanceOf(accounts[0].address))
    
    await waitforme(1000);  
} 
}).timeout(500000)
})

关键修改说明

  1. 获取初始余额:在循环启动前读取账户当前的DAI余额,作为后续阈值计算的基准值
  2. 动态计算阈值:使用mul(90n).div(100n)完成BigInt类型的百分比计算,确保18位精度的代币数值不会出现精度丢失问题
  3. 替换判断条件:将原硬编码的固定数值替换为动态计算的thresholdBalance,实现任意初始余额场景下的自动适配

内容的提问来源于stack exchange,提问作者Shuayb Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 01:45:34