Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 19 additions & 10 deletions packages/shared/src/blockchain/alchemy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,40 @@ import { logger } from "../lib";
import type { NetworkLayer } from "../types";

export class Alchemy {
private static instance: Alchemy | undefined;
private static instances: Map<NetworkLayer, Alchemy> = new Map();
private alchemy: AlchemyInstance;

public static getInstance(networkLayer: NetworkLayer) {
if (!this.instance) {
this.instance = new Alchemy(networkLayer);
public static getInstance(networkLayer: NetworkLayer): Alchemy {
if (!this.instances.has(networkLayer)) {
this.instances.set(networkLayer, new Alchemy(networkLayer));
}
return this.instance;
return this.instances.get(networkLayer)!;
}

constructor(networkLayer: NetworkLayer) {
private constructor(networkLayer: NetworkLayer) {
logger.debug(`Attempting to get alchemy network for: "${networkLayer}"`);
const network =
networkLayer === "l1"
? Network[config.ALCHEMY_L1_NETWORK as keyof typeof Network]
: Network[config.ALCHEMY_L2_NETWORK as keyof typeof Network];

const network = this.getNetworkConfig(networkLayer);
const settings = {
apiKey: config.ALCHEMY_API_KEY,
network,
maxRetries: 5,
};

this.alchemy = new AlchemyInstance({ ...settings });
}

private getNetworkConfig(networkLayer: NetworkLayer): Network {
switch (networkLayer) {
case "l1":
return Network[config.ALCHEMY_L1_NETWORK as keyof typeof Network];
case "l2":
return Network[config.ALCHEMY_L2_NETWORK as keyof typeof Network];
default:
throw new Error(`Unsupported network layer: ${networkLayer}`);
}
}

async getBlock(blockNumber: bigint) {
const blockHashOrBlockTag = `0x${Number(blockNumber).toString(16)}`;
return this.alchemy.core.getBlock(blockHashOrBlockTag);
Expand Down