Assignment - Event

hey @Samuel1 yeah most people are having this issue with metamask. So I got a few advices:

  1. For this metamask update , I just dig into it and install a new extension Metamask Legacy Web3
    from here

  2. Try using same enable method and the way you were using web3 like the course.

So I downloaded the Metamask Legacy Web3 extension. When I create an order, I receive a transaction hash in the console. It even registers a transaction in MetaMask, but there is no instance nor is there a pop-up for creating an order.
My code:


var web3 = new Web3(Web3.givenProvider);

let order; 
let accounts;
let instance;
let user;
let abi;
let contractAddress= "0xDe34Ee16b231EFFeBe073E3BA587E06Fa55d85B1";
$(document).ready(function(){
  window.ethereum.enable().then(function(accounts){
    instance = new web3.eth.Contract(abi, contractAddress, {from: accounts[0]});
    user = accounts[0];
    console.log(instance);
    instance.events.OrderMade().on('data', function(event){
      console.log(event);
      let owner = event.returnValues.owner;
      console.log(owner);
      let orderId = event.returnValues.orderVolumeId;
      console.log(orderId);
      let cost = event.returnValues.cost;
      console.log(cost);
      let productName = event.returnValues.productName;
      console.log(productName);
      let description = event.returnValues.description;
      console.log(description);
      let leadTime_in_days = event.returnValues.leadTime_in_days;
      console.log(leadTime_in_days);
  
      $("#OrderMade").css("display", "block");
      $("#OrderMade").text( "OrderId: " + orderId + 
                             "Owner: " + owner + 
                             "cost: "+ cost + 
                             "ProductName: " + productName +
                             "description: " + description +
                             "leadTime: " + leadTime_in_days
                              );
  
  })
  .on('error', console.error)
  })
})
const _createOrder = async () => {
  order = await window.ethereum.request({method: 'eth_requestAccounts'}).catch((err) => {
      console.log(err.code);
  })
  console.log(order);
} 
  
My HTML:
<meta charset="UTF-8">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 

<meta name="viewport" content="width=device-width">

  <title>SCP</title>

  <link rel="stylesheet" href="Styling/bootstrap.min.css">

  <script scr="StylingJS/popper.js"></script>

  <script src="StylingJS/web3.min.js"><script>

  <script src="./abi.js"></script>

  <script src="StylingJS/jquery-3.4.1.js"></script>

<link rel="stylesheet" href="Styling/style.css">

<link rel="stylesheet" href="Styling/bootstrap.css">

<link re="stylesheet" href="Styling/homepage.css">

<link rel="stylesheet" href="Styling/order.css">

<link rel="stylesheet" href="Styling/frontEnd.css">



</head>
<div class="container p-4" style="margin-right: 2vh;margin-bottom: 23vh;">

      <div align="center">

<h1>Supply Chain Order Factory</h1>

<h>Tracking Supply Chain Orders</h>
<div id="order">

<h2>Product Order</h2>

<table>

<thead>

<th>ID</th>

<th>Cost</th>

<th>Product Name</th>

<th>Description</th>

<td>Lead Time</td>



</thead>

<tr>

<td><input/></td>

<td><input/></td>

<td><input/></td>

<td><input/></td>

<td><input/></td>



</tr>

</table>

<button onclick="_createOrder()">Create Product Order</button>

<div class="alert alert-success" roles="alert" id="OrderMade" style="display:none">

</div>

</div>

</div>

</div>

<br>

                                          

      </div>

  </div>

</body>

<script src="./index.js"></script>
``` ```

So here is my whole project, the Web3 connect to MetaMask still does NOT workā€¦
https://github.com/THEMERLINGROUP/SupplyChain/tree/master/FrontEnd

Hi @Samuel1,

Your GitHub repository link isnā€™t available. Iā€™ll try cloning it and check it out.

Iā€™ve manually navigated to your repo but thereā€™s only a ReadMe file available.

1 Like

Hi, my code worked the first time I deployed my contract and connected it to web3 (I made two tokens and received the alert on index.html), I was using Ganache network. The next day I tried again to see the alert, but I could not create the token. I got a few errors when attempted to create a token:

  1. the metamask account showed an error (ā€œno conversion rate availableā€)
  2. and also ā€œGas limit must be at least 21000ā€

I had not changed anything on the code. And my token creation failed. Has anyone faced this problem? Here are the errors I got in my browser console:

Uncaught (in promise) ReferenceError: on is not defined
at index.js:14
this error was present even in my first attempt, yet I succeeded in creating a token. I dont know why I am getting error for ā€œevent.onā€

inpage.js:1 MetaMask - RPC Error: TxGasUtil - Trying to call a function on a non-contract address Object
(anonymous) @ inpage.js:1
I have checked the metamask again and the ā€œto addressā€ is not my contractā€™s address but I dont know where to set it right. In my index.js, I have correctly made note of the contract address and yet I see that metamask is not consistent here.

index.js:37 Uncaught (in promise) ReferenceError: err is not defined
at index.js:37
at Object._fireError (web3.min.js:1)
at u (web3.min.js:1)
at web3.min.js:1
at s._handle (inpage.js:17)
DevTools failed to load source map: Could not load content for http://localhost:8000/assets/bootstrap/js/popper.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
Iā€™d like to get your opinion on this error, please check out the index.js below:

hereā€™s my index.js code:

var web3 = new Web3(Web3.givenProvider);

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


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

        console.log(instance);
        instance.events.Birth().on('data', function(event){
            console.log(event);
            let owner = event.returnValues.owner;
            let carId = event.returnValues.carId;
            let mumId = event.returnValues.mumId;
            let dadId = event.returnValues.dadId;
            let genes = event.returnValues.genes;
            $("#carCreation").css("display", "block");
            $("#carCreation").text("Car successfully created: owner:"+owner
                                    +" carId:"+carId
                                    +" mumId:"+mumId
                                    +" dadId:"+dadId
                                    +" genes:"+genes)
        })
        .on('error', console.error)
            
        })
    })


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

if you need more information please let me know. I really appreciate any help I can get.!!

image

should the account hash on the top right be my contract address?

very good @Vivek20, how in the world did you figure this out
I read the docs and stared at the same thing but i just could not put it together
anyways, well done

Thanks for the compliment. I mostly ran into operational issues with truffle and web3 etc. but the solidity code worked well. Itā€™s been a while since I did this assignment but I remember it being fun. I will be glad to have a look if you need help after the Moralis Hackathon deadline of Tuesday :).

1 Like

In my case, in order for window.ethereum to work as expected, I had to view my website via pythonā€™s local host. After that, everything (window.ethereum and MetaMask issues) worked just fine.

1 Like

Sorry, I took a while to reply - Iā€™ve had to take a quick free-lance gig - - yeah - I will be sure to have some questions for you by next week

I was not able to figure it out so I had to watch Filipā€™s tutorial


var web3 = new Web3(Web3.givenProvider);

// event listeners and buttons---------
// https://youtu.be/NseL8v9EH_Q

const onboardButton = document.querySelector('#connectButton');

const getAccountsButton = document.querySelector('#getAccounts');
const viewCatResult = document.querySelector('#catResultId');

// event listeners and buttons---------

if (typeof window.ethereum !== 'undefined') {
  console.log('MetaMask is installed!');
  $("#metamaskStatus").text("MetaMask is installed!");
}

// ----------------------get cat-------------------------------------------

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

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

    console.log(instance);

    instance.events.Birth().on('data', function(event) { //function with callback
      console.log(event);
      let owner = event.returnValues.owner;
      let kittenId = event.returnValues.kittenId;
      let mumId = event.returnValues.kittenId;
      let dadId = event.returnValues.dadId;
      let genes = event.returnValues.genes
      
      $("#catResultId").text("owner: " + owner
      +" KittyId: " + kittenId
      +" mumId: " + mumId
      +" dadId: " + dadId
      +" genes: " + genes)
      $("#createCat").val(viewCatResult);
      
    })
  
    .on('error', console.error);
    
    });

    function createKitty() {
      var dnaStr = getDna();
      instance.methods.createKittyGen0(dnaStr).send({}, function(error, txHash) {
        if(error)
          console.log(error);
        else{
          console.log(txHash);
        } 
      })

    }

    $('#createCat').click(() =>{
      createKitty(getDna());
    })


    getAccountsButton.addEventListener('click', async () => {
      //we use eth_accounts because it returns a list of addresses owned by us.
      const accounts = await ethereum.request({ method: 'eth_accounts' });
      //We take the first address in the array of addresses and display it
      getAccountsResult.innerHTML = accounts[0] || 'Not able to get accounts';
    
    });

  })

<div class="row justify-content-start">
          <div class="col-lg-12 buttonsBox3">
            <button id="connectButton" type="submit" class= "catButtons">Enable Ethereum</button>
            <p class="smallType">metamask: <span id="metamaskStatus"> </span> </p>

            <button id="getAccounts" type="submit" class= "catButtons">Get Accounts</button>
            <p class="smallType">account: <span id="getAccountsResult"> </span></p>
            
            <!--<h2>balance: <span id="showBalance"> </span></h2>-->
            
            <button id="createCat" type="submit" class= "catButtons">Create Cat</button>
            <p class="smallType">cat result: <span id="catResultId"> </span></p>

Issues with truffle compile (Right terminal), left terminal is the python webserver (not also sure if this works properly)

image

When I launch the python webserver I have to manually navigate thru the client folder so the webpage loads. BUT the Metamask prompt works and is connecting properly.

Many Thanks!

Hereā€™s my assignment, I think itā€™s not working properly because I canā€™t see the alerts I made :sweat_smile:

Anyway hereā€™s the code (need help fixing):

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

var instance;
var user;
var contractAddress = "0xA3212250342AbEDb2EDA8A6a95e37c58B9Bd9079"; //enter contact address here

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

        console.log(instance);
    })
})

function createKitty() {
    var kittyDna = getDna();
    instance.methods.createKittyGen0(kittyDna).send({}, function(err, txHash) {
        if(err) {
            console.log(err);
        } else {
            alert("Transaction sent!");
            console.log(txHash);
            instance.events.Birth().on('connected', function(subscriptionId) {
                console.log(subscriptionId);
            }) 
            .on('error', function(error){
                console.log(error);
                alert("Kitty Birth failed");
            })
            .on('data', function(event) {
                alert(`Kitty birth successful! \n
                Kitty Owner: ${event.returnValues.owner}\n
                Kitty ID: ${event.returnValues.kittenId}\n
                Mommy Cat: ${event.returnValues.mumId}\n
                Daddy Cat: ${event.returnValues.dadId}\n
                Kitty Genes: ${event.returnValues.genes}
                `)
            })
        }
    })
}

$('#create').click(() => {
    createKitty(getDna());
})

Hereā€™s the code in for the create button in index.html:

<button id="create" type="button" class="btn btn-success my-2 my-sm-0" >Create Kitty</button>```

Hey @CryptoXyz, hope you well.

It would be easier for me to review your project if you can create a github repo where i can download the entire project and run it locally for me, i would like to replicate the issue by myself :nerd_face:

Carlos Z

1 Like

Hi @thecil, hereā€™s my GitHub repo :v:

CryptoKitties - repo

Hi, I need help, I canā€™t fix the error that was thrown

  • An error happens when I click the ā€œcreate kittyā€ button
  • The console ā€œsourcesā€ say that the error is at ā€œweb3.min.jsā€

image

Many thanks, man

I think the code is working properly, the issue happens with the default cat, when you try to create it, but if you randomly create another one, then the transaction is triggered properly.
image

Now the issue appears when your generated Cat dna start higher than 90 (Head and body).

I do remember that filip mention something about not having more than 89 values because a bug like this.

I randomly started to generate cats, those that his Head and body value are above 90, the web3 error shows up, but all below those, can be created properly.

Carlos Z

1 Like

Awesome analysis man! Thank you so much

Never thought that starting with a Kitty DNA higher than 90 would create an issue. Thanks, man, I need to watch out for errors like this one.

Have an awesome day! :wave:

1 Like

Hi there, Iā€™m having trouble with the python server, it does not display the changes I made on my code. (it still loads the previous code). But when I use a live server on VS code, the changes are implemented.

The change I made was just on the default cat and the slider range.

It happens some times with python web server, by closing the program (ctrl+c) and running it again does the trick most of the times, basically there are some changes that will be applied when rebooting the webserver (while this does not happen that often with VS live server)

Carlos Z

1 Like