Assignment - Breeding Frontend

Hey I run your code and find out some issues.

First is the contract function “Breed” does not create any cat. In order to create a cat using breed function you need to call the function _createKitty at some point inside and passing the correct arguments.
Lets take a look at your function :

2021-05-16_15h28_12

We can notice that this function is not saving anything into the blockchain. To solve it include the _createKitty function and pass the newDna from mixDna function, mum and dad id’s.

Second is your frontend functions.

In javascript when we create a function with defined arguments, when you call the function you have to pass this arguments. for example:


function hello(name){

return 'Hello ' + name
}

When you call this function you have to include the argument like:

hello("SuKalCrypto")

if you dont pass argument it will fail.
In your case you are defining breedKitty with argument but calling it without.
2021-05-16_15h29_50

I see that you get the arguments inside the function so in that case is better to not have any arguments
So you can just define this function like


breedKitty(){
}

Another issue is that you are doing the same with renderNewCat() not passing any argument. You cannot use it here because you dont have new cat yet. So is better to not use it in the creation but when you get the return values from the breed function once is working.

Sorry about your lost :frowning: hope you find peace by coding. Count with my support.

Hi @kenn.eth

I changed the code as per your advice and added this _createKitty function with all Parameters:
We can notice that this function is not saving anything into the blockchain. To solve it include the _createKitty function and pass the newDna from mixDna function, mum and dad id’s.

And so now, it’s working Fine. It was my Bad, and a silly mistake i didn’t notice

Also, I changed the code in breed.js and catalogue.js by using async functions without arguments :point_down:

var web3 = new Web3(Web3.givenProvider);
var contractInstance;
var contractAddress="0xBe0a1Da29f465c308511A76E1eBfDA724243a6E1";
var newDna;
var user;

$(document).ready(function() {
  window.ethereum.enable().then(function(accounts){
      contractInstance = new web3.eth.Contract(abi, contractAddress, { from: accounts[0]})
      user = accounts[0];
      console.log(contractInstance);
      console.log(`Use Contract address: ${contractInstance._address}`);
      //EVENT LISTENERS
      contractInstance.events.Birth()
      .on("data", function(event){
        console.log(event);
        let owner = event.returnValues.owner;
        let mumId = event.returnValues.mumId;
        let dadId = event.returnValues.dadId;
        let newDna = event.returnValues.genes;
        let newKittenId = event.returnValues.newKittenId;
      })
      .on("error", function(err){
        console.log('Error :' + err);
      });

  });
  $('#dnabody').html(defaultDNA.headColor);
  $('#dnamouth').html(defaultDNA.mouthColor);
  $('#dnaeyes').html(defaultDNA.eyesColor);
  $('#dnaears').html(defaultDNA.earsColor);
  $('#dnashape').html(defaultDNA.eyesShape);
  $('#dnadecoration').html(defaultDNA.decorationPattern);
  $('#dnadecorationMid').html(defaultDNA.decorationMidcolor);
  $('#dnadecorationSides').html(defaultDNA.decorationSidescolor);
  $('#dnaanimation').html(defaultDNA.animation);
  $('#dnaspecial').html(defaultDNA.lastNum);

  $("#ViewCatButton").click(async ()=> {
    await renderNewCat();
  });
});

  async function renderNewCat() {
    await contractInstance.events.Birth.returnValues;
    newDna.headColor = newDna.slice(0,2);
    newDna.mouthColor = newDna.slice(2,4);
    newDna.eyesColor = newDna.slice(4,6);
    newDna.earsColor = newDna.slice(6,8);
    newDna.eyesShape = newDna.slice(8,9);
    newDna.decorationPattern = newDna.slice(9,10);
    newDna.decorationMidcolor = newDna.slice(10,12);
    newDna.decorationSidescolor = newDna.slice(12,14);
    newDna.animation = newDna.slice(14,15);
    newDna.lastNum = newDna.slice(15,16);
    $('#dnabody').html(newDna.headColor);
    $('#dnamouth').html(newDna.mouthColor);
    $('#dnaeyes').html(newDna.eyesColor);
    $('#dnaears').html(newDna.earsColor);
    $('#dnashape').html(newDna.eyesShape);
    $('#dnadecoration').html(newDna.decorationPattern);
    $('#dnadecorationMid').html(newDna.decorationMidcolor);
    $('#dnadecorationSides').html(newDna.decorationSidescolor);
    $('#dnaanimation').html(newDna.animation);
    $('#dnaspecial').html(newDna.lastNum);

    renderCat(newDna);

};

But again, if you will check my code ( I have uploaded CryptoKitties2.zip), the error after calling the renderNewCat() still exists because it says “Cannot read property slice of undefined” :point_down:
Screenshot 2021-05-17 at 11.13.45 AM

So can you tell me , how and where am I going wrong ??
In my opinion my code is correct and should run, but still isn’t running ? Maybe the technique I am using is wrong even if the code is correct now ?

https://github.com/Suveett/CryptoKitties.git

Thanks and Best Regards

Suveett Kalra
(Su.Kal Crypto)

You are declaring newDna twice. One with var and other with let. You just have to declare it once inside the renderNewCat() function.
Example :

  async function renderNewCat() {
    let event = await contractInstance.events.Birth.returnValues;
    let newDna = event.genes 
    newDna.headColor = newDna.slice(0,2);

Hi Kenneth,

I just again made changes as you said , but its showing again the error " Property slice of Undefined, which means event not defined" :point_down:

TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
    at Function.r (<anonymous>:1:83)
    at renderNewCat (http://localhost:8000/client/catalogue.js:48:24)
    at async HTMLButtonElement.<anonymous> (http://localhost:8000/client/catalogue.js:42:5)

Screenshot 2021-05-17 at 8.27.45 PM

Below is my code of catalogue.js

var web3 = new Web3(Web3.givenProvider);
var contractInstance;
var contractAddress="0xBe0a1Da29f465c308511A76E1eBfDA724243a6E1";

var user;

$(document).ready(function() {
  window.ethereum.enable().then(function(accounts){
      contractInstance = new web3.eth.Contract(abi, contractAddress, { from: accounts[0]})
      user = accounts[0];
      console.log(contractInstance);
      console.log(`Use Contract address: ${contractInstance._address}`);
      //EVENT LISTENERS
      contractInstance.events.Birth({
      fromBlock: 'latest'
      }, function(error, event){ console.log(event); })
      .on("data", function(event){
        console.log(event);
        let owner = event.returnValues.owner;
        let mumId = event.returnValues.mumId;
        let dadId = event.returnValues.dadId;
        let genes = event.returnValues.genes;
        let newKittenId = event.returnValues.newKittenId;
      })
      .on("error", function(err){
        console.log('Error :' + err);
      });
  });
  $('#dnabody').html(defaultDNA.headColor);
  $('#dnamouth').html(defaultDNA.mouthColor);
  $('#dnaeyes').html(defaultDNA.eyesColor);
  $('#dnaears').html(defaultDNA.earsColor);
  $('#dnashape').html(defaultDNA.eyesShape);
  $('#dnadecoration').html(defaultDNA.decorationPattern);
  $('#dnadecorationMid').html(defaultDNA.decorationMidcolor);
  $('#dnadecorationSides').html(defaultDNA.decorationSidescolor);
  $('#dnaanimation').html(defaultDNA.animation);
  $('#dnaspecial').html(defaultDNA.lastNum);

  $("#ViewCatButton").click(async ()=> {
    await renderNewCat();
  });
});

  async function renderNewCat() {
    let event = await contractInstance.events.Birth.returnValues;
      let newDna = event.genes;
      newDna.headColor = newDna.slice(0,2);
      newDna.mouthColor = newDna.slice(2,4);
      newDna.eyesColor = newDna.slice(4,6);
      newDna.earsColor = newDna.slice(6,8);
      newDna.eyesShape = newDna.slice(8,9);
      newDna.decorationPattern = newDna.slice(9,10);
      newDna.decorationMidcolor = newDna.slice(10,12);
      newDna.decorationSidescolor = newDna.slice(12,14);
      newDna.animation = newDna.slice(14,15);
      newDna.lastNum = newDna.slice(15,16);
      $('#dnabody').html(newDna.headColor);
      $('#dnamouth').html(newDna.mouthColor);
      $('#dnaeyes').html(newDna.eyesColor);
      $('#dnaears').html(newDna.earsColor);
      $('#dnashape').html(newDna.eyesShape);
      $('#dnadecoration').html(newDna.decorationPattern);
      $('#dnadecorationMid').html(newDna.decorationMidcolor);
      $('#dnadecorationSides').html(newDna.decorationSidescolor);
      $('#dnaanimation').html(newDna.animation);
      $('#dnaspecial').html(newDna.lastNum);

      renderCat(newDna);


};

I really am getting frustrated , don’t know why this is Happening ? Especially this new error while i console.log the event “Birth” => TypeError: ‘caller’, ‘callee’, and ‘arguments’ properties may not be accessed on strict mode functions or the arguments objects for calls to them
at Function.r (:1:83)
at renderNewCat (http://localhost:8000/client/catalogue.js:48:24)
at async HTMLButtonElement. (http://localhost:8000/client/catalogue.js:42:5)

What does strict mode functions really mean ?? Tried googling it but not made much sense …
Please help :pray: :pray: :pray:

I have uploaded another CryptoKitties3.zip on Github
https://github.com/Suveett/CryptoKitties.git
so you can run smoothly

Maybe you can also send me the full code as per these below functions you mentioned in the beginning of this thread: So then i will re write my entire code again for catalogue.html and catalogue.js and in the process also try and understand exactly what you mean with this below code: :point_down:

function createCatBox(id,catDetails){

var catBox = `<div id="box`+id+`">
                         <div id="head` + id + `">
                          </div>
                         <div id="body` + id + `">
                          </div>
                         <div id="paws` + id + `">
                          </div>
                      </div>`;

document.getElementById("catBoxes").append(catBox);

}

Notice that I also include the catDetails in the arguments. So this mean that I can use them to build also the DNA number, generation etc. Including something in the Box like

<div id="dna">` + catDetails.dna + `</div>
Then you just append each box to a div with catBoxes id.
A loop example using this function

var catDetails = " ";
var id = 0;
for(var i = 0; i < allCats.length; i++){
catDetails = allCats[i];
id = i;
createCatBox(id, catDetails)
}

Thanks and Regards
Su.Kal Crypto

Hey there! Instead finding out whats you are doing wrong, will be better if you look at this project from other student and compare your code with this. Is the final project and wokring all good .
https://github.com/msuscens/CryptoKitties-Clone

Ok here’s my breeding frontend.
I made it simple this time but it works!

ezgif.com-gif-maker

Features:

  1. Selecting third cat will deselect the first cat. It stores in an array, so it remembers the order.
  2. Confirm button will ask to sign the transaction request.
  3. Cancel button will deselect selected cats and brings back to normal page.
  4. When new cat is born (listens for event), it appends the new cat to the My Doraemon page without needing to refresh the page.
  5. Unless the breed button is clicked, clicking catbox won’t do anything.

More about My Doraemon page here.

Full code on my GitHub page:
https://github.com/REGO350/nftgame

3 Likes

thanks for you code. – i got stuck adding the random Math logic tied to a function - i was close but not close enough

var colorVal = $('#bodyColor').val(getRandCol)
1 Like

Hi @kenn.eth

Thanks a lot for sending me this Code a fortnight Back. I really had a hard Look at this code, and although my code is more or less a Copy/ Paste (plus some additions/ subtractions from my side) , but the Best part is that i Have learnt a lot about JavaScript and its powers by having a look at this code :point_up:

But , I am writing to you because although my Solidity codes are compiling perfectly, my front end still isn’t working. I am having the below issues specifically and even after having a hard look at my code ( and maybe i have made a few silly mistakes, I couldn’t find any.
That means my logic is still not working , so Please help me out with this by having a look at my code on Github ( Note : Please only download the zip folder, I haven’t changed the other files yet because i would like to do that in the end when everything is running smoothly

https://github.com/Suveett/CryptoKitties.git

Please see screenshots of some errors :point_down:
index.html :point_down:

Screenshot 2021-06-03 at 9.04.19 PM

My setAnimationFunc, setEyesFunc, setDecorationFunc are not working : The console says cannot read property of undefined, which means that my eyeVariations, animationVariations and DecorationVariations are not defined in catFactory.js. But I have actually defined them in catConstants.js and all my html pages also mention catConstant.js in their code.

breed.js :point_down:

Screenshot 2021-06-03 at 9.03.35 PM

Actually, I am still not clear on this getParamFromUrl function : don’t really know (still) how it works. Please help :pray: :pray:

Screenshot 2021-06-03 at 6.32.05 PM

So please be kind to have a look at my Code and help me :pray: :pray:, so I can finally finish this project and move on to other newer Courses. I really tried my Best before writing to you :slight_smile:

Thanks and Regards

Suveett Kalra
(Su.Kal Crypto)

Here is my code for breed.html and for catSettings.js, but I am battling to get the breed function to work from the website:

<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>
    <header align="left">
        <div class="btn-group">
            <a href="index.html" class="btn btn-primary tsp-1 m-1 light-b-shadow" role="button">Home</a>
            <a href="catalogue.html" class="btn btn-primary tsp-1 m-1 light-b-shadow" role="button">Catalogue</a>
            <a href="breed.html" class="btn btn-primary tsp-1 m-1 light-b-shadow" role="button">Breed New Kitten</a>
        </div>
    </header>
    <div class="container p-5" style="margin-top: 12vh;margin-bottom: 10vh;">
        <div align="center">
            <h1 class="c-white">Kitty Nursery</h1>
            <p class="c-white">Breed a New Kitten</p>
        </div>
        <div class="row">
            <div class="col-lg-4 catBox m-2 light-b-shadow">
    
            </div>
            <div class="col-lg-7 cattributes m-2 light-b-shadow">
                <label for="mum">Mum ID: </label>
                <input type="integer" id="mum" name="mum"><br>
                <label for="dad">Dad ID: </label>
                <input type="integer" id="dad" name="dad"><br>
                <button class="btn btn-primary tsp-1 m-1 light-b-shadow" onclick="breedKitty()"><b>Breed!</b></button>
            </div>
    
        </div>
        <br>
        <div class="container">
        </div>
        <br>
    
        <div class="alert alert-success" role="alert" id="kittyCreation" style="display:none">
    
        </div>
    
    </div>
    
    <footer align="left">
        <p>Ivan on Tech Academy Bootcamp July 2020</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>
function breedKitty(){
  var dadId = $("dad").val();
  var mumId = $("mum").val();
  instance.methods.breed(dadId, mumId).send({}, function(error, txHash){ //the function here is a callback function
    if(error)
      console.log(err);
    else{
      console.log(txHash);
    }
  })
}

This is the error I’m getting:

catSettings.js:72 Uncaught TypeError: instance.methods.breed is not a function
    at breedKitty (catSettings.js:72)
    at HTMLButtonElement.onclick (breed.html:42)

Hey @Su.kal.Crypto !
You have two clear errors.
2021-06-05_19h35_22

This is typing error in the catSettings.js file, on the lines that are showing in the image: 54 and 89. So check them out

This is because you dont have this “?frstCatId” parameter into the url. Please send me the code from this getParamUrl() function. What this function should do, if to checkout if there is a param into the url and use it. If there is not, you can redirect user to other page or just notify that there is not firstCatId param.

2021-06-05_19h35_42

hey @RichJamo ! Errors in line 72 if breedKitty. Please send me a picture where you defining this instance. Also you can pass it like an argument, but the problem here is that is not getting the instance variable.

This part was really difficult for me I took me so much time and efforts, so much google, and saw this forum, changes on files created before for the project (a lot of changes). I need to include Ids(on html) on my cats and make functions that works with Ids and not classes, change the default cat for working with id=“00”, a lot of new functions, I changed those functions with switch (I have so much problems I used instead IF)
I used only a page for catalog and breed

image
image
image

this is my code
Catalogue Html

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="../client/assets/js/jquery-3.4.1.js"></script>
        <link rel="stylesheet" href="../client/assets/bootstrap/css/bootstrap.min.css">
        <script src="../client/assets/bootstrap/js/popper.js"></script>
        <script src="../client/assets/bootstrap/js/bootstrap.min.js"></script>
        <link rel="stylesheet" href="../client/assets/css/mystyle.css">
        <link rel="stylesheet" href="../client/assets/css/cats.css">
        <link rel="stylesheet" href="../client/assets/css/colors.css">
        <link rel="stylesheet" href="../client/assets/css/factory.css">
        <link rel="stylesheet" href="../client/assets/css/frontend.css">
        <link rel="stylesheet" href="../client/assets/css/animation.css">
        <script type="text/javascript" src="../web3.min.js"></script>
    </head>
    <body>
        <div class=" light-b-shadow" align = "center">
            <p class="bg-white pt-0">Academy-kitties
            <button class ='red-btn'>Home</button>
            <button class ='red-btn'>Catalogue</button>
            <button class ='red-btn' onclick="location.href='../'">Kitties Factory</button>
            </p>
        </div>
        <div class="container p-5"  >
            <h1 class="c-white">Cat Catalogue</h1>
            <p class="c-white">Checkout the Kitties</p>
            <button class="white-btn" id="renderKitties">Render </button>
            <button class="white-btn" onclick="breedingKitties()">Breeding </button>
        </div>
        <p style="width:100%" id= "1">
        </p>
    </body>
        <script src="../client/assets/js/colors.js"></script>
        <script src="../client/assets/js/catCatalogue.js"></script>
        <script src="../client/assets/js/catFactory.js"></script>
        <script src="../abi.js"></script>  
</html>

catCatalogue

var colors = Object.values(allColors())
var web3 = new Web3(Web3.givenProvider);
var contractInstance;
var tokenCount; 
var arrayDNA = [];
var j= 0; 
var catBoxFull = '';
var breedIds =0; 
var catsIds = []; 

$(document).ready(function() {
  window.ethereum.enable().then(function(accounts){
    contractInstance = new web3.eth.Contract(window.abi, "0xc7E8420a2715fB2474963279AD91e57fcE2998e3", {from: accounts[0]});
    catCatalogue()
    })
});

function catCatalogue() {
    contractInstance.methods.totalSupply().call().then((res)=>{
      tokenCount = parseInt(res);
      for(var i=0; i<tokenCount; i++){
        kittiesDNA(i);
      } 
    })    
}


function kittiesDNA(i) { //i is ID from blokchain 
        contractInstance.methods.getKitty(i).call().then(function(res){
          var DNA = {
            headcolor: res[0].slice(0,2),
            "mouthcolor": res[0].slice(2,4),
            "eyescolor": res[0].slice(4,6),
            "earscolor": res[0].slice(6,8),
            "eyesShape": parseInt(res[0].slice(8,9)),
            "decorationPattern": parseInt(res[0].slice(9,10)),
            "decorationMidcolor": res[0].slice(10,12),
            "decorationSidescolor": res[0].slice(12,14),
            "animation":  parseInt(res[0].slice(14,15)),
            "lastNum":  res[0].slice(15,16),
            "motherId": res[2],
            "fatherId": res[3],
            "catGeneration": res[4],
            "birthDate": res[1],
            "id": i
            };
            arrayDNA.push(DNA);  
            createCatBox(i)
        })  
}

function createCatBox(id){
j++
    if (j<= tokenCount){
    var catBox = 
    `<div class="col-lg-4 catBoxCatalog m-2 light-b-shadow" id= "catBox`+id+`">
        <div class='cat' id= "cat`+id+`">
            <div class= 'ears' id= "ears`+id+`">
                <div class= 'rightear' id="rightear`+id+`">
                    <div class = 'innerear' id="innerear`+id+`"></div>
                </div>
                <div class= 'leftear' id="leftear`+id+`">
                    <div class= 'innerear id=`+id+`'></div>
                </div>
            </div>
            <div class= 'head' id= "head`+id+`">
                <div class= 'front' id= "front`+id+`"></div>
                <div class= 'nouse' id="nouse`+id+`"></div>
                <div class= 'eyes' id= "eyes`+id+`">
                    <div class = 'eye' id="eye`+id+`">
                        <div class = 'pupil'  id="pupil`+id+`"></div>
                        <div class= 'intoeye' id= "intoeye`+id+`"></div>
                    </div>
                    <div class = 'eye2' id="eye2`+id+`">
                        <div class = 'pupil' id= "pupil`+id+`"></div>
                        <div class= 'intoeye' id= "intoeye`+id+`"></div>
                    </div>
                </div>
                <div class= 'mouth' id="mouth`+id+`">
                    <div class= 'tongue' id= "tongue`+id+`"></div>
                </div>  
                <div class ='whiskergroup1' id= "whiskergroup1`+id+`">
                    <div class= 'whisker' id= "whisker`+id+`"></div>
                    <div class= 'whisker2' id= "whisker2`+id+`"></div>
                    <div class= 'whisker3' id= "whisker3`+id+`"></div>
                </div>
                <div class ='whiskergroup2' id="whiskergroup2`+id+`">
                    <div class= 'whisker4' id="whisker4`+id+`"></div>
                    <div class= 'whisker5' id= "whisker5`+id+`"></div>
                    <div class= 'whisker6' id= "whisker6`+id+`"></div>
                </div>
            </div>
            <div class = 'tail' id="tail`+id+`">
                <div class= 'intotail' id="intotail`+id+`"></div>
            </div>
            <div class = 'neck' id="neck`+id+`"></div>
            <div class= 'body' id="body`+id+`">                           
                <div class = 'belly' id="belly`+id+`"> </div>
                <div class = 'legs' id="legs`+id+`">
                    <div class = 'rightleg' id="rightleg`+id+`"></div>
                    <div class = 'leftleg' id="leftleg`+id+`"></div>
                </div>
            </div>      
        </div>
        <br>
        <br>
        <div class="dnaDiv" id="catDNA">
            DNA:
            <!-- Colors -->
            <span id="dnabody`+id+`"></span>
            <span id="dnamouth`+id+`"></span>
            <span id="dnaeyes`+id+`"></span>
            <span id="dnaears`+id+`"></span>
            <!-- Cattributes -->
            <span id="dnashape`+id+`"></span>
            <span id="dnadecoration`+id+`"></span>
            <span id="dnadecorationMid`+id+`"></span>
            <span id="dnadecorationSides`+id+`"></span>
            <span id="dnaanimation`+id+`"></span>
            <span id="dnaspecial`+id+`"></span>
        </div>   
        <div class="dnaDiv" id="catStatistics">
        <br>    
            Mom ID: <span id= "momId`+id+`"></span>
            Dad ID: <span id= "dadId`+id+`"></span>
            Gen: <span id= "generation`+id+`"></span><br>
            <!--Birth Time: <span id= "birthTime"></span>-->
            <label for="breedCheck" > Breeding</label>
            <input type="checkbox" id="breedCheck`+id+`" onclick="breeding(`+id+`)">
            <p id="breedText`+id+`" style="display:none">CHECKED! `+id+`</p>
        </div>
    </div>`;
    //document.getElementById("1").append(catBox);
    //document.body.innerHTML = `<h1>${catBoxFull} </h1>`
    }
catBoxFull = catBoxFull.concat(catBox);
document.getElementById('1').innerHTML = catBoxFull;
}


    $('#renderKitties').click(()=>{
    for(var l=0; l<tokenCount; l++){ 
        headColor(colors[arrayDNA[l].headcolor],arrayDNA[l].headcolor, l)
        tailColor(colors[arrayDNA[l].mouthcolor],arrayDNA[l].mouthcolor,l)
        eyeColor(colors[arrayDNA[l].eyescolor],arrayDNA[l].eyescolor, l)
        earColor(colors[arrayDNA[l].earscolor],arrayDNA[l].earscolor, l)
        eyeVariation(arrayDNA[l].eyesShape,l)  
        decorationVariation(arrayDNA[l].decorationPattern, l)
        pattern(colors[arrayDNA[l].decorationMidcolor],arrayDNA[l].decorationMidcolor, l)
        pattern2(colors[arrayDNA[l].decorationSidescolor],arrayDNA[l].decorationSidescolor, l)
        animationVariation(arrayDNA[l].animation, l) 
        $(`#momId${l}`).html(arrayDNA[l].motherId)
        $(`#dadId${l}`).html(arrayDNA[l].fatherId)
        $(`#birthTime${l}`).html(arrayDNA[l].birthDate)
        $(`#generation${l}`).html(arrayDNA[l].catGeneration) 
        $(`#dnaspecial${l}`).html(arrayDNA[l].lastNum)
     }
    })

function breeding(id) {
    var checkBox = document.getElementById(`breedCheck${id}`);
    var text = document.getElementById(`breedText${id}`);
    if (checkBox.checked == true){
        text.style.display = "block";
        breedIds++;
        catsIds.push(id);
    } else {
        text.style.display = "none";
        breedIds--;
  }
}

function breedingKitties () {
    if (breedIds=== 2){ 
        contractInstance.methods.breed(catsIds[0], catsIds[1]).send(function(error, txHash) {
            if(error){
                console.log(error)
                breedIds =0;
                array.splice(0, array.length)
            }
            else {
                console.log(txHash)   
                breedIds =0;
                array.splice(0, array.length) 
            }    
        }); 
        contractInstance.once('Birth', function(error, event){ //listener
            if(event) {
                console.log(event)
              alert(`Owner: ${event.returnValues.owner} \nBlockHash: ${event.blockHash} 
              \nblocknumber: ${event.blockNumber} \nContract: ${event.address}
              \nGenes: ${event.returnValues.genes} \nDadID ${event.returnValues.dadId}
              \nMumID ${event.returnValues.mumId} \nKittenID ${event.returnValues.kittenId}`)
            }
            else
                console.log(error)
      });
    } 
    else {
        alert("incorrect")
    }
}

as you can see i used a click handler with a button i cannot make render the page automatically (i received errors and errors for this )
with this works ok

html 
 <button class="white-btn" id="renderKitties">Render </button>

js
$('#renderKitties').click(()=>{
    for(var l=0; l<tokenCount; l++){ 
        headColor(colors[arrayDNA[l].headcolor],arrayDNA[l].headcolor, l)
        tailColor(colors[arrayDNA[l].mouthcolor],arrayDNA[l].mouthcolor,l)
        eyeColor(colors[arrayDNA[l].eyescolor],arrayDNA[l].eyescolor, l)
        earColor(colors[arrayDNA[l].earscolor],arrayDNA[l].earscolor, l)
        eyeVariation(arrayDNA[l].eyesShape,l)  
        decorationVariation(arrayDNA[l].decorationPattern, l)
        pattern(colors[arrayDNA[l].decorationMidcolor],arrayDNA[l].decorationMidcolor, l)
        pattern2(colors[arrayDNA[l].decorationSidescolor],arrayDNA[l].decorationSidescolor, l)
        animationVariation(arrayDNA[l].animation, l) 
        $(`#momId${l}`).html(arrayDNA[l].motherId)
        $(`#dadId${l}`).html(arrayDNA[l].fatherId)
        $(`#birthTime${l}`).html(arrayDNA[l].birthDate)
        $(`#generation${l}`).html(arrayDNA[l].catGeneration) 
        $(`#dnaspecial${l}`).html(arrayDNA[l].lastNum)
     }
    })

my problem is when I call a function to render everything
there are errors calling the data that i need from the array but i don understand this, maybe i am so bad for async programming

function catCatalogue() {
    contractInstance.methods.totalSupply().call().then((res)=>{
      tokenCount = parseInt(res);
      for(var i=0; i<tokenCount; i++){
        kittiesDNA(i);
      } 
      **renderALL();** // i tried so much here 
    })    
}

function renderALL() {
    //$('#renderKitties').click(()=>{
    for(var l=0; l<tokenCount; l++){ 
        headColor(colors[arrayDNA[l].headcolor],arrayDNA[l].headcolor, l)
        tailColor(colors[arrayDNA[l].mouthcolor],arrayDNA[l].mouthcolor,l)
        eyeColor(colors[arrayDNA[l].eyescolor],arrayDNA[l].eyescolor, l)
        earColor(colors[arrayDNA[l].earscolor],arrayDNA[l].earscolor, l)
        eyeVariation(arrayDNA[l].eyesShape,l)  
        decorationVariation(arrayDNA[l].decorationPattern, l)
        pattern(colors[arrayDNA[l].decorationMidcolor],arrayDNA[l].decorationMidcolor, l)
        pattern2(colors[arrayDNA[l].decorationSidescolor],arrayDNA[l].decorationSidescolor, l)
        animationVariation(arrayDNA[l].animation, l) 
        $(`#momId${l}`).html(arrayDNA[l].motherId)
        $(`#dadId${l}`).html(arrayDNA[l].fatherId)
        $(`#birthTime${l}`).html(arrayDNA[l].birthDate)
        $(`#generation${l}`).html(arrayDNA[l].catGeneration) 
        $(`#dnaspecial${l}`).html(arrayDNA[l].lastNum)
     }
    //})
}

image

this is the only problem the rest is working (with the button all works fine)

3 Likes

hi @kenn.eth, solved it! I’d forgotten to update my abi.js file, so breed wasn’t showing up as one of the methods available. Updated the abi.js file, refreshed the website, and now it’s working!

1 Like

Hi @kenn.eth

Sorry for my late reply, because i moved ahead to finish the Ethereum Smart Contract Security Course and it was great learning and now I am revisiting this subject.

You have two clear errors.
2021-06-05_19h35_22

Well Below I am sharing with you my catSettings.js, catFactory.js, catConstants.js and colors.js code. I honestly have tried again but I couldn’t find any error ( or TypeError)

catSettings.js :point_down:

function getDna(){
  try {
    let dna = ''
    dna += $('#dnabody').html()
    dna += $('#dnamouth').html()
    dna += $('#dnaeyes').html()
    dna += $('#dnaears').html()
    dna += $('#dnashape').html()
    dna += $('#dnadecoration').html()
    dna += $('#dnadecorationMid').html()
    dna += $('#dnadecorationSides').html()
    dna += $('#dnaanimation').html()
    dna += $('#dnaspecial').html()

    if (dna.length !== 16 ) throw `DNA string ('${dna}') length should be 16 (not ${dna.length} digits)`

    return BigInt(dna)
  }
  catch (error) {
    console.log(`Error In getDna(): ${error}`)
  }
}


function renderCat(cat, idCat=""){
  try {
    headColor(cat.dna.headColor, idCat)
    mouthColor(cat.dna.mouthColor, idCat)
    eyesColor(cat.dna.eyesColor, idCat)
    earsColor(cat.dna.earsColor, idCat)
    eyeVariation(cat.dna.eyesShape, idCat)
    decorationVariation(cat.dna.decorationPattern, idCat)
    midDecorationColor(cat.dna.decorationMidColor, idCat)
    sidesDecorationColor(cat.dna.decorationSidesColor, idCat)
    animationStyle(cat.dna.animation, idCat)

    // Display Special DNA digit
    $(`${idCat} #dnaspecial`).html(cat.dna.lastNum) // Update DNA display (below cat)

    // Display Cats' Generation
    $(`${idCat}`).find('#catGenNum').html(cat.gen)

    // Display Cats' Price (if it has one)
    if (cat.price) $(`${idCat}`).find('#catPrice').html("PRICE: " + cat.price + " ETH")

    // Display Cats' status
//    $(`${idCat}`).find('#catStatus').html("TEST")

  }
  catch (error){
    console.log(`Error In renderCat, idCat=""): ${error}`)
  }
}


function updateSliders(dna){
  try {
    $('#bodycolor').val(dna.headColor)             //Update slider's value
    $('#headcode').html('code: '+dna.headColor)    //Update slider's badge

    $('#mouthcolor').val(dna.mouthColor)
    $('#mouthcode').html('code: '+dna.mouthColor)

    $('#eyescolor').val(dna.eyesColor)
    $('#eyescode').html('code: '+dna.eyesColor)

    $('#earscolor').val(dna.earsColor)
    $('#earscode').html('code: '+dna.earsColor)

    $('#eyesshape').val(dna.eyesShape)
    $('#eyename').html(eyeVariations[dna.eyesShape].name)

    $('#decorationpattern').val(dna.decorationPattern)
    $('#decorationname').html(decorationVariations[dna.decorationPattern].name)

    $('#decorationmidcolor').val(dna.decorationMidColor)
    $('#midbirthmarkcode').html('code: '+dna.decorationMidColor)

    $('#decorationsidescolor').val(dna.decorationSidesColor)
    $('#sidebirthmarkscode').html('code: '+dna.decorationSidesColor)

    $('#animationstyle').val(dna.animation)
    $('#animationcode').html(animationVariations[dna.animation].name)
  }
  catch (error){
    console.log(`Error In updateSliders(dna): ${error}`)
  }
}


//EVENT LISTENERS

// Changing cat's Body' colors
$('#bodycolor').change(()=>{
    var colorVal = $('#bodycolor').val()
    $('#headcode').html('code: '+ colorVal) //This updates text of the badge next to the slider
    headColor(colorVal)


})

// Changing Cat's Mouth color
$('#mouth_tail_color').change(()=>{
  var colorVal = $('#mouth_tail_color').val()
  $('#mouthcode').html('code: ' + colorVal) // This updates text of the badge next to the slider
  mouthColor(colorVal)


})

//Changing cat's eyes color
$('#eyescolor').change(()=>{
  var colorVal = $('#eyescolor').val()
  $('#eyescode').html('code: ' + colorVal) // This updates text of the badge next to the slider
  eyesColor(colorVal)

})

//Changing cat's ears colors
$('#earscolor').change(()=>{
  var colorVal = $('#earscolor').val()
  $('#earscode').html('code: ' + colorVal) // This updates text of the badge next to the slider
  earsColor(colorVal)

})

//Changing Cat eyes Shape
$('#eyesshape').change(()=>{
  var shape = parseInt($('#eyesshape').val())
  $('#eyename').html(eyeVariations[shape].name)
  eyeVariation(shape)

})

//Changing Decoration pattern
$('#decorationpattern').change(()=>{
  var pattern = parseInt($('#decorationpattern').val())
  $('#decorationname').html(decorationVariations[pattern].name)
  decorationVariation(pattern)
})

//Changing The Side & Mid Birthmarks colors
$('#decorationsidescolor').change(()=>{
  var colorVal = $('#decorationsidescolor').val()
  $('#sidebirthmarkscode').html('code: '+ colorVal) //This updates text of the badge next to the slider
  sidesDecorationColor(colorVal)
})
$('#decorationmidcolor').change(()=>{
  var colorVal = $('#decorationmidcolor').val()
  $('#midbirthmarkcode').html('code: '+ colorVal) //This updates text of the badge next to the slider
  midDecorationColor(colorVal)
})

//Changing the Animation Style :
$('#animationstyle').change(()=>{
  var animationVal = parseInt($('#animationstyle').val())
  $('#animationcode').html(animationVariations[animationVal].name)
  animationStyle(animationVal)
})

catFactory.js :point_down:



//This function changes the color of Head and Chest
function headColor(code,idCat = "") {
    $(`${idCat}.cat__head, ${idCat}.cat__chest`).css('background', '#' + colors[code])  //This changes the color of the cat
    $(`${idCat}#dnabody`).html(code) //This updates the body color part of the DNA that is displayed below the cat


}

// This function changes the color of Mouth and tail
function mouthColor(code,idCat = ""){
  $(`${idCat}.cat__mouth-left, ${idCat}.cat__mouth-right, ${idCat}.cat__tail`).css('background', '#' + colors[code]) //This changes the Cat's Mouth and Tail Colors
  $(`${idCat}#dnamouth`).html(code) // This updates the Mouth and Tail color part of the DNA that is displayed below the cat

}

//This function changes the color of Cat's eyes
function eyesColor(code, idCat = ""){
  $(`${idCat}.cat__eye span.pupil-left, ${idCat}.cat__eye span.pupil-right`).css('background', '#' + colors[code]) //This changes the Cat's Mouth and Tail Colors
  $(`${idCat}#dnaeyes`).html(code) // This updates the Mouth and Tail color part of the DNA that is displayed below the cat


}

//This function changes the color of Cat's ears and Paws
function earsColor(code, idCat = ""){
  $(`${idCat}.cat__ear--left, ${idCat}.cat__ear--right, ${idCat}.cat__paw-left, ${idCat}.cat__paw-right`).css('background', '#' + colors[code]) //This changes the Cat's ears Colors
  $(`${idCat}#dnaears`).html(code) //This updates the Ears color part of the DNA that is displayed below the Cat


}

//###################################################
//USING BELOW FUNCTIONS TO CHANGE CATTRIBUTES
//###################################################

//Changing Eye shapes
function eyeVariation(num, idCat = "") {
    normalEyes(idCat) //Reset eyes
    $(`${idCat}#dnashape`).html(num)//This updates the Eyes shape part of the DNA that is displayed below the Cat
    eyeVariations[num].setEyesFunc(idCat)
}
//########################################################################################
  //  switch (num) {
  //      case 1:
  //          normalEyes()
  //          $('#eyename').html('Basic Eyes')// Set the badge of the eye to 'Basic'
  //          break
  //      case 2:
  //          normalEyes()//reset
  //          $('#eyename').html('Chill Eyes')//Set the badge to "Chill"
  //          eyesType1()//Change the eye shape by bringing a Solid border-top 15 px
  //          break
  //      case 3:
  //          normalEyes()//reset
  //          $('#eyename').html('Smile Eyes')//Set the badge to "Smile"
  //          eyesType2()//Change the eye shape by bringing a Solid border- bottom15 px
  //          break
  //      case 4:
  //          normalEyes()//reset
  //          $('#eyename').html('Cool Eyes')//Set the badge to "Cool"
  //          eyesType3()//Change the eye shape by bringing a Solid border-right 15 px
  //          break
  //      case 5:
  //          normalEyes()//reset
  //          $('#eyename').html('Dotted Eyes')//Set the badge to "Dotted Eyes"
  //          eyesType4()//Change the eye shape by bringing a border-style: dotted
  //          break
  //  }




function normalEyes(idCat) {
    //Reset eye Lids to fully open
    $(`${idCat}.cat__eye`).find('span').css('border', 'none')
    // Reset pupil to round and centered
    $(`${idCat} .cat__eye`).find('span').css('width', '42px')
    $(`${idCat} .pupil-left`).css('left', '42px')
    $(`${idCat} .pupil-right`).css('left', '166px')
}

function eyesType1(idCat) {
    $(`${idCat}.cat__eye`).find('span').css('border-top', '15px solid')
}

function eyesType2(idCat) {
    $(`${idCat}.cat__eye`).find('span').css('border-bottom', '15px solid')
}

function eyesType3(idCat) {
    $(`${idCat}.cat__eye`).find('span').css('border-right', '15px solid')
}

function eyesType4(idCat) {
    $(`${idCat}.cat__eye`).find('span').css('border-style', 'Dotted')
}

//###################################################################################

//Changing Cat BirthMark Dimensions + Rotation
function decorationVariation(num, idCat="") {
  normalDecoration(idCat)
  $(`${idCat} #dnadecoration`).html(num)   // Update DNA display (below cat)
  decorationVariations[num].setDecorationFunc(idCat)
}

//#########################################################################################
  //  switch (num) {
  //    case 1:
  //          normalDecoration()
  //          $('#decorationname').html('Basic Forehead Patches')// Set the Badge to Decoration pattern Basic
  //          break
  //      case 2:
  //          normalDecoration()
  //          $('#decorationname').html('Angled Forehead Patches')// Set the Badge to Decoration pattern - Angled patches
  //          normalDecoration1()
  //          break
  //      case 3:
  //          normalDecoration()
  //          $('#decorationname').html('Smaller Forehead Width Patches')// Set the Badge to Decoration pattern - Smaller Patches
  //          normalDecoration2()
  //          break
  //      case 4:
  //          normalDecoration()
  //          $('#decorationname').html('Smaller Forehead Height Patches')// Set the Badge to Decoration pattern - Smaller Patches
  //          normalDecoration3()
  //          break
  //  }




function normalDecoration(idCat) {
    //Remove all style from other decorations
    //In this way we can also use normalDecoration() to reset the decoration style
    $(`${idCat}.cat__head-dots`).css({ "transform": "rotate(0deg)", "height": "48px", "width": "14px", "top": "1px", "border-radius": "0 0 50% 50%" })
    $(`${idCat}.cat__head-dots_first`).css({ "transform": "rotate(0deg)", "height": "35px", "width": "14px", "top": "1px", "border-radius": "50% 0 50% 50%" })
    $(`${idCat}.cat__head-dots_second`).css({ "transform": "rotate(0deg)", "height": "35px", "width": "14px", "top": "1px", "border-radius": "0 50% 50% 50%" })
}


function normalDecoration1(idCat) {
    //Remove all style from other decorations
    //In this way we can also use normalDecoration() to reset the decoration style
    $(`${idCat}.cat__head-dots`).css({ "transform": "rotate(0deg)", "height": "48px", "width": "14px", "top": "1px", "border-radius": "0 0 50% 50%" })
    $(`${idCat}.cat__head-dots_first`).css({ "transform": "rotate(45deg)", "height": "35px", "width": "14px", "top": "1px", "border-radius": "50% 0 50% 50%" })
    $(`${idCat}.cat__head-dots_second`).css({ "transform": "rotate(-45deg)", "height": "35px", "width": "14px", "top": "1px", "border-radius": "0 50% 50% 50%" })
}

function normalDecoration2(idCat) {
    //Remove all style from other decorations
    //In this way we can also use normalDecoration() to reset the decoration style
    $(`${idCat}.cat__head-dots`).css({ "transform": "rotate(0deg)", "height": "48px", "width": "8px", "top": "1px", "border-radius": "0 0 50% 50%" })
    $(`${idCat}.cat__head-dots_first`).css({ "transform": "rotate(0deg)", "height": "35px", "width": "8px", "top": "1px", "border-radius": "50% 0 50% 50%" })
    $(`${idCat}.cat__head-dots_second`).css({ "transform": "rotate(0deg)", "height": "35px", "width": "8px", "top": "1px", "border-radius": "0 50% 50% 50%" })
}

function normalDecoration3(idCat) {
    //Remove all style from other decorations
    //In this way we can also use normalDecoration() to reset the decoration style
    $(`${idCat}.cat__head-dots`).css({ "transform": "rotate(0deg)", "height": "24px", "width": "8px", "top": "1px", "border-radius": "0 0 50% 50%" })
    $(`${idCat}.cat__head-dots_first`).css({ "transform": "rotate(0deg)", "height": "20px", "width": "8px", "top": "1px", "border-radius": "50% 0 50% 50%" })
    $(`${idCat}.cat__head-dots_second`).css({ "transform": "rotate(0deg)", "height": "20px", "width": "8px", "top": "1px", "border-radius": "0 50% 50% 50%" })
}

//########################################################################################################

//This changes the Side BirthMark Colors
function sidesDecorationColor(code, idCat= "") {
    $(`${idCat}.cat__head-dots_first , ${idCat}.cat__head-dots_second`).css('background', '#' + colors[code])  //This changes the color of the cat's Side BirthMark
    $(`${idCat}#dnadecorationSides`).html(code) //This updates the Side Birthmarks color part of the DNA that is displayed below the cat
}

//This changes the Mid BirthMark colors
function midDecorationColor(code, idCat ="") {
    $(`${idCat}.cat__head-dots`).css('background', '#' + colors[code])  //This changes the color of the cat's Mid Birthmark
    $(`${idCat}#dnadecorationMid`).html(code) //This updates the Mid Birthmark color part of the DNA that is displayed below the cat
  }


//#################################################################################################################
//This Function changes the animation style
function animationStyle(num,idCat = ""){
  resetAnimation(idCat) //Reset animations
  $(`${idCat} #dnaanimation`).html(num)   // Update DNA display (below cat)
  animationVariations[num].setAnimationFunc(idCat)
}

//#################################################################################################################
//  switch (num) {
//    case 1 :
//    movingHeadAnimation()
//    $('#animationcode').html('Moving Head')//It sets the Badge to Moving Head style
//    break
//    case 2 :
//    bigHeadAnimation()
//    $('#animationcode').html('Big Head') // It sets the Badge to Scaled Head style
//    break
//    case 3 :
//    translatedHeadAnimation()
//    $('#animationcode').html("Translated Head")//It setsthe  Badge to Transitioned/Transported Head style
//    break
//    case 4 :
//    movingTailAnimation()
//    $('#animationcode').html('Moving Tail')// It sets the badge to Moving Tail animation style
//    break
//  }




function animationType1(idCat) {  //Head rotates and moves
  $(`${idCat}#head`).addClass('movingHead')
}

function animationType2(idCat) {  //Head gets scaled
  $(`${idCat}#head`).addClass('scalingHead')

}


function animationType3(idCat) { //Head gets translated
  $(`${idCat}#head`).addClass('translatingHead')
}


function animationType4(idCat) { //Tail starts Moving
  $(`${idCat}#tail`).addClass('movingTail')
}

function resetAnimation(idCat){
  $(`${idCat}#head`).removeClass('movingHead')
  $(`${idCat}#head`).removeClass('scalingHead')
  $(`${idCat}#head`).removeClass('translatingHead')
  $(`${idCat}#tail`).removeClass('movingTail')


}

catConstants.js :point_down:

var colors = Object.values(allColors())

const defaultDNA = {
    "headColor" : 10,
    "mouthColor" : 13,
    "eyesColor" : 96,
    "earsColor" : 10,
    //Cattributes
    "eyesShape" : 1,
    "decorationPattern" : 1,
    "decorationMidColor" : 13,
    "decorationSidesColor" : 13,
    "animation" : 0,
    "lastNum" : 1
    }

const defaultCat = {
    id: "",
    dna: defaultDNA,
    gen: ""
}

const eyeVariations = [
    {
      "name" : "Basic Eyes",
      "setEyesFunc" : normalEyes
    },
    {
      "name" : "Smiling Eyes",
      "setEyesFunc" : eyesType1
    },
    {
        "name" : "Shy Girl eyes",
        "setEyesFunc" : eyesType2
    },
    {
        "name" : "Chill",
        "setEyesFunc" : eyesType3
    },
    {
        "name" : "Dotted Eyes",
        "setEyesFunc" : eyesType4
    }
  ]

const decorationVariations = [
    {
        "name" : "Standard Stripes",
        "setDecorationFunc" : normalDecoration
    },
    {
        "name" : "Angular Stripes",
        "setDecorationFunc" : normalDecoration1
    },
    {
        "name" : "Big Stripes",
        "setDecorationFunc" : normalDecoration2
    },
    {
        "name" : "Small Stripes",
        "setDecorationFunc" : normalDecoration3
    }
]

const animationVariations = [
    {
        "name" : "Moving Head",
        "setAnimationFunc" : animationType1
    },
    {
        "name" : "Scaling Head",
        "setAnimationFunc" : animationType2
    },
    {
        "name" : "Translating Head",
        "setAnimationFunc" : animationType3
    },
    {
        "name" : "Moving Tail",
        "setAnimationFunc" : animationType4
    }
]

colors.js :point_down:


function allColors(){
  return colorPallete;
}


var colorPallete = {00: "ae494f",
01: "9a3031",
02: "8cd42e",
03: "a0417a",
04: "91c656",
05: "299f7a",
06: "c65d1e",
07: "b2bbd6",
08: "2d4024",
9: "4b5715",
10: "ffcc80",
11: "3f1174",
12: "b22a90",
13: "fff3e0",
14: "4c858b",
15: "18bebe",
16: "b5044b",
17: "d6b1d4",
18: "fecb40",
19: "748882",
20: "4a3c95",
21: "482916",
22: "267bf0",
23: "5af7e2",
24: "adeacc",
25: "cf2b03",
26: "b3c459",
27: "353f9",
28: "5d4993",
29: "ba8d15",
30: "da2457",
31: "ff17fe",
32: "d6e81d",
33: "daf2db",
34: "19b510",
35: "18e26f",
36: "b7c36a",
37: "8cb175",
38: "bdce32",
39: "f2e0ba",
40: "a2f8a5",
41: "64bf50",
42: "f1a771",
43: "4982a9",
44: "f66c41",
45: "2fe802",
46: "bda142",
47: "8342ff",
48: "2b4ab4",
49: "ad4595",
50: "bae4f",
51: "b76d01",
52: "8e8207",
53: "285b9f",
54: "c4422a",
55: "f1eaa7",
56: "e3a0cc",
57: "65c116",
58: "656ccf",
59: "7c25f4",
60: "1e18d1",
61: "688a7d",
62: "1fe786",
63: "425716",
64: "4ac043",
65: "547836",
66: "24a216",
67: "fd9bba",
68: "24894d",
69: "c54b03",
70: "6fbdce",
71: "cff1dd",
72: "8805fb",
73: "fe99d2",
74: "c52f14",
75: "e31c54",
76: "d010eb",
77: "b83436",
78: "c294b6",
79: "564a6c",
80: "531bcf",
81: "c04b8c",
82: "3cd2ef",
83: "82286c",
84: "aa2639",
85: "86be6c",
86: "e62102",
87: "5471fc",
88: "5c089",
89: "703c75",
90: "9a8e8f",
91: "8b9307",
92: "fcbc82",
93: "ea5978",
94: "b8e370",
95: "43474b",
96: "262d2b",
97: "ddd67e",
98: "344867"}




//Random color
function getColor() {
    const randomColor = Math.floor(Math.random() * 16777215).toString(16);
    return randomColor
}

//Generate colors for pallete
function genColors(){
    const colors = []
    for(const i = 10; i < 99; i ++){
      const color = getColor()
      colors[i] = color
    }
    return colors
}

I am honestly unable to find any errors after consistent trying, so please help me :pray: :pray:

Also, Below is my helperFunctions.js file :point_down:

tfunction getRandomIntegerBetween(low, high){
    try {
      if (low<0) throw "Error: Only supports positive integers - low is negative!"
      if (low>high) throw "Error: low is greater than high!"

      const rangeInclusive = high - low + 1
      const RandomValue = Math.floor(Math.random() * rangeInclusive) + low

      return RandomValue
    }
    catch(error) {
      throw(`In getRandomIntegerBetween(${low}, ${high}): ${error}`)
    }
  }


  function getParamFromUrl(url, paramId) {
    try {
      const startParamIdPos = url.lastIndexOf(paramId)
      if (startParamIdPos == -1) {
          throw new Error(`Parameter: "${paramId}" not present in url: "${url}"`)
      }
      const startParamValPos = startParamIdPos + paramId.length

      const endDelimPos = url.indexOf("&", startParamValPos)
      const endParamValPos = (endDelimPos > -1)? endDelimPos: url.length

      const param = url.substring( startParamValPos, endParamValPos )

      return param
    }
    catch(error) {
      throw("HelperFunctions.js: In getParamFromUrl(url, paramId): " + error)
    }
  }

I have just copy / pasted the code, but I haven’t understood it yet and it seems also not to be working
So please Help me in figuring it out :pray: :pray:

In Fact I would suggest if you can spare some time and run my entire code and see where and why these errors are coming ?
I really want to understand and finish these abnormalities, before i move forward on to other courses.

Thanks again :pray: :pray:

This is my GitHub code:

Please download this zip folder : it contains all my code:
https://github.com/Suveett/CryptoKitties/blob/main/CryptoKitties.zip

Please don’t use the other code, it’s not been updated yet.

Thanks a ton in advance

Suveett kalra
(Su.kal Crypto)

Hey guys, hope you’re all well.
When i try and create a new kitty, it throws a few errors and they don’t make sense.
The first error message is:
Screenshot 2021-06-15 at 12.40.45
I’m interpreting the above message as saying i have not declared the contract address in the index.js file. Even though i have copied and pasted the deployed contract address (and i triple checked).

.
The second error message is:
Screenshot 2021-06-15 at 12.43.45
Which i have never seen before and don’t quite understand even after research.

.
And then finally this other error message comes up when i navigate to my CATalogue page:
Screenshot 2021-06-15 at 12.50.12

My abs.js file is up-to-date and my solidity contracts have been deployed + migrated + copied and pasted the contract address to all my js files before opening the python web server.

My up-to-date Github repo is here: https://github.com/olfrank/Crypto_Cats

Thanks.

Hey @ol_frank I think your problem is coming from marketplace contract. You are calling the marketplace address in the marketplaceInstance but you got it mute. So this is causing the error.
2021-06-15_15h36_59

hey @Su.kal.Crypto the code zip file you send is just empty.
I find some issues
This is a typo. you wrote tfunction
2021-06-15_15h39_25

Also notice that the error you are getting comes from not using a correct index number for calling the property you wish. So, for this constant decorationVariations youy should log the index you are using to make sure is right,

Hi @kenn.eth

Thanks, I was just about to write to you that i figured this mistake already and sorted out the index values.

But Thanks a ton indeed for your effort and super quick Help.
And Now, I am stuck again. I am literally having nightmares in completing this Dapp (because of my not so good knowledge of JavaScript. Although I am really trying hard to understand the logic of each Function line by line by line, but just when I think I have grasped almost everything a New error crops up. I tried googling for solutions but couldn’t get to the crux of it )

I am now having the below error in createKittie() func

Screenshot 2021-06-15 at 9.03.09 PM

Error In createKittie: Error: invalid number value (arg="_genes", coderType="uint256", value="9690311201456811")

Seems to be a conversion issue between uint256 & BigInt in the getDna()

Also another question : in catsettings.js getDna() has been specifically called to return a BigInt whereas the Kittycontract.sol function createKittyGen0(uint256 _genes) public onlyOwner returns(uint256){
require(gen0Counter < CREATION_LIMIT_GEN0);
gen0Counter ++;

return _createKitty(0,0, _genes, 0, msg.sender);

}
returns a uint256

Also, One more question: actually can this statement return _createKitty(0,0, _genes, 0, msg.sender); be called a uint256 ?
Does Solidity compiler return a uint256 equivalent of this statement???

How does all this Interact with each other (if at all it does) , because the error seems in createKittie() in catSettings.js and not in the solidity Kittycontract and its function createKittyGen0, then why this error ?? :thinking: :thinking:

Error In createKittie: Error: invalid number value (arg="_genes", coderType="uint256", value="9690311201456811")

I don’t know If I am making sense, i am so god damned confused, tired and almost giving up, because there is no uint256 declaration in the getDna() function of catSettings.js


function createKittie(){
  try {
    const dnaStr = getDna()
    KITTY_CONTRACT_INSTANCE.methods.createKittyGen0(dnaStr).send({}, function(err, txHash){
        if (err) console.log(err)
        else console.log(txHash)
    })
  }
  catch(error){
    console.log(`Error In createKittie: ${error}`)
  }
}

function getDna(){
  try {
    let dna = ''
    dna += $('#dnabody').html()
    dna += $('#dnamouth').html()
    dna += $('#dnaeyes').html()
    dna += $('#dnaears').html()
    dna += $('#dnashape').html()
    dna += $('#dnadecoration').html()
    dna += $('#dnadecorationMid').html()
    dna += $('#dnadecorationSides').html()
    dna += $('#dnaanimation').html()
    dna += $('#dnaspecial').html()

    if (dna.length !== 16 ) throw `DNA string ('${dna}') length should be 16 (not ${dna.length} digits)`

    return BigInt(dna)
  }
  catch (error) {
    console.log(`Error In getDna(): ${error}`)
  }
}

Thanks and awaiting revert

Suveett Kalra
(Su.Kal Crypto)

Ok cool ! try to pass this dna as a string to your createKittyGen0(). You can use the toString() JS function.
Something like :

const dnaStr = dnaStr = getDna().toString()
//Then call your function 
KITTY_CONTRACT_INSTANCE.methods.createKittyGen0(dnaStr)....

When you call from JS function using w3 you get just strings and numbers.

Hi @kenn.eth

I did exactly as you told me :point_down:


function createKittie(){
  try {
    const dnaStr = dnaStr = getDna().toString()
    KITTY_CONTRACT_INSTANCE.methods.createKittyGen0(dnaStr).send({}, function(err, txHash){
        if (err) console.log(err)
        else console.log(txHash)
    })
  }
  catch(error){
    console.log(`Error In createKittie: ${error}`)
  }
}

And now its showing error :point_down:

Error In createKittie: ReferenceError: Cannot access 'dnaStr' before initialization

What does this Mean ??

Also i understand your comment below here :point_down:

When you call from JS function using w3 you get just strings and numbers.

But how does solidity understand it when the Kittycontract is being called from my index.js using w3 passing a “string” input , whereas the function clearly defines uint256 as input ? :point_down:

function getKitty(uint256 _newKittenId) public view returns() {}

Please clarify this too !!

Thanks and Regards

Su.kal Crypto

1 Like