-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.js
More file actions
106 lines (96 loc) · 2.36 KB
/
graph.js
File metadata and controls
106 lines (96 loc) · 2.36 KB
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
const { GraphQLClient, gql } = require("graphql-request");
const config = require("./config");
async function querySubgraph(subgraphUrl, query) {
try {
const client = new GraphQLClient(subgraphUrl, { headers: {} });
const response = await client.request(query);
return response;
} catch (error) {
console.log("fetch error ", error);
return null;
}
}
async function extractLiquidations(graphUrl, startTime, lastDocId) {
let query = "";
if (!lastDocId) {
query = gql`
query {
liquidates(first: 100, where: { timestamp_gte: "${startTime}" }, orderBy: blockNumber) {
id
amount
amountUSD
blockNumber
hash
timestamp
liquidator { id }
liquidatee { id }
asset {
decimals
id
name
symbol
lastPriceUSD
lastPriceBlockNumber
}
profitUSD
}
}
`;
} else {
query = gql`
query {
liquidates(
first: 100,
where: { id_gt: "${lastDocId}", timestamp_gt: "${startTime}" },
orderBy: blockNumber
) {
id
amount
amountUSD
blockNumber
hash
timestamp
liquidator { id }
liquidatee { id }
asset {
decimals
id
name
symbol
lastPriceUSD
lastPriceBlockNumber
}
profitUSD
}
}
`;
}
try {
const result = await querySubgraph(graphUrl, query);
console.log("fetched ", result?.liquidates?.length);
return result?.liquidates;
} catch (error) {
console.log("something went wrong ", error);
return [];
}
}
async function fetchLiquidationDataFromGraph(
startTime,
lastDocId,
currentProtocolIndex
) {
const subgraphUrl = config.protocols?.[currentProtocolIndex]?.subgraph;
let results;
let nextLastDocId;
if (!lastDocId) {
results = await extractLiquidations(subgraphUrl, startTime, null);
nextLastDocId = results?.[results?.length - 1]?.id;
} else {
results = await extractLiquidations(subgraphUrl, startTime, lastDocId);
nextLastDocId = results?.[results?.length - 1]?.id;
}
return { liquidations: results, nextLastDocId };
}
module.exports = {
fetchLiquidationDataFromGraph,
};