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

无法通过ReactJS调用智能合约public pure函数求解决办法

修改建议

1. 修正参数传递语法

你的参数写法存在冗余和潜在类型问题:

  • 移除多余的包裹语法,把 {sellerinfo}['sellerinfo'] 改为 sellerinfo['sellerinfo'](若sellerinfo是存储地址的对象)
  • 确保quantity1是数字类型:合约函数接收uint类型参数,若quantity1是字符串,需用parseInt(quantity1)或Number(quantity1)转换为数字

2. 仅用call()调用pure函数

合约中的_3_1getMessageHash是public pure函数,这类函数不修改链上状态,无需发送交易,只能通过call()调用。send()用于触发修改状态的交易,会消耗gas,且pure函数不允许通过交易调用,因此直接删掉send()相关的代码。

3. 处理异步调用逻辑

call()是异步操作,直接console.log会输出Promise对象,需用async/await或.then()获取实际返回值,同时建议添加错误捕获。

修改后的完整代码

async function sign_1(e){
  e.preventDefault();
  
  try {
    // 整理参数,确保类型匹配
    const toAddress = sellerinfo['sellerinfo'];
    const amount = parseInt(quantity1);
    const message = 'test';
    const nonce = 0;

    // 调用pure函数并获取结果
    const messageHash = await project.methods._3_1getMessageHash(toAddress, amount, message, nonce).call();
    console.log('消息哈希:', messageHash);
  } catch (err) {
    console.error('调用失败:', err);
  }
}

额外检查项

  • 确认合约ABI中包含_3_1getMessageHash函数的定义,否则project.methods无法识别该函数
  • 验证sellerinfo['sellerinfo']是有效的以太坊地址(0x开头的42位字符串)
  • 若合约中uint对应以太币单位(如wei),需确保quantity1转换后的值符合合约逻辑(比如传入的是以太币数量时,需乘以10**18)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:55:19