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

使用Ethers调用智能合约withdrawFunds函数时如何正确传参?

解决方案

你的问题出在调用withdrawFunds时的参数传递方式错误,合约函数要求传入一个uint256类型的wei数量,而不是通过data字段传递字符串。

修正后的代码

async function withdrawFunds() {
  console.log(`Withdrawing Funds...`);
  if (typeof window.ethereum !== "undefined") {
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();
    const contract = new ethers.Contract(contractAddress, abi, signer);
    // 把0.5 ETH转换为wei(合约参数要求uint256类型,单位是wei)
    const amountToWithdraw = ethers.utils.parseEther("0.5");
    // 直接将转换后的数值作为参数传入合约函数
    const transactionResponse = await contract.withdrawFunds(amountToWithdraw);
    // 可选:等待交易上链确认
    await transactionResponse.wait();
    console.log("提款交易已确认");
  }
}

关键要点

  • 合约的withdrawFunds函数需要的是uint256类型的提款金额(wei单位),不能直接传入字符串"0.5",必须用ethers.utils.parseEther()将ETH金额转换为对应的wei数值。
  • 调用合约函数时,参数要按ABI定义的顺序直接传递,而不是放在对象里(对象通常用来传递交易附加参数,比如存款时的value字段)。
  • 由于合约函数的stateMutability是nonpayable,调用时不需要传value参数,避免额外转账。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:05:27