0

I have this contract:

// SPDX-License-Identifier: GPL-2.0-or-later

pragma solidity 0.7.4;

contract CoinFlip {
  uint public contractBalance;
  address owner;

  constructor() {
    owner = msg.sender;
    contractBalance = 0;
  }

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

  event WinOrLose(bytes4 coinSide);

  // 0 is HEADS and 1 is TAILS
  function bet(uint chosenSide) public payable {
    // Must be no less than 0.01 ETH and no more than 10 ETH in value
    require(msg.value >= 10000000000000000 && msg.value <= 10000000000000000000, "Improper amount entered.");

    // Contract must have enough funds to cover paying the bet, if won - plus some extra for gas
    contractBalance += msg.value;
    require(contractBalance >= msg.value * 2 + 100000000000000000, "Sorry, the contract cannot cover this bet.");

    uint side = block.timestamp % 2;
    bytes4 result;

    if (side == chosenSide) {
      result = "won";
      uint winnings = msg.value * 2;
      contractBalance -= winnings;
      (bool success, ) = msg.sender.call{value: winnings}("");
      require(success, "Ether send failed");
    } else {
      result = "lost";
    }
    emit WinOrLose(result);
  }

  fallback() external payable {}
  receive() external payable { contractBalance += msg.value; }

  function withdrawAll() public onlyOwner returns(uint) {
      uint toSend = address(this).balance;
      contractBalance = 0;
      (bool success, ) = msg.sender.call{value: toSend}("");
      require(success, "Ether send failed");
      return toSend;
  }

}

And this is the JS file I am using to interact with it.

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

$(document).ready(function() {
    window.ethereum.enable().then(function(accounts){
      contractInstance = new web3.eth.Contract(abi, "0x6B966608067c98A74c782e521e0d4f7FEd238250", {from: accounts[0]});
      console.log(contractInstance);

    });

    $(document).on("click", "#flip_button", function() {

      var amount = $("#amount_input").val();
      if (amount < 0.1 || amount > 10) {
        alert('invalid amount submitted');
      } else {
        $("#amount_input").val(null);

      var choice = $("input[name='flipping']:checked").val();

      var config = {value: web3.utils.toWei(amount, "ether")};

      contractInstance.methods.bet(choice).send(config)
      .once('transactionHash', function(hash){ })
      .once('receipt', function(receipt){ })
      .on('confirmation', function(confNumber, receipt){ })
      .on('error', function(error){ })
      .then(function(receipt){
        contractInstance.events.WinOrLose({})
        .on('data', function(returnValues){
          console.log("Result" + returnValues.coinSide);
      });
      });

      }
    });
});

I am trying to figure out how to capture my emitted event value after the ‘methods.bet’ function is executed. Have tried several things but nothing seems to work. No error, but nothing showing in the console either.

1
  • You have to start listening before making the bet. Inside the then block is too late the transaction was already processed. – Ismael Nov 8 '20 at 18:41
0

Alright so I worked it out. First of all, I found comments on another forum that apparently web3js subscription functionality does not play well with http provider.

Second of all, my event wasn’t firing at all in Ganache. Not sure why.

So what I did was deploy my contract to Kovan testnet and then I could see the event firing. Then I used the following code to catch the event from the transaction receipt (instead of subscription).

contractInstance.methods.bet(choice).send(config)
        .once('transactionHash', function(hash){ })
        .once('receipt', function(receipt){ })
        .on('confirmation', function(confNumber, receipt){ })
        .on('error', function(error){})
        .then(function(receipt){
        
          var myevent = receipt.events.WinOrLose.raw.topics[1];
          var eventDecoded = web3.utils.hexToUtf8(myevent);
          if (eventDecoded == 'won') {
            alert('YOU HAVE WON!');
          } else {
            alert('SORRY, YOU LOST.');
          }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.