solana-risk-engine 0.5.2 → 0.5.4

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.
package/src/map.js CHANGED
@@ -1,250 +1,250 @@
1
- import { ADDRESS_RE, TOKEN_PROGRAM, TOKEN_2022, RUGCHECK } from "./constants.js";
2
- import { ScanError, isCancel } from "./errors.js";
3
- import { pool, progress, uniq } from "./util.js";
4
- import { holderBase, EXCHANGE_PER_HOUR, perHour, sourceRates, onlyReceives } from "./holders.js";
5
- export { EXCHANGE_PER_HOUR, perHour, sourceRates };
6
- import { accountKinds } from "./tokens.js";
7
- import { rugcheckReport } from "./rugcheck.js";
8
-
9
- /* ---------- connection map ----------
10
- Everything around a token at once: its largest holders, what kind of wallet each one is, who gave each
11
- one its first SOL (holders sharing that source are probably one owner), and the token-transfer networks
12
- RugCheck keeps (one wallet handing tokens to many). Young tokens (under 14 days) are read for the team's
13
- split; mature ones for what stayed hidden, with exchanges and pools set aside. */
14
-
15
- // Same rule as markBusy: 200 transactions within 2 days is a bot or trader, not a holder sitting on tokens
16
- export const BOT_PER_HOUR = 200 / 48;
17
- export const YOUNG_DAYS = 14;
18
- export const MAP_GROUP_YOUNG = 10, MAP_GROUP_MATURE = 15, MAP_HUB = 20, MAP_WHALE = 10;
19
- // Many holders funded by one wallet warn whatever they hold together: with only the top 20 read the share
20
- // is cut short (1/11, Leverhedge: 19 of the top 20 with 0.4% each from one source, 8.1% in view)
21
- export const MAP_SWARM = 10;
22
- export const MAP_MAX_FREE = 20, MAP_MAX_OWN = 75;
23
-
24
- const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
25
- function b58encode(bytes) {
26
- let n = 0n;
27
- for (const b of bytes) n = n * 256n + BigInt(b);
28
- let s = "";
29
- while (n > 0n) { s = B58[Number(n % 58n)] + s; n /= 58n; }
30
- for (const b of bytes) { if (b !== 0) break; s = "1" + s; }
31
- return s;
32
- }
33
- function b64bytes(s) {
34
- if (typeof atob === "function") { const t = atob(s), out = new Uint8Array(t.length); for (let i = 0; i < t.length; i++) out[i] = t.charCodeAt(i); return out; }
35
- return Uint8Array.from(Buffer.from(s, "base64"));
36
- }
37
-
38
-
39
- // person | bot | exchange | pool
40
- export function walletType(kind, rate) {
41
- if (kind === "program") return "pool";
42
- if (rate > EXCHANGE_PER_HOUR) return "exchange";
43
- if (rate > BOT_PER_HOUR || kind === "active") return "bot";
44
- return "person";
45
- }
46
-
47
- // walletType, but a busy wallet that signed none of the sampled transactions only RECEIVES (fee shares,
48
- // airdrops, dust): it is a person who gets paid, not a bot or an exchange (same rule as markBusy, 0.4.7).
49
- // Returns { type, passive }.
50
- export async function mapType(client, addr, kind, rate, sigs) {
51
- const type = walletType(kind, rate);
52
- if ((type === "bot" || type === "exchange") && kind !== "active" && sigs && sigs.length >= 2 &&
53
- await onlyReceives(client, addr, sigs)) return { type: "person", passive: true };
54
- return { type: type, passive: false };
55
- }
56
-
57
- // Every token account of the mint (own RPC only), summed by owner, largest first. Reads just the owner
58
- // and amount of each account. Returns null when the RPC refuses or the token is too big to list.
59
- export async function allHolders(client, mint, program, max) {
60
- const filters = [{ memcmp: { offset: 0, bytes: mint } }];
61
- if (program === TOKEN_PROGRAM) filters.push({ dataSize: 165 });
62
- let res;
63
- try { res = await client.rpc("getProgramAccounts", [program, { encoding: "base64", dataSlice: { offset: 32, length: 40 }, filters: filters }]); }
64
- catch (e) { if (isCancel(e)) throw e; return null; }
65
- if (!Array.isArray(res)) return null;
66
- const by = {};
67
- res.forEach(function (a) {
68
- const d = a && a.account && a.account.data;
69
- const raw = d && b64bytes(Array.isArray(d) ? d[0] : d);
70
- if (!raw || raw.length < 40) return;
71
- const owner = b58encode(raw.slice(0, 32));
72
- let amt = 0n;
73
- for (let i = 39; i >= 32; i--) amt = amt * 256n + BigInt(raw[i]);
74
- if (amt > 0n) by[owner] = (by[owner] || 0n) + amt;
75
- });
76
- return Object.keys(by).sort(function (a, b) { return by[b] > by[a] ? 1 : by[b] < by[a] ? -1 : 0; })
77
- .slice(0, max).map(function (o) { return { owner: o, raw: Number(by[o]) }; });
78
- }
79
-
80
- // Up to 3 pages of signatures: the oldest one and the newest page (for the rate). first = null when the
81
- // wallet has more than 3000 (its first transaction is too far back to find cheaply).
82
- async function history(client, addr, pages) {
83
- let before = null, first = null, top = null;
84
- for (let i = 0; i < pages; i++) {
85
- const page = await client.rpc("getSignaturesForAddress", [addr, before ? { limit: 1000, before: before } : { limit: 1000 }]);
86
- if (!page || !page.length) break;
87
- if (!top) top = page;
88
- if (page.length < 1000) { first = page[page.length - 1].signature; break; }
89
- before = page[page.length - 1].signature;
90
- }
91
- return { rate: perHour(top), n: top ? top.length : 0, first: first, top: top };
92
- }
93
- // Fee payer (account 0) of a transaction
94
- async function payerOf(client, sig) {
95
- let tx;
96
- try { tx = await client.rpc("getTransaction", [sig, { maxSupportedTransactionVersion: 1, encoding: "jsonParsed" }]); }
97
- catch (e) {
98
- if (isCancel(e) || !/version|invalid param/i.test(e.message || "")) throw e;
99
- tx = await client.rpc("getTransaction", [sig, { maxSupportedTransactionVersion: 0, encoding: "jsonParsed" }]);
100
- }
101
- const keys = tx && tx.transaction && tx.transaction.message && tx.transaction.message.accountKeys;
102
- const k = keys && keys[0];
103
- return k ? (k.pubkey !== undefined ? k.pubkey : k) : null;
104
- }
105
-
106
-
107
- // RugCheck's token-transfer networks with their links (who handed tokens to whom)
108
- export async function transferNetworks(client, mint, supply) {
109
- const g = await client.softJson(RUGCHECK + mint + "/insiders/graph", 8000);
110
- if (!Array.isArray(g)) return [];
111
- return g.map(function (n) {
112
- const nodes = (n.nodes || []).filter(function (x) { return x && ADDRESS_RE.test(x.id || ""); })
113
- .map(function (x) { return { addr: x.id, pct: supply > 0 ? Number(x.holdings || 0) / supply * 100 : 0 }; });
114
- const links = (n.links || []).filter(function (l) { return l && l.source && l.target; }).map(function (l) { return [l.source, l.target]; });
115
- return { type: n.network_type || "transfer", nodes: nodes, links: links };
116
- }).filter(function (n) { return n.nodes.length > 1; }).sort(function (a, b) { return b.nodes.length - a.nodes.length; });
117
- }
118
-
119
- // Wallet in the networks that handed tokens to the most others
120
- export function topHub(nets) {
121
- let best = null;
122
- nets.forEach(function (n) {
123
- const out = {};
124
- n.links.forEach(function (l) { out[l[0]] = (out[l[0]] || 0) + 1; });
125
- Object.keys(out).forEach(function (a) { if (!best || out[a] > best.out) best = { addr: a, out: out[a] }; });
126
- });
127
- return best;
128
- }
129
-
130
- // Groups: sources that gave the first SOL to 2+ holders and are not exchanges. In mature tokens only
131
- // people count (bots there are traders who came later, not the team's split).
132
- export function mapGroups(holders, sources, mode) {
133
- const by = {};
134
- holders.forEach(function (h) {
135
- if (!h.funder) return;
136
- if (mode === "mature" && h.type !== "person") return;
137
- const s = sources[h.funder];
138
- if (!s || s.type === "exchange") return;
139
- (by[h.funder] = by[h.funder] || []).push(h);
140
- });
141
- const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
142
- return Object.keys(by).filter(function (f) { return by[f].length >= 2; }).map(function (f) {
143
- return { funder: f, members: by[f].map(function (h) { return h.addr; }), pct: by[f].reduce(function (s, h) { return s + h.pct; }, 0), rate: sources[f].rate };
144
- }).sort(function (a, b) { return b.pct - a.pct; }).map(function (g, i) { g.id = LETTERS[i] || "G" + i; return g; });
145
- }
146
-
147
- export function mapSignals(m) {
148
- const out = [], young = m.mode === "young", big = m.groups[0];
149
- const gLimit = young ? MAP_GROUP_YOUNG : MAP_GROUP_MATURE;
150
- const grouped = big && big.pct > gLimit;
151
- if (grouped) out.push({ code: "MAP_GROUP", s: young ? "bad" : "warn", data: { n: big.members.length, pct: big.pct, funder: big.funder } });
152
- // the group with most wallets, unless it is the one MAP_GROUP already named
153
- const many = m.groups.slice().sort(function (a, b) { return b.members.length - a.members.length || b.pct - a.pct; })[0];
154
- if (many && many.members.length >= MAP_SWARM && !(grouped && many === big))
155
- out.push({ code: "MAP_SWARM", s: young ? "bad" : "warn", data: { n: many.members.length, of: (m.holders || []).length, pct: many.pct, funder: many.funder } });
156
- if (young && m.hub && m.hub.out >= MAP_HUB) out.push({ code: "MAP_HUB", s: "bad", data: { n: m.hub.out, addr: m.hub.addr } });
157
- if (!young) {
158
- const w = m.holders.filter(function (h) { return h.type === "person" && h.pct > MAP_WHALE; }).sort(function (a, b) { return b.pct - a.pct; })[0];
159
- if (w) out.push({ code: "MAP_WHALE", s: "warn", data: { pct: w.pct, addr: w.addr } });
160
- }
161
- return out;
162
- }
163
-
164
- /**
165
- * Connection map of a token.
166
- * @param [opts.createdAt] ms when its market started (DexScreener pairCreatedAt); without it RugCheck's detectedAt
167
- * @param [opts.max] holders to read (default 20, or 75 with your own RPC)
168
- * @param [opts.now]
169
- * @returns {mint, mode, ageDays, supply, holders: [{addr, pct, type, rate, funder}], sources: {addr: {rate, type, n}},
170
- * groups, nets, hub, creator, payer, signals}
171
- */
172
- export async function connectionMap(client, mint, opts) {
173
- opts = opts || {};
174
- const onProgress = opts.onProgress, now = opts.now || Date.now();
175
- if (!ADDRESS_RE.test(mint || "")) throw new ScanError("INVALID_ADDRESS", "not a Solana address");
176
- const own = client.ownRpc(), max = opts.max || (own ? MAP_MAX_OWN : MAP_MAX_FREE);
177
-
178
- // 1) holders: with your own RPC, every account of the token (up to max); otherwise the RPC's top 20
179
- const b = await holderBase(client, mint, onProgress);
180
- const supply = Number(b.info.supply) || 0;
181
- let rows = null;
182
- if (own && max > 20) {
183
- const prog = b.info.program === TOKEN_2022 ? TOKEN_2022 : TOKEN_PROGRAM;
184
- rows = await allHolders(client, mint, prog, max);
185
- }
186
- let kind = b.kind;
187
- if (rows && rows.length) {
188
- const missing = rows.map(function (r) { return r.owner; }).filter(function (o) { return !kind[o]; });
189
- if (missing.length) kind = Object.assign({}, kind, await accountKinds(client, missing, true));
190
- } else {
191
- const agg = {};
192
- b.largest.forEach(function (a, i) { const o = b.owners[i] || a.address; agg[o] = (agg[o] || 0) + Number(a.amount); });
193
- rows = Object.keys(agg).map(function (o) { return { owner: o, raw: agg[o] }; }).sort(function (x, y) { return y.raw - x.raw; });
194
- }
195
-
196
- // 2) age and mode
197
- const rc = await rugcheckReport(client, mint);
198
- const created = opts.createdAt || (rc && rc.detectedAt ? Date.parse(rc.detectedAt) : null);
199
- const ageDays = created ? (now - created) / 86400000 : null;
200
- const mode = ageDays !== null && ageDays < YOUNG_DAYS ? "young" : "mature";
201
-
202
- // 3) each holder: how busy it is and who paid its first transaction
203
- const holders = rows.map(function (r) { return { addr: r.owner, pct: supply > 0 ? r.raw / supply * 100 : 0, kind: kind[r.owner] || "program" }; });
204
- let done = 0;
205
- await pool(holders, 3, async function (h) {
206
- try {
207
- if (h.kind !== "program") {
208
- const hs = await history(client, h.addr, mode === "young" ? 3 : 1);
209
- h.rate = hs.rate;
210
- const t = await mapType(client, h.addr, h.kind, hs.rate, hs.top);
211
- h.type = t.type; if (t.passive) h.passive = true;
212
- // in mature tokens only people are traced; exchanges never (they would join strangers)
213
- let first = hs.first;
214
- if (!first && mode === "mature" && h.type === "person" && hs.n >= 1000) first = (await history(client, h.addr, 3)).first;
215
- if (first && h.type !== "exchange" && (mode === "young" || h.type === "person")) {
216
- const p = await payerOf(client, first);
217
- if (p && p !== h.addr) h.funder = p;
218
- }
219
- } else { h.type = "pool"; h.rate = 0; }
220
- } catch (e) { if (isCancel(e)) throw e; h.type = h.type || walletType(h.kind, 0); }
221
- delete h.kind;
222
- done++; progress(onProgress, "funders", 0.45 + 0.35 * done / holders.length, { done: done, total: holders.length });
223
- });
224
-
225
- // 4) the sources: exchanges or not
226
- const srcList = uniq(holders.map(function (h) { return h.funder; }).filter(Boolean));
227
- const rates = await sourceRates(client, srcList, function (c, n) { progress(onProgress, "exchangeSources", 0.8 + 0.08 * c / Math.max(1, n), { done: c, total: n }); });
228
- const sources = {};
229
- srcList.forEach(function (s) {
230
- sources[s] = { rate: rates[s] || 0, type: (rates[s] || 0) > EXCHANGE_PER_HOUR ? "exchange" : "person",
231
- n: holders.filter(function (h) { return h.funder === s; }).length };
232
- });
233
-
234
- // 5) transfer networks, creator and who paid the launch (young tokens)
235
- progress(onProgress, "networks", 0.9);
236
- const nets = await transferNetworks(client, mint, supply);
237
- let payer = null;
238
- if (mode === "young") {
239
- try { const mh = await history(client, mint, 3); if (mh.first) payer = await payerOf(client, mh.first); }
240
- catch (e) { if (isCancel(e)) throw e; }
241
- }
242
- const m = {
243
- mint: mint, mode: mode, ageDays: ageDays, supply: supply, holders: holders, sources: sources,
244
- groups: mapGroups(holders, sources, mode), nets: nets, hub: topHub(nets),
245
- creator: (rc && rc.creator) || null, payer: payer
246
- };
247
- m.signals = mapSignals(m);
248
- progress(onProgress, "done", 1);
249
- return m;
250
- }
1
+ import { ADDRESS_RE, TOKEN_PROGRAM, TOKEN_2022, RUGCHECK } from "./constants.js";
2
+ import { ScanError, isCancel } from "./errors.js";
3
+ import { pool, progress, uniq } from "./util.js";
4
+ import { holderBase, EXCHANGE_PER_HOUR, perHour, sourceRates, onlyReceives } from "./holders.js";
5
+ export { EXCHANGE_PER_HOUR, perHour, sourceRates };
6
+ import { accountKinds } from "./tokens.js";
7
+ import { rugcheckReport } from "./rugcheck.js";
8
+
9
+ /* ---------- connection map ----------
10
+ Everything around a token at once: its largest holders, what kind of wallet each one is, who gave each
11
+ one its first SOL (holders sharing that source are probably one owner), and the token-transfer networks
12
+ RugCheck keeps (one wallet handing tokens to many). Young tokens (under 14 days) are read for the team's
13
+ split; mature ones for what stayed hidden, with exchanges and pools set aside. */
14
+
15
+ // Same rule as markBusy: 200 transactions within 2 days is a bot or trader, not a holder sitting on tokens
16
+ export const BOT_PER_HOUR = 200 / 48;
17
+ export const YOUNG_DAYS = 14;
18
+ export const MAP_GROUP_YOUNG = 10, MAP_GROUP_MATURE = 15, MAP_HUB = 20, MAP_WHALE = 10;
19
+ // Many holders funded by one wallet warn whatever they hold together: with only the top 20 read the share
20
+ // is cut short (1/11, Leverhedge: 19 of the top 20 with 0.4% each from one source, 8.1% in view)
21
+ export const MAP_SWARM = 10;
22
+ export const MAP_MAX_FREE = 20, MAP_MAX_OWN = 75;
23
+
24
+ const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
25
+ function b58encode(bytes) {
26
+ let n = 0n;
27
+ for (const b of bytes) n = n * 256n + BigInt(b);
28
+ let s = "";
29
+ while (n > 0n) { s = B58[Number(n % 58n)] + s; n /= 58n; }
30
+ for (const b of bytes) { if (b !== 0) break; s = "1" + s; }
31
+ return s;
32
+ }
33
+ function b64bytes(s) {
34
+ if (typeof atob === "function") { const t = atob(s), out = new Uint8Array(t.length); for (let i = 0; i < t.length; i++) out[i] = t.charCodeAt(i); return out; }
35
+ return Uint8Array.from(Buffer.from(s, "base64"));
36
+ }
37
+
38
+
39
+ // person | bot | exchange | pool
40
+ export function walletType(kind, rate) {
41
+ if (kind === "program") return "pool";
42
+ if (rate > EXCHANGE_PER_HOUR) return "exchange";
43
+ if (rate > BOT_PER_HOUR || kind === "active") return "bot";
44
+ return "person";
45
+ }
46
+
47
+ // walletType, but a busy wallet that signed none of the sampled transactions only RECEIVES (fee shares,
48
+ // airdrops, dust): it is a person who gets paid, not a bot or an exchange (same rule as markBusy, 0.4.7).
49
+ // Returns { type, passive }.
50
+ export async function mapType(client, addr, kind, rate, sigs) {
51
+ const type = walletType(kind, rate);
52
+ if ((type === "bot" || type === "exchange") && kind !== "active" && sigs && sigs.length >= 2 &&
53
+ await onlyReceives(client, addr, sigs)) return { type: "person", passive: true };
54
+ return { type: type, passive: false };
55
+ }
56
+
57
+ // Every token account of the mint (own RPC only), summed by owner, largest first. Reads just the owner
58
+ // and amount of each account. Returns null when the RPC refuses or the token is too big to list.
59
+ export async function allHolders(client, mint, program, max) {
60
+ const filters = [{ memcmp: { offset: 0, bytes: mint } }];
61
+ if (program === TOKEN_PROGRAM) filters.push({ dataSize: 165 });
62
+ let res;
63
+ try { res = await client.rpc("getProgramAccounts", [program, { encoding: "base64", dataSlice: { offset: 32, length: 40 }, filters: filters }]); }
64
+ catch (e) { if (isCancel(e)) throw e; return null; }
65
+ if (!Array.isArray(res)) return null;
66
+ const by = {};
67
+ res.forEach(function (a) {
68
+ const d = a && a.account && a.account.data;
69
+ const raw = d && b64bytes(Array.isArray(d) ? d[0] : d);
70
+ if (!raw || raw.length < 40) return;
71
+ const owner = b58encode(raw.slice(0, 32));
72
+ let amt = 0n;
73
+ for (let i = 39; i >= 32; i--) amt = amt * 256n + BigInt(raw[i]);
74
+ if (amt > 0n) by[owner] = (by[owner] || 0n) + amt;
75
+ });
76
+ return Object.keys(by).sort(function (a, b) { return by[b] > by[a] ? 1 : by[b] < by[a] ? -1 : 0; })
77
+ .slice(0, max).map(function (o) { return { owner: o, raw: Number(by[o]) }; });
78
+ }
79
+
80
+ // Up to 3 pages of signatures: the oldest one and the newest page (for the rate). first = null when the
81
+ // wallet has more than 3000 (its first transaction is too far back to find cheaply).
82
+ async function history(client, addr, pages) {
83
+ let before = null, first = null, top = null;
84
+ for (let i = 0; i < pages; i++) {
85
+ const page = await client.rpc("getSignaturesForAddress", [addr, before ? { limit: 1000, before: before } : { limit: 1000 }]);
86
+ if (!page || !page.length) break;
87
+ if (!top) top = page;
88
+ if (page.length < 1000) { first = page[page.length - 1].signature; break; }
89
+ before = page[page.length - 1].signature;
90
+ }
91
+ return { rate: perHour(top), n: top ? top.length : 0, first: first, top: top };
92
+ }
93
+ // Fee payer (account 0) of a transaction
94
+ async function payerOf(client, sig) {
95
+ let tx;
96
+ try { tx = await client.rpc("getTransaction", [sig, { maxSupportedTransactionVersion: 1, encoding: "jsonParsed" }]); }
97
+ catch (e) {
98
+ if (isCancel(e) || !/version|invalid param/i.test(e.message || "")) throw e;
99
+ tx = await client.rpc("getTransaction", [sig, { maxSupportedTransactionVersion: 0, encoding: "jsonParsed" }]);
100
+ }
101
+ const keys = tx && tx.transaction && tx.transaction.message && tx.transaction.message.accountKeys;
102
+ const k = keys && keys[0];
103
+ return k ? (k.pubkey !== undefined ? k.pubkey : k) : null;
104
+ }
105
+
106
+
107
+ // RugCheck's token-transfer networks with their links (who handed tokens to whom)
108
+ export async function transferNetworks(client, mint, supply) {
109
+ const g = await client.softJson(RUGCHECK + mint + "/insiders/graph", 8000);
110
+ if (!Array.isArray(g)) return [];
111
+ return g.map(function (n) {
112
+ const nodes = (n.nodes || []).filter(function (x) { return x && ADDRESS_RE.test(x.id || ""); })
113
+ .map(function (x) { return { addr: x.id, pct: supply > 0 ? Number(x.holdings || 0) / supply * 100 : 0 }; });
114
+ const links = (n.links || []).filter(function (l) { return l && l.source && l.target; }).map(function (l) { return [l.source, l.target]; });
115
+ return { type: n.network_type || "transfer", nodes: nodes, links: links };
116
+ }).filter(function (n) { return n.nodes.length > 1; }).sort(function (a, b) { return b.nodes.length - a.nodes.length; });
117
+ }
118
+
119
+ // Wallet in the networks that handed tokens to the most others
120
+ export function topHub(nets) {
121
+ let best = null;
122
+ nets.forEach(function (n) {
123
+ const out = {};
124
+ n.links.forEach(function (l) { out[l[0]] = (out[l[0]] || 0) + 1; });
125
+ Object.keys(out).forEach(function (a) { if (!best || out[a] > best.out) best = { addr: a, out: out[a] }; });
126
+ });
127
+ return best;
128
+ }
129
+
130
+ // Groups: sources that gave the first SOL to 2+ holders and are not exchanges. In mature tokens only
131
+ // people count (bots there are traders who came later, not the team's split).
132
+ export function mapGroups(holders, sources, mode) {
133
+ const by = {};
134
+ holders.forEach(function (h) {
135
+ if (!h.funder) return;
136
+ if (mode === "mature" && h.type !== "person") return;
137
+ const s = sources[h.funder];
138
+ if (!s || s.type === "exchange") return;
139
+ (by[h.funder] = by[h.funder] || []).push(h);
140
+ });
141
+ const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
142
+ return Object.keys(by).filter(function (f) { return by[f].length >= 2; }).map(function (f) {
143
+ return { funder: f, members: by[f].map(function (h) { return h.addr; }), pct: by[f].reduce(function (s, h) { return s + h.pct; }, 0), rate: sources[f].rate };
144
+ }).sort(function (a, b) { return b.pct - a.pct; }).map(function (g, i) { g.id = LETTERS[i] || "G" + i; return g; });
145
+ }
146
+
147
+ export function mapSignals(m) {
148
+ const out = [], young = m.mode === "young", big = m.groups[0];
149
+ const gLimit = young ? MAP_GROUP_YOUNG : MAP_GROUP_MATURE;
150
+ const grouped = big && big.pct > gLimit;
151
+ if (grouped) out.push({ code: "MAP_GROUP", s: young ? "bad" : "warn", data: { n: big.members.length, pct: big.pct, funder: big.funder } });
152
+ // the group with most wallets, unless it is the one MAP_GROUP already named
153
+ const many = m.groups.slice().sort(function (a, b) { return b.members.length - a.members.length || b.pct - a.pct; })[0];
154
+ if (many && many.members.length >= MAP_SWARM && !(grouped && many === big))
155
+ out.push({ code: "MAP_SWARM", s: young ? "bad" : "warn", data: { n: many.members.length, of: (m.holders || []).length, pct: many.pct, funder: many.funder } });
156
+ if (young && m.hub && m.hub.out >= MAP_HUB) out.push({ code: "MAP_HUB", s: "bad", data: { n: m.hub.out, addr: m.hub.addr } });
157
+ if (!young) {
158
+ const w = m.holders.filter(function (h) { return h.type === "person" && h.pct > MAP_WHALE; }).sort(function (a, b) { return b.pct - a.pct; })[0];
159
+ if (w) out.push({ code: "MAP_WHALE", s: "warn", data: { pct: w.pct, addr: w.addr } });
160
+ }
161
+ return out;
162
+ }
163
+
164
+ /**
165
+ * Connection map of a token.
166
+ * @param [opts.createdAt] ms when its market started (DexScreener pairCreatedAt); without it RugCheck's detectedAt
167
+ * @param [opts.max] holders to read (default 20, or 75 with your own RPC)
168
+ * @param [opts.now]
169
+ * @returns {mint, mode, ageDays, supply, holders: [{addr, pct, type, rate, funder}], sources: {addr: {rate, type, n}},
170
+ * groups, nets, hub, creator, payer, signals}
171
+ */
172
+ export async function connectionMap(client, mint, opts) {
173
+ opts = opts || {};
174
+ const onProgress = opts.onProgress, now = opts.now || Date.now();
175
+ if (!ADDRESS_RE.test(mint || "")) throw new ScanError("INVALID_ADDRESS", "not a Solana address");
176
+ const own = client.ownRpc(), max = opts.max || (own ? MAP_MAX_OWN : MAP_MAX_FREE);
177
+
178
+ // 1) holders: with your own RPC, every account of the token (up to max); otherwise the RPC's top 20
179
+ const b = await holderBase(client, mint, onProgress);
180
+ const supply = Number(b.info.supply) || 0;
181
+ let rows = null;
182
+ if (own && max > 20) {
183
+ const prog = b.info.program === TOKEN_2022 ? TOKEN_2022 : TOKEN_PROGRAM;
184
+ rows = await allHolders(client, mint, prog, max);
185
+ }
186
+ let kind = b.kind;
187
+ if (rows && rows.length) {
188
+ const missing = rows.map(function (r) { return r.owner; }).filter(function (o) { return !kind[o]; });
189
+ if (missing.length) kind = Object.assign({}, kind, await accountKinds(client, missing, true));
190
+ } else {
191
+ const agg = {};
192
+ b.largest.forEach(function (a, i) { const o = b.owners[i] || a.address; agg[o] = (agg[o] || 0) + Number(a.amount); });
193
+ rows = Object.keys(agg).map(function (o) { return { owner: o, raw: agg[o] }; }).sort(function (x, y) { return y.raw - x.raw; });
194
+ }
195
+
196
+ // 2) age and mode
197
+ const rc = await rugcheckReport(client, mint);
198
+ const created = opts.createdAt || (rc && rc.detectedAt ? Date.parse(rc.detectedAt) : null);
199
+ const ageDays = created ? (now - created) / 86400000 : null;
200
+ const mode = ageDays !== null && ageDays < YOUNG_DAYS ? "young" : "mature";
201
+
202
+ // 3) each holder: how busy it is and who paid its first transaction
203
+ const holders = rows.map(function (r) { return { addr: r.owner, pct: supply > 0 ? r.raw / supply * 100 : 0, kind: kind[r.owner] || "program" }; });
204
+ let done = 0;
205
+ await pool(holders, 3, async function (h) {
206
+ try {
207
+ if (h.kind !== "program") {
208
+ const hs = await history(client, h.addr, mode === "young" ? 3 : 1);
209
+ h.rate = hs.rate;
210
+ const t = await mapType(client, h.addr, h.kind, hs.rate, hs.top);
211
+ h.type = t.type; if (t.passive) h.passive = true;
212
+ // in mature tokens only people are traced; exchanges never (they would join strangers)
213
+ let first = hs.first;
214
+ if (!first && mode === "mature" && h.type === "person" && hs.n >= 1000) first = (await history(client, h.addr, 3)).first;
215
+ if (first && h.type !== "exchange" && (mode === "young" || h.type === "person")) {
216
+ const p = await payerOf(client, first);
217
+ if (p && p !== h.addr) h.funder = p;
218
+ }
219
+ } else { h.type = "pool"; h.rate = 0; }
220
+ } catch (e) { if (isCancel(e)) throw e; h.type = h.type || walletType(h.kind, 0); }
221
+ delete h.kind;
222
+ done++; progress(onProgress, "funders", 0.45 + 0.35 * done / holders.length, { done: done, total: holders.length });
223
+ });
224
+
225
+ // 4) the sources: exchanges or not
226
+ const srcList = uniq(holders.map(function (h) { return h.funder; }).filter(Boolean));
227
+ const rates = await sourceRates(client, srcList, function (c, n) { progress(onProgress, "exchangeSources", 0.8 + 0.08 * c / Math.max(1, n), { done: c, total: n }); });
228
+ const sources = {};
229
+ srcList.forEach(function (s) {
230
+ sources[s] = { rate: rates[s] || 0, type: (rates[s] || 0) > EXCHANGE_PER_HOUR ? "exchange" : "person",
231
+ n: holders.filter(function (h) { return h.funder === s; }).length };
232
+ });
233
+
234
+ // 5) transfer networks, creator and who paid the launch (young tokens)
235
+ progress(onProgress, "networks", 0.9);
236
+ const nets = await transferNetworks(client, mint, supply);
237
+ let payer = null;
238
+ if (mode === "young") {
239
+ try { const mh = await history(client, mint, 3); if (mh.first) payer = await payerOf(client, mh.first); }
240
+ catch (e) { if (isCancel(e)) throw e; }
241
+ }
242
+ const m = {
243
+ mint: mint, mode: mode, ageDays: ageDays, supply: supply, holders: holders, sources: sources,
244
+ groups: mapGroups(holders, sources, mode), nets: nets, hub: topHub(nets),
245
+ creator: (rc && rc.creator) || null, payer: payer
246
+ };
247
+ m.signals = mapSignals(m);
248
+ progress(onProgress, "done", 1);
249
+ return m;
250
+ }