In some cases contracts have to be initialized with constant values: Contract A needs to know address of contract B. This address doesn't change anymore after deployment. Currently the easiest way to accomplish this is be passing the address of B to A as a constructor argument and save the address in a storage variable. This is very gas costly. It would be better to directly save the address in code. It would be beneficial if constants could be initialized in the constructor instead without using the contract storage at all:
contract A {
address constant B;
function Test(address _B) {
B = _B;
}
}
If a constant is not initialized after the constructor is executed, the compiler should throw a compiler error.
While it might be tempting to re-use the constant keyword here, I think we need a new keyword. Currently, constants are associated with contract "classes", which also allows things like X.c, i.e. referring to constants in other contract classes. This feature creates constants for contract instances, which cannot be accessed through the class name.
Understood. What about address immutable B;?
This would be very useful. When a storage value is meant to be immutable, then a constant value is both safer and more gas efficient. However developers often avoid using them because it reduces the portability of the code.
That said... I'm not sure how it could even be done in the current solidity constructor, since the values would need to be placed into the bytecode itself, like linking a library address.
Would be important that the storage slot configuration isn't changed for storing this information, otherwise it could make difficult to use this with delegatecall.
I strongly support this feature. It would greatly reduce the amount of assembly I have to write.
As SLOAD cost climbs, placing constants in code will be increasingly important for gas savings.
This is probably superseded, resp. will be implemented by https://github.com/ethereum/solidity/issues/3835
So if nobody objects, I'll close this in favour of https://github.com/ethereum/solidity/issues/3835
Closing this in favour of #3835
Most helpful comment
Understood. What about
address immutable B;?