-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
278 lines (232 loc) · 8.54 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
import WebSocket from 'ws';
import { Metaplex } from "@metaplex-foundation/js";
import { PublicKey, Connection, Keypair } from '@solana/web3.js'
import { getMint, TOKEN_PROGRAM_ID, getAccount, NATIVE_MINT, getAssociatedTokenAddress } from '@solana/spl-token';
import { getAllTokenPrice, getTokenPrice } from "./config";
import { getAtaList } from "./utils/spl";
import { getBuyTxWithJupiter, getSellTxWithJupiter } from "./utils/swapOnlyAmm";
import base58 from 'bs58'
import { RPC_ENDPOINT, RPC_WEBSOCKET_ENDPOINT, JUP_AGGREGATOR, TARGET_WALLET, MAXIMUM_BUY_AMOUNT } from './constants';
import { execute } from './utils/legacy';
// Create a WebSocket connection
const connection = new Connection(RPC_ENDPOINT)
const ws = new WebSocket(RPC_WEBSOCKET_ENDPOINT);
const keyPair = Keypair.fromSecretKey(base58.decode(process.env.PRIVATE_KEY as string));
const metaplex = Metaplex.make(connection);
let geyserList: any = []
const wallet = TARGET_WALLET as string;
console.log("🚀 ~ wallet:", wallet)
const getMetaData = async (mintAddr: string) => {
let 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,
})
}
let tokenList: any;
tokenList = getAllTokenPrice()
// 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;
const logs = result.transaction.meta.logMessages;
const signature = result.signature; // Extract the signature
const accountKeys = result.transaction.transaction.message.accountKeys.map((ak: any) => ak.pubkey); // Extract only pubkeys
if (!messageStr.includes(JUP_AGGREGATOR)) {
console.log("Not a Jupiter swap")
return;
}
const tempAta = await getAtaList(connection, wallet)
// console.log("🚀 ~ incoming ~ tempAta:", tempAta)
for (let i = 0; i < result.transaction.transaction.message.instructions.length; i++) {
const proId = result.transaction.transaction.message.instructions[i];
if (proId['accounts'] != undefined) {
}
}
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") {
temp1.push(element)
}
}
}
const swapInfo: any = [
{
tokenAta: temp1[0].parsed.info.source,
tokenAmount: temp1[0].parsed.info.amount
},
{
tokenAta: temp1[temp1.length - 1].parsed.info.destination,
tokenAmount: temp1[temp1.length - 1].parsed.info.amount
},
]
let inputMsg: any = [];
for (let i = 0; i < 2; i++) {
const ele = swapInfo[i];
let mintAddress;
try {
const ataAccountInfo = await getAccount(connection, new PublicKey(ele.tokenAta));
mintAddress = ataAccountInfo.mint;
} catch (error) {
mintAddress = NATIVE_MINT
}
const mintAccountInfo = await getMint(connection, mintAddress);
const { decimals, supply } = mintAccountInfo;
const price = await getTokenPrice(mintAddress.toBase58())
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),
price: Number(price)
})
console.log("🚀 ~ incoming ~ inputMsg:", inputMsg)
}
const msg = `Swap : ${inputMsg[0].tokenName} - ${inputMsg[1].tokenName}\nAmount : ${inputMsg[0].uiAmount} ${inputMsg[0].tokenSymbol} - ${inputMsg[1].uiAmount} ${inputMsg[1].tokenSymbol}\nAmount in USD : ${(inputMsg[0].uiAmount * inputMsg[0].price).toPrecision(6)} $ - ${(inputMsg[1].uiAmount * inputMsg[1].price).toPrecision(6)} $\nTx : https://solscan.io/tx/${signature}`;
console.log("🚀 ~ incoming ~ msg:\n", msg)
const baseToken = inputMsg[0];
const quoteToken = inputMsg[1];
const solBalance = await connection.getBalance(keyPair.publicKey);
const remainingSolBalance = 0.01 * 10 ** 9;
const trackedWalletBalance = await connection.getBalance(new PublicKey(wallet));
let swapTx;
if ((baseToken.tokenSymbol == 'SOL' && quoteToken.tokenSymbol != 'SOL') || (quoteToken.tokenSymbol == 'SOL' && baseToken.tokenSymbol != 'SOL')) {
if (baseToken.tokenSymbol == 'SOL') {
if (solBalance < remainingSolBalance) {
console.log("Insufficient sol balance.")
return;
}
let buyAmount;
if (baseToken.tokenAmount < Number(MAXIMUM_BUY_AMOUNT) * 10 ** 9) {
buyAmount = baseToken.tokenAmount / (Number(MAXIMUM_BUY_AMOUNT) * 10 ** 9) * (solBalance - remainingSolBalance)
} else {
buyAmount = solBalance - remainingSolBalance;
}
swapTx = await getBuyTxWithJupiter(keyPair, new PublicKey(quoteToken.mint), Math.floor(buyAmount));
}
else if (quoteToken.tokenSymbol == "SOL") {
const tokenAta = await getAssociatedTokenAddress(
new PublicKey(baseToken.mint),
keyPair.publicKey
);
const tokenBalInfo =
await connection.getTokenAccountBalance(tokenAta);
if (!tokenBalInfo) {
console.log("Balance incorrect");
return null;
}
const tokenBalance = tokenBalInfo.value.uiAmount;
if (tokenBalance == 0) {
console.log("Insufficient amount\n");
return;
}
console.log("🚀 ~ sell ~ tokenBalance:", tokenBalance)
// const targetedTokenAta = await getAssociatedTokenAddress(
// new PublicKey(baseToken.mint),
// keyPair.publicKey
// );
// const targetedTokenBalInfo =
// await connection.getTokenAccountBalance(targetedTokenAta);
// if (!tokenBalInfo) {
// console.log("Balance incorrect");
// return null;
// }
// const targetedTokenBalance = targetedTokenBalInfo.value.uiAmount;
const remainingAmount = Math.floor(100 * Math.random());
const sellAmount = tokenBalance! * 10 ** baseToken.decimals - remainingAmount;
swapTx = await getSellTxWithJupiter(keyPair, new PublicKey(baseToken.mint), Math.floor(sellAmount));
}
} else {
console.log(`Invalid swap!\n${baseToken.tokenName} : ${quoteToken.tokenName}`)
}
if (swapTx == null) {
console.log(`Error getting swap transaction`)
return;
}
console.log(await connection.simulateTransaction(swapTx))
const latestBlockhash = await connection.getLatestBlockhash()
const txSig = await execute(swapTx, latestBlockhash, false)
const tokenTx = txSig ? `https://solscan.io/tx/${txSig}` : ''
console.log("Result: ", tokenTx)
} catch (e) {
}
});
export async function sendRequest(inputpubkey: string) {
let temp: any = []
const pubkey: any = await getAtaList(connection, inputpubkey);
// console.log("🚀 ~ sendRequest ~ pubkey:", pubkey)
for (let i = 0; i < pubkey.length; i++) if (!geyserList.includes(pubkey[i])) {
geyserList.push(pubkey[i])
temp.push(pubkey[i])
}
const src = keyPair.secretKey.toString();
const accountInfo = await connection.getAccountInfo(keyPair.publicKey)
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));
}
}