forked from radotzki/eth-json-rpc-middleware
-
Notifications
You must be signed in to change notification settings - Fork 1
/
block-ref-rewrite.js
27 lines (23 loc) · 1021 Bytes
/
block-ref-rewrite.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
const createAsyncMiddleware = require('json-rpc-engine/src/createAsyncMiddleware')
const blockTagParamIndex = require('./cache-utils').blockTagParamIndex
module.exports = createBlockRefRewriteMiddleware
function createBlockRefRewriteMiddleware (opts = {}) {
const { blockTracker } = opts
if (!blockTracker) {
throw Error('BlockRefRewriteMiddleware - mandatory "blockTracker" option is missing.')
}
return createAsyncMiddleware(async (req, res, next) => {
const blockRefIndex = blockTagParamIndex(req)
// skip if method does not include blockRef
if (blockRefIndex === undefined) return next()
// skip if not "latest"
let blockRef = req.params[blockRefIndex]
// omitted blockRef implies "latest"
if (blockRef === undefined) blockRef = 'latest'
if (blockRef !== 'latest') return next()
// rewrite blockRef to block-tracker's block number
const latestBlockNumber = await blockTracker.getLatestBlock()
req.params[blockRefIndex] = latestBlockNumber
next()
})
}