区块链众筹应用调用getDonators函数参数缺失错误求助
区块链众筹应用合约调用错误排查与解决
错误信息
Uncaught (in promise) Error: Function "getDonators" requires 1 arguments, but undefined were provided.
Expected function signature: contract.call("getDonators", _id: BigNumberish): Promise<string[], BigNumber[]>
前端调用代码
const getDonations = async (pId) => { const donations = await contract.call('getDonators', pId); // 报错位置 const numberOfDonations = donations[0].length; const parsedDonations = []; for(let i = 0; i < numberOfDonations; i++) { parsedDonations.push({ donator: donations[0][i], donation: ethers.utils.formatEther(donations[1][i].toString()) }) } return parsedDonations; }
Solidity合约函数代码
function getDonators(uint256 _id) view public returns (address[] memory, uint256[] memory) { return (campaigns[_id].donators, campaigns[_id].donations); }
问题分析与解决方案
你的参数传递逻辑本身没问题,报错核心原因是调用getDonations函数时没有传入有效的pId参数,导致pId为undefined,进而传给getDonators的参数不符合要求。
解决步骤:
- 先检查所有调用
getDonations的位置,确保传入了合法的项目ID(必须是uint256类型的数值,比如整数或ethers的BigNumber实例)。 - 推荐改用更直观的合约函数调用方式(和你调用
donateToCampaign的写法一致),避免call方法的传参歧义,同时优化代码可读性:const getDonations = async (pId) => { // 直接通过合约实例调用函数,解构返回值更清晰 const [donators, donations] = await contract.getDonators(pId); // 用map替代for循环简化逻辑 return donators.map((donator, index) => ({ donator, donation: ethers.utils.formatEther(donations[index].toString()) })); } - 可选:在
getDonations开头加参数校验,提前拦截无效输入:const getDonations = async (pId) => { if (!pId || isNaN(Number(pId))) { throw new Error('请传入有效的项目ID'); } const [donators, donations] = await contract.getDonators(pId); return donators.map((donator, index) => ({ donator, donation: ethers.utils.formatEther(donations[index].toString()) })); }
内容的提问来源于stack exchange,提问作者Tanishq-Dadhich
相关产品推荐
相关产品推荐

