Solidity事件未从Web3.js中显示

问题描述 投票:1回答:1

我正在尝试在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

我想念的是什么?

ethereum solidity web3 web3js
1个回答
0
投票

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

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

请注意,出于安全原因,您很可能NOT希望允许*,但要更加明确。

然后通过类似的方法连接到它:

const web3 = new Web3(new Web3.providers.WebsocketProvider("ws://localhost:XXXX"))
© www.soinside.com 2019 - 2024. All rights reserved.