-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
549 lines (490 loc) · 17.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
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
import { BN } from "@coral-xyz/anchor";
import { SYSTEM_PROGRAM_ID } from "@coral-xyz/anchor/dist/cjs/native/system";
import { Metaplex } from "@metaplex-foundation/js";
import {
ASSOCIATED_TOKEN_PROGRAM_ID,
createAssociatedTokenAccountInstruction,
getAccount,
getAssociatedTokenAddress,
getAssociatedTokenAddressSync,
getMint,
NATIVE_MINT,
TOKEN_PROGRAM_ID,
} from "@solana/spl-token";
import {
ComputeBudgetProgram,
Connection,
Keypair,
LAMPORTS_PER_SOL,
PublicKey,
sendAndConfirmTransaction,
Transaction,
TransactionInstruction,
VersionedTransaction,
} from "@solana/web3.js";
import base58 from "bs58";
import WebSocket from "ws";
import { getAllTokenPrice } from "./config";
import {
JUP_AGGREGATOR,
METEORA,
METEORA_DLMM,
MOONSHOT,
ORCA_V1,
ORCA_V2,
PUMP_FUN,
RAYDIUM,
RAYDIUM_CLMM,
RAYDIUM_CP,
RPC_ENDPOINT,
RPC_WEBSOCKET_ENDPOINT,
TARGET_WALLET,
} from "./constants";
import { BONDING_CURV, bufferFromUInt64, execute } from "./utils/common";
import { getAtaList } from "./utils/spl";
const connection = new Connection(RPC_ENDPOINT, { commitment: "processed" });
const ws = new WebSocket(RPC_WEBSOCKET_ENDPOINT);
const keyPair = Keypair.fromSecretKey(
base58.decode(process.env.PRIVATE_KEY as string)
);
const metaplex = Metaplex.make(connection);
const geyserList: any = [];
const wallet = TARGET_WALLET as string;
console.log("🚀 ~ wallet:", wallet);
// Global variables
const GLOBAL = new PublicKey("4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf");
const FEE_RECIPIENT = new PublicKey(
"CebN5WGQ4jvEPvsVU4EoHEpgzq1VV7AbicfhtW4xC9iM"
);
const SYSTEM_PROGRAM = new PublicKey("11111111111111111111111111111111");
const ASSOC_TOKEN_ACC_PROG = new PublicKey(
"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
);
const RENT = new PublicKey("SysvarRent111111111111111111111111111111111");
const PUMP_FUN_ACCOUNT = new PublicKey(
"Ce6TQqeHC9p8KetsN6JsjHK7UTZk7nasjjnr7XxXp9F1"
);
const PUMP_FUN_PROGRAM = new PublicKey(
"6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"
);
const TRADE_PROGRAM_ID = new PublicKey(
"6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"
);
const BONDING_ADDR_SEED = new Uint8Array([
98, 111, 110, 100, 105, 110, 103, 45, 99, 117, 114, 118, 101,
]);
let bonding: PublicKey;
let assoc_bonding_addr: PublicKey;
const getMetaData = async (mintAddr: string) => {
const mintAddress = new PublicKey(mintAddr);
let tokenName: string = "";
let tokenSymbol: string = "";
let tokenLogo: string = "";
const metadataAccount = metaplex
.nfts()
.pdas()
.metadata({ mint: mintAddress });
const metadataAccountInfo = await connection.getAccountInfo(metadataAccount);
if (metadataAccountInfo) {
const token = await metaplex
.nfts()
.findByMint({ mintAddress: mintAddress });
tokenName = token.name;
tokenSymbol = token.symbol;
// @ts-ignore
tokenLogo = token.json?.image;
}
return {
tokenName: tokenName,
tokenSymbol: tokenSymbol,
tokenLogo: tokenLogo,
};
};
getAllTokenPrice();
const getPoolState = async (mint: PublicKey, connection: Connection) => {
try {
// get the address of bonding curve and associated bonding curve
// get the accountinfo of bonding curve
// console.log(":rocket: ~ accountInfo:", accountInfo)
// get the poolstate of the bonding curve
// Calculate tokens out
const virtualSolReserves = poolState.virtualSolReserves;
const virtualTokenReserves = poolState.virtualTokenReserves;
return { virtualSolReserves, virtualTokenReserves };
} catch (error) {
console.log("getting·pool·state·error·=>·", error);
return false;
}
};
// Function to send a request to the WebSocket server
ws.on("open", async function open() {
await sendRequest(wallet);
console.log("send request\n");
});
ws.on("message", async function incoming(data: any) {
const messageStr = data.toString("utf8");
// console.log("🚀 ~ incoming ~ messageStr:", messageStr)
try {
const messageObj = JSON.parse(messageStr);
const result = messageObj.params.result;
if (messageStr.includes(JUP_AGGREGATOR)) {
console.log("JUP_AGGREGATOR");
} else if (messageStr.includes(METEORA_DLMM)) {
console.log("METEORA_DLMM");
} else if (messageStr.includes(METEORA)) {
console.log("METEORA");
} else if (messageStr.includes(RAYDIUM_CLMM)) {
console.log("RAYDIUM_CLMM");
} else if (messageStr.includes(RAYDIUM)) {
console.log("RAYDIUM");
} else if (messageStr.includes(RAYDIUM_CP)) {
console.log("RAYDIUM_CP");
} else if (messageStr.includes(PUMP_FUN)) {
console.log("PUMP_FUN");
} else if (messageStr.includes(MOONSHOT)) {
console.log("MOONSHOT");
} else if (messageStr.includes(ORCA_V1)) {
console.log("ORCA_V1");
} else if (messageStr.includes(ORCA_V2)) {
console.log("ORCA_V2");
} else {
console.log("This is not swap");
return
}
if (messageStr.includes("Swap") || messageStr.includes("Buy") || messageStr.includes("Sell") || messageStr.includes("Route")) {
let routingPro: any = []
for (let i = 0; i < result.transaction.transaction.message.instructions.length; i++) {
const proId = result.transaction.transaction.message.instructions[i];
if (proId['accounts'] != undefined) {
if (proId.accounts.length > 0) {
routingPro.push(result.transaction.transaction.message.instructions[i].programId)
}
}
}
let temp: any = []
for (let i = 0; i < messageObj.params.result.transaction.meta.innerInstructions.length; i++) {
const element = messageObj.params.result.transaction.meta.innerInstructions[i];
for (let index = 0; index < element.instructions.length; index++) {
const subelement = element.instructions[index];
temp.push(subelement)
}
}
let temp1: any = []
for (let index = 0; index < temp.length; index++) {
const element = temp[index];
if (element['program'] == "spl-token") {
if (element['parsed']['type'] == "transfer" || element['parsed']['type'] == "transferChecked") {
temp1.push(element)
}
}
}
const swapInfo: any = [
{
tokenAta: temp1[0].parsed.info.source,
tokenAmount: temp1[0].parsed.info.amount == undefined ? temp1[0].parsed.info.tokenAmount.amount : temp1[0].parsed.info.amount
},
{
tokenAta: temp1[temp1.length - 1].parsed.info.destination,
tokenAmount: temp1[temp1.length - 1].parsed.info.amount == undefined ? temp1[temp1.length - 1].parsed.info.tokenAmount.amount : temp1[temp1.length - 1].parsed.info.amount
},
]
console.log(1);
let inputMsg: any = [];
for (let i = 0; i < 2; i++) {
const ele = swapInfo[i];
let mintAddress;
let temp
try {
temp = setTimeout(() => {
throw new Error("NATIVE TOKEN")
}, 3000)
const ataAccountInfo = await getAccount(connection, new PublicKey(ele.tokenAta));
mintAddress = ataAccountInfo.mint;
} catch (error) {
mintAddress = NATIVE_MINT
}
console.log(2);
clearTimeout(temp)
const mintAccountInfo = await getMint(connection, mintAddress);
const { decimals, supply } = mintAccountInfo;
console.log(2);
const {
tokenName,
tokenSymbol,
tokenLogo,
} = await getMetaData(mintAddress.toBase58())
inputMsg.push({
...ele,
tokenName: tokenName,
tokenSymbol: tokenSymbol,
tokenLogo: tokenLogo,
mint: mintAddress.toBase58(),
decimals: Number(decimals),
uiAmount: Number(parseInt(ele.tokenAmount) / (10 ** decimals)),
supply: Number(supply),
})
}
if (messageStr.includes("Buy") || messageStr.includes("Sell")) {
if (messageStr.includes("Buy")) {
const amount: number = messageObj.params.result.transaction.meta.innerInstructions[0].instructions[1].parsed.info.lamports;
new PublicKey(inputMsg[0].mint);
const tokenInfo = await getPoolState(new PublicKey(inputMsg[0].mint), connection);
// @ts-ignore
await buy(keyPair, new PublicKey(inputMsg[0].mint), amount / 10 ** 9, 100, connection, tokenInfo.virtualSolReserves!, tokenInfo.virtualTokenReserves)
} else {
console.log(messageStr);
const tokenInfo = await getPoolState(new PublicKey(inputMsg[1].mint), connection);
console.log(inputMsg[1] , inputMsg[0]);
const tokenAccountAddress = getAssociatedTokenAddressSync(new PublicKey(inputMsg[1].mint) , keyPair.publicKey)
console.log(tokenAccountAddress);
// @ts-ignore
await sell(keyPair, new PublicKey(inputMsg[1].mint), new BN(inputMsg[1].tokenAmount), 0.25, connection , tokenAccountAddress , tokenInfo.virtualSolReserves!, tokenInfo.virtualTokenReserves)
}
} else {
// ** General Swap
console.log("inputMsg : ", inputMsg);
const baseToken = inputMsg[0];
const quoteToken = inputMsg[1];
console.log(`https://quote-api.jup.ag/v6/quote?inputMint=${baseToken.mint}&outputMint=${quoteToken.mint}&amount=${baseToken.tokenAmount}&slippageBps=1000`);
const quoteResponse = await (
await fetch(
`https://quote-api.jup.ag/v6/quote?inputMint=${baseToken.mint}&outputMint=${quoteToken.mint}&amount=${baseToken.tokenAmount}&slippageBps=1000`
)
).json();
console.log("🚀 ~ getBuyTxWithJupiter ~ quoteResponse:", quoteResponse)
// get serialized transactions for the swap
// deserialize the transaction
const swapTransactionBuf = Buffer.from(swapTransaction, "base64");
var transaction = VersionedTransaction.deserialize(swapTransactionBuf);
// sign the transaction
console.log("Result: ", tokenTx);
}
} else {
console.log("this is not");
}
} catch (e) { }
});
export async function sendRequest(inputpubkey: string) {
const temp: any = [];
const pubkey: any = await getAtaList(connection, inputpubkey);
for (let i = 0; i < pubkey.length; i++) {
if (!geyserList.includes(pubkey[i])) {
geyserList.push(pubkey[i]);
temp.push(pubkey[i]);
}
}
const tokenAccounts = await connection.getTokenAccountsByOwner(
keyPair.publicKey,
{
programId: TOKEN_PROGRAM_ID,
},
"confirmed"
);
console.log("🚀 ~ sendRequest ~ tokenAccounts:", tokenAccounts);
const request = {
jsonrpc: "2.0",
id: 420,
method: "transactionSubscribe",
params: [
{
failed: false,
accountInclude: temp,
},
{
commitment: "finalized",
encoding: "jsonParsed",
transactionDetails: "full",
maxSupportedTransactionVersion: 0,
},
],
};
if (temp.length > 0) {
ws.send(JSON.stringify(request));
}
}
export const buy = async (
keypair: Keypair,
mint: PublicKey,
solIn: number,
slippageDecimal: number = 0.01,
connection: Connection,
virtualSolReserves: BN,
virtualTokenReserves: BN
) => {
console.time("tx");
const buyerKeypair = keypair;
const buyerWallet = buyerKeypair.publicKey;
const tokenMint = mint;
const buyerAta = await getAssociatedTokenAddress(tokenMint, buyerWallet);
try {
const ixs: TransactionInstruction[] = [
// Increase compute budget to prioritize transaction
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1_000_000 }),
ComputeBudgetProgram.setComputeUnitLimit({ units: 100_000 }),
];
// Math.floor(txFee * 10 ** 10 / computeUnit * 10 ** 6)
// Attempt to retrieve token account, otherwise create associated token account
try {
const buyerTokenAccountInfo = await connection.getAccountInfo(buyerAta);
if (!buyerTokenAccountInfo) {
ixs.push(
createAssociatedTokenAccountInstruction(
buyerWallet,
buyerAta,
buyerWallet,
tokenMint
)
);
}
} catch (error) {
console.log("Creating token account error => ", error);
return;
}
const solInLamports = solIn * LAMPORTS_PER_SOL;
const tokenOut = Math.round(
solInLamports * virtualTokenReserves.div(virtualSolReserves).toNumber()
);
const ATA_USER = buyerAta;
const USER = buyerWallet;
// Build account key list
const keys = [
{ pubkey: GLOBAL, isSigner: false, isWritable: false },
{ pubkey: FEE_RECIPIENT, isSigner: false, isWritable: true },
{ pubkey: tokenMint, isSigner: false, isWritable: false },
{ pubkey: bonding, isSigner: false, isWritable: true },
{ pubkey: assoc_bonding_addr, isSigner: false, isWritable: true },
{ pubkey: ATA_USER, isSigner: false, isWritable: true },
{ pubkey: USER, isSigner: true, isWritable: true },
{ pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },
{ pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },
{ pubkey: RENT, isSigner: false, isWritable: false },
{ pubkey: PUMP_FUN_ACCOUNT, isSigner: false, isWritable: false },
{ pubkey: PUMP_FUN_PROGRAM, isSigner: false, isWritable: false },
];
// Slippage calculation
const calc_slippage_up = (sol_amount: number, slippage: number): number => {
const lamports = sol_amount * LAMPORTS_PER_SOL;
return Math.round(lamports * (1 + slippage));
};
const instruction_buf = Buffer.from("66063d1201daebea", "hex");
const token_amount_buf = Buffer.alloc(8);
token_amount_buf.writeBigUInt64LE(BigInt(tokenOut), 0);
const slippage_buf = Buffer.alloc(8);
slippage_buf.writeBigUInt64LE(
BigInt(calc_slippage_up(solInLamports, slippageDecimal)),
0
);
const data = Buffer.concat([
instruction_buf,
token_amount_buf,
slippage_buf,
]);
const swapInstruction = new TransactionInstruction({
keys: keys,
programId: PUMP_FUN_PROGRAM,
data: data,
});
const blockhash = await connection.getLatestBlockhash();
ixs.push(swapInstruction);
const legacyTransaction = new Transaction().add(...ixs);
legacyTransaction.recentBlockhash = blockhash.blockhash;
legacyTransaction.feePayer = buyerKeypair.publicKey;
console.timeEnd("tx");
console.log("buying token");
console.time("buy");
console.log("confirming transaction");
const sig = await sendAndConfirmTransaction(
connection,
legacyTransaction,
[buyerKeypair],
{ skipPreflight: true, preflightCommitment: "processed" }
);
console.log("Buy signature: ", `https://solscan.io/tx/${sig}`);
console.timeEnd("buy");
return sig;
} catch (e) {
console.log(`Failed to buy token, ${mint}`);
console.log("buying token error => ", e);
return false;
}
};
export const sell = async (
payerKeypair: Keypair,
mint: PublicKey,
tokenBalance: number,
slippageDecimal: number = 0.25,
connection: Connection,
tokenAccountAddress: PublicKey,
virtualSolReserves: BN,
virtualTokenReserves: BN
) => {
try {
console.log(1);
const owner = payerKeypair;
console.log(2);
const txBuilder = new Transaction();
console.log(3);
// Calculate the sell price
const tokenAccount = tokenAccountAddress;
console.log(4);
console.log(
tokenBalance,
slippageDecimal,
virtualSolReserves,
virtualTokenReserves
);
const minSolOutput = Math.floor(
tokenBalance *
virtualSolReserves.mul(new BN(1)).div(virtualTokenReserves).toNumber()
);
console.log("minSolOut: ", minSolOutput);
const keys = [
{ pubkey: GLOBAL, isSigner: false, isWritable: false },
{ pubkey: FEE_RECIPIENT, isSigner: false, isWritable: true },
{ pubkey: mint, isSigner: false, isWritable: false },
{ pubkey: bonding, isSigner: false, isWritable: true },
{ pubkey: assoc_bonding_addr, isSigner: false, isWritable: true },
{ pubkey: tokenAccount, isSigner: false, isWritable: true },
{ pubkey: owner.publicKey, isSigner: false, isWritable: true },
{ pubkey: SYSTEM_PROGRAM, isSigner: false, isWritable: false },
{ pubkey: ASSOC_TOKEN_ACC_PROG, isSigner: false, isWritable: false },
{ pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },
{ pubkey: PUMP_FUN_ACCOUNT, isSigner: false, isWritable: false },
{ pubkey: PUMP_FUN_PROGRAM, isSigner: false, isWritable: false },
];
const data = Buffer.concat([
bufferFromUInt64("12502976635542562355"),
bufferFromUInt64(tokenBalance),
bufferFromUInt64(minSolOutput),
]);
const ixs: TransactionInstruction[] = [
// Increase compute budget to prioritize transaction
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1_000_000 }),
ComputeBudgetProgram.setComputeUnitLimit({ units: 100_000 }),
];
txBuilder.add(...ixs);
const instruction = new TransactionInstruction({
keys: keys,
programId: PUMP_FUN_PROGRAM,
data: data,
});
txBuilder.add(instruction);
txBuilder.feePayer = owner.publicKey;
txBuilder.recentBlockhash = (
await connection.getLatestBlockhash()
).blockhash;
// console.log(transaction);
console.log(await connection.simulateTransaction(txBuilder));
const signature = await sendAndConfirmTransaction(
connection,
txBuilder,
[owner],
{ skipPreflight: true, preflightCommitment: "processed" }
);
if (signature) {
console.log("Sell transaction confirmed:", signature);
}
} catch (error) {
console.log(error);
}
};