Skip to content

Commit

Permalink
simplify using iteratorToArray
Browse files Browse the repository at this point in the history
  • Loading branch information
holic committed Sep 22, 2024
1 parent 6e4af79 commit 99e7f37
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 11 deletions.
15 changes: 8 additions & 7 deletions packages/block-logs-stream/src/fetchBlockLogs.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { AbiEvent, Log } from "viem";
import { AbiEvent } from "viem";
import { GroupLogsByBlockNumberResult, groupLogsByBlockNumber } from "./groupLogsByBlockNumber";
import { FetchLogsOptions, FetchLogsResult, fetchLogs } from "./fetchLogs";
import { iteratorToArray } from "@latticexyz/common/utils";

/**
* Fetches all logs from the blockchain for the given range, grouped by block number.
Expand All @@ -12,14 +13,14 @@ import { FetchLogsOptions, FetchLogsResult, fetchLogs } from "./fetchLogs";
*
* @param {FetchLogsOptions<AbiEvent[]>} options See `FetchLogsOptions`.
*
* @returns {GroupLogsByBlockNumberResult} See `GroupLogsByBlockNumberResult`.
*
* @throws Will throw an error if the block range can't be reduced any further.
*/
export async function fetchBlockLogs<abiEvents extends readonly AbiEvent[]>(
opts: FetchLogsOptions<abiEvents>,
): Promise<GroupLogsByBlockNumberResult<Log<bigint, number, false, undefined, true, abiEvents, undefined>>> {
const results: FetchLogsResult<abiEvents>[] = [];
for await (const result of fetchLogs(opts)) {
results.push(result);
}
return groupLogsByBlockNumber(results.flatMap((result) => result.logs));
): Promise<GroupLogsByBlockNumberResult<FetchLogsResult<abiEvents>["logs"][number]>> {
const fetchedLogs = await iteratorToArray(fetchLogs(opts));
const logs = fetchedLogs.flatMap(({ logs }) => logs);
return groupLogsByBlockNumber(logs);
}
6 changes: 3 additions & 3 deletions packages/block-logs-stream/src/groupLogsByBlockNumber.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { BlockNumber } from "viem";
import { bigIntSort, isDefined } from "@latticexyz/common/utils";

type PartialLog = { blockNumber: bigint; logIndex: number };
type PartialLog = { readonly blockNumber: bigint; readonly logIndex: number };

export type GroupLogsByBlockNumberResult<log extends PartialLog> = {
blockNumber: log["blockNumber"];
logs: readonly log[];
readonly blockNumber: log["blockNumber"];
readonly logs: readonly log[];
}[];

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/common/src/utils/iteratorToArray.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export async function iteratorToArray<T>(iterator: AsyncIterable<T>): Promise<T[]> {
export async function iteratorToArray<T>(iterator: AsyncIterable<T>): Promise<readonly T[]> {
const items: T[] = [];
for await (const item of iterator) {
items.push(item);
Expand Down

0 comments on commit 99e7f37

Please sign in to comment.