Newer
Older
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
import * as express from 'express';
import { Request, Response } from 'express';
import { ApiPromise } from '@polkadot/api';
import { TypeRegistry } from '@polkadot/types';
import { BlockHash } from '@polkadot/types/interfaces/rpc';
const PORT = 8080;
async function main() {
const api = await ApiPromise.create();
const app = express();
async function getBlock(hash: BlockHash, req: Request, res: Response) {
const { block } = await api.rpc.chain.getBlock(hash);
const { parentHash, number, stateRoot, extrinsicsRoot } = block.header;
// console.log(block.toJSON());
const logs = block.header.digest.logs.map(log => log.type);
const extrinsics = block.extrinsics.map(extrinsic => ({
method: `${extrinsic.method.sectionName}.${extrinsic.method.methodName}`,
args: extrinsic.args.map(arg => arg.toJSON()),
}));
res.send({
number,
hash,
parentHash,
stateRoot,
extrinsicsRoot,
logs,
extrinsics,
});
}
app.get('/', (req, res) => res.send('Hello World!'))
app.get('/block/:number', async (req, res) => {
const number = Number(req.params.number) || 0;
const hash = await api.rpc.chain.getBlockHash(number);
await getBlock(hash, req, res);
})
app.get('/block/', async (req, res) => {
const hash = await api.rpc.chain.getFinalizedHead();
await getBlock(hash, req, res);
})
app.listen(PORT, () => console.log(`Example app listening on port ${PORT}!`))
}
main();