Dapp Introduction

Good day!

Is there a difference between web3.eth.requestAccounts() and web3.eth.getAccounts()? I managed to get the contractInstance object with the getAccounts function and not with the requestAccounts function. Thanks!

Code:

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

$(document).ready(function() {

    window.ethereum.enable().then(async function connectMetamask(){
      let accounts;
      if (typeof window.ethereum !== undefined) {
        accounts = await web3.eth.getAccounts();
        console.log("Accounts: " + accounts);
      }
      contractInstance = new web3.eth.Contract(abi, "0x5A3b9bC258048835071947db21fd367a5A2CDF04", {from: accounts[0]});
      console.log(contractInstance);
    });

});
1 Like

Hey @Jose_Hernandez

They are the same thing :slight_smile: You can use web3.eth.getAccounts() without problem.

Happy learning,
Dani

1 Like

I get this error when trying to input data:

Uncaught Error: invalid string value (arg=“name”, coderType=“string”, value=undefined)
at Object.n [as throwError] (web3.min.js:1)
at t.encode (web3.min.js:1)
at web3.min.js:1
at Array.forEach ()
at N (web3.min.js:1)
at t.encode (web3.min.js:1)
at e.encode (web3.min.js:1)
at i.encodeParameters (web3.min.js:1)
at web3.min.js:1
at Array.map ()

Should I be using a different web3 js file? Thanks again!

Code:

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

$(document).ready(function() {

    window.ethereum.enable().then(async function connectMetamask(){
      let accounts;
      if (typeof window.ethereum !== undefined) {
        accounts = await web3.eth.getAccounts();
        console.log("Accounts: " + accounts);
      }
      contractInstance = new web3.eth.Contract(abi, "0x5A3b9bC258048835071947db21fd367a5A2CDF04", {from: accounts[0]});
      console.log(contractInstance);
    });

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

});

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);
};

Hey @Jose_Hernandez

window.ethereum.enable() is deprecated and you should not use it, that’s the reason why you are calling await web3.eth.getAccounts();

Your connection should look like this

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

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

Also I suggest to import web3 by just including the link to it instead of the whole old file.

In your HTML

<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>

Cheers,
Dani

Thanks! I’ll edit and retry with this

Hello, I have a problem with the code from the lecture. I copied it from Filip’s github page. The only modification I made is added some gas to contractInstance. Pressing "Get Data " button gives me Uncaught (in promise) Error. Looks like problem somewhere in contractInstance.methods.getPerson().call() inside fetchAndDisplay function. In other words, I cant get any data after transaction have been submitted. Need some help, please.

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

$(document).ready(function () {
  window.ethereum.enable().then(function (accounts) {
    contractInstance = new web3.eth.Contract(
      window.abi,
      "0xdA5E6a762993FD52fB6881d0482E990ec21460d9",
      { from: accounts[0], gas: 400000 }
    );
  });
  $("#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);
    });
}
function fetchAndDisplay() {
  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"]);
}

inpage.js:1 MetaMask: 'ethereum.enable()' is deprecated and may be removed in the future. Please use the 'eth_requestAccounts' RPC method instead.
For more information, see: https://eips.ethereum.org/EIPS/eip-1102
enable @ inpage.js:1
(anonymous) @ main.js:59
e @ jquery-3.4.1.min.js:2
t @ jquery-3.4.1.min.js:2
setTimeout (async)
(anonymous) @ jquery-3.4.1.min.js:2
c @ jquery-3.4.1.min.js:2
fireWith @ jquery-3.4.1.min.js:2
fire @ jquery-3.4.1.min.js:2
c @ jquery-3.4.1.min.js:2
fireWith @ jquery-3.4.1.min.js:2
ready @ jquery-3.4.1.min.js:2
B @ jquery-3.4.1.min.js:2
main.js:78 tx hash
main.js:84 {transactionHash: "0xcff6d5b7a452b546204fba2cb7e68e8f4af9e134b9bcb88f7f1f2e22895eac2c", transactionIndex: 0, blockHash: "0x9fdc759f697ee740d2f39cc2ace8cd0ad9f724a0c1157eb0e326b98205edb6f8", blockNumber: 25, from: "0xb375f7662ed7391ae5975aabba67aac1b35cc2d6", …}
web3.min.js:1 Uncaught (in promise) Error: Returned values aren't valid, did it run Out of Gas?
    at i.decodeParameters (web3.min.js:1)
    at o._decodeMethodReturn (web3.min.js:1)
    at _.outputFormatter (web3.min.js:1)
    at _.formatOutput (web3.min.js:1)
    at u (web3.min.js:1)
    at web3.min.js:1
    at s._handle (inpage.js:17)
i.decodeParameters @ web3.min.js:1
o._decodeMethodReturn @ web3.min.js:1
outputFormatter @ web3.min.js:1
_.formatOutput @ web3.min.js:1
u @ web3.min.js:1
(anonymous) @ web3.min.js:1
_handle @ inpage.js:17
Promise.then (async)
fetchAndDisplay @ main.js:91
dispatch @ jquery-3.4.1.min.js:2
v.handle @ jquery-3.4.1.min.js:2

Hi . . . I can’t seem to get python running on my computer. I downloaded Python (3.9.1) onto my computer. Then I typed in the following into Powershell: python -m http.server

I got the following error message:
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

I have no idea what to do. Please help! There were no instructions in the video re: downloading and installing Python - I imagine it was just a matter of going to the Python website, downloading it, and installing it (nothing else needed).

UPDATE: I went into Settings > Manage App Execution Aliases and disabled the “app installer” for Python. Then I went back to Powershell and entered (again) “python -m http.server”. Now I get the following error message:

python : The term ‘python’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1

  • python -m http.server

Have you tried : python3 -m http.server?

That didn’t work either. I got the following error message when I typed in “python3 -m http.server”:

python3 : The term ‘python3’ is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1

  • python3 -m http.server
  •   + CategoryInfo          : ObjectNotFound: (python3:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException

I don’t know if it is any help but, for some reasons python command does not work on my Windows 10 machine either. The simplest solution that I’ve found is to install Ubuntu subsystem for Windows. Then I moved working files to the home directory, run code editor and ‘successfully’ python server from Ubuntu terminal.
Step-by-step instruction:

  1. install Ubuntu subsystem for windows.(https://www.itechguides.com/how-to-install-ubuntu-on-windows-10/)

  2. run Ubuntu. find folder with code files. Windows files located somewhere on a path user:~$ /mnt/c/Users/<maybe your name>/.../<jsFiles> . Copy them to home directory
    user:~$ cp /mnt/c/Users/name&gt;/..... ~/ -r.

  3. I’m using VS Code editor, so the run command for me was
    user:~$ code .

  4. and finally
    user:~$ python3 -m http.server 8000

Try running powershell as an administrator.

So I figured out an easy way to do this. First I uninstalled Python completely. Then I went to the Python site (not Microsoft Store) and downloaded Python 3.9.1. I double clicked on the .exe file to install it. There was an option to check a box that said something about the “PATH” (I forget exactly what it said). Anyhow, all I had to do was check that box. That worked. I was able to run Python from my Powershell.

I decided to try checking that box as a solution because some of the error messages (if I remember correctly said something about the path, and I think when I was googling the problem something about paths came up.)

Anyhow, I think I just got a bit lucky, lol.

1 Like

Good day! I have these functions in my contract

  function _random() internal view returns (bool) {
    return(now % 2 == 0);
  }

  function flip(bool _choice) public payable returns(bool, bool){
    bool coin = _random();
    if(coin == _choice){
      //win
      msg.sender.transfer(msg.value*2);
      return(coin, true);
    }
    else{
      //lose
      return(coin, false);
    }
  }

How do i send a transaction to the flip function and get its return value within the same block of javascript code? Thanks!

Update:
I think I got it to work. Is this the correct way to implement it?

function placeBet(_choice){
  var bet = $("#bet").val();
  var config = {value: web3.utils.toWei(bet, "ether")};
  var result;
  var coin;
  console.log(_choice);

  let flip = contractInstance.methods.flip(_choice);
  flip.send(config).then(function(){
    flip.call().then(function(res){
      console.log(res);

      if(res[0] == true){
        coin = "Heads";
      }
      else coin = "Tails";

      if(res[1] == true){
        result = "win";
      }
      else{
        result = "lose";
      }

      $("#coin").text(coin);
      $("#result").text("You "+result+"!");
    });
  });
};

For lesson “Creating a Contract Instance”, I am stuck when trying to run “truffel console”.
I have my new files placed in same parent folder.
I can run the localhost:8000
I get this error:
image

Arh, I solved it. Had to move the truffle config file out of the "dapp-archieve’ folder, and have it at same level as the main/index/web3 files.

1 Like

New issue … think I have moved my files around a bit too much now.
To me it looks correctly !?

image
image

Hey @Mette

Because you are probably in the wrong folder, you have to post a full screenshot of your terminal so that we can check where exactly you are.

Cheers,
Dani

Hi Dani, IOT support

Thank you very much for reaching out. Here is the requested overview + migration error message.
I do have the migration.sol file.


image

1 Like

Hi, I’m still learning so I’m not sure of what I’m saying… but maybe you should do the “truffle console” of the dapp-archieve instead of ETH 201. Or maybe you shouldn’t use the dapp–archive folder, maybe dapp, build, contracts, migrations should be everyone on the same “level”. I’m not sure but I’m trying to help you.

2 Likes

Hey guys, hope you are great.

@giomiri almost explained, you have to be in the same folder that you have your “contracts, migration, test” folders, which is “dapp-archieve”, then truffle should be able to locate all the files needed.

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

2 Likes