0

Hello Eth Stack Exchange,

I am practicing Solidity on Remix. This is actually the first language I have ever learned. In the contract below, I created a program to allow users to create dinosaurs and then fight them against one another.

I wanted to make the results of the fights (semi)random and in favor of the attacker, I tried to do that via this line of code in the fightDino function: if (uint((keccak256(now)) % 100) > 40) {

Why is the compiler telling me "Operator % not compatible with types bytes32 and int_const 100"

Here is a copy of the whole contract.

pragma solidity ^0.4.25;

contract DinoFighter {

uint cooldownTime = 30 seconds;

struct Dino {
    string name;
    string color;
    uint readyTime;
    uint level;
    string status;
}

Dino[] public dinos;
mapping (uint => address) public dinoToOwner;

 modifier onlyOwner(uint _dinoId) {
     require(dinoToOwner[_dinoId] == msg.sender);
     _;
 }

function createDino(string _name, string _color) public {
    uint id = dinos.push(Dino("Velonica", "Brown", (now + cooldownTime), 0, "none")) - 1;
    dinoToOwner[id] = msg.sender;
}

function fightDino(uint _dinoId, uint _targetId) public onlyOwner(_dinoId) returns (string) {
    Dino storage myDino = dinos[_dinoId];
    Dino storage tDino = dinos[_targetId];
    if (uint((keccak256(now)) % 100) > 40) {
        myDino.level++;
        myDino.status = "king";
        tDino.readyTime = now + cooldownTime;
        tDino.status = "loser";
        return "Winner";
    } 
    else {
        tDino.level++;
        tDino.status = "king";
        myDino.readyTime = now + cooldownTime;
        myDino.status = "loser";
        return "Loser";
    }


}
}

1 Answer 1

1

The error that you're getting pertains to the usage of operand %. Change the bracket ordering in the if conditional as follows and you won't get the error.

if ((uint(keccak256(now)) % 100) > 40) {
    myDino.level++;
    ...
} 

The error "Operator % not compatible with types bytes32 and int_const 100" is thrown because the operand resolution for % in your code happens such that the mode of the return value from keccak256(now) is calculated against 100, but since keccak256 returns bytes32 type, the compiler throws the error that it can't use % with a byte32 type and a const 100 type. I fixed it by converting the return value of keccak256(now) to an uint and then everything works fine.

1
  • @JulianMartinez glad I could help :) You can accept the answer by clicking the tick button next to the answer.
    – DaveIdito
    Commented Nov 7, 2018 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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