Assignment - Event

  1. Create a listener for the birth event.
  2. Create a popup of a newborn cat whenever you get an event of type birth.

Read about Event listeners in Web3.js: https://web3js.readthedocs.io/en/v1.2.9/web3-eth-contract.html#contract-events

Make sure to take a look at their example code for hints about implementation.

Hint from Filip:
Make sure that the instance variable is defined and initialized when you define your event listener.

2 Likes

Event Assignment Code

index.js
var web3 = new Web3(Web3.givenProvider);



var instance;
var user;
var contractAddress = "0x6Ab01DdFF59dc9E6a53CbEE4937d35670468cFD1";

$(document).ready(function(){
    window.ethereum.enable().then(function(accounts) {
        instance = new web3.eth.Contract(abi, contractAddress, {from: accounts[0]});
        user = accounts[0];

        console.log(instance);

        
    })
})

async function createNewBear(){
    var dnaString = getDna();
    console.log(dnaString);
    await instance.methods.createBearGen0(dnaString).send({}, function(error, txHash){
        if (error){
            console.log(error);
        }
        else{
            console.log(txHash);
            alert("Transaction has been sent succesfully!");
            instance.events.Birth({}, function(error, event){
                if(error){
                    alert("Birthproblems!")
                }
                else{
                    console.log(event);
                    alert("A new bear was born!");
                }
                
            });
        }
    })


}

FineTune:

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



var instance;
var user;
var contractAddress = "0x9455BfdE053c0E02340b6e0De750ae094Da2981d";

$(document).ready(function(){
    window.ethereum.enable().then(function(accounts) {
        instance = new web3.eth.Contract(abi, contractAddress, {from: accounts[0]});
        user = accounts[0];

        console.log(instance);

        
    })
})

async function createNewBear(){
    var dnaString = getDna();
    console.log(dnaString);
    await instance.methods.createBearGen0(dnaString).send({}, function(error, txHash){
        if (error){
            console.log(error);
        }
        else{
            console.log(txHash);
            instance.events.Birth().on('data', function(event){
                    console.log(event);
                    let owner = event.returnValues.owner;
                    console.log(owner);
                    let bearId = event.returnValues.bearId;
                    console.log(bearId);
                    let mumId = event.returnValues.mumId;
                    console.log(mumId);
                    let dadId = event.returnValues.dadId;
                    console.log(dadId);
                    let genes = event.returnValues.genes;
                    console.log(genes);

                    $("#bearCreated").css("display", "block");
                    $("#bearCreated").text("Bear Id: " + bearId +
                                           " Owner: " + owner + 
                                           " MumId: " + mumId + 
                                           " DadId: " + dadId +
                                           " Genes: " + genes );
            }).on('error', console.error);
        }
    })


}

2 Likes

Hey guys, when i refresh or load the page my metamask does not link up to it like it should. It is throwing this error but not sure why or how to fix it.

Screenshot 2021-04-20 at 13.48.17

//this line will connect us to the Ethereum blockchain 
//and we can access it through this variable
var web3 = new Web3(Web3.givenProvider);

//contract instance
var instance;

var user;

var contractAddress = "0x46B045187410B07a17eF15467bc2c92A39553661";

$(document).ready(function(){
    window.ethereum.enable().then(function(accounts){
        instance = new web3.eth.Contract(abi, contractAddress, {from: accounts[0]})
        user = accounts[0];

        console.log(instance);

        
    })
});

function createCat(){
    var dnaStr = getDna();
    instance.methods.createCatGen0(dnaStr).send({}, function(error, txHash){
        if(error)
            console.log(err);
        else{
            console.log(txHash)
            
        }
    })
}```

Code I put together in index.js …

var web3 = new Web3(Web3.givenProvider);

var instance;
var user;
var contractAddress="0x109B6A59B33fa48ad1be84006853D0F66C804236";

$(document).ready(function() {
    window.ethereum.enable().then(function(accounts){
        instance = new web3.eth.Contract(abi, contractAddress, { from: accounts[0]})
        user = accounts[0];

        console.log(instance);

        
    }).then(function(){
        instance.events.Birth({}, function(error, event){ console.log(event); })
        .on("connected", function(subscriptionId){
            console.log("Event subsciption connected with id: " + subscriptionId);
        })
        .on('data', function(event){
            alertstring = "Kitten born with following properties: id: " + event.returnValues.kittenId +
            ", mumId: " + event.returnValues.mumId + ", dadId: " + event.returnValues.dadId + ", genes: " +
            event.returnValues.genes + ", owner: " + event.returnValues.owner + ".";
            console.log(alertstring);
            alert(alertstring);
            //console.log(event.returnValues);
        })
        .on('changed', function(event){
            // nothing to do yet
        })
        .on('error', function(error, receipt) { // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
            console.log(error);
        });
    });
})

function createKitty(dnaStr){
    instance.methods.createKittyGen0(dnaStr).send({}, function(err, txHash){
        if (err){
            console.log(err)
        } else {
            console.log("Kitty create msg sent with txHash: " + txHash)
        }

    });
}

$('#createCatButton').click(() =>{
    createKitty(getDna());
  })
1 Like

Can you send me a picture of HTML header libraries? I think this issue is about loading the libraries to use window.ethereum.

@kenn.eth Here is my HTML file:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Academy kitties </title>
  <script type="text/javascript" src="assets/js/jquery-3.4.1.js"></script>
  <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
  <script src="assets/bootstrap/js/popper.js"></script>
  <script src="assets/bootstrap/js/bootstrap.min.js"></script>
  <script src="assets/js/web3.min.js"></script>
  <script src="./abi.js"></script>

  
  <link rel="stylesheet" href="assets/css/animations.css">
  <link rel="stylesheet" href="assets/css/mystyle.css">
  <link rel="stylesheet" href="assets/css/cats.css">
  <link rel="stylesheet" href="assets/css/colors.css">
  <link rel="stylesheet" href="assets/css/factory.css">
  <link rel="stylesheet" href="assets/css/frontend.css">
</head>
  <body>
    <div class="container p-5" style="margin-top: 12vh;margin-bottom: 10vh;">
        <div align="center">
        <h1 class="c-blue">Kitties-Factory</h1>
        <p class="c-blue">Create your custom Kitty</p>
    </div>
        <div class="row">
            <div class="col-lg-4 catBox m-2 light-b-shadow">


                <div class = "cat">
                    <div class = "ears">
                        <div class= "ear left-ear">
                            <div class = " left-inner-ear"></div>
                        </div>
                        <div class = "ear right-ear">
                            <div class = "right-inner-ear"></div>
                        </div>
                    </div>
        
                    <div class = "tail">
                        <div class = "inner-tail"></div>
                    </div>
        
                    <div class = "body"></div>
                    <div class = "belly"></div>
                    <div class = "head">
                        <!-- <div class= "head-pattern"></div> -->
                                        <div id="midShape" class="head-shapes">
                                            <div id="leftShape" class="left_head-shape"></div>
                                            <div id="rightShape" class="right_head-shape"></div>
                                        </div>
        
                        <div class = "eyes">
                            <div class = "eye-left">
                                <span class = "pupil-left">
                                    <div class = "inner-eyes-big-left"></div>
                                    <div class = "inner-eyes-small-left"></div>
                                </span>
                            </div>
        
                            <div class = "eye-right">
                                <span class = "pupil-right">
                                    <div class = "inner-eyes-big-right"></div>
                                    <div class = "inner-eyes-small-right"></div>
                                </span>
                            </div>    
                        </div>
        
                        
                        <div class = "mouth"></div>
                        <div class = "whiskers">
                            <div class = "whiskers-right">
                                <div class = "whisker1"></div>
                                <div class = "whisker2"></div>
                                <div class = "whisker3"></div>
                            </div>
                            <div class = "whiskers-left">
                                <div class = "whisker4"></div>
                                <div class = "whisker5"></div>
                                <div class = "whisker6"></div>
                            </div>
                        </div>
                        <div class = "mouth-left"></div>
                        <div class = "mouth-right"></div>
                        <div class = "nose"></div>
                        <div class = "chin"></div>
                    </div>

                    
                    <div class = "feet">
                        <div class = "foot-left"></div>
                        <div class = "foot-right"></div>
                    </div>
                </div>



                <br>
                <div class="dnaDiv" id="catDNA">
                    <b>
                        DNA:
                        <!-- Colors -->
                         <span id="dnabody"></span>
                         <span id="dnaeyes"></span>
                         <span id="dnabelly"></span>
                         <span id="dnaears"></span>
                         <span id="dnatail"></span>
                        
                         <!-- Cattributes -->
                         <span id="dnashape"></span>
                         <span id="dnadecoration"></span>
                         <span id="dnadecorationMid"></span>
                         <span id="dnadecorationSides"></span>
                         <span id="dnaanimation"></span>
                         <span id="dnaspecial"></span>
                    </b>
                </div>
            </div>
            <div class="col-lg-7 cattributes m-2 light-b-shadow">

<!-- Cat colors -->
<div id="catColors">
    <button id="btnColorsTab" type="button" class="btn btn-dark">Colors</button>
    <button id="btnAttributesTab" type="button" class="btn btn-dark">Attributes</button>

                <div id= "headGroup" class="form-group">
                    <label for="formControlRange"><b>Head & Body</b><span class="badge badge-dark ml-2" id="bodycode"></span></label>
                    <input type="range" min="10" max="98" class="form-control-range" id="bodycolor">
                </div>

                <div id = "eyesGroup" class="form-group">
                    <label for="formControlRange"><b>Eyes</b><span class="badge badge-dark ml-2" id="eyecode"></span></label>
                    <input type="range" min="10" max="98" class="form-control-range" id="eyecolor">
                </div>

                <div id = "mouthGroup" class="form-group">
                    <label for="formControlRange"><b>Belly & Mouth</b><span class="badge badge-dark ml-2" id="bellycode"></span></label>
                    <input type="range" min="10" max="98" class="form-control-range" id="bellycolor">
                </div>

                <div id = "earsGroup" class="form-group">
                    <label for="formControlRange"><b>Ears & Inner Tail</b><span class="badge badge-dark ml-2" id="earcode"></span></label>
                    <input type="range" min="10" max="98" class="form-control-range" id="earcolor">
                </div>

                <div id = "tailGroup" class="form-group">
                    <label for="formControlRange"><b>Tail</b><span class="badge badge-dark ml-2" id="tailcode"></span></label>
                    <input type="range" min="10" max="98" class="form-control-range" id="tailcolor">
                </div>
                 
            </div>
            <br>

<div id = "cattributes">
            <div id = "eyeShapeGroup" class="form-group">
                <label for="formControlRange"><b>Eye Shape</b><span class="badge badge-dark ml-2" id="eyeName"></span></label>
                <input type="range" min="1" max="11" class="form-control-range" id="eyeshape">
            </div>

            <div id = "patternGroup" class="form-group">
                <label for="formControlRange"><b>Head Pattern</b><span class="badge badge-dark ml-2" id="patternName"></span></label>
                <input type="range" min="1" max="7" class="form-control-range" id="decorationpattern">
            </div>
        
            <div id = "patternColorGroup" class="form-group">
                <label for="formControlRange"><b>Middle Shape Color</b><span class="badge badge-dark ml-2" id="middlecolorcode"></span></label>
                <input type="range" min="10" max="98" class="form-control-range" id="decorationmid">
                <label for="formControlRange"><b>Sides Shape Color</b><span class="badge badge-dark ml-2" id="sidecolorcode"></span></label>
                <input type="range" min="10" max="98" class="form-control-range" id="decorationside">
            </div>
            <div id = "animationGroup" class="form-group">
                <label for="formControlRange"><b>Animations</b><span class="badge badge-dark ml-2" id="animationName"></span></label>
                <input type="range" min="1" max="9" class="form-control-range" id="animations">
            </div>
            </div>

            <button id = "random" class = "badge badge-pill badge-info" onclick = "randomCat()">Random Cat</button>
            <button id = "default" class = "badge badge-pill badge-warning" onclick = "defualtCat()">Default</button>
            <button id = "create" class = "badge badge-pill badge-success" onclick = "createCat()">Create New Cat</button>

            </div>
            <br>
            <div class = "alert alert-success" role = "alert" id="catCreation" style= "display:none"></div>

            
        </div>



    </div>
    <footer align="left">
        <p>Ivan on Tech Academy April 2021</p>
    </footer>

  </body>
  <script src="./index.js"></script>
  <script src="assets/js/colors.js"></script>
  <script src="assets/js/catSettings.js"></script>
  <script src="assets/js/catFactory.js"></script>

</html>

And my file list:
Screenshot 2021-04-21 at 11.05.13

1 Like

@kenn.eth did you manage to find where the issue is?

Do you have it into a github repo? Its looks ok but now metamask connection have some changes. So old way to connect to contract on work if you install Metamask Legacy in some cases. If you can share the project with me i can test it.

1 Like

Okay no problem. I will upload it tomorrow and let you know. @kenn.eth

https://github.com/olfrank/Crypto_Cats

1 Like

Cool, will check it tomorrow and let you know.

1 Like

Hi there,

I was working on the index.js file:

$(document).ready(() =>{
	window.ethereum.enable().then((accounts) =>{
		//the enable function will return an array of 1 element so we take the first element
		user = accounts[0];
		//now we reference our deployued contract and with the "from" parameter tell who will be submitting Tx's
		// we also need to provide a definition of the functions, variables, etc, the contract supports. 
		// that's what the abi is for.
		instance = new web3.eth.Contracts(abi, contractAddress, {from: user});

		console.log(instance);

	})
})

and getting the following error when attempting to test the load of my contract:
image

I’ve dealt a little bit in the past with web3 and know that perhaps this is a version problem but any insight you can provide will help!

As a side note, I’m not running the python server but just simply opening the index.html file which seems to have worked so far.

Thanks!

1 Like

Its looks ok but now metamask connection have some changes. Install Metamask Legacy extension and let me know.
https://chrome.google.com/webstore/detail/metamask-legacy-web3/dgoegggfhkapjphahmgihfgemkgecdgl

Hey @ol_frank im having problems to compile your contract. There is something missing.
2021-04-25_16h35_00
Im getting this error. Did you try the google extesion Metamask Legacy?
https://chrome.google.com/webstore/detail/metamask-legacy-web3/dgoegggfhkapjphahmgihfgemkgecdgl
Install this and let know if the frontend error is solve.

1 Like

@kenn.eth. I have no idea why it suddenly doesn’t migrate correctly. When i run truffle compile it works but as soon as i run truffle migrate that error (the one you screen shotted) throws. I have looked online and the answers given don’t help my situation. Last week it was able to migrate the contract but suddenly now it doesn’t. This is beyond frustrating haha. Also even after installing the metamask legacy extension it still does not work. Did it work for you @Mariano_Collarte ??

Screenshot 2021-04-26 at 11.58.55

There its looks like you are not loading jquery and web3 at the top first? so you can use it.
Please update this changes to your github repo so i can run it for testing.

1 Like

ok please update github repo is like 4 days ago. So i run it locally

1 Like

@kenn.eth this is my updated repo. Thanks
https://github.com/olfrank/Crypto_Cats

1 Like

ok gonna run it tomorrow. Keep it uodated everytime.

1 Like

Hi guys, question, is it necessary to have the python3 server running in order to connect to metamask? I’ve been just using the index.html file so far, i wonder if that could be the reason why my metamask doesnt do anything when i hit the buttons on that page…

thanks!