Files
pumpfun-bonkfun-bot/learning-examples/blockSubscribe_extract_transactions.py
T

81 lines
3.4 KiB
Python
Raw Normal View History

2024-09-09 09:04:23 +07:00
import asyncio
import hashlib
import json
import os
2025-03-05 07:03:32 +00:00
2024-09-09 09:04:23 +07:00
import websockets
from solders.pubkey import Pubkey
2024-09-09 09:04:23 +07:00
PUMP_PROGRAM = Pubkey.from_string("6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P")
WSS_ENDPOINT = os.environ.get("SOLANA_NODE_WSS_ENDPOINT")
2025-03-05 07:03:32 +00:00
2024-09-09 09:04:23 +07:00
async def save_transaction(tx_data, tx_signature):
os.makedirs("blockSubscribe-transactions", exist_ok=True)
hashed_signature = hashlib.sha256(tx_signature.encode()).hexdigest()
file_path = os.path.join("blockSubscribe-transactions", f"{hashed_signature}.json")
2025-03-05 07:03:32 +00:00
with open(file_path, "w") as f:
2024-09-09 09:04:23 +07:00
json.dump(tx_data, f, indent=2)
print(f"Saved transaction: {hashed_signature[:8]}...")
2025-03-05 07:03:32 +00:00
2024-09-09 09:04:23 +07:00
async def listen_for_transactions():
async with websockets.connect(WSS_ENDPOINT) as websocket:
2025-03-05 07:03:32 +00:00
subscription_message = json.dumps(
{
"jsonrpc": "2.0",
"id": 1,
"method": "blockSubscribe",
"params": [
{"mentionsAccountOrProgram": str(PUMP_PROGRAM)},
2025-03-05 07:03:32 +00:00
{
"commitment": "confirmed",
"encoding": "base64",
"showRewards": False,
"transactionDetails": "full",
"maxSupportedTransactionVersion": 0,
},
],
},
2025-03-05 07:03:32 +00:00
)
2024-09-09 09:04:23 +07:00
await websocket.send(subscription_message)
print(f"Subscribed to blocks mentioning program: {PUMP_PROGRAM}")
2024-09-09 09:04:23 +07:00
while True:
try:
response = await websocket.recv()
data = json.loads(response)
2025-03-05 07:03:32 +00:00
if "method" in data and data["method"] == "blockNotification":
if "params" in data and "result" in data["params"]:
block_data = data["params"]["result"]
if "value" in block_data and "block" in block_data["value"]:
block = block_data["value"]["block"]
if "transactions" in block:
transactions = block["transactions"]
2024-09-09 09:04:23 +07:00
for tx in transactions:
2025-03-05 07:03:32 +00:00
if isinstance(tx, dict) and "transaction" in tx:
if (
isinstance(tx["transaction"], list)
and len(tx["transaction"]) > 0
):
tx_signature = tx["transaction"][0]
elif (
isinstance(tx["transaction"], dict)
and "signatures" in tx["transaction"]
):
tx_signature = tx["transaction"][
"signatures"
][0]
2024-09-09 09:04:23 +07:00
else:
continue
await save_transaction(tx, tx_signature)
2025-03-05 07:03:32 +00:00
elif "result" in data:
print("Subscription confirmed")
2024-09-09 09:04:23 +07:00
except Exception as e:
print(f"An error occurred: {e!s}")
2024-09-09 09:04:23 +07:00
2025-03-05 07:03:32 +00:00
2024-09-09 09:04:23 +07:00
if __name__ == "__main__":
2025-03-05 07:03:32 +00:00
asyncio.run(listen_for_transactions())