Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(api): add support for fetching blocks by slot #700

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions .changeset/early-shrimps-guess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@blobscan/api": minor
---

Added support for fetching blocks by slot
73 changes: 44 additions & 29 deletions packages/api/src/routers/block/getByBlockId.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { TRPCError } from "@trpc/server";

import { z } from "@blobscan/zod";
import type { Prisma } from "@blobscan/db";
import { hashSchema, z } from "@blobscan/zod";

import {
createExpandsSchema,
withExpands,
} from "../../middlewares/withExpands";
import type { Filters } from "../../middlewares/withFilters";
import {
withFilters,
withTypeFilterSchema,
Expand All @@ -19,37 +21,54 @@ import {
} from "./common";
import type { QueriedBlock } from "./common";

const blockIdSchema = z
.string()
.refine(
(id) => {
const isHash = id.startsWith("0x") && id.length === 66;
const s_ = Number(id);
const isNumber = !isNaN(s_) && s_ > 0;
const blockHashSchema = hashSchema.refine((value) => value.length === 66, {
message: "Block hashes must be 66 characters long",
});

return isHash || isNumber;
},
{
message: "Invalid block id",
}
)
.transform((id) => {
if (id.startsWith("0x")) {
return id;
}

return Number(id);
});
const blockNumberOrSlotSchema = z.union([
z
.string()
.refine((value) => !hashSchema.safeParse(value).success)
.pipe(z.coerce.number().positive().int()),
z.number().positive().int(),
]);
const blockIdSchema = z.union([blockHashSchema, blockNumberOrSlotSchema]);

const inputSchema = z
.object({
id: blockIdSchema,
slot: z.boolean().optional(),
})
.merge(withTypeFilterSchema)
.merge(createExpandsSchema(["transaction", "blob", "blob_data"]));

const outputSchema = serializedBlockSchema;

function buildBlockWhereClause(
{ id, slot: isSlot }: z.output<typeof inputSchema>,
filters: Filters
): Prisma.BlockWhereInput {
const blockNumberOrSlotRes = blockNumberOrSlotSchema.safeParse(id);

if (blockNumberOrSlotRes.success) {
return {
[isSlot ? "slot" : "number"]: blockNumberOrSlotRes.data,
transactionForks: filters.blockType,
};
}

const blockHashResult = blockHashSchema.safeParse(id);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The blockHashSchema will never succeed if the blockNumberOrSlotSchema has already failed.


if (blockHashResult.data) {
return { hash: blockHashResult.data };
}

throw new TRPCError({
code: "BAD_REQUEST",
message: `Invalid block id "${id}"`,
});
}

Comment on lines +28 to +71
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const blockNumberOrSlotSchema = z.union([
z
.string()
.refine((value) => !hashSchema.safeParse(value).success)
.pipe(z.coerce.number().positive().int()),
z.number().positive().int(),
]);
const blockIdSchema = z.union([blockHashSchema, blockNumberOrSlotSchema]);
const inputSchema = z
.object({
id: blockIdSchema,
slot: z.boolean().optional(),
})
.merge(withTypeFilterSchema)
.merge(createExpandsSchema(["transaction", "blob", "blob_data"]));
const outputSchema = serializedBlockSchema;
function buildBlockWhereClause(
{ id, slot: isSlot }: z.output<typeof inputSchema>,
filters: Filters
): Prisma.BlockWhereInput {
const blockNumberOrSlotRes = blockNumberOrSlotSchema.safeParse(id);
if (blockNumberOrSlotRes.success) {
return {
[isSlot ? "slot" : "number"]: blockNumberOrSlotRes.data,
transactionForks: filters.blockType,
};
}
const blockHashResult = blockHashSchema.safeParse(id);
if (blockHashResult.data) {
return { hash: blockHashResult.data };
}
throw new TRPCError({
code: "BAD_REQUEST",
message: `Invalid block id "${id}"`,
});
}
const blockIdSchema = z.string().pipe(z.coerce.number().positive().int());
const inputSchema = z
.object({
id: blockIdSchema,
slot: z.boolean().optional(),
})
.merge(withTypeFilterSchema)
.merge(createExpandsSchema(["transaction", "blob", "blob_data"]));
const outputSchema = serializedBlockSchema;
function buildBlockWhereClause(
{ id, slot: isSlot }: z.output<typeof inputSchema>,
filters: Filters
): Prisma.BlockWhereInput {
const blockHashResult = blockHashSchema.safeParse(id);
if (blockHashResult.success) {
return { hash: blockHashResult.data };
}
const blockId = blockIdSchema.safeParse(id);
if (blockId.success) {
return {
[isSlot ? "slot" : "number"]: blockId.data,
transactionForks: filters.blockType,
};
}
throw new TRPCError({
code: "BAD_REQUEST",
message: `Invalid block id "${id}"`,
});
}

export const getByBlockId = publicProcedure
.meta({
openapi: {
Expand All @@ -66,23 +85,19 @@ export const getByBlockId = publicProcedure
.query(
async ({
ctx: { blobStorageManager, prisma, expands, filters },
input: { id },
input,
}) => {
const isNumber = typeof id === "number";
const where = buildBlockWhereClause(input, filters);

const queriedBlock = await prisma.block.findFirst({
select: createBlockSelect(expands),
where: {
[isNumber ? "number" : "hash"]: id,
// Hash is unique, so we don't need to filter by transaction forks if we're querying by it
transactionForks: isNumber ? filters.blockType : undefined,
},
where,
});

if (!queriedBlock) {
throw new TRPCError({
code: "NOT_FOUND",
message: `No block with id '${id}'.`,
message: `No block with id '${input.id}'.`,
});
}

Expand Down
52 changes: 52 additions & 0 deletions packages/api/test/__snapshots__/block.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -1634,6 +1634,58 @@ exports[`Block router > getByBlockId > should get a block by hash 1`] = `
}
`;

exports[`Block router > getByBlockId > should get a block by slot 1`] = `
{
"blobAsCalldataGasUsed": "2042780",
"blobGasPrice": "22",
"blobGasUsed": "786432",
"excessBlobGas": "15000",
"hash": "blockHash001",
"number": 1001,
"slot": 101,
"timestamp": "2022-10-16T12:00:00.000Z",
"transactions": [
{
"blobs": [
{
"versionedHash": "blobHash001",
},
{
"versionedHash": "blobHash002",
},
{
"versionedHash": "blobHash003",
},
],
"category": "other",
"hash": "txHash001",
},
{
"blobs": [
{
"versionedHash": "blobHash001",
},
],
"category": "other",
"hash": "txHash002",
},
{
"blobs": [
{
"versionedHash": "blobHash001",
},
{
"versionedHash": "blobHash002",
},
],
"category": "rollup",
"hash": "txHash003",
"rollup": "optimism",
},
],
}
`;

exports[`Block router > getByBlockId > should get a reorged block by block number 1`] = `
{
"blobAsCalldataGasUsed": "255000",
Expand Down
10 changes: 10 additions & 0 deletions packages/api/test/block.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,16 @@ describe("Block router", async () => {
};

const result = await caller.block.getByBlockId(input);

expect(result).toMatchSnapshot();
});

it("should get a block by slot", async () => {
const result = await caller.block.getByBlockId({
id: "101",
slot: true,
});

expect(result).toMatchSnapshot();
});

Expand Down
4 changes: 4 additions & 0 deletions packages/zod/src/schemas.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { z } from "zod";

export const hashSchema = z
.string()
.regex(/^0x[a-fA-F0-9]+$/, "Invalid hex string");

// We use this workaround instead of z.coerce.boolean.default(false)
// because it considers as "true" any value different than "false"
// (including the empty string).
Expand Down
Loading