-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
259 lines (205 loc) · 7.29 KB
/
index.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
import 'dotenv/config';
import { PrismaClient } from '@prisma/client';
import { Client, Intents } from 'discord.js';
import { AbiItem } from 'web3-utils';
import { Contract } from 'web3-eth-contract';
import { WebsocketProvider } from 'web3-providers-ws';
import express, { Application } from 'express';
import cors from 'cors';
import EventEmitter from 'events';
import fs from 'fs';
import Web3 from 'web3';
import config from './src/config';
import { Event } from './types/contract';
import { TransactionEvent } from './types/events';
import postTransactionEvent from './src/utils/postTransactionEvent';
import transactionsRoutes from './src/routes/transactions';
import logger from './logger';
const events: EventEmitter = new EventEmitter();
const transactions: Map<string, TransactionEvent> = new Map();
const prisma: PrismaClient = new PrismaClient();
const refreshProvider = (web3Obj: Web3, providerWs: string): WebsocketProvider => {
let retries = 0;
const retry = (event: string | null): number | WebsocketProvider | null => {
if (event) {
retries++;
refreshProvider(web3Obj, providerWs);
logger.error('Web3 disconnected or errored');
if (retries > 5) {
logger.error('Exceeded number of 5 retries');
return setTimeout(refreshProvider, 5000);
}
} else {
logger.info('Reconnecting to the provider');
return refreshProvider(web3Obj, providerWs);
}
return null;
};
const provider: WebsocketProvider = new Web3.providers.WebsocketProvider(providerWs, {
timeout: 30000, // ms
clientConfig: {
// Useful if requests are large
maxReceivedFrameSize: 100000000, // bytes - default: 1MiB
maxReceivedMessageSize: 100000000, // bytes - default: 8MiB
// Useful to keep a connection alive
keepalive: true,
keepaliveInterval: 60000, // ms
},
reconnect: {
auto: true,
delay: 5000, // ms
maxAttempts: 10,
onTimeout: false,
},
});
provider.on('end', retry as () => unknown | void);
provider.on('error', retry as () => unknown | void);
web3Obj.setProvider(provider);
logger.info('New Web3 provider initiated');
return provider;
};
(() => {
if (!config || !config.length) {
return;
}
config.forEach((element) => {
const web3: Web3 = new Web3();
refreshProvider(web3, element.rpc);
const ABI: unknown = fs.readFileSync(`./src/abi/${element.abi}.json`, 'utf-8');
const contract: Contract = new web3.eth.Contract(JSON.parse(ABI as string) as AbiItem[], element.contractAddress);
const discordData = {
mainChannelIds: element.mainChannelIds,
whaleChannelIds: element.whaleChannelIds,
};
contract.events
.Transfer({}, (error: never) => {
if (error) {
logger.error(error);
console.log(error);
}
})
.on('data', (event: Event) => {
const {
transactionHash,
returnValues: { from, to, value },
} = event;
const amount: number = parseInt(value, 10) / 10 ** element.decimals;
const isFeeCollection: boolean =
from.toLowerCase() === element.exchangeAddress.toLowerCase() &&
to.toLowerCase() === element.contractAddress.toLowerCase();
const isBuy: boolean =
from.toLowerCase() === element.exchangeAddress.toLowerCase() &&
to.toLowerCase() !== element.contractAddress.toLowerCase();
const isSell: boolean =
from.toLowerCase() !== element.contractAddress.toLowerCase() &&
to.toLowerCase() === element.exchangeAddress.toLowerCase();
const isBurn: boolean = to.toLowerCase() === element.burnAddress.toLowerCase();
const getTransactionEvent = (): TransactionEvent => {
const getType = () => {
if (!isFeeCollection && isBuy) {
return 'buy';
}
if (!isFeeCollection && isSell) {
return 'sell';
}
if (!isFeeCollection && isBurn) {
return 'burn';
}
return 'fee';
};
return {
hash: transactionHash,
amount,
explorer: element.explorer,
getCurrentPrice: element.getCurrentPrice,
name: element.name,
type: getType(),
...discordData,
};
};
const getTransactionEventAfterFees = (): TransactionEvent => {
const fee = transactions.get(transactionHash);
const transactionEvent = getTransactionEvent();
if (fee) {
if (fee.type !== 'fee') {
return transactionEvent;
}
transactionEvent.amount = transactionEvent.amount + fee.amount;
transactions.delete(transactionHash);
}
return transactionEvent;
};
const addBurnTransaction = async (): Promise<void> => {
const transactionEvent = getTransactionEventAfterFees();
const price = await transactionEvent.getCurrentPrice();
const existingTransaction = await prisma.transactions.findFirst({
where: {
hash: transactionEvent.hash
}
});
if (existingTransaction) {
return;
}
await prisma.transactions.create({
data: {
name: transactionEvent.name,
type: -1,
amount: transactionEvent.amount,
address: from,
hash: transactionEvent.hash,
price,
},
});
};
if (isBurn) {
addBurnTransaction();
}
if (isFeeCollection && (!isBuy || !isSell)) {
transactions.set(transactionHash, getTransactionEvent());
}
if (!isFeeCollection && isBuy && element.buyAmount > 0) {
const transactionEvent = getTransactionEventAfterFees();
if (transactionEvent.amount >= element.buyAmount) {
events.emit('whale-buy', transactionEvent);
}
return;
}
if (!isFeeCollection && isSell && element.sellAmount > 0) {
const transactionEvent = getTransactionEventAfterFees();
if (transactionEvent.amount >= element.sellAmount) {
events.emit('whale-sell', transactionEvent);
}
return;
}
})
.on('error', (error: never) => {
if (error) {
logger.error(error);
console.log(error);
}
});
});
})();
(() => {
const client: Client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
client.once('ready', async () => {
console.log('Whale Watcher running');
logger.info('Whale watcher discord bot running');
events.on('whale-buy', async (data: TransactionEvent) => postTransactionEvent(client, data));
events.on('whale-sell', async (data: TransactionEvent) => postTransactionEvent(client, data));
});
client.login(process.env.DISCORD_TOKEN);
})();
(() => {
const server: Application = express();
const port = process.env.PORT || 2500;
server.use(express.json());
server.use(express.urlencoded({ extended: true }));
server.use(cors());
server.use('/transactions', transactionsRoutes);
server.listen(port, () => {
console.log(`Transaction watcher listening on ${port}`);
});
})();