-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
87 lines (76 loc) · 2.18 KB
/
server.ts
File metadata and controls
87 lines (76 loc) · 2.18 KB
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
import express, { Request } from 'express';
import {
createPublicClient,
http,
formatEther,
getAddress
} from 'viem';
import { mainnet } from 'viem/chains';
import {
getBalancesForAddresses,
getBalancesForAllNotes
} from './balanceService';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const port = 8080;
const client = createPublicClient({
chain: mainnet,
transport: http(process.env.RPC)
});
async function getBlockNumberOrDefault(req: Request): Promise<bigint> {
const blockNumberQuery = req.query['blockNumber'];
if (
blockNumberQuery &&
(typeof blockNumberQuery !== 'string' || isNaN(parseInt(blockNumberQuery)))
) {
throw new Error('Invalid block number');
}
if (!blockNumberQuery) {
return await client.getBlockNumber();
}
return BigInt(blockNumberQuery);
}
function parseAddressesFromQuery(req: Request): `0x${string}`[] {
const address = req.query['address'];
let addresses: string[];
if (typeof address === 'string') {
addresses = [address];
} else {
addresses = address as string[];
}
const parsedAddresses = addresses.map((address) => getAddress(address));
return parsedAddresses;
}
app.get('/', async (req, res) => {
try {
const blockNumber = await getBlockNumberOrDefault(req);
let balances: Record<string, bigint>;
if (req.query['address']) {
let addresses: `0x${string}`[];
try {
addresses = parseAddressesFromQuery(req);
} catch {
res.status(400).json({ error: 'Invalid address' });
return;
}
balances = await getBalancesForAddresses(client, addresses, blockNumber);
} else {
balances = await getBalancesForAllNotes(client, blockNumber);
}
const formattedBalances = Object.entries(balances).map(
([owner, balance]) => ({
address: owner,
effective_balance: parseFloat(formatEther(balance))
})
);
res.status(200).json({ Result: formattedBalances });
} catch (error) {
console.log(error);
res.status(500).json({ error: 'An error occurred while fetching data' });
}
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});