forked from whistledev411/pumpfun-copy-trading-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
328 lines (279 loc) · 10.5 KB
/
index.ts
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
import Client, {
CommitmentLevel,
SubscribeRequest,
SubscribeUpdate,
SubscribeUpdateTransaction,
} from "@triton-one/yellowstone-grpc";
import { CompiledInstruction } from "@triton-one/yellowstone-grpc/dist/grpc/solana-storage";
import { ClientDuplexStream } from '@grpc/grpc-js';
import { Connection, Keypair, PublicKey } from '@solana/web3.js';
import bs58 from 'bs58';
import buyToken from "./pumputils/utils/buyToken";
import dotenv from 'dotenv';
import { formatDate } from "./utils/commonFunc";
import fs from 'fs'
dotenv.config()
// Constants
const ENDPOINT = process.env.GRPC_ENDPOINT!;
const TOKEN = process.env.GRPC_TOKEN!;
const PUMP_FUN_PROGRAM_ID = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';
const PUMP_FUN_CREATE_IX_DISCRIMINATOR = Buffer.from([24, 30, 200, 40, 5, 28, 7, 119]);
const PUMP_FUN_BUY_IX_DISCRIMINATOR = Buffer.from([102, 6, 61, 18, 1, 218, 235, 234]);
const COMMITMENT = CommitmentLevel.PROCESSED;
const solanaConnection = new Connection(process.env.RPC_ENDPOINT!, 'confirmed');
const keypair = Keypair.fromSecretKey(bs58.decode(process.env.PRIVATE_KEY!));
const amount = process.env.BUY_AMOUNT;
const TARGET_ADDRESS = process.env.TARGET_ADDRESS!;
const PURCHASE_PERCENT = Number(process.env.PURCHASE_PERCENT!);
const MAX_LIMIT = Number(process.env.MAX_LIMIT!);
if(!TARGET_ADDRESS) console.log('Target Address is not defined')
if(!PURCHASE_PERCENT || PURCHASE_PERCENT === 0) console.log("Purchase percent is not defined");
if(!MAX_LIMIT || MAX_LIMIT === 0) console.log("Max Limit is not defined");
console.log('========================================= Your Config ======================================= \n')
console.log('Target Wallet Address =====> ', TARGET_ADDRESS);
console.log('Purchase Amount Percent =====> ', `${PURCHASE_PERCENT} %`);
console.log('Max Limit =====> ', `${MAX_LIMIT} SOL \n`);
// Configuration
const FILTER_CONFIG = {
programIds: [PUMP_FUN_PROGRAM_ID],
instructionDiscriminators: [PUMP_FUN_BUY_IX_DISCRIMINATOR]
};
// Main function
async function main(): Promise<void> {
const client = new Client(ENDPOINT, TOKEN, {});
const stream = await client.subscribe();
const request = createSubscribeRequest();
try {
await sendSubscribeRequest(stream, request);
console.log(`Geyser connection established - watching ${TARGET_ADDRESS} \n`);
await handleStreamEvents(stream);
} catch (error) {
console.error('Error in subscription process:', error);
stream.end();
}
}
// Helper functions
function createSubscribeRequest(): SubscribeRequest {
return {
accounts: {},
slots: {},
transactions: {
pumpFun: {
accountInclude: FILTER_CONFIG.programIds,
accountExclude: [],
accountRequired: [TARGET_ADDRESS],
failed: false
}
},
transactionsStatus: {},
entry: {},
blocks: {},
blocksMeta: {},
commitment: COMMITMENT,
accountsDataSlice: [],
ping: undefined,
};
}
function sendSubscribeRequest(
stream: ClientDuplexStream<SubscribeRequest, SubscribeUpdate>,
request: SubscribeRequest
): Promise<void> {
return new Promise<void>((resolve, reject) => {
stream.write(request, (err: Error | null) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
function handleStreamEvents(stream: ClientDuplexStream<SubscribeRequest, SubscribeUpdate>): Promise<void> {
return new Promise<void>((resolve, reject) => {
stream.on('data', async (data) => {
await handleData(data, stream)
// const result = await handleData(data, stream)
// if (result) {
// stream.end();
// process.exit(1)
// }
});
stream.on("error", (error: Error) => {
console.error('Stream error:', error);
reject(error);
stream.end();
});
stream.on("end", () => {
console.log('Stream ended');
resolve();
});
stream.on("close", () => {
console.log('Stream closed');
resolve();
});
});
}
let isStopped = false;
async function handleData(data: SubscribeUpdate, stream: ClientDuplexStream<SubscribeRequest, SubscribeUpdate>) {
if (isStopped) {
return; // Skip processing if the stream is stopped
}
if (!isSubscribeUpdateTransaction(data) || !data.filters.includes('pumpFun')) {
return;
}
const transaction = data.transaction?.transaction;
const message = transaction?.transaction?.message;
if (!transaction || !message) {
return;
}
let type = '';
// Check if buy transaction or not
const isBuy = checkBuy(data);
const isSell = checkSell(data);
if (!isBuy && !isSell) {
return;
}
if (isBuy) {
type = 'buy'
} else {
type = 'sell'
}
const formattedSignature = convertSignature(transaction.signature);
const { mint, accountIndex } = getMintAccount(data);
if (mint && accountIndex) {
isStopped = true; // Set the flag to prevent further handling
if (type === 'buy') {
console.log("Signature => ", `https://solscan.io/tx/${formattedSignature.base58}`, await formatDate());
const tokenAmount = getBalanceChange(data);
const solAmount = getSolChange(data, accountIndex)
console.log("Detail => ", `Bought ${tokenAmount} of ${mint} token with ${solAmount} sol \n`);
const buyAmount = solAmount * PURCHASE_PERCENT / 100;
const purchase = (Math.floor(buyAmount * 10 ** 9)) / 10 ** 9;
if (purchase > MAX_LIMIT) {
console.log(`Going to skip this transaction! Purchased more than ${MAX_LIMIT} sol \n`)
isStopped = false
return true
}
console.log("Going to start buy ", `${mint} token of ${purchase} sol`);
const mint_pub = new PublicKey(mint);
const sig = await buyToken(mint_pub, solanaConnection, keypair, purchase, 1);
if (sig) {
console.log('Buy success ===> ', `https://solscan.io/tx/${sig}`);
} else {
console.log("Buy failed!")
}
isStopped = false
} else {
console.log("Signature => ", `https://solscan.io/tx/${formattedSignature.base58}`);
const tokenAmount = getBalanceChange(data);
const solAmount = getSolChange(data, accountIndex)
console.log("Detail => ", `Sold ${Math.abs(tokenAmount)} of ${mint} token with ${Math.abs(solAmount)} sol \n`);
console.log("Going to start sell ", `${mint} token`);
// Sell Functionality here.
isStopped = false
}
}
return true;
}
const saveToJSONFile = (filePath: string, data: object): void => {
// Convert data object to JSON string
const jsonData = JSON.stringify(data, null, 2); // The `null, 2` argument formats the JSON with indentation
fs.writeFileSync(filePath, jsonData, 'utf8');
console.log('Data saved to JSON file.');
};
// Check token balance change of target wallet
const getBalanceChange = (data: SubscribeUpdate) => {
let preBalance = 0;
let postBalance = 0;
const preAccounts = data.transaction?.transaction?.meta?.preTokenBalances;
const postAccounts = data.transaction?.transaction?.meta?.postTokenBalances;
const preAccount = preAccounts?.filter((account: any, i: number) => {
if (account.owner === TARGET_ADDRESS) {
return true
} else {
return false
}
})
const postAccount = postAccounts?.filter((account: any, i: number) => {
if (account.owner === TARGET_ADDRESS) {
return true
} else {
return false
}
})
if (preAccount && preAccount.length !== 0) {
preBalance = Number(preAccount[0].uiTokenAmount?.amount)
}
if (postAccount && postAccount.length !== 0) {
postBalance = Number(postAccount[0].uiTokenAmount?.amount)
}
return (postBalance - preBalance) / 10 ** 6
}
// Program log: Instruction: Sell
// Check buy transaction
const checkBuy = (data: SubscribeUpdate) => {
const isBuy = data.transaction?.transaction?.meta?.logMessages.toString().includes('Program log: Instruction: Buy');
if (isBuy) {
return true
} else {
false
}
}
// Check sell transaction
const checkSell = (data: SubscribeUpdate) => {
const isSell = data.transaction?.transaction?.meta?.logMessages.toString().includes('Program log: Instruction: Sell');
if (isSell) {
return true
} else {
false
}
}
// Get Token mint
const getMintAccount = (data: SubscribeUpdate) => {
const tokenAccount = data.transaction?.transaction?.meta?.preTokenBalances.filter((preToken) => {
if (preToken.accountIndex === 1) {
return false
} else {
return true
}
})
if (tokenAccount && tokenAccount.length !== 0) {
return {
mint: tokenAccount[0].mint,
accountIndex: tokenAccount[0].accountIndex
}
} else {
return {
mint: null,
accountIndex: null
}
}
}
// Get sol balance change of target wallet
const getSolChange = (data: SubscribeUpdate, accountIndex: number) => {
const preSolBalance = data.transaction?.transaction?.meta?.preBalances[accountIndex - 1];
const postBalance = data.transaction?.transaction?.meta?.postBalances[accountIndex - 1];
const change = (Number(postBalance) - Number(preSolBalance)) / 10 ** 9;
return change
}
function isSubscribeUpdateTransaction(data: SubscribeUpdate): data is SubscribeUpdate & { transaction: SubscribeUpdateTransaction } {
return (
'transaction' in data &&
typeof data.transaction === 'object' &&
data.transaction !== null &&
'slot' in data.transaction &&
'transaction' in data.transaction
);
}
function convertSignature(signature: Uint8Array): { base58: string } {
return { base58: bs58.encode(Buffer.from(signature)) };
}
function matchesInstructionDiscriminator(ix: CompiledInstruction): boolean {
return ix?.data && FILTER_CONFIG.instructionDiscriminators.some(discriminator =>
Buffer.from(discriminator).equals(ix.data.slice(0, 8))
);
}
main().catch((err) => {
console.error('Unhandled error in main:', err);
process.exit(1);
});