-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
639 lines (607 loc) · 18.2 KB
/
index.js
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
const ethers = require('ethers');
const axios = require('axios');
const { Client, Intents, MessageEmbed } = require('discord.js');
const ABI = require('./abi');
const Redis = require('ioredis');
let redis_url = process.env.REDIS_TLS_URL;
let redisOptions = {
tls: { rejectUnauthorized: false },
};
if (process.env.ENVIRONMENT !== 'production') {
redisOptions = {};
redis_url = 'redis://127.0.0.1';
require('dotenv').config();
}
const {
DISCORD_TOKEN,
CHANNEL_ID,
MINT_CHANNEL_ID,
OPENSEA_KEY,
COLLECTION_SLUG,
AUTHOR_NAME,
AUTHOR_THUMBNAIL,
AUTHOR_URL,
LISTING_CHANNEL_ID,
} = process.env;
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
const fetchOptions = {
headers: { 'x-api-key': OPENSEA_KEY },
};
const ensprovider = new ethers.providers.InfuraProvider(
process.env.ENS_NETWORK,
process.env.INFURA_API_KEY
);
const provider = new ethers.providers.InfuraProvider(
process.env.CONTRACT_NETWORK,
process.env.INFURA_API_KEY
);
const contract = new ethers.Contract(
process.env.CONTRACT_ADDRESS,
ABI,
provider
);
provider.pollingInterval = 30000;
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
let redisClient;
let listingChannel;
// When the client is ready, run this code (only once)
client.once('ready', async () => {
console.log('Ready!');
console.log(`Watching ${COLLECTION_SLUG}`);
// console.log(`Watching ${await contract.name()}`);
const channel = await client.channels.fetch(CHANNEL_ID);
const mintChannel = MINT_CHANNEL_ID
? await client.channels.fetch(MINT_CHANNEL_ID)
: channel;
listenForSales(channel, mintChannel);
if (LISTING_CHANNEL_ID) {
listingChannel = await client.channels.fetch(LISTING_CHANNEL_ID);
redisClient = new Redis(redis_url, redisOptions);
pollListings(true);
}
});
client.on('error', function (error) {
console.error(`client's WebSocket encountered a connection error: ${error}`);
});
function osLink(chain, nft) {
return `https://opensea.io/assets/${chain}/${nft.contract}/${nft.identifier}`;
}
async function getOpenSeaName(address) {
const response = await axios
.get(`https://api.opensea.io/api/v2/accounts/${address}`, fetchOptions)
.catch(() => false);
let username;
if (
!response ||
!response.data ||
response.data.username === 'null' ||
response.data.username === null ||
response.data.username.length === 0
) {
username = await getENSName(address);
} else {
username = response.data.username;
username = `[${username}](https://opensea.io/${username})`;
}
return username;
}
async function getENSName(address) {
let name = await ensprovider.lookupAddress(address).catch(() => false);
if (!name) {
name = address.substr(0, 10);
}
return `[${name}](https://opensea.io/${address})`;
}
async function getBalance(address, id) {
if (!address) {
return '?';
}
let balance;
console.log(`checking balance of ${address}`);
try {
balance = await contract['balanceOf(address)'](address);
} catch (e) {
console.log(`Err! ${e}`);
try {
console.log(`Error! checking balance of ${address}, ${id}`);
balance = await contract['balanceOf(address,uint256)'](
address,
parseInt(id, 10)
);
} catch (e) {
console.log(`Err! ${e}`);
}
}
return balance || 0;
}
async function mint(toAddress, value, channel, count, gasPrice, gasUsed) {
count = count || 0;
const tokenId = value;
const tokenURI = await contract.tokenURI(value);
const totalSupply = (await contract.totalSupply()).toNumber();
// todo: make this work for JSON tokenURI's
console.log(`MintBot fetching ${tokenURI}`);
const response = await axios
.get(tokenURI.replace('ipfs://', 'https://0x420.mypinata.cloud/ipfs/'))
.catch((error) => {
console.log(`error fetching tokenURI: ${tokenURI}`);
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
return false;
});
if (!response) {
console.log('Error fetching token metadata');
if (count < 30) {
console.log(`Checking ${value} again in 5 seconds. ${count} / 30`);
setTimeout(() => {
mint(toAddress, value, channel, count + 1, gasPrice, gasUsed);
}, 5000);
} else {
console.log(`Giving up on ${value}`);
}
return;
}
const token = response.data;
const image = token.image.replace(
'ipfs://',
'https://0x420.mypinata.cloud/ipfs/'
);
const fields = [
{
name: 'Minter',
value: `${await getOpenSeaName(toAddress)}`,
inline: true,
},
{
name: 'Minter Holds',
value: `${(await getBalance(toAddress, value)).toLocaleString()}`,
inline: true,
},
{ name: 'Total Supply', value: totalSupply.toLocaleString(), inline: true },
];
if (token.attributes) {
token.attributes.forEach((attr) => {
fields.push({
name: attr.trait_type,
value: attr.value,
inline: true,
});
});
}
// if (gasPrice && gasUsed) {
// fields.push({
// name: 'Gas Price',
// value: `${gasPrice} Gwei`,
// inline: true,
// });
// fields.push({
// name: 'Gas Spent',
// value: `${String(gasUsed.substring(0, 7))} Ether`,
// inline: true,
// });
// }
const embed = new MessageEmbed()
.setColor(token.background_color || '#0099ff')
.setURL(
`https://opensea.io/assets/ethereum/${process.env.CONTRACT_ADDRESS}/${tokenId}`
) // todo this needs to handle /matic/
.setTitle(token.name + ' minted!')
.setAuthor(AUTHOR_NAME, AUTHOR_THUMBNAIL, AUTHOR_URL)
.setThumbnail(AUTHOR_THUMBNAIL)
.addFields(fields)
.setImage(image)
.setTimestamp();
channel.send({ embeds: [embed] });
}
const buildMessage = async (sale, gasPrice, gasUsed) => {
const fields = [
{
name: 'Buyer',
value: `${await getOpenSeaName(sale.buyer)}`,
inline: true,
},
{
name: 'Buyer Holds',
value: `${(
await getBalance(sale.buyer, sale.nft.identifier)
).toLocaleString()}`,
inline: true,
},
{
name: 'Price',
value: `${ethers.utils.formatEther(BigInt(sale.payment.quantity || 0))}${
sale.payment.symbol
}`,
inline: true,
},
// { name: '\u200B', value: '\u200B', inline: true },
{
name: 'Seller',
value: `${await getOpenSeaName(sale.seller)}`,
inline: true,
},
{
name: 'Seller Holds',
value: `${(
await getBalance(sale.seller, sale.nft.identifier)
).toLocaleString()}`,
inline: true,
},
];
// if (gasPrice && gasUsed) {
// fields.push({
// name: 'Gas Price',
// value: `${gasPrice} Gwei`,
// inline: true,
// });
// fields.push({
// name: 'Gas Spent',
// value: `${gasUsed} Ether`,
// inline: true,
// });
// }
return new MessageEmbed()
.setColor('#0099ff')
.setTitle(sale.nft.name + ' sold!')
.setURL(osLink(sale.chain, sale.nft))
.setAuthor(AUTHOR_NAME, AUTHOR_THUMBNAIL, AUTHOR_URL)
.setThumbnail(sale.nft.imge_url)
.addFields(fields)
.setImage(sale.nft.image_url)
.setTimestamp(new Date(sale.closing_date * 1000))
.setFooter(
'Sold on OpenSea (v2)',
'https://files.readme.io/566c72b-opensea-logomark-full-colored.png'
);
};
async function searchForToken(
token,
from,
to,
channel,
count,
gasPrice,
gasUsed
) {
count = count || 0;
console.log(`Searching for token: ${token} attempt: ${count}`);
let found = false;
const params = new URLSearchParams({
event_type: 'sale',
});
console.log('With params:', params);
const openSeaResponseObject = await axios
.get(
`https://api.opensea.io/api/v2/events/collection/${COLLECTION_SLUG}?` +
params,
fetchOptions
)
.catch((e) => {
console.log('ERRRRR');
console.log(e);
});
if (openSeaResponseObject && openSeaResponseObject.data) {
const openSeaResponse = openSeaResponseObject.data;
if (!openSeaResponse.asset_events) {
console.log('no asset_events');
}
if (openSeaResponse.asset_events) {
openSeaResponse.asset_events.forEach((event) => {
if (event.nft) {
console.log(
`Comparing ${token} to ${event.nft.identifier}, to: ${to}, winner: ${event.buyer}`
);
if (
event.nft.identifier === token &&
to.toLowerCase() === event.buyer.toLowerCase()
) {
found = event;
}
} else {
console.log('Strange event', event);
}
});
if (found && found.buyer) {
const embed = await buildMessage(found, gasPrice, gasUsed);
channel.send({ embeds: [embed] });
}
}
}
if (!found && count < 30) {
setTimeout(() => {
searchForToken(token, from, to, channel, count + 1, gasPrice, gasUsed);
}, count * count * 1000);
}
}
// function keepAlive() {
// contract.name().then((r) => {
// // console.log(`Keep Alive for ${r}`);
// });
// }
function listenForSales(channel, mintChannel) {
contract.on('Transfer', async (fromAddress, toAddress, value, event) => {
const receipt = await event.getTransactionReceipt();
const gasPrice = ethers.utils.formatUnits(
receipt.effectiveGasPrice,
'gwei'
);
const gasUsed = ethers.utils.formatUnits(
receipt.gasUsed.mul(receipt.effectiveGasPrice),
'ether'
);
console.log(
`Token ${value} Transferred from ${fromAddress} to ${toAddress}`
);
if (fromAddress === ZERO_ADDRESS) {
mint(toAddress, value, mintChannel, 0, gasPrice, gasUsed);
} else if (toAddress === ZERO_ADDRESS) {
// do nothing… burn
} else {
setTimeout(() => {
searchForToken(
String(value),
fromAddress.toString(),
toAddress.toString(),
channel,
0,
gasPrice,
gasUsed
);
}, 5000);
}
});
contract.on(
'TransferSingle',
async (operator, fromAddress, toAddress, value) => {
console.log(`Token ${value} Transferrred`);
setTimeout(() => {
searchForToken(
String(value),
fromAddress.toString(),
toAddress.toString(),
channel
);
}, 5000);
}
);
contract.on(
'TransferBatch',
async (operator, fromAddress, toAddress, values) => {
setTimeout(() => {
values.forEach((value) => {
console.log(`Token ${value} Transferrred`);
searchForToken(String(value), fromAddress, toAddress, channel);
});
}, 5000);
}
);
}
async function pollListings(skipFirstTime) {
const params = new URLSearchParams({
event_type: 'order',
});
const openSeaResponseObject = await axios
.get(
`https://api.opensea.io/api/v2/events/collection/${COLLECTION_SLUG}?` +
params,
fetchOptions
)
.catch((e) => {
console.log('ERROR Fetching Listing Events');
console.log(e);
});
if (openSeaResponseObject && openSeaResponseObject.data) {
const openSeaResponse = openSeaResponseObject.data;
if (!openSeaResponse.asset_events) {
console.log('no asset_events');
}
if (openSeaResponse.asset_events) {
for (let i = 0; i < openSeaResponse.asset_events.length; i += 1) {
const event = openSeaResponse.asset_events[i];
if (event.order_type !== 'listing') {
continue;
}
const REF = `listing/${event.order_hash}`;
const completed = await redisClient.get(REF);
if (completed) {
continue;
}
if (!completed) {
await redisClient.set(REF, true);
if (!skipFirstTime) {
const name = (event && event.asset && event.asset.name) || '?';
let image = event.asset.image_url;
if (
event.maker.toLowerCase() ===
'0x750198134f72db6a068423a0e1fb20e5a9c8b26c'.toLowerCase()
) {
continue;
}
if (
event.maker.toLowerCase() ===
'0x28fcc58649bb1b85e75eed9f710e11e8e861486c'.toLowerCase()
) {
continue;
}
if (
event.maker.toLowerCase() ===
'0x556272591d28705AFA610fb6c82D299379fc162B'.toLowerCase()
) {
continue;
}
if (
event.maker.toLowerCase() ===
'0x7b1414a97471bcc28259827bc7db427d3a65cdff'.toLowerCase()
) {
continue;
}
if (
event.maker.toLowerCase() ===
'0x9F515f3B8EFb88FBFB24D4bBe624abFF7ba7e7ce'.toLowerCase()
) {
continue;
// image = 'https://0x420.mypinata.cloud/ipfs/QmVjXXaFxW87R6Fe5Pwdwrr5CkDTtkBvaj6FM5qmKcMyGG';
}
if (
event.maker.toLowerCase() ===
'0xF30feE0b988AA124F03cc25B8B0e88B2C8667c00'.toLowerCase()
) {
continue;
}
if (
event.maker.toLowerCase() ===
'0x90aa587b339e81fa93af9920e78b72d398c8c655'.toLowerCase()
) {
continue;
}
if (
event.maker.toLowerCase() ===
'0xbD40D4fF0b6B1fD591da0138d428B15b2ab343fD'.toLowerCase()
) {
continue;
}
if (
event.maker.toLowerCase() ===
'0x2ff895e051f7A1c29c2D3bdAB35C4960E3E1ec72'.toLowerCase()
) {
// gemma addition 4/12/23
continue;
}
if (
event.maker.toLowerCase() ===
'0xF179b80C4699C7e2B97daa8aB20a91c9e952a98C'.toLowerCase()
) {
// gemma addition 4/27/23
continue;
}
if (
event.maker.toLowerCase() ===
'0xeec9a835df1298587348b5c01048aac2277f340a'.toLowerCase()
) {
// KRILLER addition 6/15/23
continue;
}
if (
event.maker.toLowerCase() ===
'0x622a5b6c4e544a4c085745c4b147d995bb235bbe'.toLowerCase()
) {
// KRILLER addition 6/15/23
continue;
}
if (
event.maker.toLowerCase() ===
'0xF5e2C95ffa3845c6B8398404FFAdABD2D1b6Eff5'.toLowerCase()
) {
// CYBER BANDIT addition 8/30/23
continue;
}
if (
event.maker.toLowerCase() ===
'0x881ba48b3e959c30a714ebc307e20048aee2aa8f'.toLowerCase()
) {
// CYBER BANDIT addition 9/5/23
continue;
}
if (
event.maker.toLowerCase() ===
'0xbea8017ccf98017c698a10065d01fdc480930366'.toLowerCase()
) {
// GEMMA addition 9/11/23
continue;
}
if (
event.maker.toLowerCase() ===
'0x8328af4c65ace04382f83ab0063884f0ee694d0b'.toLowerCase()
) {
// GEMMA addition 9/25/23
continue;
}
if (
event.maker.toLowerCase() ===
'0x476151646c8674cdd9f956d78f7233939864b799'.toLowerCase()
) {
// Vizzie addition 1/15/24
continue;
}
if (
event.maker.toLowerCase() ===
'0x9667857f0461354a7e2caeb6c86a560eeca1d2da'.toLowerCase()
) {
// GEMMA addition 3/9/24
continue;
}
if (
event.maker.toLowerCase() ===
'0xb1a5a0c38d95dee2e5f6a8be5e1247394434ce7a'.toLowerCase()
) {
// GEMMA addition 3/9/24
continue;
}
let symbol = event.payment.symbol;
if (symbol === 'ETH') {
symbol = ethers.constants.EtherSymbol;
}
// let royalty = sale.dev_seller_fee_basis_points / 100;
// const royaltyField = {
// name: 'Royalty to the Artist',
// value: `${royalty}%`,
// inline: true,
// };
const embed = new MessageEmbed()
.setColor('#0099ff')
.setTitle(name + ' Listed!')
.setURL(osLink(event.chain, event.asset))
.setAuthor(AUTHOR_NAME, AUTHOR_THUMBNAIL, AUTHOR_URL)
.setThumbnail(event.asset.image_url)
.addFields(
{
name: 'Price',
value: `${ethers.utils.formatEther(BigInt(
event.payment.quantity || 0
))}${symbol}`,
inline: true,
},
{
name: 'Seller',
value: `${await getOpenSeaName(event.maker)}`,
inline: true,
},
{
name: 'Seller Holds',
value: `${(
await getBalance(event.maker, event.asset.identifier)
).toLocaleString()}`,
inline: true,
}
)
.setImage(image)
.setTimestamp(new Date(event.start_date * 1000))
.setFooter(
'Listed on OpenSea (v2)',
'https://files.readme.io/566c72b-opensea-logomark-full-colored.png'
);
listingChannel.send({ embeds: [embed] });
}
}
}
}
}
setTimeout(pollListings, 10000);
// setTimeout(keepAlive, 10000);
}
console.log('logging in discord client');
client.login(DISCORD_TOKEN);