Go-Ethereum
如何從區塊鏈中提取所有事件日誌?
我正在嘗試從區塊鏈中提取所有事件日誌,這就是我在智能合約中呼叫事件的方式。
function rateBook(uint id, uint rating, string comments) onlyMember { if (id > numBooks || rating < 1 || rating > 5) { throw; } Rate(id, msg.sender, rating, comments, now); }
我通過測試案例觸發了 Rate Event 幾次,然後嘗試獲取所有記錄的事件並像這樣編寫測試案例 -
it('should allow a member to rate multiple times', async function() { await lms.addBook("1984", "Orwell", "Classic Publishers", "image url", "description", "genre"); let reviews = [ {bookId: 1, rating: 5, comments: 'A must-read classic!'}, {bookId: 1, rating: 4, comments: 'Great Book, I loved it'}, {bookId: 1, rating: 3, comments: 'Decent book, not my types though'}, {bookId: 1, rating: 2, comments: 'Hell No!, Boring book'}, ] for (let i = 0; i <= 3; i++) { await lms.rateBook(reviews[i].bookId, reviews[i].rating, reviews[i].comments); } let rateEvent = lms.Rate({}, {fromBlock: 0, toBlock: 'latest'}); let i = 0; rateEvent.watch(function(err, result) { rateEvent.stopWatching(); if (!err) { assert.equal(reviews[i].bookId, result.args.bookId); assert.equal(reviews[i].rating, result.args.rating); assert.equal(reviews[i].comments, result.args.comments); assert.equal(result.args.reviewer, accounts[0]); i++; } }); });
但是,在 Web3JS文件中,我發現了一個名為 - web3.eth.filter 的函式。我嘗試使用過濾器實現,但它不起作用,然後使用上面測試案例中所示的 watch 函式。它工作正常,但我不確定這是否是正確的方法,它會獲取所有記錄的事件還是僅獲取在測試案例時觸發的事件?
請指教。
由於您指定
{fromBlock: 0, toBlock: 'latest'}
,您的程式碼將擷取Rate
合約自創建以來記錄的所有事件,並在呼叫函式lms
時擷取最新的區塊。watch
它只會檢索由該特定合約記錄的事件,而不是任何其他事件。