forked from Smartdevs17/SubTrackr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatchTransactionService.ts
More file actions
353 lines (305 loc) · 8.69 KB
/
Copy pathbatchTransactionService.ts
File metadata and controls
353 lines (305 loc) · 8.69 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
// ════════════════════════════════════════════════════════════════
// BATCH TRANSACTION SERVICE - Frontend batch management
// ════════════════════════════════════════════════════════════════
/**
* Represents a single transaction in a batch
*/
export interface BatchTransaction {
functionName: string;
params: any[];
dependsOn?: number;
required: boolean;
}
/**
* Result of executing a batch operation
*/
export interface OperationResult {
index: number;
success: boolean;
result?: any;
error?: string;
}
/**
* Complete batch result
*/
export interface BatchExecutionResult {
batchId: string;
totalOperations: number;
successfulOperations: number;
failedOperations: number;
results: OperationResult[];
atomic: boolean;
gasEstimate: number;
}
/**
* Batch Transaction Service - Handles transaction batching
*/
export class BatchTransactionService {
private pendingTransactions: BatchTransaction[] = [];
private maxBatchSize: number = 10;
private gasPerOperation: number = 100_000;
private baseGasCost: number = 50_000;
constructor(maxBatchSize: number = 10) {
this.maxBatchSize = maxBatchSize;
}
/**
* Add transaction to batch queue
* @returns true if added, false if batch is full
*/
addTransaction(functionName: string, params: any[], required: boolean = true): boolean {
// Check if batch is full
if (this.pendingTransactions.length >= this.maxBatchSize) {
console.warn(`Batch is full (${this.maxBatchSize}), cannot add more transactions`);
return false;
}
const transaction: BatchTransaction = {
functionName,
params,
required,
};
this.pendingTransactions.push(transaction);
console.log(
`✅ Added ${functionName}. Pending: ${this.pendingTransactions.length}/${this.maxBatchSize}`
);
return true;
}
/**
* Add transaction with dependency on another operation
*/
addTransactionWithDependency(
functionName: string,
params: any[],
dependsOn: number,
required: boolean = true
): boolean {
if (this.pendingTransactions.length >= this.maxBatchSize) {
return false;
}
// Validate dependency
if (dependsOn >= this.pendingTransactions.length) {
console.error(`Invalid dependency: index ${dependsOn} out of range`);
return false;
}
const transaction: BatchTransaction = {
functionName,
params,
dependsOn,
required,
};
this.pendingTransactions.push(transaction);
return true;
}
/**
* Get pending transactions count
*/
getPendingCount(): number {
return this.pendingTransactions.length;
}
/**
* Is batch ready to execute?
*/
isBatchReady(): boolean {
return this.pendingTransactions.length >= this.maxBatchSize;
}
/**
* Get current pending batch
*/
getPendingBatch(): BatchTransaction[] {
return [...this.pendingTransactions];
}
/**
* Simulate batch execution without actually executing
* Useful for gas estimation and validation
*/
async simulateBatch(): Promise<BatchExecutionResult> {
console.log(`📊 Simulating batch with ${this.pendingTransactions.length} operations...`);
const totalGas = this.getGasEstimate();
const batchId = this.generateBatchId();
const results: OperationResult[] = this.pendingTransactions.map((tx, index) => ({
index,
success: true,
result: null,
}));
return {
batchId,
totalOperations: this.pendingTransactions.length,
successfulOperations: this.pendingTransactions.length,
failedOperations: 0,
results,
atomic: false,
gasEstimate: totalGas,
};
}
/**
* Execute batch synchronously
*/
async executeBatch(atomic: boolean = true): Promise<BatchExecutionResult> {
console.log(
`🚀 Executing batch with ${this.pendingTransactions.length} operations (atomic: ${atomic})...`
);
if (this.pendingTransactions.length === 0) {
throw new Error('❌ No transactions to execute');
}
const results: OperationResult[] = [];
let successCount = 0;
let failCount = 0;
let totalGas = 0;
let shouldStop = false;
// Execute each transaction
for (let i = 0; i < this.pendingTransactions.length; i++) {
const tx = this.pendingTransactions[i];
// Check if we should stop (atomic mode)
if (shouldStop && atomic) {
results.push({
index: i,
success: false,
error: 'Skipped due to atomic failure',
});
failCount++;
continue;
}
// Check dependencies
if (tx.dependsOn !== undefined) {
const dependencyResult = results[tx.dependsOn];
if (!dependencyResult.success) {
results.push({
index: i,
success: false,
error: 'Dependency failed',
});
failCount++;
if (tx.required) {
shouldStop = true;
}
continue;
}
}
// Execute transaction
try {
console.log(` 📝 Executing: ${tx.functionName}`);
// Simulate execution
const result = await this.executeTransaction(tx);
const gasUsed = this.gasPerOperation;
results.push({
index: i,
success: true,
result,
});
successCount++;
totalGas += gasUsed;
} catch (error) {
console.error(` ❌ Transaction failed: ${tx.functionName}`, error);
results.push({
index: i,
success: false,
error: String(error),
});
failCount++;
if (tx.required) {
shouldStop = true;
}
}
}
const batchResult: BatchExecutionResult = {
batchId: this.generateBatchId(),
totalOperations: this.pendingTransactions.length,
successfulOperations: successCount,
failedOperations: failCount,
results,
atomic,
gasEstimate: totalGas,
};
// Clear batch after execution
this.pendingTransactions = [];
console.log(`✅ Batch complete: ${successCount}/${batchResult.totalOperations} successful`);
console.log(` Gas used: ${totalGas.toLocaleString()} units`);
return batchResult;
}
/**
* Execute single transaction (simulated)
*/
private async executeTransaction(_tx: BatchTransaction): Promise<any> {
// In real implementation, call actual contract function
// For now, simulate with delay
return new Promise((resolve) => {
setTimeout(() => {
resolve({ success: true, txHash: `0x${Math.random().toString(16).slice(2)}` });
}, 100);
});
}
/**
* Clear pending batch
*/
clearBatch(): void {
this.pendingTransactions = [];
console.log('🗑️ Batch cleared');
}
/**
* Get gas estimate for pending batch
*/
getGasEstimate(): number {
return this.baseGasCost + this.pendingTransactions.length * this.gasPerOperation;
}
/**
* Get batch summary
*/
getBatchSummary(): {
pending: number;
maxSize: number;
estimatedGas: number;
isFull: boolean;
gasPercentFull: number;
} {
const pending = this.pendingTransactions.length;
const percentFull = (pending / this.maxBatchSize) * 100;
return {
pending,
maxSize: this.maxBatchSize,
estimatedGas: this.getGasEstimate(),
isFull: this.isBatchReady(),
gasPercentFull: percentFull,
};
}
/**
* Set maximum batch size
*/
setMaxBatchSize(size: number): void {
if (size > 100) {
console.warn('Max batch size should not exceed 100');
return;
}
this.maxBatchSize = size;
console.log(`📦 Max batch size set to: ${size}`);
}
/**
* Generate unique batch ID
*/
private generateBatchId(): string {
const timestamp = Date.now();
const random = Math.random().toString(36).substr(2, 9);
return `batch_${timestamp}_${random}`;
}
/**
* Calculate gas savings
*/
calculateGasSavings(): {
individual: number;
batched: number;
savings: number;
percentSavings: number;
} {
const numTx = this.pendingTransactions.length;
const individualGas = numTx * (this.baseGasCost + this.gasPerOperation);
const batchedGas = this.getGasEstimate();
const savings = individualGas - batchedGas;
const percentSavings = (savings / individualGas) * 100;
return {
individual: individualGas,
batched: batchedGas,
savings,
percentSavings,
};
}
}
// Export for use in React components
export default BatchTransactionService;