-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
334 lines (307 loc) · 9.91 KB
/
main.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
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
import { parse } from "https://deno.land/[email protected]/flags/mod.ts";
import { parse as parseCsv } from "https://deno.land/[email protected]/encoding/csv.ts";
import { providers } from "https://esm.sh/[email protected]?dts";
import { readFileSync } from "https://deno.land/x/[email protected]/std/node/fs.ts";
import * as path from "https://deno.land/x/[email protected]/std/node/path.ts";
// import * as parseCSV from "npm:csv-parse";
import {
contractHandler,
customHandler,
restHandler,
rpcHandler,
} from "./handlers/index.ts";
import type { Metrics, ReturnedMetric, ReturnedMetrics } from "./lib/types.ts";
import defaultFormatter from "./lib/defaultFormatter.ts";
import newDB from "./db/db.ts";
import newModel from "./db/newModel.ts";
import loadConfig from "./lib/loadConfig.ts";
// import the dashboards
import dashboards from "./dashboards/index.ts";
Deno.addSignalListener("SIGINT", () => {
console.log("interrupted!");
Deno.exit(0);
});
const flags = parse(Deno.args, {
string: ["mode", "port", "path", "concurrency"],
boolean: ["json"],
alias: {
mode: "m",
port: "p",
path: "d",
concurrency: "n",
json: "j",
},
default: {
mode: "stout",
port: "8080",
path: "./metrics.db",
concurrency: "15",
json: false,
},
});
const concurrentRequests = parseInt(flags.concurrency);
const { contracts, deployment } = await loadConfig();
const provider = new providers.StaticJsonRpcProvider(
deployment.sources.eth,
deployment.chain.chainID
);
// helps the dashboards
const handler = async (metrics: Metrics): Promise<ReturnedMetric> => {
let res;
try {
switch (metrics.type) {
case "contract":
res = await contractHandler(provider, metrics, contracts, deployment);
break;
case "rpc":
res = await rpcHandler(metrics, deployment);
break;
case "rest":
res = await restHandler(metrics, deployment);
break;
case "custom":
res = await customHandler(provider, metrics, contracts, deployment);
break;
default:
throw new Error("Invalid metrics type");
}
if (metrics.metric?.formatter) {
return metrics.metric.formatter(metrics, res);
}
} catch (e) {
console.log("Error in handler: ", metrics.metric?.name || "unknown");
console.error(e);
// set the response to be null
res = null;
}
return defaultFormatter(metrics, res);
};
const gatherDashboards = async (
concurrentRequests = 15
): Promise<ReturnedMetrics> => {
// flatten the dashboards
// spread (...) doesn't work on dashboards because it's a default export
const metrics = dashboards.reduce((acc, curr) => [...acc, ...curr], []);
// chunk metrics into groups of 10
const metricChunks: Metrics[][] = [];
while (metrics.length > 0) {
metricChunks.push(metrics.splice(0, concurrentRequests));
}
const results = [];
for (const chunk of metricChunks) {
const res = await Promise.all(chunk.map(handler));
results.push(...res);
}
const obj = {} as ReturnedMetrics;
results.forEach((result) => {
obj[result.name as string] = result;
});
return obj;
};
const ggpCSandTSCalc = (): number[] => {
const csvFilePath = path.resolve("./tokenholders.csv");
const maxSupply = 22500000;
let circulatingSupply = 0;
const initialSupply = 18000000;
let currentTotalSupply = 0;
const headers = [
"name",
"percentageOfTotalSupply",
"lockUpLengthMonths",
"vestingLengthMonths",
"vestingIntervalInMonths",
"vestingStartDate",
"initialTokens",
];
const fileContent = readFileSync(csvFilePath, { encoding: "utf-8" });
const tokenHolders = parseCsv(fileContent.toString(), {
separator: ",",
columns: headers,
skipFirstRow: true,
});
// deno-lint-ignore no-explicit-any
tokenHolders.forEach(function (holder: any) {
// convert from string to date
const [month, day, year] = holder.vestingStartDate.split("/");
const vestingDate = new Date(+year, +month - 1, +day);
const now = new Date();
holder.percentageOfTotalSupply = parseFloat(
holder.percentageOfTotalSupply.replace("%", "")
);
holder.lockUpLengthMonths = parseInt(holder.lockUpLengthMonths);
holder.holderInitialTokens = parseInt(holder.holderInitialTokens);
holder.vestingLengthMonths = parseInt(holder.vestingLengthMonths);
holder.vestingIntervalInMonths = parseInt(holder.vestingIntervalInMonths);
if (now >= vestingDate) {
const differenceInMonths = getMonthDifference(vestingDate, now);
if (holder.vestingIntervalInMonths <= differenceInMonths) {
if (holder.name === "IDO" || holder.name === "Liquidity") {
circulatingSupply += parseInt(holder.initialTokens);
} else if (holder.name === "Rewards") {
const inflation = 0.04821842;
let inflatedInitialSupply = initialSupply;
const intervalsPassed =
differenceInMonths / holder.vestingIntervalInMonths;
for (let i = 0; i < intervalsPassed; i++) {
inflatedInitialSupply += inflatedInitialSupply * (inflation / 12);
}
currentTotalSupply = inflatedInitialSupply;
circulatingSupply += inflatedInitialSupply - initialSupply;
} else {
const percentageValue =
parseFloat(holder.percentageOfTotalSupply) / 100;
// console.log(holder.name, percentageValue);
const totalTokensDue = maxSupply * percentageValue;
// console.log(holder.name, totalTokensDue);
const amtPerInterval =
totalTokensDue /
(holder.vestingLengthMonths / holder.vestingIntervalInMonths);
// console.log(holder.name, amtPerInterval);
const intervalsPassed =
differenceInMonths / holder.vestingIntervalInMonths;
// console.log(holder.name, intervalsPassed);
circulatingSupply += amtPerInterval * intervalsPassed;
// console.log(holder.name, circulatingSupply);
}
}
}
});
return [circulatingSupply, currentTotalSupply];
};
function getMonthDifference(startDate: Date, endDate: Date) {
return (
endDate.getMonth() -
startDate.getMonth() +
12 * (endDate.getFullYear() - startDate.getFullYear())
);
}
const cacheTime = 60 * 1000; // 1 minute
interface kvCache {
// deno-lint-ignore no-explicit-any
data: any;
timestamp: number;
}
const kv = await Deno.openKv();
const serveHTTP = async (conn: Deno.Conn) => {
const ggpCSTS = ggpCSandTSCalc();
const [circulatingSupply, totalSupply] = ggpCSTS;
const httpConn = Deno.serveHttp(conn);
for await (const requestEvent of httpConn) {
const url = new URL(requestEvent.request.url);
if (url.pathname === "/ggpCirculatingSupply") {
const results = circulatingSupply;
requestEvent.respondWith(
new Response(JSON.stringify(results), {
status: 200,
headers: new Headers({
"content-type": "application/json",
}),
})
);
} else if (url.pathname === "/ggpTotalSupply") {
const results = totalSupply;
requestEvent.respondWith(
new Response(JSON.stringify(results), {
status: 200,
headers: new Headers({
"content-type": "application/json",
}),
})
);
} else {
const queryParams = url.searchParams;
const filter = queryParams.get("token") !== Deno.env.get("TOKEN");
const useCache = filter;
if (useCache) {
// get the cache from the kv store
const cache = await kv.get<kvCache>(["cache"]);
if (cache.value) {
// check the time. If the time is less than the current time, use the cache
const cacheTime = new Date(cache.value.timestamp);
const now = new Date();
if (cacheTime > now) {
requestEvent.respondWith(
new Response(JSON.stringify(cache.value.data), {
status: 200,
headers: new Headers({
"content-type": "application/json",
}),
})
);
continue;
}
}
}
const results = await gatherDashboards(concurrentRequests);
if (filter) {
const filters = ["rialto", "balance"];
// case insensitive. if the key contains the filter, return it
Object.keys(results).forEach((key) => {
const lowerKey = key.toLowerCase();
filters.forEach((filter) => {
const lowerFilter = filter.toLowerCase();
if (lowerKey.includes(lowerFilter)) {
delete results[key];
}
});
});
}
if (useCache) {
// store results in cache
await kv.set(["cache"], {
data: results,
timestamp: Date.now() + cacheTime,
});
}
requestEvent.respondWith(
new Response(JSON.stringify(results), {
status: 200,
headers: new Headers({
"content-type": "application/json",
}),
})
);
}
}
};
const dumpToDB = async (path: string) => {
const results = await gatherDashboards(concurrentRequests);
// get all the values from the results
await newDB(path);
await Promise.all(
Object.values(results).map(async (result) => {
const metric = newModel(result);
await metric.save();
})
);
};
try {
switch (flags.mode) {
case "stout": {
const results = await gatherDashboards(concurrentRequests);
if (flags.json) {
console.log(JSON.stringify(results));
} else {
console.log(results);
}
break;
}
case "serve": {
const server = Deno.listen({ port: parseInt(flags.port) });
console.log(`Listening on port ${flags.port}`);
for await (const conn of server) {
serveHTTP(conn);
}
break;
}
case "dump":
await dumpToDB(flags.path);
break;
default:
throw new Error(`Invalid mode: ${flags.mode}`);
}
} catch (e) {
console.error(e);
Deno.exit(1);
}
Deno.exit(0);