Parse a Web3 exception and return a human-readable error message.
Exception from Web3 transaction or call
Human-readable error message
def parse_contract_error(error: Exception) -> str:
error_data = None
if hasattr(error, 'data'):
error_data = error.data
elif hasattr(error, 'args') and len(error.args) > 0:
if isinstance(error.args[0], dict) and 'data' in error.args[0]:
error_data = error.args[0]['data']
if error_data is None:
error_str = str(error)
if '0x' in error_str:
import re
hex_match = re.search('0x[a-fA-F0-9]+', error_str)
if hex_match:
error_data = hex_match.group(0)
if error_data:
signature = extract_error_signature(error_data)
if signature and signature in CONTRACT_ERROR_MESSAGES:
return CONTRACT_ERROR_MESSAGES[signature]
return str(error)