-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlashloanerOps.js
292 lines (272 loc) · 9.94 KB
/
FlashloanerOps.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
/**
* used to interact with the Flashloaner smart contract
*/
const {
BlockchainConfig,
getItemFromTokenList,
} = require("./BlockchainConfig.js");
const Util = require("./Util.js");
const assert = require("assert");
const Flashloan = require("./build/contracts/Flashloaner");
const ERC20ops = require("./ERC20ops.js");
const Web3 = require("web3");
class FlashloanerOps {
constructor(_GLOBAL) {
this.loggerBalanceEventABI = [
{ type: "uint256", name: "oldBalance" },
{ type: "uint256", name: "newBalance" },
];
this.GLOBAL = _GLOBAL;
let flashloanerAddress;
//it uses the FLASHLOANER address set in .env file, if it is set, else uses the local deployed contract
if (this.GLOBAL.flashloanerDeployedAddressMainnet) {
flashloanerAddress = this.GLOBAL.flashloanerDeployedAddressMainnet;
} else {
flashloanerAddress = Flashloan.networks[this.GLOBAL.networkId].address;
}
this.contractInstance = new this.GLOBAL.web3Instance.eth.Contract(
Flashloan.abi,
flashloanerAddress,
{ from: this.GLOBAL.ownerAddress }
);
}
/**
* Withdraw all balance of informed _token
* @param {*} _amount
* @returns transaction (Promise)
*/
async withdrawToken(_token) {
Util.assertValidInputs([_token], "withdrawToken");
//handle response tx
let txPromise = new Promise(async (resolve, reject) => {
try {
//encode withdraw method
let dataWithdraw = this.contractInstance.methods
.withdraw(_token.address)
.encodeABI();
//sets maxFeePerGas and maxPriorityFeePerGas, lesser values were generating 'transaction underpriced' error on Polygon mainnet
let maxPriorityFeePerGas =
await this.GLOBAL.web3Instance.eth.getGasPrice();
let maxFeePerGas = maxPriorityFeePerGas * 3;
//declare raw tx to withdraw
let rawWithdrawTx = {
from: this.GLOBAL.ownerAddress,
to: this.contractInstance._address,
maxFeePerGas: String(maxFeePerGas),
maxPriorityFeePerGas: String(maxPriorityFeePerGas),
gasLimit:
BlockchainConfig.blockchain[this.GLOBAL.blockchain].GAS_LIMIT_LOW,
data: dataWithdraw,
};
//sign tx
let signedWithdrawTx =
await this.GLOBAL.web3Instance.eth.accounts.signTransaction(
rawWithdrawTx,
this.GLOBAL.ownerPK
);
//send signed transaction
let withdrawTx = this.GLOBAL.web3Instance.eth.sendSignedTransaction(
signedWithdrawTx.raw || signedWithdrawTx.rawTransaction
);
withdrawTx.on("receipt", (receipt) => {
console.log(`### ${_token.symbol} withdrawn successfully: ###`);
console.log(`### tx: ${receipt.transactionHash} ###`);
resolve(receipt);
});
withdrawTx.on("error", (err) => {
console.log("### withdrawn tx error: ###");
reject(err);
});
} catch (error) {
reject(error);
}
});
return txPromise;
}
/**
* query chain id contained in the storage variable chainId of the contract
* @param {*} _amount
* @returns chainId (Number)
*/
async getChainId() {
try {
let chainId = await this.contractInstance.methods.getChainId().call();
return chainId;
} catch (error) {
throw new Error(error);
}
}
/**
* query owner of the contract
* @param {*} _amount
* @returns address owner (String)
*/
async getOwner() {
try {
let owner = await this.contractInstance.methods.owner().call();
return owner;
} catch (error) {
throw new Error(error);
}
}
/**
* Executes flashloan
* @param {*} _parsedJson input flashloan data
* @returns transaction (Promise)
*/
executeFlashloan(_parsedJson) {
Util.assertValidInputs([_parsedJson], "executeFlashloan");
//handle response tx
let txPromise = new Promise(async (resolve, reject) => {
try {
console.log(
`### Executing flashloan on ${
_parsedJson.flashloanInputData.flashLoanSource
} | $${Number(_parsedJson.initialAmountInUSD).toFixed(
2
)} => ${JSON.stringify(_parsedJson.route)} ###`
);
let amountToBorrowOfFirstToken = Util.amountToBlockchain(
_parsedJson.initialTokenAmount,
_parsedJson.initialTokenDecimals
);
//include amount on input data
_parsedJson.flashloanInputData.loanAmount = amountToBorrowOfFirstToken;
//encode method
let encodedMethod;
if (_parsedJson.flashloanInputData.flashLoanSource == "Dodo") {
encodedMethod = this.contractInstance.methods
.flashloanDodo(_parsedJson.flashloanInputData)
.encodeABI();
} else if (_parsedJson.flashloanInputData.flashLoanSource == "Aave") {
encodedMethod = this.contractInstance.methods
.flashloanAave(_parsedJson.flashloanInputData)
.encodeABI();
} else {
reject("Invalid flashloan souce on flashloanInputData!");
}
//sets maxFeePerGas and maxPriorityFeePerGas, 3 times more fees to execute faster
let maxPriorityFeePerGas =
(await this.GLOBAL.web3Instance.eth.getGasPrice()) * 3;
let maxFeePerGas = maxPriorityFeePerGas * 3;
//declare raw tx
let rawFlashloanTx = {
from: this.GLOBAL.ownerAddress,
to: this.contractInstance._address,
maxFeePerGas: String(maxFeePerGas),
maxPriorityFeePerGas: String(maxPriorityFeePerGas),
gasLimit:
BlockchainConfig.blockchain[this.GLOBAL.blockchain].GAS_LIMIT_HIGH,
data: encodedMethod,
};
//sign tx
let signedFlashloanTx =
await this.GLOBAL.web3Instance.eth.accounts.signTransaction(
rawFlashloanTx,
this.GLOBAL.ownerPK
);
//send signed transaction
this.GLOBAL.web3Instance.eth
.sendSignedTransaction(
signedFlashloanTx.raw || signedFlashloanTx.rawTransaction
)
.on("transactionHash", function (hash) {
console.log(`### tx: ${hash} ###`);
})
.on("receipt", function (receipt) {
console.log(`### !!! Flashloan executed !!! ###`);
})
.on("confirmation", function (confirmationNumber, receipt) {
console.log(`### Confirmation number: ${confirmationNumber} ###`);
receipt.flashloanProtocol =
_parsedJson.flashloanInputData.flashLoanSource;
receipt.status = "confirmed";
receipt.details = "Ok";
resolve(receipt);
})
.on("error", function (error) {
console.log(`### No profit found: ###`);
if (error.receipt) {
error.receipt.flashloanProtocol =
_parsedJson.flashloanInputData.flashLoanSource;
error.receipt.status = "failed";
let details = "";
if (error.reason) {
details += error.reason + " \n";
}
if (error.message) {
details += error.message;
}
error.receipt.details = details;
reject(error.receipt);
} else {
reject({ status: "failed" });
}
});
} catch (error) {
reject(error);
}
});
return txPromise;
}
/**
* Verifies input flashloan data
* @param {*} _parsedJson
* @returns Object
*/
isInputFileOk(_parsedJson) {
let isOk = true;
let message = "Verified";
if (!_parsedJson.initialTokenAmount) {
message = "field initialTokenAmount not found in input file";
return { isOk: false, message: message };
}
if (!_parsedJson.initialTokenDecimals) {
message = "field initialTokenDecimals not found in input file";
return { isOk: false, message: message };
}
if (!_parsedJson.flashloanInputData) {
message = "field flashloanInputData not found in input file";
return { isOk: false, message: message };
}
if (!_parsedJson.flashloanInputData.flashLoanSource) {
message = "field flashLoanSource not found in input file";
return { isOk: false, message: message };
}
if (!_parsedJson.flashloanInputData.flashLoanPool) {
message = "field flashLoanPool not found in input file";
return { isOk: false, message: message };
}
if (!_parsedJson.flashloanInputData.swaps) {
message =
"field _parsedJson.flashloanInputData.swaps not found in input file";
return { isOk: false, message: message };
}
if (_parsedJson.flashloanInputData.swaps.length == 0) {
message =
"at least one swap must be in the flashloanInputData.swaps list in input file";
return { isOk: false, message: message };
}
//vefify fees addressesss
for (let swap of _parsedJson.flashloanInputData.swaps) {
if (!this.GLOBAL.web3Instance.utils.isAddress(swap.routerAddress)) {
message = "invalid address found: routerAddress";
return { isOk: false, message: message };
}
if (!this.GLOBAL.web3Instance.utils.isAddress(swap.tokenInAddress)) {
message = "invalid address found: tokenInAddress";
return { isOk: false, message: message };
}
if (!this.GLOBAL.web3Instance.utils.isAddress(swap.tokenOutAddress)) {
message = "invalid address found: tokenOutAddress";
return { isOk: false, message: message };
}
if (!swap.fee) {
message = "invalid fee found";
return { isOk: false, message: message };
}
}
return { isOk: true, message: message };
}
}
module.exports = FlashloanerOps;