-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
1239 lines (1130 loc) · 60.1 KB
/
app.js
File metadata and controls
1239 lines (1130 loc) · 60.1 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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Oikos App — Pear Runtime Frontend (Phase 2 Refactor)
*
* 4 tabs: Feed, Wealth, Swarm, Policy Engine
* Portfolio chart, markdown chat, board-style swarm, bottom bar
*/
/* global Pear */
var API_BASE = '' // set during waitForServer bootstrap
var currentView = 'feed'
var feedMode = 'activity'
var chatMessageCount = 0
var swarmSearchQuery = ''
var swarmActiveTag = null
var lastSwarmData = null
// ── Asset constants ──
var COLORS = { USDT: '#2d8a4e', XAUT: '#b8860b', USAT: '#2874a6', BTC: '#d35400', ETH: '#148f77' }
var DOTS = { USDT: 'c-usdt', XAUT: 'c-xaut', USAT: 'c-usat', BTC: 'c-btc', ETH: 'c-eth' }
var PRICES = { USDT: 1, USAT: 1, XAUT: 2400, BTC: 60000, ETH: 3000 }
var DECS = { USDT: 6, USAT: 6, XAUT: 6, BTC: 8, ETH: 18 }
var DOT_COLORS = {
BTC: '#d35400', ETH: '#148f77', XAUT: '#b8860b', USDT: '#2d8a4e', USAT: '#2874a6',
SOL: '#9945ff', XRP: '#23292f', ADA: '#0033ad', DOT: '#e6007a', AVAX: '#e84142',
LINK: '#2a5ada', LTC: '#bfbbbb', UNI: '#ff007a', AAVE: '#b6509e', NEAR: '#00c08b',
ARB: '#28a0f0', SUI: '#4da2ff', APT: '#00b4d8', TON: '#0098ea', DOGE: '#c2a633',
SHIB: '#ffa409', TRX: '#ff0013', FIL: '#0090ff'
}
var ASSET_NAMES = {
BTC: 'Bitcoin', ETH: 'Ethereum', XAUT: 'Tether Gold', USDT: 'Tether USD', USAT: 'Tether US',
SOL: 'Solana', XRP: 'Ripple', ADA: 'Cardano', DOT: 'Polkadot', AVAX: 'Avalanche',
LINK: 'Chainlink', LTC: 'Litecoin', UNI: 'Uniswap', AAVE: 'Aave', NEAR: 'NEAR',
ARB: 'Arbitrum', SUI: 'Sui', APT: 'Aptos', TON: 'Toncoin', DOGE: 'Dogecoin',
SHIB: 'Shiba Inu', TRX: 'TRON', FIL: 'Filecoin'
}
// ── API ──
async function api (path) {
try { var r = await fetch(API_BASE + path); return await r.json() } catch (e) { return null }
}
async function apiPost (path, body) {
try { var r = await fetch(API_BASE + path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); return await r.json() } catch (e) { return null }
}
// ── Prices ──
async function fetchPrices () {
var data = await api('/api/prices')
if (data && data.prices) data.prices.forEach(function (p) { if (p.symbol && p.priceUsd !== undefined) PRICES[p.symbol] = p.priceUsd })
}
// ── Portfolio calc ──
function allocate (balances) {
var items = balances.map(function (b) {
var raw = parseInt(b.balance || '0', 10)
var d = DECS[b.symbol] || 18
var human = raw / Math.pow(10, d)
var usd = human * (PRICES[b.symbol] || 0)
return { symbol: b.symbol, chain: b.chain, formatted: b.formatted, usd: usd }
})
var total = items.reduce(function (s, e) { return s + e.usd }, 0)
return {
total: total,
items: items.map(function (e) {
return { symbol: e.symbol, chain: e.chain, formatted: e.formatted, usd: e.usd, pct: total > 0 ? (e.usd / total * 100).toFixed(1) : '0.0' }
})
}
}
// ── Navigation ──
function switchView (name) {
currentView = name
document.querySelectorAll('.nav-item').forEach(function (el) { el.classList.toggle('active', el.dataset.view === name) })
document.querySelectorAll('.view').forEach(function (el) { el.classList.toggle('active', el.id === 'view-' + name) })
updateCurrentView()
}
document.querySelectorAll('.nav-item').forEach(function (el) {
el.addEventListener('click', function () { switchView(el.dataset.view) })
})
// ── Market Prices modal ──
document.getElementById('w-prices-btn').addEventListener('click', function () {
document.getElementById('prices-modal').classList.remove('hidden')
})
document.getElementById('prices-modal-close').addEventListener('click', function () {
document.getElementById('prices-modal').classList.add('hidden')
})
document.getElementById('prices-modal').addEventListener('click', function (e) {
if (e.target === this) this.classList.add('hidden')
})
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') {
var modal = document.getElementById('prices-modal')
if (modal && !modal.classList.contains('hidden')) modal.classList.add('hidden')
}
})
// ── Copy wallet address ──
function copyAddr (btn) {
var addr = btn.getAttribute('data-addr')
if (!addr) return
navigator.clipboard.writeText(addr).then(function () {
btn.classList.add('copied')
var orig = btn.textContent
btn.textContent = 'Copied!'
setTimeout(function () { btn.classList.remove('copied'); btn.textContent = orig }, 1500)
})
}
// ── Feed mode toggle ──
document.querySelectorAll('.feed-toggle').forEach(function (el) {
el.addEventListener('click', function () {
feedMode = el.dataset.mode
document.querySelectorAll('.feed-toggle').forEach(function (t) { t.classList.toggle('active', t.dataset.mode === feedMode) })
document.getElementById('feed-activity').classList.toggle('hidden', feedMode !== 'activity')
document.getElementById('feed-audit').classList.toggle('hidden', feedMode !== 'audit')
if (feedMode === 'audit') updateAudit()
})
})
// ── Helpers ──
function opBadge (type) {
var t = (type || 'payment').toLowerCase()
var cls = 'badge-' + t
if (!['badge-payment', 'badge-swap', 'badge-bridge', 'badge-yield', 'badge-feedback'].includes(cls)) cls = 'badge-payment'
return '<span class="op-badge ' + cls + '">' + t.toUpperCase() + '</span>'
}
function setDot (id, on) { var el = document.getElementById(id); if (el) el.className = 'cs-dot ' + (on ? 'on' : 'off') }
function escapeHtml (str) { var d = document.createElement('div'); d.textContent = str; return d.innerHTML }
function timeAgo (ts) {
var diff = Date.now() - new Date(ts).getTime()
if (diff < 60000) return Math.floor(diff / 1000) + 's ago'
if (diff < 3600000) return Math.floor(diff / 60000) + 'm ago'
if (diff < 86400000) return Math.floor(diff / 3600000) + 'h ago'
return Math.floor(diff / 86400000) + 'd ago'
}
// ── Markdown renderer (lightweight, no deps) ──
function renderMarkdown (text) {
var html = escapeHtml(text)
// Code blocks (inline)
html = html.replace(/`([^`]+)`/g, '<code>$1</code>')
// Bold
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
// Italic
html = html.replace(/\*([^*]+)\*/g, '<em>$1</em>')
// Numbered lists: "1. item" at start of line
html = html.replace(/^(\d+)\.\s+(.+)$/gm, '<li>$2</li>')
// Bullet lists: "- item" at start of line
html = html.replace(/^[-*]\s+(.+)$/gm, '<li>$1</li>')
// Wrap consecutive <li> in <ol> or <ul>
html = html.replace(/((?:<li>.*<\/li>\n?)+)/g, '<ul>$1</ul>')
// Line breaks
html = html.replace(/\n/g, '<br>')
// Clean up <br> inside lists
html = html.replace(/<br><ul>/g, '<ul>').replace(/<\/ul><br>/g, '</ul>')
return html
}
var CHAIN_DISPLAY = {
bitcoin: { name: 'Bitcoin', icon: '\u20bf' },
spark: { name: 'Spark (Lightning)', icon: '\u26a1' },
ethereum: { name: 'Ethereum (Sepolia)', icon: '\u039e' },
arbitrum: { name: 'Arbitrum (Sepolia)', icon: '\u25c6' },
polygon: { name: 'Polygon', icon: '\u2b21' }
}
function renderAssetList (id, items) {
var el = document.getElementById(id); if (!el) return
var grouped = {}
items.forEach(function (i) {
if (!grouped[i.symbol]) grouped[i.symbol] = { symbol: i.symbol, chains: [], usd: 0, formatted: 0, pct: 0 }
grouped[i.symbol].chains.push(i.chain)
grouped[i.symbol].usd += i.usd
grouped[i.symbol].formatted = (parseFloat(grouped[i.symbol].formatted) + parseFloat(i.formatted)).toFixed(i.symbol === 'BTC' ? 6 : 2)
grouped[i.symbol].pct = (parseFloat(grouped[i.symbol].pct) + parseFloat(i.pct)).toFixed(1)
})
var sorted = Object.values(grouped).sort(function (a, b) { return b.usd - a.usd })
el.innerHTML = sorted.map(function (i) {
var chains = i.chains.filter(function (v, idx, a) { return a.indexOf(v) === idx }).join(', ')
return '<div class="asset-row"><div class="asset-left"><span class="asset-dot ' + (DOTS[i.symbol] || '') + '" style="background:' + (DOT_COLORS[i.symbol] || '#999') + ';"></span><div><span class="asset-symbol">' + i.symbol + '</span><span class="asset-chain">' + chains + '</span></div></div><div class="asset-right"><span class="asset-amount">' + i.formatted + '</span><br><span class="asset-usd">$' + i.usd.toFixed(2) + '</span> <span class="asset-pct">' + i.pct + '%</span></div></div>'
}).join('')
}
function showResult (id, text, isError) {
var el = document.getElementById(id); el.classList.remove('hidden')
el.textContent = text; el.style.borderColor = isError ? 'var(--red)' : 'var(--green)'
}
// ── Bottom bar (addresses popup is event-driven, no clock needed) ──
var heldAmounts = {}
/* ═══ UPDATE: Feed ═══ */
async function updateFeed () {
var [state, health, valuation, swarm, audit] = await Promise.all([
api('/api/state'), api('/api/health'), api('/api/valuation'), api('/api/swarm'), api('/api/audit?limit=30')
])
if (health) {
setDot('td-wallet', health.walletConnected)
setDot('td-swarm', health.swarmEnabled)
setDot('td-companion', health.companionConnected)
}
if (valuation && valuation.totalUsd > 0) document.getElementById('ss-portfolio').textContent = '$' + valuation.totalUsd.toFixed(0)
if (swarm && swarm.enabled) {
document.getElementById('ss-peers').textContent = (swarm.boardPeers || []).length
if (swarm.identity && swarm.identity.name) {
var sw = document.getElementById('ss-swarm-wrap')
if (sw) { sw.classList.remove('hidden'); document.getElementById('ss-swarm-name').textContent = swarm.identity.name }
}
}
if (feedMode === 'activity') {
var feedItems = []
if (audit && audit.entries) {
audit.entries.filter(function (e) { return e.type !== 'proposal_received' }).forEach(function (e) {
var type = (e.proposalType || e.type || 'system').toLowerCase()
// AuditEntry uses .type (execution_success, policy_enforcement); ExecutionResult uses .status
var rawStatus = (e.status || (e.type === 'execution_success' ? 'executed' : e.type === 'policy_enforcement' ? 'rejected' : e.type === 'execution_failure' ? 'failed' : '') || '').toLowerCase()
// Financial verbs: outflows = SENT (red), swaps = SWAPPED (gold), failures = red
var status = rawStatus
var indicator = 'fi-financial'
if (rawStatus === 'executed') {
if (type === 'payment' || type === 'spark_send') { status = 'sent'; indicator = 'fi-rejected' } // red = outflow
else if (type === 'swap') { status = 'swapped'; indicator = 'fi-financial' } // gold = neutral exchange
else if (type === 'bridge') { status = 'bridged'; indicator = 'fi-financial' }
else if (type === 'yield' && e.proposal && e.proposal.action === 'withdraw') { status = 'withdrawn'; indicator = 'fi-success' } // green = inflow
else if (type === 'yield') { status = 'deposited'; indicator = 'fi-rejected' } // red = outflow
else { indicator = 'fi-financial' }
} else if (rawStatus === 'rejected' || rawStatus === 'failed') {
indicator = 'fi-rejected'
}
if (type === 'feedback') indicator = 'fi-system'
var amount = e.proposal ? (e.proposal.amount || '') : ''
var sym = e.proposal ? (e.proposal.symbol || '') : ''
var d = DECS[sym] || 6
var humanAmt = amount ? (parseInt(amount, 10) / Math.pow(10, d)).toFixed(d <= 6 ? 2 : 6) : ''
var summary = opBadge(type) + ' <span style="font-weight:700;">' + status.toUpperCase() + '</span>'
if (humanAmt) summary += ' ' + humanAmt + ' ' + sym
if (type === 'swap' && e.proposal) summary += ' → ' + (e.proposal.toSymbol || '?')
if (type === 'bridge' && e.proposal) summary += ' ' + (e.proposal.fromChain || '') + ' → ' + (e.proposal.toChain || '')
feedItems.push({ ts: e.timestamp || Date.now(), indicator: indicator, summary: summary, detail: e.reason || e.error || ((e.violations || []).join(', ')) || (e.txHash ? 'tx: ' + e.txHash.slice(0, 16) + '...' : '') })
})
}
if (swarm && swarm.recentEvents) {
swarm.recentEvents.slice(0, 10).forEach(function (e) {
feedItems.push({ ts: e.timestamp || Date.now(), indicator: 'fi-swarm', summary: '<span style="color:var(--blue);font-weight:700;">SWARM</span> ' + (e.summary || e.kind || 'event'), detail: '' })
})
}
feedItems.sort(function (a, b) { return new Date(b.ts) - new Date(a.ts) })
var el = document.getElementById('feed-list')
el.innerHTML = feedItems.length === 0
? '<li class="empty" style="padding:2rem;">No activity yet. Your agent will appear here when active.</li>'
: feedItems.slice(0, 40).map(function (f) {
return '<li class="feed-item"><div class="feed-indicator ' + f.indicator + '"></div><div class="feed-body"><div class="feed-summary">' + f.summary + '</div>' + (f.detail ? '<div class="feed-detail">' + escapeHtml(f.detail) + '</div>' : '') + '</div><div class="feed-time">' + timeAgo(f.ts) + '</div></li>'
}).join('')
}
}
/* ═══ UPDATE: Audit ═══ */
async function updateAudit () {
var data = await api('/api/audit?limit=100')
if (!data || !data.entries) return
document.getElementById('audit-body').innerHTML = data.entries.length === 0
? '<tr><td colspan="5" class="empty">No entries</td></tr>'
: data.entries.filter(function (e) { return e.type !== 'proposal_received' }).map(function (e) {
var time = e.timestamp ? new Date(e.timestamp).toLocaleString() : '--'
var type = e.proposalType || e.type || '--'
// AuditEntry uses .type (execution_success, policy_enforcement); ExecutionResult uses .status
var rawStatus = e.status || (e.type === 'execution_success' ? 'executed' : e.type === 'policy_enforcement' ? 'rejected' : e.type === 'execution_failure' ? 'failed' : '--')
var tl = (e.proposalType || '').toLowerCase()
var status = rawStatus
if (rawStatus === 'executed') {
if (tl === 'payment' || tl === 'spark_send') status = 'sent'
else if (tl === 'swap') status = 'swapped'
else if (tl === 'bridge') status = 'bridged'
else if (tl === 'yield' && e.proposal && e.proposal.action === 'withdraw') status = 'withdrawn'
else if (tl === 'yield') status = 'deposited'
}
// Colors: red = outflow (sent, deposited, rejected, failed), green = inflow (withdrawn), gold = neutral (swapped, bridged)
var sc = (status === 'sent' || status === 'deposited' || status === 'rejected' || status === 'failed') ? 'var(--red)'
: (status === 'withdrawn') ? 'var(--green)'
: 'var(--yellow)'
var amount = e.proposal ? (e.proposal.amount || '--') : '--'
var sym = e.proposal ? (e.proposal.symbol || '') : ''
var detail = e.reason || e.error || ((e.violations || []).join(', ')) || (e.txHash ? 'tx: ' + e.txHash.slice(0, 16) + '...' : '')
return '<tr><td style="font-size:10px;white-space:nowrap;">' + time + '</td><td>' + opBadge(type) + '</td><td style="color:' + sc + ';font-weight:700;">' + status.toUpperCase() + '</td><td>' + amount + ' ' + sym + '</td><td style="color:var(--muted);font-size:11px;">' + detail + '</td></tr>'
}).join('')
}
/* ═══ UPDATE: Wealth ═══ */
async function updateWealth () {
var [balances, valuation, priceData, audit, addrData] = await Promise.all([
api('/api/balances'), api('/api/valuation'), api('/api/prices'),
api('/api/audit?limit=20'), api('/api/addresses')
])
// Build address lookup: chain -> address
var addrLookup = {}
if (addrData && addrData.addresses) {
addrData.addresses.forEach(function (a) { if (a && a.chain) addrLookup[a.chain] = a.address })
}
// Portfolio total bar
var totalUsd = 0
var chainSet = {}
if (balances && balances.balances) {
var a = allocate(balances.balances)
a.items.forEach(function (i) {
if (!heldAmounts[i.symbol]) heldAmounts[i.symbol] = 0
heldAmounts[i.symbol] += parseFloat(i.formatted) || 0
chainSet[i.chain] = true
})
totalUsd = (valuation && valuation.totalUsd > 0) ? valuation.totalUsd : a.total
}
document.getElementById('w-portfolio-total').textContent = '$' + totalUsd.toFixed(2)
document.getElementById('w-chain-count').textContent = Object.keys(chainSet).length + ' chains'
// Group balances by chain -> wallet cards
var walletMap = {}
if (balances && balances.balances) {
var alloc = allocate(balances.balances)
alloc.items.forEach(function (i) {
if (!walletMap[i.chain]) walletMap[i.chain] = { chain: i.chain, assets: [], totalUsd: 0, address: addrLookup[i.chain] || '', txns: [] }
walletMap[i.chain].assets.push(i)
walletMap[i.chain].totalUsd += i.usd
})
}
// Assign audit transactions to wallet cards by proposal.chain
if (audit && audit.entries) {
audit.entries.filter(function (e) { return e.status === 'executed' || e.status === 'rejected' }).forEach(function (e) {
var chain = (e.proposal && e.proposal.chain) ? e.proposal.chain : 'ethereum'
if (walletMap[chain]) walletMap[chain].txns.push(e)
})
}
// Sort wallets by total USD value (highest first)
var wallets = Object.values(walletMap).sort(function (a, b) { return b.totalUsd - a.totalUsd })
// Render wallet cards
var gridEl = document.getElementById('w-wallet-grid')
if (wallets.length === 0) {
gridEl.innerHTML = '<div class="empty" style="padding:2rem;">No wallet balances found</div>'
} else {
gridEl.innerHTML = wallets.map(function (w) {
var cd = CHAIN_DISPLAY[w.chain] || { name: w.chain, icon: '\u26d3' }
var addrBtn = w.address
? '<button class="wallet-addr-btn" data-addr="' + escapeHtml(w.address) + '" onclick="copyAddr(this)">' + w.address.slice(0, 6) + '...' + w.address.slice(-4) + '</button>'
: ''
// Asset rows
var assetRows = w.assets.sort(function (a, b) { return b.usd - a.usd }).map(function (i) {
var dot = DOT_COLORS[i.symbol] || '#999'
var usdStr = i.usd >= 1 ? '$' + i.usd.toFixed(2) : i.usd > 0 ? '$' + i.usd.toFixed(4) : '$0.00'
return '<div class="wallet-asset-row">' +
'<div class="wallet-asset-left">' +
'<span class="wallet-asset-dot" style="background:' + dot + ';"></span>' +
'<span class="wallet-asset-sym">' + i.symbol + '</span>' +
'<span class="wallet-asset-amt">' + i.formatted + '</span>' +
'</div>' +
'<div class="wallet-asset-right">' +
'<span class="wallet-asset-usd">' + usdStr + '</span>' +
'<span class="wallet-asset-pct">' + i.pct + '%</span>' +
'</div>' +
'</div>'
}).join('')
// Recent transactions (max 3)
var txHtml = ''
if (w.txns.length > 0) {
var txRows = w.txns.slice(0, 3).map(function (e) {
var type = (e.proposalType || 'payment').toLowerCase()
var status = (e.status || '').toLowerCase()
var amount = e.proposal ? (e.proposal.amount || '') : ''
var sym = e.proposal ? (e.proposal.symbol || '') : ''
var d = DECS[sym] || 6
var humanAmt = amount ? (parseInt(amount, 10) / Math.pow(10, d)).toFixed(d <= 6 ? 2 : 6) : ''
var dotCls = status === 'executed' ? 'success' : 'rejected'
return '<div class="wallet-tx-row"><span class="wallet-tx-dot ' + dotCls + '"></span>' + opBadge(type) + ' ' + humanAmt + ' ' + sym + ' <span style="color:var(--dim);font-size:10px;">' + timeAgo(e.timestamp) + '</span></div>'
}).join('')
txHtml = '<div class="wallet-txns-label">Recent</div><div class="wallet-txns">' + txRows + '</div>'
}
// Funded assets shown as transactions if no audit txns
if (w.txns.length === 0 && w.assets.length > 0) {
var fundedRows = w.assets.filter(function (i) { return parseFloat(i.formatted) > 0 }).slice(0, 3).map(function (i) {
return '<div class="wallet-tx-row"><span class="wallet-tx-dot funded"></span><span style="background:#1a472a;color:#4ade80;padding:1px 5px;font-size:9px;font-weight:700;">FUNDED</span> ' + i.formatted + ' ' + i.symbol + '</div>'
}).join('')
if (fundedRows) txHtml = '<div class="wallet-txns-label">Recent</div><div class="wallet-txns">' + fundedRows + '</div>'
}
return '<div class="wallet-card">' +
'<div class="wallet-card-header">' +
'<div class="wallet-card-title"><span class="wallet-card-icon">' + cd.icon + '</span> ' + cd.name + '</div>' +
addrBtn +
'</div>' +
'<div class="wallet-assets">' + assetRows + '</div>' +
txHtml +
'</div>'
}).join('')
// AAVE Lending card (conditional — only if yield operations exist)
if (audit && audit.entries) {
var yieldOps = audit.entries.filter(function (e) {
return (e.proposalType === 'yield') && e.proposal && (e.status === 'executed' || e.status === 'rejected')
})
if (yieldOps.length > 0) {
var yieldRows = yieldOps.slice(0, 3).map(function (e) {
var action = e.proposal.action || 'deposit'
var sym = e.proposal.symbol || ''
var amount = e.proposal.amount || ''
var d = DECS[sym] || 6
var humanAmt = amount ? (parseInt(amount, 10) / Math.pow(10, d)).toFixed(d <= 6 ? 2 : 6) : ''
var dotCls = e.status === 'executed' ? 'success' : 'rejected'
return '<div class="wallet-tx-row"><span class="wallet-tx-dot ' + dotCls + '"></span>' + opBadge('yield') + ' ' + action + ' ' + humanAmt + ' ' + sym + '</div>'
}).join('')
var protocol = (yieldOps[0].proposal && yieldOps[0].proposal.protocol) || 'AAVE'
gridEl.innerHTML += '<div class="wallet-card">' +
'<div class="wallet-card-header"><div class="wallet-card-title"><span class="wallet-card-icon">\ud83c\udfe6</span> ' + protocol.toUpperCase() + ' Lending</div></div>' +
'<div class="wallet-txns-label">Operations</div><div class="wallet-txns">' + yieldRows + '</div>' +
'</div>'
}
}
}
// Live prices — rendered into modal grid (same logic as before)
if (priceData && priceData.prices) {
var held = {}
if (valuation && valuation.assets) valuation.assets.forEach(function (a) { held[(a.symbol || '').toUpperCase()] = true })
var sorted = priceData.prices.slice().sort(function (a, b) {
var aH = held[(a.symbol || '').toUpperCase()] ? 1 : 0, bH = held[(b.symbol || '').toUpperCase()] ? 1 : 0
if (aH !== bH) return bH - aH; return (b.priceUsd || 0) - (a.priceUsd || 0)
})
document.getElementById('w-prices').innerHTML = sorted.map(function (p) {
var sym = (p.symbol || '').toUpperCase()
var price = p.priceUsd || 0
var dot = DOT_COLORS[sym] || '#999'
var name = ASSET_NAMES[sym] || sym
var priceStr = price >= 1000 ? '$' + price.toLocaleString('en-US', { maximumFractionDigits: 0 }) : price >= 1 ? '$' + price.toFixed(2) : '$' + price.toFixed(6)
return '<div class="price-row"><div class="price-left"><span class="price-dot" style="background:' + dot + ';"></span><span class="price-sym">' + sym + '</span><span class="price-name">' + name + '</span></div><div class="price-right"><span class="price-usd">' + priceStr + '</span></div></div>'
}).join('')
}
}
/* ═══ UPDATE: Swarm ═══ */
async function updateSwarm () {
var [swarm, econ] = await Promise.all([api('/api/swarm'), api('/api/economics')])
if (!swarm || !swarm.enabled) {
document.getElementById('swarm-disabled').classList.remove('hidden')
document.getElementById('swarm-content').classList.add('hidden')
return
}
document.getElementById('swarm-disabled').classList.add('hidden')
document.getElementById('swarm-content').classList.remove('hidden')
lastSwarmData = swarm
if (swarm.identity) {
document.getElementById('sw-rep-off').textContent = ((swarm.identity.reputation || 0) * 100).toFixed(0) + '%'
var onChain = swarm.identity.onChainReputation
document.getElementById('sw-rep-on').textContent = onChain && onChain.averageScore != null ? ((onChain.averageScore * 100).toFixed(0) + '%') : '--'
document.getElementById('sw-erc8004').textContent = swarm.identity.erc8004AgentId ? '#' + swarm.identity.erc8004AgentId : '--'
}
var peers = swarm.boardPeers || []
document.getElementById('sw-peer-count').textContent = peers.length
// Economics
if (econ && econ.enabled && econ.economics) {
var e = econ.economics
document.getElementById('sw-econ-rev').textContent = '$' + (Number(e.totalRevenue) || 0).toFixed(0)
document.getElementById('sw-econ-cost').textContent = '$' + (Number(e.totalCosts) || 0).toFixed(0)
// Deals: count open rooms vs settled
var rooms = swarm.activeRooms || []
var open = rooms.filter(function (r) { return r.status !== 'settled' }).length
var closed = (e.dealsCompleted || 0)
document.getElementById('sw-deals-open').textContent = open
document.getElementById('sw-deals-closed').textContent = closed
}
// Tag cloud — collect from tags array only (don't mix in categories)
var anns = swarm.announcements || []
var tagCounts = {}
anns.forEach(function (a) {
var tags = a.tags || []
tags.forEach(function (t) { if (t) tagCounts[t] = (tagCounts[t] || 0) + 1 })
})
var tagEl = document.getElementById('sw-tags')
var tags = Object.keys(tagCounts).sort(function (a, b) { return tagCounts[b] - tagCounts[a] })
tagEl.innerHTML = tags.map(function (t) {
var cls = swarmActiveTag === t ? ' active' : ''
return '<span class="tag-pill' + cls + '" data-tag="' + t + '">' + t + ' <span class="tag-count">' + tagCounts[t] + '</span></span>'
}).join('')
tagEl.querySelectorAll('.tag-pill').forEach(function (el) {
el.addEventListener('click', function () {
swarmActiveTag = swarmActiveTag === el.dataset.tag ? null : el.dataset.tag
renderSwarmBoard(anns)
// Update tag active state
tagEl.querySelectorAll('.tag-pill').forEach(function (t) { t.classList.toggle('active', swarmActiveTag === t.dataset.tag) })
})
})
renderSwarmBoard(anns)
}
function renderSwarmBoard (anns) {
var filtered = anns.filter(function (a) {
if (swarmActiveTag && !(a.tags || []).includes(swarmActiveTag)) return false
if (swarmSearchQuery) {
var q = swarmSearchQuery.toLowerCase()
var hay = ((a.title || '') + ' ' + (a.description || '') + ' ' + (a.agentName || '') + ' ' + (a.tags || []).join(' ')).toLowerCase()
if (hay.indexOf(q) === -1) return false
}
return true
})
document.getElementById('sw-ann-count').textContent = filtered.length
var el = document.getElementById('sw-anns')
el.innerHTML = filtered.length === 0
? '<div class="empty">No announcements match</div>'
: filtered.map(function (a) {
var id = (a.id || '').slice(0, 8)
var rawCat = a.category || 'general'
var cat = (rawCat === 'seller' || rawCat === 'service' || rawCat === 'offer') ? 'seller' :
rawCat === 'auction' ? 'auction' :
rawCat === 'buyer' ? 'buyer' : 'general'
var price = (a.priceRange && a.priceRange.min !== undefined && a.priceRange.min !== 'undefined') ? a.priceRange.min + '-' + a.priceRange.max + ' ' + (a.priceRange.symbol || '') : ''
var tagsHtml = (a.tags || []).map(function (t) { return '<span class="ann-tag" data-tag="' + t + '">' + t + '</span>' }).join('')
var rep = a.reputation ? ((a.reputation * 100).toFixed(0) + '%') : ''
return '<div class="ann-item">' +
'<div class="ann-top"><div class="ann-title-row"><span class="ann-title">' + escapeHtml(a.title || 'Untitled') + '</span><span class="ann-id">' + id + '</span></div><span class="ann-cat cat-' + cat + '">' + cat.toUpperCase() + '</span></div>' +
(a.description ? '<div class="ann-desc">' + escapeHtml(a.description).slice(0, 200) + '</div>' : '') +
(tagsHtml ? '<div class="ann-tags">' + tagsHtml + '</div>' : '') +
'<div class="ann-bottom"><span class="ann-agent">' + escapeHtml(a.agentName || '?') + '</span>' + (rep ? '<span class="ann-rep">' + rep + '</span>' : '') + (a.erc8004AgentId ? '<span class="erc-badge" title="ERC-8004: #' + a.erc8004AgentId + '">⛓</span>' : '') + (price ? '<span class="ann-price">' + price + '</span>' : '') + '<span>' + timeAgo(a.timestamp || Date.now()) + '</span></div>' +
'</div>'
}).join('')
}
// Swarm search
var swSearchInput = document.getElementById('sw-search')
var swSearchClear = document.getElementById('sw-search-clear')
if (swSearchInput) {
swSearchInput.addEventListener('input', function () {
swarmSearchQuery = swSearchInput.value.trim()
swSearchClear.style.display = swarmSearchQuery ? 'block' : 'none'
if (lastSwarmData) renderSwarmBoard(lastSwarmData.announcements || [])
})
}
if (swSearchClear) {
swSearchClear.addEventListener('click', function () {
swSearchInput.value = ''; swarmSearchQuery = ''
swSearchClear.style.display = 'none'
if (lastSwarmData) renderSwarmBoard(lastSwarmData.announcements || [])
})
}
/* ═══ UPDATE: Policies ═══ */
var currentPolicyRules = []
// Toggle capabilities expansion
var capToggle = document.getElementById('pol-cap-toggle')
if (capToggle) {
capToggle.addEventListener('click', function () {
var el = document.getElementById('pol-modules')
if (el) el.classList.toggle('hidden')
})
}
async function updatePolicies () {
var [pol, strats] = await Promise.all([api('/api/policies'), api('/api/strategies')])
// ── GUARDRAILS (budget-first, compact) ──
var guardrailsEl = document.getElementById('pol-guardrails')
if (pol && pol.policies && pol.policies[0]) {
var p = pol.policies[0]
var rules = p.rules || []
currentPolicyRules = rules
var state = p.state || {}
var dayTotals = state.dayTotals || {}
var sessionTotals = state.sessionTotals || {}
// Extract key values
var maxDay = 0, maxSession = 0, maxTx = 0, maxRecip = 0, cooldown = 0, confidence = 0, hourStart = 0, hourEnd = 24, tz = 'UTC'
rules.forEach(function (r) {
if (r.type === 'max_per_day' && r.amount) maxDay = Number(r.amount) / 1000000
if (r.type === 'max_per_session' && r.amount) maxSession = Number(r.amount) / 1000000
if (r.type === 'max_per_tx' && r.amount) maxTx = Number(r.amount) / 1000000
if (r.type === 'max_per_recipient_per_day' && r.amount) maxRecip = Number(r.amount) / 1000000
if (r.type === 'cooldown_seconds') cooldown = r.seconds
if (r.type === 'require_confidence') confidence = r.min
if (r.type === 'time_window') { hourStart = r.start_hour; hourEnd = r.end_hour; tz = r.timezone || 'UTC' }
})
// Calculate usage
var dayUsed = 0, sessionUsed = 0
var dayRule = rules.find(function (r) { return r.type === 'max_per_day' })
var sessionRule = rules.find(function (r) { return r.type === 'max_per_session' })
if (dayRule) dayUsed = Number(dayTotals[dayRule.symbol] || 0) / Number(dayRule.amount) * 100
if (sessionRule) sessionUsed = Number(sessionTotals[sessionRule.symbol] || 0) / Number(sessionRule.amount) * 100
function budgetColor (pct) { return pct > 80 ? 'var(--red)' : pct > 50 ? 'var(--yellow)' : 'var(--green)' }
var html = ''
// Budget bars (the hero)
if (maxDay > 0) {
var daySpent = (dayUsed / 100 * maxDay).toFixed(0)
html += '<div class="pol-budget-row"><div class="pol-budget-header"><span class="pol-budget-label">Daily Budget</span><span class="pol-budget-nums"><strong>' + daySpent + '</strong> / ' + maxDay + ' USDT</span></div><div class="pol-budget-bar"><div class="pol-budget-bar-fill" style="width:' + Math.min(100, dayUsed).toFixed(0) + '%;background:' + budgetColor(dayUsed) + ';"></div></div></div>'
}
if (maxSession > 0) {
var sessSpent = (sessionUsed / 100 * maxSession).toFixed(0)
html += '<div class="pol-budget-row"><div class="pol-budget-header"><span class="pol-budget-label">Session Budget</span><span class="pol-budget-nums"><strong>' + sessSpent + '</strong> / ' + maxSession + ' USDT</span></div><div class="pol-budget-bar"><div class="pol-budget-bar-fill" style="width:' + Math.min(100, sessionUsed).toFixed(0) + '%;background:' + budgetColor(sessionUsed) + ';"></div></div></div>'
}
// Compact rules line
var parts = []
if (maxTx > 0) parts.push('<strong>' + maxTx + '</strong> USDT/tx')
if (maxRecip > 0) parts.push('<strong>' + maxRecip + '</strong> USDT/recipient/day')
if (cooldown > 0) parts.push('<strong>' + cooldown + 's</strong> cooldown')
if (confidence > 0) parts.push('confidence ≥ <strong>' + confidence + '</strong>')
if (hourStart !== undefined) parts.push('<strong>' + hourStart + ':00–' + hourEnd + ':00</strong> ' + tz)
if (parts.length > 0) {
html += '<div class="pol-rules-line">' + parts.join('<span class="pol-rule-sep">·</span>') + '</div>'
}
guardrailsEl.innerHTML = html
// Populate edit modal (only when modal is closed — don't overwrite user input)
var modalOpen = !document.getElementById('pol-edit-modal').classList.contains('hidden')
if (!modalOpen) rules.forEach(function (r) {
if (r.type === 'max_per_tx' && r.amount) document.getElementById('pol-max-tx').value = Number(r.amount) / 1000000
if (r.type === 'max_per_day' && r.amount) document.getElementById('pol-max-day').value = Number(r.amount) / 1000000
if (r.type === 'max_per_session' && r.amount) document.getElementById('pol-max-session').value = Number(r.amount) / 1000000
if (r.type === 'max_per_recipient_per_day' && r.amount) document.getElementById('pol-max-recipient').value = Number(r.amount) / 1000000
if (r.type === 'cooldown_seconds') document.getElementById('pol-cooldown').value = r.seconds
if (r.type === 'require_confidence') document.getElementById('pol-confidence').value = r.min
if (r.type === 'time_window') { document.getElementById('pol-hour-start').value = r.start_hour; document.getElementById('pol-hour-end').value = r.end_hour }
})
if (p.name) document.getElementById('pol-name').value = p.name
}
// ── STRATEGIES ──
var stratEl = document.getElementById('pol-strategies')
if (strats && strats.strategies && strats.strategies.length > 0) {
stratEl.innerHTML = strats.strategies.map(function (s) {
var srcClass = s.source === 'purchased' ? 'strat-src-purchased' : s.source === 'agent' ? 'strat-src-agent' : 'strat-src-human'
var isPending = !s.enabled && (s.source === 'purchased' || s.source === 'agent')
var toggleCls = s.enabled ? 'strat-toggle-on' : 'strat-toggle-off'
var lines = s.content.split('\n').filter(function (l) { return l.trim() && !l.startsWith('#') && !l.startsWith('---') && !l.startsWith('enabled:') }).slice(0, 2)
var desc = lines.join(' ').slice(0, 150)
var html = '<div class="strat-item' + (isPending ? ' strat-pending' : '') + '">'
html += '<div class="strat-header"><div class="strat-left"><span class="strat-name">' + escapeHtml(s.name) + '</span><span class="strat-source ' + srcClass + '">' + s.source + '</span></div>'
html += '<div style="display:flex;align-items:center;gap:0.3rem;">'
if (!isPending) html += '<button class="strat-toggle ' + toggleCls + '" data-id="' + escapeHtml(s.id) + '" data-enabled="' + (s.enabled ? 'true' : 'false') + '">' + (s.enabled ? 'ON' : 'OFF') + '</button>'
html += '<button class="strat-action-btn strat-edit-btn" data-filename="' + escapeHtml(s.filename) + '" data-name="' + escapeHtml(s.id) + '">EDIT</button>'
html += '<button class="strat-delete" data-id="' + escapeHtml(s.id) + '" title="Delete strategy">DEL</button>'
html += '</div></div>'
if (desc) html += '<div class="strat-desc">' + escapeHtml(desc) + '</div>'
if (isPending) {
html += '<div class="strat-approval-btns"><button class="strat-approve" data-id="' + escapeHtml(s.id) + '">Approve</button><button class="strat-reject" data-id="' + escapeHtml(s.id) + '">Reject</button></div>'
}
html += '</div>'
return html
}).join('')
} else {
stratEl.innerHTML = '<div class="empty">No strategies loaded. Add one to guide your agent\'s behavior.</div>'
}
// ── CAPABILITIES (compact) ──
var modEl = document.getElementById('pol-modules')
var modCount = document.getElementById('pol-mod-count')
if (strats && strats.modules && strats.modules.length > 0) {
modCount.textContent = strats.modules.length
// Short names: strip "— Oikos Policy Engine Skill" suffix
modEl.innerHTML = strats.modules.map(function (m) {
var short = (m.name || m.filename).replace(/\s*[—\-]\s*Oikos Policy Engine Skill/i, '').trim()
return '<span class="pol-mod-tag">' + escapeHtml(short) + '</span>'
}).join('')
} else {
modCount.textContent = '0'
modEl.innerHTML = ''
}
}
/* ═══ Settings ═══ */
async function updateSettings () {
var health = await api('/api/health')
if (!health) return
document.getElementById('settings-content').innerHTML = '<div style="font-size:12px;color:var(--muted);line-height:2;">' +
'<strong>Wallet:</strong> ' + (health.walletConnected ? '<span style="color:var(--green)">Connected</span>' : '<span style="color:var(--red)">Disconnected</span>') + '<br>' +
'<strong>Swarm:</strong> ' + (health.swarmEnabled ? 'Enabled' : 'Disabled') + '<br>' +
'<strong>Agent:</strong> ' + (health.companionConnected ? 'Connected' : 'Disconnected') + '<br>' +
'<strong>Events:</strong> ' + (health.eventsBuffered || 0) + '</div>'
}
/* ═══ CHAT ═══ */
function appendChatMsg (text, from, timestamp) {
var mc = document.getElementById('chat-messages')
var div = document.createElement('div')
var t = new Date(timestamp)
var timeStr = t.toLocaleTimeString() + ' | ' + t.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
if (from === 'human') {
div.className = 'chat-msg human'
div.innerHTML = '<div class="chat-msg-header"><span>You</span><span>' + timeStr + '</span></div><div class="chat-bubble">' + escapeHtml(text) + '</div>'
} else {
div.className = 'chat-msg agent'
div.innerHTML = '<div class="chat-msg-header"><span>Agent</span><span>' + timeStr + '</span></div><div class="chat-bubble">' + renderMarkdown(text) + '</div>'
}
mc.appendChild(div)
mc.scrollTop = mc.scrollHeight
}
async function updateChat () {
var data = await api('/api/agent/chat/history?limit=50')
if (!data || !data.messages) return
if (data.messages.length > chatMessageCount) {
data.messages.slice(chatMessageCount).forEach(function (msg) { appendChatMsg(msg.text, msg.from, msg.timestamp) })
chatMessageCount = data.messages.length
}
}
async function sendInstruction () {
var input = document.getElementById('chat-input')
var text = input.value.trim(); if (!text) return
var btn = document.getElementById('chat-send')
btn.disabled = true; btn.textContent = '...'; input.value = ''
appendChatMsg(text, 'human', Date.now())
chatMessageCount++
var result = await apiPost('/api/agent/chat', { message: text, from: 'companion' })
btn.disabled = false; btn.textContent = 'Send'
if (result && result.reply) { appendChatMsg(result.reply, 'agent', Date.now()); chatMessageCount++ }
else if (result && result.error) { appendChatMsg('[Error: ' + result.error + ']', 'agent', Date.now()); chatMessageCount++ }
else { appendChatMsg('[No response]', 'agent', Date.now()); chatMessageCount++ }
input.focus()
}
document.getElementById('chat-send').addEventListener('click', sendInstruction)
document.getElementById('chat-input').addEventListener('keydown', function (e) {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendInstruction() }
})
/* ═══ Modals ═══ */
var manualSendBtn = document.getElementById('manual-send-btn')
if (manualSendBtn) manualSendBtn.addEventListener('click', function () { document.getElementById('send-modal').classList.remove('hidden') })
document.getElementById('send-modal-close').addEventListener('click', function () { document.getElementById('send-modal').classList.add('hidden') })
document.getElementById('pay-btn').addEventListener('click', async function () {
var to = document.getElementById('pay-to').value.trim()
var amount = document.getElementById('pay-amount').value
if (!to || !amount) { showResult('pay-result', 'Fill in recipient and amount.', true); return }
var btn = document.getElementById('pay-btn'); btn.disabled = true; btn.textContent = 'SENDING...'
var result = await apiPost('/api/companion/propose', { type: 'payment', to: to, amount: amount, symbol: document.getElementById('pay-symbol').value, chain: document.getElementById('pay-chain').value, reason: document.getElementById('pay-reason').value.trim() || 'companion' })
btn.disabled = false; btn.textContent = 'SEND'
if (result) showResult('pay-result', JSON.stringify(result, null, 2), result.status === 'rejected' || result.status === 'failed')
else showResult('pay-result', 'Failed.', true)
})
document.getElementById('settings-btn').addEventListener('click', function () { document.getElementById('settings-modal').classList.remove('hidden'); updateSettings() })
document.getElementById('settings-modal-close').addEventListener('click', function () { document.getElementById('settings-modal').classList.add('hidden') })
// Policy edit modal
document.getElementById('pol-edit-btn').addEventListener('click', function () { document.getElementById('pol-edit-modal').classList.remove('hidden') })
document.getElementById('pol-edit-close').addEventListener('click', function () { document.getElementById('pol-edit-modal').classList.add('hidden') })
document.getElementById('pol-cancel-btn').addEventListener('click', function () { document.getElementById('pol-edit-modal').classList.add('hidden') })
document.getElementById('pol-save-btn').addEventListener('click', async function () {
var btn = document.getElementById('pol-save-btn')
btn.disabled = true; btn.textContent = 'APPLYING...'
var rules = [
{ type: 'max_per_tx', amount: String(Math.round(Number(document.getElementById('pol-max-tx').value) * 1000000)), symbol: 'USDT' },
{ type: 'max_per_session', amount: String(Math.round(Number(document.getElementById('pol-max-session').value) * 1000000)), symbol: 'USDT' },
{ type: 'max_per_day', amount: String(Math.round(Number(document.getElementById('pol-max-day').value) * 1000000)), symbol: 'USDT' },
{ type: 'max_per_recipient_per_day', amount: String(Math.round(Number(document.getElementById('pol-max-recipient').value) * 1000000)), symbol: 'USDT' },
{ type: 'cooldown_seconds', seconds: Number(document.getElementById('pol-cooldown').value) },
{ type: 'require_confidence', min: Number(document.getElementById('pol-confidence').value) },
{ type: 'time_window', start_hour: Number(document.getElementById('pol-hour-start').value), end_hour: Number(document.getElementById('pol-hour-end').value), timezone: 'UTC' }
]
var result = await apiPost('/api/policies', { rules: rules, name: document.getElementById('pol-name').value })
btn.disabled = false; btn.textContent = 'Apply & Restart Wallet'
if (result && result.success) {
showResult('pol-save-result', 'Policy updated! Restart wallet to enforce new rules.', false)
setTimeout(function () { document.getElementById('pol-edit-modal').classList.add('hidden') }, 2000)
updatePolicies()
} else {
showResult('pol-save-result', result ? result.error : 'Failed to update policy', true)
}
})
// Strategy add modal — prefill with YAML frontmatter template
document.getElementById('strat-add-btn').addEventListener('click', function () {
document.getElementById('strat-name').value = ''
var now = new Date().toISOString().replace(/\.\d+Z$/, 'Z')
document.getElementById('strat-content').value = '---\nenabled: true\nsource: human\nversion: 1.0\ncreated_at: ' + now + '\ntags: []\n---\n\n# Strategy Title\n\n'
document.getElementById('strat-add-modal').classList.remove('hidden')
})
// Strategy edit (delegated click on dynamic buttons)
document.addEventListener('click', function (e) {
var btn = e.target.closest('.strat-edit-btn')
if (!btn) return
var filename = btn.dataset.filename
var name = btn.dataset.name
// Fetch the full content from API
api('/api/strategies').then(function (data) {
if (!data || !data.strategies) return
var strat = data.strategies.find(function (s) { return s.filename === filename || s.id === name })
if (!strat) return
document.getElementById('strat-name').value = strat.id || strat.filename.replace('.md', '')
document.getElementById('strat-content').value = strat.content
document.getElementById('strat-add-modal').classList.remove('hidden')
})
})
document.getElementById('strat-add-close').addEventListener('click', function () { document.getElementById('strat-add-modal').classList.add('hidden') })
document.getElementById('strat-cancel-btn').addEventListener('click', function () { document.getElementById('strat-add-modal').classList.add('hidden') })
document.getElementById('strat-save-btn').addEventListener('click', async function () {
var name = document.getElementById('strat-name').value.trim()
var content = document.getElementById('strat-content').value.trim()
if (!name || !content) { showResult('strat-save-result', 'Name and content required', true); return }
var btn = document.getElementById('strat-save-btn')
btn.disabled = true; btn.textContent = 'SAVING...'
var result = await apiPost('/api/strategies', { filename: name, content: content })
btn.disabled = false; btn.textContent = 'Save Strategy'
if (result && result.success) {
showResult('strat-save-result', 'Strategy saved: ' + result.filename, false)
document.getElementById('strat-name').value = ''
document.getElementById('strat-content').value = ''
setTimeout(function () { document.getElementById('strat-add-modal').classList.add('hidden') }, 1500)
updatePolicies()
} else {
showResult('strat-save-result', result ? result.error : 'Failed to save', true)
}
})
document.querySelectorAll('.modal-overlay').forEach(function (el) {
el.addEventListener('click', function (e) { if (e.target === el) el.classList.add('hidden') })
})
// Strategy toggle (delegated — ON/OFF)
document.addEventListener('click', function (e) {
var toggle = e.target.closest('.strat-toggle')
if (!toggle) return
e.stopPropagation()
var id = toggle.dataset.id
var currentlyEnabled = toggle.dataset.enabled === 'true'
var newEnabled = !currentlyEnabled
// Optimistic UI
toggle.className = 'strat-toggle ' + (newEnabled ? 'strat-toggle-on' : 'strat-toggle-off')
toggle.dataset.enabled = newEnabled ? 'true' : 'false'
toggle.textContent = newEnabled ? 'ON' : 'OFF'
apiPost('/api/strategies/toggle', { filename: id, enabled: newEnabled }).then(function (result) {
if (!result || !result.success) {
toggle.className = 'strat-toggle ' + (currentlyEnabled ? 'strat-toggle-on' : 'strat-toggle-off')
toggle.dataset.enabled = currentlyEnabled ? 'true' : 'false'
toggle.textContent = currentlyEnabled ? 'ON' : 'OFF'
}
updatePolicies()
})
})
// Strategy approve (delegated) — enable the agent-proposed strategy
document.addEventListener('click', function (e) {
var btn = e.target.closest('.strat-approve')
if (!btn) return
e.stopPropagation()
var id = btn.dataset.id
btn.textContent = '...'
btn.disabled = true
apiPost('/api/strategies/toggle', { filename: id, enabled: true }).then(function (result) {
if (result && result.success) {
updatePolicies()
} else {
btn.textContent = 'Approve'
btn.disabled = false
}
})
})
// Strategy reject (delegated) — delete the agent-proposed strategy
document.addEventListener('click', function (e) {
var btn = e.target.closest('.strat-reject')
if (!btn) return
e.stopPropagation()
var id = btn.dataset.id
btn.textContent = '...'
btn.disabled = true
apiPost('/api/strategies/delete', { filename: id }).then(function (result) {
if (result && result.success) {
updatePolicies()
} else {
btn.textContent = 'Reject'
btn.disabled = false
}
})
})
// Strategy delete (delegated)
document.addEventListener('click', function (e) {
var btn = e.target.closest('.strat-delete')
if (!btn) return
var id = btn.dataset.id
if (!confirm('Delete strategy "' + id + '"? This cannot be undone.')) return
apiPost('/api/strategies/delete', { filename: id }).then(function (result) {
if (result && result.success) updatePolicies()
})
})
// Auth bar collapse/expand
document.getElementById('auth-bar').addEventListener('click', function () {
var expand = document.getElementById('auth-expand')
var chevron = document.getElementById('auth-chevron')
expand.classList.toggle('hidden')
chevron.classList.toggle('open')
})
// Address popup (bottom bar)
document.getElementById('bb-addr-label').addEventListener('click', function () {
var popup = document.getElementById('bb-addr-popup')
if (!popup.classList.contains('hidden')) { popup.classList.add('hidden'); return }
// Fetch addresses
api('/api/addresses').then(function (data) {
if (!data || !data.addresses || data.addresses.length === 0) {
popup.innerHTML = '<div style="font-size:10px;color:var(--dim);padding:0.3rem;">No addresses available</div>'
} else {
popup.innerHTML = data.addresses.map(function (a) {
var short = a.address.length > 20 ? a.address.slice(0, 10) + '...' + a.address.slice(-8) : a.address
return '<div class="bb-addr-row">' +
'<span class="bb-addr-chain">' + escapeHtml(a.chain) + '</span>' +
'<span class="bb-addr-val" title="' + escapeHtml(a.address) + '">' + short + '</span>' +
'<button class="bb-addr-copy" data-addr="' + escapeHtml(a.address) + '">COPY</button>' +
'</div>'
}).join('')
}
popup.classList.remove('hidden')
})
})
// Close address popup when clicking outside
document.addEventListener('click', function (e) {
var popup = document.getElementById('bb-addr-popup')
if (!popup.classList.contains('hidden') && !e.target.closest('#bb-addresses')) {
popup.classList.add('hidden')
}
})
// Copy address
document.addEventListener('click', function (e) {
var btn = e.target.closest('.bb-addr-copy')
if (!btn) return
var addr = btn.dataset.addr
if (navigator.clipboard) {
navigator.clipboard.writeText(addr).then(function () {
btn.textContent = 'OK'; btn.classList.add('copied')
setTimeout(function () { btn.textContent = 'COPY'; btn.classList.remove('copied') }, 1500)
})
}
})
/* ═══ PASSPHRASE AUTH ═══ */
// Update auth UI in Policy Engine tab
async function updateAuthUI () {
var data = await api('/api/auth/status')
if (!data) return
var badge = document.getElementById('auth-badge')
var enableBtn = document.getElementById('auth-enable-btn')
var disableBtn = document.getElementById('auth-disable-btn')
var ppInput = document.getElementById('auth-passphrase')
if (data.enabled) {
badge.textContent = data.authenticated ? 'ON' : 'LOCKED'
badge.style.color = data.authenticated ? 'var(--green)' : 'var(--yellow)'
enableBtn.classList.add('hidden')
disableBtn.classList.remove('hidden')
ppInput.placeholder = 'Current password to disable'
document.getElementById('auth-threshold').value = data.threshold
document.getElementById('auth-timeout').value = data.timeoutMinutes
} else {
badge.textContent = 'OFF'
badge.style.color = 'var(--dim)'
enableBtn.classList.remove('hidden')
disableBtn.classList.add('hidden')
ppInput.placeholder = 'Min 4 chars'
}
}
// Enable auth
document.getElementById('auth-enable-btn').addEventListener('click', async function () {
var pp = document.getElementById('auth-passphrase').value
var threshold = Number(document.getElementById('auth-threshold').value) || 100
var timeout = Number(document.getElementById('auth-timeout').value) || 15
if (!pp || pp.length < 4) { showResult('auth-result', 'Passphrase must be at least 4 characters', true); return }
var result = await apiPost('/api/auth/setup', { passphrase: pp, threshold: threshold, timeoutMinutes: timeout })
if (result && result.success) {