@fiderail/indexer 0.0.0-stage → 2.3.2

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,485 @@
1
+ import { getChainSpec, getPrimaryAssetContract, rawAmountToDecimal, toUsdAmount, } from "@fiderail/spec";
2
+ export const SOL_USDC_MINT = getPrimaryAssetContract("solana");
3
+ export const SOL_USDT_MINT = getChainSpec("solana").assets.find((a) => a.symbol === "USDT")?.contract ||
4
+ "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
5
+ export const SOL_MEMO_PROGRAMS = new Set([
6
+ "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr",
7
+ "Memo1UhkJRfHyvLMcVucJwxXeuD728EqVDDwQDxFMNo",
8
+ ]);
9
+ export const SOL_TOKEN_PROGRAMS = new Set([
10
+ "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
11
+ "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",
12
+ ]);
13
+ export const DEFAULT_SOLANA_TARGETS = [
14
+ {
15
+ label: "PayAI (exact)",
16
+ address: "CjNFTjvBhbJJd2B5ePPMHRLx1ELZpa8dwQgGL727eKww",
17
+ channel: "solana_x402_payai",
18
+ },
19
+ {
20
+ label: "PayAI (signer)",
21
+ address: "2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4",
22
+ channel: "solana_x402_payai",
23
+ },
24
+ {
25
+ label: "Coinbase CDP (exact)",
26
+ address: "BENrLoUbndxoNMUS5JXApGMtNykLjFXXixMtpDwDR9SP",
27
+ channel: "solana_x402_cdp",
28
+ },
29
+ ];
30
+ function parsePositiveBigInt(value) {
31
+ if (typeof value === "bigint")
32
+ return value > 0n ? value : 0n;
33
+ if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) {
34
+ return BigInt(value);
35
+ }
36
+ if (typeof value === "string") {
37
+ const trimmed = value.trim();
38
+ if (/^\d+$/.test(trimmed)) {
39
+ const parsed = BigInt(trimmed);
40
+ return parsed > 0n ? parsed : 0n;
41
+ }
42
+ }
43
+ return 0n;
44
+ }
45
+ function isSplTokenInstruction(ix) {
46
+ if (!ix || typeof ix !== "object")
47
+ return false;
48
+ return (SOL_TOKEN_PROGRAMS.has(ix.programId) ||
49
+ ix.program === "spl-token" ||
50
+ ix.program === "spl-token-2022");
51
+ }
52
+ function collectSolanaInstructions(tx) {
53
+ const outer = Array.isArray(tx?.transaction?.message?.instructions)
54
+ ? tx.transaction.message.instructions
55
+ : [];
56
+ const innerGroups = Array.isArray(tx?.meta?.innerInstructions)
57
+ ? tx.meta.innerInstructions
58
+ : [];
59
+ if (innerGroups.length === 0)
60
+ return outer;
61
+ const innerByIndex = new Map();
62
+ const orphanInner = [];
63
+ for (const g of innerGroups) {
64
+ const list = Array.isArray(g?.instructions) ? g.instructions : [];
65
+ if (typeof g?.index === "number" && g.index >= 0 && g.index < outer.length) {
66
+ const existing = innerByIndex.get(g.index) || [];
67
+ existing.push(...list);
68
+ innerByIndex.set(g.index, existing);
69
+ }
70
+ else {
71
+ orphanInner.push(...list);
72
+ }
73
+ }
74
+ const ordered = [];
75
+ for (let i = 0; i < outer.length; i += 1) {
76
+ ordered.push(outer[i]);
77
+ const children = innerByIndex.get(i);
78
+ if (children)
79
+ ordered.push(...children);
80
+ }
81
+ if (orphanInner.length > 0)
82
+ ordered.push(...orphanInner);
83
+ return ordered;
84
+ }
85
+ function buildSolanaAccountKeys(tx) {
86
+ const rawKeys = Array.isArray(tx?.transaction?.message?.accountKeys)
87
+ ? tx.transaction.message.accountKeys
88
+ : [];
89
+ const keys = [];
90
+ let hasLookupTableKeys = false;
91
+ for (const entry of rawKeys) {
92
+ if (typeof entry === "string") {
93
+ keys.push(entry);
94
+ }
95
+ else if (entry && typeof entry === "object") {
96
+ const obj = entry;
97
+ if (obj.source === "lookupTable")
98
+ hasLookupTableKeys = true;
99
+ keys.push(typeof obj.pubkey === "string" ? obj.pubkey : "");
100
+ }
101
+ else {
102
+ keys.push("");
103
+ }
104
+ }
105
+ const loaded = tx?.meta?.loadedAddresses;
106
+ if (!hasLookupTableKeys && loaded && typeof loaded === "object") {
107
+ for (const k of Array.isArray(loaded.writable) ? loaded.writable : []) {
108
+ keys.push(typeof k === "string" ? k : "");
109
+ }
110
+ for (const k of Array.isArray(loaded.readonly) ? loaded.readonly : []) {
111
+ keys.push(typeof k === "string" ? k : "");
112
+ }
113
+ }
114
+ return keys;
115
+ }
116
+ function buildTokenAccountMeta(meta, accountKeys) {
117
+ const byTokenAccount = new Map();
118
+ const mintsByOwner = new Map();
119
+ const absorb = (entries) => {
120
+ if (!Array.isArray(entries))
121
+ return;
122
+ for (const b of entries) {
123
+ if (!b || typeof b !== "object")
124
+ continue;
125
+ const mint = typeof b.mint === "string" ? b.mint : "";
126
+ const owner = typeof b.owner === "string" ? b.owner : "";
127
+ if (owner && mint) {
128
+ let set = mintsByOwner.get(owner);
129
+ if (!set) {
130
+ set = new Set();
131
+ mintsByOwner.set(owner, set);
132
+ }
133
+ set.add(mint);
134
+ }
135
+ if (typeof b.accountIndex === "number" && b.accountIndex >= 0 && b.accountIndex < accountKeys.length) {
136
+ const pubkey = accountKeys[b.accountIndex];
137
+ if (!pubkey)
138
+ continue;
139
+ const prev = byTokenAccount.get(pubkey);
140
+ byTokenAccount.set(pubkey, {
141
+ owner: owner || prev?.owner || "",
142
+ mint: mint || prev?.mint || "",
143
+ });
144
+ }
145
+ }
146
+ };
147
+ absorb(meta.preTokenBalances);
148
+ absorb(meta.postTokenBalances);
149
+ return { byTokenAccount, mintsByOwner };
150
+ }
151
+ function computeAssetNetDeltas(meta, assets) {
152
+ const result = new Map();
153
+ for (const asset of assets) {
154
+ const deltas = new Map();
155
+ const addBal = (entries, sign) => {
156
+ if (!Array.isArray(entries))
157
+ return;
158
+ for (const b of entries) {
159
+ if (!b || b.mint !== asset.contract || !b.owner)
160
+ continue;
161
+ const raw = parsePositiveBigInt(b.uiTokenAmount?.amount);
162
+ deltas.set(b.owner, (deltas.get(b.owner) || 0n) + sign * raw);
163
+ }
164
+ };
165
+ addBal(meta.preTokenBalances, -1n);
166
+ addBal(meta.postTokenBalances, 1n);
167
+ result.set(asset.contract, deltas);
168
+ }
169
+ return result;
170
+ }
171
+ function isNodeInDirectedCycle(node, edges) {
172
+ const adj = new Map();
173
+ for (const e of edges) {
174
+ if (e.payer === e.payee)
175
+ continue;
176
+ let next = adj.get(e.payer);
177
+ if (!next) {
178
+ next = new Set();
179
+ adj.set(e.payer, next);
180
+ }
181
+ next.add(e.payee);
182
+ }
183
+ const startNeighbors = adj.get(node);
184
+ if (!startNeighbors || startNeighbors.size === 0)
185
+ return false;
186
+ const visited = new Set();
187
+ const queue = [...startNeighbors];
188
+ while (queue.length > 0) {
189
+ const cur = queue.shift();
190
+ if (cur === node)
191
+ return true;
192
+ if (visited.has(cur))
193
+ continue;
194
+ visited.add(cur);
195
+ const next = adj.get(cur);
196
+ if (next) {
197
+ for (const n of next) {
198
+ if (!visited.has(n))
199
+ queue.push(n);
200
+ }
201
+ }
202
+ }
203
+ return false;
204
+ }
205
+ /**
206
+ * Collapses acyclic zero-delta pass-through intermediaries (e.g. Buyer -> RouterPDA -> Merchant)
207
+ * while strictly preserving self-transfers and same-tx circular wash loops (A -> B -> A, A -> B -> C -> A).
208
+ */
209
+ function collapsePassthroughIntermediaries(transfers, netDeltas) {
210
+ if (transfers.length < 2 || !netDeltas || netDeltas.size === 0) {
211
+ return [...transfers];
212
+ }
213
+ let current = [...transfers];
214
+ for (let pass = 0; pass < transfers.length; pass += 1) {
215
+ const inByNode = new Map();
216
+ const outByNode = new Map();
217
+ for (let i = 0; i < current.length; i += 1) {
218
+ const t = current[i];
219
+ if (t.payer === t.payee)
220
+ continue;
221
+ const inList = inByNode.get(t.payee) || [];
222
+ inList.push(i);
223
+ inByNode.set(t.payee, inList);
224
+ const outList = outByNode.get(t.payer) || [];
225
+ outList.push(i);
226
+ outByNode.set(t.payer, outList);
227
+ }
228
+ let collapsed = false;
229
+ for (const [mid, inIndices] of inByNode.entries()) {
230
+ const outIndices = outByNode.get(mid);
231
+ if (!outIndices || outIndices.length === 0)
232
+ continue;
233
+ if (!netDeltas.has(mid) || (netDeltas.get(mid) ?? 0n) !== 0n)
234
+ continue;
235
+ if (isNodeInDirectedCycle(mid, current))
236
+ continue;
237
+ let sumIn = 0n;
238
+ for (const idx of inIndices)
239
+ sumIn += current[idx].amountRaw;
240
+ let sumOut = 0n;
241
+ for (const idx of outIndices)
242
+ sumOut += current[idx].amountRaw;
243
+ if (sumIn <= 0n || sumIn !== sumOut)
244
+ continue;
245
+ const replaced = [];
246
+ let ii = 0;
247
+ let oi = 0;
248
+ let inRem = current[inIndices[0]].amountRaw;
249
+ let outRem = current[outIndices[0]].amountRaw;
250
+ while (ii < inIndices.length && oi < outIndices.length) {
251
+ const take = inRem < outRem ? inRem : outRem;
252
+ if (take > 0n) {
253
+ const inEdge = current[inIndices[ii]];
254
+ const outEdge = current[outIndices[oi]];
255
+ replaced.push({
256
+ asset: inEdge.asset,
257
+ amountRaw: take,
258
+ payer: inEdge.payer,
259
+ payee: outEdge.payee,
260
+ });
261
+ }
262
+ inRem -= take;
263
+ outRem -= take;
264
+ if (inRem === 0n) {
265
+ ii += 1;
266
+ if (ii < inIndices.length)
267
+ inRem = current[inIndices[ii]].amountRaw;
268
+ }
269
+ if (outRem === 0n) {
270
+ oi += 1;
271
+ if (oi < outIndices.length)
272
+ outRem = current[outIndices[oi]].amountRaw;
273
+ }
274
+ }
275
+ const removeSet = new Set([...inIndices, ...outIndices]);
276
+ const insertPos = Math.min(...inIndices, ...outIndices);
277
+ const nextList = [];
278
+ let inserted = false;
279
+ for (let i = 0; i < current.length; i += 1) {
280
+ if (i === insertPos && !inserted) {
281
+ nextList.push(...replaced);
282
+ inserted = true;
283
+ }
284
+ if (!removeSet.has(i)) {
285
+ nextList.push(current[i]);
286
+ }
287
+ }
288
+ if (!inserted)
289
+ nextList.push(...replaced);
290
+ current = nextList;
291
+ collapsed = true;
292
+ break;
293
+ }
294
+ if (!collapsed)
295
+ break;
296
+ }
297
+ return current;
298
+ }
299
+ function compareBalanceEntries(a, b) {
300
+ if (b.amt > a.amt)
301
+ return 1;
302
+ if (b.amt < a.amt)
303
+ return -1;
304
+ return a.owner.localeCompare(b.owner);
305
+ }
306
+ function toParsedTransfer(eventIndex, asset, amountRaw, payer, payee) {
307
+ const amountDecimal = rawAmountToDecimal(amountRaw, asset.decimals);
308
+ const amountUsd = toUsdAmount(amountDecimal, asset.fiatPeg);
309
+ if (amountUsd <= 0)
310
+ return null;
311
+ return {
312
+ eventIndex,
313
+ assetContract: asset.contract,
314
+ assetSymbol: asset.symbol,
315
+ amountRaw: amountRaw.toString(),
316
+ amountDecimal,
317
+ amountUsd,
318
+ amountUsdc: amountUsd,
319
+ payer,
320
+ payee,
321
+ };
322
+ }
323
+ /**
324
+ * Parses ALL recognized Solana stablecoin transfers (USDC + USDT) from a parsed transaction.
325
+ *
326
+ * Strategy:
327
+ * 1. Instruction-level SPL Token / Token-2022 `transfer` & `transferChecked` parsing (outer + inner CPI),
328
+ * resolving token account owners via `accountKeys` + `loadedAddresses` + token balance metadata.
329
+ * Accurately preserves multi-payer `x402:batch` settlements, multi-receiver fee splits,
330
+ * and true self-transfers while collapsing acyclic zero-delta pass-through routers.
331
+ * 2. Deterministic multi-sender/multi-receiver balance-delta fallback for minimal transactions
332
+ * without parsed instruction / accountKey tables.
333
+ * 3. Strict self-transfer fallback that NEVER misclassifies non-stablecoin SPL tokens as USDC.
334
+ */
335
+ export function parseSolanaStablecoinTransfers(tx) {
336
+ const meta = tx?.meta;
337
+ if (!meta || meta.err !== null)
338
+ return [];
339
+ const solSpec = getChainSpec("solana");
340
+ const assetByMint = new Map(solSpec.assets.map((asset) => [asset.contract, asset]));
341
+ const accountKeys = buildSolanaAccountKeys(tx);
342
+ const { byTokenAccount, mintsByOwner } = buildTokenAccountMeta(meta, accountKeys);
343
+ const assetNetDeltas = computeAssetNetDeltas(meta, solSpec.assets);
344
+ const instructions = collectSolanaInstructions(tx);
345
+ // Pass 1: Instruction-level SPL stablecoin transfer parsing (handles multi-payer, multi-receiver, batch, self-transfers)
346
+ const ixByAsset = new Map();
347
+ const unresolvedAssets = new Set();
348
+ for (const ix of instructions) {
349
+ if (!isSplTokenInstruction(ix))
350
+ continue;
351
+ const t = ix.parsed?.type;
352
+ if (t !== "transfer" && t !== "transferChecked")
353
+ continue;
354
+ const info = ix.parsed?.info || {};
355
+ const raw = parsePositiveBigInt(info.tokenAmount?.amount ?? info.amount);
356
+ if (raw <= 0n)
357
+ continue;
358
+ const source = typeof info.source === "string" ? info.source : "";
359
+ const destination = typeof info.destination === "string" ? info.destination : "";
360
+ const mint = (typeof info.mint === "string" && info.mint) ||
361
+ byTokenAccount.get(source)?.mint ||
362
+ byTokenAccount.get(destination)?.mint ||
363
+ "";
364
+ const asset = assetByMint.get(mint);
365
+ if (!asset)
366
+ continue;
367
+ const srcOwner = byTokenAccount.get(source)?.owner || "";
368
+ const dstOwner = byTokenAccount.get(destination)?.owner || "";
369
+ const authority = (typeof info.authority === "string" && info.authority) ||
370
+ (typeof info.multisigAuthority === "string" && info.multisigAuthority) ||
371
+ "";
372
+ const payer = srcOwner || authority;
373
+ const payee = dstOwner || (source && source === destination ? payer : "");
374
+ if (payer && payee) {
375
+ const list = ixByAsset.get(asset.contract) || [];
376
+ list.push({ asset, amountRaw: raw, payer, payee });
377
+ ixByAsset.set(asset.contract, list);
378
+ }
379
+ else {
380
+ unresolvedAssets.add(asset.contract);
381
+ }
382
+ }
383
+ const results = [];
384
+ for (const asset of solSpec.assets) {
385
+ const netDeltas = assetNetDeltas.get(asset.contract);
386
+ const ixTransfers = ixByAsset.get(asset.contract) || [];
387
+ if (ixTransfers.length > 0 && !unresolvedAssets.has(asset.contract)) {
388
+ const resolved = collapsePassthroughIntermediaries(ixTransfers, netDeltas);
389
+ for (const item of resolved) {
390
+ const parsed = toParsedTransfer(results.length, item.asset, item.amountRaw, item.payer, item.payee);
391
+ if (parsed)
392
+ results.push(parsed);
393
+ }
394
+ continue;
395
+ }
396
+ // Pass 2: Deterministic balance-delta fallback conserving full multi-sender / multi-receiver flows
397
+ if (!netDeltas || netDeltas.size === 0)
398
+ continue;
399
+ const senders = [];
400
+ const receivers = [];
401
+ for (const [owner, delta] of netDeltas.entries()) {
402
+ if (delta < 0n)
403
+ senders.push({ owner, amt: -delta });
404
+ else if (delta > 0n)
405
+ receivers.push({ owner, amt: delta });
406
+ }
407
+ senders.sort(compareBalanceEntries);
408
+ receivers.sort(compareBalanceEntries);
409
+ let si = 0;
410
+ let ri = 0;
411
+ let sRem = senders[0]?.amt ?? 0n;
412
+ let rRem = receivers[0]?.amt ?? 0n;
413
+ while (si < senders.length && ri < receivers.length) {
414
+ const matched = sRem < rRem ? sRem : rRem;
415
+ if (matched > 0n) {
416
+ const parsed = toParsedTransfer(results.length, asset, matched, senders[si].owner, receivers[ri].owner);
417
+ if (parsed)
418
+ results.push(parsed);
419
+ }
420
+ sRem -= matched;
421
+ rRem -= matched;
422
+ if (sRem === 0n) {
423
+ si += 1;
424
+ sRem = senders[si]?.amt ?? 0n;
425
+ }
426
+ if (rRem === 0n) {
427
+ ri += 1;
428
+ rRem = receivers[ri]?.amt ?? 0n;
429
+ }
430
+ }
431
+ }
432
+ if (results.length > 0)
433
+ return results;
434
+ // Pass 3: Strict self-transfer fallback for minimal mock payloads lacking source/destination accountKeys
435
+ for (const ix of instructions) {
436
+ if (!isSplTokenInstruction(ix))
437
+ continue;
438
+ const t = ix.parsed?.type;
439
+ if (t !== "transfer" && t !== "transferChecked")
440
+ continue;
441
+ const info = ix.parsed?.info || {};
442
+ const raw = parsePositiveBigInt(info.tokenAmount?.amount ?? info.amount);
443
+ const authority = (typeof info.authority === "string" && info.authority) ||
444
+ (typeof info.multisigAuthority === "string" && info.multisigAuthority) ||
445
+ "";
446
+ if (raw <= 0n || !authority)
447
+ continue;
448
+ const source = typeof info.source === "string" ? info.source : "";
449
+ const destination = typeof info.destination === "string" ? info.destination : "";
450
+ // Never fabricate a self-transfer when distinct source & destination accounts exist without confirmed equal owners
451
+ if (source && destination && source !== destination) {
452
+ const srcOwner = byTokenAccount.get(source)?.owner || "";
453
+ const dstOwner = byTokenAccount.get(destination)?.owner || "";
454
+ if (!srcOwner || srcOwner !== dstOwner)
455
+ continue;
456
+ }
457
+ let mint = typeof info.mint === "string" ? info.mint : "";
458
+ if (!mint && t === "transfer") {
459
+ const ownerMints = mintsByOwner.get(authority);
460
+ if (ownerMints && ownerMints.size === 1) {
461
+ const onlyMint = [...ownerMints][0];
462
+ if (assetByMint.has(onlyMint))
463
+ mint = onlyMint;
464
+ }
465
+ }
466
+ const matchedAsset = assetByMint.get(mint);
467
+ if (!matchedAsset)
468
+ continue;
469
+ const parsed = toParsedTransfer(results.length, matchedAsset, raw, authority, authority);
470
+ if (parsed)
471
+ results.push(parsed);
472
+ }
473
+ return results;
474
+ }
475
+ /**
476
+ * Backward-compatible single-transfer parser (prefers USDC, falls back to USDT).
477
+ */
478
+ export function parseSolanaUsdcTransfer(tx) {
479
+ const list = parseSolanaStablecoinTransfers(tx);
480
+ return list.find((item) => item.assetSymbol === "USDC") || list[0] || null;
481
+ }
482
+ export function hasSolanaMemo(tx) {
483
+ return collectSolanaInstructions(tx || {}).some((ix) => SOL_MEMO_PROGRAMS.has(ix.programId) || ix.program === "spl-memo");
484
+ }
485
+ //# sourceMappingURL=svm-adapter.js.map
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@fiderail/indexer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.3.2",
4
+ "description": "Unified 4-chain x 2-stablecoin indexer (EVM + SVM adapters), Bazaar capability synchronizer, and SSRF-hardened L1 liveness probe / x402 endpoint grader.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "README.md",
16
+ "LICENSE",
17
+ "dist",
18
+ "!dist/**/*.map",
19
+ "!dist/**/*.tsbuildinfo"
20
+ ],
21
+ "scripts": {
22
+ "prepublishOnly": "tsc -b"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "engines": {
28
+ "node": ">=22.13.0"
29
+ },
30
+ "homepage": "https://fiderail.com",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://gitlab.com/fiderail/fiderail.git",
34
+ "directory": "packages/indexer"
35
+ },
36
+ "bugs": {
37
+ "url": "https://gitlab.com/fiderail/fiderail/-/issues"
38
+ },
39
+ "keywords": [
40
+ "fiderail",
41
+ "ai-agent",
42
+ "indexer",
43
+ "x402",
44
+ "bazaar",
45
+ "evm",
46
+ "solana",
47
+ "base",
48
+ "arbitrum",
49
+ "polygon",
50
+ "liveness-probe"
51
+ ],
52
+ "dependencies": {
53
+ "@fiderail/core": "2.3.2",
54
+ "@fiderail/db": "2.3.2",
55
+ "@fiderail/guard": "2.3.2",
56
+ "@fiderail/spec": "2.3.2"
57
+ },
58
+ "license": "MIT"
59
+ }