-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
303 lines (251 loc) · 13.3 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
// Dependencies
const dotenv = require('dotenv');
const { Client, Intents, MessageEmbed } = require('discord.js');
const { ethers, Contract, BigNumber } = require("ethers");
const publicIp = require('public-ip');
const swapABI = require('./constants/swapABI.json');
const contracts = require('./constants/contracts.json');
const retry = require('async-retry');
const fetch = require('node-fetch');
// Set up dotenv config and discord bot
dotenv.config();
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const provider = new ethers.providers.JsonRpcProvider(process.env.ALCHEMY_API);
const isProduction = !process.env.ALCHEMY_API.includes("127.0.0.1")
const coinGeckoAPI = "https://api.coingecko.com/api/v3/simple/price"
const slippageSeekerRole = "935614128880508969"
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
async function queryTokenPricesUSD(tokenIDs) {
return await retry(async bail => {
// if anything throws, we retry
const res = await fetch(`${coinGeckoAPI}?ids=${encodeURIComponent(tokenIDs.join(","))}&vs_currencies=usd`)
if (403 === res.status) {
// don't retry upon 403
bail(new Error('Unauthorized'))
return
}
return res.json()
}, {
retries: 5
})
}
function getChannel(channelID) {
return bot.channels.cache.get(channelID);
}
async function log(message) {
return getChannel(process.env.DISCORD_LOG_CHANNEL_ID).send(message);
}
async function send(message) {
return getChannel(process.env.DISCORD_CHANNEL_ID).send(message);
}
function toHumanString(rawTokenAmount, decimals, digitsToShow) {
let s = BigNumber.from(rawTokenAmount).div(BigNumber.from(10).pow(decimals - digitsToShow)).toNumber();
s = s / (10 ** digitsToShow)
if (s === 0) {
return "0";
} else {
return s.toFixed(digitsToShow);
}
}
function calculateExchangeRate(sellAmount, buyAmount) {
return buyAmount / sellAmount
}
function toUSD(s) {
return formatter.format(parseFloat(s))
}
function formatNum(num) {
return BigNumber.from(parseInt(parseFloat(num.toFixed(2)) * 100))
}
async function main() {
bot.on('ready', async () => {
console.log(`Logged in as ${bot.user.tag}!`);
log(`Bot started at ${await publicIp.v4()}. Using ${process.env.ALCHEMY_API} as the json rpc endpoint...`)
});
bot.on('message', msg => {
if (msg.content === 'ping') {
send('pong');
}
});
for (const contract of contracts) {
const contractAddress = isProduction ? contract["address"] : contract["localAddress"]
const instance = new Contract(contractAddress, swapABI, provider)
// On token swap event
instance.on("TokenSwap", async (buyer, tokensSold, tokensBought, soldId, boughtId, event) => {
const soldTokenName = contract["tokens"][soldId]
const boughtTokenName = contract["tokens"][boughtId]
const digitsToShow = 4
const prices = await queryTokenPricesUSD(contract["coingeckoIDs"])
const numOfTokenSold = toHumanString(tokensSold, contract["decimals"][soldId], digitsToShow)
const numOfTokenBought = toHumanString(tokensBought, contract["decimals"][boughtId], digitsToShow)
const totalUSDValueSold = toUSD(toHumanString(
BigNumber.from(tokensSold).mul(formatNum(prices[`${contract["coingeckoIDs"][soldId]}`]["usd"])).div(100),
contract["decimals"][soldId],
digitsToShow
))
const totalUSDValueBought = toUSD(toHumanString(
BigNumber.from(tokensBought).mul(formatNum(prices[`${contract["coingeckoIDs"][boughtId]}`]["usd"])).div(100),
contract["decimals"][boughtId],
digitsToShow
))
const fee = (numOfTokenBought * 0.0004 / (1 - 0.0004))
const totalUSDFee = toUSD( fee * prices[`${contract["coingeckoIDs"][boughtId]}`]["usd"])
const exchangeRate = calculateExchangeRate(numOfTokenSold * 1, numOfTokenBought * 1)
// inside a command, event listener, etc.
let embed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Token swap')
.setURL(`https://etherscan.io/tx/${event.transactionHash}`)
.setAuthor(contract["name"], contract["authorThumbnailURL"], `https://etherscan.io/address/${contractAddress}`)
.setDescription(`${buyer} swapped ${soldTokenName} to ${boughtTokenName}`)
.addFields(
{ name: 'Input amount', value: `${numOfTokenSold} ${soldTokenName} (${totalUSDValueSold})`, inline: true },
{ name: 'Output amount', value: `${numOfTokenBought} ${boughtTokenName} (${totalUSDValueBought})`, inline: true },
)
.addField(`Fees gained by LPs`, `${fee.toFixed(digitsToShow)} ${boughtTokenName} (${totalUSDFee})`, false)
.setTimestamp()
if (exchangeRate <= 0.98) {
embed.addField('Exchange rate', `1:${exchangeRate.toFixed(3)} (attn: <@&${slippageSeekerRole}>)`)
}
if (!isProduction) {
embed = embed.setFooter(`Hardhat network`)
}
send(embed);
log(JSON.stringify(event));
});
instance.on("FlashLoan", async (receiver, tokenIndex, amount, amountFee, protocolFee, event) => {
const loanAmount = toHumanString(amount, contract["decimals"][tokenIndex], 3)
const getUSDAmount = (amt, idx) => toHumanString(BigNumber.from(amt).mul(formatNum(prices[`${contract["coingeckoIDs"][idx]}`]["usd"])).div(100), contract["decimals"][idx], 2)
const loanAmountUSD = getUSDAmount(amount, tokenIndex)
const feeAmountUSD = getUSDAmount(amountFee, tokenIndex)
let embed = new MessageEmbed()
.setColor('#33ff33')
.setTitle('Flash Loan')
.setURL(`https://etherscan.io/tx/${event.transactionHash}`)
.setAuthor(contract["name"], contract["authorThumbnailURL"], `https://etherscan.io/address/${contractAddress}`)
.setDescription(`${receiver} took a flash loan from the ${contract['name']}`)
.addFields(
{ name: "Loan amount", value: `${loanAmount} ${contract["tokens"][tokenIndex]}`, inline: false },
{ name: "Loan USD value", value: `${toUSD(loanAmountUSD)}`, inline: false },
{ name: "Fees collected", value: `${toUSD(feeAmountUSD)}`, inline: false }
)
.setTimestamp()
if (!isProduction) {
embed = embed.setFooter(`Hardhat network`)
}
})
// On AddLiquidity event
instance.on("AddLiquidity", async (provider, tokenAmounts, fees, invariant, lpTokenSupply, event) => {
const digitsToShow = 3
const depositAmounts = tokenAmounts.map((amount, i) =>
`${toHumanString(amount, contract["decimals"][i], digitsToShow)} ${contract["tokens"][i]}`
).join(', ')
const prices = await queryTokenPricesUSD(contract["coingeckoIDs"])
const totalDollarValue = tokenAmounts.map((amount, i) =>
toHumanString(BigNumber.from(amount).mul(formatNum(prices[`${contract["coingeckoIDs"][i]}`]["usd"])).div(100), contract["decimals"][i], digitsToShow)
).reduce((a, val) => a + parseFloat(val), 0)
// inside a command, event listener, etc.
let embed = new MessageEmbed()
.setColor('#33ff33')
.setTitle('Deposit')
.setURL(`https://etherscan.io/tx/${event.transactionHash}`)
.setAuthor(contract["name"], contract["authorThumbnailURL"], `https://etherscan.io/address/${contractAddress}`)
.setDescription(`${provider} added new liquidity to the ${contract['name']}`)
.addFields(
{ name: 'Deposit amounts', value: `${depositAmounts}`, inline: false },
{name: "Total USD value", value: `${toUSD(totalDollarValue)}`, inline: false}
)
.setTimestamp()
if (!isProduction) {
embed = embed.setFooter(`Hardhat network`)
}
send(embed);
log(JSON.stringify(event));
});
// On RemoveLiquidity event
instance.on("RemoveLiquidity", async (provider, tokenAmounts, lpTokenSupply, event) => {
const digitsToShow = 3
const withdrawAmounts = tokenAmounts.map((amount, i) =>
`${toHumanString(amount, contract["decimals"][i], digitsToShow)} ${contract["tokens"][i]}`
).join(', ')
const prices = await queryTokenPricesUSD(contract["coingeckoIDs"])
const totalDollarValue = tokenAmounts.map((amount, i) =>
toHumanString(BigNumber.from(amount).mul(formatNum(prices[`${contract["coingeckoIDs"][i]}`]["usd"])).div(100), contract["decimals"][i], digitsToShow)
).reduce((a, val) => a + parseFloat(val), 0)
// inside a command, event listener, etc.
let embed = new MessageEmbed()
.setColor('#FF9A00')
.setTitle('Withdraw')
.setURL(`https://etherscan.io/tx/${event.transactionHash}`)
.setAuthor(contract["name"], contract["authorThumbnailURL"], `https://etherscan.io/address/${contractAddress}`)
.setDescription(`${provider} removed liquidity from the ${contract['name']}`)
.addFields(
{ name: 'Withdraw amounts', value: `${withdrawAmounts}`, inline: false },
{name: "Total USD value", value: `${toUSD(totalDollarValue)}`, inline: false}
)
.setTimestamp()
if (!isProduction) {
embed = embed.setFooter(`Hardhat network`)
}
send(embed);
log(JSON.stringify(event));
});
// On RemoveLiquidity event
instance.on("RemoveLiquidityOne", async (provider, lpTokenAmount, lpTokenSupply, boughtId, tokensBought, event) => {
const digitsToShow = 3
const withdrawAmounts = `${toHumanString(tokensBought, contract["decimals"][boughtId], digitsToShow)} ${contract["tokens"][boughtId]}`;
const prices = await queryTokenPricesUSD(contract["coingeckoIDs"])
const totalDollarValue =
toHumanString(BigNumber.from(tokensBought).mul(formatNum(prices[`${contract["coingeckoIDs"][boughtId]}`]["usd"])).div(100), contract["decimals"][boughtId], digitsToShow)
// inside a command, event listener, etc.
let embed = new MessageEmbed()
.setColor('#FF9A00')
.setTitle('Withdraw')
.setURL(`https://etherscan.io/tx/${event.transactionHash}`)
.setAuthor(contract["name"], contract["authorThumbnailURL"], `https://etherscan.io/address/${contractAddress}`)
.setDescription(`${provider} removed liquidity from the ${contract['name']}`)
.addFields(
{ name: 'Withdraw amounts', value: `${withdrawAmounts}`, inline: false },
{name: "Total USD value", value: `${toUSD(totalDollarValue)}`, inline: false}
)
.setTimestamp()
if (!isProduction) {
embed = embed.setFooter(`Hardhat network`)
}
send(embed);
log(JSON.stringify(event));
});
// On RemoveLiquidity event
instance.on("RemoveLiquidityImbalance", async (provider, tokenAmounts, fees, invariant, lpTokenSupply, event) => {
const digitsToShow = 4
const withdrawAmounts = tokenAmounts.map((amount, i) =>
`${toHumanString(amount, contract["decimals"][i], digitsToShow)} ${contract["tokens"][i]}`
).join(', ')
const prices = await queryTokenPricesUSD(contract["coingeckoIDs"])
const totalDollarValue = tokenAmounts.map((amount, i) =>
toHumanString(BigNumber.from(amount).mul(formatNum(prices[`${contract["coingeckoIDs"][i]}`]["usd"])).div(100), contract["decimals"][i], digitsToShow)
).reduce((a, val) => a + parseFloat(val), 0)
// inside a command, event listener, etc.
let embed = new MessageEmbed()
.setColor('#FF9A00')
.setTitle('Withdraw')
.setURL(`https://etherscan.io/tx/${event.transactionHash}`)
.setAuthor(contract["name"], contract["authorThumbnailURL"], `https://etherscan.io/address/${contractAddress}`)
.setDescription(`${provider} removed liquidity from the ${contract['name']}`)
.addFields(
{ name: 'Withdraw amounts', value: `${withdrawAmounts}`, inline: false },
{name: "Total USD value", value: `${toUSD(totalDollarValue)}`, inline: false}
)
.setTimestamp()
if (!isProduction) {
embed = embed.setFooter(`Hardhat network`)
}
send(embed);
log(JSON.stringify(event));
});
}
await bot.login(process.env.DISCORD_BOT_TOKEN);
}
main();