In defi contracts, I see codes like this

address public constant dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);

What's the point of casting an address to address? Or is this just messy code? Thanks


The type of value 0x6B175474E89094C44Da98b954EedeAC495271d0F is actually address literal (https://docs.soliditylang.org/en/v0.7.0/types.html#address-literals) which is not exactly the same as an address - although it is easy to convert between these two.

Doing just address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; works as well but under the hood Solidity is casting it into an address as it recognizes that it looks like an address (and because you are setting it to an address type).

So you can basically choose. Doing an explicit cast makes the intention clearer - it's often good to be as clear as possible when writing Solidity code.

  • Opening statement is wrong. The value of 0x6B1...d0F is... well, 0x6B1...d0F. Its type (which is probably what you meant to say) is not string but uint (or integer in general). – goodvibration Nov 18 '20 at 9:22
  • Thanks for the heads up. I couldn't find a source which claims that addresses are stored as uints - I changed my answer to talk about type of address literal. – Lauri Peltonen Nov 18 '20 at 10:04
  • I'm pretty sure that 0x... is regarded as an integer in every strongly-typed language (such as Solidity). In fact, even in JS, which is not a strongly-typed language AFAIK, it will be regarded as Number rather than String (causing a lot of headache to web3.js developers who are not aware of this, as address values typically exceed Number.MAX_SAFE_INTEGER). – goodvibration Nov 18 '20 at 10:07
  • Could very well be true. However since even Solidity documentation fails to mention this I don't want to mention it - I don't see any reason to confuse things more. The eventual underlying type is not relevant here in my opinion. – Lauri Peltonen Nov 18 '20 at 10:11
  • You can try something as simple as uint256 x = 0x6B175474E89094C44Da98b954EedeAC495271d0F;, and see that it compiles well. Replace uint256 with string, and compilation will fail. – goodvibration Nov 18 '20 at 10:15

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.