Created
January 29, 2025 17:53
-
-
Save sh4dowb/16ba949d00a95e69be8778bc09cdd9b4 to your computer and use it in GitHub Desktop.
solana websocket subscribe to transactions & all token transfers of address
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 websockets.sync.client import connect | |
import json | |
addresses = [] # base58 address/account/pubkey list | |
with connect('wss://solana-rpc.publicnode.com') as ws: | |
i = 0 | |
for address in addresses: | |
i += 1 | |
msg = json.dumps({"jsonrpc": "2.0", "id": i, "method": "logsSubscribe", "params": [{"mentions": [address]}, {"commitment": "finalized"}]}) | |
# subscribes to solana transactions. token transfers will mention the associated token addresses instead of owner address, so it's not picked up by this filter | |
ws.send(msg) | |
i += 1 | |
msg = json.dumps({"jsonrpc": "2.0", "id": i, "method": "programSubscribe", "params": [ | |
"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", {"commitment": "finalized", "encoding": "jsonParsed", "filters": [{"memcmp": {"offset": 32, "bytes": address, "encoding": "base58"}}]}]}) | |
# subscribes to both incoming and outgoing token transfers owned by this address | |
ws.send(msg) | |
while True: | |
# implement ping here if needed by websocket server | |
try: | |
msg = json.loads(ws.recv(timeout=1)) | |
except TimeoutError: | |
continue | |
if msg.get("method") not in ["logsNotification", "programNotification"]: | |
# print("Unhandled message:", msg) | |
continue | |
block = msg['params']['result']['context']['slot'] | |
print("Transaction in block:", block) | |
# these subscriptions don't provide transaction info | |
# scan the block and find the transaction with address (there can be multiple notifications for the same transaction/block) | |
# getBlock will have preBalance and postBalance, as well as preTokenBalance and postTokenBalance | |
# preBalance and postBalance indexes are in the same order as: transaction.message.accountKeys + meta.loadedAddresses.writable + meta.loadedAddresses.readonly | |
# token balances will contain owner, mint (token address), amount | |
# this data can be used to determine net transferred amounts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment