Skip to content

Commit 8053b6a

Browse files
committed
refactor: clean up code formatting and improve readability across multiple files
1 parent 995d1a0 commit 8053b6a

9 files changed

Lines changed: 132 additions & 130 deletions

File tree

src/index.ts

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,13 @@ import "dotenv/config";
22
import { handleUplinks } from "./services/mqtt";
33
import { Request, Response } from "express";
44
import { app } from "./services/context";
5-
import { loadExtensionsFromConfig, loadUIExtensionsFromConfig, getUIComponents, invokeUIAction, runHook } from "./lib/utils";
5+
import {
6+
loadExtensionsFromConfig,
7+
loadUIExtensionsFromConfig,
8+
getUIComponents,
9+
invokeUIAction,
10+
runHook,
11+
} from "./lib/utils";
612
import setupDatabase, { getAllMeterRecords, deleteMeterByPublicKey } from "./store/sqlite";
713

814
// Async initialization function
@@ -49,10 +55,10 @@ initializeApp();
4955

5056
app.get("/", async (req: Request, res: Response) => {
5157
const m3ters = getAllMeterRecords();
52-
58+
5359
// Get UI components from loaded UI extensions
5460
const { icons, windows } = await getUIComponents();
55-
61+
5662
res.render("index", { m3ters, icons, windows });
5763
console.log("[server]: Server handled GET request at `/`");
5864
});
@@ -61,9 +67,9 @@ app.get("/", async (req: Request, res: Response) => {
6167
app.post("/api/actions/:moduleId/:actionId", async (req: Request, res: Response) => {
6268
const { moduleId, actionId } = req.params;
6369
console.log(`[server]: Invoking action '${actionId}' from module '${moduleId}'`);
64-
70+
6571
const result = await invokeUIAction(moduleId, actionId);
66-
72+
6773
if (result.success) {
6874
res.status(200).json(result);
6975
} else {

src/lib/core/streamr/index.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,12 @@ export default class implements Hooks {
1616
private cronSchedule: string = process.env.STREAMR_CRONSCHEDULE || "0 * * * *";
1717

1818
async onAfterInit() {
19-
console.log("Registering Streamr cron job... Schedule: ", this.cronSchedule, " Stream IDs: ", JSON.stringify(this.streamIds));
19+
console.log(
20+
"Registering Streamr cron job... Schedule: ",
21+
this.cronSchedule,
22+
" Stream IDs: ",
23+
JSON.stringify(this.streamIds),
24+
);
2025

2126
// Schedule a cron job to publish pending transactions
2227
cron.schedule(

src/lib/encode.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,11 @@ function floatToByteArray(float: number) {
2424
}
2525

2626
/**
27-
*
27+
*
2828
* @notice only needs `nonce` from the state
2929
*/
3030
export function encode(state: State, latitude: number, longitude: number) {
31-
let responseBytes = floatToByteArray(latitude).concat(
32-
floatToByteArray(longitude)
33-
);
31+
let responseBytes = floatToByteArray(latitude).concat(floatToByteArray(longitude));
3432

3533
let nonce = state.nonce;
3634

src/lib/sync.ts

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -28,30 +28,30 @@ let isCacheInitialized = false;
2828
export async function initializeVerifiersCache(): Promise<void> {
2929
try {
3030
console.log("[info] Initializing verifiers cache...");
31-
31+
3232
// Get the number of verifiers
3333
const verifierCount = Number(await retry(() => ccipRevenueReaderContract.verifierCount()));
3434
console.log(`[info] Found ${verifierCount} verifiers to cache`);
35-
35+
3636
const verifiers: VerifierInfo[] = [];
37-
37+
3838
// Fetch all verifiers and resolve their ENS names
3939
for (let i = 0; i < verifierCount; i++) {
4040
try {
4141
// Get verifier info (ensName, targetContractAddress)
4242
const [ensName, targetAddress] = await retry(() => ccipRevenueReaderContract.verifiers(i));
43-
43+
4444
console.log(`[info] Fetching verifier ${i}: ENS: ${ensName}, target: ${targetAddress}`);
45-
45+
4646
// Resolve ENS name to get the verifier address
4747
const verifierAddress = await retry(() => provider.resolveName(ensName));
48-
48+
4949
if (!verifierAddress || verifierAddress === ZeroAddress) {
5050
throw new Error(`Failed to resolve ENS name: ${ensName}`);
5151
}
52-
52+
5353
console.log(`[info] Resolved ${ensName} to verifier address: ${verifierAddress}`);
54-
54+
5555
verifiers.push({
5656
ensName,
5757
targetAddress,
@@ -62,11 +62,11 @@ export async function initializeVerifiersCache(): Promise<void> {
6262
throw error; // Fail fast as requested
6363
}
6464
}
65-
65+
6666
// Cache the verifiers
6767
verifiersCache = verifiers;
6868
isCacheInitialized = true;
69-
69+
7070
console.log(`[info] Successfully cached ${verifiers.length} verifiers`);
7171
} catch (error) {
7272
console.error("[error] Failed to initialize verifiers cache:", error);
@@ -102,9 +102,7 @@ export function getCachedVerifiersCount(): number {
102102

103103
export async function pruneAndSyncOnchain(meterIdentifier: number | string): Promise<number> {
104104
const meter =
105-
typeof meterIdentifier === "number"
106-
? getMeterByTokenId(meterIdentifier)
107-
: getMeterByPublicKey(meterIdentifier);
105+
typeof meterIdentifier === "number" ? getMeterByTokenId(meterIdentifier) : getMeterByPublicKey(meterIdentifier);
108106

109107
if (!meter) {
110108
throw new Error(`Meter with identifier ${meterIdentifier} not found`);
@@ -148,20 +146,22 @@ export async function getCrossChainRevenue(tokenId: number): Promise<number> {
148146
try {
149147
// Use cached verifiers instead of fetching them each time
150148
const verifiers = await getCachedVerifiers();
151-
149+
152150
let totalRevenue = 0;
153151

154152
// Iterate through all cached verifiers and get revenue from each chain
155153
for (const verifier of verifiers) {
156154
try {
157-
console.log(`[info] Getting revenue from ENS: ${verifier.ensName}, target: ${verifier.targetAddress}, verifier: ${verifier.verifierAddress}`);
155+
console.log(
156+
`[info] Getting revenue from ENS: ${verifier.ensName}, target: ${verifier.targetAddress}, verifier: ${verifier.verifierAddress}`,
157+
);
158158

159159
// Get revenue from this specific chain using CCIP read
160160
// Parameters: tokenId, target (L2 contract), verifier (resolved from ENS)
161161
const revenue = await retry(() =>
162162
ccipRevenueReaderContract.read(tokenId, verifier.targetAddress, verifier.verifierAddress, {
163163
enableCcipRead: true,
164-
})
164+
}),
165165
);
166166
const revenueAmount = Number(revenue);
167167

src/services/context.ts

Lines changed: 57 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -52,66 +52,63 @@ wss.on("connection", (ws: WebSocket, request: http.IncomingMessage) => {
5252
ssh
5353
.on("ready", () => {
5454
console.log("[ws/ssh]: SSH connection established");
55-
ssh.shell(
56-
{ term: "xterm", cols: parseInt(cols), rows: parseInt(rows) },
57-
(err, stream) => {
58-
if (err) {
59-
ws.send(`[ws/ssh]: SSH shell error: ${err.message}`);
60-
ws.close();
61-
ssh.end();
62-
return;
63-
}
55+
ssh.shell({ term: "xterm", cols: parseInt(cols), rows: parseInt(rows) }, (err, stream) => {
56+
if (err) {
57+
ws.send(`[ws/ssh]: SSH shell error: ${err.message}`);
58+
ws.close();
59+
ssh.end();
60+
return;
61+
}
6462

65-
// SSH -> WebSocket
66-
stream.on("data", (data: Buffer) => {
67-
if (ws.readyState === WebSocket.OPEN) {
68-
ws.send(data);
69-
}
70-
});
63+
// SSH -> WebSocket
64+
stream.on("data", (data: Buffer) => {
65+
if (ws.readyState === WebSocket.OPEN) {
66+
ws.send(data);
67+
}
68+
});
7169

72-
stream.on("close", () => {
73-
console.log("[ws/ssh]: SSH stream closed");
74-
ws.close();
75-
ssh.end();
76-
});
70+
stream.on("close", () => {
71+
console.log("[ws/ssh]: SSH stream closed");
72+
ws.close();
73+
ssh.end();
74+
});
7775

78-
stream.stderr.on("data", (data: Buffer) => {
79-
if (ws.readyState === WebSocket.OPEN) {
80-
ws.send(`[ws/ssh]: SSH stderr: ${data.toString()}`);
81-
}
82-
});
83-
84-
// WebSocket -> SSH
85-
console.log("[ws/ssh]: Setting up WebSocket message handler");
86-
ws.on("message", (msg) => {
87-
// support JSON control messages for resize
88-
try {
89-
const parsed = JSON.parse(msg.toString());
90-
if (parsed.type === "resize") {
91-
const { cols, rows } = parsed;
92-
stream.setWindow(rows, cols, cols * 8, rows * 16); // width/height px optional
93-
return;
94-
}
95-
} catch (e) {
96-
/* not JSON - treat as raw data */
76+
stream.stderr.on("data", (data: Buffer) => {
77+
if (ws.readyState === WebSocket.OPEN) {
78+
ws.send(`[ws/ssh]: SSH stderr: ${data.toString()}`);
79+
}
80+
});
81+
82+
// WebSocket -> SSH
83+
console.log("[ws/ssh]: Setting up WebSocket message handler");
84+
ws.on("message", (msg) => {
85+
// support JSON control messages for resize
86+
try {
87+
const parsed = JSON.parse(msg.toString());
88+
if (parsed.type === "resize") {
89+
const { cols, rows } = parsed;
90+
stream.setWindow(rows, cols, cols * 8, rows * 16); // width/height px optional
91+
return;
9792
}
93+
} catch (e) {
94+
/* not JSON - treat as raw data */
95+
}
9896

99-
if (stream.writable) stream.write(msg);
100-
});
101-
102-
ws.on("close", () => {
103-
console.log("[ws]: WebSocket closed, closing SSH stream");
104-
stream.end();
105-
ssh.end();
106-
});
107-
108-
ws.on("error", () => {
109-
console.log("[ws]: WebSocket error, closing SSH stream");
110-
stream.end();
111-
ssh.end();
112-
});
113-
}
114-
);
97+
if (stream.writable) stream.write(msg);
98+
});
99+
100+
ws.on("close", () => {
101+
console.log("[ws]: WebSocket closed, closing SSH stream");
102+
stream.end();
103+
ssh.end();
104+
});
105+
106+
ws.on("error", () => {
107+
console.log("[ws]: WebSocket error, closing SSH stream");
108+
stream.end();
109+
ssh.end();
110+
});
111+
});
115112
})
116113
.on("error", (err) => {
117114
console.error("[ws/ssh]: SSH connection error:", err);
@@ -131,17 +128,14 @@ export const provider = new JsonRpcProvider(process.env.MAINNET_RPC);
131128

132129
export const m3ter = new Contract(
133130
process.env.M3TER_CONTRACT_ADDRESS || "0x9C547B649475f1bE81323AefdbcF209C17961D5E",
134-
[
135-
"function publicKey(uint256) view returns (bytes32)",
136-
"function tokenID(bytes32) view returns (uint256)",
137-
],
138-
provider
131+
["function publicKey(uint256) view returns (bytes32)", "function tokenID(bytes32) view returns (uint256)"],
132+
provider,
139133
);
140134

141135
export const rollup = new Contract(
142136
process.env.ROLLUP_CONTRACT_ADDRESS || "0xf8f2d4315DB5db38f3e5c45D0bCd59959c603d9b",
143137
["function nonce(uint256) external view returns (bytes6)"],
144-
provider
138+
provider,
145139
);
146140

147141
export const ccipRevenueReader = new Contract(
@@ -152,11 +146,11 @@ export const ccipRevenueReader = new Contract(
152146
"function verifierCount() external view returns (uint256)",
153147
"function verifiers(uint256) external view returns (string, address)",
154148
],
155-
provider
149+
provider,
156150
);
157151

158152
export const priceContext = new Contract(
159153
process.env.PRICE_CONTEXT_ADDRESS || "0xc6D5Ff8E80F4Ee511Db4bCf6a0BcEbF9f41aAA32",
160154
["function owed(uint256 tokenId) public view returns (uint256)"],
161-
provider
155+
provider,
162156
);

src/services/grpc.ts

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,8 @@
11
import { credentials, Metadata } from "@grpc/grpc-js";
22
import { DeviceServiceClient } from "@chirpstack/chirpstack-api/api/device_grpc_pb";
3-
import {
4-
DeviceQueueItem,
5-
EnqueueDeviceQueueItemRequest,
6-
} from "@chirpstack/chirpstack-api/api/device_pb";
3+
import { DeviceQueueItem, EnqueueDeviceQueueItemRequest } from "@chirpstack/chirpstack-api/api/device_pb";
74

8-
const deviceService = new DeviceServiceClient(
9-
`${process.env.CHIRPSTACK_HOST}:8080`,
10-
credentials.createInsecure()
11-
);
5+
const deviceService = new DeviceServiceClient(`${process.env.CHIRPSTACK_HOST}:8080`, credentials.createInsecure());
126

137
const metadata = new Metadata();
148
metadata.set("authorization", "Bearer " + process.env.API_TOKEN);

src/services/mqtt.ts

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,12 @@ import {
1616
import type { State, TransactionRecord } from "../types";
1717
import { decodePayload } from "../lib/decode";
1818
import { runHook, verifyPayloadSignature } from "../lib/utils";
19-
import { getLatestTransactionNonce, pruneAndSyncOnchain, getCrossChainRevenue, getOwedFromPriceContext } from "../lib/sync";
19+
import {
20+
getLatestTransactionNonce,
21+
pruneAndSyncOnchain,
22+
getCrossChainRevenue,
23+
getOwedFromPriceContext,
24+
} from "../lib/sync";
2025
import { createMeterLogger } from "../utils/logger";
2126

2227
const CHIRPSTACK_HOST = process.env.CHIRPSTACK_HOST;
@@ -193,7 +198,7 @@ export async function handleMessage(blob: Buffer) {
193198

194199
enqueue(
195200
message["deviceInfo"]["devEui"],
196-
encode(state as State, decoded.extensions.latitude ?? 0, decoded.extensions.longitude ?? 0)
201+
encode(state as State, decoded.extensions.latitude ?? 0, decoded.extensions.longitude ?? 0),
197202
);
198203

199204
return; // Exit early without processing the transaction
@@ -228,24 +233,24 @@ export async function handleMessage(blob: Buffer) {
228233
await runHook("onTransactionDistribution", m3ter.tokenId, decoded, pendingTransactions);
229234
}
230235

231-
try {
232-
is_on = await runHook("isOnStateCompute", m3ter.tokenId);
233-
} catch (error) {
234-
runHook("onIsOnStateComputeError", m3ter.tokenId, error);
235-
logger.error(`Error in isOnStateCompute hook: ${error}`);
236-
}
236+
try {
237+
is_on = await runHook("isOnStateCompute", m3ter.tokenId);
238+
} catch (error) {
239+
runHook("onIsOnStateComputeError", m3ter.tokenId, error);
240+
logger.error(`Error in isOnStateCompute hook: ${error}`);
241+
}
237242

238-
runHook("onIsOnStateComputed", m3ter.tokenId, is_on);
243+
runHook("onIsOnStateComputed", m3ter.tokenId, is_on);
239244

240-
const state = decoded.nonce === expectedNonce ? { is_on } : { nonce: m3ter.latestNonce, is_on };
245+
const state = decoded.nonce === expectedNonce ? { is_on } : { nonce: m3ter.latestNonce, is_on };
241246

242-
logger.info(`Enqueuing state: ${JSON.stringify(state)}`);
247+
logger.info(`Enqueuing state: ${JSON.stringify(state)}`);
243248

244-
enqueue(
245-
message["deviceInfo"]["devEui"],
246-
encode(state as State, decoded.extensions.latitude ?? 0, decoded.extensions.longitude ?? 0)
247-
);
248-
runHook("onStateEnqueued", state, decoded.extensions.latitude ?? 0, decoded.extensions.longitude ?? 0);
249+
enqueue(
250+
message["deviceInfo"]["devEui"],
251+
encode(state as State, decoded.extensions.latitude ?? 0, decoded.extensions.longitude ?? 0),
252+
);
253+
runHook("onStateEnqueued", state, decoded.extensions.latitude ?? 0, decoded.extensions.longitude ?? 0);
249254
} catch (error) {
250255
logger.error(`Error handling MQTT message: ${error}`);
251256
runHook("onMessageError", error);

0 commit comments

Comments
 (0)