current position:Home>How to distinguish between contract address and ordinary account address?

How to distinguish between contract address and ordinary account address?

2022-02-03 20:46:54 Q & A of Denglian community

How to distinguish between contract address and ordinary account address ?




Take the answer 1:

We often need to distinguish whether an address is a contract address or an external account address , The key to distinguish is to see if there is any code associated with this address .EVM An opcode is provided EXTCODESIZE, Used to get the code size associated with the address ( length ), If it is an external account address , No code returns . Therefore, we can use the following methods to judge the contract address and external account address :

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

If it is judged outside the contract , You can use web3.eth.getCode (), Or corresponding JSON-RPC Method eth_getcode.getCode () The code used to obtain the contract corresponding to the parameter address , If the parameter is an external account address , Then return to ”0x”; If the parameter is contract , Then the corresponding bytecode is returned , As shown below :

web3.eth.getCode(“0xa5Acc472597C1e1651270da9081Cc5a0b38258E3”)“0x”

web3.eth.getCode(“0xd5677cf67b5aa051bb40496e68ad359eb97cfbf8”)

“0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b600060078202905091905056”

So we can get through getCode () What kind of address is it .




copyright notice
author[Q & A of Denglian community],Please bring the original link to reprint, thank you.
https://en.netfreeman.com/2022/02/202202032046520374.html

Random recommended