0

Can parameter overflow be prevented in the contract, or does it have to be dealt with on the frontend?

Solidity:

contract parameterOverflows {

    uint8 selectedCharacter;

    modifier onlyCharacter(uint8 _character) {
        require(_character < 256);
           _;
    }

    function selectCharacter(uint8 _character) public onlyCharacter(_character) {
        selectedCharacter = _character;
    }

}

If selectCharacter(257) is called, selectedCharacter becomes 1 because (I think) the 257 overflows to 1.

This could be prevented by just not calling the function with anything outside the intended range, but is it possible to prevent this from the contract? Where exactly is the overflow happening?

1

Just change the type of your parameter to accept any uint so you prevent the overflow and you can do your assertion.

contract parameterOverflows {

    uint8 public selectedCharacter;

    modifier onlyCharacter(uint _character) {
        require(_character <= 255);
           _;
    }

    function selectCharacter(uint _character) public onlyCharacter(_character) {
        selectedCharacter = uint8(_character);
    }

}
  • 1
    Wouldn't 256 overflow as well? uint8 goes from 0-255 – Raghav Sood Aug 13 '18 at 1:38
  • oh, yeah, I just copy pasted the op code, but you're right. code updated – mirg Aug 13 '18 at 1:39

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.