是这样的。 突然想到可以让gpt帮我这个代码小白写代码。 然后我就向它提出要求了。
代码是出来了,但是它总是要遍历区块。 我想,你这不慢到天际了么。
我就让它不要遍历,直接浏览区块链浏览器来搞定。
可,它就是不干。
我无语了。
大佬们,帮忙看看。
我也就是想, 输入代币地址,输出代币的交易记录(谁买的,买了多少,花了多少E/B;谁卖的,卖了多少,得到了多少E/B)
from eth_abi import decode_abi
import pandas as pd
from datetime import datetime
w3 = Web3(Web3.HTTPProvider('https://bsc-dataseed.binance.org/'))
def get_transactions(pair_address, start_block=0, end_block=None):
if end_block is None:
end_block = w3.eth.blockNumber
swap_event_signature = "Swap(address,uint256,uint256,uint256,uint256,address)"
swap_event_topic = w3.keccak(text=swap_event_signature).hex()
logs = w3.eth.getLogs({'fromBlock': start_block, 'toBlock': end_block, 'address': pair_address, 'topics': [swap_event_topic]})
swaps = []
for log in logs:
swap = decode_abi(['address', 'uint256', 'uint256', 'uint256', 'uint256', 'address'], bytes.fromhex(log['data'][2:]))
timestamp = pd.to_datetime(w3.eth.getBlock(log['blockNumber'])['timestamp'], unit='s')
timestamp_utc8 = timestamp.tz_localize('UTC').tz_convert('Asia/Shanghai')
swaps.append({
'交易哈希': log['transactionHash'].hex(),
'交易时间': timestamp_utc8,
'买入方': swap[0],
'卖出方': swap[5],
'买入数量': swap[1] / (10 ** 18),
'卖出数量': swap[2] / (10 ** 18),
})
return pd.DataFrame(swaps)
def get_token_symbol(token_address):
contract = w3.eth.contract(address=token_address, abi=[{"constant":True,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"type":"function"}])
return contract.functions.symbol().call()
def main():
pair_address = input('请输入 PancakeSwap Pair 合约地址(例如:0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852): ')
token0_address = input('请输入 PancakeSwap Pair 合约的 token0 地址: ')
token0_symbol = get_token_symbol(Web3.toChecksumAddress(token0_address))
df = get_transactions(Web3.toChecksumAddress(pair_address), start_block=0)
filename = f'{token0_symbol}swap{datetime.now().strftime("%Y%m%d%H%M%S")}.xlsx'
df.to_excel(filename, index=False)
print(f'交易数据已保存到 {filename}')
if __name__ == "__main__":
main()