-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathliquidator.js
More file actions
223 lines (186 loc) · 6.71 KB
/
liquidator.js
File metadata and controls
223 lines (186 loc) · 6.71 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
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
import { dfinance_backend } from "./index.js";
const cache = {};
const POLLING_INTERVAL = 10 * 60 * 1000; // 10 minutes
async function fetchExchangeRate(baseAsset) {
try {
const result = await dfinance_backend.get_exchange_rates(
baseAsset,
[],
100000000
);
// console.log(result);
if (result && result.Ok) {
const [price, timestamp] = result.Ok;
console.log(
`Exchange rate fetched successfully for ${baseAsset}:`,
price,
timestamp
);
return price;
} else {
console.error(
`Error fetching price for ${baseAsset}:`,
result.Err || "Unknown error"
);
return null;
}
} catch (error) {
console.error(`Failed to fetch exchange rate for ${baseAsset}:`, error);
return null;
}
}
async function updateCacheAndTriggerActions(assets) {
for (const asset of assets) {
const newPrice = await fetchExchangeRate(asset);
if (newPrice !== null) {
// Update the cache with the new price unconditionally
console.log(
`Updating price for ${asset}: Old: ${cache[asset]}, New: ${newPrice}`
);
cache[asset] = newPrice;
// Trigger actions for the asset
}
}
await calculateUserHealthFactor();
}
async function calculateUserHealthFactor() {
try {
const allUsers = await dfinance_backend.get_all_users();
for (const [principal, userData] of allUsers) {
// Use for...of instead of forEach
//console.log("Principal:", principal.toText());
const reserves = userData.reserves || [];
// console.log("Reserves:", reserves);
let totalCollateral = 0;
let totalDebt = 0;
let largestBorrowAsset = { asset: null, value: 0 };
let largestCollateralAsset = { asset: null, value: 0 };
// Flatten and process reserves
for (const reserveArray of reserves) {
// Navigate outer array
for (const reserve of reserveArray) {
// Navigate inner reserves
const reserveAsset = reserve[0]; // Extract asset name (e.g., 'ckUSDC')
const userreserveData = reserve[1]; // Extract reserve data object
console.log("*******Fetching Reserve**********");
console.log("Processing reserve:", reserveAsset);
//console.log("Reserve data:", userreserveData);
// Check if supply_rate key exists
if (!("supply_rate" in userreserveData)) {
console.error(
`Missing "supply_rate" for reserve: ${reserveAsset}`,
userreserveData
);
continue; // Skip this reserve if "supply_rate" is missing
}
// Proceed with valid reserves
const supplyRate = userreserveData.supply_rate;
//console.log(`Supply rate for ${reserveAsset}:`, supplyRate);
// Fetch normalized income and debt
const normalizedIncome =
await dfinance_backend.user_normalized_supply(userreserveData);
const normalizedDebt = await dfinance_backend.user_normalized_debt(
userreserveData
);
const assetPrice = cache[reserveAsset] || 0; // Use cached price
console.log(
`Normalized Income for ${reserveAsset}:`,
normalizedIncome.Ok * userreserveData.asset_supply
);
console.log(
`Normalized Debt for ${reserveAsset}:`,
normalizedDebt.Ok
);
console.log(`Asset price for ${reserveAsset}:`, assetPrice);
// Process collateral
if (userreserveData.is_collateral) {
const collateralValue = Math.round(
(((Number(normalizedIncome.Ok) * Number(assetPrice)) / 1e8) *
Number(userreserveData.asset_supply)) /
1e8
);
totalCollateral += collateralValue;
if (collateralValue > largestCollateralAsset.value) {
largestCollateralAsset = {
asset: reserveAsset,
value: collateralValue,
};
}
}
// Process debt
const debtValue = Math.round(
(((Number(normalizedDebt.Ok) * Number(assetPrice)) / 1e8) *
Number(userreserveData.asset_borrow)) /
1e8
);
totalDebt += debtValue;
if (debtValue > largestBorrowAsset.value) {
largestBorrowAsset = { asset: reserveAsset, value: debtValue };
}
}
}
const position = {
total_collateral_value: totalCollateral,
total_borrowed_value: totalDebt,
liquidation_threshold: userData.liquidation_threshold,
};
const healthFactor = calculateHealthFactor(position);
console.log(`User ${principal} Health Factor (h.f): ${healthFactor}`);
if (healthFactor < 1e8) {
console.log(`User ${principal} is at risk of liquidation!`);
const borrowAsset = Array.isArray(largestBorrowAsset.asset)
? largestBorrowAsset.asset[0]
: largestBorrowAsset.asset;
const collateralAsset = Array.isArray(largestCollateralAsset.asset)
? largestCollateralAsset.asset[0]
: largestCollateralAsset.asset;
const principalText = principal.toText();
console.log("Largest Borrow Asset:", borrowAsset);
console.log("Largest Collateral Asset:", collateralAsset);
console.log("Principal:", principalText);
console.log("Value:", largestBorrowAsset.value);
try {
const result = await dfinance_backend.liquidation_call(
borrowAsset,
collateralAsset,
largestBorrowAsset.value,
principalText
);
console.log(`Liquidation result for ${principalText}:`, result);
} catch (error) {
console.error(
`Error during liquidation call for ${principalText}:`,
error
);
}
}
console.log("*************");
}
} catch (error) {
console.error(`Error fetching users by asset:`, error);
}
}
async function startPriceMonitoring(assets) {
console.log("Starting price monitoring...");
await updateCacheAndTriggerActions(assets);
setInterval(async () => {
console.log("Checking for price updates...");
await updateCacheAndTriggerActions(assets);
}, POLLING_INTERVAL);
}
const assets = ["ICP", "ckBTC", "ckETH", "ckUSDC", "ckUSDT"];
// Start the monitoring process
startPriceMonitoring(assets);
function calculateHealthFactor(position) {
const {
total_collateral_value,
total_borrowed_value,
liquidation_threshold,
} = position;
if (total_borrowed_value === 0) {
return Number.MAX_SAFE_INTEGER;
}
return (
(total_collateral_value * liquidation_threshold) / total_borrowed_value
);
}