3

I'm trying to extract all event logs from the blockchain, this is how I called an Event in the smart contract.

function rateBook(uint id, uint rating, string comments) onlyMember {
    if (id > numBooks || rating < 1 || rating > 5) {
        throw;
    }
    Rate(id, msg.sender, rating, comments, now);
}

I fired Rate Event few times through test case then tried to fetch all logged events and wrote the test case like this -

    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++;
            }
        });
    });

However, on Web3JS documentation, I found a function named - web3.eth.filter. I tried implementing using the filter but It did not work, then used the watch function as shown in the test case above. It works fine but I'm not sure if this is the correct way and it fetches all events logged or only those which are fired at the time of test case?

Please advise.

2

Since you specified {fromBlock: 0, toBlock: 'latest'}, your code will catch all Rate events logged by the contract lms since its creation, to the latest block mined when the watch function is called.

It will only retrieve the events logged by that specific contract, not any other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.