Created
November 7, 2024 10:19
-
-
Save halaprix/57361dee945e8a9c20a7e34ac19fe6ee to your computer and use it in GitHub Desktop.
simple tuple decoding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from eth_abi import decode | |
from eth_utils import to_hex, to_checksum_address | |
def decode_swap_data(hex_data): | |
# Remove '0x' if present | |
hex_data = hex_data.replace('0x', '') | |
# First, decode the initial offset | |
data_bytes = bytes.fromhex(hex_data) | |
(initial_offset,) = decode(['uint256'], data_bytes[:32]) | |
# Now decode the actual data starting from the offset | |
actual_data = data_bytes[initial_offset:] | |
# Define types in the same order as the struct | |
# Example of struct in Solidity: | |
""" | |
struct SwapData { | |
address fromAsset; | |
address toAsset; | |
uint256 amount; | |
uint256 receiveAtLeast; | |
uint256 fee; | |
bytes withData; | |
bool collectFeeInFromToken; | |
FeeType feeType; | |
} | |
""" | |
types = [ | |
'address', # fromAsset | |
'address', # toAsset | |
'uint256', # amount | |
'uint256', # receiveAtLeast | |
'uint256', # fee | |
'bytes', # withData | |
'bool', # collectFeeInFromToken | |
'uint8' # feeType (enum) | |
] | |
# Decode the data | |
decoded = decode(types, actual_data) | |
# Format the result into a dictionary ( optional to return feeType as enum ) | |
result = { | |
'fromAsset': to_checksum_address(decoded[0]), | |
'toAsset': to_checksum_address(decoded[1]), | |
'amount': decoded[2], | |
'receiveAtLeast': decoded[3], | |
'fee': decoded[4], | |
'withData': to_hex(decoded[5]), | |
'collectFeeInFromToken': decoded[6], | |
'feeType': 'Percentage' if decoded[7] == 0 else 'Fixed' # e.g. FeeType is an enum with values 0 for Percentage and 1 for Fixed | |
} | |
return result | |
# Your input data | |
hex_input = "0x..............." | |
try: | |
decoded_data = decode_swap_data(hex_input) | |
# Pretty print the result | |
print("Decoded SwapData:") | |
for key, value in decoded_data.items(): | |
print(f"{key}: {value}") | |
except Exception as e: | |
print(f"Error decoding data: {str(e)}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment