This repository has been archived by the owner on Oct 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
/
liquidate.ts
152 lines (134 loc) · 5.43 KB
/
liquidate.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
/* eslint-disable no-continue */
/* eslint-disable no-restricted-syntax */
import {
Account,
Connection,
Keypair,
PublicKey,
} from '@solana/web3.js';
import dotenv from 'dotenv';
import { ObligationParser } from 'models/layouts/obligation';
import {
getObligations, getReserves, getWalletBalances, getWalletDistTarget, getWalletTokenData, wait,
} from 'libs/utils';
import { getTokensOracleData } from 'libs/pyth';
import { calculateRefreshedObligation } from 'libs/refreshObligation';
import { readSecret } from 'libs/secret';
import { liquidateAndRedeem } from 'libs/actions/liquidateAndRedeem';
import { rebalanceWallet } from 'libs/rebalanceWallet';
import { Jupiter } from '@jup-ag/core';
import { unwrapTokens } from 'libs/unwrap/unwrapToken';
import { getMarkets } from './config';
dotenv.config();
async function runLiquidator() {
const rpcEndpoint = process.env.RPC_ENDPOINT;
if (!rpcEndpoint) {
throw new Error('Pls provide an private RPC endpoint in docker-compose.yaml');
}
const markets = await getMarkets();
const connection = new Connection(rpcEndpoint, 'confirmed');
// liquidator's keypair.
const payer = new Account(JSON.parse(readSecret('keypair')));
const jupiter = await Jupiter.load({
connection,
cluster: 'mainnet-beta',
user: Keypair.fromSecretKey(payer.secretKey),
wrapUnwrapSOL: false,
});
const target = getWalletDistTarget();
console.log(`
app: ${process.env.APP}
rpc: ${rpcEndpoint}
wallet: ${payer.publicKey.toBase58()}
auto-rebalancing: ${target.length > 0 ? 'ON' : 'OFF'}
rebalancingDistribution: ${process.env.TARGETS}
Running against ${markets.length} pools
`);
for (let epoch = 0; ; epoch += 1) {
for (const market of markets) {
const tokensOracle = await getTokensOracleData(connection, market);
const allObligations = await getObligations(connection, market.address);
const allReserves = await getReserves(connection, market.address);
for (let obligation of allObligations) {
try {
while (obligation) {
const {
borrowedValue,
unhealthyBorrowValue,
deposits,
borrows,
} = calculateRefreshedObligation(
obligation.info,
allReserves,
tokensOracle,
);
// Do nothing if obligation is healthy
if (borrowedValue.isLessThanOrEqualTo(unhealthyBorrowValue)) {
break;
}
// select repay token that has the highest market value
let selectedBorrow;
borrows.forEach((borrow) => {
if (!selectedBorrow || borrow.marketValue.gt(selectedBorrow.marketValue)) {
selectedBorrow = borrow;
}
});
// select the withdrawal collateral token with the highest market value
let selectedDeposit;
deposits.forEach((deposit) => {
if (!selectedDeposit || deposit.marketValue.gt(selectedDeposit.marketValue)) {
selectedDeposit = deposit;
}
});
if (!selectedBorrow || !selectedDeposit) {
// skip toxic obligations caused by toxic oracle data
break;
}
console.log(`Obligation ${obligation.pubkey.toString()} is underwater
borrowedValue: ${borrowedValue.toString()}
unhealthyBorrowValue: ${unhealthyBorrowValue.toString()}
market address: ${market.address}`);
// get wallet balance for selected borrow token
const { balanceBase } = await getWalletTokenData(connection, market, payer, selectedBorrow.mintAddress, selectedBorrow.symbol);
if (balanceBase === 0) {
console.log(`insufficient ${selectedBorrow.symbol} to liquidate obligation ${obligation.pubkey.toString()} in market: ${market.address}`);
break;
} else if (balanceBase < 0) {
console.log(`failed to get wallet balance for ${selectedBorrow.symbol} to liquidate obligation ${obligation.pubkey.toString()} in market: ${market.address}.
Potentially network error or token account does not exist in wallet`);
break;
}
// Set super high liquidation amount which acts as u64::MAX as program will only liquidate max
// 50% val of all borrowed assets.
await liquidateAndRedeem(
connection,
payer,
balanceBase,
selectedBorrow.symbol,
selectedDeposit.symbol,
market,
obligation,
);
const postLiquidationObligation = await connection.getAccountInfo(
new PublicKey(obligation.pubkey),
);
obligation = ObligationParser(obligation.pubkey, postLiquidationObligation!);
}
} catch (err) {
console.error(`error liquidating ${obligation!.pubkey.toString()}: `, err);
continue;
}
}
await unwrapTokens(connection, payer);
if (target.length > 0) {
const walletBalances = await getWalletBalances(connection, payer, tokensOracle, market);
await rebalanceWallet(connection, payer, jupiter, tokensOracle, walletBalances, target);
}
// Throttle to avoid rate limiter
if (process.env.THROTTLE) {
await wait(Number(process.env.THROTTLE));
}
}
}
}
runLiquidator();