|
| 1 | +require('dotenv').config(); |
| 2 | +const express = require('express') |
| 3 | +const Web3 = require("web3"); |
| 4 | +const store = require('data-store')({ path: process.cwd() + '/localstore.json' }); |
| 5 | +const { arbitrageStatus, executeArbitrage } = require("./src/utils/prices") |
| 6 | +const { Wallet, providers } = require("ethers"); |
| 7 | + |
| 8 | +const HTTP
10000
S_PROVIDER_URL = process.env.HTTPS_PROVIDER |
| 9 | +const WSS_PROVIDER_URL = process.env.WSS_PROVIDER |
| 10 | +const PRIVATE_KEY = process.env.PRIVATE_KEY |
| 11 | + |
| 12 | +const webSocketProvider = new Web3.providers.WebsocketProvider(WSS_PROVIDER_URL); |
| 13 | +const webSocketWeb3 = new Web3(webSocketProvider); |
| 14 | + |
| 15 | +const jsonRpcProvider = new providers.JsonRpcProvider(HTTPS_PROVIDER_URL); |
| 16 | +const wallet = new Wallet(PRIVATE_KEY).connect(jsonRpcProvider); |
| 17 | +const app = express() |
| 18 | +const port = 3000 |
| 19 | +const ONGOING_STATUS = 'TX_ONGOING' |
| 20 | + |
| 21 | +let subscription; |
| 22 | +let status; |
| 23 | + |
| 24 | +app.get('/', async (req, res) => { |
| 25 | + console.log(process.env.FOO) |
| 26 | + res.send('Start arbitrage server by hitting url: <ip>:3000/subscribe' + |
| 27 | + '<br/>Unsubscribe by hitting url: <ip>:3000/unsubscribe') |
| 28 | +}) |
| 29 | + |
| 30 | +app.get('/subscribe', async (req, res) => { |
| 31 | + subscription = webSocketWeb3.eth.subscribe('newBlockHeaders', function (error, result) { |
| 32 | + if (!error) { |
| 33 | + performArbitrage() |
| 34 | + } |
| 35 | + }).on("connected", function (subscriptionId) { |
| 36 | + console.log(subscriptionId); |
| 37 | + }).on("error", console.error); |
| 38 | +}) |
| 39 | + |
| 40 | +app.get('/unsubscribe', async (req, res) => { |
| 41 | + // unsubscribes the subscription |
| 42 | + subscription.unsubscribe(function (error, success) { |
| 43 | + if (success) { |
| 44 | + console.log('Successfully unsubscribed!'); |
| 45 | + } |
| 46 | + }); |
| 47 | +}) |
| 48 | + |
| 49 | +const performArbitrage = async () => { |
| 50 | + if (!store.get(ONGOING_STATUS)) { |
| 51 | + store.set(ONGOING_STATUS, true) |
| 52 | + |
| 53 | + status = await arbitrageStatus(jsonRpcProvider, webSocketWeb3, wallet) |
| 54 | + if (status["status"] == 1) { |
| 55 | + await executeArbitrage(status["amountIn"], status["populatedRedemption"], status['profit'], webSocketWeb3); |
| 56 | + } |
| 57 | + |
| 58 | + store.set(ONGOING_STATUS, false) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +const init = () => { |
| 63 | + store.set(ONGOING_STATUS, false) |
| 64 | + webSocketWeb3.eth.accounts.wallet.add(PRIVATE_KEY); |
| 65 | +} |
| 66 | + |
| 67 | +app.listen(port, () => { |
| 68 | + init() |
| 69 | + console.log(`Arbitrage app listening at http://localhost:${port}`) |
| 70 | +}) |
| 71 | + |
| 72 | + |
| 73 | + |
0 commit comments