0
# ABI Processing
1
2
Smart contract Application Binary Interface (ABI) manipulation including signature generation, function selectors, event topics, and parameter extraction. Essential for contract interaction and transaction processing.
3
4
## Capabilities
5
6
### Function Signature Processing
7
8
Generate function selectors and signatures for smart contract interaction.
9
10
```python { .api }
11
def function_signature_to_4byte_selector(function_signature: str) -> bytes:
12
"""
13
Generate 4-byte function selector from function signature.
14
15
Args:
16
function_signature (str): Function signature like "transfer(address,uint256)"
17
18
Returns:
19
bytes: 4-byte function selector
20
"""
21
22
def function_abi_to_4byte_selector(abi_element) -> bytes:
23
"""
24
Generate 4-byte function selector from ABI element.
25
26
Args:
27
abi_element: Function ABI dictionary
28
29
Returns:
30
bytes: 4-byte function selector
31
"""
32
33
def abi_to_signature(abi_element) -> str:
34
"""
35
Convert ABI element to signature string.
36
37
Args:
38
abi_element: ABI element (function, event, etc.)
39
40
Returns:
41
str: Signature string
42
"""
43
```
44
45
```python
46
from eth_utils import function_signature_to_4byte_selector, encode_hex
47
48
# Generate function selector for ERC-20 transfer
49
selector = function_signature_to_4byte_selector("transfer(address,uint256)")
50
print(encode_hex(selector)) # 0xa9059cbb
51
52
# Generate selector for approve function
53
approve_selector = function_signature_to_4byte_selector("approve(address,uint256)")
54
print(encode_hex(approve_selector)) # 0x095ea7b3
55
```
56
57
### Event Topic Generation
58
59
Generate Keccak-256 topics for event filtering and log processing.
60
61
```python { .api }
62
def event_signature_to_log_topic(event_signature: str) -> bytes:
63
"""
64
Generate Keccak-256 log topic from event signature.
65
66
Args:
67
event_signature (str): Event signature like "Transfer(address,address,uint256)"
68
69
Returns:
70
bytes: 32-byte Keccak-256 hash for topic filtering
71
"""
72
73
def event_abi_to_log_topic(event_abi) -> bytes:
74
"""
75
Generate log topic from event ABI element.
76
77
Args:
78
event_abi: Event ABI dictionary
79
80
Returns:
81
bytes: 32-byte Keccak-256 hash for topic filtering
82
"""
83
```
84
85
```python
86
from eth_utils import event_signature_to_log_topic, encode_hex
87
88
# Generate topic for ERC-20 Transfer event
89
topic = event_signature_to_log_topic("Transfer(address,address,uint256)")
90
print(encode_hex(topic)) # 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
91
92
# Generate topic for Approval event
93
approval_topic = event_signature_to_log_topic("Approval(address,address,uint256)")
94
print(encode_hex(approval_topic))
95
```
96
97
### ABI Filtering and Extraction
98
99
Filter and extract information from contract ABIs.
100
101
```python { .api }
102
def filter_abi_by_type(abi_type: str, contract_abi) -> list:
103
"""
104
Filter ABI elements by type.
105
106
Args:
107
abi_type (str): ABI element type ('function', 'event', 'constructor', etc.)
108
contract_abi: Contract ABI array
109
110
Returns:
111
list: Filtered ABI elements of specified type
112
"""
113
114
def filter_abi_by_name(abi_name: str, contract_abi) -> list:
115
"""
116
Filter ABI elements by name.
117
118
Args:
119
abi_name (str): Name of ABI element to find
120
contract_abi: Contract ABI array
121
122
Returns:
123
list: ABI elements with matching name
124
"""
125
126
def get_all_function_abis(contract_abi) -> list:
127
"""Extract all function ABIs from contract ABI."""
128
129
def get_all_event_abis(contract_abi) -> list:
130
"""Extract all event ABIs from contract ABI."""
131
```
132
133
### ABI Parameter Extraction
134
135
Extract parameter information from ABI elements.
136
137
```python { .api }
138
def get_abi_input_names(abi_element) -> list:
139
"""
140
Extract input parameter names from ABI element.
141
142
Args:
143
abi_element: ABI element (function, event, etc.)
144
145
Returns:
146
list: List of input parameter names (may contain None for unnamed params)
147
"""
148
149
def get_abi_input_types(abi_element) -> list:
150
"""
151
Extract input parameter types from ABI element.
152
153
Args:
154
abi_element: ABI element
155
156
Returns:
157
list: List of input parameter type strings
158
"""
159
160
def get_abi_output_names(abi_element) -> list:
161
"""Extract output parameter names from ABI element."""
162
163
def get_abi_output_types(abi_element) -> list:
164
"""Extract output parameter types from ABI element."""
165
```
166
167
### ABI Input Processing
168
169
Process and normalize function inputs according to ABI specification.
170
171
```python { .api }
172
def get_normalized_abi_inputs(abi_element, *args, **kwargs) -> tuple:
173
"""
174
Normalize and validate ABI inputs.
175
176
Args:
177
abi_element: Function ABI element
178
*args: Positional arguments
179
**kwargs: Keyword arguments
180
181
Returns:
182
tuple: Normalized input values
183
184
Raises:
185
ValidationError: If inputs don't match ABI specification
186
"""
187
188
def get_aligned_abi_inputs(abi_element, normalized_args) -> tuple:
189
"""
190
Align provided arguments with ABI specification.
191
192
Args:
193
abi_element: Function ABI element
194
normalized_args: Normalized argument values
195
196
Returns:
197
tuple: (types_tuple, values_tuple) aligned with ABI
198
"""
199
200
def collapse_if_tuple(abi) -> str:
201
"""
202
Extract argument types from ABI component, handling tuple types.
203
204
Args:
205
abi: ABI component or type string
206
207
Returns:
208
str: Collapsed type string
209
"""
210
```
211
212
## Usage Examples
213
214
### Contract Function Call Encoding
215
216
```python
217
from eth_utils import function_signature_to_4byte_selector, encode_hex
218
219
# Prepare function call data
220
function_sig = "transfer(address,uint256)"
221
selector = function_signature_to_4byte_selector(function_sig)
222
223
print(f"Function selector: {encode_hex(selector)}")
224
# Use selector as first 4 bytes of transaction data
225
```
226
227
### Event Log Filtering
228
229
```python
230
from eth_utils import event_signature_to_log_topic, encode_hex
231
232
# Create event filter for Transfer events
233
transfer_topic = event_signature_to_log_topic("Transfer(address,address,uint256)")
234
approval_topic = event_signature_to_log_topic("Approval(address,address,uint256)")
235
236
# Use topics for filtering logs
237
filter_params = {
238
"topics": [
239
[encode_hex(transfer_topic), encode_hex(approval_topic)] # Either event
240
]
241
}
242
```
243
244
### ABI Analysis
245
246
```python
247
from eth_utils import filter_abi_by_type, get_abi_input_types
248
249
# Sample ERC-20 ABI (partial)
250
erc20_abi = [
251
{
252
"type": "function",
253
"name": "transfer",
254
"inputs": [
255
{"name": "to", "type": "address"},
256
{"name": "amount", "type": "uint256"}
257
],
258
"outputs": [{"name": "", "type": "bool"}]
259
},
260
{
261
"type": "event",
262
"name": "Transfer",
263
"inputs": [
264
{"name": "from", "type": "address", "indexed": True},
265
{"name": "to", "type": "address", "indexed": True},
266
{"name": "value", "type": "uint256", "indexed": False}
267
]
268
}
269
]
270
271
# Extract all functions
272
functions = filter_abi_by_type("function", erc20_abi)
273
print(f"Found {len(functions)} functions")
274
275
# Get input types for transfer function
276
transfer_abi = functions[0]
277
input_types = get_abi_input_types(transfer_abi)
278
print(f"Transfer input types: {input_types}") # ['address', 'uint256']
279
```