forked from Trac-Systems/intercom
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker.js
More file actions
322 lines (272 loc) Β· 10.6 KB
/
tracker.js
File metadata and controls
322 lines (272 loc) Β· 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/**
* TracScope β Swap Analytics Tracker
* Subscribes to the Intercom sidechannel and aggregates swap/RFQ events
* into an in-memory store that the dashboard reads from.
*
* Usage (Pear runtime only):
* pear run . store1
*
* The tracker auto-starts when index.js boots. You can also require it
* directly in tests: const tracker = require('./tracker')
*/
'use strict'
// βββ Constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const TRACKER_VERSION = '1.0.0'
// Event types emitted by IntercomSwap over the sidechannel
const EV = {
RFQ_REQUEST: 'rfq_request', // peer requests a quote
RFQ_RESPONSE: 'rfq_response', // market-maker responds
RFQ_ACCEPT: 'rfq_accept', // requester accepts quote
RFQ_REJECT: 'rfq_reject', // requester rejects quote
SWAP_INIT: 'swap_init', // HTLC initiated
SWAP_SETTLE: 'swap_settle', // HTLC settled (success)
SWAP_REFUND: 'swap_refund', // HTLC expired / refunded
PEER_HELLO: 'peer_hello', // peer announces itself
}
// How long to keep per-minute buckets (rolling window)
const ROLLING_MINUTES = 60
// βββ In-memory state ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* All aggregated analytics live here.
* The dashboard reads this object directly (same process) or via the
* local HTTP/WebSocket bridge in index.js.
*/
const state = {
startedAt: Date.now(),
version: TRACKER_VERSION,
peers: new Map(), // peerId β { firstSeen, lastSeen, rfqs, swaps }
swaps: [], // last 500 completed swaps (ring buffer)
rfqs: [], // last 500 RFQ events
totals: {
rfqRequests: 0,
rfqAccepted: 0,
rfqRejected: 0,
swapsSuccess: 0,
swapsRefund: 0,
volumeBtcSats: 0n, // BigInt β satoshis
volumeUsdtMicro: 0n, // BigInt β USDT * 1_000_000
},
// Rolling 1-min buckets for sparkline charts
minuteBuckets: [], // [{ ts, swaps, volumeSats }] β newest last
// Live peer set (active in last 5 min)
activePeers: new Set(),
}
// βββ Ring-buffer helper ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function pushRing(arr, item, maxLen = 500) {
arr.push(item)
if (arr.length > maxLen) arr.shift()
}
// βββ Bucket helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function currentMinute() {
return Math.floor(Date.now() / 60_000) * 60_000
}
function getOrCreateBucket(ts = currentMinute()) {
const last = state.minuteBuckets[state.minuteBuckets.length - 1]
if (last && last.ts === ts) return last
const bucket = { ts, swaps: 0, rfqs: 0, volumeSats: 0n }
state.minuteBuckets.push(bucket)
// Keep only ROLLING_MINUTES buckets
if (state.minuteBuckets.length > ROLLING_MINUTES) {
state.minuteBuckets.shift()
}
return bucket
}
// βββ Peer tracking ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function touchPeer(peerId) {
const now = Date.now()
if (!state.peers.has(peerId)) {
state.peers.set(peerId, { firstSeen: now, lastSeen: now, rfqs: 0, swaps: 0 })
} else {
state.peers.get(peerId).lastSeen = now
}
state.activePeers.add(peerId)
// Expire peers not seen in 5 min
for (const [id, p] of state.activePeers) {
if (now - state.peers.get(id)?.lastSeen > 5 * 60_000) {
state.activePeers.delete(id)
}
}
return state.peers.get(peerId)
}
// βββ Event handlers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const handlers = {
[EV.PEER_HELLO](msg) {
touchPeer(msg.peerId)
},
[EV.RFQ_REQUEST](msg) {
const peer = touchPeer(msg.peerId)
peer.rfqs++
state.totals.rfqRequests++
getOrCreateBucket().rfqs++
pushRing(state.rfqs, {
ts: msg.ts || Date.now(),
peerId: msg.peerId,
type: 'request',
amountSats: BigInt(msg.amountSats || 0),
pair: msg.pair || 'BTC/USDT',
})
},
[EV.RFQ_RESPONSE](msg) {
touchPeer(msg.peerId)
pushRing(state.rfqs, {
ts: msg.ts || Date.now(),
peerId: msg.peerId,
type: 'response',
quotedRate: msg.quotedRate,
pair: msg.pair || 'BTC/USDT',
})
},
[EV.RFQ_ACCEPT](msg) {
touchPeer(msg.peerId)
state.totals.rfqAccepted++
},
[EV.RFQ_REJECT](msg) {
touchPeer(msg.peerId)
state.totals.rfqRejected++
},
[EV.SWAP_INIT](msg) {
touchPeer(msg.peerId)
},
[EV.SWAP_SETTLE](msg) {
const peer = touchPeer(msg.peerId)
peer.swaps++
state.totals.swapsSuccess++
const sats = BigInt(msg.amountSats || 0)
const usdt = BigInt(msg.amountUsdtMicro || 0)
state.totals.volumeBtcSats += sats
state.totals.volumeUsdtMicro += usdt
const bucket = getOrCreateBucket()
bucket.swaps++
bucket.volumeSats += sats
pushRing(state.swaps, {
ts: msg.ts || Date.now(),
peerId: msg.peerId,
amountSats: sats,
amountUsdt: usdt,
settlementMs: msg.settlementMs || null,
txIdLightning: msg.txIdLightning || null,
txIdSolana: msg.txIdSolana || null,
})
},
[EV.SWAP_REFUND](msg) {
touchPeer(msg.peerId)
state.totals.swapsRefund++
},
}
// βββ Core dispatcher ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Feed a raw sidechannel message into the tracker.
* Call this from your Intercom message handler in index.js:
*
* sidechannel.on('message', (msg) => tracker.ingest(msg))
*
* @param {object} msg Parsed JSON from the sidechannel
*/
function ingest(msg) {
if (!msg || typeof msg.type !== 'string') return
const handler = handlers[msg.type]
if (handler) {
try {
handler(msg)
} catch (err) {
console.error('[TracScope] handler error for', msg.type, err.message)
}
}
}
// βββ Snapshot API (used by dashboard / HTTP bridge) ββββββββββββββββββββββββββ
/**
* Returns a plain JSON-serialisable snapshot of the current analytics state.
* Converts BigInts to strings so JSON.stringify works.
*/
function snapshot() {
const fillRate = state.totals.rfqRequests > 0
? ((state.totals.rfqAccepted / state.totals.rfqRequests) * 100).toFixed(1)
: '0.0'
const topPeers = [...state.peers.entries()]
.map(([id, p]) => ({ id, ...p }))
.sort((a, b) => b.swaps - a.swaps)
.slice(0, 10)
const recentSwaps = [...state.swaps].reverse().slice(0, 50).map(s => ({
...s,
amountSats: s.amountSats.toString(),
amountUsdt: (Number(s.amountUsdt) / 1_000_000).toFixed(6),
}))
return {
version: TRACKER_VERSION,
snapshotAt: Date.now(),
uptimeMs: Date.now() - state.startedAt,
totals: {
rfqRequests: state.totals.rfqRequests,
rfqAccepted: state.totals.rfqAccepted,
rfqRejected: state.totals.rfqRejected,
rfqFillRate: fillRate + '%',
swapsSuccess: state.totals.swapsSuccess,
swapsRefund: state.totals.swapsRefund,
volumeBtc: (Number(state.totals.volumeBtcSats) / 1e8).toFixed(8),
volumeUsdt: (Number(state.totals.volumeUsdtMicro) / 1e6).toFixed(2),
},
activePeerCount: state.activePeers.size,
totalPeerCount: state.peers.size,
topPeers,
recentSwaps,
// Sparkline data β last 60 min, each bucket: { ts, swaps, volumeBtc }
buckets: state.minuteBuckets.map(b => ({
ts: b.ts,
swaps: b.swaps,
rfqs: b.rfqs,
volumeBtc: (Number(b.volumeSats) / 1e8).toFixed(8),
})),
}
}
// βββ Demo / simulation mode βββββββββββββββββββββββββββββββββββββββββββββββββββ
// When running without a live Intercom node, call startSimulation() to feed
// synthetic events so the dashboard has data to display.
let _simInterval = null
function startSimulation() {
if (_simInterval) return
console.log('[TracScope] Simulation mode active β generating synthetic events')
const peers = ['peer_alice', 'peer_bob', 'peer_carol', 'peer_dave', 'peer_eve']
function randomPeer() { return peers[Math.floor(Math.random() * peers.length)] }
function randomSats() { return Math.floor(Math.random() * 500_000) + 10_000 }
// Seed some history
for (let i = 0; i < 40; i++) {
ingest({ type: EV.PEER_HELLO, peerId: randomPeer() })
ingest({ type: EV.RFQ_REQUEST, peerId: randomPeer(), amountSats: randomSats(), pair: 'BTC/USDT' })
ingest({ type: EV.RFQ_RESPONSE, peerId: randomPeer(), quotedRate: (92000 + Math.random() * 2000).toFixed(2) })
if (Math.random() > 0.25) {
ingest({ type: EV.RFQ_ACCEPT, peerId: randomPeer() })
ingest({ type: EV.SWAP_INIT, peerId: randomPeer() })
ingest({
type: EV.SWAP_SETTLE,
peerId: randomPeer(),
amountSats: randomSats(),
amountUsdtMicro: Math.floor(Math.random() * 50_000_000),
settlementMs: Math.floor(Math.random() * 8000) + 1200,
})
} else {
ingest({ type: EV.RFQ_REJECT, peerId: randomPeer() })
}
}
// Live trickle
_simInterval = setInterval(() => {
const peerId = randomPeer()
ingest({ type: EV.RFQ_REQUEST, peerId, amountSats: randomSats(), pair: 'BTC/USDT' })
if (Math.random() > 0.3) {
ingest({ type: EV.RFQ_ACCEPT, peerId })
ingest({
type: EV.SWAP_SETTLE,
peerId,
amountSats: randomSats(),
amountUsdtMicro: Math.floor(Math.random() * 50_000_000),
settlementMs: Math.floor(Math.random() * 8000) + 1200,
})
} else {
ingest({ type: EV.RFQ_REJECT, peerId })
}
}, 3000)
}
function stopSimulation() {
if (_simInterval) { clearInterval(_simInterval); _simInterval = null }
}
// βββ Exports ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
module.exports = { ingest, snapshot, startSimulation, stopSimulation, EV, state }