Fonction bien utile qui renverra True
si une fonction donnée est présente dans un contrat :
from eth_hash.auto import keccak
def has_function(contract_addr: str, signature: str) -> bool:
code = w3.eth.get_code(contract_addr).hex()
fn_hash = keccak(signature.encode()).hex()
fn_hash = f"63{fn_hash[:8]}" # 0x63 is PUSH4
return fn_hash in code
Utilisation :
>>> contract_addr = "0x00e1656e45f18ec6747F5a8496Fd39B50b38396D" # random
>>> has_function(contract_addr, "transfer(address,uint256)")
True
>>> has_function(contract_addr, "rugMeDaddy(address)")
False
Nada !
Version anglaise très courte.
Historique
- 2022-04-23 : code plus rapide et supportant Web3.py v6+ (diff).