Programming Project - Phase 1

hello,

yes 9 eth sent to the contract from the owner to get the liquidity for the bets.

(by the way, is there another way to send 9 eth rather than writing 9*1000000000000000000 ?)

i don’t understand why this new version gives the error while the older version migrate with no error and it has the same constructor

this is the older version

import "./Ownable.sol";
pragma solidity 0.5.16;

 contract coin1 is Ownable{

    struct player {
      uint amount;
      uint hot;
    }

    uint public balance;
    uint public minBet;
    uint public result;

    string public message = "";

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

    constructor() public payable{
    require(msg.value >= 9*1000000000000000000);
       balance += msg.value;
}



    mapping (address => player) private players;
    // address[] private playersArr;



// link amount player want ot pay to his address
    function setBet(uint amount, uint hot) public payable costs( (players[msg.sender].amount)*1000000000000000000 ){


        require(hot == 1 || hot == 0);

        player memory newPlayer;
        newPlayer.amount = amount;
        newPlayer.hot = hot;

        insertPlayer(newPlayer);
        // playersArr.push(msg.sender);
        require((players[msg.sender].amount)*1000000000000000000 >= minBet*1000000000000000000, "Bet under minimum bet");
        require((players[msg.sender].amount)*1000000000000000000 <= balance/2, "Bet over contract funds");



      if(random() == (players[msg.sender].hot)){
        balance = balance - (players[msg.sender].amount)*1000000000000000000*2;
       msg.sender.transfer( (players[msg.sender].amount)*1000000000000000000*2 );

       message = "WIN";
       result = random();
         }
        else{

        message ="LOSE";
        result = random();

        }

        //maxBet = balance/2;

        balance += msg.value;
        }


// coin win or lose
    function random() public view returns(uint){
    return now % 2;
    }

   function getResult() public view returns(uint amount, uint hot, string memory s, uint r){
        address creator = msg.sender; // salvo indirizzo di chi da input in variabile creator
        s = message;
        r = result;
        return (players[creator].amount, players[creator].hot, s, r);
    }

// only owner can withdraw money
    function withdrawFunds(uint withdraw) public onlyOwner {

       balance = balance - withdraw*1000000000000000000;
       msg.sender.transfer(withdraw*1000000000000000000);
       //maxBet = balance/2;
   }

  function insertPlayer(player memory newPlayer) private {
        address creator = msg.sender; // variabile creator contiene address del giocatore
        players[creator] = newPlayer;  // collego player al suo address
    }



}

@enrico can you please post your migration file?

I’m trying to create a withdraw money function that gives the msg.sender twice the value if he gets a one, but I can’t seem to figure out how it works.
This is my code so far:

function insertMoney() public payable costs(1 ether){
  // Inserts money into the coinflip smart contract
    require(msg.value >= 1 ether);
    require(msg.value <= 100 ether);
    contractBalance += msg.value;
  }

  function withdrawMoney() public payable returns(uint) {
    if(random() == 1) {
      insertMoney();
      uint moneyEarned = msg.value * 2;
      msg.sender.transfer(moneyEarned);
      contractBalance -= moneyEarned;
      return moneyEarned;
    }

  }

Any suggestions?

Hi, I couldn’t make my dapp works, I don’t know why, can you show me how to correct it to make it work @dan-i.

Here is the link to the full project: https://drive.google.com/drive/folders/1hmLHy_gN7U52knCi0jUQj6Pu6oXRf4ew?usp=sharing

i checked the migration file and i found and fix the mistake.

now when i interact in the page of the contract when i set the bet i get this error from metamask:

inpage.js:1 MetaMask - RPC Error: Error: [ethjs-query] while formatting outputs from RPC '{"value":{"code":-32603,"message":"Internal JSON-RPC error.","data":{"message":"the tx doesn't have the correct nonce. account has nonce of: 0 tx has nonce of: 1","code":-32000,"data":{"stack":"Error: \n    at validateNonce (C:\\Program Files\\Ganache\\resources\\app.asar\\node_modules\\ganache-core\\lib\\statemanager.js:964:11)\n    at blockchain.getQueuedNonce (C:\\Program Files\\Ganache\\resources\\app.asar\\node_modules\\ganache-core\\lib\\statemanager.js:973:7)\n    at C:\\Program Files\\Ganache\\resources\\app.asar\\node_modules\\ganache-core\\lib\\blockchain_double.js:436:5\n    at C:\\Program Files\\Ganache\\resources\\app.asar\\node_modules\\ganache-core\\node_modules\\merkle-patricia-tree\\baseTrie.js:77:5\n    at C:\\Program Files\\Ganache\\resources\\app.asar\\node_modules\\ganache-core\\node_modules\\merkle-patricia-tree\\baseTrie.js:461:14\n    at Object.return (C:\\Program Files\\Ganache\\resources\\app.asar\\node_modules\\ganache-core\\node_modules\\merkle-patricia-tree\\baseTrie.js:485:9)\n    at processNode (C:\\Program Files\\Ganache\\resources\\app.asar\\node_modules\\ganache-core\\node_modules\\merkle-patricia-tree\\baseTrie.js:285:30)\n    at processNode (C:\\Program Files\\Ganache\\resources\\app.asar\\node_modules\\ganache-core\\node_modules\\merkle-patricia-tree\\baseTrie.js:521:5)\n    at C:\\Program Files\\Ganache\\resources\\app.asar\\node_modules\\ganache-core\\node_modules\\merkle-patricia-tree\\baseTrie.js:516:13\n    at C:\\Program Files\\Ganache\\resources\\app.asar\\node_modules\\ganache-core\\node_modules\\merkle-patricia-tree\\baseTrie.js:180:7\n    at _combinedTickCallback (internal/process/next_tick.js:131:7)\n    at process._tickCallback (internal/process/next_tick.js:180:9)","name":"TXRejectedError"}},"stack":"Error: Internal JSON-RPC error.\n    at s (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:60:394249)\n    at Object.internal (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:60:394652)\n    at l (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:60:56839)\n    at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:60:55995"}}' {code: -32603, message: "Error: [ethjs-query] while formatting outputs from…aeaoehlefnkodbefgpgknn/background.js:60:55995"}}'"}
(anonymous) @ inpage.js:1
(anonymous) @ inpage.js:15
_runReturnHandlers @ inpage.js:15
_processRequest @ inpage.js:15
async function (async)
_processRequest @ inpage.js:15
_handle @ inpage.js:15
handle @ inpage.js:15
_rpcRequest @ inpage.js:1
sendAsync @ inpage.js:1
s.send @ web3.min.js:1
n @ web3.min.js:1
(anonymous) @ web3.min.js:1
u @ web3.min.js:1
(anonymous) @ web3.min.js:1
(anonymous) @ inpage.js:15
Promise.finally (async)
_handle @ inpage.js:15
handle @ inpage.js:15
_rpcRequest @ inpage.js:1
sendAsync @ inpage.js:1
s.send @ web3.min.js:1
n @ web3.min.js:1
t @ web3.min.js:1
t @ web3.min.js:1
o._executeMethod @ web3.min.js:1
inputData @ main.js:37
dispatch @ jquery-3.4.1.min.js:2
v.handle @ jquery-3.4.1.min.js:2
web3.min.js:1 Uncaught (in promise) {code: -32603, message: "Error: [ethjs-query] while formatting outputs from…aeaoehlefnkodbefgpgknn/background.js:60:55995"}}'"}
(anonymous) @ web3.min.js:1
setTimeout (async)
_fireError @ web3.min.js:1
u @ web3.min.js:1
(anonymous) @ web3.min.js:1
(anonymous) @ inpage.js:15
Promise.finally (async)
_handle @ inpage.js:15
handle @ inpage.js:15
_rpcRequest @ inpage.js:1
sendAsync @ inpage.js:1
s.send @ web3.min.js:1
n @ web3.min.js:1
(anonymous) @ web3.min.js:1
u @ web3.min.js:1
(anonymous) @ web3.min.js:1
(anonymous) @ inpage.js:15
Promise.finally (async)
_handle @ inpage.js:15
handle @ inpage.js:15
_rpcRequest @ inpage.js:1
sendAsync @ inpage.js:1
s.send @ web3.min.js:1
n @ web3.min.js:1
t @ web3.min.js:1
t @ web3.min.js:1
o._executeMethod @ web3.min.js:1
inputData @ main.js:37
dispatch @ jquery-3.4.1.min.js:2
v.handle @ jquery-3.4.1.min.js:2

i don’t understand where the mistake is.

the contract is in the previous post

thanks a lot

Hey @Rithvik_Prakki

There are some errors in your code

function insertMoney() public payable costs(1 ether){
  // Inserts money into the coinflip smart contract
    require(msg.value >= 1 ether);
    require(msg.value <= 100 ether);
    contractBalance += msg.value;
  }

The require statements are both not necessary.
require(msg.value >= 1 ether); You don’t need this one as you are already using a modifier that checks the same condition costs(1 ether).

require(msg.value <= 100 ether); Not sure why you want to cap the max amount of ether that can be deposited.

  function withdrawMoney() public payable returns(uint) {
    if(random() == 1) {
      insertMoney();
      uint moneyEarned = msg.value * 2;
      msg.sender.transfer(moneyEarned);
      contractBalance -= moneyEarned;
      return moneyEarned;
    }
  }

Withdraw functions do not receive ether so it should not be payable.
uint moneyEarned = msg.value * 2; for the reason explained above this statement is wrong uint moneyEarned = msg.value * 2;

You have to retrieve the user balance (the amount of ether you want to send), and just msg.sender.transfer(_amount);

Hey @Oussama

What is the issue / error message you get?
How can I reproduce it?

Try to reset Metamask as explained here: https://metamask.zendesk.com/hc/en-us/articles/360015488891-Resetting-an-Account

1 Like

when I open the dapp and I put the bet amount and I click the button nothing happens, I provided the link to the file in the previous message, I think that the issue is in main.js because I’m not sure whether what I did, is correct or not.


1 Like

Hello @filip

I’ve been workin on the coinflip Dapp but I can’t figure out why I can’t reach te flip() function of the contract.

can you support?

https://github.com/leeandroleeite/coinflipDapp.git

Is anyone else having this error? I just can’t get passed the truffle setup…
Here is the commit with the changes for ropsten…
Also:

Hi, I recorded a demo of my implentation of Phase 1 - any feedback is much appreciated! <3
https://www.youtube.com/watch?v=_scoPGNWZR0&feature=youtu.be&ab_channel=RaunoK

I managed to fix the issue. I used the “wss…” instead of “https…” and it now works :slight_smile:

1 Like

Hey @leeandro.leeite

Can you please describe a way to reproduce the issue?

cheers,
Dani

good catch well done!

@dan-i @filip

In phase one I sent some ETH to my contract when I deployed it, but upgrading my contract to meet phase 2 requirements broke this functionality somehow. I get this error when I try to send the contract ether when deploying it; everything works fine if I deploy my contract without sending it ether. This is the error I get:

Here’s my contract code:

import "./Ownable.sol";
import "./provableAPI.sol";
pragma solidity 0.6.12;

contract Coinflip is Ownable, usingProvable {

  struct Bet { // We use this struct to map query IDs to bet data.
    address payable bettor_address;
    uint256 betamount;
    uint256 flipresult;
  }

  mapping (bytes32 => Bet) queries; //Create the mapping where we are gonna store every queryID and the result corresponding to that ID. When we get the ID we need to push it to the mapping.

  event QueryInitiated (
    bytes32 InitialQueryID
  );

  event QueryCompleted (
    bytes32 returnedQueryID,
    uint256 betResult,
    uint256 netamount,
    bytes proof
  );

  function __callback(bytes32 _queryId, string memory _result, bytes memory _proof) internal {
    //require(msg.sender == provable_cbAddress()); - enable this later when converting to actual orcale
    uint256 randomnumber = uint256(keccak256(abi.encodePacked(_result))) % 2; // Takes the result, encodes it, hashes it, converts it to an integer and returns either 0 or 1 if its even / odd respectively.
    queries[_queryId].flipresult = randomnumber; //Now we have the result of the flip - let's say 1 == win
    if (queries[_queryId].flipresult == 1){
      queries[_queryId].bettor_address.transfer(queries[_queryId].betamount * 2);
    }
    emit QueryCompleted(_queryId, queries[_queryId].betamount, queries[_queryId].flipresult, _proof);
  }

  function testRandom() internal returns (bytes32) { //Testing function by Philip so that we can test on localhost. provable_newRandomDSQuery takes 3 parameters, this takes 0.
    bytes32 queryId = bytes32(keccak256(abi.encodePacked(msg.sender)));
    __callback(queryId, "1", bytes("test")); // This will eventually be called by the oracle when we get an answer. Here it is called immediately for testing purposes.
    return queryId;
  }

  function Flip() public payable { //This is what the user of the dApp calls when they make a bet. 
    bytes32 queryID = testRandom(); //We get a query ID that is saved into this variable.
    queries[queryID].bettor_address = msg.sender; //Map bettor address to random number query ID.
    queries[queryID].betamount = msg.value; //Map bet amount to random number query ID.
    emit QueryInitiated(queryID); // Emits query ID to track in JS
  }

  function withdraw(uint amount) public onlyOwner{ //Withdraws specified amount in wei
    msg.sender.transfer(amount);
  }
}

And here’s my migration file. accounts[0] returns the correct Ganache account that has 100ETH on it.

const Coinflip = artifacts.require("Coinflip");

module.exports = async function (deployer, network, accounts) {
  await deployer.deploy(Coinflip, {from: accounts[0], value: web3.utils.toWei("1", "ether")}); //Send 10 ETH to the contract as initial balance. You can send funds to contract when you are deploying.
};
// THIS IS BROKEN FOR SOME REASON!!

I set the constructor to payable in Ownable.sol so the contract should be able to receive funds:

pragma solidity 0.6.12;

contract Ownable{
    address public owner;

    modifier onlyOwner(){
        require(msg.sender == owner);
        _; //Continue execution
    }

    constructor() public payable{
        owner = msg.sender;
    }
}

Once again, this functionality worked perfectly in phase 1 and I really have no idea what I could have changed to break it. Would really appreciate some help!

Here is version 1 of my Coin Flipper dApp. It isn’t pretty but I think it has some good functionality to start.

https://drive.google.com/file/d/1K-6M_aJXJa8CYPlTxkZrvypoG5u2fkRY/view?usp=sharing

2 Likes

I am not able to reproduce the issue, also there are no requirements in your constructor so if you can please push your modifications to Github and share the repo, I will take a look.

Thank your for the video well done!
Ready for phase two :muscle: