forked from Echo-Mirror-Butler/echomirror-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.ts
More file actions
68 lines (58 loc) · 1.8 KB
/
Copy pathbackground.ts
File metadata and controls
68 lines (58 loc) · 1.8 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
// Background service worker — handles Stellar transaction watching
interface WatchState {
publicKey: string
network: string
cursor: string
totalSeen: number
}
let watchState: WatchState | null = null
let pollInterval: ReturnType<typeof setInterval> | null = null
chrome.runtime.onMessage.addListener((msg) => {
if (msg.type === 'START_WATCH') {
startWatching(msg.publicKey, msg.network)
} else if (msg.type === 'STOP_WATCH') {
stopWatching()
}
})
function startWatching(publicKey: string, network: string) {
stopWatching()
watchState = { publicKey, network, cursor: 'now', totalSeen: 0 }
poll()
pollInterval = setInterval(poll, 5_000)
}
function stopWatching() {
if (pollInterval) {
clearInterval(pollInterval)
pollInterval = null
}
watchState = null
}
async function poll() {
if (!watchState) return
const { publicKey, network, cursor } = watchState
const horizon = network === 'testnet'
? 'https://horizon-testnet.stellar.org'
: 'https://horizon.stellar.org'
try {
const res = await fetch(
`${horizon}/accounts/${publicKey}/transactions?limit=10&order=asc&cursor=${cursor}`,
)
if (!res.ok) return
const data = await res.json()
const records: Array<{ hash: string; ledger: number; paging_token: string; memo?: string }> =
data._embedded?.records ?? []
for (const r of records) {
watchState.totalSeen++
watchState.cursor = r.paging_token
chrome.notifications.create(`echo-tx-${r.hash}`, {
type: 'basic',
iconUrl: 'icons/icon48.png',
title: 'EchoMirror: Stellar Transaction',
message: `Ledger ${r.ledger} • ${r.hash.slice(0, 16)}…${r.memo ? ` • ${r.memo}` : ''}`,
priority: 1,
})
}
} catch {
// Network errors during polling are silently ignored
}
}