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

Add Route to Fetch Blocks by Tenure Height #2144

Open
wants to merge 1 commit into
base: develop
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
2 changes: 2 additions & 0 deletions src/api/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
} from '@hirosystems/api-toolkit';
import { BlockRoutesV2 } from './routes/v2/blocks';
import { BurnBlockRoutesV2 } from './routes/v2/burn-blocks';
import { TenureHeightRoutesV2 } from './routes/v2/tenure-heights';
import { MempoolRoutesV2 } from './routes/v2/mempool';
import { SmartContractRoutesV2 } from './routes/v2/smart-contracts';
import { AddressRoutesV2 } from './routes/v2/addresses';
Expand Down Expand Up @@ -99,6 +100,7 @@ export const StacksApiRoutes: FastifyPluginAsync<
async fastify => {
await fastify.register(BlockRoutesV2, { prefix: '/blocks' });
await fastify.register(BurnBlockRoutesV2, { prefix: '/burn-blocks' });
await fastify.register(TenureHeightRoutesV2, { prefix: '/tenure-height' });
Copy link
Collaborator

Choose a reason for hiding this comment

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

For v2 endpoints we're trying to keep route names as REST-ful as possible, so we want to group endpoints according to the entity that they return. Adding tenure-height here would not fit the standard.

Could you instead add a tenure_height query param to the /extended/v2/blocks endpoint? That will also allow you to get cursor pagination for free and will work much better with API clients.

Copy link
Author

Choose a reason for hiding this comment

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

Hello @rafaelcr! I am currently trying to modify the query from pg-store-v2, but when parsing a tenure height query, the results list is empty. Can you please take a look over it and let me know what I'm doing wrong? Thank you!

https://github.com/degen-lab/stacks-blockchain-api/blob/test/get-blocks-by-tenure-height/src/datastore/pg-store-v2.ts#L76-L140

await fastify.register(SmartContractRoutesV2, { prefix: '/smart-contracts' });
await fastify.register(MempoolRoutesV2, { prefix: '/mempool' });
await fastify.register(PoxRoutesV2, { prefix: '/pox' });
Expand Down
5 changes: 5 additions & 0 deletions src/api/pagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export enum ResourceType {
Pox2Event,
Stacker,
BurnBlock,
TenureHeight,
Signer,
PoxCycle,
TokenHolders,
Expand All @@ -51,6 +52,10 @@ export const pagingQueryLimits: Record<ResourceType, { defaultLimit: number; max
defaultLimit: 20,
maxLimit: 30,
},
[ResourceType.TenureHeight]: {
defaultLimit: 20,
maxLimit: 30,
},
[ResourceType.Tx]: {
defaultLimit: 20,
maxLimit: 50,
Expand Down
16 changes: 16 additions & 0 deletions src/api/routes/v2/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ const BurnBlockHeightParamSchema = Type.Integer({
examples: [777678],
});

const TenureHeightParamSchema = Type.Integer({
title: 'Tenure height',
description: 'Tenure height',
examples: [777678],
});

const BlockHeightParamSchema = Type.Integer({
title: 'Block height',
description: 'Block height',
Expand Down Expand Up @@ -207,6 +213,16 @@ export const BurnBlockParamsSchema = Type.Object(
);
export type BurnBlockParams = Static<typeof BurnBlockParamsSchema>;

export const TenureParamsSchema = Type.Object(
{
height: Type.Union([
TenureHeightParamSchema,
]),
},
{ additionalProperties: false }
);
export type TenureParams = Static<typeof TenureParamsSchema>;

export const SmartContractStatusParamsSchema = Type.Object(
{
contract_id: Type.Union([Type.Array(SmartContractIdParamSchema), SmartContractIdParamSchema]),
Expand Down
63 changes: 63 additions & 0 deletions src/api/routes/v2/tenure-heights.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { handleChainTipCache } from '../../controllers/cache-controller';
import { parseDbNakamotoBlock } from './helpers';
import { TenureParamsSchema } from './schemas';
import { InvalidRequestError, NotFoundError } from '../../../errors';
import { FastifyPluginAsync } from 'fastify';
import { Type, TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { Server } from 'node:http';
import { LimitParam, OffsetParam } from '../../schemas/params';
import { ResourceType } from '../../pagination';
import { PaginatedResponse } from '../../schemas/util';
import { NakamotoBlockSchema } from '../../schemas/entities/block';

export const TenureHeightRoutesV2: FastifyPluginAsync<
Record<never, never>,
Server,
TypeBoxTypeProvider
> = async fastify => {
fastify.get(
'/:height/blocks',
{
preHandler: handleChainTipCache,
schema: {
operationId: 'get_blocks_by_tenure_height',
summary: 'Get blocks by tenure height',
description: `Retrieves a list of blocks confirmed within a specific tenure height`,
tags: ['Tenure Height'],
params: TenureParamsSchema,
querystring: Type.Object({
limit: LimitParam(ResourceType.TenureHeight),
offset: OffsetParam(),
}),
response: {
200: PaginatedResponse(NakamotoBlockSchema),
},
},
},
async (req, reply) => {
const { height } = req.params;
const query = req.query;

try {
const { limit, offset, results, total } = await fastify.db.v2.getBlocksByTenureHeight({
height,
...query,
});
const blocks = results.map(r => parseDbNakamotoBlock(r));
await reply.send({
limit,
offset,
total,
results: blocks,
});
} catch (error) {
if (error instanceof InvalidRequestError) {
throw new NotFoundError(error.message);
}
throw error;
}
}
);

await Promise.resolve();
};
46 changes: 46 additions & 0 deletions src/datastore/pg-store-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,52 @@ export class PgStoreV2 extends BasePgStoreModule {
});
}

async getBlocksByTenureHeight(args: {
height: number;
limit?: number;
offset?: number;
}): Promise<DbPaginatedResult<DbBlock>> {
return await this.sqlTransaction(async sql => {
const limit = args.limit ?? BlockLimitParamSchema.default;
const offset = args.offset ?? 0;
const filter = sql`tenure_height = ${args.height}`;
const blockCheck = await sql`SELECT burn_block_hash FROM blocks WHERE ${filter} LIMIT 1`;
if (blockCheck.count === 0)
throw new InvalidRequestError(
`Tenure height not found`,
InvalidRequestErrorType.invalid_param
);

const blocksQuery = await sql<(BlockQueryResult & { total: number })[]>`
WITH block_count AS (
SELECT COUNT(*) AS count FROM blocks WHERE canonical = TRUE AND ${filter}
)
SELECT
${sql(BLOCK_COLUMNS)},
(SELECT count FROM block_count)::int AS total
FROM blocks
WHERE canonical = true AND ${filter}
ORDER BY block_height DESC
LIMIT ${limit}
OFFSET ${offset}
`;
if (blocksQuery.count === 0)
return {
limit,
offset,
results: [],
total: 0,
};
const blocks = blocksQuery.map(b => parseBlockQueryResult(b));
return {
limit,
offset,
results: blocks,
total: blocksQuery[0].total,
};
});
}

async getBlock(args: BlockIdParam): Promise<DbBlock | undefined> {
return await this.sqlTransaction(async sql => {
const filter =
Expand Down