forked from nirholas/pump-fun-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwith-worker-threads.ts
More file actions
196 lines (168 loc) · 5.02 KB
/
Copy pathwith-worker-threads.ts
File metadata and controls
196 lines (168 loc) · 5.02 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
/**
* @fileoverview Example demonstrating worker threads for parallel generation.
*
* EDUCATIONAL NOTE: This example shows how to use Node.js worker threads
* to parallelize vanity address generation. While JavaScript is single-threaded,
* worker threads allow true parallel execution.
*
* For production use, consider the Rust CLI implementation which is significantly
* faster due to native performance.
*
* Run with: npx ts-node examples/with-worker-threads.ts
*/
import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';
import { cpus } from 'os';
import * as path from 'path';
import { VanityGenerator, saveKeypair } from '../src/lib';
import type { GenerationResult, VanityOptions } from '../src/lib/types';
/**
* Configuration for the vanity address search
*/
interface WorkerConfig {
options: VanityOptions;
workerId: number;
}
/**
* Message from worker to main thread
*/
interface WorkerMessage {
type: 'result' | 'progress';
workerId: number;
result?: GenerationResult;
attempts?: number;
rate?: number;
}
/**
* Worker thread code
*/
async function runWorker(): Promise<void> {
const config = workerData as WorkerConfig;
const { options, workerId } = config;
const generator = new VanityGenerator({
...options,
onProgress: (attempts, rate) => {
const message: WorkerMessage = {
type: 'progress',
workerId,
attempts,
rate,
};
parentPort?.postMessage(message);
},
});
try {
const result = await generator.generate();
const message: WorkerMessage = {
type: 'result',
workerId,
result,
};
parentPort?.postMessage(message);
} catch (error) {
// Max attempts reached or other error
parentPort?.postMessage({
type: 'progress',
workerId,
attempts: -1,
});
}
}
/**
* Main thread code
*/
async function main(): Promise<void> {
console.log('🔑 Solana Vanity Address Generator - Worker Threads Example\n');
const numWorkers = cpus().length;
console.log(`Using ${numWorkers} worker threads\n`);
const prefix = 'So';
const options: VanityOptions = {
prefix,
maxAttempts: 10000000, // Max per worker
};
console.log(`Searching for address starting with "${prefix}"...\n`);
// Track progress from each worker
const workerProgress = new Map<number, { attempts: number; rate: number }>();
const workers: Worker[] = [];
let foundResult: GenerationResult | null = null;
// Create workers
for (let i = 0; i < numWorkers; i++) {
const config: WorkerConfig = {
options,
workerId: i,
};
const worker = new Worker(__filename, {
workerData: config,
});
worker.on('message', (message: WorkerMessage) => {
if (message.type === 'result' && foundResult === null) {
foundResult = message.result ?? null;
// Terminate all workers
for (const w of workers) {
w.terminate().catch(() => {
// Ignore termination errors
});
}
} else if (message.type === 'progress') {
if (message.attempts !== undefined && message.rate !== undefined) {
workerProgress.set(message.workerId, {
attempts: message.attempts,
rate: message.rate,
});
}
// Display combined progress
let totalAttempts = 0;
let totalRate = 0;
for (const progress of workerProgress.values()) {
totalAttempts += progress.attempts;
totalRate += progress.rate;
}
process.stdout.write(
`\rTotal: ${totalAttempts.toLocaleString()} attempts | ${totalRate.toFixed(0)}/sec (${numWorkers} workers)`
);
}
});
worker.on('error', (error) => {
console.error(`Worker ${i} error:`, error);
});
workers.push(worker);
}
// Wait for result
await new Promise<void>((resolve) => {
const checkInterval = setInterval(() => {
if (foundResult !== null) {
clearInterval(checkInterval);
resolve();
}
}, 100);
});
// Clear progress line
process.stdout.write('\r' + ' '.repeat(80) + '\r');
// Type assertion needed because TypeScript can't track the async callback modification
const result = foundResult as GenerationResult | null;
if (result !== null) {
console.log('\n✅ Found matching address!\n');
console.log(` Address: ${result.publicKey}`);
console.log(` Attempts: ${result.attempts.toLocaleString()}`);
console.log(` Duration: ${(result.duration / 1000).toFixed(2)}s\n`);
// Save to file
const outputPath = `${result.publicKey}.json`;
await saveKeypair(result.secretKey, outputPath);
console.log(`📁 Keypair saved to: ${outputPath}\n`);
} else {
console.log('❌ No match found within the attempt limit.\n');
}
// Cleanup
for (const worker of workers) {
worker.terminate().catch(() => {
// Ignore
});
}
}
// Entry point
if (isMainThread) {
main().catch(console.error);
} else {
runWorker().catch((error) => {
console.error('Worker error:', error);
});
}