Skip to content

feat(txn-table): transaction table #37

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

Merged
merged 19 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
123 changes: 81 additions & 42 deletions apps/storybook/src/components/ui/data-table.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import {
ColumnDef,
SortingState,
flexRender,
getCoreRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";

Expand All @@ -13,6 +16,8 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
import { useState } from "react";
import { Button } from "./button";

interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
Expand All @@ -23,56 +28,90 @@ export function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = useState<SortingState>([]);

const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
state: {
sorting,
},
});

return (
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
<div>
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center"
>
No results.
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-end space-x-2 py-4">
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
Next
</Button>
</div>
</div>
);
}
20 changes: 18 additions & 2 deletions apps/storybook/src/hooks/use-blockscout.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { asTransactionMeta, getTransaction } from "@/lib/blockscout/api";
import {
GetTxnByFilterQuery,
asTransactionMeta,
getTransaction,
getTxnsByFilter,
} from "@/lib/blockscout/api";
import { TransactionMeta } from "@/lib/domain/transaction/transaction";
import { useQuery } from "@tanstack/react-query";
import { Address, Transaction } from "viem";

export const CACHE_KEY = "blockscout";

Expand All @@ -14,3 +18,15 @@ export const useGetTransaction = (txnHash: string) => {
},
});
};

export const useGetTransactions = (query: GetTxnByFilterQuery) => {
return useQuery<TransactionMeta[]>({
queryKey: [`${CACHE_KEY}.transactions`, query],
queryFn: async () => {
const results = await getTxnsByFilter(query);
// TODO: implement pagination with API calls
if (!!results) return results.items;
return [];
},
});
};
80 changes: 66 additions & 14 deletions apps/storybook/src/lib/blockscout/api.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { Address, Transaction, parseGwei, parseUnits } from "viem";
import { Address, parseUnits } from "viem";
import * as chains from "viem/chains";
import {
TokenTransfer,
TransactionMeta,
} from "../domain/transaction/transaction";

const ROOT = "https://eth.blockscout.com/api/";
const chainIdToApiRoot: any = {
[chains.mainnet.id]: "https://eth.blockscout.com/api/",
[chains.optimism.id]: "https://optimism.blockscout.com/api/",
};

export const invokeApi = async (endpoint: string, body?: any) => {
return fetch(endpoint, {
method: "GET",
Expand All @@ -26,42 +31,87 @@ export interface BlockscoutEndpointParams {
txnHash?: string;
}

export const ENDPOINT_STRATEGIES = {
export const getEndpointStrategy = (chainId?: number) => ({
[BlockscoutEndpoint.Address]: (params: BlockscoutEndpointParams) => {
const { address } = params;
return ROOT + "v1/address/" + address;
return (
chainIdToApiRoot[chainId || chains.mainnet.id] + "v1/address/" + address
);
},
[BlockscoutEndpoint.Transaction]: (params: BlockscoutEndpointParams) => {
const { txnHash } = params;
return ROOT + "v2/transactions/" + txnHash;
return (
chainIdToApiRoot[chainId || chains.mainnet.id] +
"v2/transactions/" +
txnHash
);
},
};
});

// TODO enum type
export const getEndpoint = (
endpoint: BlockscoutEndpoint,
params: BlockscoutEndpointParams,
chainId = 1,
) => {
const strategy = ENDPOINT_STRATEGIES[endpoint];
const strategy = getEndpointStrategy(chainId)[endpoint];
if (!strategy) {
throw new Error("");
}

return strategy(params);
};

export const getAddressInfo = async (address: Address) => {
const endpoint = getEndpoint(BlockscoutEndpoint.Address, { address });
export const getAddressInfo = async (address: Address, chainId?: number) => {
const endpoint = getEndpoint(
BlockscoutEndpoint.Address,
{ address },
chainId,
);
return invokeApi(endpoint);
};

export const getTransaction = async (txnHash: string) => {
const endpoint = getEndpoint(BlockscoutEndpoint.Transaction, {
txnHash,
});
export const getTransaction = async (txnHash: string, chainId?: number) => {
const endpoint = getEndpoint(
BlockscoutEndpoint.Transaction,
{
txnHash,
},
chainId,
);
return invokeApi(endpoint);
};

export interface GetTxnByFilterQuery {
filter?: string;

// maybe have more types
type?: (
| "token_transfer"
| "contract_creation"
| "contract_call"
| "coin_transfer"
| "token_creation"
)[];
method?: string;
chainId?: number;
}

export const getTxnsByFilter = async ({
filter,
type,
method,
chainId = 1,
}: GetTxnByFilterQuery) => {
const queryString = new URLSearchParams({
...(filter && { filter }),
...(method && { method }),
...(type && { type: type.join(",") }),
});
const endpoint = `${chainIdToApiRoot[chainId || chains.mainnet.id]}v2/transactions?${queryString.toString()}`;
return await invokeApi(endpoint);
};

export const findDisplayedTxType = (transaction_types: any[]): string => {
if (transaction_types.includes("contract_call")) {
return "contract_call";
Expand Down Expand Up @@ -96,6 +146,8 @@ export const asTransactionMeta = (res: any): TransactionMeta => {
isSuccess: res.success,
displayedTxType: findDisplayedTxType(res.tx_types),
value: parseUnits(res.value, res.decimals),
tokenTransfers: res.token_transfers.map(asTokenTransfer),
tokenTransfers: (res.token_transfers || []).map(asTokenTransfer),
gas: res.gas_used,
blockNumber: res.block_number,
};
};
Loading
Loading