-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.ts
325 lines (289 loc) · 12.8 KB
/
bot.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
import { Keypair, Connection, PublicKey, VersionedTransaction, LAMPORTS_PER_SOL, TransactionInstruction, AddressLookupTableAccount, TransactionMessage } from "@solana/web3.js";
import { createJupiterApiClient, DefaultApi, ResponseError, QuoteGetRequest, QuoteResponse, Instruction, AccountMeta } from '@jup-ag/api';
import { getAssociatedTokenAddressSync } from "@solana/spl-token";
import * as fs from 'fs';
import * as path from 'path';
interface ArbBotConfig {
solanaEndpoint: string; // e.g., "https://ex-am-ple.solana-mainnet.quiknode.pro/123456/"
metisEndpoint: string; // e.g., "https://jupiter-swap-api.quiknode.pro/123456/"
secretKey: Uint8Array;
firstTradePrice: number; // e.g. 94 USDC/SOL
targetGainPercentage?: number;
checkInterval?: number;
initialInputToken: SwapToken;
initialInputAmount: number;
}
interface NextTrade extends QuoteGetRequest {
nextTradeThreshold: number;
}
export enum SwapToken {
SOL,
USDC
}
interface LogSwapArgs {
inputToken: string;
inAmount: string;
outputToken: string;
outAmount: string;
txId: string;
timestamp: string;
}
export class ArbBot {
private solanaConnection: Connection;
private jupiterApi: DefaultApi;
private wallet: Keypair;
private usdcMint: PublicKey = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
private solMint: PublicKey = new PublicKey("So11111111111111111111111111111111111111112");
private usdcTokenAccount: PublicKey;
private solBalance: number = 0;
private usdcBalance: number = 0;
private checkInterval: number = 1000 * 10;
private lastCheck: number = 0;
private priceWatchIntervalId?: NodeJS.Timeout;
private targetGainPercentage: number = 1;
private nextTrade: NextTrade;
private waitingForConfirmation: boolean = false;
constructor(config: ArbBotConfig) {
const {
solanaEndpoint,
metisEndpoint,
secretKey,
targetGainPercentage,
checkInterval,
initialInputToken,
initialInputAmount,
firstTradePrice
} = config;
this.solanaConnection = new Connection(solanaEndpoint);
this.jupiterApi = createJupiterApiClient({ basePath: metisEndpoint });
this.wallet = Keypair.fromSecretKey(secretKey);
this.usdcTokenAccount = getAssociatedTokenAddressSync(this.usdcMint, this.wallet.publicKey);
if (targetGainPercentage) { this.targetGainPercentage = targetGainPercentage }
if (checkInterval) { this.checkInterval = checkInterval }
this.nextTrade = {
inputMint: initialInputToken === SwapToken.SOL ? this.solMint.toBase58() : this.usdcMint.toBase58(),
outputMint: initialInputToken === SwapToken.SOL ? this.usdcMint.toBase58() : this.solMint.toBase58(),
amount: initialInputAmount,
nextTradeThreshold: firstTradePrice,
};
}
async init(): Promise<void> {
console.log(`🤖 Initiating arb bot for wallet: ${this.wallet.publicKey.toBase58()}.`)
await this.refreshBalances();
console.log(`🏦 Current balances:\nSOL: ${this.solBalance / LAMPORTS_PER_SOL},\nUSDC: ${this.usdcBalance}`);
this.initiatePriceWatch();
}
private async refreshBalances(): Promise<void> {
try {
const results = await Promise.allSettled([
this.solanaConnection.getBalance(this.wallet.publicKey),
this.solanaConnection.getTokenAccountBalance(this.usdcTokenAccount)
]);
const solBalanceResult = results[0];
const usdcBalanceResult = results[1];
if (solBalanceResult.status === 'fulfilled') {
this.solBalance = solBalanceResult.value;
} else {
console.error('Error fetching SOL balance:', solBalanceResult.reason);
}
if (usdcBalanceResult.status === 'fulfilled') {
this.usdcBalance = usdcBalanceResult.value.value.uiAmount ?? 0;
} else {
this.usdcBalance = 0;
}
if (this.solBalance < LAMPORTS_PER_SOL / 100) {
this.terminateSession("Low SOL balance.");
}
} catch (error) {
console.error('Unexpected error during balance refresh:', error);
}
}
private initiatePriceWatch(): void {
this.priceWatchIntervalId = setInterval(async () => {
const currentTime = Date.now();
if (currentTime - this.lastCheck >= this.checkInterval) {
this.lastCheck = currentTime;
try {
if (this.waitingForConfirmation) {
console.log('Waiting for previous transaction to confirm...');
return;
}
const quote = await this.getQuote(this.nextTrade);
this.evaluateQuoteAndSwap(quote);
} catch (error) {
console.error('Error getting quote:', error);
}
}
}, this.checkInterval);
}
private async getQuote(quoteRequest: QuoteGetRequest): Promise<QuoteResponse> {
try {
const quote: QuoteResponse | null = await this.jupiterApi.quoteGet(quoteRequest);
if (!quote) {
throw new Error('No quote found');
}
return quote;
} catch (error) {
if (error instanceof ResponseError) {
console.log(await error.response.json());
}
else {
console.error(error);
}
throw new Error('Unable to find quote');
}
}
private async evaluateQuoteAndSwap(quote: QuoteResponse): Promise<void> {
let difference = (parseInt(quote.outAmount) - this.nextTrade.nextTradeThreshold) / this.nextTrade.nextTradeThreshold;
console.log(`📈 Current price: ${quote.outAmount} is ${difference > 0 ? 'higher' : 'lower'
} than the next trade threshold: ${this.nextTrade.nextTradeThreshold} by ${Math.abs(difference * 100).toFixed(2)}%.`);
if (parseInt(quote.outAmount) > this.nextTrade.nextTradeThreshold) {
try {
this.waitingForConfirmation = true;
await this.executeSwap(quote);
} catch (error) {
console.error('Error executing swap:', error);
}
}
}
private async executeSwap(route: QuoteResponse): Promise<void> {
try {
const {
computeBudgetInstructions,
setupInstructions,
swapInstruction,
cleanupInstruction,
addressLookupTableAddresses,
} = await this.jupiterApi.swapInstructionsPost({
swapRequest: {
quoteResponse: route,
userPublicKey: this.wallet.publicKey.toBase58(),
prioritizationFeeLamports: 'auto'
},
});
const instructions: TransactionInstruction[] = [
...computeBudgetInstructions.map(this.instructionDataToTransactionInstruction),
...setupInstructions.map(this.instructionDataToTransactionInstruction),
this.instructionDataToTransactionInstruction(swapInstruction),
this.instructionDataToTransactionInstruction(cleanupInstruction),
].filter((ix) => ix !== null) as TransactionInstruction[];
const addressLookupTableAccounts = await this.getAdressLookupTableAccounts(
addressLookupTableAddresses,
this.solanaConnection
);
const { blockhash, lastValidBlockHeight } = await this.solanaConnection.getLatestBlockhash();
const messageV0 = new TransactionMessage({
payerKey: this.wallet.publicKey,
recentBlockhash: blockhash,
instructions,
}).compileToV0Message(addressLookupTableAccounts);
const transaction = new VersionedTransaction(messageV0);
transaction.sign([this.wallet]);
const rawTransaction = transaction.serialize();
const txid = await this.solanaConnection.sendRawTransaction(rawTransaction, {
skipPreflight: true,
maxRetries: 2
});
const confirmation = await this.solanaConnection.confirmTransaction({ signature: txid, blockhash, lastValidBlockHeight }, 'confirmed');
if (confirmation.value.err) {
throw new Error('Transaction failed');
}
await this.postTransactionProcessing(route, txid);
} catch (error) {
if (error instanceof ResponseError) {
console.log(await error.response.json());
}
else {
console.error(error);
}
throw new Error('Unable to execute swap');
} finally {
this.waitingForConfirmation = false;
}
}
private async updateNextTrade(lastTrade: QuoteResponse): Promise<void> {
const priceChange = this.targetGainPercentage / 100;
this.nextTrade = {
inputMint: this.nextTrade.outputMint,
outputMint: this.nextTrade.inputMint,
amount: parseInt(lastTrade.outAmount),
nextTradeThreshold: parseInt(lastTrade.inAmount) * (1 + priceChange),
};
}
private async logSwap(args: LogSwapArgs): Promise<void> {
const { inputToken, inAmount, outputToken, outAmount, txId, timestamp } = args;
const logEntry = {
inputToken,
inAmount,
outputToken,
outAmount,
txId,
timestamp,
};
const filePath = path.join(__dirname, 'trades.json');
try {
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, JSON.stringify([logEntry], null, 2), 'utf-8');
} else {
const data = fs.readFileSync(filePath, { encoding: 'utf-8' });
const trades = JSON.parse(data);
trades.push(logEntry);
fs.writeFileSync(filePath, JSON.stringify(trades, null, 2), 'utf-8');
}
console.log(`✅ Logged swap: ${inAmount} ${inputToken} -> ${outAmount} ${outputToken},\n TX: ${txId}}`);
} catch (error) {
console.error('Error logging swap:', error);
}
}
private terminateSession(reason: string): void {
console.warn(`❌ Terminating bot...${reason}`);
console.log(`Current balances:\nSOL: ${this.solBalance / LAMPORTS_PER_SOL},\nUSDC: ${this.usdcBalance}`);
if (this.priceWatchIntervalId) {
clearInterval(this.priceWatchIntervalId);
this.priceWatchIntervalId = undefined; // Clear the reference to the interval
}
setTimeout(() => {
console.log('Bot has been terminated.');
process.exit(1);
}, 1000);
}
private instructionDataToTransactionInstruction (
instruction: Instruction | undefined
) {
if (instruction === null || instruction === undefined) return null;
return new TransactionInstruction({
programId: new PublicKey(instruction.programId),
keys: instruction.accounts.map((key: AccountMeta) => ({
pubkey: new PublicKey(key.pubkey),
isSigner: key.isSigner,
isWritable: key.isWritable,
})),
data: Buffer.from(instruction.data, "base64"),
});
};
private async getAdressLookupTableAccounts (
keys: string[], connection: Connection
): Promise<AddressLookupTableAccount[]> {
const addressLookupTableAccountInfos =
await connection.getMultipleAccountsInfo(
keys.map((key) => new PublicKey(key))
);
return addressLookupTableAccountInfos.reduce((acc, accountInfo, index) => {
const addressLookupTableAddress = keys[index];
if (accountInfo) {
const addressLookupTableAccount = new AddressLookupTableAccount({
key: new PublicKey(addressLookupTableAddress),
state: AddressLookupTableAccount.deserialize(accountInfo.data),
});
acc.push(addressLookupTableAccount);
}
return acc;
}, new Array<AddressLookupTableAccount>());
};
private async postTransactionProcessing(quote: QuoteResponse, txid: string): Promise<void> {
const { inputMint, inAmount, outputMint, outAmount } = quote;
await this.updateNextTrade(quote);
await this.refreshBalances();
await this.logSwap({ inputToken: inputMint, inAmount, outputToken: outputMint, outAmount, txId: txid, timestamp: new Date().toISOString() });
}
}