@lidofinance/api-rpc-proxy 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +61 -2
- package/dist/index.cjs +636 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +152 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.mjs +602 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +59 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,636 @@
|
|
|
1
|
+
var $jf5wi$nodestream = require("node:stream");
|
|
2
|
+
var $jf5wi$nodestreampromises = require("node:stream/promises");
|
|
3
|
+
var $jf5wi$lidofinancerpc = require("@lidofinance/rpc");
|
|
4
|
+
var $jf5wi$memorycache = require("memory-cache");
|
|
5
|
+
var $jf5wi$nodenet = require("node:net");
|
|
6
|
+
var $jf5wi$lidofinanceapirpc = require("@lidofinance/api-rpc");
|
|
7
|
+
var $jf5wi$promclient = require("prom-client");
|
|
8
|
+
var $jf5wi$lidofinanceapimetrics = require("@lidofinance/api-metrics");
|
|
9
|
+
|
|
10
|
+
function $parcel$exportWildcard(dest, source) {
|
|
11
|
+
Object.keys(source).forEach(function(key) {
|
|
12
|
+
if (key === 'default' || key === '__esModule' || dest.hasOwnProperty(key)) {
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
Object.defineProperty(dest, key, {
|
|
17
|
+
enumerable: true,
|
|
18
|
+
get: function get() {
|
|
19
|
+
return source[key];
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
return dest;
|
|
25
|
+
}
|
|
26
|
+
function $parcel$export(e, n, v, s) {
|
|
27
|
+
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
$parcel$export(module.exports, "rpcFactory", () => $c36759493dc2a380$export$9bfcc39f106ad871);
|
|
31
|
+
$parcel$export(module.exports, "baseRequestValidationFactory", () => $fc26c06bc08587fb$export$564dd6c0fb12e680);
|
|
32
|
+
$parcel$export(module.exports, "ethCallValidationFactory", () => $fc26c06bc08587fb$export$b724143801441d66);
|
|
33
|
+
$parcel$export(module.exports, "ethGetLogsValidationFactory", () => $fc26c06bc08587fb$export$5d8ee2232a9cb21a);
|
|
34
|
+
$parcel$export(module.exports, "rpcMethodsValidationFactory", () => $fc26c06bc08587fb$export$bd57dbd3bc9a1cc6);
|
|
35
|
+
$parcel$export(module.exports, "shouldValidateRpcMethod", () => $fc26c06bc08587fb$export$e67f820dcb2fefda);
|
|
36
|
+
$parcel$export(module.exports, "streamMaxSizeValidationFactory", () => $fc26c06bc08587fb$export$7c5a2292697deb4b);
|
|
37
|
+
$parcel$export(module.exports, "createRateLimitHook", () => $ed77a7c0d430b773$export$d4d313c44e137fbd);
|
|
38
|
+
$parcel$export(module.exports, "FixedWindowStore", () => $1837de1d3fa59747$export$50407732e532e273);
|
|
39
|
+
$parcel$export(module.exports, "getClientIp", () => $b79779073d6c1ff6$export$a136460b3a4d9dd1);
|
|
40
|
+
$parcel$export(module.exports, "normalizeIp", () => $b79779073d6c1ff6$export$d72b6c2c9b6e498);
|
|
41
|
+
$parcel$export(module.exports, "RATE_LIMIT_ERROR_MESSAGE", () => $d664e7ff5c5c06af$export$cc8ff9baf1a1960);
|
|
42
|
+
$parcel$export(module.exports, "RATE_LIMIT_HEADERS", () => $d664e7ff5c5c06af$export$a063967512de3ebf);
|
|
43
|
+
$parcel$export(module.exports, "probeChains", () => $197799e10b2d45f5$export$b1f76e97540655f3);
|
|
44
|
+
$parcel$export(module.exports, "createRpcProxyMetrics", () => $325c7c1d154acf14$export$b3e9bcd4083b83c6);
|
|
45
|
+
$parcel$export(module.exports, "registerRpcProxyRoutes", () => $91c84f984aa4e6af$export$be56850439a72159);
|
|
46
|
+
// RPC proxy factory adapted from the @lidofinance/next-api-wrapper rpcFactory pattern
|
|
47
|
+
// (https://github.com/lidofinance/lido-frontend-template).
|
|
48
|
+
// Changes from the original:
|
|
49
|
+
// - Ported from Next.js API routes to Fastify request handlers
|
|
50
|
+
// - Added per-chain contract-address allowlist (eth_call / eth_getLogs restriction)
|
|
51
|
+
// - Integrated @lidofinance/api-rpc trackedFetchRpcFactory for prom-client metrics
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
const $de5e38af76816541$var$URL_PATTERN = /\b(?:https?|wss?):\/\/[^\s'"<>]+/gi;
|
|
56
|
+
const $de5e38af76816541$var$toHost = (url)=>{
|
|
57
|
+
try {
|
|
58
|
+
return new URL(url).hostname;
|
|
59
|
+
} catch {
|
|
60
|
+
return "<url>";
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const $de5e38af76816541$export$dac76f5d4966dbe0 = (text)=>text.replace($de5e38af76816541$var$URL_PATTERN, $de5e38af76816541$var$toHost);
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
var $50baca306c9e1fc2$exports = {};
|
|
67
|
+
|
|
68
|
+
$parcel$export($50baca306c9e1fc2$exports, "DEFAULT_API_ERROR_MESSAGE", () => $50baca306c9e1fc2$export$c982278a0ddc4dbe);
|
|
69
|
+
$parcel$export($50baca306c9e1fc2$exports, "HEALTHY_RPC_SERVICES_ARE_OVER", () => $50baca306c9e1fc2$export$56a189db5508cdcb);
|
|
70
|
+
$parcel$export($50baca306c9e1fc2$exports, "ClientError", () => $50baca306c9e1fc2$export$bb8c263ad32caa8);
|
|
71
|
+
$parcel$export($50baca306c9e1fc2$exports, "UnsupportedChainIdError", () => $50baca306c9e1fc2$export$fc97cac2ba066ec7);
|
|
72
|
+
$parcel$export($50baca306c9e1fc2$exports, "UnsupportedHTTPMethodError", () => $50baca306c9e1fc2$export$2dfa2d8949b43fdc);
|
|
73
|
+
$parcel$export($50baca306c9e1fc2$exports, "InvalidRequestError", () => $50baca306c9e1fc2$export$2adbfa76b71ba748);
|
|
74
|
+
$parcel$export($50baca306c9e1fc2$exports, "SizeTooLargeError", () => $50baca306c9e1fc2$export$e224c1080d950012);
|
|
75
|
+
const $50baca306c9e1fc2$export$c982278a0ddc4dbe = "Something went wrong. Sorry, try again later :(";
|
|
76
|
+
const $50baca306c9e1fc2$export$56a189db5508cdcb = "Healthy RPC services are over!";
|
|
77
|
+
class $50baca306c9e1fc2$export$bb8c263ad32caa8 extends Error {
|
|
78
|
+
}
|
|
79
|
+
class $50baca306c9e1fc2$export$fc97cac2ba066ec7 extends $50baca306c9e1fc2$export$bb8c263ad32caa8 {
|
|
80
|
+
constructor(message){
|
|
81
|
+
super(message || "Unsupported chainId");
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
class $50baca306c9e1fc2$export$2dfa2d8949b43fdc extends $50baca306c9e1fc2$export$bb8c263ad32caa8 {
|
|
85
|
+
constructor(message){
|
|
86
|
+
super(message || "Unsupported HTTP method");
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
class $50baca306c9e1fc2$export$2adbfa76b71ba748 extends $50baca306c9e1fc2$export$bb8c263ad32caa8 {
|
|
90
|
+
constructor(message){
|
|
91
|
+
super(message || "Invalid Request");
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
class $50baca306c9e1fc2$export$e224c1080d950012 extends $50baca306c9e1fc2$export$bb8c263ad32caa8 {
|
|
95
|
+
constructor(message){
|
|
96
|
+
super(message || "Response size too large");
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
const $d68ede9964e6b015$export$66d7aef0343e6f4b = 10000;
|
|
102
|
+
const $d68ede9964e6b015$export$6d59a6fe1a73319b = async (timeoutMs, request)=>{
|
|
103
|
+
if (!(timeoutMs > 0)) return request();
|
|
104
|
+
const controller = new AbortController();
|
|
105
|
+
const timer = setTimeout(()=>controller.abort(new Error(`no response within ${timeoutMs} ms`)), timeoutMs);
|
|
106
|
+
try {
|
|
107
|
+
return await request(controller.signal);
|
|
108
|
+
} finally{
|
|
109
|
+
clearTimeout(timer);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
// BigInt(0), not a 0n literal — this file is type-checked under the repo's shared
|
|
118
|
+
// root tsconfig (target es5) whenever a sibling package without its own tsconfig
|
|
119
|
+
// runs `tsc`, and BigInt literal syntax requires an ES2020+ target to parse.
|
|
120
|
+
const $fc26c06bc08587fb$var$zeroBN = BigInt(0);
|
|
121
|
+
const $fc26c06bc08587fb$var$HEX_BLOCK_NUMBER = /^0x[0-9a-fA-F]+$/;
|
|
122
|
+
// Tags that resolve within a few blocks of head, far below any sane maxGetLogsRange
|
|
123
|
+
const $fc26c06bc08587fb$var$NEAR_HEAD_BLOCK_TAGS = new Set([
|
|
124
|
+
"latest",
|
|
125
|
+
"safe",
|
|
126
|
+
"finalized",
|
|
127
|
+
"pending"
|
|
128
|
+
]);
|
|
129
|
+
const $fc26c06bc08587fb$export$564dd6c0fb12e680 = (defaultChain, providers, maxBatchSize)=>{
|
|
130
|
+
return (req)=>{
|
|
131
|
+
const rawChainId = Array.isArray(req.query.chainId) ? req.query.chainId[0] : req.query.chainId;
|
|
132
|
+
const chainId = Number(rawChainId || defaultChain);
|
|
133
|
+
if (providers[chainId] == null) throw new (0, $50baca306c9e1fc2$export$fc97cac2ba066ec7)();
|
|
134
|
+
const requests = Array.isArray(req.body) ? req.body : [
|
|
135
|
+
req.body
|
|
136
|
+
];
|
|
137
|
+
if (typeof maxBatchSize === "number" && requests.length > maxBatchSize) throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`Too many batched requests`);
|
|
138
|
+
return {
|
|
139
|
+
chainId: chainId,
|
|
140
|
+
requests: requests
|
|
141
|
+
};
|
|
142
|
+
};
|
|
143
|
+
};
|
|
144
|
+
const $fc26c06bc08587fb$export$bd57dbd3bc9a1cc6 = (allowedMethods)=>{
|
|
145
|
+
const methodsMap = new Set(allowedMethods ?? []);
|
|
146
|
+
return (request, context)=>{
|
|
147
|
+
const method = request.method;
|
|
148
|
+
if (typeof method !== "string") throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method isn't string`);
|
|
149
|
+
if (allowedMethods && !methodsMap.has(request.method)) {
|
|
150
|
+
context.rpcRequestBlocked.inc({
|
|
151
|
+
reason: "method not allowed"
|
|
152
|
+
});
|
|
153
|
+
throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method ${method} not allowed`);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
};
|
|
157
|
+
const $fc26c06bc08587fb$export$b724143801441d66 = (allowedAddress)=>{
|
|
158
|
+
const allowedCallAddressMap = $fc26c06bc08587fb$var$createAllowedAddressMap(allowedAddress);
|
|
159
|
+
return (request, { chainId: chainId, rpcRequestBlocked: rpcRequestBlocked })=>{
|
|
160
|
+
const { params: params } = request;
|
|
161
|
+
// Explicitly reject any request whose first param is not a well-formed tx object.
|
|
162
|
+
// Using an early-return guard keeps the "address allowed?" check unconditionally
|
|
163
|
+
// reachable and prevents future edits to the condition from accidentally creating
|
|
164
|
+
// a path that forwards an unvalidated eth_call.
|
|
165
|
+
const txObject = Array.isArray(params) ? params[0] : undefined;
|
|
166
|
+
if (txObject == null || typeof txObject !== "object" || !("to" in txObject) || typeof txObject.to !== "string") throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_call is invalid`);
|
|
167
|
+
const toAddress = txObject.to;
|
|
168
|
+
if (!allowedCallAddressMap[chainId]?.has(toAddress.toLowerCase())) {
|
|
169
|
+
rpcRequestBlocked.inc({
|
|
170
|
+
reason: "address not allowed for eth_call"
|
|
171
|
+
});
|
|
172
|
+
throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`Address not allowed for eth_call`);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
};
|
|
176
|
+
const $fc26c06bc08587fb$export$5d8ee2232a9cb21a = (allowedAddress, blockEmptyAddressGetLogs, maxBlockRange, currentBlockTTL = 60000)=>{
|
|
177
|
+
const allowedAddressMap = $fc26c06bc08587fb$var$createAllowedAddressMap(allowedAddress ?? {});
|
|
178
|
+
const maxBlockRangeBN = maxBlockRange ? BigInt(maxBlockRange) : $fc26c06bc08587fb$var$zeroBN;
|
|
179
|
+
const currentBlock = new (0, $jf5wi$memorycache.Cache)();
|
|
180
|
+
return async (request, { chainId: chainId, rpcRequestBlocked: rpcRequestBlocked, requestRPC: requestRPC })=>{
|
|
181
|
+
try {
|
|
182
|
+
const params = request.params[0];
|
|
183
|
+
const fromBlock = params.fromBlock;
|
|
184
|
+
const toBlock = params.toBlock ?? "latest";
|
|
185
|
+
if (blockEmptyAddressGetLogs || allowedAddress) {
|
|
186
|
+
const address = params.address;
|
|
187
|
+
if (blockEmptyAddressGetLogs && !address) throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_getLogs address is invalid`);
|
|
188
|
+
const addresses = Array.isArray(address) ? address : [
|
|
189
|
+
address
|
|
190
|
+
];
|
|
191
|
+
if (blockEmptyAddressGetLogs && addresses.length === 0) throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_getLogs address is invalid`);
|
|
192
|
+
if (allowedAddress && addresses.some((eventAddress)=>typeof eventAddress !== "string" || !allowedAddressMap[chainId]?.has(eventAddress.toLowerCase()))) {
|
|
193
|
+
rpcRequestBlocked.inc({
|
|
194
|
+
reason: "address not allowed for eth_getLogs"
|
|
195
|
+
});
|
|
196
|
+
throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`Address not allowed for eth_getLogs`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (maxBlockRange) {
|
|
200
|
+
if (fromBlock === "earliest") throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_getLogs fromBlock is invalid`);
|
|
201
|
+
// Anything that is neither a hex number nor a near-head tag would skip the range check
|
|
202
|
+
if (!$fc26c06bc08587fb$var$HEX_BLOCK_NUMBER.test(fromBlock) && !$fc26c06bc08587fb$var$NEAR_HEAD_BLOCK_TAGS.has(fromBlock)) throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_getLogs fromBlock is invalid`);
|
|
203
|
+
if (fromBlock.startsWith("0x")) {
|
|
204
|
+
const normalizedFromBlock = BigInt(fromBlock);
|
|
205
|
+
let normalizedToBlock;
|
|
206
|
+
if (toBlock.startsWith("0x")) normalizedToBlock = BigInt(toBlock);
|
|
207
|
+
else {
|
|
208
|
+
const cached = currentBlock.get(chainId);
|
|
209
|
+
if (cached) normalizedToBlock = cached;
|
|
210
|
+
else {
|
|
211
|
+
normalizedToBlock = await requestRPC(chainId, {
|
|
212
|
+
id: 1,
|
|
213
|
+
jsonrpc: "2.0",
|
|
214
|
+
method: "eth_blockNumber"
|
|
215
|
+
}).then((res)=>res.json()).then((res)=>BigInt(res.result));
|
|
216
|
+
currentBlock.put(chainId, normalizedToBlock, currentBlockTTL);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const range = normalizedToBlock - normalizedFromBlock;
|
|
220
|
+
if (range < $fc26c06bc08587fb$var$zeroBN || range > maxBlockRangeBN) {
|
|
221
|
+
rpcRequestBlocked.inc({
|
|
222
|
+
reason: "eth_getLogs range is invalid"
|
|
223
|
+
});
|
|
224
|
+
throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_getLogs range is invalid`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
} catch (error) {
|
|
229
|
+
if (error instanceof (0, $50baca306c9e1fc2$export$bb8c263ad32caa8)) throw error;
|
|
230
|
+
throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_getLogs is invalid`);
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
};
|
|
234
|
+
const $fc26c06bc08587fb$export$7c5a2292697deb4b = (MAX_SIZE)=>(context)=>{
|
|
235
|
+
let bytesWritten = 0;
|
|
236
|
+
return new (0, $jf5wi$nodestream.Transform)({
|
|
237
|
+
transform (chunk, _encoding, callback) {
|
|
238
|
+
bytesWritten += chunk.length;
|
|
239
|
+
if (bytesWritten > MAX_SIZE) {
|
|
240
|
+
context.rpcRequestBlocked.inc({
|
|
241
|
+
reason: "response too large"
|
|
242
|
+
});
|
|
243
|
+
return callback(new (0, $50baca306c9e1fc2$export$e224c1080d950012)(`Stream size exceeds the maximum limit of ${MAX_SIZE} bytes`));
|
|
244
|
+
}
|
|
245
|
+
return callback(null, chunk);
|
|
246
|
+
},
|
|
247
|
+
flush (callback) {
|
|
248
|
+
callback();
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
};
|
|
252
|
+
const $fc26c06bc08587fb$export$e67f820dcb2fefda = (method, allowedRPCMethods)=>!allowedRPCMethods || allowedRPCMethods.includes(method);
|
|
253
|
+
const $fc26c06bc08587fb$var$createAllowedAddressMap = (allowedAddress)=>Object.entries(allowedAddress).reduce((acc, [chainId, addresses])=>{
|
|
254
|
+
acc[chainId] = new Set(addresses.map((a)=>a.toLowerCase()));
|
|
255
|
+
return acc;
|
|
256
|
+
}, {});
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
const $c36759493dc2a380$export$9bfcc39f106ad871 = ({ providers: providers, fetchRPC: fetchRPC, defaultChain: defaultChain, validation: validation, serverLogger: serverLogger = console, metrics: metrics, upstreamTimeoutMs: upstreamTimeoutMs = (0, $d68ede9964e6b015$export$66d7aef0343e6f4b) })=>{
|
|
260
|
+
const { allowedRPCMethods: allowedRPCMethods, allowedCallAddresses: allowedCallAddresses, allowedLogsAddresses: allowedLogsAddresses, maxResponseSize: maxResponseSize = 1000000, maxBatchCount: maxBatchCount = 20, currentBlockTTLms: currentBlockTTLms = 60000, maxGetLogsRange: maxGetLogsRange = 20000, blockEmptyAddressGetLogs: blockEmptyAddressGetLogs = true } = validation;
|
|
261
|
+
// 'any' is an explicit opt-out: no method / address check
|
|
262
|
+
const rpcMethods = allowedRPCMethods === "any" ? undefined : allowedRPCMethods;
|
|
263
|
+
const callAddresses = allowedCallAddresses === "any" ? undefined : allowedCallAddresses;
|
|
264
|
+
const logsAddresses = allowedLogsAddresses === "any" ? undefined : allowedLogsAddresses;
|
|
265
|
+
const rpcRequestBlocked = metrics?.rpcRequestBlocked ?? {
|
|
266
|
+
inc: (_labels)=>{}
|
|
267
|
+
};
|
|
268
|
+
const rpcRequestMethods = metrics?.rpcRequestMethods;
|
|
269
|
+
const validateBaseRequest = (0, $fc26c06bc08587fb$export$564dd6c0fb12e680)(defaultChain, providers, maxBatchCount);
|
|
270
|
+
const validateRpcMethod = (0, $fc26c06bc08587fb$export$bd57dbd3bc9a1cc6)(rpcMethods);
|
|
271
|
+
const validateEthCall = callAddresses && (0, $fc26c06bc08587fb$export$e67f820dcb2fefda)("eth_call", rpcMethods) ? (0, $fc26c06bc08587fb$export$b724143801441d66)(callAddresses) : undefined;
|
|
272
|
+
const validateEthGetLogs = (logsAddresses || blockEmptyAddressGetLogs) && (0, $fc26c06bc08587fb$export$e67f820dcb2fefda)("eth_getLogs", rpcMethods) ? (0, $fc26c06bc08587fb$export$5d8ee2232a9cb21a)(logsAddresses, blockEmptyAddressGetLogs, maxGetLogsRange, currentBlockTTLms) : undefined;
|
|
273
|
+
const validateMaxSteamSize = (0, $fc26c06bc08587fb$export$7c5a2292697deb4b)(maxResponseSize);
|
|
274
|
+
const requestRPC = (chainId, body)=>(0, $jf5wi$lidofinancerpc.iterateUrls)(providers[chainId], (url)=>(0, $d68ede9964e6b015$export$6d59a6fe1a73319b)(upstreamTimeoutMs, (signal)=>fetchRPC(url, {
|
|
275
|
+
body: body,
|
|
276
|
+
...signal ? {
|
|
277
|
+
signal: signal
|
|
278
|
+
} : {}
|
|
279
|
+
}, {
|
|
280
|
+
chainId: chainId
|
|
281
|
+
})), (error)=>{
|
|
282
|
+
const message = (0, $de5e38af76816541$export$dac76f5d4966dbe0)(error instanceof Error ? error.message : String(error));
|
|
283
|
+
serverLogger.warn(`[rpcFactory] provider failed for chain ${chainId}: ${message}`);
|
|
284
|
+
});
|
|
285
|
+
return async (request, reply)=>{
|
|
286
|
+
const abortController = new AbortController();
|
|
287
|
+
try {
|
|
288
|
+
const { chainId: chainId, requests: requests } = validateBaseRequest(request);
|
|
289
|
+
const validationContext = {
|
|
290
|
+
chainId: chainId,
|
|
291
|
+
rpcRequestBlocked: rpcRequestBlocked,
|
|
292
|
+
requestRPC: requestRPC
|
|
293
|
+
};
|
|
294
|
+
for (const req of requests){
|
|
295
|
+
validateRpcMethod(req, validationContext);
|
|
296
|
+
rpcRequestMethods?.inc({
|
|
297
|
+
method: req.method
|
|
298
|
+
});
|
|
299
|
+
if (req.method === "eth_call" && validateEthCall) validateEthCall(req, validationContext);
|
|
300
|
+
if (req.method === "eth_getLogs" && validateEthGetLogs) await validateEthGetLogs(req, validationContext);
|
|
301
|
+
}
|
|
302
|
+
const proxiedRPC = await requestRPC(chainId, request.body);
|
|
303
|
+
// iterateUrls returns the last response when no provider answered ok;
|
|
304
|
+
// never relay a provider's error body to the client as a success.
|
|
305
|
+
if (!proxiedRPC.ok) {
|
|
306
|
+
await proxiedRPC.body?.cancel().catch(()=>undefined);
|
|
307
|
+
reply.status(502).send((0, $50baca306c9e1fc2$export$c982278a0ddc4dbe));
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
// Reject a declared oversized body before streaming starts — once bytes are on the
|
|
311
|
+
// wire the status can no longer change and the stream is only cut short.
|
|
312
|
+
const contentLength = Number(proxiedRPC.headers.get("content-length"));
|
|
313
|
+
if (contentLength > maxResponseSize) {
|
|
314
|
+
await proxiedRPC.body?.cancel().catch(()=>undefined);
|
|
315
|
+
rpcRequestBlocked.inc({
|
|
316
|
+
reason: "response too large"
|
|
317
|
+
});
|
|
318
|
+
throw new (0, $50baca306c9e1fc2$export$e224c1080d950012)(`Stream size exceeds the maximum limit of ${maxResponseSize} bytes`);
|
|
319
|
+
}
|
|
320
|
+
reply.header("content-type", proxiedRPC.headers.get("content-type") ?? "application/json");
|
|
321
|
+
if (!proxiedRPC.body) throw new Error("There are problems with RPC provider");
|
|
322
|
+
await (0, $jf5wi$nodestreampromises.pipeline)((0, $jf5wi$nodestream.Readable).fromWeb(proxiedRPC.body), validateMaxSteamSize(validationContext), reply.raw, {
|
|
323
|
+
signal: abortController.signal
|
|
324
|
+
});
|
|
325
|
+
} catch (error) {
|
|
326
|
+
if (error instanceof (0, $50baca306c9e1fc2$export$bb8c263ad32caa8)) {
|
|
327
|
+
if (!reply.raw.headersSent) reply.status(error instanceof (0, $50baca306c9e1fc2$export$e224c1080d950012) ? 413 : 400).send(error.message ?? (0, $50baca306c9e1fc2$export$c982278a0ddc4dbe));
|
|
328
|
+
} else if (error instanceof Error) {
|
|
329
|
+
serverLogger.error("[rpcFactory] " + (0, $de5e38af76816541$export$dac76f5d4966dbe0)(error.message ?? (0, $50baca306c9e1fc2$export$c982278a0ddc4dbe)));
|
|
330
|
+
if (!reply.sent) reply.status(500).send((0, $50baca306c9e1fc2$export$c982278a0ddc4dbe));
|
|
331
|
+
} else reply.status(500).send((0, $50baca306c9e1fc2$export$56a189db5508cdcb));
|
|
332
|
+
} finally{
|
|
333
|
+
abortController.abort();
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
var $83621533ef5f6afb$exports = {};
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
const $d664e7ff5c5c06af$export$a063967512de3ebf = {
|
|
345
|
+
limit: "X-RateLimit-Limit",
|
|
346
|
+
remaining: "X-RateLimit-Remaining",
|
|
347
|
+
reset: "X-RateLimit-Reset"
|
|
348
|
+
};
|
|
349
|
+
const $d664e7ff5c5c06af$export$cc8ff9baf1a1960 = "Rate limit exceeded";
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
class $1837de1d3fa59747$export$50407732e532e273 {
|
|
353
|
+
set(key, value, durationSec) {
|
|
354
|
+
clearTimeout(this.store.get(key)?.timeoutId);
|
|
355
|
+
const timeoutId = setTimeout(()=>this.store.delete(key), durationSec * 1000);
|
|
356
|
+
// This is a cache-eviction timer, not pending work — it must not keep the
|
|
357
|
+
// process alive on its own (matters for a long-running server, unlike the
|
|
358
|
+
// serverless functions the ported design originally ran in).
|
|
359
|
+
timeoutId.unref();
|
|
360
|
+
this.store.set(key, {
|
|
361
|
+
value: value,
|
|
362
|
+
timeoutId: timeoutId
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
get(key) {
|
|
366
|
+
return this.store.get(key)?.value;
|
|
367
|
+
}
|
|
368
|
+
increment(key, durationSec) {
|
|
369
|
+
const next = (this.get(key) ?? 0) + 1;
|
|
370
|
+
this.set(key, next, durationSec);
|
|
371
|
+
return next;
|
|
372
|
+
}
|
|
373
|
+
constructor(){
|
|
374
|
+
this.store = new Map();
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
const $b79779073d6c1ff6$export$d72b6c2c9b6e498 = (ip)=>ip.trim().replace(/^::ffff:/i, "");
|
|
381
|
+
const $b79779073d6c1ff6$var$firstValidIp = (value)=>{
|
|
382
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
383
|
+
if (!raw) return undefined;
|
|
384
|
+
const candidate = $b79779073d6c1ff6$export$d72b6c2c9b6e498(raw.split(",")[0] ?? "");
|
|
385
|
+
return candidate && (0, $jf5wi$nodenet.isIP)(candidate) ? candidate : undefined;
|
|
386
|
+
};
|
|
387
|
+
const $b79779073d6c1ff6$export$a136460b3a4d9dd1 = (req, customIpHeader)=>{
|
|
388
|
+
const customIp = customIpHeader ? $b79779073d6c1ff6$var$firstValidIp(req.headers[customIpHeader.toLowerCase()]) : undefined;
|
|
389
|
+
return customIp ?? $b79779073d6c1ff6$export$d72b6c2c9b6e498(req.ip || "0.0.0.0");
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
const $ed77a7c0d430b773$export$d4d313c44e137fbd = ({ max: max, windowSec: windowSec, customIpHeader: customIpHeader, onBlocked: onBlocked })=>{
|
|
394
|
+
const store = new (0, $1837de1d3fa59747$export$50407732e532e273)();
|
|
395
|
+
return async (req, reply)=>{
|
|
396
|
+
const ip = (0, $b79779073d6c1ff6$export$a136460b3a4d9dd1)(req, customIpHeader);
|
|
397
|
+
const now = Date.now() / 1000;
|
|
398
|
+
const window = Math.floor(now / windowSec);
|
|
399
|
+
const key = `${ip}:${window}`;
|
|
400
|
+
const count = store.increment(key, windowSec);
|
|
401
|
+
const remaining = max - count;
|
|
402
|
+
const reset = (window + 1) * windowSec;
|
|
403
|
+
reply.header((0, $d664e7ff5c5c06af$export$a063967512de3ebf).limit, String(max));
|
|
404
|
+
reply.header((0, $d664e7ff5c5c06af$export$a063967512de3ebf).remaining, String(Math.max(remaining, 0)));
|
|
405
|
+
reply.header((0, $d664e7ff5c5c06af$export$a063967512de3ebf).reset, String(reset));
|
|
406
|
+
if (remaining < 0) {
|
|
407
|
+
const retryAfter = Math.max(Math.ceil(reset - now), 0);
|
|
408
|
+
reply.header("Retry-After", String(retryAfter));
|
|
409
|
+
onBlocked?.(ip);
|
|
410
|
+
reply.status(429).send(`${(0, $d664e7ff5c5c06af$export$cc8ff9baf1a1960)} for ip:${ip}`);
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
const $197799e10b2d45f5$var$DEFAULT_HEALTH_TIMEOUT_MS = 5000;
|
|
421
|
+
const $197799e10b2d45f5$export$b1f76e97540655f3 = async (providers, { fetchRPC: fetchRPC, timeoutMs: timeoutMs = $197799e10b2d45f5$var$DEFAULT_HEALTH_TIMEOUT_MS, onResult: onResult, logger: logger = console })=>{
|
|
422
|
+
const results = await Promise.all(Object.entries(providers).map(async ([chainId, urls])=>{
|
|
423
|
+
const urlResults = await Promise.all(urls.map(async (url)=>{
|
|
424
|
+
try {
|
|
425
|
+
const response = await fetchRPC(url, {
|
|
426
|
+
body: {
|
|
427
|
+
id: 1,
|
|
428
|
+
jsonrpc: "2.0",
|
|
429
|
+
method: "eth_blockNumber",
|
|
430
|
+
params: []
|
|
431
|
+
},
|
|
432
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
433
|
+
}, {
|
|
434
|
+
chainId: chainId
|
|
435
|
+
});
|
|
436
|
+
const { result: result } = await response.json();
|
|
437
|
+
return response.ok && result != null;
|
|
438
|
+
} catch (error) {
|
|
439
|
+
const reason = (0, $de5e38af76816541$export$dac76f5d4966dbe0)(error instanceof Error ? error.message : String(error));
|
|
440
|
+
logger.warn(`[health] probe failed for chain ${chainId} provider ${(0, $de5e38af76816541$export$dac76f5d4966dbe0)(url)}: ${reason}`);
|
|
441
|
+
return false;
|
|
442
|
+
}
|
|
443
|
+
}));
|
|
444
|
+
const ok = urlResults.some(Boolean);
|
|
445
|
+
return {
|
|
446
|
+
chainId: chainId,
|
|
447
|
+
ok: ok
|
|
448
|
+
};
|
|
449
|
+
}));
|
|
450
|
+
for (const result of results)onResult?.(result);
|
|
451
|
+
return results;
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
const $325c7c1d154acf14$export$b3e9bcd4083b83c6 = ({ prefix: prefix, registry: registry = new (0, $jf5wi$promclient.Registry)(), collectDefault: collectDefault = true })=>{
|
|
458
|
+
const rpcRequestBlocked = new (0, $jf5wi$promclient.Counter)({
|
|
459
|
+
name: `${prefix}rpc_request_blocked_total`,
|
|
460
|
+
help: "Number of blocked RPC requests by reason",
|
|
461
|
+
labelNames: [
|
|
462
|
+
"reason"
|
|
463
|
+
],
|
|
464
|
+
registers: [
|
|
465
|
+
registry
|
|
466
|
+
]
|
|
467
|
+
});
|
|
468
|
+
// Client-requested RPC methods, counted at validation time — before a request is
|
|
469
|
+
// blocked or forwarded. Distinct from fetchRPC's own request-methods counter (from
|
|
470
|
+
// @lidofinance/api-rpc), which only counts methods that actually reached a provider.
|
|
471
|
+
const rpcRequestMethods = new (0, $jf5wi$promclient.Counter)({
|
|
472
|
+
name: `${prefix}rpc_request_methods`,
|
|
473
|
+
help: "RPC methods requested by clients, by method",
|
|
474
|
+
labelNames: [
|
|
475
|
+
"method"
|
|
476
|
+
],
|
|
477
|
+
registers: [
|
|
478
|
+
registry
|
|
479
|
+
]
|
|
480
|
+
});
|
|
481
|
+
const rateLimitBlockedCount = new (0, $jf5wi$promclient.Counter)({
|
|
482
|
+
name: `${prefix}rate_limit_blocked_total`,
|
|
483
|
+
help: "Number of requests rejected by the in-process per-IP rate limiter, by route",
|
|
484
|
+
labelNames: [
|
|
485
|
+
"route"
|
|
486
|
+
],
|
|
487
|
+
registers: [
|
|
488
|
+
registry
|
|
489
|
+
]
|
|
490
|
+
});
|
|
491
|
+
const apiResponse = new (0, $jf5wi$promclient.Histogram)({
|
|
492
|
+
name: `${prefix}api_response_seconds`,
|
|
493
|
+
help: "API response time",
|
|
494
|
+
buckets: [
|
|
495
|
+
0.1,
|
|
496
|
+
0.2,
|
|
497
|
+
0.3,
|
|
498
|
+
0.6,
|
|
499
|
+
1,
|
|
500
|
+
1.5,
|
|
501
|
+
2,
|
|
502
|
+
5
|
|
503
|
+
],
|
|
504
|
+
labelNames: [
|
|
505
|
+
"method",
|
|
506
|
+
"route",
|
|
507
|
+
"status"
|
|
508
|
+
],
|
|
509
|
+
registers: [
|
|
510
|
+
registry
|
|
511
|
+
]
|
|
512
|
+
});
|
|
513
|
+
const rpcChainReachable = new (0, $jf5wi$promclient.Gauge)({
|
|
514
|
+
name: `${prefix}rpc_chain_reachable`,
|
|
515
|
+
help: "1 if the RPC endpoint for the chain is reachable, 0 otherwise",
|
|
516
|
+
labelNames: [
|
|
517
|
+
"chainId"
|
|
518
|
+
],
|
|
519
|
+
registers: [
|
|
520
|
+
registry
|
|
521
|
+
]
|
|
522
|
+
});
|
|
523
|
+
// Registers its own request/response/methods/result counters into `registry`.
|
|
524
|
+
const fetchRPC = (0, $jf5wi$lidofinanceapirpc.trackedFetchRpcFactory)({
|
|
525
|
+
prefix: prefix,
|
|
526
|
+
registry: registry
|
|
527
|
+
});
|
|
528
|
+
if (collectDefault) (0, $jf5wi$promclient.collectDefaultMetrics)({
|
|
529
|
+
register: registry,
|
|
530
|
+
prefix: prefix
|
|
531
|
+
});
|
|
532
|
+
return {
|
|
533
|
+
registry: registry,
|
|
534
|
+
fetchRPC: fetchRPC,
|
|
535
|
+
rpcRequestBlocked: rpcRequestBlocked,
|
|
536
|
+
rpcRequestMethods: rpcRequestMethods,
|
|
537
|
+
rateLimitBlockedCount: rateLimitBlockedCount,
|
|
538
|
+
apiResponse: apiResponse,
|
|
539
|
+
rpcChainReachable: rpcChainReachable
|
|
540
|
+
};
|
|
541
|
+
};
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
const $91c84f984aa4e6af$var$DEFAULT_HEALTH_CACHE_MS = 5000;
|
|
549
|
+
const $91c84f984aa4e6af$export$be56850439a72159 = (app, options)=>{
|
|
550
|
+
const { providers: providers, defaultChain: defaultChain, fetchRPC: fetchRPC, metrics: metrics, validation: validation, rateLimit: rateLimit, healthTimeoutMs: healthTimeoutMs, healthCacheMs: healthCacheMs = $91c84f984aa4e6af$var$DEFAULT_HEALTH_CACHE_MS, upstreamTimeoutMs: upstreamTimeoutMs, serverLogger: serverLogger } = options;
|
|
551
|
+
// Route label uses the matched route template (e.g. "/rpc"), not request.url —
|
|
552
|
+
// avoid request.url here because unmatched URLs (404s) can blow up label
|
|
553
|
+
// cardinality, hence the 'unknown' fallback instead. status is the aggregated
|
|
554
|
+
// 2xx/4xx/… class, not the exact code.
|
|
555
|
+
app.addHook("onResponse", (request, reply, done)=>{
|
|
556
|
+
metrics.apiResponse.observe({
|
|
557
|
+
method: request.method,
|
|
558
|
+
route: request.routeOptions.url ?? "unknown",
|
|
559
|
+
status: (0, $jf5wi$lidofinanceapimetrics.getStatusLabel)(reply.statusCode)
|
|
560
|
+
}, reply.elapsedTime / 1000);
|
|
561
|
+
done();
|
|
562
|
+
});
|
|
563
|
+
// A probe in flight is shared by every request that arrives meanwhile, and its result is
|
|
564
|
+
// reused for healthCacheMs after it settles, so /health cannot be used to multiply upstream calls.
|
|
565
|
+
let cachedProbe;
|
|
566
|
+
const probe = ()=>{
|
|
567
|
+
if (cachedProbe && Date.now() < cachedProbe.expiresAt) return cachedProbe.checks;
|
|
568
|
+
const checks = (0, $197799e10b2d45f5$export$b1f76e97540655f3)(providers, {
|
|
569
|
+
fetchRPC: fetchRPC,
|
|
570
|
+
timeoutMs: healthTimeoutMs,
|
|
571
|
+
onResult: ({ chainId: chainId, ok: ok })=>metrics.rpcChainReachable.set({
|
|
572
|
+
chainId: chainId
|
|
573
|
+
}, ok ? 1 : 0),
|
|
574
|
+
logger: serverLogger
|
|
575
|
+
});
|
|
576
|
+
if (healthCacheMs > 0) {
|
|
577
|
+
const entry = {
|
|
578
|
+
checks: checks,
|
|
579
|
+
expiresAt: Infinity
|
|
580
|
+
};
|
|
581
|
+
cachedProbe = entry;
|
|
582
|
+
checks.then(()=>entry.expiresAt = Date.now() + healthCacheMs, ()=>entry.expiresAt = 0);
|
|
583
|
+
}
|
|
584
|
+
return checks;
|
|
585
|
+
};
|
|
586
|
+
app.get("/health", async (_req, reply)=>{
|
|
587
|
+
const checks = await probe();
|
|
588
|
+
const healthy = checks.every((c)=>c.ok);
|
|
589
|
+
// Structured JSON (status code still carries the pass/fail signal for simple
|
|
590
|
+
// probes like a Dockerfile's `wget --spider`) so infra/dashboards hitting this
|
|
591
|
+
// directly can see which chain is unreachable, not just an aggregate.
|
|
592
|
+
return reply.status(healthy ? 200 : 503).send({
|
|
593
|
+
status: healthy ? "ok" : "degraded",
|
|
594
|
+
chains: Object.fromEntries(checks.map((c)=>[
|
|
595
|
+
c.chainId,
|
|
596
|
+
c.ok ? "ok" : "unreachable"
|
|
597
|
+
]))
|
|
598
|
+
});
|
|
599
|
+
});
|
|
600
|
+
app.get("/metrics", async (_req, reply)=>{
|
|
601
|
+
const content = await metrics.registry.metrics();
|
|
602
|
+
reply.status(200).header("Content-Type", metrics.registry.contentType).send(content);
|
|
603
|
+
});
|
|
604
|
+
const handleRpc = (0, $c36759493dc2a380$export$9bfcc39f106ad871)({
|
|
605
|
+
providers: providers,
|
|
606
|
+
defaultChain: defaultChain,
|
|
607
|
+
fetchRPC: fetchRPC,
|
|
608
|
+
metrics: {
|
|
609
|
+
rpcRequestBlocked: metrics.rpcRequestBlocked,
|
|
610
|
+
rpcRequestMethods: metrics.rpcRequestMethods
|
|
611
|
+
},
|
|
612
|
+
validation: validation,
|
|
613
|
+
serverLogger: serverLogger,
|
|
614
|
+
upstreamTimeoutMs: upstreamTimeoutMs
|
|
615
|
+
});
|
|
616
|
+
const rpcRateLimit = (0, $ed77a7c0d430b773$export$d4d313c44e137fbd)({
|
|
617
|
+
max: rateLimit.max,
|
|
618
|
+
windowSec: rateLimit.windowSec,
|
|
619
|
+
customIpHeader: rateLimit.customIpHeader,
|
|
620
|
+
onBlocked: ()=>metrics.rateLimitBlockedCount.inc({
|
|
621
|
+
route: "/rpc"
|
|
622
|
+
})
|
|
623
|
+
});
|
|
624
|
+
app.register((scope)=>{
|
|
625
|
+
scope.addHook("preHandler", rpcRateLimit);
|
|
626
|
+
scope.post("/rpc", handleRpc);
|
|
627
|
+
return Promise.resolve();
|
|
628
|
+
});
|
|
629
|
+
};
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
$parcel$exportWildcard(module.exports, $83621533ef5f6afb$exports);
|
|
633
|
+
$parcel$exportWildcard(module.exports, $50baca306c9e1fc2$exports);
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
//# sourceMappingURL=index.cjs.map
|