2

I am learning to program Solidity and just playing around with it in remix.

I am creating compiling the following code in Solidity:

pragma solidity >=0.4.22 <0.6.0;
contract Ballot {
    function giveRightToVote() public {
        uint8 tempnumber = 0;
        tempnumber += 1;
    }
}

Just a simple contract with no state variables.

When I change the keyword contract to library as in:

pragma solidity >=0.4.22 <0.6.0;
library Ballot {
    function giveRightToVote() public {
        uint8 tempnumber = 0;
        tempnumber += 1;
    }
}

The bytecode generated is completely different.

As per the solidity documentation, I infer that a library is only a contract that promises not to make any state changes to the caller (due to being stateless itself), unless the caller explicitly provides it with storage pointers.

As per my understanding, the bytecode in both cases should be the same.

Why is there a difference?

  • The function is obviously pure in the library. I'm not sure, but perhaps the compiler doesn't need you to specify this obvious fact, and automatically sets the function as such. In the contract, however, it is possibly not the case. Again, I'm not sure about the behavior of the compiler in this case, but I know that the function can be pure, view or neither (even though pure is the most suitable choice of course). So in short, I suggest that you explicitly declare it pure and then compare the bytecode again. – goodvibration Feb 16 at 2:03
  • Compiled both the segments with the pure keyword. Still completely different bytecodes generated by the compiler. – Mudabbir Feb 16 at 3:23
  • As you know, for each function, the selector is calculated as a hash (keccak256) of the function name followed by the function argument types inside parenthesis. For example, a hash of "transfer(address,uint256)". I believe that in a library, the name of each function is prepended with the name of the library, in order to avoid a possible collision between library functions and contract functions. For example, allow a contract to implement func(uint) and use a library which implements func(uint). So all function selectors are completely different, and subsequently, so is the byte-code. – goodvibration Feb 16 at 5:20
  • Possibly related question here. In order to assert my conjecture above, you can look into the solc's source code here and see if you find it there. – goodvibration Feb 16 at 5:22

Your Answer

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

Browse other questions tagged or ask your own question.