-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathmain.js
More file actions
455 lines (409 loc) · 13.6 KB
/
Copy pathmain.js
File metadata and controls
455 lines (409 loc) · 13.6 KB
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/**
* Скрипт для голосования на snapshot.org
* @Author JanSergeev (telegram)
* Donate: 0x9D278054C3e73294215b63ceF34c385Abe52768B
* node main.js <название_проекта> <айди_проползала> <номер_варианта>
* Название проекта - скопировать из строки, например https://snapshot.org/#/arbitrum-odyssey.eth
* arbitrum-odyssey.eth - это то, что нам нужно
* Айди проползала - скопируйте из браузера, например
* https://snapshot.org/#/arbitrum-odyssey.eth/proposal/0x44aba87414d2d7ce88218b676d9938338d7866a245f48a7829e805a99bcda6a2
* хеш 0x44aba87414d2d7ce88218b676d9938338d7866a245f48a7829e805a99bcda6a2 - айди
* Номер варианта - просто порядковый номер варианта
* Так как бывает подкидывают проползал специально для ботов, поэтому моя реализация
* для голосования по ID проползала не в полном авто-режиме
* Автоматически спарсить и скопировать в файл props.json список активных проползалов проекта:
* node main.js <название_проекта> getprops
*/
import ethers from "ethers";
import snapshot from "@snapshot-labs/snapshot.js";
import { HttpsProxyAgent } from "https-proxy-agent";
import chalk from "chalk";
import fetch from "node-fetch";
import { exit } from "process";
import * as fs from "fs";
import * as path from "path";
import * as accs from "./accs.js";
const version = "1.2.4";
const __dirname = path.resolve();
// rpc node url
const url = "https://rpc.ankr.com/eth";
// Базовые переменные
const rand_mode = 0; // 0 => стандартный, 1 => рандомная отправка варианта
const random_min = 1; // минимальный номер в голосовании
const random_max = 3; // максимальный номер в голосовании
const isSleep = true; // задержка перед отправкой, нужна ли? изменить на true, если нужна
const sleep_from = 3; // от 30 секунд
const sleep_to = 10; // до 60 секунд
const isPropList = false; // кастомный список проползалов
const type_voting = 0; // 0 => стандартный, 1 => approval
const isSubscribe = true; // подписываемся ли
let isParseProps = false;
// Кастомный клиент для обработки исключений
class ClientCustom extends snapshot.Client712 {
async send(envelop) {
const url = `${this.address}/api/msg`;
let init = {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(envelop),
};
if (proxies.length > 0) {
init = {
...init,
agent: proxies[randomIntInRange(0, proxies.length - 1)],
};
}
return new Promise((resolve, reject) => {
fetch(url, init)
.then((res) => {
if (res.ok) {
return resolve(res.json());
}
throw res;
})
.catch(async (e) => {
if (typeof e.text === "function") {
const text = await e.text();
try {
const data = JSON.parse(text);
reject(data);
} catch (e) {
reject({
error: "Error",
error_description: "Can't parse json in fetch",
});
}
} else {
reject({
error: "Error",
error_description: e.message,
error_stack: e.stack,
});
}
});
});
}
}
/**
* Абстрактная задержка (async)
* @param {Integer} millis
* @returns
*/
const sleep = async (millis) =>
new Promise((resolve) => setTimeout(resolve, millis));
/**
* Абстрактная задержка
* @param {Integer} millis
* @returns
*/
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
/**
* Запись в итоговый результат
* @param {String} address
* @param {String} result
* @returns
*/
const add_result = (address, result) =>
pretty_result.push({ Адрес: address, Результат: result });
/**
* Случайное min/max целое значение
* @param {Integer} min
* @param {Integer} max
* @returns Случайное число
*/
const randomIntInRange = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
/**
* Повторная отправка действия
* @param {String} address адрес
* @param {Arrow function} operation стрелочная функция
* @param {Integer} delay задержка в милли секундах
* @param {Integer} retries количество повторов
* @returns Promise
*/
const retryOperation = (address, operation, delay, retries) =>
new Promise((resolve, reject) => {
return operation.then(resolve).catch((reason) => {
if (retries > 0) {
if (
typeof reason === "string" &&
(reason.includes("timeout") || reason.includes("failed")) &&
retries === 3
) {
retries = 1000;
}
console.log(
`(${chalk.red(
"Ошибка"
)}) ${address} => повторная отправка действия, задержка: ${delay}с, осталось попыток: ${
retries - 1
}`
);
return wait(delay * 1000)
.then(
retryOperation.bind(null, address, operation, delay, retries - 1)
)
.then(resolve)
.catch(reject);
}
return reject(reason);
});
});
/**
* Голосование
* @param {Wallet} wallet
* @param {String} address
* @param {String} prop
* @returns Promise
*/
const voteSnap = (ethWallet, address, prop) =>
new Promise(async (resolve, reject) => {
await client
.vote(ethWallet, address, {
space: project,
proposal: prop,
type: type_voting == 0 ? "single-choice" : "approval",
choice:
rand_mode == 0
? type_voting == 0
? vote
: Array.isArray(vote)
? vote
: [vote]
: type_voting == 0
? randomIntInRange(random_min, random_max)
: [randomIntInRange(random_min, random_max)],
reason: "",
app: "snapshot",
})
.then((result) => {
if (result.hasOwnProperty("id")) {
console.log(
`(${chalk.green("Голосование")}) ${address} => голос засчитан`
);
add_result(address, "засчитано");
} else {
console.log(`(${chalk.red("Голосование")}) ${address} =>`);
console.dir(result);
add_result(address, "неизвестно");
}
resolve();
})
.catch((err) => {
if (typeof err.error_description !== "string") {
console.log(
`(${chalk.red("Голосование")}) ${address} => ошибка "${err.error}":`
);
console.dir(err.error_description);
if (err.hasOwnProperty("error_stack")) {
console.log(err.error_stack);
}
} else {
console.log(
`(${chalk.red("Голосование")}) ${address} => ошибка "${
err.error
}": ${err.error_description}`
);
if (err.hasOwnProperty("error_stack")) {
console.log(err.error_stack);
}
}
add_result(address, `${err.error}: ${err.error_description}`);
(typeof err.error_description === "string" &&
(err.error_description.includes("timeout") ||
err.error_description.includes("many") ||
err.error_description.includes("failed"))) ||
typeof err.error_description !== "string"
? reject(err.error_description)
: resolve();
});
});
/**
* Подписка
* @param {Wallet} wallet
* @param {String} address
* @returns Promise
*/
const subSnap = (ethWallet, address) =>
new Promise(async (resolve, reject) => {
await client
.follow(ethWallet, address, {
space: project,
})
.then((result) => {
if (result.hasOwnProperty("id")) {
console.log(
`(${chalk.green("Подписка")}) ${address} => вы подписались`
);
} else {
console.log(`(${chalk.green("Подписка")}) ${address} =>`);
console.dir(result);
}
resolve();
})
.catch((err) => {
if (typeof err.error_description !== "string") {
console.log(
`(${chalk.red("Подписка")}) ${address} => ошибка "${err.error}":`
);
console.dir(err.error_description);
if (err.hasOwnProperty("error_stack")) {
console.log(err.error_stack);
}
} else {
console.log(
`(${chalk.red("Подписка")}) ${address} => ошибка "${err.error}": ${
err.error_description
}`
);
if (err.hasOwnProperty("error_stack")) {
console.log(err.error_stack);
}
}
(typeof err.error_description === "string" &&
(err.error_description.includes("timeout") ||
err.error_description.includes("many") ||
err.error_description.includes("failed"))) ||
typeof err.error_description !== "string"
? reject(err.error_description)
: resolve();
});
});
// Авторство
console.log(`${chalk.bold.green(`-=- snapshotvoter v${version} -=-`)}`);
console.log(
`License: ISC\nAuthor: @JanSergeev\nDonate: 0x9D278054C3e73294215b63ceF34c385Abe52768B`
);
// Парсинг параметров
let project, prop_id, vote;
process.argv.forEach(function (val, index, array) {
switch (index) {
case 2:
project = val;
case 3:
if (String(val).toLowerCase() == "getprops") {
isParseProps = true;
} else {
prop_id = val;
}
case 4:
vote = val.includes(",") ? val.split(",").map(Number) : +val;
}
});
// Unhandled errors/promises, fix app crash
process.on("uncaughtException", (error, origin) => {
console.log("----- Uncaught exception -----");
console.dir(error);
console.log("----- Exception origin -----");
console.dir(origin);
});
process.on("unhandledRejection", (reason, promise) => {
console.log("----- Unhandled Rejection at -----");
console.dir(promise);
console.log("----- Reason -----");
console.dir(reason);
});
// Парсинг
if (isParseProps) {
let q = `
query {
proposals (
where: {
space_in: ["${project}"],
state: "active"
}
) {
id
}
}`;
await fetch("https://hub.snapshot.org/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({ query: q }),
})
.then((r) => r.json())
.then((data) => {
if (
data.hasOwnProperty("data") &&
data.data.hasOwnProperty("proposals")
) {
let arr = [];
data.data.proposals.forEach((i) => arr.push(i.id));
fs.writeFileSync(
path.join(__dirname, "/props.json"),
JSON.stringify(arr, null, 4),
{ encoding: "utf8", flag: "w" }
);
console.log("Данные сохранены, проверьте props.json.");
} else {
console.log("Ошибка при парсинге данных.");
}
});
exit();
}
// Запуск rpc
const web3 = new ethers.providers.JsonRpcProvider(url);
const hub = "https://hub.snapshot.org"; // or https://testnet.snapshot.org for testnet
const client = new ClientCustom(hub);
// Чтение аккаунтов
let adata = await accs.importAccs();
let props_list = isPropList ? accs.importProps() : [prop_id];
let proxies = (await accs.importProxies()).map((v) => new HttpsProxyAgent(v));
// Перебор аккаунтов
let i = 0,
promises = [],
pretty_result = [];
for (let acc of adata) {
const ethWallet = new ethers.Wallet(acc, web3);
const address = await ethWallet.getAddress();
let prom = promises.push(
new Promise(async (resolve, reject) => {
// Голосование
let prom_list = [];
props_list.forEach((prop) =>
prom_list.push(
retryOperation(
address,
voteSnap(ethWallet, address, prop),
isSleep ? randomIntInRange(sleep_from, sleep_to) : 1,
3
)
)
);
// Подписка
if (isSubscribe) {
prom_list.push(
retryOperation(
address,
subSnap(ethWallet, address),
isSleep ? randomIntInRange(sleep_from, sleep_to) : 1,
3
)
);
}
await Promise.allSettled(prom_list).then(() => resolve());
})
);
// Задержка
if (isSleep) {
let sle = randomIntInRange(sleep_from, sleep_to);
promises
.at(prom - 1)
.then(() =>
i < adata.length
? console.log(`Задержка ${chalk.yellow(sle)}с..`)
: null
);
i < adata.length ? await sleep(sle * 1000) : null;
}
++i;
}
// Результат
await Promise.allSettled(promises).then(() => console.table(pretty_result));