-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-dht-contracts.html
More file actions
557 lines (470 loc) · 21.3 KB
/
test-dht-contracts.html
File metadata and controls
557 lines (470 loc) · 21.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smart Contracts DHT Testing - ZHTP Browser</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
color: white;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: rgba(255, 255, 255, 0.1);
padding: 30px;
border-radius: 15px;
backdrop-filter: blur(10px);
box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
}
h1 {
text-align: center;
color: #fff;
margin-bottom: 30px;
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
}
.section {
background: rgba(255, 255, 255, 0.05);
margin: 20px 0;
padding: 20px;
border-radius: 10px;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.section h2 {
color: #4fc3f7;
margin-top: 0;
border-bottom: 2px solid #4fc3f7;
padding-bottom: 10px;
}
.button {
background: linear-gradient(45deg, #4fc3f7, #29b6f6);
color: white;
border: none;
padding: 12px 24px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
margin: 5px;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(79, 195, 247, 0.3);
}
.button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(79, 195, 247, 0.4);
}
.button:disabled {
background: #666;
cursor: not-allowed;
transform: none;
box-shadow: none;
}
input, textarea {
width: 100%;
padding: 10px;
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 6px;
background: rgba(255, 255, 255, 0.1);
color: white;
font-size: 14px;
margin: 5px 0;
box-sizing: border-box;
}
input::placeholder, textarea::placeholder {
color: rgba(255, 255, 255, 0.6);
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin: 20px 0;
}
.log-area {
background: rgba(0, 0, 0, 0.3);
padding: 15px;
border-radius: 8px;
max-height: 200px;
overflow-y: auto;
font-family: 'Consolas', 'Monaco', monospace;
font-size: 12px;
border: 1px solid rgba(255, 255, 255, 0.2);
}
.status {
padding: 10px;
border-radius: 6px;
margin: 10px 0;
font-weight: bold;
}
.status.success {
background: rgba(76, 175, 80, 0.3);
border: 1px solid #4caf50;
}
.status.error {
background: rgba(244, 67, 54, 0.3);
border: 1px solid #f44336;
}
.status.info {
background: rgba(33, 150, 243, 0.3);
border: 1px solid #2196f3;
}
.contract-list {
background: rgba(255, 255, 255, 0.05);
border-radius: 8px;
padding: 15px;
margin: 10px 0;
}
.contract-item {
background: rgba(255, 255, 255, 0.1);
padding: 10px;
margin: 8px 0;
border-radius: 6px;
border-left: 4px solid #4fc3f7;
}
.form-group {
margin: 15px 0;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #e1f5fe;
}
.inline-form {
display: flex;
gap: 10px;
align-items: end;
}
.inline-form input {
flex: 1;
}
.progress {
width: 100%;
height: 4px;
background: rgba(255, 255, 255, 0.1);
border-radius: 2px;
overflow: hidden;
margin: 10px 0;
}
.progress-bar {
height: 100%;
background: linear-gradient(90deg, #4fc3f7, #29b6f6);
width: 0%;
transition: width 0.3s ease;
}
</style>
</head>
<body>
<div class="container">
<h1>🚀 Smart Contracts DHT Testing</h1>
<p style="text-align: center; opacity: 0.9;">Test direct DHT packet-based smart contract operations through ZHTP protocol</p>
<div class="section">
<h2> DHT Connection Status</h2>
<div id="connection-status" class="status info">Checking DHT connection...</div>
<button class="button" onclick="checkDhtStatus()"> Refresh Status</button>
<button class="button" onclick="listContracts()"> List DHT Contracts</button>
</div>
<div class="grid">
<div class="section">
<h2>🚀 Deploy Contract</h2>
<div class="form-group">
<label for="deploy-contract-id">Contract ID:</label>
<input type="text" id="deploy-contract-id" placeholder="e.g., counter_v1" value="test_counter">
</div>
<div class="form-group">
<label for="deploy-contract-name">Contract Name:</label>
<input type="text" id="deploy-contract-name" placeholder="e.g., Simple Counter" value="Test Counter">
</div>
<div class="form-group">
<label for="deploy-description">Description:</label>
<input type="text" id="deploy-description" placeholder="Contract description" value="A simple counter for DHT testing">
</div>
<button class="button" onclick="deployTestContract()">🚀 Deploy Test Contract</button>
<button class="button" onclick="deployCustomContract()">Deploy Custom</button>
</div>
<div class="section">
<h2> Query Contract</h2>
<div class="form-group">
<label for="query-contract-id">Contract ID:</label>
<input type="text" id="query-contract-id" placeholder="e.g., counter_v1" value="test_counter">
</div>
<div class="form-group">
<label for="query-function">Function Name (optional):</label>
<input type="text" id="query-function" placeholder="e.g., get_count">
</div>
<button class="button" onclick="queryContract()"> Query Contract</button>
<button class="button" onclick="findContract()">🔎 Find Contract</button>
</div>
</div>
<div class="section">
<h2>⚡ Execute Contract</h2>
<div class="inline-form">
<div style="flex: 1;">
<label for="exec-contract-id">Contract ID:</label>
<input type="text" id="exec-contract-id" placeholder="e.g., counter_v1" value="test_counter">
</div>
<div style="flex: 1;">
<label for="exec-function">Function Name:</label>
<input type="text" id="exec-function" placeholder="e.g., increment" value="increment">
</div>
<div style="flex: 1;">
<label for="exec-args">Arguments (JSON):</label>
<input type="text" id="exec-args" placeholder='e.g., [1]' value='[]'>
</div>
<button class="button" onclick="executeContract()">⚡ Execute</button>
</div>
</div>
<div class="section">
<h2>🔥 Quick Actions</h2>
<button class="button" onclick="deployAndExecute()">🚀⚡ Deploy & Execute</button>
<button class="button" onclick="runFullDemo()">🎬 Run Full Demo</button>
<button class="button" onclick="clearLogs()">🧹 Clear Logs</button>
</div>
<div class="section">
<h2> Available Contracts</h2>
<div id="contracts-list" class="contract-list">
<div class="status info">Click "List DHT Contracts" to load available contracts</div>
</div>
</div>
<div class="section">
<h2>📊 Operation Logs</h2>
<div id="logs" class="log-area"></div>
<div class="progress">
<div id="progress-bar" class="progress-bar"></div>
</div>
</div>
</div>
<script>
// Load the contracts DHT API
const contractsApi = new (require('../src/api/contracts-dht-api.js'))();
let operationCount = 0;
function log(message, type = 'info') {
const timestamp = new Date().toLocaleTimeString();
const logs = document.getElementById('logs');
const logEntry = `[${timestamp}] ${message}`;
logs.innerHTML += logEntry + '\n';
logs.scrollTop = logs.scrollHeight;
console.log(`DHT Contract Test: ${logEntry}`);
// Update progress
operationCount++;
updateProgress();
}
function updateProgress() {
const progressBar = document.getElementById('progress-bar');
const progress = Math.min((operationCount * 10) % 100, 90);
progressBar.style.width = `${progress}%`;
setTimeout(() => {
if (progress >= 90) {
progressBar.style.width = '100%';
setTimeout(() => {
progressBar.style.width = '0%';
operationCount = 0;
}, 500);
}
}, 200);
}
function showStatus(message, type = 'info') {
const statusDiv = document.getElementById('connection-status');
statusDiv.className = `status ${type}`;
statusDiv.textContent = message;
}
async function checkDhtStatus() {
log(' Checking DHT connection status...');
showStatus('Checking DHT connection...', 'info');
try {
// Test basic connectivity to ZHTP node
const response = await fetch('http://localhost:9333/health');
if (response.ok) {
showStatus(' ZHTP node connected - DHT operations available', 'success');
log(' ZHTP node is running and accessible');
} else {
showStatus('⚠️ ZHTP node responding but may have issues', 'error');
log('⚠️ ZHTP node response issues');
}
} catch (error) {
showStatus('❌ Cannot connect to ZHTP node', 'error');
log(`❌ Connection failed: ${error.message}`);
}
}
async function deployTestContract() {
log('🚀 Starting test contract deployment via DHT...');
const contractId = document.getElementById('deploy-contract-id').value || 'test_counter';
const contractName = document.getElementById('deploy-contract-name').value || 'Test Counter';
const description = document.getElementById('deploy-description').value || 'A simple counter for DHT testing';
try {
const testContract = contractsApi.createTestContract();
const metadata = {
...testContract.metadata,
name: contractName,
description: description,
};
const result = await contractsApi.deployContract(contractId, testContract.bytecode, metadata);
log(` Contract deployment initiated: ${JSON.stringify(result)}`);
log(` Contract ID: ${contractId}`);
log(` Message ID: ${result.message_id}`);
} catch (error) {
log(`❌ Contract deployment failed: ${error.message}`);
}
}
async function queryContract() {
const contractId = document.getElementById('query-contract-id').value || 'test_counter';
const functionName = document.getElementById('query-function').value || null;
log(` Querying contract ${contractId} via DHT...`);
try {
const result = await contractsApi.queryContract(contractId, functionName);
log(` Contract query sent: ${JSON.stringify(result)}`);
log(` Message ID: ${result.message_id}`);
// Try to get response after a delay
setTimeout(async () => {
try {
const response = await contractsApi.listenForContractResponses(result.message_id, 10000);
log(`📥 Query response: ${JSON.stringify(response)}`);
} catch (error) {
log(`⏱️ Query response timeout (this is normal in test environment)`);
}
}, 2000);
} catch (error) {
log(`❌ Contract query failed: ${error.message}`);
}
}
async function executeContract() {
const contractId = document.getElementById('exec-contract-id').value || 'test_counter';
const functionName = document.getElementById('exec-function').value || 'increment';
const argsStr = document.getElementById('exec-args').value || '[]';
log(`⚡ Executing contract ${contractId}.${functionName} via DHT...`);
try {
const args = JSON.parse(argsStr);
const result = await contractsApi.executeContract(contractId, functionName, args);
log(` Contract execution initiated: ${JSON.stringify(result)}`);
log(` Message ID: ${result.message_id}`);
} catch (error) {
log(`❌ Contract execution failed: ${error.message}`);
}
}
async function findContract() {
const contractId = document.getElementById('query-contract-id').value || 'test_counter';
log(`🔎 Finding contract ${contractId} in DHT network...`);
try {
const result = await contractsApi.findContract(contractId);
log(` Contract search initiated: ${JSON.stringify(result)}`);
log(` Message ID: ${result.message_id}`);
} catch (error) {
log(`❌ Contract search failed: ${error.message}`);
}
}
async function listContracts() {
log(' Listing available contracts in DHT network...');
try {
const contracts = await contractsApi.listContracts();
const contractsList = document.getElementById('contracts-list');
if (contracts.length === 0) {
contractsList.innerHTML = '<div class="status info">No contracts found in DHT network</div>';
log(' No contracts found in DHT network');
} else {
let html = `<div class="status success">Found ${contracts.length} contracts in DHT network:</div>`;
contracts.forEach(contract => {
html += `
<div class="contract-item">
<strong>${contract.name}</strong> (${contract.contract_id})
<br>Version: ${contract.version}
<br>Author: ${contract.author || 'Unknown'}
<br>Description: ${contract.description || 'No description'}
<br>Deployed: ${new Date(contract.deployed_at * 1000).toLocaleString()}
</div>
`;
});
contractsList.innerHTML = html;
log(` Found ${contracts.length} contracts in DHT network`);
}
} catch (error) {
log(`❌ Failed to list contracts: ${error.message}`);
const contractsList = document.getElementById('contracts-list');
contractsList.innerHTML = '<div class="status error">Failed to load contracts from DHT</div>';
}
}
async function deployAndExecute() {
log('🚀⚡ Starting deploy and execute sequence via DHT...');
const contractId = 'demo_' + Math.random().toString(36).substr(2, 9);
try {
const result = await contractsApi.deployAndExecute(
contractId,
contractsApi.createTestContract().bytecode,
{
name: 'Demo Contract',
description: 'Demo contract for DHT testing',
version: '1.0.0'
},
'increment',
[]
);
log(` Deploy and execute completed: ${JSON.stringify(result)}`);
} catch (error) {
log(`❌ Deploy and execute failed: ${error.message}`);
}
}
async function runFullDemo() {
log('🎬 Starting full DHT smart contract demo...');
// Step 1: Check status
await checkDhtStatus();
await new Promise(resolve => setTimeout(resolve, 1000));
// Step 2: List existing contracts
await listContracts();
await new Promise(resolve => setTimeout(resolve, 1000));
// Step 3: Deploy a test contract
document.getElementById('deploy-contract-id').value = 'demo_full_test';
document.getElementById('deploy-contract-name').value = 'Full Demo Contract';
await deployTestContract();
await new Promise(resolve => setTimeout(resolve, 2000));
// Step 4: Query the contract
document.getElementById('query-contract-id').value = 'demo_full_test';
await queryContract();
await new Promise(resolve => setTimeout(resolve, 1000));
// Step 5: Execute contract function
document.getElementById('exec-contract-id').value = 'demo_full_test';
await executeContract();
await new Promise(resolve => setTimeout(resolve, 1000));
log(' Full DHT smart contract demo completed!');
}
function deployCustomContract() {
const contractId = prompt('Enter contract ID:', 'custom_contract_' + Date.now());
if (!contractId) return;
const bytecodeHex = prompt('Enter contract bytecode (hex):', '');
if (!bytecodeHex) return;
try {
const bytecode = new Uint8Array(bytecodeHex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
const metadata = {
name: prompt('Contract name:', 'Custom Contract'),
version: prompt('Version:', '1.0.0'),
description: prompt('Description:', 'Custom deployed contract'),
};
contractsApi.deployContract(contractId, bytecode, metadata)
.then(result => {
log(` Custom contract deployed: ${JSON.stringify(result)}`);
})
.catch(error => {
log(`❌ Custom contract deployment failed: ${error.message}`);
});
} catch (error) {
log(`❌ Invalid bytecode format: ${error.message}`);
}
}
function clearLogs() {
document.getElementById('logs').innerHTML = '';
operationCount = 0;
document.getElementById('progress-bar').style.width = '0%';
log('🧹 Logs cleared');
}
// Initialize the page
window.addEventListener('load', () => {
log('🚀 DHT Smart Contracts testing interface loaded');
log(' Testing direct DHT packet communication for smart contracts');
checkDhtStatus();
});
// Auto-refresh status periodically
setInterval(checkDhtStatus, 30000);
</script>
</body>
</html>