solana-launch-forensics 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ """Read-only forensics for pump.fun style token launches.
2
+
3
+ The package answers four questions from public chain data alone:
4
+
5
+ 1. Which mints did a wallet create?
6
+ 2. How fast, and were any created in the same transaction?
7
+ 3. How did the proceeds leave, and did the payouts repeat a single size?
8
+ 4. Which mints belong to the same operator, and what is the evidence?
9
+
10
+ It never guesses intent. It reports signatures, slots and amounts, so the
11
+ reader can check every claim against an explorer.
12
+ """
13
+
14
+ from .analytics import (
15
+ create_count,
16
+ equal_size_outflows,
17
+ funding_inflows,
18
+ pump_invocations,
19
+ signers,
20
+ summarize,
21
+ sweep_count,
22
+ swept_mints,
23
+ system_transfers,
24
+ token_mints_in_tx,
25
+ )
26
+ from .cluster import build_clusters
27
+ from .rpc import Rpc, RpcError
28
+
29
+ __version__ = "0.2.0"
30
+
31
+ __all__ = [
32
+ "Rpc",
33
+ "RpcError",
34
+ "build_clusters",
35
+ "create_count",
36
+ "equal_size_outflows",
37
+ "funding_inflows",
38
+ "pump_invocations",
39
+ "signers",
40
+ "summarize",
41
+ "sweep_count",
42
+ "swept_mints",
43
+ "system_transfers",
44
+ "token_mints_in_tx",
45
+ "__version__",
46
+ ]
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,337 @@
1
+ """Parsing helpers for Solana transactions returned in ``jsonParsed`` encoding.
2
+
3
+ The goal is deliberately narrow: turn one transaction into a small set of
4
+ facts that are useful when auditing token launches.
5
+
6
+ * who paid and who signed
7
+ * which program ran which instruction (resolved from the log stack)
8
+ * which token mints were touched, and how many were created
9
+ * how SOL moved between accounts
10
+
11
+ Nothing here assigns blame. It reports what the chain says.
12
+
13
+ Two details matter more than they look:
14
+
15
+ 1. Contemporary RPC responses for versioned transactions omit
16
+ ``message.header``. Signers therefore come from the per-account
17
+ ``signer`` flag when it is present.
18
+ 2. ``Program log:`` lines carry no program id. Log lines must be attributed
19
+ by walking the ``invoke`` / ``success`` stack, otherwise a token program
20
+ logging ``Instruction: InitializeMint2`` gets counted as a pump.fun
21
+ instruction.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from collections import Counter, defaultdict
27
+ from typing import Iterator
28
+
29
+ PUMP_PROGRAM = "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"
30
+ SYSTEM_PROGRAM = "11111111111111111111111111111111"
31
+ TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
32
+ TOKEN_2022_PROGRAM = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"
33
+ ASSOCIATED_TOKEN_PROGRAM = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
34
+
35
+ LAMPORTS_PER_SOL = 1_000_000_000
36
+
37
+ CREATE_INSTRUCTIONS = {"Create", "CreateV2"}
38
+ SWEEP_INSTRUCTIONS = {"SweepCreatorFee", "CollectCreatorFeeV2"}
39
+
40
+
41
+ # -- accounts -------------------------------------------------------------
42
+ def account_keys(tx: dict) -> list[str]:
43
+ keys = tx["transaction"]["message"]["accountKeys"]
44
+ return [k["pubkey"] if isinstance(k, dict) else k for k in keys]
45
+
46
+
47
+ def signers(tx: dict) -> list[str]:
48
+ """All signing accounts, in account-key order.
49
+
50
+ Handles both the modern (per-key ``signer`` flag) and legacy
51
+ (``message.header.numRequiredSignatures``) representations.
52
+ """
53
+ raw = tx["transaction"]["message"]["accountKeys"]
54
+ if raw and isinstance(raw[0], dict) and "signer" in raw[0]:
55
+ return [k["pubkey"] for k in raw if k.get("signer")]
56
+
57
+ header = tx["transaction"]["message"].get("header") or {}
58
+ n = header.get("numRequiredSignatures", 1)
59
+ return account_keys(tx)[:n]
60
+
61
+
62
+ def fee_payer(tx: dict) -> str | None:
63
+ keys = account_keys(tx)
64
+ return keys[0] if keys else None
65
+
66
+
67
+ # -- instructions ---------------------------------------------------------
68
+ def all_instructions(tx: dict) -> Iterator[dict]:
69
+ """Yield outer instructions first, then inner instructions."""
70
+ yield from tx["transaction"]["message"]["instructions"]
71
+ meta = tx.get("meta") or {}
72
+ for group in meta.get("innerInstructions") or []:
73
+ yield from group.get("instructions") or []
74
+
75
+
76
+ def program_ids(tx: dict) -> list[str]:
77
+ return [ix.get("programId", "") for ix in all_instructions(tx)]
78
+
79
+
80
+ def pump_invocations(tx: dict) -> int:
81
+ """How many times the pump.fun program was entered (outer + inner)."""
82
+ return sum(1 for pid in program_ids(tx) if pid == PUMP_PROGRAM)
83
+
84
+
85
+ def log_messages(tx: dict) -> list[str]:
86
+ return (tx.get("meta") or {}).get("logMessages") or []
87
+
88
+
89
+ def log_events(tx: dict) -> list[dict]:
90
+ """Pair every ``Program log:`` line with the program that emitted it.
91
+
92
+ The runtime interleaves ``invoke`` / ``success`` markers, so a simple
93
+ stack walk recovers attribution exactly:
94
+
95
+ Program A invoke [1] stack: [A]
96
+ Program log: Instruction: X -> A
97
+ Program B invoke [2] stack: [A, B]
98
+ Program log: Instruction: Y -> B
99
+ Program B success stack: [A]
100
+
101
+ ``Program log: Instruction:`` lines are normalised to
102
+ ``{"program", "instruction"}``. Other log lines keep their raw text.
103
+ """
104
+ stack: list[str] = []
105
+ events: list[dict] = []
106
+
107
+ for line in log_messages(tx):
108
+ if line.startswith("Program ") and " invoke [" in line:
109
+ stack.append(line.split()[1])
110
+ continue
111
+
112
+ if line.startswith("Program ") and line.endswith(" success"):
113
+ if stack:
114
+ stack.pop()
115
+ continue
116
+
117
+ if line.startswith("Program ") and " consumed " in line:
118
+ continue
119
+
120
+ if not line.startswith("Program log: "):
121
+ continue
122
+
123
+ body = line[len("Program log: "):]
124
+ owner = stack[-1] if stack else None
125
+ if body.startswith("Instruction: "):
126
+ events.append(
127
+ {
128
+ "program": owner,
129
+ "instruction": body[len("Instruction: "):].strip(),
130
+ "raw": line,
131
+ }
132
+ )
133
+ else:
134
+ events.append({"program": owner, "instruction": None, "raw": line})
135
+
136
+ return events
137
+
138
+
139
+ def pump_instruction_names(tx: dict) -> list[str]:
140
+ """pump.fun instruction names in execution order."""
141
+ return [
142
+ e["instruction"]
143
+ for e in log_events(tx)
144
+ if e["program"] == PUMP_PROGRAM and e["instruction"]
145
+ ]
146
+
147
+
148
+ def pump_ops(tx: dict) -> dict[str, int]:
149
+ """Counts per pump.fun instruction name."""
150
+ return dict(Counter(pump_instruction_names(tx)))
151
+
152
+
153
+ def create_count(tx: dict) -> int:
154
+ """Number of token-creation calls.
155
+
156
+ pump.fun emits ``Instruction: Create`` or ``Instruction: CreateV2`` once
157
+ per mint. Attribution is by program stack, so the token program's own
158
+ ``InitializeMint2`` is never mistaken for a launch.
159
+ """
160
+ return sum(1 for name in pump_instruction_names(tx) if name in CREATE_INSTRUCTIONS)
161
+
162
+
163
+ def sweep_count(tx: dict) -> int:
164
+ """Number of creator-fee collection calls.
165
+
166
+ ``SweepCreatorFee`` and ``CollectCreatorFeeV2`` can only be issued by a
167
+ mint's creator, so a sweep is ownership evidence, not a behavioural
168
+ guess. It is also easily confused with a creation when instructions are
169
+ counted without reading their names.
170
+ """
171
+ return sum(1 for name in pump_instruction_names(tx) if name in SWEEP_INSTRUCTIONS)
172
+
173
+
174
+ def swept_mints(tx: dict) -> list[str]:
175
+ """Mints whose creator fee was collected in this transaction.
176
+
177
+ Returns an empty list for transactions that contain no sweep, so the
178
+ caller can use it as a predicate without a second pass over the logs.
179
+ """
180
+ if not sweep_count(tx):
181
+ return []
182
+ return token_mints_in_tx(tx)
183
+
184
+
185
+ # -- tokens ---------------------------------------------------------------
186
+ def token_mints_in_tx(tx: dict) -> list[str]:
187
+ """Mints *referenced* by the transaction.
188
+
189
+ This is intentionally broader than creation: a fee-sweep transaction
190
+ touches mints it did not create. Use :func:`create_count` to separate
191
+ the two questions.
192
+
193
+ pump.fun mints carry a ``pump`` vanity suffix, which makes the first
194
+ heuristic cheap. ``initializeMint`` instructions are also parsed so
195
+ non-pump SPL mints are picked up when the encoding allows it.
196
+ """
197
+ found: dict[str, None] = {}
198
+
199
+ for key in account_keys(tx):
200
+ if key.endswith("pump"):
201
+ found[key] = None
202
+
203
+ for ix in all_instructions(tx):
204
+ if ix.get("programId") not in (TOKEN_PROGRAM, TOKEN_2022_PROGRAM):
205
+ continue
206
+ parsed = ix.get("parsed")
207
+ if not isinstance(parsed, dict):
208
+ continue
209
+ if parsed.get("type") in {"initializeMint", "initializeMint2"}:
210
+ mint = (parsed.get("info") or {}).get("mint")
211
+ if mint:
212
+ found[mint] = None
213
+
214
+ return list(found)
215
+
216
+
217
+ # -- value flow -----------------------------------------------------------
218
+ def system_transfers(tx: dict) -> list[dict]:
219
+ """SOL transfers as ``{source, destination, lamports}``."""
220
+ out: list[dict] = []
221
+ for ix in all_instructions(tx):
222
+ if ix.get("programId") != SYSTEM_PROGRAM:
223
+ continue
224
+ parsed = ix.get("parsed")
225
+ if not isinstance(parsed, dict) or parsed.get("type") != "transfer":
226
+ continue
227
+ info = parsed.get("info") or {}
228
+ try:
229
+ lamports = int(info.get("lamports", 0))
230
+ except (TypeError, ValueError):
231
+ continue
232
+ out.append(
233
+ {
234
+ "source": info.get("source"),
235
+ "destination": info.get("destination"),
236
+ "lamports": lamports,
237
+ }
238
+ )
239
+ return out
240
+
241
+
242
+ def funding_inflows(tx: dict) -> list[dict]:
243
+ """SOL transfers into the fee payer from another account.
244
+
245
+ A launch wallet is usually funded just before it creates, so the payer is
246
+ a useful link between otherwise unrelated creations. Transfers out of the
247
+ payer are excluded: they say nothing about who controls it.
248
+ """
249
+ payer = fee_payer(tx)
250
+ if not payer:
251
+ return []
252
+ out: list[dict] = []
253
+ for t in system_transfers(tx):
254
+ if t["destination"] != payer or t["source"] == payer:
255
+ continue
256
+ if t["lamports"] <= 0 or not t["source"]:
257
+ continue
258
+ out.append(
259
+ {
260
+ "from": t["source"],
261
+ "to": payer,
262
+ "lamports": t["lamports"],
263
+ }
264
+ )
265
+ return out
266
+
267
+
268
+ def sol_balance_deltas(tx: dict) -> dict[str, int]:
269
+ """Net lamport change per account, from ``meta.pre/postBalances``."""
270
+ meta = tx.get("meta") or {}
271
+ keys = account_keys(tx)
272
+ pre = meta.get("preBalances") or []
273
+ post = meta.get("postBalances") or []
274
+ deltas: dict[str, int] = {}
275
+ for i, key in enumerate(keys):
276
+ if i >= len(pre) or i >= len(post):
277
+ continue
278
+ deltas[key] = deltas.get(key, 0) + (post[i] - pre[i])
279
+ return deltas
280
+
281
+
282
+ def equal_size_outflows(tx: dict, *, min_count: int = 2) -> list[dict]:
283
+ """Groups of transfers leaving a signer with an identical lamport size.
284
+
285
+ Scripted payouts tend to round to one number; humans rarely do.
286
+ """
287
+ signer_set = set(signers(tx))
288
+ groups: dict[int, list[str]] = defaultdict(list)
289
+ for t in system_transfers(tx):
290
+ if t["source"] in signer_set and t["lamports"] > 0:
291
+ groups[t["lamports"]].append(t["destination"])
292
+
293
+ out = []
294
+ for lamports, dests in groups.items():
295
+ unique = sorted({d for d in dests if d})
296
+ if len(unique) >= min_count:
297
+ out.append(
298
+ {
299
+ "lamports": lamports,
300
+ "sol": lamports / LAMPORTS_PER_SOL,
301
+ "destinations": unique,
302
+ }
303
+ )
304
+ return sorted(out, key=lambda g: -g["lamports"])
305
+
306
+
307
+ # -- summary --------------------------------------------------------------
308
+ def summarize(tx: dict) -> dict:
309
+ meta = tx.get("meta") or {}
310
+ mints = token_mints_in_tx(tx)
311
+ names = pump_instruction_names(tx)
312
+ ops = Counter(names)
313
+ creates = sum(ops[n] for n in CREATE_INSTRUCTIONS)
314
+ repeated = {k: v for k, v in ops.items() if v >= 2}
315
+
316
+ return {
317
+ "slot": tx.get("slot"),
318
+ "block_time": tx.get("blockTime"),
319
+ "fee_payer": fee_payer(tx),
320
+ "signers": signers(tx),
321
+ "fee_lamports": meta.get("fee"),
322
+ "err": meta.get("err"),
323
+ "pump_invocations": pump_invocations(tx),
324
+ "pump_instructions": names,
325
+ "pump_ops": dict(ops),
326
+ "repeated_ops": repeated,
327
+ "creates": creates,
328
+ "mints": mints,
329
+ "creates_mints": creates >= 2,
330
+ "batches_ops": bool(repeated),
331
+ "transfers": len(system_transfers(tx)),
332
+ "equal_size_outflows": equal_size_outflows(tx),
333
+ }
334
+
335
+
336
+ def format_sol(lamports: int) -> str:
337
+ return f"{lamports / LAMPORTS_PER_SOL:.9f}".rstrip("0").rstrip(".")