@fiderail/indexer 0.0.0-stage → 2.3.1
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/LICENSE +21 -0
- package/README.md +47 -2
- package/dist/bazaar-sync.d.ts +23 -0
- package/dist/bazaar-sync.js +151 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +30 -0
- package/dist/evm-adapter.d.ts +36 -0
- package/dist/evm-adapter.js +98 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/indexer.d.ts +112 -0
- package/dist/indexer.js +1043 -0
- package/dist/liveness-probe.d.ts +178 -0
- package/dist/liveness-probe.js +662 -0
- package/dist/svm-adapter.d.ts +41 -0
- package/dist/svm-adapter.js +485 -0
- package/package.json +57 -4
package/dist/indexer.js
ADDED
|
@@ -0,0 +1,1043 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { DEFAULT_EUR_USD_RATE, getChainSpec, } from "@fiderail/spec";
|
|
4
|
+
import { openSqliteRepository } from "@fiderail/db";
|
|
5
|
+
import { syncBazaarCapabilities } from "./bazaar-sync.js";
|
|
6
|
+
import { runLivenessProbeBatch } from "./liveness-probe.js";
|
|
7
|
+
import { BASE_CDP_FACILITATOR, BASE_PERMIT2_PROXY, ERC8004_IDENTITY, TOPIC_EIP3009_AUTH_USED, TOPIC_TRANSFER, X402_PERMIT2_EXACT_PROXY, X402_PERMIT2_PROXIES, getEvmChainAssetContracts, isPermit2ProxyReceipt, padAddressTopic, parseEvmReceiptStablecoinTransfers, unpadTopicAddress, } from "./evm-adapter.js";
|
|
8
|
+
import { DEFAULT_SOLANA_TARGETS, hasSolanaMemo, parseSolanaStablecoinTransfers, } from "./svm-adapter.js";
|
|
9
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
const DEFAULT_DB_PATH = path.resolve(__dirname, "..", "..", "..", "data", "fiderail.db");
|
|
11
|
+
const FACILITATOR_ENDPOINTS = [
|
|
12
|
+
{ name: "PayAI", url: "https://facilitator.payai.network/supported" },
|
|
13
|
+
{ name: "Dexter", url: "https://x402.dexter.cash/supported" },
|
|
14
|
+
{ name: "Daydreams", url: "https://facilitator.daydreams.systems/supported" },
|
|
15
|
+
];
|
|
16
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
17
|
+
export function createIndexer(options = {}) {
|
|
18
|
+
const zanKey = options.zanApiKey ?? process.env.ZAN_API_KEY ?? "";
|
|
19
|
+
const alchemyKey = options.alchemyApiKey ?? process.env.ALCHEMY_API_KEY ?? "";
|
|
20
|
+
const eurUsdRate = Number(options.eurUsdRate ?? process.env.EUR_USD_RATE ?? DEFAULT_EUR_USD_RATE);
|
|
21
|
+
const parseUrlList = (val) => String(val || "")
|
|
22
|
+
.split(",")
|
|
23
|
+
.map((s) => s.trim())
|
|
24
|
+
.filter(Boolean);
|
|
25
|
+
const customBaseRpcs = parseUrlList(options.baseRpcUrls ?? process.env.BASE_RPC_URLS);
|
|
26
|
+
const customBaseReceiptRpcs = parseUrlList(options.baseReceiptRpcUrls ?? process.env.BASE_RECEIPT_RPC_URLS);
|
|
27
|
+
const customSolanaRpcs = parseUrlList(options.solanaRpcUrls ?? process.env.SOLANA_RPC_URLS);
|
|
28
|
+
const customArbitrumRpcs = parseUrlList(options.arbitrumRpcUrls ?? process.env.ARBITRUM_RPC_URLS);
|
|
29
|
+
const customArbitrumReceiptRpcs = parseUrlList(options.arbitrumReceiptRpcUrls ?? process.env.ARBITRUM_RECEIPT_RPC_URLS);
|
|
30
|
+
const customPolygonRpcs = parseUrlList(options.polygonRpcUrls ?? process.env.POLYGON_RPC_URLS);
|
|
31
|
+
const customPolygonReceiptRpcs = parseUrlList(options.polygonReceiptRpcUrls ?? process.env.POLYGON_RECEIPT_RPC_URLS);
|
|
32
|
+
const isExplicitlyDisabled = (raw) => {
|
|
33
|
+
const v = String(raw || "").trim().toLowerCase();
|
|
34
|
+
return v === "off" || v === "none" || v === "disabled";
|
|
35
|
+
};
|
|
36
|
+
const arbitrumDisabled = isExplicitlyDisabled(options.arbitrumRpcUrls ?? process.env.ARBITRUM_RPC_URLS);
|
|
37
|
+
const polygonDisabled = isExplicitlyDisabled(options.polygonRpcUrls ?? process.env.POLYGON_RPC_URLS);
|
|
38
|
+
const baseRpcs = options.baseRpcs ||
|
|
39
|
+
(customBaseRpcs.length > 0
|
|
40
|
+
? customBaseRpcs
|
|
41
|
+
: [
|
|
42
|
+
zanKey ? `https://api.zan.top/node/v1/base/mainnet/${zanKey}` : "",
|
|
43
|
+
alchemyKey ? `https://base-mainnet.g.alchemy.com/v2/${alchemyKey}` : "",
|
|
44
|
+
"https://mainnet.base.org",
|
|
45
|
+
].filter(Boolean));
|
|
46
|
+
const baseReceiptRpcs = options.baseReceiptRpcs ||
|
|
47
|
+
(customBaseReceiptRpcs.length > 0
|
|
48
|
+
? customBaseReceiptRpcs
|
|
49
|
+
: customBaseRpcs.length > 0
|
|
50
|
+
? customBaseRpcs
|
|
51
|
+
: [
|
|
52
|
+
alchemyKey ? `https://base-mainnet.g.alchemy.com/v2/${alchemyKey}` : "",
|
|
53
|
+
zanKey ? `https://api.zan.top/node/v1/base/mainnet/${zanKey}` : "",
|
|
54
|
+
"https://mainnet.base.org",
|
|
55
|
+
].filter(Boolean));
|
|
56
|
+
const solanaRpcs = options.solanaRpcs ||
|
|
57
|
+
(customSolanaRpcs.length > 0
|
|
58
|
+
? customSolanaRpcs
|
|
59
|
+
: [
|
|
60
|
+
zanKey ? `https://api.zan.top/node/v1/solana/mainnet/${zanKey}` : "",
|
|
61
|
+
alchemyKey ? `https://solana-mainnet.g.alchemy.com/v2/${alchemyKey}` : "",
|
|
62
|
+
"https://api.mainnet-beta.solana.com",
|
|
63
|
+
].filter(Boolean));
|
|
64
|
+
const arbitrumRpcs = options.arbitrumRpcs !== undefined
|
|
65
|
+
? options.arbitrumRpcs
|
|
66
|
+
: arbitrumDisabled
|
|
67
|
+
? []
|
|
68
|
+
: customArbitrumRpcs.length > 0
|
|
69
|
+
? customArbitrumRpcs
|
|
70
|
+
: [
|
|
71
|
+
zanKey ? `https://api.zan.top/node/v1/arb/one/${zanKey}` : "",
|
|
72
|
+
alchemyKey ? `https://arb-mainnet.g.alchemy.com/v2/${alchemyKey}` : "",
|
|
73
|
+
"https://arb1.arbitrum.io/rpc",
|
|
74
|
+
].filter(Boolean);
|
|
75
|
+
const arbitrumReceiptRpcs = options.arbitrumReceiptRpcs !== undefined
|
|
76
|
+
? options.arbitrumReceiptRpcs
|
|
77
|
+
: customArbitrumReceiptRpcs.length > 0
|
|
78
|
+
? customArbitrumReceiptRpcs
|
|
79
|
+
: arbitrumRpcs;
|
|
80
|
+
const polygonRpcs = options.polygonRpcs !== undefined
|
|
81
|
+
? options.polygonRpcs
|
|
82
|
+
: polygonDisabled
|
|
83
|
+
? []
|
|
84
|
+
: customPolygonRpcs.length > 0
|
|
85
|
+
? customPolygonRpcs
|
|
86
|
+
: [
|
|
87
|
+
zanKey ? `https://api.zan.top/node/v1/polygon/mainnet/${zanKey}` : "",
|
|
88
|
+
alchemyKey ? `https://polygon-mainnet.g.alchemy.com/v2/${alchemyKey}` : "",
|
|
89
|
+
"https://polygon-bor-rpc.publicnode.com",
|
|
90
|
+
"https://polygon-rpc.com",
|
|
91
|
+
].filter(Boolean);
|
|
92
|
+
const polygonReceiptRpcs = options.polygonReceiptRpcs !== undefined
|
|
93
|
+
? options.polygonReceiptRpcs
|
|
94
|
+
: customPolygonReceiptRpcs.length > 0
|
|
95
|
+
? customPolygonReceiptRpcs
|
|
96
|
+
: polygonRpcs;
|
|
97
|
+
const ownRepo = !options.repo;
|
|
98
|
+
const repo = options.repo ||
|
|
99
|
+
openSqliteRepository(options.dbPath || process.env.FIDERAIL_DB_PATH || DEFAULT_DB_PATH);
|
|
100
|
+
const fetchImpl = options.fetchImpl || globalThis.fetch;
|
|
101
|
+
const logger = options.logger || console;
|
|
102
|
+
const basePollIntervalMs = Math.max(1000, Number(options.basePollIntervalMs ?? process.env.BASE_POLL_INTERVAL_MS ?? 30000));
|
|
103
|
+
const solanaPollIntervalMs = Math.max(1000, Number(options.solanaPollIntervalMs ?? process.env.SOLANA_POLL_INTERVAL_MS ?? 60000));
|
|
104
|
+
const allowlistedEvmPollIntervalMs = Math.max(5000, Number(options.allowlistedEvmPollIntervalMs ?? process.env.ALLOWLISTED_EVM_POLL_INTERVAL_MS ?? 90000));
|
|
105
|
+
const recomputeIntervalMs = Math.max(0, Number(options.recomputeIntervalMs ?? process.env.RECOMPUTE_INTERVAL_MS ?? 180000));
|
|
106
|
+
const bazaarSyncIntervalMs = Math.max(60000, Number(options.bazaarSyncIntervalMs ?? process.env.BAZAAR_SYNC_INTERVAL_MS ?? 1200000));
|
|
107
|
+
const livenessProbeIntervalMs = Math.max(60000, Number(options.livenessProbeIntervalMs ?? process.env.LIVENESS_PROBE_INTERVAL_MS ?? 600000));
|
|
108
|
+
const livenessProbeBatchSize = Math.max(1, Math.min(100, Number(options.livenessProbeBatchSize ?? process.env.LIVENESS_PROBE_BATCH_SIZE ?? 30)));
|
|
109
|
+
const skipBazaarSync = Boolean(options.skipBazaarSync);
|
|
110
|
+
const skipLivenessProbe = Boolean(options.skipLivenessProbe);
|
|
111
|
+
const baseBackfillBlocks = Math.max(10, Number(options.baseBackfillBlocks ?? process.env.BASE_BACKFILL_BLOCKS ?? 1200));
|
|
112
|
+
const baseMaxBlocksPerTick = Math.max(50, Number(options.baseMaxBlocksPerTick ?? process.env.BASE_MAX_BLOCKS_PER_TICK ?? 2000));
|
|
113
|
+
const baseMaxReceiptsPerTick = Math.max(1, Number(options.baseMaxReceiptsPerTick ?? process.env.BASE_MAX_RECEIPTS_PER_TICK ?? 80));
|
|
114
|
+
const solanaMaxTxsPerTick = Math.max(1, Number(options.solanaMaxTxsPerTick ?? process.env.SOLANA_MAX_TXS_PER_TICK ?? 40));
|
|
115
|
+
const solanaMaxCatchupPages = Math.max(0, Number(options.solanaMaxCatchupPages ?? process.env.SOLANA_MAX_CATCHUP_PAGES ?? 10));
|
|
116
|
+
const retentionDays = Math.max(1, Number(options.retentionDays ?? process.env.PAYMENT_RETENTION_DAYS ?? 60));
|
|
117
|
+
const rpcPaceMs = Number(options.rpcPaceMs ?? process.env.RPC_PACE_MS ?? 350);
|
|
118
|
+
const probeProxyUrl = options.probeProxyUrl ?? process.env.FIDERAIL_PROBE_PROXY_URL ?? "";
|
|
119
|
+
const probeProxyToken = options.probeProxyToken ?? process.env.FIDERAIL_PROBE_PROXY_TOKEN ?? "";
|
|
120
|
+
const solanaTargets = options.solanaTargets || DEFAULT_SOLANA_TARGETS;
|
|
121
|
+
let cachedFacilitators = null;
|
|
122
|
+
let facilitatorsFetchedAt = 0;
|
|
123
|
+
const lastRecomputeAt = {
|
|
124
|
+
base: 0,
|
|
125
|
+
solana: 0,
|
|
126
|
+
arbitrum: 0,
|
|
127
|
+
polygon: 0,
|
|
128
|
+
};
|
|
129
|
+
async function maybeRecomputeProfiles(chain, force = false) {
|
|
130
|
+
const now = Date.now();
|
|
131
|
+
const existingCount = (await repo.getStats()).profiles[chain] || 0;
|
|
132
|
+
if (force ||
|
|
133
|
+
existingCount === 0 ||
|
|
134
|
+
recomputeIntervalMs === 0 ||
|
|
135
|
+
now - lastRecomputeAt[chain] >= recomputeIntervalMs) {
|
|
136
|
+
const { profileCount } = await repo.recomputeProfiles(chain);
|
|
137
|
+
lastRecomputeAt[chain] = now;
|
|
138
|
+
return { profileCount, recomputed: true };
|
|
139
|
+
}
|
|
140
|
+
return { profileCount: existingCount, recomputed: false };
|
|
141
|
+
}
|
|
142
|
+
function redactSecrets(text) {
|
|
143
|
+
let s = String(text ?? "");
|
|
144
|
+
if (zanKey)
|
|
145
|
+
s = s.split(zanKey).join("<REDACTED>");
|
|
146
|
+
if (alchemyKey)
|
|
147
|
+
s = s.split(alchemyKey).join("<REDACTED>");
|
|
148
|
+
for (const url of [
|
|
149
|
+
...customBaseRpcs,
|
|
150
|
+
...customBaseReceiptRpcs,
|
|
151
|
+
...customSolanaRpcs,
|
|
152
|
+
...customArbitrumRpcs,
|
|
153
|
+
...customArbitrumReceiptRpcs,
|
|
154
|
+
...customPolygonRpcs,
|
|
155
|
+
...customPolygonReceiptRpcs,
|
|
156
|
+
]) {
|
|
157
|
+
s = s.split(url).join("<REDACTED_RPC_URL>");
|
|
158
|
+
}
|
|
159
|
+
return s;
|
|
160
|
+
}
|
|
161
|
+
const hostNextSlotMs = new Map();
|
|
162
|
+
async function paceRpcHost(url, isBatch) {
|
|
163
|
+
if (rpcPaceMs <= 0)
|
|
164
|
+
return;
|
|
165
|
+
let host = url;
|
|
166
|
+
try {
|
|
167
|
+
host = new URL(url).host.toLowerCase();
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
host = url;
|
|
171
|
+
}
|
|
172
|
+
const gap = isBatch ? Math.min(2000, rpcPaceMs * 2) : rpcPaceMs;
|
|
173
|
+
const now = Date.now();
|
|
174
|
+
const prev = hostNextSlotMs.get(host) ?? 0;
|
|
175
|
+
const slot = Math.max(now, prev);
|
|
176
|
+
hostNextSlotMs.set(host, slot + gap);
|
|
177
|
+
const waitMs = slot - now;
|
|
178
|
+
if (waitMs > 0) {
|
|
179
|
+
await sleep(waitMs);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
async function rpcRequestSingle(url, payload, attempt = 0) {
|
|
183
|
+
if (options.rpcHandler) {
|
|
184
|
+
return options.rpcHandler(url, payload);
|
|
185
|
+
}
|
|
186
|
+
await paceRpcHost(url, Array.isArray(payload) && payload.length > 1);
|
|
187
|
+
try {
|
|
188
|
+
const res = await fetchImpl(url, {
|
|
189
|
+
method: "POST",
|
|
190
|
+
headers: { "Content-Type": "application/json" },
|
|
191
|
+
body: JSON.stringify(payload),
|
|
192
|
+
signal: AbortSignal.timeout(15000),
|
|
193
|
+
});
|
|
194
|
+
if (!res.ok) {
|
|
195
|
+
const txt = await res.text().catch(() => "");
|
|
196
|
+
const retryable = res.status === 429 || res.status >= 500;
|
|
197
|
+
throw Object.assign(new Error(`HTTP ${res.status}: ${redactSecrets(txt.slice(0, 140))}`), { retryable });
|
|
198
|
+
}
|
|
199
|
+
const json = await res.json();
|
|
200
|
+
if (Array.isArray(json)) {
|
|
201
|
+
const rl = json.find((x) => x.error &&
|
|
202
|
+
(x.error.code === 429 || /rate|limit|busy|timeout/i.test(x.error.message || "")));
|
|
203
|
+
if (rl) {
|
|
204
|
+
throw Object.assign(new Error(`Batch RPC err: ${redactSecrets(rl.error.message)}`), {
|
|
205
|
+
retryable: true,
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
else if (json.error) {
|
|
210
|
+
const retryable = json.error.code === 429 || /rate|limit|busy|timeout/i.test(json.error.message || "");
|
|
211
|
+
throw Object.assign(new Error(`RPC err (${json.error.code}): ${redactSecrets(json.error.message)}`), { retryable });
|
|
212
|
+
}
|
|
213
|
+
return json;
|
|
214
|
+
}
|
|
215
|
+
catch (err) {
|
|
216
|
+
const wrapped = new Error(redactSecrets(err.message));
|
|
217
|
+
wrapped.retryable = err.retryable;
|
|
218
|
+
if (attempt < 3 && err.retryable !== false) {
|
|
219
|
+
const wait = 500 * Math.pow(2, attempt);
|
|
220
|
+
await sleep(wait);
|
|
221
|
+
return rpcRequestSingle(url, payload, attempt + 1);
|
|
222
|
+
}
|
|
223
|
+
throw wrapped;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
async function rpcCallWithFailover(urls, method, params) {
|
|
227
|
+
let lastErr = null;
|
|
228
|
+
for (const url of urls) {
|
|
229
|
+
try {
|
|
230
|
+
const res = await rpcRequestSingle(url, { jsonrpc: "2.0", id: 1, method, params });
|
|
231
|
+
return res.result;
|
|
232
|
+
}
|
|
233
|
+
catch (err) {
|
|
234
|
+
lastErr = err;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
throw lastErr || new Error(`All RPC endpoints failed for ${method}`);
|
|
238
|
+
}
|
|
239
|
+
async function rpcBatchWithFailover(urls, batchPayload) {
|
|
240
|
+
let lastErr = null;
|
|
241
|
+
for (const url of urls) {
|
|
242
|
+
try {
|
|
243
|
+
return await rpcRequestSingle(url, batchPayload);
|
|
244
|
+
}
|
|
245
|
+
catch (err) {
|
|
246
|
+
lastErr = err;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
throw lastErr || new Error("All RPC endpoints failed for batch");
|
|
250
|
+
}
|
|
251
|
+
async function getKnownEvmFacilitators() {
|
|
252
|
+
const now = Date.now();
|
|
253
|
+
if (cachedFacilitators && now - facilitatorsFetchedAt < 6 * 3600 * 1000) {
|
|
254
|
+
return cachedFacilitators;
|
|
255
|
+
}
|
|
256
|
+
const map = new Map([
|
|
257
|
+
[BASE_CDP_FACILITATOR, "Coinbase-CDP"],
|
|
258
|
+
[BASE_PERMIT2_PROXY, "x402-Permit2-Proxy"],
|
|
259
|
+
[X402_PERMIT2_EXACT_PROXY, "x402-Permit2-Exact-Proxy"],
|
|
260
|
+
]);
|
|
261
|
+
if (!options.skipFacilitatorDiscovery) {
|
|
262
|
+
for (const ep of FACILITATOR_ENDPOINTS) {
|
|
263
|
+
try {
|
|
264
|
+
const res = await fetchImpl(ep.url, { signal: AbortSignal.timeout(5000) });
|
|
265
|
+
if (!res.ok)
|
|
266
|
+
continue;
|
|
267
|
+
const data = await res.json();
|
|
268
|
+
const signerBuckets = data.signers && typeof data.signers === "object" ? data.signers : {};
|
|
269
|
+
for (const [ns, list] of Object.entries(signerBuckets)) {
|
|
270
|
+
if (!ns.startsWith("eip155:") || !Array.isArray(list))
|
|
271
|
+
continue;
|
|
272
|
+
for (const addr of list) {
|
|
273
|
+
if (typeof addr === "string" && /^0x[0-9a-fA-F]{40}$/.test(addr)) {
|
|
274
|
+
map.set(addr.toLowerCase(), ep.name);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
for (const k of data.kinds || []) {
|
|
279
|
+
if (k.extra?.facilitatorAddress && /^0x[0-9a-fA-F]{40}$/.test(String(k.extra.facilitatorAddress))) {
|
|
280
|
+
map.set(String(k.extra.facilitatorAddress).toLowerCase(), ep.name);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
// ignore facilitator discovery failure
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
cachedFacilitators = map;
|
|
290
|
+
facilitatorsFetchedAt = now;
|
|
291
|
+
return map;
|
|
292
|
+
}
|
|
293
|
+
async function fetchEvmLogsRange(rpcs, filterBase, fromBlock, toBlock) {
|
|
294
|
+
const allLogs = [];
|
|
295
|
+
for (let cursor = fromBlock; cursor <= toBlock; cursor += 1000) {
|
|
296
|
+
const end = Math.min(toBlock, cursor + 999);
|
|
297
|
+
const logs = await rpcCallWithFailover(rpcs, "eth_getLogs", [
|
|
298
|
+
{
|
|
299
|
+
...filterBase,
|
|
300
|
+
fromBlock: "0x" + cursor.toString(16),
|
|
301
|
+
toBlock: "0x" + end.toString(16),
|
|
302
|
+
},
|
|
303
|
+
]);
|
|
304
|
+
if (Array.isArray(logs))
|
|
305
|
+
allLogs.push(...logs);
|
|
306
|
+
if (end < toBlock && rpcPaceMs > 0)
|
|
307
|
+
await sleep(rpcPaceMs);
|
|
308
|
+
}
|
|
309
|
+
return allLogs;
|
|
310
|
+
}
|
|
311
|
+
async function fetchEvmReceipts(rpcs, txHashes) {
|
|
312
|
+
const map = new Map();
|
|
313
|
+
const batchSize = 5;
|
|
314
|
+
for (let i = 0; i < txHashes.length; i += batchSize) {
|
|
315
|
+
const slice = txHashes.slice(i, i + batchSize);
|
|
316
|
+
const batch = slice.map((h, idx) => ({
|
|
317
|
+
jsonrpc: "2.0",
|
|
318
|
+
id: idx + 1,
|
|
319
|
+
method: "eth_getTransactionReceipt",
|
|
320
|
+
params: [h],
|
|
321
|
+
}));
|
|
322
|
+
const res = await rpcBatchWithFailover(rpcs, batch);
|
|
323
|
+
if (Array.isArray(res)) {
|
|
324
|
+
for (const item of res) {
|
|
325
|
+
if (item?.result)
|
|
326
|
+
map.set(slice[item.id - 1], item.result);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (i + batchSize < txHashes.length && rpcPaceMs > 0)
|
|
330
|
+
await sleep(rpcPaceMs);
|
|
331
|
+
}
|
|
332
|
+
return map;
|
|
333
|
+
}
|
|
334
|
+
async function syncBaseOnce({ forceRecompute = false } = {}) {
|
|
335
|
+
const state = await repo.getState();
|
|
336
|
+
const latestHex = await rpcCallWithFailover(baseRpcs, "eth_blockNumber", []);
|
|
337
|
+
const latestBlock = parseInt(latestHex, 16);
|
|
338
|
+
const latestBlkObj = await rpcCallWithFailover(baseRpcs, "eth_getBlockByNumber", [
|
|
339
|
+
latestHex,
|
|
340
|
+
false,
|
|
341
|
+
]);
|
|
342
|
+
const latestTs = parseInt(latestBlkObj?.timestamp || "0x0", 16) || Math.floor(Date.now() / 1000);
|
|
343
|
+
const prevLast = state.base_last_block !== undefined ? Number(state.base_last_block) : null;
|
|
344
|
+
const fromBlock = prevLast !== null && Number.isFinite(prevLast)
|
|
345
|
+
? prevLast + 1
|
|
346
|
+
: Math.max(0, latestBlock - baseBackfillBlocks + 1);
|
|
347
|
+
const toBlock = Math.min(latestBlock, fromBlock + baseMaxBlocksPerTick - 1);
|
|
348
|
+
await repo.setState("base_latest_chain_block", String(latestBlock));
|
|
349
|
+
if (fromBlock > toBlock) {
|
|
350
|
+
await repo.setState("base_last_sync_at", new Date().toISOString());
|
|
351
|
+
await repo.setState("base_last_error", "");
|
|
352
|
+
return {
|
|
353
|
+
chain: "base",
|
|
354
|
+
fromBlock,
|
|
355
|
+
toBlock,
|
|
356
|
+
latestBlock,
|
|
357
|
+
inserted: 0,
|
|
358
|
+
identitiesUpserted: 0,
|
|
359
|
+
profiles: (await repo.getStats()).profiles.base,
|
|
360
|
+
recomputed: false,
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
let secPerBlock = 0.2;
|
|
364
|
+
const refSpan = Math.min(5000, toBlock);
|
|
365
|
+
if (refSpan >= 100) {
|
|
366
|
+
try {
|
|
367
|
+
const refHex = "0x" + (latestBlock - refSpan).toString(16);
|
|
368
|
+
const refBlk = await rpcCallWithFailover(baseRpcs, "eth_getBlockByNumber", [refHex, false]);
|
|
369
|
+
const refTs = parseInt(refBlk?.timestamp || "0x0", 16);
|
|
370
|
+
if (refTs > 0 && latestTs > refTs) {
|
|
371
|
+
const calc = (latestTs - refTs) / refSpan;
|
|
372
|
+
if (calc >= 0.15 && calc <= 5.0)
|
|
373
|
+
secPerBlock = calc;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
catch {
|
|
377
|
+
// keep default 0.2s
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
const knownFacilitators = await getKnownEvmFacilitators();
|
|
381
|
+
const baseAssetContracts = getEvmChainAssetContracts("base");
|
|
382
|
+
const permit2Logs = await fetchEvmLogsRange(baseRpcs, { address: BASE_PERMIT2_PROXY }, fromBlock, toBlock);
|
|
383
|
+
if (rpcPaceMs > 0)
|
|
384
|
+
await sleep(rpcPaceMs);
|
|
385
|
+
// Scan EIP-3009 AuthorizationUsed across BOTH Base USDC and Base EURC
|
|
386
|
+
const authLogs = await fetchEvmLogsRange(baseRpcs, { address: baseAssetContracts, topics: [TOPIC_EIP3009_AUTH_USED] }, fromBlock, toBlock);
|
|
387
|
+
if (rpcPaceMs > 0)
|
|
388
|
+
await sleep(rpcPaceMs);
|
|
389
|
+
const idLogs = await fetchEvmLogsRange(baseRpcs, { address: ERC8004_IDENTITY, topics: [TOPIC_TRANSFER] }, fromBlock, toBlock);
|
|
390
|
+
const permit2Hashes = [...new Set(permit2Logs.map((l) => l.transactionHash).filter(Boolean))];
|
|
391
|
+
const permit2Set = new Set(permit2Hashes);
|
|
392
|
+
const authHashes = [
|
|
393
|
+
...new Set(authLogs.map((l) => l.transactionHash).filter((h) => h && !permit2Set.has(h))),
|
|
394
|
+
];
|
|
395
|
+
const prioritized = [
|
|
396
|
+
...permit2Hashes.slice(0, baseMaxReceiptsPerTick),
|
|
397
|
+
...authHashes.slice(-Math.max(0, baseMaxReceiptsPerTick - permit2Hashes.length)),
|
|
398
|
+
].slice(0, baseMaxReceiptsPerTick);
|
|
399
|
+
const receipts = prioritized.length > 0 ? await fetchEvmReceipts(baseReceiptRpcs, prioritized) : new Map();
|
|
400
|
+
const paymentRows = [];
|
|
401
|
+
for (const h of prioritized) {
|
|
402
|
+
const rcpt = receipts.get(h);
|
|
403
|
+
if (!rcpt || rcpt.status !== "0x1")
|
|
404
|
+
continue;
|
|
405
|
+
const transfers = parseEvmReceiptStablecoinTransfers("base", rcpt, eurUsdRate);
|
|
406
|
+
if (transfers.length === 0)
|
|
407
|
+
continue;
|
|
408
|
+
const relayer = (rcpt.from || "").toLowerCase();
|
|
409
|
+
const isPermit2Tx = permit2Set.has(h) || (rcpt.to || "").toLowerCase() === BASE_PERMIT2_PROXY;
|
|
410
|
+
const facilitatorName = knownFacilitators.get(relayer) || (isPermit2Tx ? "Permit2-Proxy" : "EIP3009-Relayer");
|
|
411
|
+
const blkNum = parseInt(rcpt.blockNumber, 16);
|
|
412
|
+
const estBlockTime = Math.round(latestTs - Math.max(0, latestBlock - blkNum) * secPerBlock);
|
|
413
|
+
for (const tr of transfers) {
|
|
414
|
+
paymentRows.push({
|
|
415
|
+
chain: "base",
|
|
416
|
+
txId: h,
|
|
417
|
+
eventIndex: tr.eventIndex,
|
|
418
|
+
assetContract: tr.assetContract,
|
|
419
|
+
assetSymbol: tr.assetSymbol,
|
|
420
|
+
amountRaw: tr.amountRaw,
|
|
421
|
+
amountUsd: tr.amountUsd,
|
|
422
|
+
amountUsdc: tr.amountUsd,
|
|
423
|
+
blockNumber: blkNum,
|
|
424
|
+
blockTime: estBlockTime,
|
|
425
|
+
confirmationStatus: "CONFIRMED",
|
|
426
|
+
channel: knownFacilitators.has(relayer) || isPermit2Tx ? "base_x402_permit2" : "base_eip3009",
|
|
427
|
+
facilitator: facilitatorName,
|
|
428
|
+
relayer,
|
|
429
|
+
payer: tr.payer,
|
|
430
|
+
payee: tr.payee,
|
|
431
|
+
hasMemo: false,
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
const identityRows = [];
|
|
436
|
+
for (const l of idLogs) {
|
|
437
|
+
if (unpadTopicAddress(l.topics?.[1]) !== "0x0000000000000000000000000000000000000000") {
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
const owner = unpadTopicAddress(l.topics?.[2]);
|
|
441
|
+
if (!owner)
|
|
442
|
+
continue;
|
|
443
|
+
const blkNum = parseInt(l.blockNumber || "0x0", 16) || null;
|
|
444
|
+
const estTime = blkNum !== null
|
|
445
|
+
? Math.round(latestTs - Math.max(0, latestBlock - blkNum) * secPerBlock)
|
|
446
|
+
: null;
|
|
447
|
+
let tokenId = null;
|
|
448
|
+
try {
|
|
449
|
+
if (l.topics?.[3])
|
|
450
|
+
tokenId = Number(BigInt(l.topics[3]));
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
tokenId = null;
|
|
454
|
+
}
|
|
455
|
+
identityRows.push({
|
|
456
|
+
chain: "base",
|
|
457
|
+
ownerAddress: owner,
|
|
458
|
+
tokenId,
|
|
459
|
+
blockNumber: blkNum,
|
|
460
|
+
blockTime: estTime,
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
const { inserted } = await repo.insertPayments(paymentRows);
|
|
464
|
+
await repo.upsertErc8004Owners(identityRows);
|
|
465
|
+
const { profileCount, recomputed } = await maybeRecomputeProfiles("base", forceRecompute);
|
|
466
|
+
await repo.setState("base_last_block", String(toBlock));
|
|
467
|
+
await repo.setState("base_last_sync_at", new Date().toISOString());
|
|
468
|
+
await repo.setState("base_last_inserted", String(inserted));
|
|
469
|
+
await repo.setState("base_last_error", "");
|
|
470
|
+
return {
|
|
471
|
+
chain: "base",
|
|
472
|
+
fromBlock,
|
|
473
|
+
toBlock,
|
|
474
|
+
latestBlock,
|
|
475
|
+
inserted,
|
|
476
|
+
identitiesUpserted: identityRows.length,
|
|
477
|
+
profiles: profileCount,
|
|
478
|
+
recomputed,
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Unified allowlisted EVM adapter for Arbitrum (USDC + USDT0) and Polygon (USDC + USDT).
|
|
483
|
+
* Combines 3 noise-shielded channels:
|
|
484
|
+
* 1. x402 Permit2 Proxies (captures USDC, USDT0, and non-EIP-3009 Polygon USDT with zero DeFi noise)
|
|
485
|
+
* 2. Bazaar-allowlisted payee Transfer logs (captures all stablecoin transfers to registered Agent payees)
|
|
486
|
+
* 3. Facilitator-filtered EIP-3009 AuthorizationUsed logs (resilient against Polymarket log spikes)
|
|
487
|
+
* Strictly filters receipts to Permit2 Proxy OR known x402 facilitators OR Bazaar-registered service payees
|
|
488
|
+
* so non-Agent DeFi/Polymarket noise never pollutes FideRail credit graphs.
|
|
489
|
+
*/
|
|
490
|
+
async function syncAllowlistedEvmOnce(chain, { forceRecompute = false } = {}) {
|
|
491
|
+
const rpcs = chain === "arbitrum" ? arbitrumRpcs : polygonRpcs;
|
|
492
|
+
const receiptRpcs = chain === "arbitrum" ? arbitrumReceiptRpcs : polygonReceiptRpcs;
|
|
493
|
+
if (!rpcs || rpcs.length === 0) {
|
|
494
|
+
return {
|
|
495
|
+
chain,
|
|
496
|
+
skipped: true,
|
|
497
|
+
reason: "No RPC endpoints configured",
|
|
498
|
+
inserted: 0,
|
|
499
|
+
profiles: (await repo.getStats()).profiles[chain],
|
|
500
|
+
recomputed: false,
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
const state = await repo.getState();
|
|
504
|
+
const latestHex = await rpcCallWithFailover(rpcs, "eth_blockNumber", []);
|
|
505
|
+
const latestBlock = parseInt(latestHex, 16);
|
|
506
|
+
const latestBlkObj = await rpcCallWithFailover(rpcs, "eth_getBlockByNumber", [
|
|
507
|
+
latestHex,
|
|
508
|
+
false,
|
|
509
|
+
]);
|
|
510
|
+
const latestTs = parseInt(latestBlkObj?.timestamp || "0x0", 16) || Math.floor(Date.now() / 1000);
|
|
511
|
+
const prevLast = state[`${chain}_last_block`] !== undefined ? Number(state[`${chain}_last_block`]) : null;
|
|
512
|
+
const fromBlock = prevLast !== null && Number.isFinite(prevLast)
|
|
513
|
+
? prevLast + 1
|
|
514
|
+
: Math.max(0, latestBlock - baseBackfillBlocks + 1);
|
|
515
|
+
const toBlock = Math.min(latestBlock, fromBlock + baseMaxBlocksPerTick - 1);
|
|
516
|
+
await repo.setState(`${chain}_latest_chain_block`, String(latestBlock));
|
|
517
|
+
if (fromBlock > toBlock) {
|
|
518
|
+
await repo.setState(`${chain}_last_sync_at`, new Date().toISOString());
|
|
519
|
+
await repo.setState(`${chain}_last_error`, "");
|
|
520
|
+
return {
|
|
521
|
+
chain,
|
|
522
|
+
skipped: false,
|
|
523
|
+
fromBlock,
|
|
524
|
+
toBlock,
|
|
525
|
+
latestBlock,
|
|
526
|
+
inserted: 0,
|
|
527
|
+
profiles: (await repo.getStats()).profiles[chain],
|
|
528
|
+
recomputed: false,
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
const [knownFacilitators, bazaarCaps] = await Promise.all([
|
|
532
|
+
getKnownEvmFacilitators(),
|
|
533
|
+
repo.searchCapabilities({ chain, limit: 500 }),
|
|
534
|
+
]);
|
|
535
|
+
const allowlistedPayees = new Set(bazaarCaps.map((c) => c.address.toLowerCase()));
|
|
536
|
+
const assetContracts = getEvmChainAssetContracts(chain);
|
|
537
|
+
// Channel 1: x402 Permit2 Proxies (works across USDC, USDT0, and non-EIP-3009 Polygon USDT)
|
|
538
|
+
const permit2Logs = await fetchEvmLogsRange(rpcs, { address: [...X402_PERMIT2_PROXIES] }, fromBlock, toBlock);
|
|
539
|
+
if (rpcPaceMs > 0)
|
|
540
|
+
await sleep(rpcPaceMs);
|
|
541
|
+
// Channel 2: Direct ERC-20 Transfer logs specifically targeting Bazaar-allowlisted agent payees
|
|
542
|
+
const bazaarTransferLogs = [];
|
|
543
|
+
if (allowlistedPayees.size > 0) {
|
|
544
|
+
const payeeTopics = [...allowlistedPayees].map(padAddressTopic);
|
|
545
|
+
for (let i = 0; i < payeeTopics.length; i += 50) {
|
|
546
|
+
const chunk = payeeTopics.slice(i, i + 50);
|
|
547
|
+
const logs = await fetchEvmLogsRange(rpcs, { address: assetContracts, topics: [TOPIC_TRANSFER, null, chunk] }, fromBlock, toBlock);
|
|
548
|
+
bazaarTransferLogs.push(...logs);
|
|
549
|
+
if (i + 50 < payeeTopics.length && rpcPaceMs > 0)
|
|
550
|
+
await sleep(rpcPaceMs);
|
|
551
|
+
}
|
|
552
|
+
if (rpcPaceMs > 0)
|
|
553
|
+
await sleep(rpcPaceMs);
|
|
554
|
+
}
|
|
555
|
+
// Channel 3: EIP-3009 AuthorizationUsed (non-fatal if Polymarket floods Polygon >10k logs/range)
|
|
556
|
+
let authLogs = [];
|
|
557
|
+
try {
|
|
558
|
+
authLogs = await fetchEvmLogsRange(rpcs, { address: assetContracts, topics: [TOPIC_EIP3009_AUTH_USED] }, fromBlock, toBlock);
|
|
559
|
+
}
|
|
560
|
+
catch {
|
|
561
|
+
// Channels 1 (Permit2 Proxy) + 2 (Bazaar Transfer allowlist) already succeeded without DeFi noise
|
|
562
|
+
authLogs = [];
|
|
563
|
+
}
|
|
564
|
+
const permit2Hashes = [...new Set(permit2Logs.map((l) => l.transactionHash).filter(Boolean))];
|
|
565
|
+
const seen = new Set(permit2Hashes);
|
|
566
|
+
const bazaarHashes = [
|
|
567
|
+
...new Set(bazaarTransferLogs.map((l) => l.transactionHash).filter((h) => h && !seen.has(h))),
|
|
568
|
+
];
|
|
569
|
+
for (const h of bazaarHashes)
|
|
570
|
+
seen.add(h);
|
|
571
|
+
const rawAuthHashes = [
|
|
572
|
+
...new Set(authLogs.map((l) => l.transactionHash).filter((h) => h && !seen.has(h))),
|
|
573
|
+
];
|
|
574
|
+
// Protect Polygon receipt RPC budget when Polymarket floods EIP-3009 logs
|
|
575
|
+
const authBudget = chain === "polygon" && rawAuthHashes.length > 200
|
|
576
|
+
? Math.min(20, baseMaxReceiptsPerTick)
|
|
577
|
+
: baseMaxReceiptsPerTick;
|
|
578
|
+
const authHashes = rawAuthHashes.slice(-authBudget);
|
|
579
|
+
const txHashes = [...permit2Hashes, ...bazaarHashes, ...authHashes].slice(0, baseMaxReceiptsPerTick);
|
|
580
|
+
const receipts = txHashes.length > 0 ? await fetchEvmReceipts(receiptRpcs, txHashes) : new Map();
|
|
581
|
+
const paymentRows = [];
|
|
582
|
+
const defaultSecPerBlock = chain === "arbitrum" ? 0.25 : 2.0;
|
|
583
|
+
for (const h of txHashes) {
|
|
584
|
+
const rcpt = receipts.get(h);
|
|
585
|
+
if (!rcpt || rcpt.status !== "0x1")
|
|
586
|
+
continue;
|
|
587
|
+
const relayer = String(rcpt.from || "").toLowerCase();
|
|
588
|
+
const isPermit2Tx = isPermit2ProxyReceipt(rcpt);
|
|
589
|
+
const isKnownFacilitator = knownFacilitators.has(relayer);
|
|
590
|
+
const transfers = parseEvmReceiptStablecoinTransfers(chain, rcpt, eurUsdRate);
|
|
591
|
+
if (transfers.length === 0)
|
|
592
|
+
continue;
|
|
593
|
+
const blkNum = parseInt(rcpt.blockNumber, 16);
|
|
594
|
+
const estBlockTime = Math.round(latestTs - Math.max(0, latestBlock - blkNum) * defaultSecPerBlock);
|
|
595
|
+
for (const tr of transfers) {
|
|
596
|
+
if (!isPermit2Tx && !isKnownFacilitator && !allowlistedPayees.has(tr.payee)) {
|
|
597
|
+
continue; // Strict allowlist noise shield for Arbitrum & Polygon
|
|
598
|
+
}
|
|
599
|
+
paymentRows.push({
|
|
600
|
+
chain,
|
|
601
|
+
txId: h,
|
|
602
|
+
eventIndex: tr.eventIndex,
|
|
603
|
+
assetContract: tr.assetContract,
|
|
604
|
+
assetSymbol: tr.assetSymbol,
|
|
605
|
+
amountRaw: tr.amountRaw,
|
|
606
|
+
amountUsd: tr.amountUsd,
|
|
607
|
+
amountUsdc: tr.amountUsd,
|
|
608
|
+
blockNumber: blkNum,
|
|
609
|
+
blockTime: estBlockTime,
|
|
610
|
+
confirmationStatus: "CONFIRMED",
|
|
611
|
+
channel: isPermit2Tx ? `${chain}_x402_permit2` : `${chain}_x402_allowlist`,
|
|
612
|
+
facilitator: knownFacilitators.get(relayer) ||
|
|
613
|
+
(isPermit2Tx ? "x402-Permit2-Proxy" : "Bazaar-Allowlisted"),
|
|
614
|
+
relayer,
|
|
615
|
+
payer: tr.payer,
|
|
616
|
+
payee: tr.payee,
|
|
617
|
+
hasMemo: false,
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
const { inserted } = await repo.insertPayments(paymentRows);
|
|
622
|
+
const { profileCount, recomputed } = await maybeRecomputeProfiles(chain, forceRecompute);
|
|
623
|
+
await repo.setState(`${chain}_last_block`, String(toBlock));
|
|
624
|
+
await repo.setState(`${chain}_last_sync_at`, new Date().toISOString());
|
|
625
|
+
await repo.setState(`${chain}_last_inserted`, String(inserted));
|
|
626
|
+
await repo.setState(`${chain}_last_error`, "");
|
|
627
|
+
return {
|
|
628
|
+
chain,
|
|
629
|
+
skipped: false,
|
|
630
|
+
fromBlock,
|
|
631
|
+
toBlock,
|
|
632
|
+
latestBlock,
|
|
633
|
+
inserted,
|
|
634
|
+
profiles: profileCount,
|
|
635
|
+
recomputed,
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
async function fetchSolanaTxsBatch(signatures) {
|
|
639
|
+
const map = new Map();
|
|
640
|
+
const batchSize = 3;
|
|
641
|
+
const solanaBatchPaceMs = rpcPaceMs > 0 ? Math.max(rpcPaceMs, 500) : 0;
|
|
642
|
+
for (let i = 0; i < signatures.length; i += batchSize) {
|
|
643
|
+
const slice = signatures.slice(i, i + batchSize);
|
|
644
|
+
const batch = slice.map((sig, idx) => ({
|
|
645
|
+
jsonrpc: "2.0",
|
|
646
|
+
id: idx + 1,
|
|
647
|
+
method: "getTransaction",
|
|
648
|
+
params: [sig, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }],
|
|
649
|
+
}));
|
|
650
|
+
const res = await rpcBatchWithFailover(solanaRpcs, batch);
|
|
651
|
+
if (Array.isArray(res)) {
|
|
652
|
+
for (const item of res) {
|
|
653
|
+
if (item?.result)
|
|
654
|
+
map.set(slice[item.id - 1], item.result);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
if (i + batchSize < signatures.length && solanaBatchPaceMs > 0) {
|
|
658
|
+
await sleep(solanaBatchPaceMs);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
return map;
|
|
662
|
+
}
|
|
663
|
+
async function syncSolanaOnce({ forceRecompute = false } = {}) {
|
|
664
|
+
const state = await repo.getState();
|
|
665
|
+
let latestSlot = null;
|
|
666
|
+
try {
|
|
667
|
+
latestSlot = await rpcCallWithFailover(solanaRpcs, "getSlot", []);
|
|
668
|
+
if (latestSlot !== null && latestSlot !== undefined) {
|
|
669
|
+
await repo.setState("solana_latest_slot", String(latestSlot));
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
catch {
|
|
673
|
+
// ignore slot failure
|
|
674
|
+
}
|
|
675
|
+
const paymentRows = [];
|
|
676
|
+
const cursorUpdates = [];
|
|
677
|
+
for (const target of solanaTargets) {
|
|
678
|
+
const stateKey = `solana_until_${target.address}`;
|
|
679
|
+
const pendingHeadKey = `solana_pending_head_${target.address}`;
|
|
680
|
+
const pendingBeforeKey = `solana_pending_before_${target.address}`;
|
|
681
|
+
const pendingPagesKey = `solana_pending_pages_${target.address}`;
|
|
682
|
+
const untilSig = state[stateKey] || undefined;
|
|
683
|
+
const pendingHead = state[pendingHeadKey] || "";
|
|
684
|
+
const pendingBefore = state[pendingBeforeKey] || "";
|
|
685
|
+
const pendingPages = Math.max(0, Number(state[pendingPagesKey] || 0));
|
|
686
|
+
const processSigPage = async (sigs) => {
|
|
687
|
+
// Skip failed signatures (s.err != null) before calling getTransaction to preserve RPC budget
|
|
688
|
+
const validSigIds = sigs
|
|
689
|
+
.filter((s) => s?.signature && s.err == null)
|
|
690
|
+
.map((s) => String(s.signature));
|
|
691
|
+
const txMap = validSigIds.length > 0 ? await fetchSolanaTxsBatch(validSigIds) : new Map();
|
|
692
|
+
for (const s of sigs) {
|
|
693
|
+
if (!s?.signature || s.err != null)
|
|
694
|
+
continue;
|
|
695
|
+
const tx = txMap.get(s.signature);
|
|
696
|
+
if (!tx)
|
|
697
|
+
continue;
|
|
698
|
+
const transfers = parseSolanaStablecoinTransfers(tx);
|
|
699
|
+
for (const tr of transfers) {
|
|
700
|
+
paymentRows.push({
|
|
701
|
+
chain: "solana",
|
|
702
|
+
txId: s.signature,
|
|
703
|
+
eventIndex: tr.eventIndex,
|
|
704
|
+
assetContract: tr.assetContract,
|
|
705
|
+
assetSymbol: tr.assetSymbol,
|
|
706
|
+
amountRaw: tr.amountRaw,
|
|
707
|
+
amountUsd: tr.amountUsd,
|
|
708
|
+
amountUsdc: tr.amountUsd,
|
|
709
|
+
blockNumber: tx.slot ?? s.slot ?? null,
|
|
710
|
+
blockTime: tx.blockTime ?? s.blockTime ?? null,
|
|
711
|
+
confirmationStatus: "CONFIRMED",
|
|
712
|
+
channel: target.channel || "solana_x402_payai",
|
|
713
|
+
facilitator: target.label,
|
|
714
|
+
relayer: target.address,
|
|
715
|
+
payer: tr.payer,
|
|
716
|
+
payee: tr.payee,
|
|
717
|
+
hasMemo: hasSolanaMemo(tx),
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
let newestSettled = "";
|
|
722
|
+
for (const s of sigs) {
|
|
723
|
+
if (!s?.signature)
|
|
724
|
+
continue;
|
|
725
|
+
if (s.err != null || txMap.has(s.signature)) {
|
|
726
|
+
newestSettled = String(s.signature);
|
|
727
|
+
break;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
let oldestSettled = "";
|
|
731
|
+
for (let i = sigs.length - 1; i >= 0; i -= 1) {
|
|
732
|
+
const s = sigs[i];
|
|
733
|
+
if (!s?.signature)
|
|
734
|
+
continue;
|
|
735
|
+
if (s.err != null || txMap.has(s.signature)) {
|
|
736
|
+
oldestSettled = String(s.signature);
|
|
737
|
+
break;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
return { validSigIds, txMap, newestSettled, oldestSettled };
|
|
741
|
+
};
|
|
742
|
+
// Phase A: Drain any pending gap [before..until] left by a prior burst tick exceeding solanaMaxTxsPerTick
|
|
743
|
+
if (pendingBefore && pendingHead && untilSig) {
|
|
744
|
+
const gapSigs = await rpcCallWithFailover(solanaRpcs, "getSignaturesForAddress", [
|
|
745
|
+
target.address,
|
|
746
|
+
{ limit: solanaMaxTxsPerTick, before: pendingBefore, until: untilSig },
|
|
747
|
+
]);
|
|
748
|
+
if (!Array.isArray(gapSigs) || gapSigs.length === 0) {
|
|
749
|
+
// Gap reached `untilSig` cleanly: advance watermark to pendingHead and immediately poll new tip
|
|
750
|
+
cursorUpdates.push([stateKey, pendingHead]);
|
|
751
|
+
cursorUpdates.push([pendingHeadKey, ""]);
|
|
752
|
+
cursorUpdates.push([pendingBeforeKey, ""]);
|
|
753
|
+
cursorUpdates.push([pendingPagesKey, ""]);
|
|
754
|
+
const tipSigs = await rpcCallWithFailover(solanaRpcs, "getSignaturesForAddress", [
|
|
755
|
+
target.address,
|
|
756
|
+
{ limit: solanaMaxTxsPerTick, until: pendingHead },
|
|
757
|
+
]);
|
|
758
|
+
if (Array.isArray(tipSigs) && tipSigs.length > 0) {
|
|
759
|
+
const { validSigIds, txMap, newestSettled, oldestSettled } = await processSigPage(tipSigs);
|
|
760
|
+
if (validSigIds.length === 0 || txMap.size > 0) {
|
|
761
|
+
if (tipSigs.length >= solanaMaxTxsPerTick &&
|
|
762
|
+
solanaMaxCatchupPages > 0 &&
|
|
763
|
+
newestSettled &&
|
|
764
|
+
oldestSettled) {
|
|
765
|
+
cursorUpdates.push([pendingHeadKey, newestSettled]);
|
|
766
|
+
cursorUpdates.push([pendingBeforeKey, oldestSettled]);
|
|
767
|
+
cursorUpdates.push([pendingPagesKey, "0"]);
|
|
768
|
+
}
|
|
769
|
+
else if (newestSettled) {
|
|
770
|
+
cursorUpdates.push([stateKey, newestSettled]);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
continue;
|
|
775
|
+
}
|
|
776
|
+
const { validSigIds, txMap, oldestSettled } = await processSigPage(gapSigs);
|
|
777
|
+
if (validSigIds.length > 0 && txMap.size === 0) {
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
780
|
+
const nextPages = pendingPages + 1;
|
|
781
|
+
if (gapSigs.length < solanaMaxTxsPerTick || nextPages >= solanaMaxCatchupPages) {
|
|
782
|
+
cursorUpdates.push([stateKey, pendingHead]);
|
|
783
|
+
cursorUpdates.push([pendingHeadKey, ""]);
|
|
784
|
+
cursorUpdates.push([pendingBeforeKey, ""]);
|
|
785
|
+
cursorUpdates.push([pendingPagesKey, ""]);
|
|
786
|
+
}
|
|
787
|
+
else if (oldestSettled && oldestSettled !== pendingBefore) {
|
|
788
|
+
cursorUpdates.push([pendingBeforeKey, oldestSettled]);
|
|
789
|
+
cursorUpdates.push([pendingPagesKey, String(nextPages)]);
|
|
790
|
+
}
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
// Phase B: Poll newest signatures from tip back to `untilSig`
|
|
794
|
+
const cfg = untilSig
|
|
795
|
+
? { limit: solanaMaxTxsPerTick, until: untilSig }
|
|
796
|
+
: { limit: solanaMaxTxsPerTick };
|
|
797
|
+
const sigs = await rpcCallWithFailover(solanaRpcs, "getSignaturesForAddress", [
|
|
798
|
+
target.address,
|
|
799
|
+
cfg,
|
|
800
|
+
]);
|
|
801
|
+
if (!Array.isArray(sigs) || sigs.length === 0)
|
|
802
|
+
continue;
|
|
803
|
+
const { validSigIds, txMap, newestSettled, oldestSettled } = await processSigPage(sigs);
|
|
804
|
+
if (validSigIds.length > 0 && txMap.size === 0) {
|
|
805
|
+
continue;
|
|
806
|
+
}
|
|
807
|
+
if (untilSig &&
|
|
808
|
+
sigs.length >= solanaMaxTxsPerTick &&
|
|
809
|
+
solanaMaxCatchupPages > 0 &&
|
|
810
|
+
newestSettled &&
|
|
811
|
+
oldestSettled) {
|
|
812
|
+
// Keep `solana_until_` anchored while draining the older gap [oldestSettled..untilSig] on subsequent ticks
|
|
813
|
+
cursorUpdates.push([pendingHeadKey, newestSettled]);
|
|
814
|
+
cursorUpdates.push([pendingBeforeKey, oldestSettled]);
|
|
815
|
+
cursorUpdates.push([pendingPagesKey, "0"]);
|
|
816
|
+
}
|
|
817
|
+
else if (newestSettled) {
|
|
818
|
+
cursorUpdates.push([stateKey, newestSettled]);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
const { inserted } = await repo.insertPayments(paymentRows);
|
|
822
|
+
const { profileCount, recomputed } = await maybeRecomputeProfiles("solana", forceRecompute);
|
|
823
|
+
for (const [k, v] of cursorUpdates) {
|
|
824
|
+
await repo.setState(k, v);
|
|
825
|
+
}
|
|
826
|
+
await repo.setState("solana_last_sync_at", new Date().toISOString());
|
|
827
|
+
await repo.setState("solana_last_inserted", String(inserted));
|
|
828
|
+
await repo.setState("solana_last_error", "");
|
|
829
|
+
return {
|
|
830
|
+
chain: "solana",
|
|
831
|
+
latestSlot,
|
|
832
|
+
inserted,
|
|
833
|
+
profiles: profileCount,
|
|
834
|
+
recomputed,
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
async function syncBazaarOnce() {
|
|
838
|
+
return syncBazaarCapabilities({ repo, fetchImpl });
|
|
839
|
+
}
|
|
840
|
+
async function runLivenessOnce() {
|
|
841
|
+
return runLivenessProbeBatch({
|
|
842
|
+
repo,
|
|
843
|
+
limit: livenessProbeBatchSize,
|
|
844
|
+
fetchImpl,
|
|
845
|
+
allowPrivateHosts: Boolean(options.allowPrivateHosts),
|
|
846
|
+
proxyUrl: probeProxyUrl,
|
|
847
|
+
proxyToken: probeProxyToken,
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
async function runOnce() {
|
|
851
|
+
const out = {
|
|
852
|
+
base: null,
|
|
853
|
+
solana: null,
|
|
854
|
+
arbitrum: null,
|
|
855
|
+
polygon: null,
|
|
856
|
+
bazaar: null,
|
|
857
|
+
liveness: null,
|
|
858
|
+
errors: [],
|
|
859
|
+
};
|
|
860
|
+
try {
|
|
861
|
+
out.base = await syncBaseOnce({ forceRecompute: true });
|
|
862
|
+
}
|
|
863
|
+
catch (err) {
|
|
864
|
+
const msg = redactSecrets(err.message);
|
|
865
|
+
await repo.setState("base_last_error", msg);
|
|
866
|
+
out.errors.push(`base: ${msg}`);
|
|
867
|
+
logger.error(`[Indexer][Base] ${msg}`);
|
|
868
|
+
}
|
|
869
|
+
try {
|
|
870
|
+
out.solana = await syncSolanaOnce({ forceRecompute: true });
|
|
871
|
+
}
|
|
872
|
+
catch (err) {
|
|
873
|
+
const msg = redactSecrets(err.message);
|
|
874
|
+
await repo.setState("solana_last_error", msg);
|
|
875
|
+
out.errors.push(`solana: ${msg}`);
|
|
876
|
+
logger.error(`[Indexer][Solana] ${msg}`);
|
|
877
|
+
}
|
|
878
|
+
if (arbitrumRpcs.length > 0) {
|
|
879
|
+
try {
|
|
880
|
+
out.arbitrum = await syncAllowlistedEvmOnce("arbitrum", { forceRecompute: true });
|
|
881
|
+
}
|
|
882
|
+
catch (err) {
|
|
883
|
+
const msg = redactSecrets(err.message);
|
|
884
|
+
await repo.setState("arbitrum_last_error", msg);
|
|
885
|
+
out.errors.push(`arbitrum: ${msg}`);
|
|
886
|
+
logger.error(`[Indexer][Arbitrum] ${msg}`);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
if (polygonRpcs.length > 0) {
|
|
890
|
+
try {
|
|
891
|
+
out.polygon = await syncAllowlistedEvmOnce("polygon", { forceRecompute: true });
|
|
892
|
+
}
|
|
893
|
+
catch (err) {
|
|
894
|
+
const msg = redactSecrets(err.message);
|
|
895
|
+
await repo.setState("polygon_last_error", msg);
|
|
896
|
+
out.errors.push(`polygon: ${msg}`);
|
|
897
|
+
logger.error(`[Indexer][Polygon] ${msg}`);
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
if (!skipBazaarSync) {
|
|
901
|
+
try {
|
|
902
|
+
out.bazaar = await syncBazaarOnce();
|
|
903
|
+
}
|
|
904
|
+
catch (err) {
|
|
905
|
+
const msg = redactSecrets(err.message);
|
|
906
|
+
await repo.setState("bazaar_last_error", msg);
|
|
907
|
+
logger.error(`[Indexer][Bazaar] ${msg}`);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
if (!skipLivenessProbe) {
|
|
911
|
+
try {
|
|
912
|
+
out.liveness = await runLivenessOnce();
|
|
913
|
+
}
|
|
914
|
+
catch (err) {
|
|
915
|
+
const msg = redactSecrets(err.message);
|
|
916
|
+
await repo.setState("liveness_last_error", msg);
|
|
917
|
+
logger.error(`[Indexer][Liveness] ${msg}`);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
return out;
|
|
921
|
+
}
|
|
922
|
+
let running = false;
|
|
923
|
+
const timers = [];
|
|
924
|
+
const busy = {};
|
|
925
|
+
function scheduleWorker(name, intervalMs, delayMs, fn) {
|
|
926
|
+
const runSafe = async () => {
|
|
927
|
+
if (!running || busy[name])
|
|
928
|
+
return;
|
|
929
|
+
busy[name] = true;
|
|
930
|
+
try {
|
|
931
|
+
await fn();
|
|
932
|
+
}
|
|
933
|
+
catch (err) {
|
|
934
|
+
logger.error(`[Indexer][${name}] ${redactSecrets(err.message)}`);
|
|
935
|
+
}
|
|
936
|
+
finally {
|
|
937
|
+
busy[name] = false;
|
|
938
|
+
}
|
|
939
|
+
};
|
|
940
|
+
if (delayMs > 0) {
|
|
941
|
+
timers.push(setTimeout(() => void runSafe(), delayMs));
|
|
942
|
+
}
|
|
943
|
+
else {
|
|
944
|
+
void runSafe();
|
|
945
|
+
}
|
|
946
|
+
timers.push(setInterval(() => void runSafe(), intervalMs));
|
|
947
|
+
}
|
|
948
|
+
function start() {
|
|
949
|
+
if (running)
|
|
950
|
+
return;
|
|
951
|
+
running = true;
|
|
952
|
+
logger.log(`[Indexer] Started v2.3 (backend=${repo.backend}, base=${basePollIntervalMs}ms, solana=${solanaPollIntervalMs}ms, arbitrum=${arbitrumRpcs.length > 0 ? `${allowlistedEvmPollIntervalMs}ms` : "standby"}, polygon=${polygonRpcs.length > 0 ? `${allowlistedEvmPollIntervalMs}ms` : "standby"})`);
|
|
953
|
+
scheduleWorker("Base", basePollIntervalMs, 0, async () => {
|
|
954
|
+
try {
|
|
955
|
+
const r = await syncBaseOnce();
|
|
956
|
+
logger.log(`[Indexer][Base] blocks ${r.fromBlock}-${r.toBlock} (head ${r.latestBlock ?? "?"}) +${r.inserted} tx | profiles=${r.profiles}`);
|
|
957
|
+
}
|
|
958
|
+
catch (err) {
|
|
959
|
+
const msg = redactSecrets(err.message);
|
|
960
|
+
await repo.setState("base_last_error", msg);
|
|
961
|
+
throw new Error(msg);
|
|
962
|
+
}
|
|
963
|
+
});
|
|
964
|
+
scheduleWorker("Solana", solanaPollIntervalMs, 5000, async () => {
|
|
965
|
+
try {
|
|
966
|
+
const r = await syncSolanaOnce();
|
|
967
|
+
logger.log(`[Indexer][Solana] slot ${r.latestSlot ?? "?"} +${r.inserted} tx | profiles=${r.profiles}`);
|
|
968
|
+
}
|
|
969
|
+
catch (err) {
|
|
970
|
+
const msg = redactSecrets(err.message);
|
|
971
|
+
await repo.setState("solana_last_error", msg);
|
|
972
|
+
throw new Error(msg);
|
|
973
|
+
}
|
|
974
|
+
});
|
|
975
|
+
if (arbitrumRpcs.length > 0) {
|
|
976
|
+
scheduleWorker("Arbitrum", allowlistedEvmPollIntervalMs, 10000, async () => {
|
|
977
|
+
try {
|
|
978
|
+
const r = await syncAllowlistedEvmOnce("arbitrum");
|
|
979
|
+
logger.log(`[Indexer][Arbitrum] blocks ${r.fromBlock ?? "?"}-${r.toBlock ?? "?"} (head ${r.latestBlock ?? "?"}) +${r.inserted} tx | profiles=${r.profiles}`);
|
|
980
|
+
}
|
|
981
|
+
catch (err) {
|
|
982
|
+
const msg = redactSecrets(err.message);
|
|
983
|
+
await repo.setState("arbitrum_last_error", msg);
|
|
984
|
+
throw new Error(msg);
|
|
985
|
+
}
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
if (polygonRpcs.length > 0) {
|
|
989
|
+
scheduleWorker("Polygon", allowlistedEvmPollIntervalMs, 15000, async () => {
|
|
990
|
+
try {
|
|
991
|
+
const r = await syncAllowlistedEvmOnce("polygon");
|
|
992
|
+
logger.log(`[Indexer][Polygon] blocks ${r.fromBlock ?? "?"}-${r.toBlock ?? "?"} (head ${r.latestBlock ?? "?"}) +${r.inserted} tx | profiles=${r.profiles}`);
|
|
993
|
+
}
|
|
994
|
+
catch (err) {
|
|
995
|
+
const msg = redactSecrets(err.message);
|
|
996
|
+
await repo.setState("polygon_last_error", msg);
|
|
997
|
+
throw new Error(msg);
|
|
998
|
+
}
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
if (!skipBazaarSync) {
|
|
1002
|
+
scheduleWorker("Bazaar", bazaarSyncIntervalMs, 12000, async () => {
|
|
1003
|
+
const r = await syncBazaarOnce();
|
|
1004
|
+
logger.log(`[Indexer][Bazaar] upserted=${r.upserted} total=${r.totalCapabilities}`);
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
if (!skipLivenessProbe) {
|
|
1008
|
+
scheduleWorker("Liveness", livenessProbeIntervalMs, 25000, async () => {
|
|
1009
|
+
const r = await runLivenessOnce();
|
|
1010
|
+
logger.log(`[Indexer][Liveness] probed=${r.probed} healthy=${r.healthy}`);
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
scheduleWorker("Prune", 6 * 3600 * 1000, 60000, async () => {
|
|
1014
|
+
const r = await repo.pruneOldPayments(retentionDays);
|
|
1015
|
+
if (r.deleted > 0)
|
|
1016
|
+
logger.log(`[Indexer][Prune] Removed ${r.deleted} expired rows`);
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
async function stop() {
|
|
1020
|
+
running = false;
|
|
1021
|
+
for (const t of timers) {
|
|
1022
|
+
clearTimeout(t);
|
|
1023
|
+
clearInterval(t);
|
|
1024
|
+
}
|
|
1025
|
+
timers.length = 0;
|
|
1026
|
+
if (ownRepo) {
|
|
1027
|
+
await repo.close();
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
return {
|
|
1031
|
+
repo,
|
|
1032
|
+
getChainSpec,
|
|
1033
|
+
syncBaseOnce,
|
|
1034
|
+
syncSolanaOnce,
|
|
1035
|
+
syncAllowlistedEvmOnce,
|
|
1036
|
+
syncBazaarOnce,
|
|
1037
|
+
runLivenessOnce,
|
|
1038
|
+
runOnce,
|
|
1039
|
+
start,
|
|
1040
|
+
stop,
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
//# sourceMappingURL=indexer.js.map
|