Python, Web3 : Déterminer si un contrat contient une fonction donnée¶
Fonction Python qui renverra True
si une fonction donnée est présente dans un contrat (adapter RPC_URL
) :
from eth_hash.auto import keccak
from web3 import HTTPProvider, Web3
W3 = Web3(HTTPProvider("RPC_URL"))
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
Version anglaise très courte. Déplacement de l’article depuis le blog. Code plus rapide et supportant Web3.py v6+ : Avant : Après : Premier jet.📜 Historique¶
+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 = w3.keccak(signature.encode()).hex()
- fn_hash = f"63{fn_hash[2:10]}" # 0x63 is PUSH4
+ fn_hash = keccak(signature.encode()).hex()
+ fn_hash = f"63{fn_hash[:8]}" # 0x63 is PUSH4
return fn_hash in code
0,0677
sec0,0256
sec (- 62,2 %)