0

So, I have been reading through A LOT of pages about events in Solidity and how to interact with them on frontend but I am still pretty new to this and it seems like there have been multiple changes, since many sites I saw used outdated methods to watch for Solidity event changes. I had it working at some point but it then suddenly stopped working for no apparent reason.

I tried this with all of my 4 Solidity events, for simplicity sake, I will only show my example with one method

pragma solidity ^0.5.0;

contract Platoonfactory {
    event PlatoonCreated(address owner, uint256 platoonId);

    uint256 public currentPlatoonID = 1;
    uint256 public contractBalance = address(this).balance;

    /**
     * A platoon has atleast one truck driving in front and 0..n trucks following
     */
    struct Platoon {
        uint256 platoonId;
        address payable owner;
        uint costPerMinute;
        uint startDate;
        uint endDate;
        // participants contains all joined trucks inside this platoon
        mapping(uint /* index */ => TruckInPlatoon) participants;
        uint participantsSize;
    }

    /**
     * A TruckInPlatoon struct describes exactly one truck inside a platoon *besides* the leaders
     */
    struct TruckInPlatoon {
        uint platoonId;
        address truckOwner;
        uint startDate;
        uint allowedParticipationUntilDate;
        uint payedAmountOfWei;
    }

    // map the owner of a platoon to the unique ID
    mapping(address => uint) public platoonOwners;
    // map the unique ID to each platoon
    mapping(uint => Platoon) public platoons;


    /**
     * Create a new platoon with required cost to join and the amount of hours in which this platoon is available
     */
    function createPlatoon(uint cpm, uint endDate) public returns (uint) {
        require(platoonOwners[msg.sender] == 0, "You have already started a platoon");
        require(endDate >= 1, "Platoon must at least be available for one hour");

        // create a new platoon and push it to the storage
        platoons[currentPlatoonID] = Platoon({platoonId: currentPlatoonID, owner: msg.sender, costPerMinute: cpm, startDate: now, endDate: (now + endDate*3600), participantsSize:0});
        platoonOwners[msg.sender] = currentPlatoonID;

        //Increment current ID
        currentPlatoonID++;

        // fire event
        emit PlatoonCreated(msg.sender, currentPlatoonID);
        return currentPlatoonID - 1;
    }

}

JavaScript:

App = {
    contracts: {},
    address: "",
    web3js: null,
    PlatoonContract: null,

    init: function () {
        return App.initWeb3();
    },

    initWeb3: function () {
        if (typeof web3 !== 'undefined') {
            App.web3js = new Web3(web3.currentProvider);
        } else {
            App.web3js = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
        }
        return App.initHTML();
    },

    initHTML: function () {
        App.web3js.eth.getAccounts((err, accounts) => {
            if (!err) {
                document.getElementById("account-id").innerHTML = accounts[0];
                App.address = accounts[0];
            } else {
                console.log(err);
            }
        });
        return App.initContract();
    },

    initContract: function () {
        $.getJSON('../build/contracts/Platoonfactory.json', function (data) {
            var PlatoonArtifact = data;
            App.contracts.Platoonfactory = TruffleContract(PlatoonArtifact);
            App.contracts.Platoonfactory.setProvider(web3.currentProvider);

            App.contracts.Platoonfactory.deployed().then(function (instance) {
                App.PlatoonContract = instance;
                return App.listenFor();
            });
        });
    },

    listenFor: function () {
        App.PlatoonContract.PlatoonCreated({}, {fromBlock:0, toBlock: 'latest'}).watch(function(err, result) {
            if (err) {
                console.log(err);
            }

            if (result) {
                console.log(result);
                document.getElementById("platoonList").innerText = "ID: " + res.args.platoonId.c[0] + " Owner: " + res.args.owner;
            }
        });
        return App.bindEvents();
    },

    bindEvents: function () {
        $("#btnCreatePlatoon").click(event => {
            event.preventDefault();
            let cpm = document.getElementById("costPerMinute").value;
            let duration = document.getElementById("hoursAvailable").value;
            App.PlatoonContract.createPlatoon(cpm, duration);
        });

        $("#btnContractBalance").click(event => {
            event.preventDefault();
            App.PlatoonContract.contractBalance().then(result => console.log(result.c[0]));
        });
    },

};

$(function () {
    $(window).load(function () {
        App.init();
    });
});

The HTML shouldn't matter in this case. I have been trying to fix this since nearly a week and started to get crazy about this already since there are so many outdated posts. I would be extremely thankfull if one could finally find what's going wrong. I tested the Solidity code in Remix and all methods worked fine and Ganache even recognized the events at the Contract Tab, the error seems to lay at the point I am attaching the listener.

ADDITION: I am using Truffle, Ganache and Metamask to test my DApp

4
  • What version of web3 are you using? Is Metamask connected to Ganache? Is transaction executed successfully? I'd start commenting out or disable stuff until thing start to work again.
    – Ismael
    Commented Sep 24, 2019 at 17:30
  • @Ismael thanks for responding. I am using web3 @ 2.0.0-alpha.1 which is the current pre-release. Metamask is connected to Ganache and transactions all succeed and can be seen in Ganache. I already disabled everything to the core of executing that function and listening to the event. At this point I have no idea what to exclude additionally. Could you try to run my code at your build to verify there is no error in my configurations?
    – Xore
    Commented Sep 25, 2019 at 22:50
  • Your code appears to be correct. You are using an alpha version of web3 so I'd start trying a more stable version.
    – Ismael
    Commented Sep 26, 2019 at 16:03
  • @Ismael I fixed the code by removing the toBlock parameter. I am not completely sure why Metamask didn't quite like that but at least it's working now
    – Xore
    Commented Sep 29, 2019 at 11:33

1 Answer 1

0

So I fixed it finally! It seems like the 2nd parameter in the event handler which which specified fromBlock and toBlock is not compatible with Metamask. It worked after I removed the toBlock parameter. Working snippet:

App.PlatoonContract.PlatoonCreated({}, {fromBlock:0}).watch(function(err, result) {
        if (err) {
            console.log(err);
        }

        if (result) {
            console.log(result);
            document.getElementById("platoonList").innerText = "ID: " + res.args.platoonId.c[0] + " Owner: " + res.args.owner;
        }
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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