Programming Project - Phase 2

@filip @dan-i I am having issues using provable_newRandomDSQuery function, as you can see in my code below I am trying to save the query_id in a mapping mapping(address => bytes32) userQuery;
and trying to compare it in _callback function to match with current user to get the random number.
But the quryId received in _callback is not matching to one that is stored when provable_newRandomDSQuery function called if(userQuery[msg.sender] == _queryId). I couldn’t find what is wrong here can you please help?
Thanks

bytes32 calledQueryId;
event LogNewProvableQuery(string description);
event generatedRandomNumber(uint256 randomNumber);
event coinFlipped(uint _coinState);
mapping(address => bytes32) userQuery;

function __callback(bytes32 _queryId, string memory _result, bytes memory _proof) public {
  require(msg.sender == provable_cbAddress());
  proof = _proof;
  if(userQuery[msg.sender] == _queryId) {
    uint256 randomNumber = uint256(keccak256(abi.encodePacked(_result))) % 2;
    latestNumber = randomNumber;
    emit generatedRandomNumber(randomNumber);
  } else {
    //in case it doesn't match set latestNumber to 0 to make it work remove it after testing.
    latestNumber = 0;
  }
}

function update() payable public {
  uint256 QUERY_EXECUTION_DELAY = 0;
  uint256 GAS_FOR_CALLBACK = 200000;
  address user = msg.sender;
  calledQueryId = provable_newRandomDSQuery(QUERY_EXECUTION_DELAY, NUM_RANDOM_BYTES_REQUESTED, GAS_FOR_CALLBACK);
  userQuery[user] = calledQueryId;
  emit LogNewProvableQuery("Provable query was sent, standing by for the answer");
}

Completed the CoinFlip Project using Provable. There’s definitely some improvements that could be made such as passing Provable gas fees onto users and changing to odds slightly to make a profit. Front End could definitely do with a polish, however all works as expected and I’m going to move onto another project now…

https://github.com/DecentB/IvanOnTech

1 Like

Hey @KaiStryker

My only concerns are how can I ensure that the required amount of gas is taken from the update() function and that, that amount doesn’t affect the contracts balance.

They have a function explained in their documentation that will help you with your question.

The function is the following:
provable_getPrice("random")

Give it a try :slight_smile:

If you need some help you can check my implementation: https://github.com/dani69654/CoinFlip/blob/master/contracts/CoinFlip.sol

Happy coding!
Dani

1 Like

Hey @kHarsh

These is a logic error in the code you wrote:
if(userQuery[msg.sender] == _queryId) {
msg.sender in the callBack function is the oracle, is not the user address therefore it will never match.

You have to rethink the way you are saving data because at the moment you are not able to associate a user with a queryId.

Think about it and let me know if you have questions.

Happy learning,
Dani

Hey @dan-i,

Ok great, implemented!

Thanks a lot,

Kai

1 Like

https://github.com/kharsh/FlipCoin

Thanks Dan I understand the issue just forget the callBack is called by oracle.so changed my code as follow.

function __callback(bytes32 _queryId, string memory _result, bytes memory _proof) public {
require(msg.sender == provable_cbAddress());
if (provable_randomDS_proofVerify__returnCode(_queryId, _result, _proof) == 0) {
uint256 latestNumber = uint256(keccak256(abi.encodePacked(_result))) % 2;
applyResult(_queryId, latestNumber);
emit generatedRandomNumber(latestNumber);
}
}

function update() internal {
  uint256 QUERY_EXECUTION_DELAY = 0;
  uint256 GAS_FOR_CALLBACK = 200000;
  bytes32 calledQueryId = provable_newRandomDSQuery(QUERY_EXECUTION_DELAY, NUM_RANDOM_BYTES_REQUESTED, GAS_FOR_CALLBACK);
  userQuery[gamblerAddress] = calledQueryId;
  emit LogNewProvableQuery("Provable query was sent, standing by for the answer");
}

function applyResult(bytes32 _queryId, uint256 _latestNumber) private {
  bytes32 storedQueryId = userQuery[gamblerAddress];
  if(storedQueryId == _queryId) {
    coinState = _latestNumber;
    emit coinFlipped(_latestNumber);
    uint256 winAmount =  betAmount;
    if(betChoice == _latestNumber) {
      winAmount = winAmount * 2;
      msg.sender.transfer(winAmount);
      contractBalance -= winAmount;
    } else {
     contractBalance += msg.value;
   }
  }

  delete(userQuery[gamblerAddress]);
}
1 Like

Hi,
I have managed to finish the second phase of building a DAPP by implementing the provable oracle. My GitHub repository can be found using this link: https://github.com/mihirf/Coin-Flipp-DAPP-Provable-Oracle-

I would appreciate any feedback as it will be highly valuable for future projects. I would also like to thank Ivan and Filip for providing the best resources to learn everything about blockchain development!

Thanks,

Finally finished! :grin:

Here is the Github link:

https://github.com/KaiStryker/coinflip-dapp

Would love some feedback. I am eager to learn and improve my skills so all comments and critiques are welcomed.

Heads up, the HTML is very basic and will be improved on once I learn how to use ReactJS.

Cheers,

Kai

1 Like

Hey @Mihir23

I tried to run your tests but lots of them are failing, can you double check?

thanks
Dani

Hi @dan-i,

Those test cases were made when I was using the pseudo random oracle code. They are only compatible with the previous version of my CoinFlip contract which can be found in this repository: https://github.com/mihirf/CoinFlip-Testing
If you download the respository above and set the directory to the CoinFlip folder(in PowerShell) the test cases will run perfectly. Let me know if there are any more issues.

Thanks,

Mihir

Good day! I need help migrating to ropsten. After running truffle migrate --network ropsten , I get this error

SyntaxError: Unexpected end of input
    at wrapSafe (node:internal/modules/cjs/loader:1024:16)
    at Module._compile (node:internal/modules/cjs/loader:1072:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Module.require (node:internal/modules/cjs/loader:997:19)
    at Object.require (node:internal/modules/cjs/helpers:92:18)
    at Function.load (/usr/local/lib/node_modules/truffle/build/webpack:/packages/config/dist/index.js:145:1)
    at Function.detect (/usr/local/lib/node_modules/truffle/build/webpack:/packages/config/dist/index.js:134:1)
    at Object.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/migrate.js:188:1)
    at Command.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/command.js:136:1)
    at Object.<anonymous> (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/cli.js:52:1)
    at __webpack_require__ (/usr/local/lib/node_modules/truffle/build/webpack:/webpack/bootstrap d3abaec0ba5c4953076d:19:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/webpack/bootstrap d3abaec0ba5c4953076d:65:1
    at Object.<anonymous> (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:71:10)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47
Truffle v5.0.42 (core: 5.0.42)
Node v15.7.0

Any ideas? Thanks!

Hi Filip

Am having issues installing npm init on my bet project am having below error

Update: I just forgot to comment out a line in truffle-config.js file

2 Likes

Good day! New problem :sweat_smile: I get this error after deploying the migrations contract

Saving migration to chain.
Error: Error: [object Object]
    at Object.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:96:1)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:94:5)
    at runMigrations (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/migrate.js:253:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/migrate.js:216:1
Truffle v5.0.42 (core: 5.0.42)
Node v15.7.0

I checked the transaction hash and contract address on ropsten etherscan and it seems good. What does saving migration to chain mean? Thanks!

I tried all my possible best to install npm int on my project path. All effort were lost so i copied node_modules path on my previous project into my bet project run npm install truffle-hdwallet-provider
am get below screen dump

Hi! I got a problem. It seems that even though I register all the pending bets (those that aren’t closed yet) in a mapping (assigning the correspondent player address), when I try to retrieve the address in closeBet(), it doesn’t exist inside the mapping.

I’m leaving the interested code and the events emitted when placing a new bet.
Any suggestions?

P.S. closeBet() is called by __callback(), just to be clear :slight_smile:

    struct Player {
        uint betAmount;
        uint betChoice;
        bool isWaiting;
    }

    mapping (address => Player) public betters; //to check who's the player
    mapping (bytes32 => address) public pendingBets; //to check who's the sender of a pending bet 

    function placeBet(uint _choice) public payable costsAtLeast {
        require(msg.value*2 <= balance, "Contract hasn't enough funds to perform this bet");
        require(betters[msg.sender].isWaiting == false, "This address still has an open bet");
        require(_choice <= 1, "The parameter _choice must be 0 or 1");

        balance += msg.value;
        
        bytes32 betId = update();
        pendingBets[betId] = msg.sender;
        betters[msg.sender].isWaiting = true;
        betters[msg.sender].betAmount = msg.value;
        betters[msg.sender].betChoice = _choice;
        
        emit PlacedBet(betId, msg.sender, msg.value, _choice);
        emit DebugPlacingBet(betId, pendingBets[betId]);
    }

    function closeBet(bytes32 _id, uint _result) public returns(bool) {

        address payable player = address(uint160(pendingBets[_id]));
        bool win = false;
        
        if (betters[player].betChoice == _result) {
            win = true;
            player.transfer((betters[player].betAmount*2));
            balance -= (betters[player].betAmount*2);
        }
        
        emit DebugClosingBet(_id, pendingBets[_id], betters[pendingBets[_id]].isWaiting ,betters[pendingBets[_id]].betChoice, _result);

        betters[pendingBets[_id]].isWaiting = false;
        delete pendingBets[_id];

        emit ClosedBet(_id, win);

        return win;
    }
//LOGS
	{
		"from": "0xECa4BEa0F1C7D586Ed3E194a8d33be40EbFFcD46",
		"topic": "0x07ece582b689dd9feebd135b79d6445063b32759bb58752ffe1257488a0fff33",
		"event": "DebugPlacingBet",
		"args": {
			"0": "0xe70e947083bab17d173066e35190201f5d579eb5f30a2efb20693669ecd9fe7f",
			"1": "0x2A418b2E91EbAdC72c04edB0318F5D64427BBdB9",
			"betId": "0xe70e947083bab17d173066e35190201f5d579eb5f30a2efb20693669ecd9fe7f",
			"player": "0x2A418b2E91EbAdC72c04edB0318F5D64427BBdB9"
		}
	},
    {
		"from": "0xECa4BEa0F1C7D586Ed3E194a8d33be40EbFFcD46",
		"topic": "0xcc0857fa74b86b1b46395fb6fc0cb0b87b8e4f096c4cc1bcbc4a0168e36c327c",
		"event": "DebugClosingBet",
		"args": {
			"0": "0xe70e947083bab17d173066e35190201f5d579eb5f30a2efb20693669ecd9fe7f",
			"1": "0x0000000000000000000000000000000000000000",
			"2": false,
			"3": "0",
			"4": "0",
			"betId": "0xe70e947083bab17d173066e35190201f5d579eb5f30a2efb20693669ecd9fe7f",
			"playerAddress": "0x0000000000000000000000000000000000000000",
			"waiting": false,
			"choice": "0",
			"randomNumber": "0"
		 }
	 }

Hey @chim4us

Not sure why your are npm init but still I don’t see any error there.
What I think you want to do is truffle init to start a new truffle project.

Also about your new post related to the truffle hd wallet, you have to install the new pkg as the one you are installing is deprecated.

Run npm i @truffle/hdwallet-provider

Cheers,
Dani

Hey @Jose_Hernandez

Follow this faq and downgrade node: FAQ - How to downgrade Node.Js

Should solve.

1 Like

Hi! Downgraded node to v10.21.0 got a new error, shorter one this time

Saving migration to chain.
Error: Error: [object Object]
    at Object.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:96:1)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Truffle v5.0.42 (core: 5.0.42)
Node v10.21.0