Programming Project - Phase 1

@dan-i

FIXED !! I did some more digging and solved the problem. For some reason the server was not updating the contract changes. Easy fix:

  1. Inspect page
  2. Right click the Chrome/Brave refresh button.
  3. Click “Hard Reload”

What a relief :sweat_smile:

Thanks for the help though!

1 Like

submit1

@filip Thanks for your great lessons so far. I’ve got my first phase to work. UI could use some polishing but that can wait for later. I was wondering where can I find documentation and examples on how to handle errors or exceptions from the contract in Javascript.

hi @dan-i

Please see below the main.js code
contractFunded is the event

var web3 = new Web3(Web3.givenProvider);
var contractInstance;

$(document).ready(function(){
  window.ethereum.enable().then(function(accounts){
    contractInstance = new web3.eth.Contract(abi, web3.utils.toChecksumAddress("0xBd8Faa10595d86c39a89AD0e21041ee0E0cF0202"), {from : accounts[0]});
    console.log(contractInstance);
    console.log(`Use Contract address: ${contractInstance._address}`)

    });

    $("#flip_button").click(flipCoin);
    $("#get_balance").click(fetchAndDisplay);
    $("#fund_contract_button").click(fundContract);
    $("#withdraw_funds").click(withdrawAll);



});

    function flipCoin(){
        var bet = $("#bet_input").val();
        var config = {
            value: web3.utils.toWei(bet,"ether")
        }
        contractInstance.methods.flipCoin().send(config)
        .on("transactionHash", function(hash){
            console.log(hash);
        })
        .on("confirmation", function(confirmationNr){
            console.log(confirmationNr);
        })
        .on("receipt", function(receipt){
            console.log(receipt);
            if(receipt.events.betPlaced.returnValues[2] === false){
                alert("You lost " + bet + " Ether!");
            }
            else if(receipt.events.betPlaced.returnValues[2] === true){
                alert("You won " + bet + " Ether!");
            }
        })

      };


      function fetchAndDisplay(){
          contractInstance.methods.getBalance().call().then(function(res){
            $("#jackpot_output").text("The Contract has : " + web3.utils.fromWei(res[1], "ether") + "Ether");

          })
      };


      function fundContract(){
        var fund = $("#fund_contract").val();
        var config = {
          value : web3.utils.toWei(fund, "ether")
        }
        contractInstance.methods.fundContract().send(config)
        .on("transactionHash", function(hash){
          console.log(hash);
        })
        .on("confirmation", function(confirmationNr){
          console.log(confirmationNr);
        })
        .on("receipt", function(receipt){
          console.log(receipt);
          receipt.events.contractFunded(function(error, result){
            alert("The Contract has now been funded by :" +  result.returnValues.amount(web3.utils.fromWei(amount, "ether")) + "Ether");
        })
        })
      };


      function withdrawAll(){
        contractInstance.methods.withdrawAll().send();
      };

also, see below the solidity code:


pragma solidity 0.5.12;

contract Coinflip {

  address public contractOwner;

  constructor() public {
      contractOwner = msg.sender;
  }

  modifier onlyOwner() {
      require(msg.sender == contractOwner, "You are not the owner");
      _;
  }

    uint public contractBalance;
    address public contractAddress;

    modifier costs(uint cost) {
        require(msg.value >= cost, "Minimum amount >= 0.01 ether");
        _;

    }

    event betPlaced(address user, uint bet, bool);
    event contractFunded(address contractOwner, uint amount);

    //Flip the Coin and check whether user won or lost;
    function flipCoin() public payable costs(0.01 ether) returns(bool success) {
        require(address(this).balance >= msg.value, "The contract doesnt have enough balance to play right now. Come Back later");

        if (now % 2 == 0) {
            contractBalance += msg.value;
            success = false;
        }
        else if (now % 2 == 1){
            contractBalance -= msg.value;
            msg.sender.transfer(msg.value * 2);
            success = true;
        }
        //event to be emitted
        emit betPlaced(msg.sender, msg.value, success);
        return success;
    }

    function getBalance() public view returns(address, uint, uint) {
      return(address(this), address(this).balance, contractBalance);
    }

    // withdraw all funds possible only though contractOwner address;
    function withdrawAll() public onlyOwner returns(uint){
        msg.sender.transfer(address(this).balance);
        assert(address(this).balance == 0);
        return address(this).balance;
    }

    function fundContract() public payable onlyOwner returns(uint) {

        require(msg.value != 0);
        emit contractFunded(msg.sender, msg.value);
        return msg.value;
    }
}

What am I doing wrong here ??

thanks and Regards

su.kal Crypto

2 Likes

Hey @Su.kal.Crypto

I tried your code few days ago and I was getting the pop up with the result, but the goal is to catch events.
Because you told me that you followed the faq, can you please share the code? I want to see where you doing errors and correct them :slight_smile:

Regards,
Dani

Hey @Vivek20

Can you give an example of the kind of errors you are getting?
Also in JS usually you handle errors by using catch statements, but really I would need to see the errors to be more precise.
Waiting for you code I wish you a nice day,
Dani

Thanks Dani, perhaps I’m just over complicating things. I’ll post some code later.

1 Like

If you need help I am here :slight_smile:

Finally got finished up with part 1! :smiley: This was my first time using bootstrap so I had to learn how to use the CSS with that which was a great learning opportunity. I do still need to add the error handlers and tests but will sharpen that up after part 2. Thank you @dan-i for the help on this first part. Hopefully it came out well.

Page Responsiveness
https://drive.google.com/file/d/1IJQPx8aTP-z7suPxwcKittvkEOYvVh3L/view

Contract Functionality
https://drive.google.com/file/d/1Q1smZffGkp-CB1iZFzDWB_TPfz0vfz0A/view

1 Like

Hi @dan-i

My code is below :point_down:
https://github.com/Suveett/coinFlip-Dapp.git

It’s the same since last 9 days wherein i committed some changes.
The problem is in this line below :point_down:

receipt.events.contractFunded(function(error, result){
            alert("The Contract has now been funded by :" +  result.returnValues.amount(web3.utils.fromWei(amount, "ether")) + "Ether");
        })

I am asking specifically for an Alert, but there is no pop up on my Window:

Please let me know by having a look at my code. Probably I haven’t wrapped my head around catching events properly, although I feel sensibly that I am doing the right things ( right lines of code)

So let me know.

Also, today while reloading my localhost:8000, I see that Metamask has stopped injecting web3 ?
can you tell me the changes in code so as to get around this :point_up:

Thanks and Regards

su.kal Crypto

Hey @Su.kal.Crypto

I checked your main.js last time and I tried to play with your contract too this is why I was suggesting to check the faq, you should not use the receipt but the contractnstance :slight_smile:
We created a step by step procedure that should clear all the doubts: FAQ - How to listen for events

This is an example of how it suppose to look like:

instance.events.newNumber(function (error,result){
    console.log('Here it is' + ' ' + result.returnValues._newNumber)
  })

You can also use contractInstance.once, check this out, I wrote a clean and easy code to showcase: https://github.com/dani69654/CoinFlip/blob/master/client/main.js

Also the web3 docs explains it really good and gives you lots of examples:

Give it a try and keep me posted.

Regards,
Dani

Thanks @dan-i :blush:
Will check and try out the entire code and get back to you, and also understand where I am going wrong ans then implement corrections in my code …
Su.kal Crypto

1 Like

Got an Error with the following Code when i want to get my balance:

window.ethereum.enable().then(function (accounts) {
    users = accounts;
    contractInstance = new web3.eth.Contract(abi, contract, { from: accounts[0] });
    console.log(contractInstance.events);

    contractInstance.events.contractFunded((err, ev) => {
      $("#result").html("Funded");
      console.log('Funded', ev)
    });
    contractInstance.events.wonFlip((err, ev) => {
      $("#result").html("Won");
      console.log('Won', ev)
    });
    contractInstance.events.loseFlip((err, ev) => {
      $("#result").html("Lost");
      console.log('Lost', ev)
    });

  $("#balance").click(() => {
    contractInstance.methods.getBalance().call().then(function (res) {
      $("#contractBalance").html(web3.utils.fromWei(res[1], "ether") + "Ether");

    })

function getBalance() public view returns (uint256) {
    return address(this).balance;
}
Uncaught (in promise) Error: Internal JSON-RPC error.
{
  "message": "VM Exception while processing transaction: invalid opcode",
  "code": -32000,
  "data": {
    "0x5fbd1fccf1cfc4166a4eb02aaff649068f8d28d827491cc1791c5a7f2dc37a18": {
      "error": "invalid opcode",
      "program_counter": 320,
      "return": "0x"
    },
    "stack": "RuntimeError: VM Exception while processing transaction: invalid opcode\n    at Function.RuntimeError.fromResults (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/utils/runtimeerror.js:94:13)\n    at /Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/blockchain_double.js:568:26",
    "name": "RuntimeError"
  }
}```

Could anyone help? i can deposit to the smart contract. but when i try to check the balance it crashes always. any idea why?

Hi guys,

I’m running into an issue when I redeploy my contract with an added function. I’m not able to see the added function when I console.log the instance, even though I updated my abi and contract address. Can someone help me with this? It’s really frustrating and doesn’t make any sense to me why this is happening.

Hi @niore

Can you just console.log(res) and post the result?

$("#balance").click(() => {
    contractInstance.methods.getBalance().call().then(function (res) {
         console.log(res)
    })

Hi @KaiStryker

Please post your abi and your smart contract.
You either did not update your ABI correctly, or your python server is not updating the changes.

Thanks,
Dani

Hey Dani,

I fixed it, thanks. Turns out all I needed to do was clear the cache in my browser.

1 Like

Hi guys,
I have to do the project 1 after I have finished C++ and javascript, I got confused a bit when I was checking Github, I got so much random information about Github not organized wihtout reaching what I need for my project, probably I’m going to do a grocery list with javascript.
Do I have to write on atom first then create a connection? anybody can help me if you a good tutorial about it?
Thanks in advance

flip with 1 ether


confirmation metamask

lost

won

payout prize

1 Like

New issue:

I am trying to call an event and log the results on the Frontend but every time I try to do this the site doesn’t respond with the results. Here is the code:

.then(contractInstance.getPastEvents(‘Results’,
{
fromBlock:‘latest’
},function(error, events){
console.log(events); })).then(function(events){
$("#get_results_output").text(events._results);

When I try $("#get_results_output").text(events), that works but of course that only returns the text object on the page.

P.S.

What I’m trying to return is a string that says either “You Won!” or “Sorry Try Again!”

Update: I figured it out. The solution is:

.then(contractInstance.getPastEvents(‘Results’,
{
fromBlock:‘latest’
},function(error, _events){
console.log(_events); })).then(function(_events){
$("#get_results_output").text(_events.events.Results.returnValues[’_results’]);
});

When I run this however, in the console.log the event is from the last transaction and not the current one. How do I fix this?

Screen Shot 2021-01-31 at 11.28.16 PM|690x419

1 Like