1

So I am currently implementing a Hash-Time-Lock using a given Interface for my contract.

The interface requires to give a duration as a uint(256) but then wants the produced deadline (duration + block.timestamp) to be a uint32.

This made me wonder why it is so easy to cast a uint into a uint32 in Solidity. Coming from Rust where it is a big No-Go to cast say a usize to a u16 (in fact not possible unless you use unsafe code), I was thinking if Solidity had any inbuilt checks for these things. After all its a big security risk, as far as I understand. E.g. in a Hashtimelock contract by inputing a duration that (in combination with the timestamp of the block) that would be downcast to unwanted.

Also I could not find anything about the (un-)safety of downcasting in Solidity anywhere on the Internet. Thanks in advance!

1 Answer 1

0

If you cast a value this is known as Explicit Conversion. This comes with the following warning in the docs:

If the compiler does not allow implicit conversion but you are confident a conversion will work, an explicit type conversion is sometimes possible. This may result in unexpected behaviour and allows you to bypass some security features of the compiler, so be sure to test that the result is what you want and expect!

So yeah as you mentioned this can be potentially dangerous as data is "cut off".

If you want to be on the safe side you should rely on Implicit Conversion or perform the necessary check before casting.

1
  • Thank you for your answer and the links :) Commented Jan 25, 2022 at 16:22

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.