Dapp Introduction

@dan-i what am I missing? is there a clear path aside from the video? I can see different solutions to different problems here in the forum, but I can’t seem to figure out how to stitch the info together to some working code :face_with_raised_eyebrow:


edit: my problem was that I didn’t have # before the buttons, there may be some other stuff in the photo too, but I got It working with a bit of help from a friend

I navigated to the ‘dapp-archieve’-folder, ran truffle console and get the exact same error when trying to migrate:


I have the ‘1_initial-migrations.js’-file set to deploy Migrations.sol. And the contract is there, allthough the code is greyed out, if that matters except for a user friendly look?

The language settings is ‘Plain text’, it was set to auto-detect, and I cannot chose ‘Sol’, so I just changed it to ‘flow javascript’
image
What errors in the code would be typical here? - I checked several times, but cannot find any errors.

Hey @Mette

Your solidity code is greyed out because you have to install a syntax highlighter for Atom.
Try this one: https://atom.io/packages/language-solidity

Regarding your migration, what is usually useful to see is 2_Helloworld_deploy.js, if you can copy and paste it here I will take a look.

Also try one by one these steps:

  • Downgrade node as explained here: FAQ - How to downgrade Node.Js

  • Once done reboot your pc

  • Now navigate into the directory dapp-archive ( don’t use ganache UI ).

  • Run truffle develop

Truffle will load a test blockchain

  • Run truffle migrate --reset

Let me know if it compiles.

Cheers,
Dani

2 Likes

Hi everyone,

Interesting course! While it’s frustrating that a few things have changed since the course was made, it’s also a very nice way to learn and to do extra research!!! I had to spend a couple of days to make it work, and I see that I’m not the only one haha.
So in case this issue happens to other, here is a brief summary of what I’ve done for the setup to work (basically a mix of all previous solutions in this thread):

  1. For some unexplained reason, I believe that what’s finally work for me was to use the predefined RPC port 8545 on Metamask. Just go to truffle UI, then Settings > Server > Port number and set it to 8545. (In Account & keys, you can also give yourself a few extra ETH, it’s always a good feeling)
  2. Completely removed the web3.min.js that we created (abi.js should be kept), and imported it in the index.html header with:
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
  1. Changed the code a bit in order to remove the deprecated web3 library. So here is the code I’m using, which is working at this time (Don’t forget to change the contract address):
var web3 = new Web3(Web3.givenProvider);
const contractAddress = "0xE8F488cb8B2c9919F07E84BD7B20626d0E89bAF8";
var contractInstance;

$(document).ready(async function () {
        await connectMetamask();

        $("#add_data_button").click(inputData);
    });

async function connectMetamask() {
    await ethereum.request({ method: 'eth_requestAccounts'}).then((accounts) => {
		contractInstance = new web3.eth.Contract(window.abi, contractAddress, {from: accounts[0]});		
		console.log(accounts[0]);
		console.log(contractInstance);
	});	
}

function inputData(){
    var name = $("#name_input").val();
    var age = $("#age_input").val();
    var height = $("#height_input").val();

    var config = {
        value: web3.utils.toWei("1", "ether")
    }
   
    contractInstance.methods.createPerson(name, age, height).send(config);
}
  1. installed a new and clean browser (brave in my case), dedicated to dev purpose without any extension (except metamask of course). I also created a brain new metamask wallet for development as well, so it doens’t matter if I accidentally upload my private key on Github haha!

Hope it can help. Good luck all :slight_smile:

2 Likes

Hi dani-i
Thank you for the guide.

2_Helloworld_deploy.js

  • Updated Atom with Solidity, -it works like a charm now
  • Downgraded NodeJS from v15.6.0 to v10.21.0 and restarted
  • Result: When using ‘truffle migrate --reset’ it compiles like before without deploying and giving the keys,- , and when using ‘truffle migrate’ I get the same error message concerning Migrations contract.

Btw, the keys/accounts from the test blockchain, are they teh ones needed for next step in the course?


@filip I have some question about in the backend of connection between js and .sol file interact with both of them.

I have a question. The other day I was able to execute the code just fine (setting data). When I clicked on the “Add Data” button in the People Dapp, MetaMask popped up and allowed me to confirm the transaction (for 1 ether).

Today, however, when I tried to do it again, Metamask fails to pop up to confirm the transaction. It looks like I am connected to Ganache, I migrated the contract to Ganache, Metamask shows that I am connected—everything appears to be the same as yesterday.

Any thoughts? I can’t figure out why it was working perfectly yesterday, but it is not working today. I didn’t alter any of the code. Why might Metamask be unresponsive to a click on the “Add Data” button (but it worked fine the other day)?

Thanks!

UPDATE1: I took a look at the console, and I am getting the following error:

Uncaught TypeError: Cannot read property ‘toWei’ of undefined
at HTMLButtonElement.inputData (main.js:19)
at HTMLButtonElement.dispatch (jquery-3.4.1.min.js:2)
at HTMLButtonElement.v.handle (jquery-3.4.1.min.js:2)

UPDATE 2: I seem to have fixed the issue. I started from scratch and was having a weird issue where the MetaMask transaction was now popping up to confirm transaction of 1 ether, when I know the javascript file was not requesting any value attached to the transaction (because I hadn’t gotten to that part of the lesson yet. Solution: I went into my Chrome browser and simply cleared the cache. That seems to have worked.

Hey @Mette

In your terminal type truffle -v and check the truffle version installed.

Let me know which one you are using.

thanks

Hey @Anonymous

What are you questions?

Cheers,
Dani

I have some confuse on the operation of how javascript connect to the contract in the tutorial has a copy contract address after the migrate reset I want to know if I reset again I have to copy the new contract address to the main.js file that’s right.

Hi,
I’m getting the below error:


Please help !

Hello, I’m still having problem resolving my issue. What might be possible explanation of methods.myMethod.call() not working properly in my case?
https://forum.ivanontech.com/t/dapp-introduction/10054/368?u=ivan_zg

Hi @Anonymous

When you create a web3 instance of a contract you need to specify:

  • The contract abi
  • The contract address

By specifying the two parameters above, web3 knows what are the methods in your contract and what’s its address.

Every time you deploy a new contract, you have to use the new contract address when creating the web3 instance, otherwise your front end will keep communicating with your old contract.

Regards,
Dani

1 Like

Hi @hashmiabrar1

The error message is telling you that in line 23 of your main.js contract you are trying to call .methods of a variable that is set to undefined.
I think you are doing something like contractInstance.methods.methodname(), in that case contractInstance is undefined.
Make sure that the contractInstance was created correctly and that it is available at the time you are using it.
For this kind of errors, it might be useful for you to post your js code here.

Cheers,
Dani

Hi @Ivan_Zg

Can you please post your smart contract code?

thanks
Dani

@dan-i Thank you for your answer it make me to understand a lot how the smart contract and front end interact with.

1 Like

Ok, I basically copy/past Filips code from GitHub (GitHub) and added some gas for transaction. Python server is running, ganache too, send transaction works with metamask. My main.js file:


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

$(document).ready(function () {
  window.ethereum.enable().then(function (accounts) {
    contractInstance = new web3.eth.Contract(
      window.abi,
      "0xb375f7662ed7391AE5975aabBA67aAc1B35cC2d6",
      { from: accounts[0], gas: 400000 }
    );
    console.log(window.abi);
  });
  $("#get_data_button").click(fetchAndDisplay);
  $("#add_data_button").click(inputData);
});

function inputData() {
  var name = $("#name_input").val();
  var age = $("#age_input").val();
  var height = $("#height_input").val();
  contractInstance.methods
    .createPerson(name, age, height)
    .send({ value: web3.utils.toWei("1", "ether") })
    .on("transactionHash", function (hash) {
      console.log("tx hash");
    })
    .on("confirmation", function (confirmationNumber, receipt) {
      console.log("conf");
    })
    .on("receipt", function (receipt) {
      console.log(receipt);
    });
}
async function fetchAndDisplay() {
  await contractInstance.methods
    .getPerson()
    .call()
    .then(function (res) {
      displayInfo(res);
    });
}
function displayInfo(res) {
  $("#name_output").text(res["name"]);
  $("#age_output").text(res["age"]);
  $("#height_output").text(res["height"]);
}

1 Like

Hello I cannot get the contract instance to work. Here is my code and screen shot.

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

$(document).ready(async() => {
    contractInstance = new web3.eth.Contract(abi,contractAddress);
    const accounts = await connectMetamask();
    console.log(contractInstance);
});

async function connectMetamask() {
  if (typeof window.ethereum !== undefined) {
    const accounts = await web3.eth.requestAccounts();
    return accounts;
  };
};

Hey @RCV

Other students faced the same issue and it was related to the browser they were using.
Can you try to run your dapp on a different browser?

Hello @dan-i,

Quick question - I’m following along for setting data to our smart contract. When listening for different logs, where exactly do these arguments come from? Are they built into web3.js?

1 Like