2

What happens when an address(or an uint) is cast into a contract?

The documentation says that implicit conversions are done when no information is lost so you can convert from an uint128 to an uint 256 and not the other way around. From what I can tell the address type is just an uint160 with some extra functionality so the compiler doesn`t compile the following assignments:

uint160 a;
uint256 b;
address addr;

a = b;
addr = b;

On the other hand casting an uint256 into a contract compiles just fine even though that would mean an implicit conversion from uint256 to uint160:

contract Foo {

}
contract Bar{
Foo public foo;
uint256 addr;
foo = Foo(addr);

}

I set addr to uint256(-2) to wrap it around and checked the value of foo in remix and it seems to work the way explicit conversions are described to work in the docs, i.e. higher-order bits are cut off.

How come this is allowed? I couldn`t find anything relating to contract casting in the solidity docs, i.e. found nothing on the type that is expected by the cast contract.

1

Casting a uint256 to a contract is an explicit cast, there is no secondary implicit cast. You are responsible for making sure no important data is lost when performing an explicit cast.

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.