-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
632 lines (552 loc) · 20 KB
/
server.js
File metadata and controls
632 lines (552 loc) · 20 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
/**
* Assurance Contracts
*
* Like Kickstarter - all or nothing funding.
* If goal is met by deadline: funds released to recipient
* If not: contributors get full refunds
*/
const express = require('express');
const cors = require('cors');
const { v4: uuidv4 } = require('uuid');
const { ethers } = require('ethers');
const app = express();
app.use(cors());
app.use(express.json());
// Config
const BASE_RPC = process.env.BASE_RPC || 'https://mainnet.base.org';
const TREASURY_ADDRESS = process.env.TREASURY_ADDRESS || '0xccD7200024A8B5708d381168ec2dB0DC587af83F';
const TREASURY_PRIVATE_KEY = process.env.TREASURY_PRIVATE_KEY?.trim();
const FEE_PERCENT = 5n;
let provider = null;
let wallet = null;
function getProvider() {
if (!provider) provider = new ethers.JsonRpcProvider(BASE_RPC);
return provider;
}
function getWallet() {
if (!wallet && TREASURY_PRIVATE_KEY) {
wallet = new ethers.Wallet(TREASURY_PRIVATE_KEY, getProvider());
}
return wallet;
}
// Storage
const contracts = new Map(); // Assurance contracts
const pledges = new Map(); // Pledges (contributions)
// Helpers
function formatETH(wei) {
return parseFloat(ethers.formatEther(wei.toString())).toFixed(6) + ' ETH';
}
function parseETH(ethString) {
const cleaned = ethString.toString().replace(' ETH', '').trim();
return ethers.parseEther(cleaned);
}
function getContractPledges(contractId) {
return Array.from(pledges.values())
.filter(p => p.contractId === contractId && p.status === 'active')
.reduce((sum, p) => sum + BigInt(p.amount), 0n);
}
function getContractStatus(contract) {
const now = Date.now();
const totalPledged = getContractPledges(contract.id);
const goalMet = totalPledged >= BigInt(contract.goal);
const expired = now > contract.deadline;
if (contract.status === 'completed') return 'completed';
if (contract.status === 'refunded') return 'refunded';
if (expired && goalMet) return 'succeeded';
if (expired && !goalMet) return 'failed';
if (goalMet) return 'goal_met';
return 'open';
}
// Verify ETH transfer
async function verifyETHTransfer(txHash, minAmount) {
try {
const tx = await getProvider().getTransaction(txHash);
if (!tx) return { valid: false, error: 'Transaction not found' };
const receipt = await getProvider().getTransactionReceipt(txHash);
if (!receipt || receipt.status !== 1) return { valid: false, error: 'Transaction failed' };
if (tx.to?.toLowerCase() !== TREASURY_ADDRESS.toLowerCase()) {
return { valid: false, error: 'Not sent to treasury' };
}
if (tx.value < minAmount) {
return { valid: false, error: `Amount too low: ${formatETH(tx.value)}` };
}
return {
valid: true,
from: tx.from.toLowerCase(),
amount: tx.value.toString(),
blockNumber: receipt.blockNumber
};
} catch (err) {
return { valid: false, error: err.message };
}
}
// ============================================================================
// API: CONTRACTS
// ============================================================================
// Create assurance contract
app.post('/contracts', (req, res) => {
const { name, description, goal, recipient, deadlineDays } = req.body;
if (!name || !goal || !recipient) {
return res.status(400).json({
error: 'name, goal (ETH), and recipient required',
example: { name: 'My Project', goal: '1.0', recipient: '0x...', deadlineDays: 14 }
});
}
if (!ethers.isAddress(recipient)) {
return res.status(400).json({ error: 'Invalid recipient address' });
}
let goalWei;
try {
goalWei = parseETH(goal);
} catch (e) {
return res.status(400).json({ error: 'Invalid goal format' });
}
const contract = {
id: uuidv4(),
name,
description: description || '',
goal: goalWei.toString(),
goalFormatted: formatETH(goalWei),
recipient: recipient.toLowerCase(),
deadline: Date.now() + (deadlineDays || 14) * 24 * 60 * 60 * 1000,
status: 'open',
createdAt: Date.now()
};
contracts.set(contract.id, contract);
console.log(`[CONTRACT CREATED] ${contract.id}: ${name} - Goal: ${contract.goalFormatted}`);
res.status(201).json({
...contract,
pledged: '0',
pledgedFormatted: '0.000000 ETH',
progress: 0,
currentStatus: 'open'
});
});
// List contracts
app.get('/contracts', (req, res) => {
const { status } = req.query;
let results = Array.from(contracts.values()).map(c => {
const pledged = getContractPledges(c.id);
const currentStatus = getContractStatus(c);
const goal = BigInt(c.goal);
return {
...c,
pledged: pledged.toString(),
pledgedFormatted: formatETH(pledged),
progress: goal > 0n ? Math.min(100, Number((pledged * 100n) / goal)) : 0,
currentStatus,
pledgeCount: Array.from(pledges.values()).filter(p => p.contractId === c.id && p.status === 'active').length
};
});
if (status) {
results = results.filter(c => c.currentStatus === status);
}
results.sort((a, b) => b.createdAt - a.createdAt);
res.json(results);
});
// Get contract details
app.get('/contracts/:id', (req, res) => {
const contract = contracts.get(req.params.id);
if (!contract) return res.status(404).json({ error: 'Contract not found' });
const pledged = getContractPledges(contract.id);
const currentStatus = getContractStatus(contract);
const goal = BigInt(contract.goal);
const contractPledges = Array.from(pledges.values())
.filter(p => p.contractId === contract.id)
.sort((a, b) => b.createdAt - a.createdAt);
res.json({
...contract,
pledged: pledged.toString(),
pledgedFormatted: formatETH(pledged),
progress: goal > 0n ? Math.min(100, Number((pledged * 100n) / goal)) : 0,
currentStatus,
pledges: contractPledges
});
});
// ============================================================================
// API: PLEDGES
// ============================================================================
// Make a pledge (send ETH to treasury)
app.post('/pledges', async (req, res) => {
const { contractId, txHash, amount, pledger } = req.body;
const isMock = req.query.mock === 'true';
if (!contractId || !txHash) {
return res.status(400).json({
error: 'contractId and txHash required',
instructions: `Send ETH to ${TREASURY_ADDRESS}, then submit txHash`
});
}
const contract = contracts.get(contractId);
if (!contract) return res.status(404).json({ error: 'Contract not found' });
const currentStatus = getContractStatus(contract);
if (currentStatus !== 'open' && currentStatus !== 'goal_met') {
return res.status(400).json({ error: `Contract is ${currentStatus}, not accepting pledges` });
}
// Check duplicate tx
const existingTx = Array.from(pledges.values())
.find(p => p.txHash?.toLowerCase() === txHash.toLowerCase());
if (existingTx) {
return res.status(400).json({ error: 'Transaction already used' });
}
let pledgeAddress, pledgeAmount, blockNumber;
if (!isMock) {
// Verify on-chain
const verification = await verifyETHTransfer(txHash, 0n);
if (!verification.valid) {
return res.status(400).json({ error: 'Verification failed', details: verification.error });
}
pledgeAddress = verification.from;
pledgeAmount = verification.amount;
blockNumber = verification.blockNumber;
} else {
// Mock mode: use fake data
pledgeAmount = amount ? parseETH(amount).toString() : ethers.parseEther('0.1').toString();
pledgeAddress = pledger || '0x' + '1'.repeat(40);
blockNumber = 12345678;
}
const pledge = {
id: uuidv4(),
contractId,
address: pledgeAddress,
amount: pledgeAmount,
amountFormatted: formatETH(pledgeAmount),
txHash,
blockNumber,
status: 'active',
mock: isMock || undefined,
createdAt: Date.now()
};
pledges.set(pledge.id, pledge);
console.log(`[PLEDGE] ${pledge.amountFormatted} from ${pledgeAddress.slice(0, 10)}... to ${contract.name}${isMock ? ' (MOCK)' : ''}`);
const totalPledged = getContractPledges(contractId);
const goal = BigInt(contract.goal);
const goalMet = totalPledged >= goal;
res.status(201).json({
pledge,
contractProgress: {
pledged: formatETH(totalPledged),
goal: contract.goalFormatted,
progress: goal > 0n ? Math.min(100, Number((totalPledged * 100n) / goal)) : 0,
goalMet,
status: goalMet ? 'goal_met' : 'open'
}
});
});
// ============================================================================
// API: FINALIZE
// ============================================================================
// Finalize contract (release funds or refund)
app.post('/contracts/:id/finalize', async (req, res) => {
const contract = contracts.get(req.params.id);
if (!contract) return res.status(404).json({ error: 'Contract not found' });
const currentStatus = getContractStatus(contract);
const totalPledged = getContractPledges(contract.id);
const goalMet = totalPledged >= BigInt(contract.goal);
if (currentStatus === 'completed' || currentStatus === 'refunded') {
return res.status(400).json({ error: `Contract already ${currentStatus}` });
}
if (!getWallet()) {
return res.status(500).json({ error: 'Wallet not configured' });
}
const contractPledges = Array.from(pledges.values())
.filter(p => p.contractId === contract.id && p.status === 'active');
// Goal met - release to recipient
if (goalMet) {
const fee = (totalPledged * FEE_PERCENT) / 100n;
const netAmount = totalPledged - fee;
try {
console.log(`[RELEASE] ${formatETH(netAmount)} to ${contract.recipient}`);
const tx = await getWallet().sendTransaction({
to: contract.recipient,
value: netAmount
});
contract.status = 'completed';
contract.completedAt = Date.now();
contract.releaseTxHash = tx.hash;
contract.feeCollected = fee.toString();
contracts.set(contract.id, contract);
// Mark pledges as released
contractPledges.forEach(p => {
p.status = 'released';
pledges.set(p.id, p);
});
res.json({
success: true,
action: 'released',
recipient: contract.recipient,
grossAmount: formatETH(totalPledged),
fee: formatETH(fee) + ' (5%)',
netAmount: formatETH(netAmount),
txHash: tx.hash,
basescanUrl: `https://basescan.org/tx/${tx.hash}`
});
} catch (err) {
res.status(500).json({ error: 'Release failed', details: err.message });
}
}
// Goal not met - refund all pledges
else {
const refunds = [];
for (const pledge of contractPledges) {
try {
const tx = await getWallet().sendTransaction({
to: pledge.address,
value: BigInt(pledge.amount)
});
pledge.status = 'refunded';
pledge.refundTxHash = tx.hash;
pledges.set(pledge.id, pledge);
refunds.push({
address: pledge.address,
amount: pledge.amountFormatted,
txHash: tx.hash
});
console.log(`[REFUND] ${pledge.amountFormatted} to ${pledge.address.slice(0, 10)}...`);
} catch (err) {
console.error(`[REFUND FAILED] ${pledge.address}: ${err.message}`);
refunds.push({
address: pledge.address,
amount: pledge.amountFormatted,
error: err.message
});
}
}
contract.status = 'refunded';
contract.refundedAt = Date.now();
contracts.set(contract.id, contract);
res.json({
success: true,
action: 'refunded',
reason: 'Goal not met',
totalRefunded: formatETH(totalPledged),
refunds
});
}
});
// ============================================================================
// UTILITY
// ============================================================================
app.get('/stats', (req, res) => {
const allContracts = Array.from(contracts.values());
const totalPledged = Array.from(pledges.values())
.filter(p => p.status === 'active')
.reduce((sum, p) => sum + BigInt(p.amount), 0n);
res.json({
contracts: allContracts.length,
activeContracts: allContracts.filter(c => ['open', 'goal_met'].includes(getContractStatus(c))).length,
completedContracts: allContracts.filter(c => getContractStatus(c) === 'completed').length,
refundedContracts: allContracts.filter(c => getContractStatus(c) === 'refunded').length,
totalPledges: pledges.size,
totalPledged: formatETH(totalPledged)
});
});
app.get('/health', (req, res) => {
res.json({
status: 'ok',
platform: 'Assurance Contracts',
description: 'All-or-nothing funding like Kickstarter',
network: 'Base',
treasury: TREASURY_ADDRESS,
payoutsEnabled: !!TREASURY_PRIVATE_KEY
});
});
// Agent endpoint for LLM discovery
app.get('/agent', (req, res) => {
res.json({
name: 'Assurance Contracts',
description: 'All-or-nothing funding like Kickstarter. Create contracts with funding goals and deadlines. If goal is met, funds release to recipient. If not, all pledgers get full refunds.',
network: 'Base',
treasury_fee: '5% on successful funding',
endpoints: [
{ method: 'POST', path: '/contracts', description: 'Create assurance contract', params: ['name', 'description?', 'goal (ETH)', 'recipient', 'deadlineDays?'] },
{ method: 'GET', path: '/contracts', description: 'List all contracts', query: ['status?'] },
{ method: 'GET', path: '/contracts/:id', description: 'Get contract details with pledges' },
{ method: 'POST', path: '/pledges', description: 'Make pledge (send ETH to treasury first)', params: ['contractId', 'txHash'] },
{ method: 'POST', path: '/contracts/:id/finalize', description: 'Release funds (if goal met) or refund all (if not)' },
{ method: 'GET', path: '/stats', description: 'Platform statistics' }
],
example_flow: [
'1. POST /contracts - Create contract "Community Garden" with 2 ETH goal',
'2. Send ETH to treasury address',
'3. POST /pledges - Submit txHash to record pledge',
'4. Repeat steps 2-3 until goal reached or deadline passes',
'5. POST /contracts/:id/finalize - Release to recipient or refund all'
],
x402_enabled: false
});
});
// Frontend
app.get('/', (req, res) => {
const allContracts = Array.from(contracts.values());
const totalPledged = Array.from(pledges.values())
.filter(p => p.status === 'active')
.reduce((sum, p) => sum + BigInt(p.amount), 0n);
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Assurance Contracts | All-or-Nothing Funding</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #0d1117;
color: #e6edf3;
min-height: 100vh;
}
.container { max-width: 900px; margin: 0 auto; padding: 2rem; }
.hero {
text-align: center;
padding: 4rem 2rem;
background: linear-gradient(180deg, rgba(88,166,255,0.15) 0%, transparent 100%);
border-radius: 16px;
margin-bottom: 3rem;
}
.hero h1 {
font-size: 2.5rem;
margin-bottom: 1rem;
background: linear-gradient(90deg, #58a6ff, #a371f7);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.hero p { color: #8b949e; max-width: 600px; margin: 0 auto 2rem; }
.badge {
display: inline-block;
background: #238636;
color: white;
padding: 0.25rem 0.75rem;
border-radius: 20px;
font-size: 0.8rem;
margin-bottom: 1rem;
}
.stats {
display: flex;
justify-content: center;
gap: 3rem;
margin: 2rem 0;
flex-wrap: wrap;
}
.stat { text-align: center; }
.stat-value { font-size: 2rem; font-weight: bold; color: #58a6ff; }
.stat-label { color: #8b949e; font-size: 0.85rem; }
.how-it-works {
background: rgba(88,166,255,0.1);
border: 1px solid rgba(88,166,255,0.3);
border-radius: 12px;
padding: 2rem;
margin-bottom: 3rem;
}
.how-it-works h2 { margin-bottom: 1.5rem; color: #58a6ff; }
.steps {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 1.5rem;
}
.step { text-align: center; padding: 1rem; }
.step-num {
width: 40px;
height: 40px;
background: linear-gradient(135deg, #58a6ff, #a371f7);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
margin: 0 auto 0.75rem;
}
.step h4 { margin-bottom: 0.5rem; font-size: 0.95rem; }
.step p { font-size: 0.8rem; color: #8b949e; }
.api-section {
background: #161b22;
border: 1px solid #30363d;
border-radius: 12px;
padding: 1.5rem;
}
.endpoint {
display: flex;
gap: 1rem;
padding: 0.5rem 0;
border-bottom: 1px solid #30363d;
font-family: monospace;
font-size: 0.85rem;
}
.endpoint:last-child { border-bottom: none; }
.method { width: 50px; }
.method.get { color: #58a6ff; }
.method.post { color: #3fb950; }
footer {
text-align: center;
padding: 2rem;
color: #8b949e;
border-top: 1px solid #30363d;
}
footer a { color: #58a6ff; text-decoration: none; }
</style>
</head>
<body>
<div class="container">
<div class="hero">
<div class="badge">🟢 LIVE ON BASE</div>
<h1>🎯 Assurance Contracts</h1>
<p>All-or-nothing funding like Kickstarter. Goal met = funds released. Goal missed = full refunds.</p>
<div class="stats">
<div class="stat">
<div class="stat-value">${allContracts.length}</div>
<div class="stat-label">Contracts</div>
</div>
<div class="stat">
<div class="stat-value">${formatETH(totalPledged)}</div>
<div class="stat-label">Total Pledged</div>
</div>
<div class="stat">
<div class="stat-value">${pledges.size}</div>
<div class="stat-label">Pledges</div>
</div>
</div>
</div>
<div class="how-it-works">
<h2>How It Works</h2>
<div class="steps">
<div class="step">
<div class="step-num">1</div>
<h4>Create Contract</h4>
<p>Set funding goal + deadline</p>
</div>
<div class="step">
<div class="step-num">2</div>
<h4>Pledge ETH</h4>
<p>Send ETH to treasury</p>
</div>
<div class="step">
<div class="step-num">3</div>
<h4>Goal Met?</h4>
<p>Funds release to recipient</p>
</div>
<div class="step">
<div class="step-num">4</div>
<h4>Goal Missed?</h4>
<p>Full refund to all pledgers</p>
</div>
</div>
</div>
<div class="api-section">
<h2 style="margin-bottom: 1rem;">🔌 API</h2>
<div class="endpoint"><span class="method post">POST</span><span>/contracts</span><span style="margin-left:auto;color:#8b949e">Create contract</span></div>
<div class="endpoint"><span class="method get">GET</span><span>/contracts</span><span style="margin-left:auto;color:#8b949e">List contracts</span></div>
<div class="endpoint"><span class="method get">GET</span><span>/contracts/:id</span><span style="margin-left:auto;color:#8b949e">Contract details</span></div>
<div class="endpoint"><span class="method post">POST</span><span>/pledges</span><span style="margin-left:auto;color:#8b949e">Make pledge (txHash)</span></div>
<div class="endpoint"><span class="method post">POST</span><span>/contracts/:id/finalize</span><span style="margin-left:auto;color:#8b949e">Release or refund</span></div>
</div>
</div>
<footer>
<p>5% fee on successful funding | Treasury: <a href="https://basescan.org/address/${TREASURY_ADDRESS}">${TREASURY_ADDRESS.slice(0, 6)}...${TREASURY_ADDRESS.slice(-4)}</a></p>
</footer>
</body>
</html>
`);
});
const PORT = process.env.PORT || 3010;
app.listen(PORT, () => console.log(`Assurance Contracts running on :${PORT}`));
module.exports = app;