使用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
相关产品推荐
相关产品推荐

