Programming Project - Phase 1

I am also getting this error quite a bit, but not consistently. Can you tell me how to avoid this? Thanks!

inpage.js:1 MetaMask - RPC Error: Error: [ethjs-rpc] rpc error with payload {"id":9300923051282,"jsonrpc":"2.0","params":["0xf893808504a817c800836170d49449efe51b8c23760e50ea389c5b2081a9328be12b880de0b6b3a7640000a48399515c0000000000000000000000000000000000000000000000000000000000000000822d45a0f56b8d57583c7d6aad9a985ad092bfea67b8abecef8594ed2b05850d861df2eaa04c1c6535267fe980dfd55540dc58abe9a073779be2dd1a355fa6eeb84db85bfe"],"method":"eth_sendRawTransaction"} [object Object] 

I have finally figured out how to get to the events from the receipt and use them to return the result of flipping a coin.

contractInstance.methods.coinflip().send(bet_to_ether)
  .on("transactionHash", function(hash){
    console.log(hash);
  })
  .on("confirmation", function(confirmationNr){
    console.log(confirmationNr);
  })
  .on("receipt", function(receipt){
  console.log(receipt);
  })
  .then(function(res){
    console.log("Result is: " + (res.events.coinFlipped.returnValues.win_loose ? "Win" : "Lose"));
    //alert("The result is: " + (res.events.coinFlipped.returnValues.win_loose ? "Yes" : "No"));
    $("#win_output").text(res.events.coinFlipped.returnValues.win_loose ? "Yes" : "No");
    $("#bet_result").text((res.events.coinFlipped.returnValues.win_loose ?("You won "+ 2*bet) :("You lost "+ bet)) + " Ether" );

    fetchBalance();
  })
};

Side question. Is there a way to get a return value from a smartcontract function when you use send() function? Or is it possible only with the call() function?

Hi,

I’m trying to deploy my contract but I’m getting a Meta Mask error. Can anyone help me out on this or know why this is happening?
image

Hey @djdeapvoyce

Try to reset Metamask:

Reset Metamask: Settings > Advanced > Reset account.
!Schermata 2020-09-26 alle 14.05.58


Schermata 2020-09-26 alle 14.06.28

Keep me posted,
Dani

1 Like

Hey @rostyslavdzhohola

If you use send() it will return a tx receipt.
In order to get the returned value you have indeed to use call().
When using send() it’s necessary to use an event.

Well done, I am happy that you sorted out yourself!
Dani

2 Likes

Hey @Flaflaflohi

I wrote a basic faq to help students with catching events.
Have a look here: FAQ - How to listen for events

I also suggest you to dive deep into the documentation after reading the faq above. You can do many different things with events.

Happy learning,
Dani

1 Like

Thank you so much @dan-i

I have a follow up question and was hoping you can steer me in the right direction. I’m trying to use the input from the user (heads or tails) that the user inputs (radio value) into my main flipCoin function. However, I don’t think this correctly being integrated with my main.js file:
Coinflip.sol

main.js

My main issue is I just want one button (bet button) that sets the coin side & bet amount (function createBet(uint CoinSide) and also executes the flipCoin (uint bet) function. Any help would be greatly appreciated! @dan-i

Here is my Phase 1 project completion video.

1 Like

Hey @djdeapvoyce

I’m trying to use the input from the user (heads or tails) that the user inputs (radio value) into my main flipCoin function. However, I don’t think this correctly being integrated with my main.js file:

Do you get any error from the console?
By giving a quick look, I think there is a syntax error (please next time do not post screenshots as I cannot test or indicate you the row to check).

Schermata 2020-09-30 alle 10.14.00

Try to remove the symbol from sides. [name = sides]:

Cheers,
Dani

1 Like

Hi there, can someone take a look at my code and advise if it needs any changes., also, I’m having a bit of trouble creating tests for my code, any help would be highly appreciated.,
Here’s my .sol code…,

pragma solidity 0.5.12;

contract flip
{

  uint public balance;

  modifier costs(uint cost)
  {
    require(msg.value >= cost);
    _;
  }

  function Bet(uint heads, uint tails)  public payable costs(1 ether)
  {
    heads = 0;
    tails = 1;
    require(msg.value >= 1 ether);
    balance += msg.value;

    
  }

  function random() public view returns(uint)
  {

    return now % 2;

  }


}

Here is my test code:

const flip = artifacts.require("flip");
const truffleAssert = require("truffle-assertions");

contract("flip", async function(accounts){

  let instance;
  before(async function()
  {
    instance = await flip.deployed()
  });

  it("shouldn't flip coin without payment", async function()
  {
    await truffleAssert.fails(instance.Bet(heads, tails {value: 1000 }), truffleAssert.ErrorType.REVERT);
  });

  it("should flip correctly", async function()
  {
    await instance.random({value: web3.utils.toWei("1", "ether")});
    let result = await instance.random();
  });

});

Hi @dan-i, thanks for this - I don’t think that was the issue and I’m not getting any errors on my console - just that the transaction fails. I’ve placed my edited flipCoin function and main.js code below:

> function flipCoin(uint256 CoinSide, uint256 value) public payable returns (bool){
        Bet memory newBet;
        newBet.coinSide = CoinSide;
        newBet.betValue = value;
        bettings[msg.sender] = newBet;
        //Contract's balance
        balance += msg.value;

        uint256 headsOrTails = random();
        uint256 toTransfer = value;

        if (headsOrTails == CoinSide) {
            require(balance >= 2 * toTransfer);
            balance = balance - 2 * toTransfer;
            msg.sender.transfer(2 * toTransfer);
            result = true;
        } else {
            result = false;
        }
        return (result);
    }
````Preformatted text`
var web3 = new Web3(Web3.givenProvider);
var contractInstance;
var address;
$(document).ready(function () {
  window.ethereum.enable().then(function (accounts) {
    contractInstance = new web3.eth.Contract(
      abi,
      "0x79C75e810FDA59171E6E482fDd876117F94FC762",
      { from: accounts[0] }
    );
    console.log(contractInstance);
    address = accounts[0];
  });
  $("#bet_button").click(flip); //inputData
});

function flip() {
  if ($("#bet_input").val() < 0.1) {
    alert("Minimum Bet Amount is 0.1 ETH");
    return;
  }

  var bet = 0;
  var radioValue = $("input[name='sides']:checked").val();
  var betValue = $("#bet_input").val();

  if (radioValue) {
    if (radioValue == "heads") {
      bet = 1;
    }
  }

  var config = {
    from: address,
    value: web3.utils.toWei(betValue.toString(), "ether"),
    gas: 100000,
  };

  contractInstance.methods
    .flipCoin(bet, betValue)
    .send(config)
    .on("transactionHash", function (hash) {
      console.log(hash);
    })
    .on("confirmation", function (confirmationNr) {
      console.log(confirmationNr);
    })
    .on("receipt", function (receipt) {
      console.log(receipt);
    });
}

It was more challenging then I expected :slight_smile: but I learned a lot.
Video recording:

code on github:

1 Like

Hey @djdeapvoyce

Would you please upload the whole project on GitHub? I will be happy to test it and let you know asap.

Have a great day!
Dani

Hey @Marlic

Amazing job well done!
I like the interface and you smart contract looks clean.
Ready for phase two, take your time to understand how the oracle works. Can’t wait to see the result.

Good job,
Dani

1 Like
1 Like

I wanted to make an animation for coinflip for loading, add some animations and refactore the code since its all in one file atm but this is fine for now.

1 Like

Coin Flip - Phase 1

1 Like

Video capture of my phase 1 flip project:

1 Like