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

thirdweb中实现交易执行前等待授权的技术问题求助

解决thirdweb中授权未完成就执行后续交易的问题

你的代码核心问题是:approveTokens函数仅发送了授权交易就返回true,但此时交易还未被区块链确认,授权并未实际生效。后续的兑换交易会在授权无效的情况下发起,导致执行失败。

核心修复方案

调用sendTransaction后,必须使用wait()方法等待交易被链上确认,确保授权生效后再执行后续操作。同时可以添加授权额度检查,避免重复发起不必要的授权交易。

修改后的授权函数

const approveTokens = async () => {
  try {
    console.log("Approving tokens...");

    // 可选:先检查当前授权额度,避免重复授权
    const currentAllowance = await tokenContract.call("allowance", [
      walletAddress, // 当前用户的钱包地址
      CONTRACT_ADDRESS // 需要授权的合约地址
    ]);
    
    // 若当前授权额度已满足需求,直接返回成功
    if (BigInt(currentAllowance) >= BigInt(tokenAmount)) {
      console.log("Already approved enough tokens");
      return true;
    }

    const transaction = prepareContractCall({
      contract: tokenContract,
      method: "function approve(address spender, uint256 amount)",
      params: [CONTRACT_ADDRESS, tokenAmount],
    });

    // 发送交易并等待链上确认
    const transactionResult = await sendTransaction(transaction);
    const receipt = await transactionResult.wait();
    
    // 验证交易是否执行成功
    if (receipt.status === 1) {
      console.log("Approval transaction confirmed on chain");
      return true;
    } else {
      console.error("Approval transaction failed");
      return false;
    }
  } catch (error) {
    console.error("Error approving tokens:", error);
    return false;
  }
};

兑换交易函数(可优化等待确认逻辑)

const swapTokenToEth = async () => {
  try {
    const transaction = prepareContractCall({
      contract: dexContract,
      method: "function swapTokenToEth(uint256 _tokensSold)",
      params: [tokenAmount],
    });

    const transactionResult = await sendTransaction(transaction);
    await transactionResult.wait(); // 同样等待兑换交易上链确认
    console.log("Swap transaction confirmed on chain");
    return true;
  } catch (error) {
    console.error("Error in swapTokenToEth:", error);
    return false;
  }
};

调用函数(保持原逻辑即可)

const executeSwap = async () => {
  try {
    const approved = await approveTokens();
    if (approved) {
      console.log("Proceeding with swap after approval...");
      await swapTokenToEth();
    } else {
      console.error("Approval failed, swap aborted");
    }
  } catch (error) {
    console.error("Error executing swap:", error);
  }
};

关键细节说明

  • transactionResult.wait()默认等待1个区块确认,也可传入参数指定确认数(如wait(3)),确保交易完全生效。
  • 检查receipt.status === 1可以排除交易发送成功但执行失败的情况(比如gas不足)。
  • 授权额度检查能减少不必要的链上交易,提升用户体验并节省gas费用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 05:22:38