Assignment - Breeding Frontend

Wait, where’s the catalogue video?

1 Like

There is not video for doing the catalogue, is something you have to find out your self. I exaplain here Assignment - Cat Website

1 Like

Hi @kenn.eth

Being from a Non Technical Background ( no prior CS or Programming Experience, I am having a harrowing time getting to grasp everything, especially because whatever Java Script I have learnt is all by the means of doing the Basic Courses given by Ivan and then i proceeded with ETH 101 AND ETH 201 ).
I was not able to fully understand this 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);

}

So Then I started on my own Journey to create a simple website and write simple Code :point_down:
My whole Code below :point_down:

Solidity : Kittycontract

pragma solidity 0.5.12;
import "./IERC721.sol";
import "./utils/SafeMath.sol";
import "./IERC721Receiver.sol";

contract Kittycontract is IERC721 {

using SafeMath for uint;

//constructors and Modifiers
constructor() public {
  contractOwner = msg.sender;
  }

modifier onlyOwner() {
  require(msg.sender == contractOwner);
  _;
  //continue execution
}

//events
event Birth(
  address owner,
  uint256 genes,
  uint256 newKittenId,
  uint256 mumId,
  uint256 dadId);

event Transfer(address indexed oldOwner, address indexed newOwner, uint256 indexed tokenId);
event Approval(address indexed Owner, address indexed approvedTo, uint256 indexed tokenId);
event ApproveAll(address indexed Owner, address operator, bool success);
event NewDnaCreated(uint256 indexed DNA);
//Struct- it gets stored in storage on EVM
struct Cat {
    uint256 genes;
    uint64 birthTime;
    uint32 mumId;
    uint32 dadId;
    uint16 generation;
}

//Mappings
//       owner    number of Cats
mapping(address => uint256) public tokenOwnershipCount;
//      tokenId     owner
mapping(uint256 => address) public ownershipCertificate;
// approval mapping
mapping(uint256 => address) public kittyIndexToApprove;
// approval all (operator) mapping
//[MYAADDR][OPERATORADDR] => TRUE/FALSE;
mapping(address => mapping(address => bool)) private _operatorApprovals;



//State variables
address public contractOwner;
string public constant Name = "MEOW-CATS";
string public constant Symbol = "MEOW";
uint public constant CREATION_LIMIT_GEN0 = 100;
uint public gen0Counter = 0;
bytes4 internal constant MAGIC_ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;

//arrays
Cat[] public cats;

//##############################################################################################################
//FUNCTIONS START HERE :
//Function when called from external contract returns whether this contract support IERC721 or IERC165 standard?
function supportsInterface(bytes4 _interfaceId) external view returns(bool) {
  return ( _interfaceId == _INTERFACE_ID_ERC165 || _interfaceId == _INTERFACE_ID_ERC721);
}

// SAFE TRANSFER FUNCTIONS
//Function executing an External Call from another User/ Contract(without Data):
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public {
  safeTransferFrom(_from, _to, _tokenId, " ");
}

//Function executing an Public Call which then goes through external Interface(called with @param bytes calldata _data):
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public {
  require(isApprovedOrOwner(msg.sender, _from, _to, _tokenId));
  _safeTransfer(_from, _to, _tokenId, _data);
}


//Internal safeTransfer Function
function _safeTransfer(address _from, address _to, uint256 _tokenId, bytes memory _data) internal {
  require( _checkERC721Support(_from, _to, _tokenId, _data) );
  _transfer(_from, _to, _tokenId);
}

//Function executing an External Call from another User/ Contract:
function transferFrom(address _from, address _to, uint256 _tokenId) public {
  require(isApprovedOrOwner(msg.sender, _from, _to, _tokenId));
  //require(_to != address(0));
  //require(_to != address(this));
  //require(_owns(_from, _tokenId));
  //require(msg.sender == _from || approvedFor(msg.sender, _tokenId) || isApprovedForAll(_from, msg.sender));
  //require(_tokenId < cats.length);
  _transfer(_from, _to, _tokenId);

}

//Function executing an External Call from another User/ Contract:
function transfer(address _to, uint256 _tokenId) public {
  require(_to != address(0));
  require(_to != address(this));
  require(_owns(msg.sender, _tokenId));

  _transfer(msg.sender, _to, _tokenId);
}

//Actual transfer of the token happens from this below Internal Function:
function _transfer(address _from, address _to, uint256 _tokenId) internal {
  tokenOwnershipCount[_to]++ ;
  if(_from != address(0)){
    tokenOwnershipCount[_from]-- ;
    delete(kittyIndexToApprove[_tokenId]);
  }

  //Event Transfer to be emitted now :
  emit Transfer(_from, _to, _tokenId);
}


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



//BASIC CAT CREATION, BREEDING & GETTER FUNCTIONS
function createKittyGen0(uint256 _genes) public onlyOwner returns(uint256){
  require(gen0Counter < CREATION_LIMIT_GEN0);
    gen0Counter ++;

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

}

function breed(uint256 _dadId, uint256 _mumId) public returns(uint256) {
  ( uint256 _dadDna,,,,, uint256 dadGeneration) = getKitty(_dadId);
  ( uint256 _mumDna,,,,, uint256 mumGeneration) = getKitty(_mumId);

  uint256 newDna = _mixDna(_dadDna, _mumDna);

  uint256 kidGen = 0;
  if (dadGeneration < mumGeneration) {
    kidGen = mumGeneration +1;
    kidGen /= 2;
  }
  else if (dadGeneration < mumGeneration) {
    kidGen = dadGeneration +1 ;
    kidGen /= 2;
  }
  else {
    kidGen = mumGeneration + 1;
  }

}

function _mixDna(uint256 _dadDna, uint256 _mumDna) internal returns(uint256) {
  uint256 firstHalf = _dadDna /100000000;
  uint256 secondhalf = _mumDna % 100000000;
  uint256 newDna = firstHalf * 100000000;
  newDna += secondhalf;
  //emit event DNA
  emit NewDnaCreated(newDna);
  return newDna;
}


function _createKitty (
  uint256 _mumId,
  uint256 _dadId,
  uint256 _genes,
  uint256 _generation,
  address _owner
) private returns(uint256) {

  Cat memory _cat = Cat({
    genes : _genes,
    birthTime : uint64(now),
    mumId : uint32(_mumId),
    dadId : uint32(_dadId),
    generation : uint16(_generation)
  });
  uint256 newKittenId = cats.push(_cat) - 1;

  //Event Birth to  be emitted :
  emit Birth(_owner, _genes, newKittenId, _mumId, _dadId);

  _transfer(address(0), _owner, newKittenId);
  return newKittenId;
}


function getKitty(uint256 _newKittenId) public view returns(
uint256 _genes,
uint256 _mumId,
uint256 _dadId,
uint256 _birthTime,
address _owner,
uint256 _generation){

  Cat storage cat = cats[_newKittenId];
  _genes = cat.genes;
  _dadId = uint256(cat.dadId);
  _mumId = uint256(cat.mumId);
  _generation = uint256(cat.generation);
  _birthTime = uint256(cat.birthTime);
  _owner = ownershipCertificate[_newKittenId];

}

function getKittyByOwner(address _owner) external view returns(uint[] memory) {
  uint[] memory result = new uint[](tokenOwnershipCount[_owner]);
  uint counter = 0;
  for (uint i = 0; i < cats.length; i ++) {
    if (ownershipCertificate[i] == _owner) {
      result[counter] = i;
      counter ++;
    }
  }
  return result;
}

function balanceOf(address owner) external view returns (uint256 balance) {
  return tokenOwnershipCount[owner];
}

function totalSupply() public view returns (uint256 total) {
  total = cats.length;
  return total;
}

function name() external view returns (string memory tokenName) {
  tokenName = Name;
  return tokenName;
}


function symbol() external view returns (string memory tokenSymbol) {
  tokenSymbol = Symbol;
  return tokenSymbol;
}

function ownerOf(uint256 tokenId) external view returns (address owner) {
  return ownershipCertificate[tokenId];
}



//This below Function called "_owns" gives bool result whether the address has actual ownership of the _tokenId:
function _owns(address _claimant, uint256 _tokenId) internal view returns(bool) {
  return ownershipCertificate[_tokenId] == _claimant;
}



// APPROVE FUNCTION & GETTER FUNCTIONS RELATED TO APPROVALS :

function approve(address _to, uint256 _tokenId) public {
  require(_owns(msg.sender, _tokenId));
  _approve(_to, _tokenId);
  //emit event Approve
  emit Approval(msg.sender, _to, _tokenId);
}

function _approve(address _approved, uint _tokenId ) internal {
  _approved = kittyIndexToApprove[_tokenId];
}

function getApproved(uint256 _tokenId) public view returns (address) {
  require(_tokenId < cats.length); //Token must exist
  return kittyIndexToApprove[_tokenId];
}

function setApprovalForAll(address _operator, bool approved) public {
  require(_operator != msg.sender);
  approved = _operatorApprovals[msg.sender][_operator];
  //emit event ApproveAll
  emit ApproveAll(msg.sender, _operator, approved);
}

function approvedFor(address _claimant, uint256 _tokenId) internal view returns(bool) {
  return kittyIndexToApprove[_tokenId] == _claimant;
}


function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
  return _operatorApprovals[_owner][_operator];
}

function isApprovedOrOwner(address _spender, address _from, address _to, uint256 _tokenId) internal view returns(bool) {
  require(_to != address(0));
  require(_to != address(this));
  require(_owns(_from, _tokenId));
  require(_tokenId < cats.length);
  return (_spender == _from || approvedFor(_spender, _tokenId) || isApprovedForAll(_from, _spender));
}

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

// INTERNAL FUNCTION ASKING FOR ERC 721 SUPPORT  :
function _checkERC721Support(address _from, address _to, uint256 _tokenId, bytes memory _data) internal returns(bool) {
  if ( !_isContract(_to) ) {
    return true;
  }
  bytes4 returnData = IERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
  // Call on onERC721Received in the _to contract
  return returnData == MAGIC_ERC721_RECEIVED;
  // Check on Return Value;
}

// IF SIZE = O =>ITS A USER WALLET, IF > 0 => ITS A CONTRACT :
function _isContract(address _to) internal view returns(bool) {
  uint32 size;
  assembly{
    size := extcodesize(_to)
  }
  return size > 0;
}


}

**But I know the problem is not coming from Solidity as the Contract is compiling fine **

*So below is my JS code *:point_down:
index.js

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

$(document).ready(async () => {
  window.ethereum.enable().then(function(accounts){
    contractInstance = new web3.eth.Contract(abi, contractAddress, {from: 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 genes = event.returnValues.genes;
      let newKittenId = event.returnValues.newKittenId;
      jQuery("#jackpot_output").append("<div class='alert alert-success' role='alert'>Congrats, You are proud owner of this Kitty !</div>");
      jQuery("#jackpot_output1").append("<div class='alert alert-success' role='alert'>Mint another Kitty !</div>");
      setTimeout(function(){
        jQuery("#jackpot_output").hide();
        jQuery("#jackpot_output1").hide()
      },5000);

    })
    .on("error", function(err){
      console.log('Error :' + err);
    });


  });


  $("#mintkitty").click(async()=> {
    await mintKitty();
  });
  $("#breedkitty").click(async()=> {
    await window.location.replace("/client/breed.html");
  });
});

async function mintKitty(){
  var dnaStr = getDna();
  await contractInstance.methods.createKittyGen0(dnaStr).send()
  .on("transactionHash", function(hash){
      console.log(hash);
  })
  .on("confirmation", function(confirmationNr){
      console.log(confirmationNr);
  })
  .on("receipt", function(receipt){
      console.log(receipt);
  });

};

Its running fine until this Page :point_up:

So, Now i come to breed.js :point_down:

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

var contractAddress="0xF2224FC1C0149FA056bE9ABc45b48bE3bad516B5";

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

        //EVENT LISTENERS
        contractInstance.events.Birth({
        //filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
        fromBlock: 'latest'
        }, function(error, event){ console.log(event); })
        .on("connected", function(subscriptionId){
            console.log("Event subsciption connected with id: " + subscriptionId);
            //console.log(subscriptionId);
        })
        .on('data', function(event){
            //console.log(event); // same results as the optional callback above
            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.genes);
        })
        .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);
        });
      });
    $('#BreedCatButton').click(async () =>{
         await breedKitty();
         await renderNewCat();

      });
    $("#ViewCatButton").click(async ()=> {
      await window.location.replace("/client/catalogue.html");
      });

});

 async function breedKitty(dadId, mumId){
  var dadId = $('#dad-id').val();
  var mumId = $('#mum-id').val();
  await contractInstance.methods.breed(dadId,mumId).send()
  .on("transactionHash", function(hash){
      console.log(hash);
  })
  .on("confirmation", function(confirmationNr){
      console.log(confirmationNr);
  })
  .on("receipt", function(receipt){
      console.log(receipt);

  });

};

And this runs fine too, Until I hit the #BreedNewCat button.
after this the Tx happens on Metamask , but then it says property “slice” of undefined:

see below the catalogue.js file :point_down:
catalogue.js

var web3 = new Web3(Web3.givenProvider);
var contractInstance;
var contractAddress="0xF2224FC1C0149FA056bE9ABc45b48bE3bad516B5";
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 dna = event.returnValues.genes;

  });
  $("#BackToShoppingButton").click(async()=>{
    await window.location.replace("/client/index.html");
  });
  $("#BackToBreedingButton").click(async ()=> {
    await window.location.replace("/client/breed.html");
  });
  $('#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);
});
});

  async function renderNewCat() {

    newDna.headColor = dna.slice(0,2);
    newDna.mouthColor = dna.slice(2,4);
    newDna.eyesColor = dna.slice(4,6);
    newDna.earsColor = dna.slice(6,8);
    newDna.eyesShape = dna.slice(8,9);
    newDna.decorationPattern = dna.slice(9,10);
    newDna.decorationMidcolor = dna.slice(10,12);
    newDna.decorationSidescolor = dna.slice(12,14);
    newDna.animation = dna.slice(14,15);
    newDna.lastNum = dna.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);

};

also, the Catalogue.html file :point_down:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title> Catalogue </title>
  <script type="text/javascript" src="assets/js/jquery-3.4.1.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
  <!-- <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="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>
  <script src="assets/js/abi.js"></script>
  <script src="assets/js/web3.min.js"></script>
  <link rel="stylesheet" href="assets/css/mystyle.css">
  <link rel="stylesheet" href="assets/css/animations.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-white">My Catalogue</h1>

            </div>

            <br>
            <div class="row">

                <div class="col-lg-12 cattributes m-2 light-b-shadow">
                  <div class="cat">
                      <div class="cat__ear">
                          <div id="leftEar" class="cat__ear--left">
                              <div class="cat__ear--left-inside"></div>
                          </div>
                          <div id="rightEar" class="cat__ear--right">
                              <div class="cat__ear--right-inside"></div>
                          </div>
                      </div>

                      <div id="head" class="cat__head">
                          <div id="midDot" class="cat__head-dots">
                              <div id="leftDot" class="cat__head-dots_first"></div>
                              <div id="rightDot" class="cat__head-dots_second"></div>
                          </div>
                          <div class="cat__eye">
                              <div class="cat__eye--left">
                                  <span class="pupil-left"></span>
                              </div>
                              <div class="cat__eye--right">
                                  <span class="pupil-right"></span>
                              </div>
                          </div>
                          <div class="cat__nose"></div>
                          <div class="cat__mouth-contour"></div>
                          <div class="cat__mouth-left"></div>
                          <div class="cat__mouth-right"></div>
                          <div class="cat__whiskers-left"></div>
                          <div class="cat__whiskers-right"></div>
                      </div>
                      <div class="cat__body">
                          <div class="cat__chest"></div>
                          <div class="cat__chest_inner"></div>
                          <div class="cat__paw-left"></div>
                          <div class="cat__paw-left_inner"></div>


                          <div class="cat__paw-right"></div>
                          <div class="cat__paw-right_inner"></div>


                          <div id="tail" class="cat__tail"></div>
                      </div>
                  </div>
                  <br>
                  <div class="dnaDiv" id="catDNA">
                      <b>
                          DNA:
                          <!-- Colors -->
                           <span id="dnabody"></span>
                           <span id="dnamouth"></span>
                           <span id="dnaeyes"></span>
                           <span id="dnaears"></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>

<br><br>
                    <div id="BackToShoppingButton" class="d-flex justify-content-center">
                        <button class="btn btn-success">Go Shopping More Cats</button>
                    </div><br>
                    <div id="BackToBreedingButton" class="d-flex justify-content-center">
                        <button class="btn btn-success">Go Breeding More Cats</button>
                    </div>
                </div>
            </div>
          </div>


        <footer align="left">
            <p>Ivan on Tech Academy - Asignment</p>
        </footer>
  </body>



  

and my breed.html file :point_down:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title> Catalogue </title>
  <script type="text/javascript" src="assets/js/jquery-3.4.1.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
  <!-- <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="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>
  <script src="assets/js/abi.js"></script>
  <script src="assets/js/web3.min.js"></script>
  <link rel="stylesheet" href="assets/css/mystyle.css">
  <link rel="stylesheet" href="assets/css/animations.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-white">My Catalogue</h1>

            </div>

            <br>
            <div class="row">

                <div class="col-lg-12 cattributes m-2 light-b-shadow">
                  <div class="cat">
                      <div class="cat__ear">
                          <div id="leftEar" class="cat__ear--left">
                              <div class="cat__ear--left-inside"></div>
                          </div>
                          <div id="rightEar" class="cat__ear--right">
                              <div class="cat__ear--right-inside"></div>
                          </div>
                      </div>

                      <div id="head" class="cat__head">
                          <div id="midDot" class="cat__head-dots">
                              <div id="leftDot" class="cat__head-dots_first"></div>
                              <div id="rightDot" class="cat__head-dots_second"></div>
                          </div>
                          <div class="cat__eye">
                              <div class="cat__eye--left">
                                  <span class="pupil-left"></span>
                              </div>
                              <div class="cat__eye--right">
                                  <span class="pupil-right"></span>
                              </div>
                          </div>
                          <div class="cat__nose"></div>
                          <div class="cat__mouth-contour"></div>
                          <div class="cat__mouth-left"></div>
                          <div class="cat__mouth-right"></div>
                          <div class="cat__whiskers-left"></div>
                          <div class="cat__whiskers-right"></div>
                      </div>
                      <div class="cat__body">
                          <div class="cat__chest"></div>
                          <div class="cat__chest_inner"></div>
                          <div class="cat__paw-left"></div>
                          <div class="cat__paw-left_inner"></div>


                          <div class="cat__paw-right"></div>
                          <div class="cat__paw-right_inner"></div>


                          <div id="tail" class="cat__tail"></div>
                      </div>
                  </div>
                  <br>
                  <div class="dnaDiv" id="catDNA">
                      <b>
                          DNA:
                          <!-- Colors -->
                           <span id="dnabody"></span>
                           <span id="dnamouth"></span>
                           <span id="dnaeyes"></span>
                           <span id="dnaears"></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>

<br><br>
                    <div id="BackToShoppingButton" class="d-flex justify-content-center">
                        <button class="btn btn-success">Go Shopping More Cats</button>
                    </div><br>
                    <div id="BackToBreedingButton" class="d-flex justify-content-center">
                        <button class="btn btn-success">Go Breeding More Cats</button>
                    </div>
                </div>
            </div>
          </div>


        <footer align="left">
            <p>Ivan on Tech Academy - Asignment</p>
        </footer>
  </body>



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


</html>

Not sharing my Index.html file because that page is running smoothly :

Can You please have a detailed Look at my Code and advise me what all I am doing wrong and How to correct the same ? I just want to create one Box with the Cat the owner owns after breeding it => not too fancy stuff because I would forever be lost in Java Script and I want to avoid that

*But if you tell me its necessary to learn more, I will do it *

I really want to learn Blockchain Programming and I am really trying extremely hard - sometime even 10 hours a Day , and when i fail completely i write such lengthy threads on the forum hoping you will help me soon.

In my opinion the problem lies in catalogue.js where my the cat dna is not visible, because i tried to extract it out of the event: Birth and then slice it into 2 digits each to assign values to newDna.headColor, newDna.mouthColor and so on .

If this is not the right way, then what is the right way ?

Thanks and Regards

su.kal Crypto

Hi @kenn.eth
So In fact sending you my index.html file and also catSettings.js, catfactory.js and animations.js files too :point_down:
index.html

<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/abi.js"></script>
  <script src="assets/js/web3.min.js"></script>



  <link rel="stylesheet" href="assets/css/mystyle.css">
  <link rel="stylesheet" href="assets/css/animations.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">
          <h3 class = "c-white"><span id="jackpot_output"></span></h3>
          <h4 class = "c-white"><span id="jackpot_output1"></span></h4>
        </div>
        <div align="center">
        <h1 class="c-white">Kitties-Factory</h1>
        <p class="c-white">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="cat__ear">
                        <div id="leftEar" class="cat__ear--left">
                            <div class="cat__ear--left-inside"></div>
                        </div>
                        <div id="rightEar" class="cat__ear--right">
                            <div class="cat__ear--right-inside"></div>
                        </div>
                    </div>

                    <div id="head" class="cat__head">
                        <div id="midDot" class="cat__head-dots">
                            <div id="leftDot" class="cat__head-dots_first"></div>
                            <div id="rightDot" class="cat__head-dots_second"></div>
                        </div>
                        <div class="cat__eye">
                            <div class="cat__eye--left">
                                <span class="pupil-left"></span>
                            </div>
                            <div class="cat__eye--right">
                                <span class="pupil-right"></span>
                            </div>
                        </div>
                        <div class="cat__nose"></div>
                        <div class="cat__mouth-contour"></div>
                        <div class="cat__mouth-left"></div>
                        <div class="cat__mouth-right"></div>
                        <div class="cat__whiskers-left"></div>
                        <div class="cat__whiskers-right"></div>
                    </div>
                    <div class="cat__body">
                        <div class="cat__chest"></div>
                        <div class="cat__chest_inner"></div>
                        <div class="cat__paw-left"></div>
                        <div class="cat__paw-left_inner"></div>


                        <div class="cat__paw-right"></div>
                        <div class="cat__paw-right_inner"></div>


                        <div id="tail" class="cat__tail"></div>
                    </div>
                </div>
                <br>
                <div class="dnaDiv" id="catDNA">
                    <b>
                        DNA:
                        <!-- Colors -->
                         <span id="dnabody"></span>
                         <span id="dnamouth"></span>
                         <span id="dnaeyes"></span>
                         <span id="dnaears"></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 & cattributes-->
              <div id="catColors">
                <div class="form-group">
                    <label for="formControlRange"><b>Head | body</b><span class="badge badge-dark ml-2" id="headcode"></span></label>
                    <input type="range" min="10" max="98" class="form-control-range" id="bodycolor">
                    <label for="formControlRange"><b>Mouth | Tail</b><span class="badge badge-dark ml-2" id="mouthcode"></span></label>
                    <input type="range" min="10" max="98" class="form-control-range" id="mouth_tail_color">
                    <label for="formControlRange"><b>Eyes</b><span class="badge badge-dark ml-2" id="eyescode"></span></label>
                    <input type="range" min="10" max="98" class="form-control-range" id="eyescolor">
                    <label for="formControlRange"><b>Ears | Paws </b><span class="badge badge-dark ml-2" id="earscode"></span></label>
                    <input type="range" min="10" max="98" class="form-control-range" id="earscolor">
                    <label for="formControlRange"><b>Eyes Shape</b><span class="badge badge-dark ml-2" id="eyename"></span></label>
                    <input type="range" min="1" max="5" class="form-control-range" id="eyesshape">
                    <label for="formControlRange"><b>Decoration</b><span class="badge badge-dark ml-2" id="decorationname"></span></label>
                    <input type="range" min="1" max="4" class="form-control-range" id="decorationpattern">
                    <label for="formControlRange"><b>Side BirthMarks Color</b><span class="badge badge-dark ml-2" id="sidebirthmarkscode"></span></label>
                    <input type="range" min="10" max="98" class="form-control-range" id="decorationsidescolor">
                    <label for="formControlRange"><b>Mid BirthMark Color</b><span class="badge badge-dark ml-2" id="midbirthmarkcode"></span></label>
                    <input type="range" min="10" max="98" class="form-control-range" id="decorationmidcolor">
                    <label for="formControlRange"><b>Animation</b><span class="badge badge-dark ml-2" id="animationcode"></span></label>
                    <input type="range" min="1" max="4" class="form-control-range" id="animationstyle">

                </div>
              </div>


            </div>
          </div>
          <div class="column">

                <button id = "defaultkitty" class= "btn btn-primary"> Default Kitty </button><a>
                <button id = "randomkitty" class = "btn btn-primary"> Random Kitty </button><a>
                <button id = "mintkitty" class = "btn btn-secondary">Mint Kitty on the Blockchain</button>
                <button id = "breedkitty" class = "btn btn-primary"> Breed Your Own Kitty </button><b><b>

          </div>
          <br>
        </div>
      </div>



            <footer align="left">
              <p>Ivan on Tech Academy - Asignment</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>

catSettings.js: :point_down:

var colors = Object.values(allColors())

var defaultDNA = {
    "headColor" : 10,
    "mouthColor" : 13,
    "eyesColor" : 96,
    "earsColor" : 10,
    //Cattributes
    "eyesShape" : 1,
    "decorationPattern" : 1,
    "decorationMidcolor" : 13,
    "decorationSidescolor" : 13,
    "animation" :  1,
    "lastNum" :  1
    }

// when page load
$( document ).ready(function() {
  $('#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)

  renderCat(defaultDNA)
});

function getDna(){
    var 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()


    return parseInt(dna)
}

function renderCat(dna){
    headColor(colors[dna.headColor],dna.headColor)
    $('#bodycolor').val(dna.headColor)
    mouthColor(colors[dna.mouthColor],dna.mouthColor)
    $('#mouth_tail_color').val(dna.mouthColor)
    eyesColor(colors[dna.eyesColor],dna.eyesColor)
    $('#eyescolor').val(dna.eyesColor)
    earsColor(colors[dna.earsColor],dna.earsColor)
    $('#earscolor').val(dna.earsColor)
    eyeVariation(dna.eyesShape)
    $('#eyesshape').val(dna.eyesShape)
    decorationVariation(dna.decorationPattern)
    $('#decorationpattern').val(dna.decorationPattern)
    sidesDecorationColor(colors[dna.decorationSidescolor],dna.decorationSidescolor)
    $('#decorationsidescolor').val(dna.decorationSidescolor)
    midDecorationColor(colors[dna.decorationMidcolor],dna.decorationMidcolor)
    $('#decorationmidcolor').val(dna.decorationMidcolor)
    animationStyle(dna.animation)
    $('#animationstyle').val(dna.animation)
}

//LISTENERS

// Changing cat's Body' colors
$('#bodycolor').change(()=>{
    //var bodyColorCode = $('#bodycolor').val();
    //console.log(bodyColorCode);
    var colorVal = $('#bodycolor').val()
    headColor(colors[colorVal],colorVal)
})

// Changing Cat's Mouth color
$('#mouth_tail_color').change(()=>{
  var colorVal = $('#mouth_tail_color').val()
  mouthColor(colors[colorVal],colorVal)

})

//Changing cat's eyes color
$('#eyescolor').change(()=>{
  var colorVal = $('#eyescolor').val()
  eyesColor(colors[colorVal],colorVal)
})

//Changing cat's ears colors
$('#earscolor').change(()=>{
  var colorVal = $('#earscolor').val()
  earsColor(colors[colorVal],colorVal)
})


//Changing Cat eyes Shape
$('#eyesshape').change(()=>{
  var shape = parseInt($('#eyesshape').val())
  eyeVariation(shape)
})


//Changing Decoration pattern
$('#decorationpattern').change(()=>{
  var pattern = parseInt($('#decorationpattern').val())
  decorationVariation(pattern)
})


//Changing The Side Birthmarks colors

$('#decorationsidescolor').change(()=>{
  var colorVal = $('#decorationsidescolor').val()
  sidesDecorationColor(colors[colorVal],colorVal)
})

$('#decorationmidcolor').change(()=>{
  var colorVal = $('#decorationmidcolor').val()
  midDecorationColor(colors[colorVal],colorVal)
})



$('#animationstyle').change(()=>{
  var animationVal = parseInt($('#animationstyle').val())
  animationStyle(animationVal)
})


$('#defaultkitty').click(async()=>{
  renderCat(defaultDNA);
})

$('#randomkitty').click(async()=>{
    var colorVal = Math.floor(Math.random() * 89) + 10
    headColor(colors[colorVal],colorVal)

    var colorVal = Math.floor(Math.random() * 89) + 10
    mouthColor(colors[colorVal],colorVal)

    var colorVal = Math.floor(Math.random() * 89) + 10
    eyesColor(colors[colorVal],colorVal)

    var colorVal = Math.floor(Math.random() * 89) + 10
    earsColor(colors[colorVal],colorVal)

    var shape = Math.floor(Math.random() * 5) + 1
    eyeVariation(shape)

    var pattern = Math.floor(Math.random() * 4) + 1
    decorationVariation(pattern)

    var colorVal = Math.floor(Math.random() * 89) + 10
    sidesDecorationColor(colors[colorVal],colorVal)

    var colorVal = Math.floor(Math.random() * 89) + 10
    midDecorationColor(colors[colorVal],colorVal)

    var animationVal = Math.floor(Math.random() * 4) + 1
    animationStyle(animationVal)
})

catFactory.js :point_down:


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

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

//This function changes the color of Head and Chest
function headColor(color,code) {
    $('.cat__head, .cat__chest').css('background', '#' + color)  //This changes the color of the cat
    $('#headcode').html('code: '+code) //This updates text of the badge next to the slider
    $('#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(color,code){
  $('.cat__mouth-left, .cat__mouth-right, .cat__tail').css('background', '#' + color) //This changes the Cat's Mouth and Tail Colors
  $('#mouthcode').html('code: ' + code) // This updates text of the badge next to the slider
  $('#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(color,code){
  $('.cat__eye span.pupil-left, .cat__eye span.pupil-right').css('background', '#' + color) //This changes the Cat's Mouth and Tail Colors
  $('#eyescode').html('code: ' + code) // This updates text of the badge next to the slider
  $('#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(color,code){
  $('.cat__ear--left, .cat__ear--right, .cat__paw-left, .cat__paw-right').css('background', '#' + color) //This changes the Cat's ears Colors
  $('#earscode').html('code: ' + code) // This updates text of the badge next to the slider
  $('#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) {

    $('#dnashape').html(num)//This updates the Eyes shape part of the DNA that is displayed below the Cat

    switch (num) {
        case 1:
            normalEyes()
            $('#eyename').html('Basic')// Set the badge of the eye to 'Basic'
            break
        case 2:
            normalEyes()//reset
            $('#eyename').html('Chill')//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')//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')//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
    }
}



async function normalEyes() {
    await $('.cat__eye').find('span').css('border', 'none')
}

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

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

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

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

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

//Changing Cat BirthMark Dimensions + Rotation
function decorationVariation(num) {
    $('#dnadecoration').html(num)//This updates the DNA Decoration part of the DNA that is displayed below the Cat
    switch (num) {
        case 1:
            normalDecoration()
            $('#decorationname').html('Basic')// Set the Badge to Decoration pattern Basic
            break
        case 2:
            normalDecoration()
            $('#decorationname').html('Angled Patches')// Set the Badge to Decoration pattern - Angled patches
            normalDecoration1()
            break
        case 3:
            normalDecoration()
            $('#decorationname').html('Smaller Width Patches')// Set the Badge to Decoration pattern - Smaller Patches
            normalDecoration2()
            break
        case 4:
            normalDecoration()
            $('#decorationname').html('Smaller Height Patches')// Set the Badge to Decoration pattern - Smaller Patches
            normalDecoration3()
            break
    }
}



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


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

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

async function normalDecoration3() {
    //Remove all style from other decorations
    //In this way we can also use normalDecoration() to reset the decoration style
    $('.cat__head-dots').css({ "transform": "rotate(0deg)", "height": "24px", "width": "8px", "top": "1px", "border-radius": "0 0 50% 50%" })
    $('.cat__head-dots_first').css({ "transform": "rotate(0deg)", "height": "20px", "width": "8px", "top": "1px", "border-radius": "50% 0 50% 50%" })
    $('.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(color,code) {
    $('.cat__head-dots_first , .cat__head-dots_second').css('background', '#' + color)  //This changes the color of the cat's Side BirthMark
    $('#sidebirthmarkscode').html('code: '+ code) //This updates text of the badge next to the slider
    $('#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(color,code) {
    $('.cat__head-dots').css('background', '#' + color)  //This changes the color of the cat's Mid Birthmark
    $('#midbirthmarkcode').html('code: '+ code) //This updates text of the badge next to the slider
    $('#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){
  $('#dnaanimation').html(num)//This updates the DNA animation style of the DNA that is displayed below the Cat
  switch (num) {
    case 1 :
    normalAnimation()
    $('#animationcode').html('Moving Head')//It sets the Badge to Moving Head style
    break
    case 2 :
    animationType1()
    $('#animationcode').html('Big Head') // It sets the Badge to Scaled Head style
    break
    case 3 :
    animationType2()
    $('#animationcode').html("Translated Head")//It setsthe  Badge to Transitioned/Transported Head style
    break
    case 4 :
    animationType3()
    $('#animationcode').html('Moving Tail')// It sets the badge to Moving Tail animation style
    break
  }
}



function normalAnimation() {  //Head rotates and moves
  resetAnimation()
  $('#head').addClass('movingHead')
}

function animationType1() {  //Head gets scaled
  resetAnimation()
  $('#head').addClass('scalingHead')

}


function animationType2() { //Head gets translated
  resetAnimation()
  $('#head').addClass('translatingHead')
}


function animationType3() { //Tail starts Moving
  resetAnimation()
  $('#tail').addClass('movingTail')
}

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


}

animations.js :point_down:

.movingHead {
  animation: moveHead 1s infinite;
}


@keyframes moveHead {
    0% {
      transform: rotate(0deg);
    }

    30% {
      transform : rotate(7deg);
    }

    60% {
      transform:rotate(-7deg);
    }
    100% {
      transform:rotate(0deg);
    }
}

.scalingHead {
  animation: scaleHead 1s infinite
}

@keyframes scaleHead {
  0% {
    transform: scale(1);
  }

  30% {
    transform : scale(1.1);
  }

  60% {
    transform: scale(0.9);
  }
  100% {
    transform: scale(1);
  }

}


.translatingHead {
  animation: translateHead 1s infinite
}


@keyframes translateHead {
  0% {
    transform: translate(0px);
  }
  25% {
    transform: translate(40px);
  }
  50% {
    transform: translate(0px);
  }
  75% {
    transform:translate(-40px);
  }
  100% {
    transform: translate(0px);
  }
}



.movingTail {
  animation: moveTail 1s infinite
}

 @keyframes moveTail {
  0%  {
     transform: rotate(0deg)
  }
  50%  {
    transform: rotate(45deg);
  }
  100% {
    transform: rotate(0deg)
  }
}

Thanks and Regards
And looking forward to your Kind answer :point_up:
If you want I can send my rep too

Thanks and Regards

Su.Kal Crypto

1 Like

Hey @Su.kal.Crypto in order to run your code to check errors, would be better to upload all your code to a git repository in github. So i can run it fully. What I can notice you are doing different is that, dna.slice is failing because there is not **dna** defined into this file. For dna.slice, you should pass the dna as an argument to the function like this :

renderNewCat(dna)

With valid dna value to let the function able to slice it.
I know is hard to understand javascript and specially when is apply into blockchain programming. But by keep going, you will be very unique learning this kind of technoligy and skills.

Hi @kenn.eth

Thanks a ton for your Help.
Here below is my Github Code:
https://github.com/Suveett/CryptoKitties.git

As you will see, a renderNewCat(newDna) function is already there in my breed.js file.

However, my dna is still not found because i tried to extract it from contractInstance.events.Birth.returnValues.genes

I guess this is not working , and honestly I am not able to extract the DNA (genes) in any other meaningful way or function (that i can currently think of !! ) , I also copied Filip’s code of retrieving the uint[] memory of tokenId’s that an owner address owns.

uint[] memory result = new uint[](tokenOwnershipCount[_owner]);

But I am unable to extract the DNA anyhow, hence i tried to extract it from an event , which i know is asynchronous, but thats why i created a asynchronous function renderNewCat(), **but its still not working , so i am unable to wrap my head around it as to how to make the newDna value appear so that the function can do its work properly **?

Please have a look at my code and let me know, I tried again before writing to you , BUT NO SUCCESS YET

As you will also see in my breed.js , i passed the renderNewCat() function in this file :point_down:

$('#BreedCatButton').click(async () =>{
         await breedKitty();
         await renderNewCat();

You know because i was presuming that when the User clicks “#BreedCatButton”, by the time the user goes to the catalogue page, the await breedKitty() function would have generated the Event ‘Birth’ and newDna = contractInstance.events.Birth.returnValues.genes , would capture the value of newDna and this value would be looped into the renderNewCat(newDna) would Run perfectly.

But it seems my whole Logic is wrong :thinking: In Fact I kind of understand that my logic is wrong because my dna variable is inside the window.ethereum.enable() and maybe its not visible outside the function or maybe its the fact that the event has not passed until my function starts running ?
What could be the case ??

Let me know how to correct !!

Thanks and Regards

Su.Kal Crypto

Alright! Gotta read the code today and let you know what happen tomorrow. For the moment what I can see is that you are not adding the argument into the function definition. Look at your code in this picture:

2021-05-13_16h51_43
For using the prop of dna you have to pass it like this
async function renderNewCay(dna)

Sure… Eagerly awaiting your answer !!

Sorry for late response. I test your code and cannot run it because there is some missing folders like assets. Please upload your fully code in order for me to try correctly.
2021-05-15_19h51_26

Your index.html
2021-05-15_19h51_51

For bootstrap libraries you can use CDN, so no need to upload it. You can get it from here
https://getbootstrap.com/docs/5.0/getting-started/download/

Hi Kenneth

Really sorry, I am really out of my mind because recently I just lost my Maternal Uncle (Age : 54 years old) to Covid 19 , causing excruciating Pain in the family and within me too.

I have just uploaded all the other files you asked for , especially the css files.So you can now check my Github Repository !!
https://github.com/Suveett/CryptoKitties.git

I think the abi.js and web3.min.js were already there before.

I honestly am a New developer so I really don’t know that much about how to Navigate Github and create Folders within the “Main”, hence I committed everything on the “Main” Branch (maybe you can teach me this too, if you don’t mind ?)

In fact, I have just attached my CryptoKitties.zip folder also on my Github Repository, so I hope that shall be enough ??

Awaiting your Kind reply after checking my Code.

Thanks and Regards

Suveett Kalra

Su.Kal Crypto

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