【问题标题】:Solidity event not showing up from Web3.jsSolidity 事件未从 Web3.js 显示
【发布时间】:2019-12-15 02:55:10
【问题描述】:

我正在尝试在Solidity 中设置一个事件并从Web3 收听它,但我不断收到null 的响应。这是我的代码:

合同的相关部分:

event NewUser(string userid);

function createNewUser(string memory _userId) public {
    // creating the user and setting it to a mapping 
    emit NewUser(_userId);
}

Javascript,来自Ethereum's参考:

async function watchEvents(contract) {
    contract.events.allEvents({
       fromBlock: 0
    },function(error, event){ console.log('all events?'); console.log(event); })
  .on('data', function(event){
     console.log(event); // same results as the optional callback above
  })
  .on('changed', function(event){
     // remove event from local database
  })
  .on('error', console.error);
}

使用另一个javascript 函数我可以看到正在创建新用户,并且交易在Ganache 上列为成功。但是watchEvents 方法会一直打印null

我错过了什么?

【问题讨论】:

  • 你是什么以太坊供应商? infura 还是自己的节点?
  • @YegorZaremba 我正在使用我自己的节点。另一个线程上的人告诉我null 的原因是事件仅由websockets 提供程序支持。我还没有测试过。

标签: ethereum solidity web3 web3js


【解决方案1】:

请连接到 websocket 提供程序以启用监听事件。要运行 websocket 提供程序,请使用以下标志运行节点:

--ws --wsport XXXX --wsorigins="*"

请注意,出于安全原因,您很可能希望允许*,而是更明确。

然后通过以下方式连接到它:

const web3 = new Web3(new Web3.providers.WebsocketProvider("ws://localhost:XXXX"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 2018-11-25
    • 2019-08-15
    • 2019-03-28
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多