-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
137 lines (116 loc) · 3.22 KB
/
index.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
import * as server from "http-proxy-middleware/dist/types"
import type * as client from "express"
import type * as http from "http"
import { ENDPOINT_REGISTRY, ADDRESSES, REGISTER_CALL } from "./constants/domains"
import { createProxyMiddleware } from "http-proxy-middleware"
import * as ethers from "ethers"
import express from "express"
import dotenv from "dotenv"
import zlib from "zlib"
import cors from "cors"
import fs from "fs"
const SERVER = express()
const PORT = 1232
dotenv.config()
function decodeMessage(
msg: http.IncomingMessage,
stream: Array<Buffer>,
encoding: string
) {
return new Promise((resolve) => {
msg.on('data', (chunk) => stream.push(chunk))
msg.on("end", () => {
const raw = Buffer.concat(stream)
if(encoding == "br") {
zlib.brotliDecompress(raw,
(error, buffer) => {
if(buffer) resolve(buffer.toString())
else resolve(error)
})
} else {
resolve(raw.toString())
}
})
})
}
async function selectFunctionalEndpoint(): Promise<string> {
let selectedEndpoint = ENDPOINT_REGISTRY[0]
let isEndpointWorking = false
let endpointIndex = 0
while(isEndpointWorking != true) {
selectedEndpoint = ENDPOINT_REGISTRY[endpointIndex]
isEndpointWorking = await simulateCall(selectedEndpoint)
if(!isEndpointWorking) endpointIndex++
}
return selectedEndpoint
}
async function simulateCall(rpcEndpoint: string): Promise<boolean> {
const provider = new ethers.providers.JsonRpcProvider(rpcEndpoint)
const price = await provider.getGasPrice()
let transactionCall = true
try {
await provider.call({
from: ADDRESSES.depositor,
to: ADDRESSES.pool,
data: REGISTER_CALL,
}, "latest")
} catch(e) {
transactionCall = false
} finally {
return transactionCall
}
}
function handleRequest(
proxyReq: http.ClientRequest,
req: client.Request,
res: client.Response
) {
if(req.body) {
let body = JSON.stringify(req.body)
proxyReq.setHeader("Content-type", "application/json")
proxyReq.setHeader("Content-length", Buffer.byteLength(body))
proxyReq.write(body)
}
}
async function handleResponse(
proxyRes: http.IncomingMessage,
req: client.Request,
res: client.Response
) {
const resEncoding = proxyRes.headers["content-encoding"]
const resBuffer: Array<Buffer> = []
const resBody = await decodeMessage(
proxyRes,
resBuffer,
resEncoding || "application/json"
)
console.log('RESPONSE:', resBody)
}
function handleError(
err: Error,
req: client.Request,
res: client.Response
) {
console.log('ERROR:', err)
}
const proxyConfiguration: server.Options = {
target: ENDPOINT_REGISTRY[0],
ssl: {
key: fs.readFileSync(process.env.SSL_KEY, "ascii"),
cert: fs.readFileSync(process.env.SSL_CERT, "ascii")
},
router: selectFunctionalEndpoint,
onProxyRes: handleResponse,
onProxyReq: handleRequest,
onError: handleError,
changeOrigin: true,
toProxy: true
// TODO: websocket support
// ws: true
}
SERVER.use("/", createProxyMiddleware(proxyConfiguration))
SERVER.use(express.json())
SERVER.use(express.urlencoded({ extended: true }))
SERVER.use(express.raw())
SERVER.use(cors())
SERVER.listen(PORT, () => console.log(`[server]: ${PORT}`))