I am currently trying to implement a tool that requires me to fetch the latest swap data from Binance Smart Chain. After receiving the output from the log, I would like to convert the raw hex output into actual price of the underlying conversion.
{'address': '0x560a3375c67c8ad4c13018c87633e6066477151f', 'topics': ['0x19b47279256b2a23a1665c810c8d55a1758940ee09377d4f8d26497a3577dc83', '0x00000000000000000000000013f4ea83d0bd40e75c8222255bc855a974568dd4', '0x00000000000000000000000068f9dd546d6dadf72862fda46910e5d9bed93321'], 'data': '0xffffffffffffffffffffffffffffffffffffffffffffbc79ad35ea205f38ecd30000000000000000000000000000000000000000000000001bac1c6f72210000000000000000000000000000000000000000000000a3f94aae886f87faa0174e000000000000000000000000000000000000000000000f0a82803a369f4c9774fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe2bf500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000016ab4dc5620000', 'blockNumber': '0x2c7f78c', 'transactionHash': '0x468655b34618fef300638a2cf72e4668f7f7851bcbd69543b52081743dc55f43', 'transactionIndex': '0x2', 'blockHash': '0xff7781a757058ada921f5f12696825c8b772ee071dc67bef97b74273f78b3004', 'logIndex': '0x9', 'removed': False}
This is an example of the output I get of a swap, in this case the pair (PERRY/WBNB).
I tried some stuff and decoded it but for some reason I won't get the correct price, below you can see how I tried to get the price.
, , ,
from web3 import Web3
data = "0x00000000000000000000000000000000000000000000cd27cac5635ee2dc3373ffffffffffffffffffffffffffffffffffffffffffffffffcc666e6a579a81c40000000000000000000000000000000000000000007f5079c6974c18eb15de37000000000000000000000000000000000000000000000ee6581d2f59caeb088afffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe182f0000000000000000000000000000000000000000000000a81036b2e7516aca810000000000000000000000000000000000000000000000000000000000000000"
decoded_data = Web3.to_bytes(hexstr=data)
chunks = [decoded_data[i:i+32] for i in range(0, len(decoded_data), 32)]
values = [int.from_bytes(chunk, byteorder="big", signed=True) for chunk in chunks]
for i, value in enumerate(values): print(f"Slot {i}: {value}")
amount_in = abs(values[2]) / 1e18 amount_out = abs(values[3]) / 1e18
swap_price = amount_out / amount_in
, , ,
Would appreciate any help and code snippets.
Felix