-
Notifications
You must be signed in to change notification settings - Fork 7
/
ping-thing-client-token.mjs
324 lines (280 loc) · 9.51 KB
/
ping-thing-client-token.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
// Sample use:
// node ping-thing-client-token.mjs >> ping-thing-token.log 2>&1 &
//
// This script will send a small token transfer between two ATAs of the same type. You need to
// create the ATAs in advance and put the ATA addresses in the .env file.
import dotenv from "dotenv";
import {
Connection,
Keypair,
Transaction,
ComputeBudgetProgram,
PublicKey,
} from "@solana/web3.js";
import { createTransferInstruction } from "@solana/spl-token";
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 = Keypair.fromSecretKey(
bs58.decode(process.env.WALLET_PRIVATE_KEYPAIR)
);
const VERBOSE_LOG = process.env.VERBOSE_LOG === "true" ? true : false;
if (VERBOSE_LOG) console.log(`${new Date().toISOString()} Starting script`);
console.log(`RPC_ENDPOINT: ${RPC_ENDPOINT}`);
console.log(`WS_ENDPOINT: ${WS_ENDPOINT}`);
console.log('');
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 COMMITMENT_LEVEL = process.env.COMMITMENT || "confirmed";
const USE_PRIORITY_FEE = process.env.USE_PRIORITY_FEE == "true" ? true : false;
const ATA_SEND = new PublicKey(process.env.ATA_SEND);
const ATA_REC = new PublicKey(process.env.ATA_REC);
const ATA_AMT = BigInt(process.env.ATA_AMT);
const TX_RETRY_INTERVAL = 2000;
// Set up web3 client
const connection = new Connection(RPC_ENDPOINT, {
commitment: COMMITMENT_LEVEL,
});
const connectionWs = new 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 txSendAttempts = 1;
// 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 {
// Setup our transaction
const tx = new Transaction();
if (USE_PRIORITY_FEE) {
tx.add(
ComputeBudgetProgram.setComputeUnitLimit({
units: process.env.CU_BUDGET || 5000,
}),
ComputeBudgetProgram.setComputeUnitPrice({
microLamports: process.env.PRIORITY_FEE_MICRO_LAMPORTS || 3,
})
);
}
tx.add(
createTransferInstruction(
ATA_SEND,
ATA_REC,
USER_KEYPAIR.publicKey,
ATA_AMT
)
);
// Sign
tx.lastValidBlockHeight = blockhash.lastValidBlockHeight;
tx.recentBlockhash = blockhash.blockhash;
tx.sign(USER_KEYPAIR);
const signatureRaw = tx.signatures[0].signature;
signature = bs58.encode(signatureRaw);
if (VERBOSE_LOG)
console.log(`${new Date().toISOString()} sending: ${signature}`);
// Send and wait confirmation (subscribe on confirmation before sending)
const resultPromise = connectionWs.confirmTransaction(
{
signature,
blockhash: tx.recentBlockhash,
lastValidBlockHeight: tx.lastValidBlockHeight,
},
COMMITMENT_LEVEL
);
txStart = Date.now();
const sendTxResult = await connection.sendRawTransaction(
tx.serialize(),
{
skipPreflight: true,
maxRetries: 0,
}
);
if (sendTxResult !== signature) {
throw new Error(
`Receive invalid signature from sendRawTransaction: ${sendTxResult}, expected ${signature}`
);
}
let confirmedTransaction = null;
while (!confirmedTransaction) {
const resultPromise = connectionWs.confirmTransaction(
{
signature,
blockhash: tx.recentBlockhash,
lastValidBlockHeight: tx.lastValidBlockHeight,
},
COMMITMENT_LEVEL
);
confirmedTransaction = await Promise.race([
resultPromise,
new Promise((resolve) =>
setTimeout(() => {
resolve(null);
}, TX_RETRY_INTERVAL)
),
]);
if (confirmedTransaction) {
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 (confirmedTransaction.value.err) {
throw new Error(
`Transaction ${signature} failed (${JSON.stringify(confirmedTransaction.value)})`
);
}
} 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: "transfer",
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(),
]);