-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.ts
289 lines (260 loc) · 9.58 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
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 () => {
};
// 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)