-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutils.js
389 lines (365 loc) · 12.3 KB
/
utils.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
const axios = require('axios').default;
const { ChartJSNodeCanvas } = require('chartjs-node-canvas');
const { Chart } = require('chart.js');
const ChartDataLabels = require('chartjs-plugin-datalabels');
const smallChartJSNodeCanvas = new ChartJSNodeCanvas({ width: 900, height: 900, backgroundColour: 'white'})
const bigChartJSNodeCanvas = new ChartJSNodeCanvas({ width: 1500, height: 1500, backgroundColour: 'white'})
const bubbleChartOptions = (_title, _mcap) => options = {
plugins: {
datalabels: {
align: function(context) {
value = context.dataset.data[context.dataIndex]
if (value[2] < 10 || (value[2] < 20 && value[3].length > 7))
return "end"
},
color: function() {
return 'black';
},
font: {
weight: 'bold'
},
formatter: function(value) {
return value[3]
},
offset: function(context) {
value = context.dataset.data[context.dataIndex]
if (value[2] < 10)
return 7
else if (value[2] < 20 && value[3].length > 7) {
return 15
}
},
padding: 0
},
legend: {
display: false
},
title: {
display: true,
text: _title,
font: {
size: 25
},
padding: {
top: 10,
bottom: 40
}
}
},
layout: {
padding: 16
},
scales: {
x: {
title: {
display: true,
text: function() {
if (_mcap)
return "mcap / tvl"
else
return "fdv / tvl"
},
font: {
size: 20
},
padding: {
top: 20,
bottom: 10
}
}
},
y: {
title: {
display: true,
text: "mcap / fdv",
font: {
size: 20
},
padding: {
top: 20,
bottom: 10
}
}
}
}
}
async function createAndSaveChart(_big, _result, _title, _type, _mcap) {
let config, myData
let colors = getColors(_result[0].length)
if (_type != "bubble") {
myData = {
labels: _result[0],
datasets: [{
label: _title,
data: _result[1],
backgroundColor: colors,
hoverOffset: 4
}]
}
config = {
type: _type,
data: myData,
}
} else {
Chart.register(ChartDataLabels)
myData = {
datasets: [{
data: _result,
backgroundColor: colors,
}]
}
config = {
type: _type,
data: myData,
options: bubbleChartOptions(_title, _mcap)
}
}
let buffer
_big ?
buffer = await bigChartJSNodeCanvas.renderToBuffer(config) :
buffer = await smallChartJSNodeCanvas.renderToBuffer(config)
if (_type == "bubble") Chart.unregister(ChartDataLabels)
return buffer
}
function getColors(_n) {
const COLORS = [
'#4dc9f6',
'#f67019',
'#f53794',
'#537bc4',
'#acc236',
'#166a8f',
'#00a950',
'#58595b',
'#8549ba'
];
let colors = [];
for(i = 0; i < _n; ++i) {
colors.push(COLORS[i % COLORS.length])
}
return colors;
}
async function getCurrentPriceFromCoingecko(_gecko_id) {
let response = await axios.get(
`https://api.coingecko.com/api/v3/simple/price?ids=${_gecko_id}&vs_currencies=usd`
)
let price = response.data[_gecko_id]?.usd ?? undefined
return price
}
async function getCurrentDataFromCoingecko(_gecko_id, _date = undefined) {
let response = await axios.get(
`https://api.coingecko.com/api/v3/coins/${_gecko_id}` +
(_date ? `/history?date=${_date}&localization=false` : "")
)
return response.data
}
async function getProtocols() {
let response = await axios.get('https://api.llama.fi/protocols')
let protocols = response.data;
// we'll exclude wBTC, hBTC and others
protocols = protocols.filter(p => !p.name.includes("BTC"))
return protocols
}
async function getFirstTVLProtocols(_n) {
let _apiLabels, _apiData
let protocols = await getProtocols();
let selected = protocols.slice(0, _n)
_apiLabels = selected.map(p => p.name)
_apiData = selected.map(p => p.tvl)
return [_apiLabels, _apiData]
}
async function getBestOrWorseOfFirstNTVL_LastDayOrWeek(_n, _firstN, _best, _day) {
let _apiLabels, _apiData
let protocols = await getProtocols();
let change
Number(_day) ? change = "change_1d" : change = "change_7d"
protocols = protocols.filter(p => p[change] != null)
let selected = protocols.slice(0, _firstN)
Number(_best) ?
selected = selected.sort((a, b) => b[change] - a[change])
:
selected = selected.sort((a, b) => a[change] - b[change])
selected = selected.slice(0, _n)
_apiLabels = selected.map(p => p.name)
_apiData = selected.map(p => p[change])
return [_apiLabels, _apiData]
}
async function getFDVFromCoingecko(_id) {
// could die because of delistings or too many requests
try {
let data = await getCurrentDataFromCoingecko(_id)
let price = data.market_data.current_price.usd
let fdv = data.market_data.total_supply * price
return fdv
} catch(e) {
console.error(e)
return 0
}
}
// this function takes a value which belongs to a range and
// fits it into a new value based on a new range
function normalizeData(_value, _initRange, _finalRange) {
return (_value - _initRange[0]) /
(_initRange[1] - _initRange[0])*
(_finalRange[1] - _finalRange[0]) +
_finalRange[0]
}
async function getFirstNTVLWithBestRatio(_n, _firstN, _mcap) {
let x, y, r, label, num, den
let protocols = await getProtocols();
protocols = protocols.filter(p => p.mcap != 0 && p.tvl != 0)
let selected = protocols.slice(0, _firstN)
// not everytime FDV is defined, and it's the only parameter we can
// calculate using coingecko
await Promise.all(
selected.map(async p => {
if (isNaN(p.fdv)) {
if(p.gecko_id) {
p.fdv = await getFDVFromCoingecko(p.gecko_id)
}
}
})
)
Number(_mcap) ? ( num = "mcap", den = "tvl" ) : ( num = "fdv", den = "tvl" )
selected = selected.sort((a, b) => a[num] / a[den] - b[num] / b[den])
selected = selected.slice(0, _n)
let data = []
selected.map(p => {
// lower ratio = better tokenomics
x = p[num] / p[den]
// higher ratio = better tokenomics
y = p["mcap"] / p["fdv"]
// lower market cap = better opportunities
r = p["mcap"] / 10**7
label = p.name
data.push([x,y,r,label])
})
data = data.filter(d => !isNaN(d[2]))
// as the range of protocols market cap is pretty big,
// we need to normalize the data, and set a new range
let initRange = [
Math.min(...data.map(d => d[2])),
Math.max(...data.map(d => d[2])),
]
// a radius will have values in this new range
let finalRange = [3, 50]
data = data.map(d => [
d[0],
d[1],
normalizeData(d[2], initRange, finalRange),
d[3]
])
return data
}
function setImageSize(_n, _type) {
if (_n > 25 && _type == "bar") {
return true
} else {
return false
}
}
/**
* EXPORTING FUNCTIONS
*/
async function searchProtocolForName(_name) {
let protocols = await getProtocols();
let protocol = protocols.filter(
p => p.name
.toLowerCase()
.replace(" ","")
.includes(
_name
.toLowerCase()
.replace(" ","")
)
)
return protocol
}
async function searchProtocolForSymbol(_symbol) {
let protocols = await getProtocols();
let protocol = protocols.filter(p => p.symbol.toLowerCase().includes(_symbol.toLowerCase()))
return protocol
}
async function compareProtocolAToProtocolB(protocolAData, protocolBData) {
// take data
const tokenAMcap = protocolAData.mcap
const tokenBMcap = protocolBData.mcap
const tokenATvl = protocolAData.tvl
const tokenBTvl = protocolBData.tvl
// take price of protocol A from coingecko
const tokenAPrice = await getCurrentPriceFromCoingecko(protocolAData.gecko_id)
// calculate change in price and percentage change
if (tokenAPrice) {
const tokenBMcapTvl = tokenBMcap / tokenBTvl
const tokenACirculating = tokenAMcap / tokenAPrice
const tokenAPriceWithTokenBMcapTvl = (tokenBMcapTvl * tokenATvl) / tokenACirculating
const tokenAPriceChange = tokenAPriceWithTokenBMcapTvl / tokenAPrice
return [tokenAPriceWithTokenBMcapTvl, tokenAPriceChange]
} else {
return [0, 0]
}
}
// we could also return the mcap/fdv ratio, for user info
async function fairPriceAtATHTVL(_protocolSlug) {
try {
// get history of TVL
let response = await axios.get(`https://api.llama.fi/protocol/${_protocolSlug}`)
let history = response.data;
const gecko_id = history.gecko_id;
let tvlHistory = history.tvl
const ATH_TVL = Math.max(...tvlHistory.map(h => h.totalLiquidityUSD))
let maxTvlDate = tvlHistory.find(h => h.totalLiquidityUSD == ATH_TVL).date
// convert date from unix format and prepare for coingecko query
maxTvlDate = new Date(maxTvlDate * 1000)
const maxTvlDateString = `${maxTvlDate.getDate()}-${maxTvlDate.getMonth() + 1}-${maxTvlDate.getFullYear()}`
// get history of Mcap and price
history = await getCurrentDataFromCoingecko(gecko_id, maxTvlDateString)
let mcap_at_ATH_TVL = history.market_data.market_cap.usd
let currentData = await getCurrentDataFromCoingecko(gecko_id)
let current_price = currentData.market_data.current_price.usd
let new_price_multiplier, new_price
// if mcap was unset at that time, we take current mcap
if (!mcap_at_ATH_TVL) {
let current_mcap = currentData.market_data.market_cap.usd
new_price_multiplier = ATH_TVL / current_mcap
new_price = new_price_multiplier * current_price
} else {
let price_at_ATH_TVL = history.market_data.current_price.usd
new_price_multiplier = ((ATH_TVL / mcap_at_ATH_TVL) * price_at_ATH_TVL) / current_price
new_price = new_price_multiplier * current_price
}
return [new_price, new_price_multiplier]
} catch(e) {
console.error(e)
return [0, 0]
}
}
async function getFirstTVLProtocolsChart(_n, _type) {
let big = setImageSize(_n, _type)
let result = await getFirstTVLProtocols(_n)
let title = `Top ${_n} protocols for TVL`
let bufferImg = await createAndSaveChart(big, result, title, _type)
return bufferImg
}
async function getTopPerformersChart(_firstN, _n, _best, _day, _type) {
let big = setImageSize(_n, _type)
let result = await getBestOrWorseOfFirstNTVL_LastDayOrWeek(_n, _firstN, _best, _day)
let title = `First ${_n} ${_best ? "best" : "worse"} performers in top ${_firstN} protocols for TVL of ${_day ? "last day" : "last week"}`
let bufferImg = await createAndSaveChart(big, result, title, _type)
return bufferImg
}
async function getBestRatioChart(_firstN, _n, _mcap) {
let result = await getFirstNTVLWithBestRatio(_n, _firstN, _mcap)
let title = `First ${_n} in top ${_firstN} protocols with best ${_mcap ? "mcap/tvl" : "fdv/tvl"} ratio weighing mcap/fdv`
let bufferImg = await createAndSaveChart(false, result, title, "bubble", _mcap)
return bufferImg
}
module.exports = {
searchProtocolForName,
searchProtocolForSymbol,
compareProtocolAToProtocolB,
getFirstTVLProtocolsChart,
getTopPerformersChart,
getBestRatioChart,
fairPriceAtATHTVL,
}