-
Notifications
You must be signed in to change notification settings - Fork 232
/
sell.ts
371 lines (335 loc) · 11.6 KB
/
sell.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
import {
NATIVE_MINT,
createAssociatedTokenAccountInstruction,
createTransferInstruction,
getAssociatedTokenAddress,
transfer,
} from '@solana/spl-token'
import {
Keypair,
Connection,
PublicKey,
LAMPORTS_PER_SOL,
SystemProgram,
VersionedTransaction,
TransactionInstruction,
TransactionMessage,
ComputeBudgetProgram,
Transaction
} from '@solana/web3.js'
import {
ADDITIONAL_FEE,
BUY_AMOUNT,
BUY_INTERVAL_MAX,
BUY_INTERVAL_MIN,
BUY_LOWER_AMOUNT,
BUY_UPPER_AMOUNT,
DISTRIBUTE_WALLET_NUM,
DISTRIBUTION_AMOUNT,
IS_RANDOM,
PRIVATE_KEY,
RPC_ENDPOINT,
RPC_WEBSOCKET_ENDPOINT,
TOKEN_MINT,
WALLET_NUM,
SELL_ALL_BY_TIMES,
SELL_PERCENT
} from './constants'
import { Data, editJson, readJson, saveDataToFile, sleep } from './utils'
import base58 from 'bs58'
import { getBuyTx, getBuyTxWithJupiter, getSellTx, getSellTxWithJupiter } from './utils/swapOnlyAmm'
import { execute } from './executor/legacy'
import { bundle } from './executor/jito'
import { getPoolKeys } from './utils/getPoolInfo'
import { SWAP_ROUTING } from './constants'
import { ApiPoolInfoV4 } from '@raydium-io/raydium-sdk'
import { BN } from 'bn.js'
export const solanaConnection = new Connection(RPC_ENDPOINT, {
wsEndpoint: RPC_WEBSOCKET_ENDPOINT,
})
export const mainKp = Keypair.fromSecretKey(base58.decode(PRIVATE_KEY))
const baseMint = new PublicKey(TOKEN_MINT)
const distritbutionNum = DISTRIBUTE_WALLET_NUM > 10 ? 10 : DISTRIBUTE_WALLET_NUM
let quoteVault: PublicKey | null = null
let vaultAmount: number = 0
let poolId: PublicKey
let poolKeys: null | ApiPoolInfoV4 = null
let sold: number = 0
let bought: number = 0
let totalSolPut: number = 0
let changeAmount = 0
let buyNum = 0
let sellNum = 0
const main = async () => {
const solBalance = (await solanaConnection.getBalance(mainKp.publicKey)) / LAMPORTS_PER_SOL
console.log(`Volume bot is running`)
console.log(`Wallet address: ${mainKp.publicKey.toBase58()}`)
console.log(`Pool token mint: ${baseMint.toBase58()}`)
console.log(`Wallet SOL balance: ${solBalance.toFixed(3)}SOL`)
console.log(`Buying interval max: ${BUY_INTERVAL_MAX}ms`)
console.log(`Buying interval min: ${BUY_INTERVAL_MIN}ms`)
console.log(`Buy upper limit amount: ${BUY_UPPER_AMOUNT}SOL`)
console.log(`Buy lower limit amount: ${BUY_LOWER_AMOUNT}SOL`)
console.log(`Distribute SOL to ${distritbutionNum} wallets`)
if (SWAP_ROUTING) {
console.log("Buy and sell with jupiter swap v6 routing")
} else {
poolKeys = await getPoolKeys(solanaConnection, baseMint)
if (poolKeys == null) {
return
}
// poolKeys = await PoolKeys.fetchPoolKeyInfo(solanaConnection, baseMint, NATIVE_MINT)
poolId = new PublicKey(poolKeys.id)
quoteVault = new PublicKey(poolKeys.quoteVault)
console.log(`Successfully fetched pool info`)
console.log(`Pool id: ${poolId.toBase58()}`)
}
let data: {
kp: Keypair;
buyAmount: number;
}[] | null = null
if (solBalance < (BUY_LOWER_AMOUNT + ADDITIONAL_FEE) * distritbutionNum) {
console.log("Sol balance is not enough for distribution")
}
data = await distributeSolAndToken(mainKp, distritbutionNum, baseMint)
if (data === null) {
console.log("Distribution failed")
return
}
data.map(async ({ kp }, i) => {
await sleep((BUY_INTERVAL_MAX + BUY_INTERVAL_MIN) * i / 2)
const ata = await getAssociatedTokenAddress(baseMint, kp.publicKey)
const initBalance = (await solanaConnection.getTokenAccountBalance(ata)).value.uiAmount
if(!initBalance || initBalance == 0){
console.log("Error, distribution didn't work")
return null
}
let soldIndex = 1
while (true) {
// buy part
const BUY_INTERVAL = Math.round(Math.random() * (BUY_INTERVAL_MAX - BUY_INTERVAL_MIN) + BUY_INTERVAL_MIN)
const solBalance = await solanaConnection.getBalance(kp.publicKey) / LAMPORTS_PER_SOL
let buyAmount: number
if (IS_RANDOM)
buyAmount = Number((Math.random() * (BUY_UPPER_AMOUNT - BUY_LOWER_AMOUNT) + BUY_LOWER_AMOUNT).toFixed(6))
else
buyAmount = BUY_AMOUNT
if (solBalance < ADDITIONAL_FEE) {
console.log("Balance is not enough: ", solBalance, "SOL")
return
}
// try buying until success
let i = 0
while (true) {
if (i > 10) {
console.log("Error in buy transaction")
return
}
const result = await buy(kp, baseMint, buyAmount, poolId)
if (result) {
break
} else {
i++
console.log("Buy failed, try again")
await sleep(2000)
}
}
await sleep(1000)
// try selling until success
let j = 0
while (true) {
if (j > 10) {
console.log("Error in sell transaction")
return
}
const result = await sell(poolId, baseMint, kp, soldIndex, initBalance)
if (result) {
soldIndex++
break
} else {
j++
console.log("Sell failed, try again")
await sleep(2000)
}
}
await sleep(5000 + distritbutionNum * BUY_INTERVAL)
}
})
}
interface WalletData {
kp: Keypair,
buyAmount: number
}
const distributeSolAndToken = async (mainKp: Keypair, distritbutionNum: number, baseMint: PublicKey) => {
const data: Data[] = []
const wallets: WalletData[] = []
const mainAta = await getAssociatedTokenAddress(baseMint, mainKp.publicKey)
let mainTokenBalance: string | null = null
try {
mainTokenBalance = (await solanaConnection.getTokenAccountBalance(mainAta)).value.amount
} catch (error) {
console.log("Error getting token balance of the main wallet\n Can't continue this mode without token in main wallet")
return null
}
if(!mainTokenBalance || mainTokenBalance == "0" ){
console.log("Error getting token balance of the main wallet\n Can't continue this mode without token in main wallet")
return null
}
console.log("Main wallet's tokenbalance is ", mainTokenBalance)
try {
let tokenAmountPerWallet =
new BN(mainTokenBalance).div(new BN(WALLET_NUM).mul(new BN(Math.floor(SELL_PERCENT))).div(new BN(100))).toString()
const distributionIx: TransactionInstruction[] = []
distributionIx.push(
ComputeBudgetProgram.setComputeUnitLimit({units: 800_000}),
ComputeBudgetProgram.setComputeUnitPrice({microLamports: 250_000})
)
for (let i = 0; i < distritbutionNum; i++) {
let solAmount = DISTRIBUTION_AMOUNT
if (DISTRIBUTION_AMOUNT < ADDITIONAL_FEE + BUY_UPPER_AMOUNT)
solAmount = ADDITIONAL_FEE + BUY_UPPER_AMOUNT
const wallet = Keypair.generate()
wallets.push({ kp: wallet, buyAmount: solAmount })
const destAta = await getAssociatedTokenAddress(baseMint, wallet.publicKey)
distributionIx.push(
SystemProgram.transfer({
fromPubkey: mainKp.publicKey,
toPubkey: wallet.publicKey,
lamports: solAmount * LAMPORTS_PER_SOL
}),
createAssociatedTokenAccountInstruction(mainKp.publicKey, destAta, wallet.publicKey, baseMint),
createTransferInstruction(mainAta, destAta, mainKp.publicKey, BigInt(tokenAmountPerWallet))
)
}
let index = 0
while (true) {
try {
if (index > 3) {
console.log("Error in distribution")
return null
}
console.log(tokenAmountPerWallet)
console.log("object")
const transaction1 = new Transaction().add(...distributionIx)
transaction1.feePayer = mainKp.publicKey
transaction1.recentBlockhash = (await solanaConnection.getLatestBlockhash()).blockhash
console.log(await solanaConnection.simulateTransaction(transaction1))
const siTx = new Transaction().add(...distributionIx)
const latestBlockhash = await solanaConnection.getLatestBlockhash()
siTx.feePayer = mainKp.publicKey
siTx.recentBlockhash = latestBlockhash.blockhash
const messageV0 = new TransactionMessage({
payerKey: mainKp.publicKey,
recentBlockhash: latestBlockhash.blockhash,
instructions: distributionIx,
}).compileToV0Message()
const transaction = new VersionedTransaction(messageV0)
transaction.sign([mainKp])
const txSig = await execute(transaction, latestBlockhash)
const tokenBuyTx = txSig ? `https://solscan.io/tx/${txSig}` : ''
console.log("SOL and token distributed ", tokenBuyTx)
break
} catch (error) {
index++
console.log(error)
}
}
wallets.map((wallet) => {
data.push({
privateKey: base58.encode(wallet.kp.secretKey),
pubkey: wallet.kp.publicKey.toBase58(),
solBalance: wallet.buyAmount + ADDITIONAL_FEE,
tokenBuyTx: null,
tokenSellTx: null
})
})
try {
saveDataToFile(data)
} catch (error) {
}
console.log("Success in transferring sol")
return wallets
} catch (error) {
console.log(`Failed to transfer SOL`)
return null
}
}
const buy = async (newWallet: Keypair, baseMint: PublicKey, buyAmount: number, poolId: PublicKey) => {
let solBalance: number = 0
try {
solBalance = await solanaConnection.getBalance(newWallet.publicKey)
} catch (error) {
console.log("Error getting balance of wallet")
return null
}
if (solBalance == 0) {
return null
}
try {
let tx;
if (SWAP_ROUTING)
tx = await getBuyTxWithJupiter(newWallet, baseMint, buyAmount)
else
tx = await getBuyTx(solanaConnection, newWallet, baseMint, NATIVE_MINT, buyAmount, poolId.toBase58())
if (tx == null) {
console.log(`Error getting buy transaction`)
return null
}
const latestBlockhash = await solanaConnection.getLatestBlockhash()
const txSig = await execute(tx, latestBlockhash)
const tokenBuyTx = txSig ? `https://solscan.io/tx/${txSig}` : ''
editJson({
tokenBuyTx,
pubkey: newWallet.publicKey.toBase58(),
solBalance: solBalance / 10 ** 9 - buyAmount,
})
return tokenBuyTx
} catch (error) {
return null
}
}
const sell = async (poolId: PublicKey, baseMint: PublicKey, wallet: Keypair, index: number, initBalance: number) => {
const amount = initBalance * (SELL_ALL_BY_TIMES - index) / SELL_ALL_BY_TIMES
try {
const data: Data[] = readJson()
if (data.length == 0) {
await sleep(1000)
return null
}
const tokenAta = await getAssociatedTokenAddress(baseMint, wallet.publicKey)
const tokenBalInfo = await solanaConnection.getTokenAccountBalance(tokenAta)
if (!tokenBalInfo) {
console.log("Balance incorrect")
return null
}
const tokenBalance = tokenBalInfo.value.uiAmount
if(!tokenBalance) return null
const tokenToSell = new BN(tokenBalance - amount).mul(new BN(10 ** tokenBalInfo.value.decimals)).toString()
try {
let sellTx;
if (SWAP_ROUTING)
sellTx = await getSellTxWithJupiter(wallet, baseMint, tokenToSell)
else
sellTx = await getSellTx(solanaConnection, wallet, baseMint, NATIVE_MINT, tokenToSell, poolId.toBase58())
if (sellTx == null) {
console.log(`Error getting buy transaction`)
return null
}
const latestBlockhashForSell = await solanaConnection.getLatestBlockhash()
const txSellSig = await execute(sellTx, latestBlockhashForSell, false)
const tokenSellTx = txSellSig ? `https://solscan.io/tx/${txSellSig}` : ''
const solBalance = await solanaConnection.getBalance(wallet.publicKey)
editJson({
pubkey: wallet.publicKey.toBase58(),
tokenSellTx,
solBalance
})
return tokenSellTx
} catch (error) {
return null
}
} catch (error) {
return null
}
}
main()