Skip to content

Commit

Permalink
Merge pull request #666 from gitcoinco/log-ip
Browse files Browse the repository at this point in the history
Log ip
  • Loading branch information
0xKurt authored Sep 10, 2024
2 parents b6eb77b + b79efd4 commit 64fd8e5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import type { EventHandlerContext } from "./indexer/indexer.js";
import { handleEvent as handleAlloV1Event } from "./indexer/allo/v1/handleEvent.js";
import { handleEvent as handleAlloV2Event } from "./indexer/allo/v2/handleEvent.js";
import { Database } from "./database/index.js";
import { decodeJsonWithBigInts } from "./utils/index.js";
import { decodeJsonWithBigInts, getExternalIP } from "./utils/index.js";
import { Block } from "chainsauce/dist/cache.js";
import { createPublicClient, http } from "viem";
import { IndexerEvents } from "chainsauce/dist/indexer.js";
Expand Down Expand Up @@ -121,6 +121,8 @@ async function main(): Promise<void> {
return decodeJsonWithBigInts(val);
});

await getExternalIP(baseLogger);

if (config.cacheDir) {
if (config.removeCache) {
await fs.rm(config.cacheDir, { recursive: true });
Expand Down
28 changes: 28 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
// TODO: why is eslint not recognizing type narrowing?
/* eslint-disable @typescript-eslint/no-unsafe-argument */

import { Logger } from "pino";

/* eslint-disable @typescript-eslint/no-unsafe-member-access */
export function encodeJsonWithBigInts(value: unknown): string {
return JSON.stringify(value, (_key, value) => {
Expand Down Expand Up @@ -31,3 +34,28 @@ export const UINT64_MAX = 18446744073709551615n;
export const getDateFromTimestamp = (timestamp: bigint): Date | null => {
return timestamp < UINT64_MAX ? new Date(Number(timestamp) * 1000) : null;
};

export const getExternalIP = async (logger: Logger): Promise<string> => {
const urls = ["https://api.ipify.org?format=json", "http://ipinfo.io/json"];
for (const url of urls) {
try {
logger.debug(`Attempting to fetch IP address from: ${url}`);
const response = await fetch(url);
if (response.ok) {
const { ip } = (await response.json()) as { ip: string };
logger.info(`Successfully fetched IP address: ${ip}`);
return ip;
}
throw new Error(`Request failed with status: ${response.status}`);
} catch (error) {
if (error instanceof Error) {
logger.error(`Failed to fetch from ${url}: ${error.message}`);
} else {
logger.error(`Failed to fetch from ${url}`);
}
}
}
throw new Error(
"Unable to fetch external IP address from both primary and fallback URLs."
);
};

0 comments on commit 64fd8e5

Please sign in to comment.