-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
259 lines (215 loc) · 7.65 KB
/
main.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
//import module
//Developed by [email protected], +1 541 903 5668
// const { Web3 } = require("web3");
const Web3 = require("web3");
const { BigNumber } = require("@0x/utils");
const abi = require("erc-20-abi");
// const qs = require('qs');
require("dotenv").config();
const tokenList = require("./tokenList");
//define constant
const ZERO_EX_ADDRESS = "0xdef1c0ded9bec7f1a1670819833240f027b25eff";
const takerAddress = "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9";
const buyToken = "WETH";
const sellToken = "USDT";
let sellAmount = "0";
let buyTokenAddress = tokenList.find(
(token) => token.symbol === buyToken
).address;
let sellTokenAddress = tokenList.find(
(token) => token.symbol === sellToken
).address;
// Configuring the connection to an Ethereum node
const network = process.env.ETHEREUM_NETWORK;
let web3;
let signer;
let sellTokenContract;
let buyTokenContract;
let sellTokenDecimal;
let buyTokenDecimal;
async function config() {
// web3 = new Web3(
// new Web3.providers.HttpProvider(
// `https://${network}.infura.io/v3/${process.env.INFURA_API_KEY}`
// )
// );
web3 = new Web3(
`https://${network}.infura.io/v3/${process.env.INFURA_API_KEY}`
);
signer = web3.eth.accounts.privateKeyToAccount(
process.env.SIGNER_PRIVATE_KEY
);
web3.eth.accounts.wallet.add(signer);
sellTokenContract = new web3.eth.Contract(abi, sellTokenAddress);
buyTokenContract = new web3.eth.Contract(abi, buyTokenAddress);
}
//Get SellToken Address
async function getSellTokenAddress(customtoken) {
sellTokenAddress = tokenList.find(
(token) => token.symbol === customtoken
).address;
}
//Get BuyToken Address
async function getBuyTokenAddress(customtoken) {
buyTokenAddress = tokenList.find(
(token) => token.symbol === customtoken
).address;
}
async function getTxQuoteFrom0xAPI() {
try {
await getSellTokenAddress(sellToken);
await getBuyTokenAddress(buyToken);
const url = `${process.env.X0_API_URL}quote?sellToken=${sellTokenAddress}&buyToken=${buyTokenAddress}&sellAmount=${sellAmount}`;
const response = await fetch(url, {
headers: {
"0x-api-key": process.env.X0_API_KEY,
},
});
if (!response.ok) {
console.log(await response.json());
throw new Error("Network response was not ok");
}
const data = await response.json();
return data;
} catch (error) {
console.error("There was a problem with the fetch operation:", error);
throw error;
}
}
async function sendSignedTransaction(signedTx) {
return new Promise((resolve, reject) => {
web3.eth
.sendSignedTransaction(signedTx.rawTransaction)
.on("transactionHash", (txhash) => {
console.log(`https://arbiscan.io/tx/${txhash}`);
// Timestamp
console.log(`Timestamp: ${new Date().toLocaleString()}`);
})
.on("receipt", (receipt) => {
console.log(`Total Gas Used: ${receipt.gasUsed}`);
resolve(receipt);
})
.on("error", (error) => {
reject(error);
});
});
}
async function main() {
config();
const balance = new BigNumber(
await sellTokenContract.methods.balanceOf(signer.address).call()
).toFixed();
sellTokenDecimal = new BigNumber(
await sellTokenContract.methods.decimals().call()
);
buyTokenDecimal = new BigNumber(
await buyTokenContract.methods.decimals().call()
);
if (balance < 1000000) {
console.log("Balance of token is zero or too small.");
return;
}
sellAmount = balance;
const currentAllowance = new BigNumber(
await sellTokenContract.methods
.allowance(signer.address, ZERO_EX_ADDRESS)
.call()
);
if (currentAllowance.isLessThan(balance)) {
try {
const estimatedGas = await sellTokenContract.methods
.approve(ZERO_EX_ADDRESS, sellAmount)
.estimateGas({ from: signer.address });
await sellTokenContract.methods
.approve(ZERO_EX_ADDRESS, sellAmount)
.send({ from: signer.address, gas: estimatedGas + 1000 }); // Adding a buffer of 10,000 gas units
} catch (error) {
console.error("Error during token approval:", error);
}
}
const txQuote = await getTxQuoteFrom0xAPI();
const tx = {
from: signer.address,
to: txQuote.to,
gasPrice: txQuote.gasPrice,
data: txQuote.data,
gas: Math.floor(Number(txQuote.gas) * 1.1).toString(),
};
// Inside your main function
const signedTx = await web3.eth.accounts.signTransaction(
tx,
signer.privateKey
);
if (signedTx) {
const receipt = await sendSignedTransaction(signedTx);
// Calculate the price of the selling token
var buyTokenPrice; // Price of buyToken in terms of sellToken
var sellTokenPrice; // Invert to get price of sellToken in terms of buyToken
if (buyToken == "USDT") {
buyTokenPrice = "1";
const selltokenurl = `${process.env.X0_API_URL}quote?sellToken=${sellTokenAddress}&buyToken=${buyTokenAddress}&sellAmount=${sellAmount}`;
const response1 = await fetch(selltokenurl, {
headers: {
"0x-api-key": process.env.X0_API_KEY,
},
});
const selltokendata = await response1.json();
sellTokenPrice = selltokendata.price;
} else if (sellToken == "USDT") {
sellTokenPrice = "1";
const buytokenurl = `${process.env.X0_API_URL}quote?sellToken=${sellTokenAddress}&buyToken=${buyTokenAddress}&sellAmount=${sellAmount}`;
const response = await fetch(buytokenurl, {
headers: {
"0x-api-key": process.env.X0_API_KEY,
},
});
const buytokendata = await response.json();
buyTokenPrice = 1 / Number(buytokendata.price);
} else {
const buytokenurl = `${process.env.X0_API_URL}quote?sellToken=${sellTokenAddress}&buyToken=${takerAddress}&sellAmount=${sellAmount}`;
const response = await fetch(buytokenurl, {
headers: {
"0x-api-key": process.env.X0_API_KEY,
},
});
const buytokendata = await response.json();
sellTokenPrice = buytokendata.price;
const selltokenurl = `${process.env.X0_API_URL}quote?sellToken=${buyTokenAddress}&buyToken=${takerAddress}&sellAmount=${sellAmount}`;
const response1 = await fetch(selltokenurl, {
headers: {
"0x-api-key": process.env.X0_API_KEY,
},
});
const selltokendata = await response1.json();
buyTokenPrice = selltokendata.price;
if(buyTokenPrice == undefined){
buyTokenPrice = sellTokenPrice/txQuote.price;
}
}
console.log(`Price of ${sellToken} (Selling Token): ${sellTokenPrice}`);
const sellTokenAmount =
Number(txQuote.sellAmount) /
Number(Math.pow(10, Number(sellTokenDecimal))).toFixed(10);
console.log(`Amount of ${sellToken}: ${sellTokenAmount}`);
console.log(`Price of ${buyToken} (Purchasing Token): ${buyTokenPrice}`);
const buyTokenAmount =
Number(txQuote.buyAmount) /
Number(Math.pow(10, Number(buyTokenDecimal))).toFixed(10);
console.log(`Amount of ${buyToken}: ${buyTokenAmount}`);
}
return;
}
async function retryMain() {
let success = false;
while (!success) {
try {
await main();
success = true; // Set success flag to true if main function executes without error
} catch (error) {
console.error("Error executing main function:", error);
console.log("Retrying in 10 seconds...");
await new Promise((resolve) => setTimeout(resolve, 10000)); // Wait for 5 seconds before retrying
}
}
}
retryMain();