-
Notifications
You must be signed in to change notification settings - Fork 45
/
index.js
331 lines (268 loc) · 15.8 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
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
const Web3 = require("web3");
const Big = require("big.js");
const axios = require("axios");
const fusePoolDirectoryAbi = require(__dirname + '/abi/FusePoolDirectory.json');
const fusePoolLensAbi = require(__dirname + '/abi/FusePoolLens.json');
const fuseSafeLiquidatorAbi = require(__dirname + '/abi/FuseSafeLiquidator.json');
const erc20Abi = require(__dirname + '/abi/ERC20.json');
// Set Big.js rounding mode to round down
Big.RM = 0;
var web3 = new Web3(new Web3.providers.HttpProvider(process.env.WEB3_HTTP_PROVIDER_URL));
var fusePoolDirectory = new web3.eth.Contract(fusePoolDirectoryAbi, process.env.FUSE_POOL_DIRECTORY_CONTRACT_ADDRESS);
var fusePoolLens = new web3.eth.Contract(fusePoolLensAbi, process.env.FUSE_POOL_LENS_CONTRACT_ADDRESS);
var fuseSafeLiquidator = new web3.eth.Contract(fuseSafeLiquidatorAbi, process.env.FUSE_SAFE_LIQUIDATOR_CONTRACT_ADDRESS);
async function approveTokensToSafeLiquidator(erc20Address, amount) {
// Build data
var token = new web3.eth.Contract(erc20Abi, erc20Address);
var data = token.methods.approve(amount).encodeABI();
// Build transaction
var tx = {
from: process.env.ETHEREUM_ADMIN_ACCOUNT,
to: erc20Address,
value: 0,
data: data,
nonce: await web3.eth.getTransactionCount(process.env.ETHEREUM_ADMIN_ACCOUNT)
};
if (process.env.NODE_ENV !== "production") console.log("Signing and sending " + erc20Address + " approval transaction:", tx);
// Estimate gas for transaction
try {
tx["gas"] = await web3.eth.estimateGas(tx);
} catch (error) {
throw "Failed to estimate gas before signing and sending " + erc20Address + " approval transaction: " + error;
}
// Sign transaction
try {
var signedTx = await web3.eth.accounts.signTransaction(tx, process.env.ETHEREUM_ADMIN_PRIVATE_KEY);
} catch (error) {
throw "Error signing " + erc20Address + " approval transaction: " + error;
}
// Send transaction
try {
var sentTx = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
} catch (error) {
throw "Error sending " + erc20Address + " approval transaction: " + error;
}
console.log("Successfully sent " + erc20Address + " approval transaction:", sentTx);
return sentTx;
}
async function sendTransactionToSafeLiquidator(method, params, value) {
// Build data
var data = fuseSafeLiquidator.methods[method](...params).encodeABI();
// Build transaction
var tx = {
from: process.env.ETHEREUM_ADMIN_ACCOUNT,
to: fuseSafeLiquidator.options.address,
value: value,
data: data,
nonce: await web3.eth.getTransactionCount(process.env.ETHEREUM_ADMIN_ACCOUNT)
};
if (process.env.NODE_ENV !== "production") console.log("Signing and sending", method, "transaction:", tx);
// Estimate gas for transaction
try {
tx["gas"] = await web3.eth.estimateGas(tx);
} catch (error) {
throw "Failed to estimate gas before signing and sending", method, "transaction: " + error;
}
// Sign transaction
try {
var signedTx = await web3.eth.accounts.signTransaction(tx, process.env.ETHEREUM_ADMIN_PRIVATE_KEY);
} catch (error) {
throw "Error signing", method, "transaction: " + error;
}
// Send transaction
try {
var sentTx = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
} catch (error) {
throw "Error sending", method, "transaction: " + error;
}
console.log("Successfully sent", method, "transaction:", sentTx);
return sentTx;
}
async function liquidateUnhealthyBorrows() {
var liquidations = await getPotentialLiquidations();
for (const comptroller of Object.keys(liquidations))
for (const liquidation of liquidations[comptroller])
try {
await sendTransactionToSafeLiquidator(liquidation[0], liquidation[1], liquidation[2]);
} catch { }
}
async function getPotentialLiquidations() {
var pools = {};
// Get potential liquidations from public pools
if (process.env.SUPPORT_ALL_PUBLIC_POOLS) {
var data = await fusePoolLens.methods.getPublicPoolUsersWithData(Web3.utils.toBN(1e18)).call({ gas: 1e18 });
var comptrollers = data["0"];
var users = data["1"];
var closeFactors = data["2"];
var liquidationIncentives = data["3"];
for (var i = 0; i < comptrollers.length; i++) {
users[i].slice().sort((a, b) => parseInt(b.totalBorrow) - parseInt(a.totalBorrow));
var liquidations = [];
for (var j = 0; j < users[i].length; j++) {
var liquidation = await getPotentialLiquidation(users[i][j], closeFactors[i], liquidationIncentives[i]);
if (liquidation !== null) liquidations.push(liquidation);
}
if (liquidations.length > 0) pools[comptrollers[i]] = liquidations;
}
}
// Get potential liquidations from supported pools (excluding the public pools that have already been checked)
if (process.env.SUPPORTED_POOL_COMPTROLLERS.length > 0) {
var potentialComptrollers = process.env.SUPPORTED_POOL_COMPTROLLERS.split(",");
var comptrollers = [];
for (const comptroller of potentialComptrollers) if (!pools[comptrollers[i]]) comptrollers.push(comptroller);
var data = await fusePoolLens.methods.getPoolUsersWithData(comptrollers, Web3.utils.toBN(1e18)).call({ gas: 1e18 });
var users = data["0"];
var closeFactors = data["1"];
var liquidationIncentives = data["2"];
for (var i = 0; i < comptrollers.length; i++) {
users[i].slice().sort((a, b) => parseInt(b.totalBorrow) - parseInt(a.totalBorrow));
var liquidations = [];
for (var j = 0; j < users[i].length; j++) {
var liquidation = await getPotentialLiquidation(users[i][j], closeFactors[i], liquidationIncentives[i]);
if (liquidation !== null) liquidations.push(liquidation);
}
if (liquidations.length > 0) pools[comptrollers[i]] = liquidations;
}
}
return pools;
}
async function getPotentialLiquidation(borrower, closeFactor, liquidationIncentive) {
var closeFactor = (new Big(closeFactor)).div(1e18);
var liquidationIncentive = (new Big(liquidationIncentive)).div(1e18);
// Get debt and collateral
borrower = { ...borrower };
borrower.debt = [];
borrower.collateral = [];
for (var asset of borrower.assets) {
asset = { ...asset };
asset.borrowBalanceEth = new Big(asset.borrowBalance).mul(asset.underlyingPrice).div(1e36);
asset.supplyBalanceEth = new Big(asset.supplyBalance).mul(asset.underlyingPrice).div(1e36);
if (parseInt(asset.borrowBalance) > 0) borrower.debt.push(asset);
if (asset.membership && parseInt(asset.supplyBalance) > 0) borrower.collateral.push(asset);
}
// Sort debt and collateral from highest to lowest ETH value
borrower.debt.sort((a, b) => b.borrowBalanceEth.gt(a.borrowBalanceEth) ? 1 : -1);
borrower.collateral.sort((a, b) => b.supplyBalanceEth.gt(a.supplyBalanceEth) ? 1 : -1);
// Check SUPPORTED_INPUT_CURRENCIES (if LIQUIDATION_STRATEGY === "")
if (process.env.LIQUIDATION_STRATEGY === "" && process.env.SUPPORTED_INPUT_CURRENCIES.split(',').indexOf(borrower.debt[0].underlyingSymbol === "ETH" ? "ETH" : borrower.debt[0].underlyingToken) >= 0) return null;
// Check SUPPORTED_OUTPUT_CURRENCIES: replace EXCHANGE_TO_TOKEN_ADDRESS with underlying collateral if underlying collateral is in SUPPORTED_OUTPUT_CURRENCIES
var exchangeToTokenAddress = process.env.EXCHANGE_TO_TOKEN_ADDRESS;
if (process.env.EXCHANGE_TO_TOKEN_ADDRESS === "" || process.env.SUPPORTED_OUTPUT_CURRENCIES.split(',').indexOf(borrower.collateral[0].underlyingSymbol === "ETH" ? "ETH" : borrower.collateral[0].underlyingToken) >= 0) exchangeToTokenAddress = borrower.collateral[0].underlyingSymbol === "ETH" ? "ETH" : borrower.collateral[0].underlyingToken;
// Get exchangeToTokenAddress price and decimals
var [outputPrice, outputDecimals] = await getCurrencyEthPriceAndDecimals(exchangeToTokenAddress);
// exchangeToTokenAddress to 0x0000000000000000000000000000000000000000 if ETH
if (exchangeToTokenAddress === "ETH") exchangeToTokenAddress = "0x0000000000000000000000000000000000000000";
// Get debt and collateral prices
const underlyingDebtPrice = (new Big(borrower.debt[0].underlyingPrice)).div((new Big(10)).pow(36 - borrower.debt[0].underlyingDecimals));
const underlyingCollateralPrice = (new Big(borrower.collateral[0].underlyingPrice)).div((new Big(10)).pow(36 - borrower.collateral[0].underlyingDecimals));
// Get liquidation amount
var liquidationAmountScaled = (new Big(borrower.debt[0].borrowBalance)).mul(closeFactor);
var liquidationAmount = liquidationAmountScaled.div((new Big(10)).pow(parseInt(borrower.debt[0].underlyingDecimals)));
var liquidationValueEth = liquidationAmount.mul(underlyingDebtPrice);
// Get seize amount
var seizeAmountEth = liquidationValueEth.mul(liquidationIncentive);
var seizeAmount = seizeAmountEth.div(underlyingCollateralPrice);
// Check if actual collateral is too low to seize seizeAmount; if so, recalculate liquidation amount
const actualCollateral = (new Big(borrower.collateral[0].supplyBalance)).div((new Big(10)).pow(parseInt(borrower.collateral[0].underlyingDecimals)));
if (seizeAmount.gt(actualCollateral)) {
seizeAmount = actualCollateral;
seizeAmountEth = seizeAmount.mul(underlyingCollateralPrice);
liquidationValueEth = seizeAmountEth.div(liquidationIncentive);
liquidationAmount = liquidationValueEth.div(underlyingDebtPrice);
liquidationAmountScaled = liquidationAmount.mul((new Big(10)).pow(parseInt(borrower.debt[0].underlyingDecimals)));
}
// Convert liquidationAmountScaled to string
liquidationAmountScaled = liquidationAmountScaled.toFixed(0);
// Depending on liquidation strategy
if (process.env.LIQUIDATION_STRATEGY === "") {
// Estimate gas usage
try {
if (borrower.debt[0].underlyingSymbol === 'ETH') {
var expectedGasAmount = await fuseSafeLiquidator.methods.safeLiquidate(borrower.account, borrower.debt[0].cToken, borrower.collateral[0].cToken, 0, exchangeToTokenAddress).estimateGas({ gas: 1e9, value: liquidationAmountScaled, from: process.env.ETHEREUM_ADMIN_ACCOUNT });
} else {
var expectedGasAmount = await fuseSafeLiquidator.methods.safeLiquidate(borrower.account, liquidationAmountScaled, borrower.debt[0].cToken, borrower.collateral[0].cToken, 0, exchangeToTokenAddress).estimateGas({ gas: 1e9, from: process.env.ETHEREUM_ADMIN_ACCOUNT });
}
} catch {
var expectedGasAmount = 600000;
}
// Get gas fee
const gasPrice = new Big(await web3.eth.getGasPrice()).div(1e18);
const expectedGasFee = gasPrice.mul(expectedGasAmount);
// Get min seize
var minEthSeizeAmountBreakEven = expectedGasFee.add(liquidationValueEth);
var minEthSeizeAmount = minEthSeizeAmountBreakEven.add(process.env.MINIMUM_PROFIT);
var minSeizeAmount = minEthSeizeAmount.div(outputPrice);
var minSeizeAmountScaled = minSeizeAmount.mul((new Big(10)).pow(outputDecimals)).toFixed(0);
// Check expected seize against minSeizeAmount
if (seizeAmount.lt(minSeizeAmount)) return null;
// Return transaction
if (borrower.debt[0].underlyingSymbol === 'ETH') {
return ["safeLiquidate", [borrower.account, borrower.debt[0].cToken, borrower.collateral[0].cToken, minSeizeAmountScaled, exchangeToTokenAddress], liquidationAmountScaled];
} else {
return ["safeLiquidate", [borrower.account, liquidationAmountScaled, borrower.debt[0].cToken, borrower.collateral[0].cToken, minSeizeAmountScaled, exchangeToTokenAddress], 0];
}
} else if (process.env.LIQUIDATION_STRATEGY === "uniswap") {
// Estimate gas usage
try {
if (borrower.debt[0].underlyingSymbol === 'ETH') {
var expectedGasAmount = await fuseSafeLiquidator.methods.safeLiquidateToEthWithFlashLoan(borrower.account, liquidationAmountScaled, borrower.debt[0].cToken, borrower.collateral[0].cToken, 0, exchangeToTokenAddress).estimateGas({ gas: 1e9, from: process.env.ETHEREUM_ADMIN_ACCOUNT });
} else {
var expectedGasAmount = await fuseSafeLiquidator.methods.safeLiquidateToTokensWithFlashLoan(borrower.account, liquidationAmountScaled, borrower.debt[0].cToken, borrower.collateral[0].cToken, 0, exchangeToTokenAddress).estimateGas({ gas: 1e9, from: process.env.ETHEREUM_ADMIN_ACCOUNT });
}
} catch {
var expectedGasAmount = 750000;
}
// Get gas fee
const gasPrice = new Big(await web3.eth.getGasPrice()).div(1e18);
const expectedGasFee = gasPrice.mul(expectedGasAmount);
// Get min profit
var minOutputEth = (new Big(process.env.MINIMUM_PROFIT_ETH)).add(expectedGasFee);
var minProfitAmountScaled = minOutputEth.div(outputPrice).mul((new Big(10)).pow(outputDecimals)).toFixed(0);
// Return transaction
if (borrower.debt[0].underlyingSymbol === 'ETH') {
return ["safeLiquidateToEthWithFlashLoan", [borrower.account, liquidationAmountScaled, borrower.debt[0].cToken, borrower.collateral[0].cToken, minProfitAmountScaled, exchangeToTokenAddress], 0];
} else {
return ["safeLiquidateToTokensWithFlashLoan", [borrower.account, liquidationAmountScaled, borrower.debt[0].cToken, borrower.collateral[0].cToken, minProfitAmountScaled, exchangeToTokenAddress], 0];
}
} else throw "Invalid liquidation strategy";
}
async function getPrice(tokenAddress) {
tokenAddress = tokenAddress.toLowerCase();
// Get ETH-based price of an ERC20 via CoinGecko
var decoded = (await axios.get('https://api.coingecko.com/api/v3/simple/token_price/ethereum', {
params: {
vs_currencies: "eth",
contract_addresses: tokenAddress
}
})).data;
if (!decoded || !decoded[tokenAddress]) throw "Failed to decode price of " + tokenAddress + " from CoinGecko";
return decoded[tokenAddress].eth;
}
var currencyDecimalsCache = {};
var currencyPriceCache = {};
async function getCurrencyEthPriceAndDecimals(tokenAddressOrEth) {
// Quick return for ETH
if (tokenAddressOrEth === "ETH") return [1, 18];
// Lowercase token address
tokenAddressOrEth = tokenAddressOrEth.toLowerCase();
// Get price (from cache if possible)
if (currencyPriceCache[tokenAddressOrEth] === undefined || currencyPriceCache[tokenAddressOrEth].lastUpdated < (epochNow - (60 * 15))) {
currencyPriceCache[tokenAddressOrEth] = {
lastUpdated: epochNow,
value: await getPrice(tokenAddressOrEth)
};
}
// Get decimals (from cache if possible)
if (currencyDecimalsCache[tokenAddressOrEth] === undefined) currencyDecimalsCache[tokenAddressOrEth] = tokenAddressOrEth === "ETH" ? 18 : parseInt(await (new web3.eth.Contract(erc20Abi, tokenAddressOrEth)).methods.decimals().call());
var epochNow = (new Date()).getTime() / 1000;
return [currencyPriceCache[tokenAddressOrEth].value, currencyDecimalsCache[tokenAddressOrEth]];
}
// Liquidate unhealthy borrows and repeat every LIQUIDATION_INTERVAL_SECONDS
async function liquidateAndRepeat() {
await liquidateUnhealthyBorrows();
setTimeout(liquidateAndRepeat, process.env.LIQUIDATION_INTERVAL_SECONDS * 1000);
}
(async function() {
if (process.env.LIQUIDATION_STRATEGY === "") for (const tokenAddress of process.env.SUPPORTED_INPUT_CURRENCIES.split(',')) if (tokenAddress !== "ETH") await approveTokensToSafeLiquidator(tokenAddress, web3.utils.toBN(2).pow(web3.utils.toBN(256)).subn(1));
liquidateAndRepeat();
})();