-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
514 lines (445 loc) · 16.8 KB
/
server.js
File metadata and controls
514 lines (445 loc) · 16.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
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
const http = require('http');
const fs = require('fs');
const path = require('path');
const { ethers } = require('ethers');
const PORT = process.env.PORT || 10000;
// Contract ABIs (minimal)
const ATTEST_REGISTRY_ABI = [
"function attest(address agent, bytes32 actionType, uint256 value, uint256 confidence, string calldata metadata) external payable returns (bytes32)",
"function getReputation(address agent) external view returns (uint256 score, uint256 totalAttestations, uint256 successCount)",
"event AttestationCreated(bytes32 indexed uid, address indexed agent, bytes32 actionType, uint256 value)"
];
const FEE_COLLECTOR_ABI = [
"function collectFee(address agent, uint256 tradeValue) external payable",
"function getFee(uint256 tradeValue) external pure returns (uint256)",
"function withdraw() external",
"event FeeCollected(address indexed agent, uint256 amount, uint256 tradeValue)"
];
// Contract addresses from deployment
const CONTRACTS = {
baseSepolia: {
attestRegistry: '0xC36E784E1dff616bDae4EAc7B310F0934FaF04a4',
feeCollector: '0xFF196F1e3a895404d073b8611252cF97388773A7'
}
};
// In-memory state (will be persisted to file)
let state = {
decisions: {},
attestations: [],
agents: {},
stats: {
totalValidations: 0,
totalExecutions: 0,
totalFeesCollected: 0,
totalVolume: 0
}
};
// Load state from file if exists
const STATE_FILE = './data/ep-state.json';
try {
if (fs.existsSync(STATE_FILE)) {
state = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
console.log('State loaded from file');
}
} catch (e) {
console.log('No existing state file, starting fresh');
}
// Save state helper
function saveState() {
try {
if (!fs.existsSync('./data')) fs.mkdirSync('./data', { recursive: true });
fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
} catch (e) {
console.error('Failed to save state:', e.message);
}
}
// Fee calculation: max(0.5%, 0.01 ETH)
function calculateFee(tradeValue) {
const percentageFee = tradeValue * 0.005; // 0.5%
const minFee = 0.01; // 0.01 ETH
const fee = Math.max(percentageFee, minFee);
return {
amount_eth: fee.toFixed(4),
amount_usd: (fee * 2500).toFixed(2), // Approximate ETH price
basis_points: fee === minFee ? 100 : 50
};
}
// Validation logic
function validateOpportunity(opportunity) {
const { type, asset, expected_return, confidence, max_capital } = opportunity;
// Risk scoring
let riskScore = 0;
if (confidence > 0.8) riskScore += 30;
else if (confidence > 0.6) riskScore += 20;
else if (confidence > 0.4) riskScore += 10;
if (expected_return > 0.1) riskScore += 30;
else if (expected_return > 0.05) riskScore += 20;
else if (expected_return > 0.02) riskScore += 10;
if (max_capital < 1000) riskScore += 20;
else if (max_capital < 5000) riskScore += 10;
// Decision
const approved = confidence >= 0.3 && expected_return > 0.01 && riskScore >= 30;
return {
approved,
risk_level: riskScore >= 60 ? 'low' : riskScore >= 40 ? 'medium' : 'high',
confidence_score: confidence,
max_allocation: Math.min(max_capital, 1000) // Cap at $1000 for safety
};
}
// Request handler
async function handleRequest(req, res) {
const url = new URL(req.url, `http://${req.headers.host}`);
const pathname = url.pathname;
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Agent-Key');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// API Routes
if (pathname === '/api/v1/validate' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const data = JSON.parse(body);
const { agent_id, opportunity } = data;
if (!agent_id || !opportunity) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Missing agent_id or opportunity' }));
return;
}
const decisionId = `d-${Date.now()}`;
const validation = validateOpportunity(opportunity);
const fee = calculateFee(opportunity.max_capital || 100);
const response = {
decision_id: decisionId,
status: validation.approved ? 'approved' : 'rejected',
confidence_score: validation.confidence_score,
risk_level: validation.risk_level,
max_allocation: validation.max_allocation,
fee: fee,
attestation_uid: null,
timestamp: new Date().toISOString()
};
// Store decision
state.decisions[decisionId] = {
...response,
agent_id,
opportunity,
executed: false
};
state.stats.totalValidations++;
saveState();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(response));
console.log(`[VALIDATE] ${agent_id} -> ${response.status} (${validation.risk_level})`);
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
return;
}
if (pathname === '/api/v1/execute' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const data = JSON.parse(body);
const { decision_id, approval_token } = data;
if (!decision_id) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Missing decision_id' }));
return;
}
const decision = state.decisions[decision_id];
if (!decision) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Decision not found' }));
return;
}
if (decision.executed) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Decision already executed' }));
return;
}
// Validate approval token format
if (!approval_token || !approval_token.startsWith('APPROVE:')) {
res.writeHead(401, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid approval token' }));
return;
}
// Mark as executed
decision.executed = true;
decision.execution_time = new Date().toISOString();
state.stats.totalExecutions++;
state.stats.totalVolume += decision.max_allocation || 0;
// Update agent stats
if (!state.agents[decision.agent_id]) {
state.agents[decision.agent_id] = {
validations: 0,
executions: 0,
volume: 0,
fees: 0
};
}
state.agents[decision.agent_id].executions++;
state.agents[decision.agent_id].volume += decision.max_allocation || 0;
saveState();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
decision_id,
status: 'executed',
execution_time: decision.execution_time,
fee_paid: decision.fee
}));
console.log(`[EXECUTE] ${decision_id} executed`);
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
return;
}
if (pathname.startsWith('/api/v1/reputation/') && req.method === 'GET') {
const agentAddress = pathname.split('/').pop();
const agent = state.agents[agentAddress] || { validations: 0, executions: 0, volume: 0, fees: 0 };
// Calculate reputation score
const successRate = agent.executions > 0 ? agent.executions / agent.validations : 0;
const reputationScore = Math.floor(
(agent.executions * 100) +
(successRate * 1000) +
(Math.log10(agent.volume + 1) * 100)
);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
address: agentAddress,
reputation_score: Math.min(reputationScore, 10000),
total_attestations: agent.executions || 0,
success_rate: successRate.toFixed(2),
total_volume: agent.volume || 0
}));
return;
}
if (pathname === '/api/v1/stats' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
...state.stats,
uptime: process.uptime(),
timestamp: new Date().toISOString()
}));
return;
}
// Legacy endpoint for backward compatibility
if (pathname === '/ep/validate' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const data = JSON.parse(body);
const { agent, action, params } = data;
const decisionId = `ep-${Date.now()}`;
const confidence = params?.confidence || 0.5;
const approved = confidence >= 0.3;
const response = {
decision_id: decisionId,
approved,
confidence,
fee_eth: approved ? '0.01' : '0',
timestamp: new Date().toISOString()
};
state.decisions[decisionId] = {
...response,
agent,
action,
params,
executed: false
};
saveState();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(response));
console.log(`[EP/VALIDATE] ${agent} -> ${approved ? 'APPROVED' : 'REJECTED'}`);
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
return;
}
// ============================================
// HACKATHON FEATURES — Synthesis x Bankr 2026
// Purely additive. Does not modify existing routes.
// ============================================
// Feature: EP Status endpoint
if (pathname === '/ep/status' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
status: 'operational',
version: '1.0.0',
uptime: process.uptime(),
network: 'base-sepolia',
contracts: {
attestRegistry: '0xC36E784E1dff616bDae4EAc7B310F0934FaF04a4',
feeCollector: '0xFF196F1e3a895404d073b8611252cF97388773A7',
epCommitment: '0xf1e16d3e5B74582fC326Bc6E2B82839d31f1ccE8'
},
stats: {
totalValidations: state.stats.totalValidations || 0,
totalExecutions: state.stats.totalExecutions || 0,
totalProofs: Object.keys(state.decisions || {}).length
},
timestamp: new Date().toISOString()
}));
return;
}
// Feature: Proof lookup — public, no auth
if (pathname.startsWith('/ep/proof/') && req.method === 'GET') {
const proofHash = pathname.split('/ep/proof/')[1];
if (!proofHash) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Missing proof hash' }));
return;
}
// Search decisions for matching proof hash
let found = null;
for (const [id, decision] of Object.entries(state.decisions || {})) {
if (id === proofHash || decision.proof_hash === proofHash) {
found = decision;
break;
}
}
if (!found) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
proof_hash: proofHash,
status: 'not_found',
message: 'No proof found for this hash. It may not have been committed yet.',
verify_on_chain: 'https://sepolia.basescan.org/address/0xf1e16d3e5B74582fC326Bc6E2B82839d31f1ccE8'
}));
return;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
proof_hash: proofHash,
agent_id: found.agent_id || found.agent || 'unknown',
action: found.action || `${found.opportunity?.type || 'validate'}`,
valid: found.approved !== undefined ? found.approved : (found.status === 'approved'),
risk_score: found.confidence_score || found.confidence || 0,
timestamp: found.timestamp,
executed: found.executed || false,
on_chain: {
network: 'base-sepolia',
contract: '0xf1e16d3e5B74582fC326Bc6E2B82839d31f1ccE8',
tx: null
}
}));
return;
}
// Feature: Swarm validate — multi-agent coordination
if (pathname === '/ep/swarm/validate' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const data = JSON.parse(body);
const { agent_id, swarm_id, swarm_role, swarm_context, asset, direction, amount_usd, policy_set_id } = data;
if (!agent_id || !swarm_id) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Missing agent_id or swarm_id' }));
return;
}
// Swarm-level policy checks
const maxSingleAgentPct = swarm_context?.max_single_agent_pct || 25;
const totalExposure = swarm_context?.total_exposure_usd || 1000;
const agentLimit = totalExposure * (maxSingleAgentPct / 100);
const violations = [];
if ((amount_usd || 0) > agentLimit) {
violations.push(`Agent exceeds ${maxSingleAgentPct}% swarm exposure limit ($${agentLimit})`);
}
if ((amount_usd || 0) > 100) {
violations.push('Single trade exceeds $100 policy limit');
}
const valid = violations.length === 0;
const riskScore = valid ? Math.random() * 0.4 : 0.7 + Math.random() * 0.3;
const proofHash = '0x' + require('crypto').createHash('sha256')
.update(JSON.stringify({ agent_id, swarm_id, asset, direction, amount_usd, timestamp: Date.now() }))
.digest('hex');
const decisionId = `swarm-${Date.now()}`;
const response = {
valid,
risk_score: parseFloat(riskScore.toFixed(3)),
violations,
proof_hash: proofHash,
swarm_id,
agent_id,
swarm_role: swarm_role || 'executor',
plan_summary: `${direction || 'action'} ${amount_usd || 0} USD of ${asset || 'unknown'} via swarm ${swarm_id}`,
timestamp: new Date().toISOString()
};
state.decisions[decisionId] = { ...response, executed: false };
state.stats.totalValidations++;
saveState();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(response));
console.log(`[SWARM/VALIDATE] ${agent_id}@${swarm_id} -> ${valid ? 'VALID' : 'REJECTED'}`);
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
return;
}
// Static file serving
let filePath = '.' + pathname;
if (filePath === './') filePath = './index.html';
if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
filePath = path.join(filePath, 'index.html');
}
const mimeTypes = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.md': 'text/markdown',
'.txt': 'text/plain'
};
const extname = String(path.extname(filePath)).toLowerCase();
const contentType = mimeTypes[extname] || 'application/octet-stream';
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code === 'ENOENT') {
fs.readFile('./index.html', (err, content) => {
if (err) {
res.writeHead(404);
res.end('404 Not Found');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
} else {
res.writeHead(500);
res.end('500 Server Error');
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
}
const server = http.createServer(handleRequest);
server.listen(PORT, () => {
console.log(`⚡ Execution Protocol API running on port ${PORT}`);
console.log(`📊 Stats: ${state.stats.totalValidations} validations, ${state.stats.totalExecutions} executions`);
console.log(`🌐 Endpoints:`);
console.log(` POST /api/v1/validate - Validate opportunities`);
console.log(` POST /api/v1/execute - Execute approved decisions`);
console.log(` GET /api/v1/reputation/:agent - Get agent reputation`);
console.log(` GET /api/v1/stats - Get system stats`);
console.log(` POST /ep/validate - Legacy validation endpoint`);
});