-
Notifications
You must be signed in to change notification settings - Fork 7
/
ping-thing-client-jupiter.mjs
372 lines (311 loc) · 11.1 KB
/
ping-thing-client-jupiter.mjs
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
// Sample use:
// node ping-thing-client-jupiter.mjs >> ping-thing-jupiter.log 2>&1 &
import dotenv from "dotenv";
import web3, { VersionedTransaction } from "@solana/web3.js";
import bs58 from "bs58";
import axios from "axios";
import { watchBlockhash } from "./utils/blockhash.mjs";
import { watchSlotSent } from "./utils/slot.mjs";
import { sleep } from "./utils/misc.mjs";
import { setGlobalDispatcher, Agent } from "undici";
setGlobalDispatcher(
new Agent({
connections: 50,
})
);
// Catch interrupts & exit
process.on("SIGINT", function () {
console.log(`${new Date().toISOString()} Caught interrupt signal`, "\n");
process.exit();
});
// Look for a command line flag --skip-validators-app to skip sending to validators.app
// I use this for debugging on localhost
const skipValidatorsApp = process.argv.includes("--skip-validators-app");
// Read constants from .env
dotenv.config();
const RPC_ENDPOINT = process.env.RPC_ENDPOINT;
const WS_ENDPOINT = process.env.WS_ENDPOINT;
const USER_KEYPAIR = web3.Keypair.fromSecretKey(
bs58.decode(process.env.WALLET_PRIVATE_KEYPAIR)
);
const JUPITER_ENDPOINT = `${RPC_ENDPOINT}/jupiter`;
const SLEEP_MS_RPC = process.env.SLEEP_MS_RPC || 2000;
const SLEEP_MS_LOOP = process.env.SLEEP_MS_LOOP || 0;
const VA_API_KEY = process.env.VA_API_KEY;
// process.env.VERBOSE_LOG returns a string. e.g. 'true'
const VERBOSE_LOG = process.env.VERBOSE_LOG === "true" ? true : false;
const COMMITMENT_LEVEL = process.env.COMMITMENT || "confirmed";
const PRIORITY_FEE_PERCENTILE = process.env.PRIORITY_FEE_PERCENTILE || 5000;
const SWAP_TOKEN_FROM = "So11111111111111111111111111111111111111112"; // SOL
const SWAP_TOKEN_TO = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; // USDC
const SWAP_AMOUNT = 1000;
const TX_RETRY_INTERVAL = 2000;
const PRIORITY_FEE_MICRO_LAMPORTS =
process.env.PRIORITY_FEE_MICRO_LAMPORTS || 1000;
if (VERBOSE_LOG) console.log(`${new Date().toISOString()} Starting script`);
console.log(`RPC_ENDPOINT: ${RPC_ENDPOINT}`);
console.log(`WS_ENDPOINT: ${WS_ENDPOINT}`);
console.log("");
// Set up web3 client
const connection = new web3.Connection(RPC_ENDPOINT, {
commitment: COMMITMENT_LEVEL,
});
const connectionWs = new web3.Connection(RPC_ENDPOINT, {
wsEndpoint: WS_ENDPOINT,
});
const gBlockhash = { value: null, updated_at: 0 };
// Record new slot on `firstShredReceived`
const gSlotSent = { value: null, updated_at: 0 };
async function pingThing() {
// Pre-define loop constants & variables
const FAKE_SIGNATURE =
"9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999";
// Run inside a loop that will exit after 3 consecutive failures
const MAX_TRIES = 3;
let tryCount = 0;
// Loop until interrupted
for (let i = 0; ; ++i) {
// Sleep before the next loop
if (i > 0) {
await sleep(SLEEP_MS_LOOP);
}
let blockhash;
let slotSent;
let slotLanded;
let signature;
let txStart;
let tempResponse;
let quoteResponse;
let jupiterSwapTransaction;
// Wait fresh data
while (true) {
if (
Date.now() - gBlockhash.updated_at < 10000 &&
Date.now() - gSlotSent.updated_at < 50
) {
blockhash = gBlockhash.value;
slotSent = gSlotSent.value;
break;
}
await sleep(1);
}
try {
try {
if (VERBOSE_LOG)
console.log(
`${new Date().toISOString()} fetching jupiter swap quote`
);
// Get quote for swap
tempResponse = await axios.get(
`${JUPITER_ENDPOINT}/quote?inputMint=${SWAP_TOKEN_FROM}&outputMint=${SWAP_TOKEN_TO}&amount=${SWAP_AMOUNT}&slippageBps=50`
);
// throw error if response is not ok
if (!(tempResponse.status >= 200) && tempResponse.status < 300) {
throw new Error(
`Failed to fetch jupiter swap quote: ${tempResponse.status}`
);
}
quoteResponse = tempResponse.data;
if (VERBOSE_LOG)
console.log(`${new Date().toISOString()} fetched jupiter swap quote`);
if (VERBOSE_LOG)
console.log(
`${new Date().toISOString()} fetching jupiter swap transaction`
);
const priorityFeeApiResult = await axios.post(`${RPC_ENDPOINT}`, {
method: "getRecentPrioritizationFees",
jsonrpc: "2.0",
params: [
["JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4"],
{
percentile: parseInt(PRIORITY_FEE_PERCENTILE),
},
],
id: "1",
});
const fees = priorityFeeApiResult.data.result;
let feesSum = 0;
for (let i = 0; i < fees.length; i++) {
feesSum += fees[i].prioritizationFee;
}
const average = Math.floor(feesSum / fees.length);
// Get swap transaction
tempResponse = await axios.post(`${JUPITER_ENDPOINT}/swap`, {
quoteResponse: quoteResponse,
userPublicKey: USER_KEYPAIR.publicKey.toBase58(),
wrapAndUnwrapSol: true,
dynamicComputeUnitLimit: true,
prioritizationFeeLamports: average,
});
// throw error if response is not ok
if (!(tempResponse.status >= 200) && tempResponse.status < 300) {
throw new Error(
`Failed to fetch jupiter swap transaction: ${tempResponse.status}`
);
}
jupiterSwapTransaction = tempResponse.data;
if (VERBOSE_LOG)
console.log(
`${new Date().toISOString()} fetched jupiter swap transaction`
);
const swapTransactionBuf = Buffer.from(
jupiterSwapTransaction.swapTransaction,
"base64"
);
const tx = VersionedTransaction.deserialize(swapTransactionBuf);
tx.message.recentBlockhash = blockhash.blockhash;
// Sign
tx.sign([USER_KEYPAIR]);
const signatureRaw = tx.signatures[0];
let txSignature = bs58.encode(signatureRaw);
let txSendAttempts = 1;
if (VERBOSE_LOG)
console.log(`${new Date().toISOString()} sending swap transaction`);
txStart = Date.now();
const confirmTransactionPromise = connectionWs.confirmTransaction(
{
signature: txSignature,
blockhash: blockhash.blockhash,
lastValidBlockHeight: blockhash.lastValidBlockHeight,
},
COMMITMENT_LEVEL
);
slotSent = gSlotSent.value;
// Send and wait confirmation
signature = await connection.sendRawTransaction(tx.serialize(), {
skipPreflight: true,
maxRetries: 0,
});
let confirmedTx = null;
while (!confirmedTx) {
const confirmTransactionPromise = connectionWs.confirmTransaction(
{
signature: txSignature,
blockhash: blockhash.blockhash,
lastValidBlockHeight: blockhash.lastValidBlockHeight,
},
COMMITMENT_LEVEL
);
confirmedTx = await Promise.race([
confirmTransactionPromise,
new Promise((resolve) =>
setTimeout(() => {
resolve(null);
}, TX_RETRY_INTERVAL)
),
]);
if (confirmedTx) {
break;
}
console.log(
`${new Date().toISOString()} Tx not confirmed after ${
TX_RETRY_INTERVAL * txSendAttempts++
}ms, resending`
);
await connection.sendRawTransaction(tx.serialize(), {
skipPreflight: true,
maxRetries: 0,
});
}
if (VERBOSE_LOG)
console.log(
`${new Date().toISOString()} confirming swap transaction ${signature}`
);
} catch (e) {
// Log and loop if we get a bad blockhash.
if (e.message.includes("Blockhash not found")) {
console.log(`${new Date().toISOString()} ERROR: Blockhash not found`);
continue;
}
// If the transaction expired on the chain. Make a log entry and send
// to VA. Otherwise log and loop.
if (e.name === "TransactionExpiredBlockheightExceededError") {
console.log(
`${new Date().toISOString()} ERROR: Blockhash expired/block height exceeded. TX failure sent to VA.`
);
} else {
console.log(`${new Date().toISOString()} ERROR: ${e.name}`);
console.log(e.message);
console.log(e);
console.log(JSON.stringify(e));
continue;
}
// Need to submit a fake signature to pass the import filters
signature = FAKE_SIGNATURE;
}
const txEnd = Date.now();
// Sleep a little here to ensure the signature is on an RPC node.
await sleep(SLEEP_MS_RPC);
if (signature !== FAKE_SIGNATURE) {
// Capture the slotLanded
let txLanded = await connection.getTransaction(signature, {
commitment: COMMITMENT_LEVEL,
maxSupportedTransactionVersion: 255,
});
if (txLanded === null) {
console.log(
signature,
`${new Date().toISOString()} ERROR: tx is not found on RPC within ${SLEEP_MS_RPC}ms. Not sending to VA.`
);
continue;
}
slotLanded = txLanded.slot;
}
// Don't send if the slot latency is negative
if (slotLanded < slotSent) {
console.log(
signature,
`${new Date().toISOString()} ERROR: Slot ${slotLanded} < ${slotSent}. Not sending to VA.`
);
continue;
}
// prepare the payload to send to validators.app
const vAPayload = JSON.stringify({
time: txEnd - txStart,
signature,
transaction_type: "jupiter-swap",
success: signature !== FAKE_SIGNATURE,
application: "web3",
commitment_level: COMMITMENT_LEVEL,
slot_sent: slotSent,
slot_landed: slotLanded,
});
if (VERBOSE_LOG) {
console.log(`${new Date().toISOString()} ${vAPayload}`);
}
if (!skipValidatorsApp) {
// Send the payload to validators.app
const vaResponse = await axios.post(
"https://www.validators.app/api/v1/ping-thing/mainnet",
vAPayload,
{
headers: {
"Content-Type": "application/json",
Token: VA_API_KEY,
},
}
);
// throw error if response is not ok
if (!(vaResponse.status >= 200 && vaResponse.status <= 299)) {
throw new Error(`Failed to update validators: ${vaResponse.status}`);
}
if (VERBOSE_LOG) {
console.log(
`${new Date().toISOString()} VA Response ${vaResponse.status} ${JSON.stringify(vaResponse.data)}`
);
}
}
// Reset the try counter
tryCount = 0;
} catch (e) {
console.log(`${new Date().toISOString()} ERROR: ${e.name}`);
console.log(`${new Date().toISOString()} ERROR: ${e.message}`);
if (++tryCount === MAX_TRIES) throw e;
}
}
}
await Promise.all([
watchBlockhash(gBlockhash, connection),
watchSlotSent(gSlotSent, connection),
pingThing(),
]);