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

后端 未结 6 842
谎友^
谎友^ 2020-12-24 13:31

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 cont

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 14:22

    Short answer:

    require(tx.origin == msg.sender);
    

    tx.origin is a reference of the original address who initiates this serial function call, while msg.sender is the address who directly calls the target function. Which means, tx.origin must be a human, msg.sender can be a contract or human. Thus, if someone calls you from a contract, then the msg.sender is a contract address which is different from tx.origin.

    I know most contracts may use @Manuel Aráoz's code, which works in most cases. But if you call a function within the constructor of a contract, extcodesize will return 0 which fails the isContract check.

    NOTE: DON'T use tx.origin under other circumstances if you are not clear about what it represents because .

提交回复
热议问题