|
| 1 | +from web3 import Web3 |
| 2 | +import json |
| 3 | +from pathlib import Path |
| 4 | +from .MUDIndexerSDK import MUDIndexerSDK |
| 5 | + |
| 6 | +def find_abi_files(root_dir): |
| 7 | + """Recursively find all ABI files""" |
| 8 | + abi_files = [] |
| 9 | + root_path = Path(root_dir) |
| 10 | + abi_patterns = ["*.abi.json", "*.json"] |
| 11 | + for pattern in abi_patterns: |
| 12 | + abi_files.extend(root_path.rglob(pattern)) |
| 13 | + return abi_files |
| 14 | + |
| 15 | +def load_abis(root_dir) -> dict: |
| 16 | + """Load all ABI files from directory structure""" |
| 17 | + abis = {} |
| 18 | + for abi_file in find_abi_files(root_dir): |
| 19 | + try: |
| 20 | + with open(abi_file, 'r') as f: |
| 21 | + abi_data = json.load(f) |
| 22 | + |
| 23 | + if isinstance(abi_data, dict): |
| 24 | + if 'abi' in abi_data: |
| 25 | + abi_data = abi_data['abi'] |
| 26 | + elif 'contracts' in abi_data: |
| 27 | + for contract_name, contract_data in abi_data['contracts'].items(): |
| 28 | + if 'abi' in contract_data: |
| 29 | + abis[contract_name] = contract_data['abi'] |
| 30 | + continue |
| 31 | + |
| 32 | + contract_name = abi_file.parent.name if abi_file.name == 'abi.json' else abi_file.stem.replace('.abi', '') |
| 33 | + abis[contract_name] = abi_data |
| 34 | + |
| 35 | + except Exception as e: |
| 36 | + print(f"Error processing {abi_file}: {e}") |
| 37 | + |
| 38 | + return abis |
| 39 | + |
| 40 | +class World: |
| 41 | + def __init__(self, rpc, world_address, abis_dir, indexer_url=None, mud_config_path=None): |
| 42 | + """ |
| 43 | + Initialize the World instance. |
| 44 | +
|
| 45 | + Args: |
| 46 | + rpc (str): RPC endpoint URL. |
| 47 | + world_address (str): The address of the World contract. |
| 48 | + abis_dir (str): Directory containing ABI files. |
| 49 | + indexer_url (str, optional): URL for the indexer. If provided, initializes the indexer. |
| 50 | + mud_config_path (str, optional): Path to the mud.config.ts file. Required if indexer_url is provided. |
| 51 | + """ |
| 52 | + self.w3 = Web3(Web3.HTTPProvider(rpc)) |
| 53 | + self.chain_id = self.w3.eth.chain_id # Automatically fetch the chain ID |
| 54 | + self.abis = load_abis(abis_dir) |
| 55 | + self.indexer = None |
| 56 | + |
| 57 | + # Initialize the contract |
| 58 | + if "IWorld" in self.abis: |
| 59 | + self.contract = self.w3.eth.contract(address=world_address, abi=self.abis["IWorld"]) |
| 60 | + self.errors = self._extract_all_errors() |
| 61 | + |
| 62 | + for func_name in dir(self.contract.functions): |
| 63 | + if not func_name.startswith("_"): |
| 64 | + original_function = getattr(self.contract.functions, func_name) |
| 65 | + setattr(self, func_name, self._wrap_function(original_function, func_name)) |
| 66 | + else: |
| 67 | + raise Exception("IWorld ABI not found") |
| 68 | + |
| 69 | + # Automatically set up the indexer if parameters are provided |
| 70 | + if indexer_url and mud_config_path: |
| 71 | + self._initialize_indexer(indexer_url, world_address, mud_config_path) |
| 72 | + |
| 73 | + def _initialize_indexer(self, indexer_url, world_address, mud_config_path): |
| 74 | + """ |
| 75 | + Initialize and set the indexer. |
| 76 | +
|
| 77 | + Args: |
| 78 | + indexer_url (str): URL for the indexer. |
| 79 | + world_address (str): The address of the World contract. |
| 80 | + mud_config_path (str): Path to the mud.config.ts file. |
| 81 | + """ |
| 82 | + from mud import MUDIndexerSDK # Assuming MUDIndexerSDK is part of your mud package |
| 83 | + |
| 84 | + # Create the indexer |
| 85 | + indexer = MUDIndexerSDK(indexer_url, world_address, mud_config_path) |
| 86 | + self.set_indexer(indexer) |
| 87 | + |
| 88 | + def set_indexer(self, indexer): |
| 89 | + """ |
| 90 | + Set the indexer instance and expose its tables. |
| 91 | +
|
| 92 | + Args: |
| 93 | + indexer (MUDIndexerSDK): The indexer instance. |
| 94 | + """ |
| 95 | + self.indexer = indexer |
| 96 | + |
| 97 | + # Expose tables as attributes directly under world.indexer |
| 98 | + for table_name in indexer.get_table_names(): |
| 99 | + table_instance = getattr(indexer.tables, table_name) |
| 100 | + setattr(self.indexer, table_name, table_instance) |
| 101 | + |
| 102 | + def _extract_all_errors(self): |
| 103 | + errors = {} |
| 104 | + for contract_name, abi in self.abis.items(): |
| 105 | + if not isinstance(abi, list): |
| 106 | + continue |
| 107 | + |
| 108 | + for item in abi: |
| 109 | + if item.get('type') == 'error': |
| 110 | + signature = f"{item['name']}({','.join(inp['type'] for inp in item.get('inputs', []))})" |
| 111 | + selector = self.w3.keccak(text=signature)[:4].hex() |
| 112 | + errors[selector] = (contract_name, item['name']) |
| 113 | + return errors |
| 114 | + |
| 115 | + def _wrap_function(self, contract_function, func_name): |
| 116 | + def wrapped_function(*args, **kwargs): |
| 117 | + try: |
| 118 | + return contract_function(*args, **kwargs).call() |
| 119 | + except Exception as e: |
| 120 | + error_str = str(e) |
| 121 | + if '0x' in error_str: |
| 122 | + import re |
| 123 | + hex_match = re.search(r'0x[a-fA-F0-9]+', error_str) |
| 124 | + if hex_match: |
| 125 | + selector = hex_match.group(0)[2:10] |
| 126 | + if selector in self.errors: |
| 127 | + contract, error = self.errors[selector] |
| 128 | + error_msg = f"{error} when calling {func_name}" |
| 129 | + new_error = type(e)((error_msg,)) |
| 130 | + raise new_error from None |
| 131 | + raise e |
| 132 | + return wrapped_function |
0 commit comments