forked from Echo-Mirror-Butler/echomirror-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.ts
More file actions
364 lines (327 loc) · 14.8 KB
/
Copy pathextension.ts
File metadata and controls
364 lines (327 loc) · 14.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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import * as vscode from 'vscode'
import { EchoMirrorClient } from '@echomirror/core'
import { logMood, getMoodStreak, MoodScore, MoodTag } from '@echomirror/mood'
let statusBarItem: vscode.StatusBarItem
let moodStatusBarItem: vscode.StatusBarItem
let balanceInterval: ReturnType<typeof setInterval> | undefined
export function activate(context: vscode.ExtensionContext) {
// ── Status bar — live ECHO balance ──────────────────────────────────────────
statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100)
statusBarItem.command = 'echomirror.checkBalance'
context.subscriptions.push(statusBarItem)
updateStatusBar()
const config = vscode.workspace.getConfiguration('echomirror')
if (config.get<boolean>('showStatusBar') && config.get<string>('statusBarPublicKey')) {
statusBarItem.show()
startBalancePolling()
}
// ── Status bar — Mood ───────────────────────────────────────────────────────
moodStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 101)
moodStatusBarItem.command = 'echomirror.logMood'
moodStatusBarItem.text = '$(pulse) Log Mood'
moodStatusBarItem.tooltip = 'EchoMirror SDK — click to log your mood'
moodStatusBarItem.show()
context.subscriptions.push(moodStatusBarItem)
// ── Authentication Helper ────────────────────────────────────────────────────
async function getClient(): Promise<EchoMirrorClient | undefined> {
const apiKey = await context.secrets.get('echomirror.apiKey')
if (!apiKey) {
vscode.window.showErrorMessage('Not signed in to EchoMirror. Please sign in first.')
vscode.commands.executeCommand('echomirror.signIn')
return undefined
}
const config = vscode.workspace.getConfiguration('echomirror')
const network = config.get<'mainnet' | 'testnet'>('network') ?? 'testnet'
return new EchoMirrorClient({ apiKey, network })
}
// ── Commands ─────────────────────────────────────────────────────────────────
context.subscriptions.push(
vscode.commands.registerCommand('echomirror.checkBalance', async () => {
const config = vscode.workspace.getConfiguration('echomirror')
const publicKey = config.get<string>('statusBarPublicKey')
if (!publicKey) {
const key = await vscode.window.showInputBox({
prompt: 'Enter a Stellar public key to check balance',
placeHolder: 'G...',
validateInput: (v) =>
v.startsWith('G') && v.length === 56 ? null : 'Must be a valid Stellar G-address',
})
if (key) await showBalance(key)
return
}
await showBalance(publicKey)
}),
vscode.commands.registerCommand('echomirror.validateAddress', async () => {
const address = await vscode.window.showInputBox({
prompt: 'Enter a Stellar address to validate',
placeHolder: 'G...',
})
if (!address) return
const valid = address.startsWith('G') && address.length === 56 && /^[A-Z2-7]+$/.test(address)
vscode.window.showInformationMessage(
valid
? `✅ Valid Stellar address: ${address}`
: `❌ Invalid address — must start with G and be 56 alphanumeric characters`,
)
}),
vscode.commands.registerCommand('echomirror.fundTestnet', async () => {
const config = vscode.workspace.getConfiguration('echomirror')
if (config.get<string>('network') !== 'testnet') {
vscode.window.showErrorMessage('Friendbot funding is only available on testnet. Change echomirror.network to "testnet" first.')
return
}
const address = await vscode.window.showInputBox({
prompt: 'Enter the testnet account to fund (10,000 XLM)',
placeHolder: 'G...',
})
if (!address) return
await vscode.window.withProgress(
{ location: vscode.ProgressLocation.Notification, title: 'Funding testnet account…' },
async () => {
try {
const res = await fetch(`https://friendbot.stellar.org?addr=${address}`)
if (res.ok) {
vscode.window.showInformationMessage(`✅ Funded! ${address} now has 10,000 XLM on testnet.`)
} else {
vscode.window.showErrorMessage(`Friendbot error: ${res.status}`)
}
} catch (e) {
vscode.window.showErrorMessage(`Network error: ${e}`)
}
},
)
}),
vscode.commands.registerCommand('echomirror.insertMoodLogSnippet', async () => {
const editor = vscode.window.activeTextEditor
if (!editor) return
const lang = editor.document.languageId
const isDart = lang === 'dart'
const snippet = isDart
? `final entry = await EchoMirror.instance.mood.log(\n score: \${1:7},\n note: '\${2:How are you feeling?}',\n tags: ['\${3:work}'],\n);\n`
: `const entry = await logMood(client, {\n score: \${1:7},\n note: '\${2:How are you feeling?}',\n tags: ['\${3:work}'],\n})\n`
editor.insertSnippet(new vscode.SnippetString(snippet))
}),
vscode.commands.registerCommand('echomirror.openSyncExplorer', () => {
const panel = vscode.window.createWebviewPanel(
'echomirrorSync',
'EchoMirror Sync Explorer',
vscode.ViewColumn.Beside,
{ enableScripts: true },
)
panel.webview.html = getSyncExplorerHtml()
}),
vscode.commands.registerCommand('echomirror.signIn', async () => {
const apiKey = await vscode.window.showInputBox({
prompt: 'Enter your EchoMirror API Key',
password: true,
placeHolder: 'em_live_...',
ignoreFocusOut: true
})
if (apiKey) {
await context.secrets.store('echomirror.apiKey', apiKey)
vscode.window.showInformationMessage('Successfully signed in to EchoMirror.')
}
}),
vscode.commands.registerCommand('echomirror.signOut', async () => {
await context.secrets.delete('echomirror.apiKey')
vscode.window.showInformationMessage('Signed out of EchoMirror.')
moodStatusBarItem.text = '$(pulse) Log Mood'
}),
vscode.commands.registerCommand('echomirror.logMood', async () => {
const client = await getClient()
if (!client) return
const scoreStr = await vscode.window.showQuickPick(
['10', '9', '8', '7', '6', '5', '4', '3', '2', '1'],
{ placeHolder: 'How are you feeling today? (Score 1-10)' }
)
if (!scoreStr) return
const score = parseInt(scoreStr) as MoodScore
const note = await vscode.window.showInputBox({
prompt: 'Add an optional note about your mood',
placeHolder: 'Just feeling great today...'
})
if (note === undefined) return
const tagsSelection = await vscode.window.showQuickPick(
[
{ label: 'work' },
{ label: 'health' },
{ label: 'social' },
{ label: 'focus' },
{ label: 'stress' }
],
{ placeHolder: 'Select tags (optional)', canPickMany: true }
)
if (tagsSelection === undefined) return
const tags = tagsSelection.map(t => t.label) as MoodTag[]
await vscode.window.withProgress(
{ location: vscode.ProgressLocation.Notification, title: 'Logging mood…' },
async () => {
try {
await logMood(client, { score, note: note || undefined, tags: tags.length > 0 ? tags : undefined })
vscode.window.showInformationMessage(`Mood logged successfully! (Score: ${score})`)
const color = score >= 7 ? '🟢' : score >= 4 ? '🟡' : '🔴'
moodStatusBarItem.text = `${color} Mood: ${score}/10`
} catch (e) {
vscode.window.showErrorMessage(`Failed to log mood: ${e}`)
}
}
)
}),
vscode.commands.registerCommand('echomirror.viewStreak', async () => {
const client = await getClient()
if (!client) return
await vscode.window.withProgress(
{ location: vscode.ProgressLocation.Notification, title: 'Fetching streak…' },
async () => {
try {
const streak = await getMoodStreak(client)
vscode.window.showInformationMessage(`🔥 Current Streak: ${streak.current} days | Longest: ${streak.longest} days`)
} catch (e) {
vscode.window.showErrorMessage(`Failed to fetch streak: ${e}`)
}
}
)
}),
)
// Watch config changes to restart/stop balance polling
context.subscriptions.push(
vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration('echomirror')) {
clearInterval(balanceInterval)
const cfg = vscode.workspace.getConfiguration('echomirror')
if (cfg.get<boolean>('showStatusBar') && cfg.get<string>('statusBarPublicKey')) {
statusBarItem.show()
startBalancePolling()
} else {
statusBarItem.hide()
}
}
}),
)
}
export function deactivate() {
clearInterval(balanceInterval)
}
// ── Helpers ───────────────────────────────────────────────────────────────────
async function showBalance(publicKey: string) {
const config = vscode.workspace.getConfiguration('echomirror')
const network = config.get<string>('network') ?? 'testnet'
const horizon = network === 'testnet'
? 'https://horizon-testnet.stellar.org'
: 'https://horizon.stellar.org'
await vscode.window.withProgress(
{ location: vscode.ProgressLocation.Notification, title: 'Fetching balance…' },
async () => {
try {
const res = await fetch(`${horizon}/accounts/${publicKey}`)
if (!res.ok) {
vscode.window.showErrorMessage(`Account not found on ${network}`)
return
}
const data = await res.json() as { balances: Array<{ asset_type: string; asset_code?: string; balance: string }> }
const xlm = data.balances.find((b) => b.asset_type === 'native')?.balance ?? '0'
const echo = data.balances.find((b) => b.asset_code === 'ECHO')?.balance ?? '0'
vscode.window.showInformationMessage(`💰 ${xlm} XLM • ${echo} ECHO (${network})`)
statusBarItem.text = `$(symbol-misc) ${parseFloat(echo).toFixed(2)} ECHO`
statusBarItem.tooltip = `${xlm} XLM • ${echo} ECHO on ${network}`
} catch (e) {
vscode.window.showErrorMessage(`Error fetching balance: ${e}`)
}
},
)
}
function updateStatusBar() {
statusBarItem.text = '$(symbol-misc) ECHO'
statusBarItem.tooltip = 'EchoMirror SDK — click to check balance'
}
function startBalancePolling() {
const config = vscode.workspace.getConfiguration('echomirror')
const key = config.get<string>('statusBarPublicKey')
if (!key) return
showBalance(key)
balanceInterval = setInterval(() => showBalance(key), 60_000)
}
function getSyncExplorerHtml(): string {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>EchoMirror Sync Explorer</title>
<style>
body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); background: var(--vscode-editor-background); padding: 20px; }
h2 { color: var(--vscode-textLink-foreground); }
.event { padding: 8px 12px; margin: 4px 0; background: var(--vscode-editor-inactiveSelectionBackground); border-radius: 4px; font-size: 12px; }
.event.ledger { border-left: 3px solid #6366f1; }
.event.tx { border-left: 3px solid #16a34a; }
.event.error { border-left: 3px solid #dc2626; }
input { background: var(--vscode-input-background); color: var(--vscode-input-foreground); border: 1px solid var(--vscode-input-border); padding: 6px 10px; border-radius: 4px; width: 100%; box-sizing: border-box; }
button { margin-top: 8px; padding: 6px 16px; background: #6366f1; color: white; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background: #4f46e5; }
#events { margin-top: 16px; max-height: 400px; overflow-y: auto; }
.status { font-size: 11px; color: var(--vscode-descriptionForeground); margin-top: 8px; }
</style>
</head>
<body>
<h2>Blockchain Sync Explorer</h2>
<p style="font-size:13px">Watch real-time Stellar transactions for any account.</p>
<input id="address" placeholder="Stellar public key (G...)" />
<button id="watch-btn">Watch Account</button>
<button id="stop-btn" style="background:#6b7280;display:none">Stop</button>
<p class="status" id="status">Not watching</p>
<div id="events"></div>
<script>
let intervalId = null
let cursor = 'now'
let totalSeen = 0
const addressEl = document.getElementById('address')
const watchBtn = document.getElementById('watch-btn')
const stopBtn = document.getElementById('stop-btn')
const statusEl = document.getElementById('status')
const eventsEl = document.getElementById('events')
watchBtn.addEventListener('click', () => {
const addr = addressEl.value.trim()
if (!addr.startsWith('G') || addr.length !== 56) {
statusEl.textContent = '❌ Invalid Stellar address'
return
}
cursor = 'now'
totalSeen = 0
eventsEl.innerHTML = ''
watchBtn.style.display = 'none'
stopBtn.style.display = ''
statusEl.textContent = 'Watching ' + addr.slice(0, 8) + '...'
poll(addr)
intervalId = setInterval(() => poll(addr), 5000)
})
stopBtn.addEventListener('click', () => {
clearInterval(intervalId)
watchBtn.style.display = ''
stopBtn.style.display = 'none'
statusEl.textContent = 'Stopped. Saw ' + totalSeen + ' ledger records.'
})
async function poll(addr) {
try {
const url = 'https://horizon-testnet.stellar.org/accounts/' + addr + '/transactions?limit=10&order=asc&cursor=' + cursor
const res = await fetch(url)
const data = await res.json()
const records = data._embedded?.records ?? []
for (const r of records) {
totalSeen++
cursor = r.paging_token
const div = document.createElement('div')
div.className = 'event ledger'
div.textContent = '📦 Ledger ' + r.ledger + ' • ' + r.hash.slice(0, 16) + '… • ' + new Date(r.created_at).toLocaleTimeString()
eventsEl.prepend(div)
}
statusEl.textContent = 'Watching • ' + totalSeen + ' records seen'
} catch (e) {
const div = document.createElement('div')
div.className = 'event error'
div.textContent = '⚠️ ' + e.toString()
eventsEl.prepend(div)
}
}
</script>
</body>
</html>`
}