Assignment - Marketplace Frontend

Remember that creating gen0 cats function is allowed only to the owner of the contract (deployer address), are you sure “Account 4” is the deployer ?

First time I deployed your dapp:
image

Carlos Z

Thank you for taking another look at my issue @thecil .

When you ran my code on your computer did it work for you?

I’m assuming that account 0 is the deployer which is the account shown when i migrate (picture 2). The metamask imported account shown in picture 1 is the same as the account address displayed in picture 2.

Screenshot 2021-07-28 at 11.17.15

Screenshot 2021-07-28 at 11.17.33

Also could could this be an issue:

Screenshot 2021-07-28 at 11.24.59

In one of the last lectures Filip said we need to subtract 1 from the gen variable. The compiler and pragma solidity version that i am using is more up to date and this syntax doesn’t work:
_createCat(0, 0, 0, gen-1, address(0))
i’m not sure what the correct syntax is to write this is.

Thanks again. I know this must be frustrating for you too haha. Sorry to be a such a nuisance.

Is it possible to share the final code of the project?
I am mostly into the backend and don’t feel like figuring out the IU for the marketplace, breeding, displaying, etc.

Thanks a lot for creating a very engaging and fun project - it is a great way to learn.

@thecil When you cloned my repository and ran it on your computer were you able to successfully create a cat? Or did it not work for you either?

Ive had this issue for over 2 months now and nothing has worked so far. Not sure what the best move is going forward

Thanks

1 Like

Here man, try this first (which i think it can help you to solve the issue)

Let us know if you solve it :nerd_face:

Carlos Z

1 Like

Sorry just seen this, been away all weekend. Ooooo yes this looks promising, will give it a go now mate. Thank you @thecil

1 Like

Hmmmm, Resetting my account didn’t work either. @thecil

This error doesn’t appear to have happened to anyone else on the academy.

Do you think making a new folder and starting again will work? Ive tried everything now and nothing has worked so far.

Screenshot 2021-08-05 at 13.52.21

1 Like

Hey man, I’m trying to access to the github repo (https://github.com/olfrank/Crypto_Cats), want to download your project so i can replicate the issue my self, according with the console error that you showed, there is an issue on the index.js:82 (code line 82).

Would be great if you can do your repo public, or add me as a colaborator (github nickname: thecil).

Carlos Z

Hey @thecil, thanks for taking a look, I deleted that repo. The new one is here: https://github.com/olfrank/Crypto_Cats_Dapp

index.js.82
Screenshot 2021-08-06 at 20.56.17
Thanks

image

error msg:

“Error: [ethjs-query] while formatting outputs from RPC ‘{“value”:{“code”:-32603,“data”:{“message”:“VM Exception while processing transaction: revert”,“code”:-32000,“data”:{“0x756a33ba09f7ea61c69c7fc9060011271edc36a96553c974017a3594b9df5836”:{“error”:“revert”,“program_counter”:1625,“return”:“0x”},“stack”:“RuntimeError: VM Exception while processing transaction: revert\n at Function.RuntimeError.fromResults (C:\Users\thecil\AppData\Roaming\npm\node_modules\truffle\build\webpack:\node_modules\ganache-core\lib\utils\runtimeerror.js:89:1)\n at BlockchainDouble.processBlock (C:\Users\thecil\AppData\Roaming\npm\node_modules\truffle\build\webpack:\node_modules\ganache-core\lib\blockchain_double.js:632:1)\n at process._tickCallback (internal/process/next_tick.js:68:7)”,“name”:“RuntimeError”}}}}’”

So the problem comes from a revert being triggered, (data":{"message":"VM Exception while processing transaction: revert",) now we need to know which revert is.

This is why I advice to always use a revert message, so you can easily identify which require is being triggered.

In the index.js file, we call createCat function to create a new gen 0 cat (code line 82: let result = token.methods.createCatGen0(dnaStr).send();), so checking createCatGen0 function in the contract, we have:

function createCatGen0(uint256 _genes)public onlyOwner{
    require(gen0Counter < Gen0_Creation_Limit);
    gen0Counter++;

    _createCat(_genes, 0, 0, 0, msg.sender);
}

that require could be triggered, i advice to add a msg like:
require(gen0Counter < Gen0_Creation_Limit, "createCatGen0: gen0Counter < Gen0_Creation_Limi");

Also we have to check the modifier onlyOwner require:

modifier onlyOwner{
    require(msg.sender == address(this));
    _;
}

I think the problem could be here, you are saying “msg.sender must be equal to contract address”, it could be useful to change it to the owner (create a address variable owner, which should save the deployer of the contract as the owner of it).

you can verify the problem by adding a revert msg in the modifier and update your abi.js.

modifier onlyOwner{
    require(msg.sender == address(this), "onlyOwner: msg.sender == address(this)");
    _;
}

image
NOTE: Remember to migrate --reset truffle after contract updates, then update your abi.js with the new one generated through the new migration, also remember to update the contract addresses in index.js. :nerd_face:

Carlos Z

1 Like

Damn it! I am kicking myself now haha.
Yeah that’s the bug that i was too blind to see for myself.
Thank you @thecil, and yeh you are right, I have become a bit lazy with the require “reason:”, and will implement them now. I just need to get in the habit of walking myself through my errors and being more critical with my code.

I had it in my head the RPC error meant an error with MetaMask itself and not the contract.
Anyway, cheers for taking the time to look at my issue Carlos.

Have a good weekend!

1 Like

Done! :partying_face:

GitHub:
https://github.com/derdis14/ethereum-dapp-moon-kitties

Check out my dApp on the Ropsten testnet :slight_smile::
https://derdis14.github.io/ethereum-dapp-moon-kitties/

Factory
factory

Breed
breed

Create Sales Offer
sales_offer

Buy from Marketplace
buy_marketplace

5 Likes

Wow @derdis14 thats amazing! Fully working DAPP ! Very good desgin all black and nice backgrounds for those cats. Amazing!

Wow, this has been such a tough but such a rewarding projects, still a bug or two to fix but I’m gonna post what I have and look at the solution! :slight_smile: Thanks for the course this one rocks!!!

marketplace.js

var web3 = new Web3(Web3.givenProvider);

var instance;
var user;
var mktPlaceAddress = "0x8955C96CC19A232eebA34106073E22b917e591D2";
var tokenAddress = "0x7E74636D36f73235Ddb0DeEf9F34237440460ee9";

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

    console.log(mktplace);
    token = new web3.eth.Contract(abi, tokenAddress, { from: accounts[0] });
    console.log(token);
    printOrders();
  });
}); //End document.ready

async function printOrders() {
  var offerId;
  var item;
  let items = [];
  let currentUser = ethereum.selectedAddress;
  var tokensOnSaleIds = [];
  var KittyCount = await token.methods.getkittiesLength().call();
  var tokensOnSaleCount = await mktplace.methods.getAllTokenOnSale().call();
  // console.log(tokensOnSaleCount.length);
  //console.log("Kitty COUNT: " + kittiesCount);

  for (let i = 0; i < tokensOnSaleCount.length; i++) {
    offerId = await mktplace.methods.getOffer(i).call();
    // console.log(offerId);
    let isOnSale = offerId.active;
    if (isOnSale) {
      tokensOnSaleIds.push(offerId.tokenId);
    }
  }

  for (let i = 0; i < tokensOnSaleIds.length; i++) {
    let kittenId = tokensOnSaleIds[i];
    //console.log("Current Bear Id: " + bearId);
    let object = await token.methods.getBear(tokensOnSaleIds[i]).call();
    let kittyGenes = object.genes;
    //console.log("Current Genes: " + bearGenes);
    let kittyBirthday = object.birthTime;
    // console.log("Current Birthday: " + new Date(bearBirthday * 1000));
    let kittyMomId = object.momId;
    // console.log("Current MumId: " + bearMumId);
    let kittyDadId = object.dadId;
    // console.log("Current DadId: " + bearDadId);
    let kittyGeneration = object.generation;
    // console.log("Current Generation: " + kittyGeneration);

    createKittyBox(newkittenId, kittyGenes);
  }

  function createKittyBox(newkittenid, kittyGenes) {
    let bodyDna = kittyDetails.substring(0, 2);
    //  console.log("BODYDNA" + bodyDna);
    let mouthDna = kittyDetails.substring(2, 4);
    //  console.log("MOUTHDNA: " + mouthDna);
    let eyesDna = kittyDetails.substring(4, 6);
    //  console.log("EYESDNA: " + eyesDna);
    let earsDna = kittyDetails.substring(6, 8);
    //  console.log("EARSDNA: " + earsDna);
    let eyeShape = kittyDetails.substring(8, 9);
    //  console.log("EYESHAPE: " + eyeShape);
    let decoShape = kittyDetails.substring(9, 10);
    //  console.log("DECOSHAPE: " + decoShape);
    let decoMidColor = kittyDetails.substring(10, 12);
    //  console.log("DECOMIDCOLOR: " + decoMidColor);
    let decoSideColor = kittyDetails.substring(12, 14);
    //  console.log("DECOSIDECOLOR: " + decoSideColor);
    let animDna = kittyDetails.substring(14, 15);
    //  console.log("ANIMDNA: " + animDna);
    let lastDna = kittyDetails.substring(15, 16);
    //  console.log("LASTDNA: " + lastDna);

    // console.log("BODYCOLOR: " + colors[earsDna]);

    item =
      `<div class="col-lg-4 catBox m-3 light-b-shadow" id="box` +
      id +
      `">
                  <div class="cat" id="cat` +
      id +
      `"> 
                      <div id="catEars` +
      id +
      `" class="` +
      (animDna == 4 ? "cat__ear earScale" : "cat__ear") +
      `">
                          <div id="leftEar` +
      id +
      `" class="cat__ear--left" style="background:#` +
      colors[earsDna] +
      `">
                          <div class="cat__ear--left-inside"></div>
                          </div>
                          <div id="rightEar` +
      id +
      `" class="cat__ear--right" style="background:#` +
      colors[earsDna] +
      `">
                          <div class="cat__ear--right-inside"></div>
                          </div>
                      </div>
                      <div id="head` +
      id +
      `" class="` +
      (animDna == 1 ? "cat__head movingHead" : "cat__head") +
      `" style="background:#` +
      colors[bodyDna] +
      `">
                          <div id="midDot` +
      id +
      `" class="` +
      (animDna == 3 ? "cat__head-dots midDotSpin" : "cat__head-dots") +
      ` " style="background:#` +
      colors[decoMidColor] +
      `">
                          <div id="leftDot` +
      id +
      `" class="cat__head-dots_first" style="background:#` +
      colors[decoSideColor] +
      `">
                      </div>
                      <div id="rightDot` +
      id +
      `" class="cat__head-dots_second" style="background:#` +
      colors[decoSideColor] +
      `">
                      </div>
                      </div>
                      <div id="catEyes` +
      id +
      `" class="` +
      (animDna == 2 ? "cat__eye movingEyes" : "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" style="background:#` +
      colors[mouthDna] +
      `"></div>
                          <div class="cat__mouth-left"></div>
                          <div class="cat__mouth-right"></div>
                          <div id="whiskLeft` +
      id +
      `" class="` +
      (animDna == 6 ? "cat__whiskers-left whiskShake" : "cat__whiskers-left") +
      `"></div>
                          <div id="whiskRight` +
      id +
      `" class="` +
      (animDna == 6
        ? "cat__whiskers-right whiskShake"
        : "cat__whiskers-right") +
      `"></div>
                      </div>
                      <div class="cat__body">
                          <div class="cat__chest" style="background:#` +
      colors[bodyDna] +
      `"></div>
                              <div class="cat__chest_inner" style="background:#` +
      colors[mouthDna] +
      `"></div>
                          <div class="cat__paw-left" style="background:#` +
      colors[earsDna] +
      `"></div>
                              <div class="cat__paw-left_inner"></div>
                          <div id="pawRIGHT` +
      id +
      `" class="` +
      (animDna == 7 ? "cat__paw-right sayHello" : "cat__paw-right") +
      `" style="background:#` +
      colors[earsDna] +
      `"></div>
                              <div id="pawRIGHTINNER` +
      id +
      `" class="` +
      (animDna == 7
        ? "cat__paw-right_inner sayHello"
        : "cat__paw-right_inner") +
      `"></div>
                          <div class="cat__paw-leftLower" style="background:#` +
      colors[earsDna] +
      `"></div>
                              <div class="cat__paw-leftLower_inner"></div> 
                          <div class="cat__paw-rightLower" style="background:#` +
      colors[earsDna] +
      `"></div>
                              <div class="cat__paw-rightLower_inner"></div>
                          <div id="tail` +
      id +
      `" class="` +
      (animDna == 5 ? "cat__tail tailWig" : "cat__tail") +
      `" style="background:#` +
      colors[mouthDna] +
      `"></div>
                          </div>
                          </div> 
                          <br>

                          <div class="dnaDiv" id="catDNA` +
      id +
      `">
                          <b>DNA:<!-- Colors -->
                          <span id="dnabody` +
      id +
      `">` +
      kittyDetails +
      `</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>
                          </b>
                          <br>
                          <button class="btn btn-dark" id="sell ` +
      id +
      `" onclick="removeFromSale(` +
      id +
      `)">Remove Kitty from Sale</button>
                          <button class="btn btn-dark" id="sell ` +
      id +
      `" onclick="buyKitty(` +
      id +
      `)">Buy This Kitty</button>
                          </div>
                          
                          </div>`;

    items.push(item);
  }
  $(".orderbook").append(items.join());
}

async function buyKitty(id) {
  let user = web3.currentProvider.selectedAddress;
  let isApproved = await token.methods
    .isApprovedForAll(user, mktPlaceAddress)
    .call();
  let offer = await mktplace.methods.getOffer(id).call();
  let price = offer.price;

  if (isApproved == false) {
    alert(
      "The Kittycontract DApp is not approved yet to handle your tokens! Please give approval!"
    );
    await token.methods.setApprovalForAll(mktPlaceAddress, true).send();
    alert("Approval Set!");
    isApproved = await token.methods
      .isApprovedForAll(user, mktPlaceAddress)
      .call();
    console.log("is now approved: " + isApproved);
  } else {
    await mktplace.methods.buyKitty(newkittenid).send({ value: price });
  }
}

1 Like

hey @Mickey_McClimon! What is the issue? Can you screen shoot the errors?

I’ve now deployed the dApp on the Ropsten testnet! :smiley: If you want, you can try it here: https://derdis14.github.io/ethereum-dapp-moon-kitties/

1 Like

Really good full project! Well done, this is a nice complate app… I tryed all fuetures, bought 2 cats and breed them. Now i just sell them for 50 eth, so you can buy it back jeje.

Nice design and UI very clear.
Congratulations!

1 Like

heya!!
here’s my work for all sections.

Kitty Factory
Kitty Breeding
Kitty Selling
Kitty buying

Repo for crypto kitties

Thanks.

4 Likes

hey @thecil, @kenn.eth
I’m trying to deploy this Dapp on ropsten testnet but facing some issues here.
Using this command for migration - truffle migrate --network ropsten

Starting migrations...
======================
> Network name:    'ropsten'
> Network id:      3
> Block gas limit: 7992189 (0x79f37d)


1_initial_migration.js
======================

   Deploying 'Migrations'
   ----------------------
   > transaction hash:    0xb9a6f06db7213ef53419aee8345204a262e42ac60b5dbaf361db112d781519e2

Error:  *** Deployment Failed ***

"Migrations" -- Transaction was not mined within 750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!.

    at C:\Users\HP\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\deployer\src\deployment.js:365:1
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at Migration._deploy (C:\Users\HP\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\Migration.js:75:1)
    at Migration._load (C:\Users\HP\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\Migration.js:61:1)
    at Migration.run (C:\Users\HP\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\Migration.js:218:1)
    at Object.runMigrations (C:\Users\HP\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\index.js:150:1)
    at Object.runFrom (C:\Users\HP\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\index.js:110:1)  
    at Object.run (C:\Users\HP\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\index.js:87:1)       
    at runMigrations (C:\Users\HP\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\commands\migrate.js:258:1)
    at Object.run (C:\Users\HP\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\commands\migrate.js:223:1)
    at Command.run (C:\Users\HP\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\command.js:167:1)  
Truffle v5.4.1 (core: 5.4.1)
Node v14.15.3

truffle-config.js

/**
 * Use this file to configure your truffle project. It's seeded with some
 * common settings for different networks and features like migrations,
 * compilation and testing. Uncomment the ones you need or modify
 * them to suit your project as necessary.
 *
 * More information about configuration can be found at:
 *
 * trufflesuite.com/docs/advanced/configuration
 *
 * To deploy via Infura you'll need a wallet provider (like @truffle/hdwallet-provider)
 * to sign your transactions before they're sent to a remote public node. Infura accounts
 * are available for free at: infura.io/register.
 *
 * You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
 * public/private key pairs. If you're publishing your code to GitHub make sure you load this
 * phrase from a file you've .gitignored so it doesn't accidentally become public.
 *
 */

const HDWalletProvider = require('@truffle/hdwallet-provider');
const fs = require('fs');
//const mnemonic = fs.readFileSync(".secret").toString().trim();
const mnemonicDev = "vocal mixed asset slim abandon auction joke shoot world door kiss anxiety";
require("dotenv").config();
module.exports = {
  /**
   * Networks define how you connect to your ethereum client and let you set the
   * defaults web3 uses to send transactions. If you don't specify one truffle
   * will spin up a development blockchain for you on port 9545 when you
   * run `develop` or `test`. You can ask a truffle command to use a specific
   * network from the command line, e.g
   *
   * $ truffle test --network <network-name>
   */

  networks: {
    // Useful for testing. The `development` name is special - truffle uses it by default
    // if it's defined here and no other network is specified at the command line.
    // You should run a client (like ganache-cli, geth or parity) in a separate terminal
    // tab if you use this network and you must also set the `host`, `port` and `network_id`
    // options below to some value.
    //
    // development: {
    //  host: "127.0.0.1",     // Localhost (default: none)
    //  port: 7545,            // Standard Ethereum port (default: none)
    //  network_id: "*",       // Any network (default: none)
    // },
  ganache: {
     provider: () => new HDWalletProvider(mnemonicDev, `HTTP://127.0.0.1:7545`),
     host: "127.0.0.1",     // Localhost (default: none)
	   network_id: "*"       // Any network (default: none)
    },

    // Another network with more advanced options...
    // advanced: {
    // port: 8777,             // Custom port
    // network_id: 1342,       // Custom network
    // gas: 8500000,           // Gas sent with each transaction (default: ~6700000)
    // gasPrice: 20000000000,  // 20 gwei (in wei) (default: 100 gwei)
    // from: <address>,        // Account to send txs from (default: accounts[0])
    // websocket: true        // Enable EventEmitter interface for web3 (default: false)
    // },
    // Useful for deploying to a public network.
    // NB: It's important to wrap the provider as a function.
    ropsten: {
    provider: () => new HDWalletProvider(mnemonicDev,`https://ropsten.infura.io/v3/${process.env.INFURA_API_KEY}`
    ),
    network_id: 3,       // Ropsten's id
    gas: 5500000,        // Ropsten has a lower block limit than mainnet
    confirmations: 2,    // # of confs to wait between deployments. (default: 0)
    timeoutBlocks: 200,  // # of blocks before a deployment times out  (minimum/default: 50)
    skipDryRun: true     // Skip dry run before migrations? (default: false for public nets )
    },
    // Useful for private networks
    // private: {
    // provider: () => new HDWalletProvider(mnemonic, `https://network.io`),
    // network_id: 2111,   // This network is yours, in the cloud.
    // production: true    // Treats this network as if it was a public net. (default: false)
    // }
  },

  // Set default mocha options here, use special reporters etc.
  mocha: {
    // timeout: 100000
  },

  // Configure your compilers
  compilers: {
    solc: {
      version: "0.8.0",    // Fetch exact version from solc-bin (default: truffle's version)
      // docker: true,        // Use "0.5.1" you've installed locally with docker (default: false)
      // settings: {          // See the solidity docs for advice about optimization and evmVersion
      //  optimizer: {
      //    enabled: false,
      //    runs: 200
      //  },
      //  evmVersion: "byzantium"
      // }
    }
  },

  // Truffle DB is currently disabled by default; to enable it, change enabled: false to enabled: true
  //
  // Note: if you migrated your contracts prior to enabling this field in your Truffle project and want
  // those previously migrated contracts available in the .db directory, you will need to run the following:
  // $ truffle migrate --reset --compile-all

  db: {
    enabled: false
  }
};

.env file in root folder

INFURA_API_KEY= 1a248f1e54f345319db41b38adf60e9d

env .

Kinda juggling with this for few days. Please help me in resolving this one.
Thanks.

hey @tanu_g ! Are you getting the sign for the transaction using metamask? Remember to set up metamask or check if you have the same mnemonicDev with some Ropsten ETH in the first wallet.

1 Like