How to find out if an Ethereum address is a contract?

bortzmeyer picture bortzmeyer · Jun 5, 2016 · Viewed 15.4k times · Source

An address in Solidity can be an account or a contract (or other things, such as a transaction). When I have a variable x, holding an address, how can I test if it is a contract or not?

(Yes, I've read the chapter on types in the doc)

Answer

Manuel Araoz picture Manuel Araoz · Dec 2, 2016

Yes you can, by using some EVM assembly code to get the address' code size:

function isContract(address addr) returns (bool) {
  uint size;
  assembly { size := extcodesize(addr) }
  return size > 0;
}