使用 ethers.js 多邊形監聽智能合約的所有事件
我想知道的是,是否有一種方法可以持續監聽單個合約並實時獲取所有發出的事件。我現在能找到的是在特定契約中一次只監聽一個事件的方法。更準確地說:我在多邊形測試網(孟買)中部署了一個智能合約,這是一個可升級的合約,它連接到其他合約,並且像往常一樣發出我想要擷取的事件。我使用 Alchemy 作為提供者。我不清楚的另一個事實是,為什麼在 polyscan 中事件中的方法被列為類似
0x40c10f19
而不是名稱。在向你們詢問如何執行此操作之前,我也嘗試使用此程式碼:`
filter = { address: CONTRACT_ADDRESS, topics:[ utils.id("MarketItemCreated(address,uint256,address,uint256,uint256)"), utils.id("Transfer(address,address,address,uint256,uint256)") ] } provider.on(filter,(log,event)=>{ console.log(log) console.log(event) })
But when I actually interact with the contract I can't capture the events (the console.log does not display anything) but I can see the event in polyscan. I also try with by filtering only with the address without specifying the topic and I also try with
proverer.once` 但沒辦法。我究竟做錯了什麼?或者,我錯過了什麼?每一個提示或貢獻都值得讚賞:)
`Hi developer advocate at Chainstack here!
Web3.js
has a subscriprion method to easily to that!const Web3 = require("web3"); const node_url = "CHAINSTACK_WSS_URL"; const web3 = new Web3(node_url) var logs = web3.eth.subscribe("logs", { address: "CONTRACT_ADDRESS", topics: [] }, function(error, result) { if (!error) console.log(result); }) .on("connected", function(subscriptionId) { console.log(subscriptionId); }) .on("data", function(log) { console.log(log); }) .on("changed", function(log) {});
Remember that you need a web-socket endpoint to use subscriptions in
web3.js
.You can find more examples in the Chainstack docs API reference, and in the web3.js docs.
I hope this helps you!`