-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.ts
373 lines (340 loc) · 12.9 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
import {
PublicKey, Keypair, Connection, Transaction, ComputeBudgetProgram,
sendAndConfirmTransaction, VersionedTransaction, TransactionMessage,
TransactionInstruction, SystemProgram,
} from "@solana/web3.js";
import {
NATIVE_MINT, TOKEN_PROGRAM_ID, createTransferCheckedInstruction,
createAssociatedTokenAccountIdempotentInstruction,
createCloseAccountInstruction, getAssociatedTokenAddress, getMint, getMinimumBalanceForRentExemptAccount,
createSyncNativeInstruction
} from "@solana/spl-token";
import base58 from "bs58";
import path from 'path'
import fs from 'fs'
import { retrieveEnvVariable, saveDataToFile, sleep } from "./src/utils";
import { bundle } from "./src/jito";
import { Liquidity, LiquidityPoolKeysV4, MAINNET_PROGRAM_ID, InstructionType, Percent, CurrencyAmount, Token, SOL, LiquidityPoolInfo } from "@raydium-io/raydium-sdk";
import { derivePoolKeys } from "./src/poolAll";
import { lookupTableProvider } from "./src/lut";
import { BN } from "bn.js";
import { ConnectedLeadersRegionedRequest } from "jito-ts/dist/gen/block-engine/searcher";
// Environment Variables3
const baseMintStr = retrieveEnvVariable('BASE_MINT');
const mainKpStr = retrieveEnvVariable('MAIN_KP');
const rpcUrl = retrieveEnvVariable("RPC_URL");
const isJito: boolean = retrieveEnvVariable("IS_JITO") === "true";
let buyMax = Number(retrieveEnvVariable('SOL_BUY_MAX'));
let buyMin = Number(retrieveEnvVariable('SOL_BUY_MIN'));
let interval = Number(retrieveEnvVariable('INTERVAL'));
const jito_tx_interval = Number(retrieveEnvVariable('JITO_TX_TIME_INTERVAL')) > 10 ?
Number(retrieveEnvVariable('JITO_TX_TIME_INTERVAL')) : 10
const poolId = retrieveEnvVariable('POOL_ID');
// Solana Connection and Keypair
const connection = new Connection(rpcUrl, { commitment: "processed" });
const mainKp = Keypair.fromSecretKey(base58.decode(mainKpStr));
const baseMint = new PublicKey(baseMintStr);
let poolKeys: LiquidityPoolKeysV4 | null = null;
let tokenAccountRent: number | null = null;
let decimal: number | null = null;
let poolInfo: LiquidityPoolInfo | null = null;
let maker = 0
let now = Date.now()
let unconfirmedKps: Keypair[] = []
/**
* Executes a buy and sell transaction for a given token.
* @param {PublicKey} token - The token's public key.
*/
const buySellToken = async (token: PublicKey, newWallet: Keypair, solBuyAmountLamports: number) => {
try {
if (!tokenAccountRent)
tokenAccountRent = await getMinimumBalanceForRentExemptAccount(connection);
if (!decimal)
decimal = (await getMint(connection, token)).decimals;
if (!poolKeys) {
poolKeys = await derivePoolKeys(new PublicKey(poolId))
if (!poolKeys) {
console.log("Pool keys is not derived")
return
}
}
// const solBuyAmountLamports = Math.floor((Math.random() * (buyMax - buyMin) + buyMin) * 10 ** 9);
const quoteAta = await getAssociatedTokenAddress(NATIVE_MINT, mainKp.publicKey);
const baseAta = await getAssociatedTokenAddress(token, mainKp.publicKey);
const newWalletBaseAta = await getAssociatedTokenAddress(token, newWallet.publicKey);
const newWalletQuoteAta = await getAssociatedTokenAddress(NATIVE_MINT, newWallet.publicKey);
const slippage = new Percent(100, 100);
const inputTokenAmount = new CurrencyAmount(SOL, solBuyAmountLamports);
const outputToken = new Token(TOKEN_PROGRAM_ID, baseMint, decimal);
if (!poolInfo)
poolInfo = await Liquidity.fetchInfo({ connection, poolKeys })
const { amountOut, minAmountOut } = Liquidity.computeAmountOut({
poolKeys,
poolInfo,
amountIn: inputTokenAmount,
currencyOut: outputToken,
slippage,
});
const { amountIn, maxAmountIn } = Liquidity.computeAmountIn({
poolKeys,
poolInfo,
amountOut,
currencyIn: SOL,
slippage
})
const { innerTransaction: innerBuyIxs } = Liquidity.makeSwapFixedOutInstruction(
{
poolKeys: poolKeys,
userKeys: {
tokenAccountIn: quoteAta,
tokenAccountOut: baseAta,
owner: mainKp.publicKey,
},
maxAmountIn: maxAmountIn.raw,
amountOut: amountOut.raw,
},
poolKeys.version,
)
const { innerTransaction: innerSellIxs } = Liquidity.makeSwapFixedInInstruction(
{
poolKeys: poolKeys,
userKeys: {
tokenAccountIn: baseAta,
tokenAccountOut: quoteAta,
owner: mainKp.publicKey,
},
amountIn: amountOut.raw.sub(new BN(10 ** decimal)),
minAmountOut: 0,
},
poolKeys.version,
);
const instructions: TransactionInstruction[] = [];
const latestBlockhash = await connection.getLatestBlockhash();
instructions.push(
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 500_000 }),
ComputeBudgetProgram.setComputeUnitLimit({ units: 100_000 }),
createAssociatedTokenAccountIdempotentInstruction(
mainKp.publicKey,
newWalletBaseAta,
newWallet.publicKey,
baseMint,
),
...innerBuyIxs.instructions,
createTransferCheckedInstruction(
baseAta,
baseMint,
newWalletBaseAta,
mainKp.publicKey,
10 ** decimal,
decimal
),
...innerSellIxs.instructions,
SystemProgram.transfer({
fromPubkey: newWallet.publicKey,
toPubkey: mainKp.publicKey,
lamports: 1_002_304,
}),
)
const messageV0 = new TransactionMessage({
payerKey: newWallet.publicKey,
recentBlockhash: latestBlockhash.blockhash,
instructions,
}).compileToV0Message()
const transaction = new VersionedTransaction(messageV0);
transaction.sign([mainKp, newWallet])
if (isJito)
return transaction
// console.log(await connection.simulateTransaction(transaction))
const sig = await connection.sendRawTransaction(transaction.serialize(), { skipPreflight: true })
const confirmation = await connection.confirmTransaction(
{
signature: sig,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
blockhash: latestBlockhash.blockhash,
},
"confirmed"
)
if (confirmation.value.err) {
console.log("Confrimtaion error")
return newWallet
} else {
maker++
console.log(`Buy and sell transaction: https://solscan.io/tx/${sig} and maker is ${maker}`);
}
} catch (error) {
}
};
/**
* Wraps the given amount of SOL into WSOL.
* @param {Keypair} mainKp - The central keypair which holds SOL.
* @param {number} wsolAmount - The amount of SOL to wrap.
*/
const wrapSol = async (mainKp: Keypair, wsolAmount: number) => {
try {
const wSolAccount = await getAssociatedTokenAddress(NATIVE_MINT, mainKp.publicKey);
const baseAta = await getAssociatedTokenAddress(baseMint, mainKp.publicKey);
const tx = new Transaction().add(
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 461197 }),
ComputeBudgetProgram.setComputeUnitLimit({ units: 51337 }),
);
// if (!await connection.getAccountInfo(wSolAccount))
tx.add(
createAssociatedTokenAccountIdempotentInstruction(
mainKp.publicKey,
wSolAccount,
mainKp.publicKey,
NATIVE_MINT,
),
SystemProgram.transfer({
fromPubkey: mainKp.publicKey,
toPubkey: wSolAccount,
lamports: wsolAmount,
}),
createSyncNativeInstruction(wSolAccount, TOKEN_PROGRAM_ID),
)
if (!await connection.getAccountInfo(baseAta))
tx.add(
createAssociatedTokenAccountIdempotentInstruction(
mainKp.publicKey,
baseAta,
mainKp.publicKey,
baseMint,
),
)
tx.recentBlockhash = (await connection.getLatestBlockhash()).blockhash
tx.feePayer = mainKp.publicKey
const sig = await sendAndConfirmTransaction(connection, tx, [mainKp], { skipPreflight: true, commitment: "confirmed" });
console.log(`Wrapped SOL transaction: https://solscan.io/tx/${sig}`);
await sleep(5000);
} catch (error) {
console.error("wrapSol error");
}
};
/**
* Unwraps WSOL into SOL.
* @param {Keypair} mainKp - The main keypair.
*/
const unwrapSol = async (mainKp: Keypair) => {
const wSolAccount = await getAssociatedTokenAddress(NATIVE_MINT, mainKp.publicKey);
try {
const wsolAccountInfo = await connection.getAccountInfo(wSolAccount);
if (wsolAccountInfo) {
const tx = new Transaction().add(
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 261197 }),
ComputeBudgetProgram.setComputeUnitLimit({ units: 101337 }),
createCloseAccountInstruction(
wSolAccount,
mainKp.publicKey,
mainKp.publicKey,
),
);
tx.recentBlockhash = (await connection.getLatestBlockhash()).blockhash
tx.feePayer = mainKp.publicKey
const sig = await sendAndConfirmTransaction(connection, tx, [mainKp], { skipPreflight: true, commitment: "confirmed" });
console.log(`Unwrapped SOL transaction: https://solscan.io/tx/${sig}`);
await sleep(5000);
}
} catch (error) {
console.error("unwrapSol error:", error);
}
};
function loadInterval() {
const data = fs.readFileSync(path.join(__dirname, 'interval.txt'), 'utf-8')
const num = Number(data.trim())
if(isNaN(num)) {
console.log("Interval number in interval.txt is incorrect, plz fix and run again")
return
}
interval = num
}
/**
* Main function to run the maker bot.
*/
const run = async () => {
try {
let balance = await connection.getBalance(mainKp.publicKey)
let wsolBalance = 0
const quoteAta = await getAssociatedTokenAddress(NATIVE_MINT, mainKp.publicKey);
const baseAta = await getAssociatedTokenAddress(baseMint, mainKp.publicKey);
if (await (connection.getAccountInfo(quoteAta))) {
const wsolBal = Number((await connection.getTokenAccountBalance(quoteAta)).value.amount)
wsolBalance = wsolBal
}
console.log("Main wallet address, ", mainKp.publicKey.toBase58())
const processNum = 10 // 10 processes run simultaneously
const feeAmountForSwap = 2 * 10 ** 9 // 2SOL
if (balance < feeAmountForSwap) {
console.log("Sol amount is not enough to run the volume bot")
return
}
const amountToWrap = balance - feeAmountForSwap
const transaction = new Transaction().add(
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 461197 }),
ComputeBudgetProgram.setComputeUnitLimit({ units: 51337 }),
createAssociatedTokenAccountIdempotentInstruction(
mainKp.publicKey,
quoteAta,
mainKp.publicKey,
NATIVE_MINT,
),
SystemProgram.transfer({
fromPubkey: mainKp.publicKey,
toPubkey: quoteAta,
lamports: amountToWrap,
}),
createSyncNativeInstruction(quoteAta, TOKEN_PROGRAM_ID),
createAssociatedTokenAccountIdempotentInstruction(
mainKp.publicKey,
baseAta,
mainKp.publicKey,
baseMint,
),
)
const sig = await sendAndConfirmTransaction(connection, transaction, [mainKp], { skipPreflight: true, commitment: "confirmed" })
console.log("Successfully wrapped SOL to wSOL")
const wsolBalForEach = Number((await connection.getTokenAccountBalance(quoteAta)).value.amount) / processNum
const wallets: number[] = new Array(processNum).fill(0)
try {
wallets.forEach(async _ => {
let balanceForEach = wsolBalForEach
while (true) {
try {
const kp = Keypair.generate()
const transaction = new Transaction().add(
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 7_000_000 }),
ComputeBudgetProgram.setComputeUnitLimit({ units: 2_000 }),
SystemProgram.transfer({
fromPubkey: mainKp.publicKey,
toPubkey: kp.publicKey,
lamports: 1_062_304 // 0.000910000
})
)
const sig = await sendAndConfirmTransaction(connection, transaction, [mainKp], { commitment: "confirmed", skipPreflight: true })
console.log("Sent SOL to wallet ", kp.publicKey.toBase58(), " ", `https://solscan.io/tx/${sig}`)
saveDataToFile([base58.encode(kp.secretKey)])
if (balanceForEach <= 10 ** 7) {
console.log("Balance is not enough to run volume bot")
return
}
balanceForEach -= 10 ** 6
const buyAmount = Math.floor(balanceForEach - (balanceForEach / 3 * Math.random()))
await buySellToken(baseMint, kp, buyAmount)
} catch (error) {
console.log("Error in buy sell")
}
}
});
} catch (e) {
console.log("Distribution for first run failed, ending the process")
return
}
} catch (error) {
console.log("Running error:", error)
}
};
// Main function that runs the bot
run();
// You can run the wrapSOL function to wrap some sol in central wallet for any reasone
// wrapSol(mainKp, 0.2)
// unWrapSOl function to unwrap all WSOL in central wallet that is in the wallet
// unwrapSol(mainKp)