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

Inspect Block Page #378

Open
wants to merge 15 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
1 change: 1 addition & 0 deletions app/api/block/[height]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { GET } from '@/shared/api/server/block';
4 changes: 2 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions scripts/generate-pindexer-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const pindexerTableWhitelist = [
'dex_ex_position_withdrawals',
'dex_ex_batch_swap_traces',
'dex_ex_metadata',
'dex_ex_block_summary',
];

const envFileReady = (): boolean => {
Expand Down
16 changes: 16 additions & 0 deletions src/pages/inspect/block/api/block.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useQuery } from '@tanstack/react-query';
import { BlockSummaryApiResponse } from '@/shared/api/server/block/types';
import { apiFetch } from '@/shared/utils/api-fetch';

export const useBlockSummary = (height: string) => {
return useQuery({
queryKey: ['block', height],
retry: 1,
queryFn: async (): Promise<BlockSummaryApiResponse> => {
if (!height) {
throw new Error('Invalid block height');
}
return apiFetch<BlockSummaryApiResponse>(`/api/block/${height}`);
},
});
};
10 changes: 1 addition & 9 deletions src/pages/inspect/block/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1 @@
import { Text } from '@penumbra-zone/ui/Text';

export function InspectBlock() {
return (
<div className='flex flex-col items-center justify-center h-[400px]'>
<Text color='text.muted'>Coming soon...</Text>
</div>
);
}
export { InspectBlock } from './ui';
97 changes: 97 additions & 0 deletions src/pages/inspect/block/ui/block-summary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { InfoCard } from '@/pages/explore/ui/info-card';
import { Text } from '@penumbra-zone/ui/Text';
import { TableCell } from '@penumbra-zone/ui/TableCell';
import { BlockSummaryApiResponse } from '@/shared/api/server/block/types';
import { ValueViewComponent } from '@penumbra-zone/ui/ValueView';
import { pnum } from '@penumbra-zone/types/pnum';

export function BlockSummary({ blockSummary }: { blockSummary: BlockSummaryApiResponse }) {
if ('error' in blockSummary) {
return <div>Error: {blockSummary.error}</div>;
}

return (
<div>
<div className='grid grid-cols-1 tablet:grid-cols-2 desktop:grid-cols-3 gap-2 mb-8'>
<InfoCard title='Total Transactions'>
<Text large color='text.primary'>
{blockSummary.numTxs}
</Text>
</InfoCard>
<InfoCard title='Total Swaps'>
<Text large color='text.primary'>
{blockSummary.numSwaps}
</Text>
</InfoCard>
<InfoCard title='Total Swap Claims'>
<Text large color='text.primary'>
{blockSummary.numSwapClaims}
</Text>
</InfoCard>
<InfoCard title='Total Open LPs'>
<Text large color='text.primary'>
{blockSummary.numOpenLps}
</Text>
</InfoCard>
<InfoCard title='Total Closed LPs'>
<Text large color='text.primary'>
{blockSummary.numClosedLps}
</Text>
</InfoCard>
<InfoCard title='Total Withdrawn LPs'>
<Text large color='text.primary'>
{blockSummary.numWithdrawnLps}
</Text>
</InfoCard>
</div>
<div>
<div className='mb-4'>
<Text large color='text.primary'>
Swaps
</Text>
</div>
<div className='grid grid-cols-4'>
<div className='grid grid-cols-subgrid col-span-4'>
<TableCell heading>From</TableCell>
Copy link
Contributor

Choose a reason for hiding this comment

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

question: how ok is the experience with this component after using it?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I didn't try all the props, but it was a straight fwd drop-n-replace 👍

<TableCell heading>To</TableCell>
<TableCell heading>Price</TableCell>
<TableCell heading>Number of Hops</TableCell>
</div>
{blockSummary.batchSwaps.length ? (
blockSummary.batchSwaps.map(swap => (
<div className='grid grid-cols-subgrid col-span-4' key={JSON.stringify(swap)}>
<TableCell>
<ValueViewComponent
valueView={pnum(swap.startInput).toValueView(swap.startAsset)}
trailingZeros={false}
/>
</TableCell>
<TableCell>
<ValueViewComponent
valueView={pnum(swap.endOutput).toValueView(swap.endAsset)}
trailingZeros={false}
/>
</TableCell>
<TableCell>
<Text color='text.primary'>
{swap.endPrice} {swap.endAsset.symbol}
</Text>
</TableCell>
<TableCell>
<Text color='text.primary'>{swap.numSwaps}</Text>
</TableCell>
</div>
))
) : (
<div className='grid grid-cols-subgrid col-span-4'>
<TableCell>--</TableCell>
<TableCell>--</TableCell>
<TableCell>--</TableCell>
<TableCell>--</TableCell>
</div>
)}
</div>
</div>
</div>
);
}
47 changes: 47 additions & 0 deletions src/pages/inspect/block/ui/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
'use client';

import { useParams } from 'next/navigation';
import { useBlockSummary } from '../api/block';
import { Card } from '@penumbra-zone/ui/Card';
import { Skeleton } from '@/shared/ui/skeleton';
import { BlockSummary } from './block-summary';

export function InspectBlock() {
const params = useParams<{ height: string }>();
const blockheight = params?.height;
const { data: blockSummary, isError } = useBlockSummary(blockheight ?? '');

return (
<div className='flex flex-col items-center justify-center'>
<div className='mb-4'>
{isError ? (
<Card title={`Couldn’t fetch transaction.`}>
<div className='w-[840px] min-h-[300px] text-white p-2'>
Something went wrong while fetching the transaction.
</div>
</Card>
) : (
<Card title={`Block #${blockheight}`}>
<div className='w-[840px] min-h-[300px] text-white p-2'>
{blockSummary ? (
<BlockSummary blockSummary={blockSummary} />
) : (
<div>
<div className='w-[822px] h-8 mb-2'>
<Skeleton />
</div>
<div className='w-[722px] h-6 mb-2'>
<Skeleton />
</div>
<div className='w-[422px] h-4'>
<Skeleton />
</div>
</div>
)}
</div>
</Card>
)}
</div>
</div>
);
}
103 changes: 103 additions & 0 deletions src/shared/api/server/block/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { NextRequest, NextResponse } from 'next/server';
import { pindexer } from '@/shared/database';
import { AssetId } from '@penumbra-zone/protobuf/penumbra/core/asset/v1/asset_pb';
import { ChainRegistryClient, Registry } from '@penumbra-labs/registry';
import { getDisplayDenomExponent } from '@penumbra-zone/getters/metadata';
import { pnum } from '@penumbra-zone/types/pnum';
import { hexToUint8Array, base64ToHex } from '@penumbra-zone/types/hex';
import { joinLoHi, LoHi } from '@penumbra-zone/types/lo-hi';
import { serialize, Serialized } from '@/shared/utils/serializer';
import { BatchSwapSummary as PindexerBatchSwapSummary } from '@/shared/database/schema';
import { BatchSwapSummary, BlockSummaryApiResponse } from './types';

function isLoHi(value: unknown): value is LoHi {
return typeof value === 'object' && value !== null && 'lo' in value;
}

interface AssetWithInner {
inner: string;
}

function isAsset(value: unknown): value is AssetWithInner {
return (
typeof value === 'object' &&
value !== null &&
'inner' in value &&
value.inner !== null &&
typeof (value as AssetWithInner).inner === 'string'
);
}

export const getBatchSwapDisplayData =
(registry: Registry) =>
(batchSwapSummary: PindexerBatchSwapSummary): BatchSwapSummary => {
if (!isLoHi(batchSwapSummary.input) || !isLoHi(batchSwapSummary.output)) {
throw new Error('Invalid input or output: expected LoHi type');
}

if (!isAsset(batchSwapSummary.asset_start) || !isAsset(batchSwapSummary.asset_end)) {
throw new Error('Invalid asset_start or asset_end');
}

const startAssetId = new AssetId({
inner: hexToUint8Array(base64ToHex(batchSwapSummary.asset_start.inner)),
});
const startMetadata = registry.getMetadata(startAssetId);
const startExponent = getDisplayDenomExponent.optional(startMetadata) ?? 0;

const endAssetId = new AssetId({
inner: hexToUint8Array(base64ToHex(batchSwapSummary.asset_end.inner)),
});
const endMetadata = registry.getMetadata(endAssetId);
const endExponent = getDisplayDenomExponent.optional(endMetadata) ?? 0;

const inputBigInt = joinLoHi(batchSwapSummary.input.lo, batchSwapSummary.input.hi);
const outputBigInt = joinLoHi(batchSwapSummary.output.lo, batchSwapSummary.output.hi);

return {
startAsset: startMetadata,
endAsset: endMetadata,
startInput: pnum(inputBigInt, startExponent).toString(),
endOutput: pnum(outputBigInt, endExponent).toString(),
endPrice: pnum(outputBigInt / inputBigInt, endExponent).toFormattedString(),
numSwaps: batchSwapSummary.num_swaps,
};
};

export async function GET(
_req: NextRequest,
{ params }: { params: { height: string } },
): Promise<NextResponse<Serialized<BlockSummaryApiResponse>>> {
const chainId = process.env['PENUMBRA_CHAIN_ID'];
if (!chainId) {
return NextResponse.json({ error: 'PENUMBRA_CHAIN_ID is not set' }, { status: 500 });
}

const height = params.height;
if (!height) {
return NextResponse.json({ error: 'height is required' }, { status: 400 });
}

const registryClient = new ChainRegistryClient();
const registry = await registryClient.remote.get(chainId);

const blockSummary = await pindexer.getBlockSummary(Number(height));

if (!blockSummary) {
return NextResponse.json({ error: 'Block summary not found' }, { status: 404 });
}

return NextResponse.json(
serialize({
height: blockSummary.height,
time: blockSummary.time,
batchSwaps: blockSummary.batch_swaps.map(getBatchSwapDisplayData(registry)),
numOpenLps: blockSummary.num_open_lps,
numClosedLps: blockSummary.num_closed_lps,
numWithdrawnLps: blockSummary.num_withdrawn_lps,
numSwaps: blockSummary.num_swaps,
numSwapClaims: blockSummary.num_swap_claims,
numTxs: blockSummary.num_txs,
}),
);
}
24 changes: 24 additions & 0 deletions src/shared/api/server/block/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Metadata } from '@penumbra-zone/protobuf/penumbra/core/asset/v1/asset_pb';

export interface BatchSwapSummary {
startAsset: Metadata;
endAsset: Metadata;
startInput: string;
endOutput: string;
endPrice: string;
numSwaps: number;
}

export type BlockSummaryApiResponse =
| {
height: number;
time: Date;
batchSwaps: BatchSwapSummary[];
numOpenLps: number;
numClosedLps: number;
numWithdrawnLps: number;
numSwaps: number;
numSwapClaims: number;
numTxs: number;
}
| { error: string };
9 changes: 9 additions & 0 deletions src/shared/database/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
DexExPositionExecutions,
DexExPositionReserves,
DexExPositionWithdrawals,
DexExBlockSummary,
DexExTransactions,
} from '@/shared/database/schema.ts';
import { AssetId } from '@penumbra-zone/protobuf/penumbra/core/asset/v1/asset_pb';
Expand Down Expand Up @@ -466,6 +467,14 @@ class Pindexer {
}));
}

async getBlockSummary(height: number): Promise<Selectable<DexExBlockSummary> | undefined> {
return this.db
.selectFrom('dex_ex_block_summary')
.selectAll()
.where('height', '=', height)
.executeTakeFirst();
}

async getTransaction(txHash: string): Promise<Selectable<DexExTransactions> | undefined> {
return this.db
.selectFrom('dex_ex_transactions')
Expand Down
24 changes: 24 additions & 0 deletions src/shared/database/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,28 @@ export interface DexExPriceCharts {
the_window: DurationWindow;
}

export interface BatchSwapSummary {
asset_start: Buffer;
asset_end: Buffer;
input: string;
output: string;
num_swaps: number;
price_float: number;
}

export interface DexExBlockSummary {
rowid: number;
height: number;
time: Date;
batch_swaps: BatchSwapSummary[];
num_open_lps: number;
num_closed_lps: number;
num_withdrawn_lps: number;
num_swaps: number;
num_swap_claims: number;
num_txs: number;
}

export interface DexExTransactions {
transaction_id: Buffer;
transaction: Buffer;
Expand Down Expand Up @@ -349,6 +371,7 @@ interface RawDB {
dex_ex_position_state: DexExPositionState;
dex_ex_position_withdrawals: DexExPositionWithdrawals;
dex_ex_price_charts: DexExPriceCharts;
dex_ex_block_summary: DexExBlockSummary;
dex_ex_transactions: DexExTransactions;
governance_delegator_votes: GovernanceDelegatorVotes;
governance_proposals: GovernanceProposals;
Expand Down Expand Up @@ -379,5 +402,6 @@ export type DB = Pick<
| 'dex_ex_position_withdrawals'
| 'dex_ex_batch_swap_traces'
| 'dex_ex_metadata'
| 'dex_ex_block_summary'
| 'dex_ex_transactions'
>;