-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
367 lines (341 loc) · 17.4 KB
/
Copy pathindex.html
File metadata and controls
367 lines (341 loc) · 17.4 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Plinth — capital layer for AI trading agents on Arc</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
:root {
--bg: #0f1221;
--bg2: #161a2e;
--fg: #ebebf0;
--dim: #aab1c8;
--accent: #ffc850;
--highlight: #6ec8ff;
--green: #6edca8;
--red: #eb7070;
--border: rgba(255,255,255,0.08);
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--fg);
font: 15px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}
header { padding: 32px 40px; border-bottom: 1px solid var(--border); }
header h1 { margin: 0 0 6px 0; font-size: 28px; }
header p.tag { color: var(--dim); margin: 0; }
header .meta { color: var(--dim); font-size: 12px; margin-top: 12px; font-family: ui-monospace, monospace; }
header a { color: var(--highlight); text-decoration: none; }
main { padding: 24px 40px 80px; max-width: 1200px; margin: 0 auto; }
h2 { font-size: 18px; margin: 32px 0 12px; }
.row { display: flex; gap: 12px; margin-bottom: 16px; flex-wrap: wrap; }
button { background: var(--bg2); color: var(--fg); border: 1px solid var(--border); padding: 8px 14px; border-radius: 6px; cursor: pointer; font: inherit; }
button:hover { border-color: var(--accent); }
button.primary { background: var(--accent); color: #1a1a2e; font-weight: 600; border-color: var(--accent); }
input { background: var(--bg2); color: var(--fg); border: 1px solid var(--border); padding: 8px 10px; border-radius: 6px; font: inherit; }
table { width: 100%; border-collapse: collapse; margin-top: 8px; }
th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid var(--border); }
th { font-size: 12px; text-transform: uppercase; color: var(--dim); letter-spacing: 0.5px; }
td.mono { font-family: ui-monospace, monospace; font-size: 13px; }
td a { color: var(--highlight); text-decoration: none; }
.pill { padding: 2px 8px; border-radius: 10px; font-size: 11px; }
.pill-active { background: rgba(110, 220, 168, 0.15); color: var(--green); }
.pill-paused { background: rgba(255, 200, 80, 0.15); color: var(--accent); }
.pill-closed { background: rgba(235, 112, 112, 0.15); color: var(--red); }
.vault-detail { background: var(--bg2); padding: 20px; border-radius: 8px; margin-top: 16px; border: 1px solid var(--border); }
.vault-detail .strategy { font-style: italic; color: var(--dim); padding: 8px 12px; border-left: 2px solid var(--accent); margin: 8px 0 16px; }
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; }
.stat { background: rgba(255,255,255,0.03); padding: 10px 14px; border-radius: 6px; }
.stat .label { font-size: 11px; color: var(--dim); text-transform: uppercase; }
.stat .val { font-size: 18px; margin-top: 4px; font-family: ui-monospace, monospace; }
.stat .val.green { color: var(--green); }
.stat .val.red { color: var(--red); }
.actions { margin-top: 20px; padding-top: 16px; border-top: 1px solid var(--border); }
.reviews { margin-top: 16px; }
.review { background: rgba(255,255,255,0.03); padding: 12px; border-radius: 6px; margin-bottom: 8px; }
.review .by { font-size: 12px; color: var(--dim); }
.review pre { white-space: pre-wrap; word-break: break-word; font-size: 12px; color: var(--fg); margin: 6px 0 0; }
.info { color: var(--dim); font-size: 13px; }
.err { color: var(--red); font-size: 13px; }
.ok { color: var(--green); font-size: 13px; }
</style>
</head>
<body>
<header>
<h1>Plinth</h1>
<p class="tag">Capital layer for AI trading agents on Arc. Browse vaults, deposit USDC, redeem at NAV.</p>
<div style="background: rgba(110, 220, 168, 0.08); border-left: 3px solid #6edca8; padding: 10px 14px; margin: 12px 0; border-radius: 0 4px 4px 0; max-width: 720px;">
<strong style="color: #6edca8;">→ See it in action:</strong>
<a href="verify.html" style="color: #ffc850; font-weight: 600;">Verifiable PnL Demo</a>
— Underwriter cryptographically reconciles agent's reportedPnL against Aster L1 trade history, runs in your browser.
</div>
<div class="meta">
Plinth v0 (this UI): <a id="plinthLink" target="_blank" rel="noopener">0xc2994ce3df612ebd2f898244a992a0bbfef86627</a> — historical / 5 demo vaults + Aster L1 verifiable-PnL vault<br>
Plinth v0.5 (recommended, security-hardened): <a href="https://testnet.arcscan.app/address/0xba1b087b0ac77b398c250a9fd7e298f3f96addc7" target="_blank" rel="noopener">0xba1b087b0ac77b398c250a9fd7e298f3f96addc7</a> — closes 6 audit findings, 98/98 tests<br>
Chain: Arc Testnet (chainId 5042002) · <span id="rpcStatus" class="info">connecting…</span>
</div>
</header>
<main>
<h2>Vaults</h2>
<div class="row">
<button id="refreshBtn" title="Scan full chain history for any new vaults beyond the known list">Refresh (full scan)</button>
<span class="info" id="vaultsInfo">scanning…</span>
</div>
<table id="vaultsTable">
<thead>
<tr>
<th>Vault ID</th>
<th>Agent</th>
<th>Strategy</th>
<th>Status</th>
<th>Total Shares</th>
<th>NAV</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="vaultsBody"><tr><td colspan="7" class="info">loading…</td></tr></tbody>
</table>
<div id="detailContainer"></div>
</main>
<script type="module">
import {
createPublicClient, defineChain, http, fallback, parseAbiItem, decodeEventLog, formatEther, keccak256, toBytes,
} from "https://esm.sh/viem@2.48.11";
const PLINTH = "0xc2994ce3df612ebd2f898244a992a0bbfef86627";
// Arc's own rpc.testnet.arc.network sends no Access-Control-Allow-Origin, so a
// browser can't read it. These provider endpoints do send CORS headers AND carry
// full history; the official one stays last in case it regains CORS later.
const RPCS = [
"https://rpc.drpc.testnet.arc.network",
"https://rpc.quicknode.testnet.arc.network",
"https://rpc.testnet.arc.network",
];
const EXPLORER = "https://testnet.arcscan.app";
const arc = defineChain({
id: 5042002, name: "Arc Testnet",
nativeCurrency: { name: "USDC", symbol: "USDC", decimals: 18 },
rpcUrls: { default: { http: RPCS } },
});
const client = createPublicClient({
chain: arc,
transport: fallback(RPCS.map(u => http(u, { timeout: 60_000 }))),
});
const PLINTH_ABI = [
{ type:"function", name:"vaults", stateMutability:"view", inputs:[{type:"bytes32"}],
outputs:[
{name:"agent",type:"address"},{name:"createdAt",type:"uint64"},{name:"status",type:"uint8"},
{name:"totalShares",type:"uint256"},{name:"inVault",type:"uint256"},{name:"deployedAUM",type:"uint256"},
{name:"reportedPnL",type:"int256"},{name:"strategyDescriptor",type:"string"},
]},
{ type:"function", name:"nav", stateMutability:"view", inputs:[{type:"bytes32"}], outputs:[{type:"uint256"}] },
{ type:"function", name:"getApprovedVenues", stateMutability:"view", inputs:[{type:"bytes32"}], outputs:[{type:"address[]"}] },
];
document.getElementById("plinthLink").href = `${EXPLORER}/address/${PLINTH}`;
function shortHex(s, h=10, t=6) { if (!s) return ""; return s.slice(0, h) + "…" + s.slice(-t); }
function fmtUsdc(wei, decimals=6) {
if (typeof wei !== "bigint") wei = BigInt(wei);
const neg = wei < 0n; const abs = neg ? -wei : wei;
const whole = abs / 10n**18n;
let frac = (abs % 10n**18n).toString().padStart(18, "0").slice(0, decimals).replace(/0+$/, "");
return (neg ? "-" : "") + whole + (frac ? "." + frac : "");
}
function statusPill(s) {
if (s === 1) return `<span class="pill pill-active">Active</span>`;
if (s === 2) return `<span class="pill pill-paused">Paused</span>`;
if (s === 3) return `<span class="pill pill-closed">Closed</span>`;
return s;
}
// v0 contract was deployed at this block. We walk forward from here to find all vaults.
const PLINTH_DEPLOY_BLOCK = 41_977_066n;
async function getLogsWithRetry(params, retries = 2) {
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const r = await client.getLogs(params);
return r;
} catch (e) {
if (attempt === retries) return [];
await new Promise(r => setTimeout(r, 200 * (attempt + 1)));
}
}
return [];
}
async function findVaultEvents() {
const latest = await client.getBlockNumber();
// Arc Testnet caps eth_getLogs at 10k blocks AND throttles high parallelism, so batch in groups of 5.
const CHUNK = 9_900n;
const BATCH = 5;
const event = parseAbiItem("event VaultCreated(bytes32 indexed vaultId, address indexed agent, address[] approvedVenues, string strategyDescriptor, uint256 initialDeposit)");
const ranges = [];
let cursor = PLINTH_DEPLOY_BLOCK;
while (cursor <= latest) {
const to = cursor + CHUNK > latest ? latest : cursor + CHUNK;
ranges.push([cursor, to]);
cursor = to + 1n;
}
const info = document.getElementById("vaultsInfo");
const all = [];
for (let i = 0; i < ranges.length; i += BATCH) {
if (info) info.textContent = `scanning ${i+1}-${Math.min(i+BATCH, ranges.length)} of ${ranges.length} chunks…`;
const batch = ranges.slice(i, i + BATCH);
const results = await Promise.all(batch.map(([from, to]) =>
getLogsWithRetry({ address: PLINTH, event, fromBlock: from, toBlock: to })
));
all.push(...results.flat());
}
// Dedup by vaultId, keep first (chronologically earliest)
const seen = new Set();
return all
.sort((a, b) => Number(a.blockNumber - b.blockNumber))
.filter(l => {
const id = l.topics[1];
if (seen.has(id)) return false;
seen.add(id);
return true;
});
}
// Known vault IDs on Plinth v0 (snapshot at submission). Used as the fast-path render —
// reading vault state directly via `vaults(id)` view is O(1) vs. log-scanning the full history.
// The Refresh button triggers a full log scan to discover any new vaults created later.
const KNOWN_VAULT_IDS = [
"0xc003ec854ac99d1054541f6160568b13bff6f4e443bbaa25422ff3392eb29d46",
"0xc4c82a676f3b5a8f2aa511cab2e350667b9039029e57413fa08c18371cd06fc6",
"0xd33068c5f41fcc0165fc96af540cc2d8f0e79b58884fa8ca0f4a71ac4932d0c9",
"0x5c7eebdb1644c0a1ca6a976e4e81c8d634039caf806488868aa22232c14f9a5c",
"0x71002b008dcf44b560f61f9ee686f3789bf7b538e03a18307e7c1c1893b953c1",
"0xefb495a02c14af970104d62e9623d83eea8d0b725dea9ffd6b7aa479284430fc",
];
async function loadVaults(opts = {}) {
const { fullScan = false } = opts;
const tbody = document.getElementById("vaultsBody");
const info = document.getElementById("vaultsInfo");
info.textContent = fullScan ? "scanning chain…" : "loading known vaults…";
// Fast path: read state for each known vault id directly. ~1s, no log scan needed.
let vaultIds = [...KNOWN_VAULT_IDS];
document.getElementById("rpcStatus").innerHTML = `<span class="ok">connected, latest block ${await client.getBlockNumber()}</span>`;
// Slow path: if user clicks Refresh, scan full chain history for any new vaults too.
if (fullScan) {
try {
const logs = await findVaultEvents();
const seen = new Set(vaultIds.map(s => s.toLowerCase()));
for (const l of logs) if (!seen.has(l.topics[1].toLowerCase())) vaultIds.push(l.topics[1]);
} catch (e) {
info.textContent = `scan error: ${e.message.slice(0,60)}`;
}
}
if (vaultIds.length === 0) {
tbody.innerHTML = `<tr><td colspan="7" class="info">No vaults found on contract ${shortHex(PLINTH)} since block ${PLINTH_DEPLOY_BLOCK}.</td></tr>`;
info.textContent = "0 vaults";
return;
}
// Fetch live state for each vault id in parallel — typically completes in ~1-2 seconds
const rows = (await Promise.all(vaultIds.map(async (vaultId) => {
try {
const [vaultData, nav] = await Promise.all([
client.readContract({ address: PLINTH, abi: PLINTH_ABI, functionName: "vaults", args: [vaultId] }),
client.readContract({ address: PLINTH, abi: PLINTH_ABI, functionName: "nav", args: [vaultId] }),
]);
const [agent, createdAt, status, totalShares, inVault, deployedAUM, reportedPnL, strategyDescriptor] = vaultData;
// Filter out non-existent vaults (status=0/None means the id never existed)
if (status === 0) return null;
return { vaultId, agent, createdAt, status, totalShares, inVault, deployedAUM, reportedPnL, strategyDescriptor, nav };
} catch { return null; }
}))).filter(Boolean);
info.textContent = fullScan ? `${rows.length} vault(s) (full scan)` : `${rows.length} vault(s)`;
tbody.innerHTML = rows.map(r => `
<tr>
<td class="mono"><a href="${EXPLORER}/address/${PLINTH}" target="_blank">${shortHex(r.vaultId)}</a></td>
<td class="mono">${shortHex(r.agent, 8, 4)}</td>
<td>${r.strategyDescriptor.slice(0, 50)}${r.strategyDescriptor.length > 50 ? "…" : ""}</td>
<td>${statusPill(r.status)}</td>
<td class="mono">${fmtUsdc(r.totalShares)}</td>
<td class="mono">${fmtUsdc(r.nav)} USDC</td>
<td><button onclick="window.showDetail('${r.vaultId}')">Detail</button></td>
</tr>
`).join("");
window._vaults = rows;
}
window.showDetail = async function(vaultId) {
const r = window._vaults.find(v => v.vaultId === vaultId);
if (!r) return;
const venues = await client.readContract({ address: PLINTH, abi: PLINTH_ABI, functionName: "getApprovedVenues", args: [vaultId] });
const totalAUM = r.inVault + r.deployedAUM + r.reportedPnL;
const pnlClass = r.reportedPnL > 0n ? "green" : r.reportedPnL < 0n ? "red" : "";
// Reviews — batched (5 at a time) with retry, same pattern as vault scan
const latest = await client.getBlockNumber();
const reviewEvent = parseAbiItem("event UnderwriterReviewPosted(bytes32 indexed vaultId, address indexed underwriter, bytes32 reviewHash, string reviewUri)");
let reviews = [];
try {
const CHUNK = 9_900n;
const BATCH = 5;
const ranges = [];
let cursor = PLINTH_DEPLOY_BLOCK;
while (cursor <= latest) {
const to = cursor + CHUNK > latest ? latest : cursor + CHUNK;
ranges.push([cursor, to]);
cursor = to + 1n;
}
const allLogs = [];
for (let i = 0; i < ranges.length; i += BATCH) {
const batch = ranges.slice(i, i + BATCH);
const results = await Promise.all(batch.map(([from, to]) =>
getLogsWithRetry({ address: PLINTH, event: reviewEvent, args: { vaultId }, fromBlock: from, toBlock: to })
));
allLogs.push(...results.flat());
}
allLogs.sort((a, b) => Number(a.blockNumber - b.blockNumber));
reviews = allLogs.map(l => decodeEventLog({ abi:[reviewEvent], data:l.data, topics:l.topics }).args)
.map((a, i) => ({ ...a, blockNumber: allLogs[i].blockNumber, txHash: allLogs[i].transactionHash }));
} catch {}
const container = document.getElementById("detailContainer");
container.innerHTML = `
<div class="vault-detail">
<h2 style="margin-top:0">Vault ${shortHex(r.vaultId)}</h2>
<div class="strategy">${r.strategyDescriptor}</div>
<div class="info">Agent: <a class="mono" href="${EXPLORER}/address/${r.agent}" target="_blank">${r.agent}</a></div>
<div class="info">Approved venues: ${venues.map(v => `<a class="mono" href="${EXPLORER}/address/${v}" target="_blank">${shortHex(v, 8, 4)}</a>`).join(", ")}</div>
<div class="stats" style="margin-top:16px">
<div class="stat"><div class="label">Status</div><div class="val">${statusPill(r.status)}</div></div>
<div class="stat"><div class="label">Total Shares</div><div class="val">${fmtUsdc(r.totalShares)}</div></div>
<div class="stat"><div class="label">NAV</div><div class="val">${fmtUsdc(r.nav)}</div></div>
<div class="stat"><div class="label">In Vault (liquid)</div><div class="val">${fmtUsdc(r.inVault)} USDC</div></div>
<div class="stat"><div class="label">Deployed AUM</div><div class="val">${fmtUsdc(r.deployedAUM)} USDC</div></div>
<div class="stat"><div class="label">Reported PnL</div><div class="val ${pnlClass}">${fmtUsdc(r.reportedPnL)} USDC</div></div>
<div class="stat"><div class="label">Total AUM</div><div class="val">${fmtUsdc(totalAUM)} USDC</div></div>
</div>
<div class="actions">
<h3 style="margin-top:0">Deposit / Redeem</h3>
<p class="info">Web UI is read-only in v0 — connect a wallet on Arc Testnet and call the contract directly (or use the @plinth/sdk TypeScript client).</p>
<p class="info">Contract: <a class="mono" href="${EXPLORER}/address/${PLINTH}" target="_blank">${PLINTH}</a></p>
</div>
<div class="reviews">
<h3>Underwriter Reviews (${reviews.length})</h3>
${reviews.length === 0 ? '<p class="info">No reviews posted in the last ~10k blocks.</p>' : ''}
${reviews.map(rv => `
<div class="review">
<div class="by">by <a href="${EXPLORER}/address/${rv.underwriter}" target="_blank">${shortHex(rv.underwriter, 8, 4)}</a>
· block ${rv.blockNumber}
· hash <code>${shortHex(rv.reviewHash)}</code>
· <a href="${EXPLORER}/tx/${rv.txHash}" target="_blank">tx</a>
</div>
<pre>${decodeReviewUri(rv.reviewUri)}</pre>
</div>
`).join("")}
</div>
</div>
`;
container.scrollIntoView({ behavior: "smooth" });
};
function decodeReviewUri(uri) {
if (uri.startsWith("data:application/json;base64,")) {
try {
const b64 = uri.slice("data:application/json;base64,".length);
return atob(b64);
} catch { return uri.slice(0, 200) + "…"; }
}
return uri;
}
document.getElementById("refreshBtn").addEventListener("click", () => loadVaults({ fullScan: true }));
loadVaults();
</script>
</body>
</html>