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

Implement transactions list #17

Merged
merged 10 commits into from
Jul 1, 2024
Merged
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: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"@emotion/styled": "^11.10.6",
"@tanstack/react-query": "^5.40.0",
"@vocdoni/chakra-components": "~0.8.1",
"@vocdoni/extended-sdk": "^0.0.2",
"@vocdoni/extended-sdk": "^0.0.3",
"@vocdoni/sdk": "~0.8.1",
"date-fns": "^2.29.3",
"ethers": "^5.7.2",
Expand Down
1 change: 0 additions & 1 deletion src/components/Blocks/BlocksList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ export const PaginatedBlocksList = () => {
const totalPages = Math.ceil(count / PaginationItemsPerPage)

// Calculate the first block index for the current page
// todo(kon): when paginator is fixed, it won't be needed to do page - 1
const currentPage = page && page > 0 ? Number(page - 1) : 0
// Get the first block of the page
const firstPageIndex = count - currentPage * PaginationItemsPerPage
Expand Down
2 changes: 1 addition & 1 deletion src/components/TopBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const TopBar = () => {
},
{
name: t('links.transactions'),
url: '',
url: generatePath(RoutePath.TransactionsList, { page: null }),
},
{
name: t('links.validators'),
Expand Down
143 changes: 143 additions & 0 deletions src/components/Transactions/Detail.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { AdminTx, ensure0x, NewProcessTx, SetProcessTx, TransactionType, Tx, VoteEnvelope } from '@vocdoni/sdk'
import { Box, Card, CardBody, Code, Flex, Heading, Link, Text } from '@chakra-ui/react'
import { Trans } from 'react-i18next'
import ShowRawButton from '~src/layout/ShowRawButton'
import { useBlockToDate } from '~queries/stats'
import { generatePath, Link as RouterLink } from 'react-router-dom'
import { RoutePath } from '~constants'
import { useDateFns } from '~i18n/use-date-fns'
import { TransactionTypeBadge } from '~components/Transactions/TransactionCard'
import { b64ToHex, objectB64StringsToHex } from '~utils/objects'

export const TransactionDetail = (tx: Tx) => {
const { data } = useBlockToDate({ height: tx.txInfo.blockHeight })
const { formatDistance } = useDateFns()

let createdOn = ''
if (data) {
createdOn = formatDistance(new Date(data.date), new Date())
}

const blockHeight = tx.txInfo.blockHeight
const txIndex = tx.txInfo.transactionIndex

let entity = ''
let process = ''
let votePackage = ''

if (!tx.tx) return

const txPayload = tx.tx as any
const txType = Object.keys(tx.tx)[0] as TransactionType

// For some reason, response payload converted transactions have some
// values into base64 string. This values, on the interface declaration are
// `Uint8Array`, but on JSON decoding are treated as 'strings'.
// So is a little bit tricky to know if a payload value have to be
// converted to a b64 or not. Probably reflection could help with that. BTW
// is solved checking regex.

const rawTx = JSON.parse(JSON.stringify(tx))
objectB64StringsToHex(rawTx, ['txInfo'])

switch (txType) {
case 'vote': {
const voteTx = txPayload.vote as VoteEnvelope
if (voteTx.votePackage) {
// Decode the vote package from base64
votePackage = atob(voteTx.votePackage)
// And copy it alsow to rawTx
rawTx['tx']['vote']['votePackage'] = JSON.parse(votePackage)
}
process = ensure0x(b64ToHex(voteTx.processId))
break
}
case 'newProcess': {
const newProcessTx = txPayload.newProcess as NewProcessTx
if (newProcessTx.process) {
process = ensure0x(b64ToHex(newProcessTx.process.processId as unknown as string))
entity = ensure0x(b64ToHex(newProcessTx.process.entityId as unknown as string))
}
break
}
case 'admin': {
const adminTx = txPayload.admin as AdminTx
process = ensure0x(b64ToHex(adminTx.processId as unknown as string))
break
}
case 'setProcess': {
const setProcessTx = txPayload.setProcess as SetProcessTx
process = ensure0x(b64ToHex(setProcessTx.processId as unknown as string))

if (setProcessTx?.results) {
entity = ensure0x(b64ToHex(setProcessTx.results.entityId as unknown as string))
}
break
}
}

return (
<Flex direction={'column'} mt={'40px'} gap={6}>
<Heading isTruncated wordBreak='break-word'>
<Trans i18nKey={'transactions.tx_detail'}>Transaction Details</Trans>
</Heading>
<Box>
<TransactionTypeBadge transactionType={txType} />
</Box>
<Link as={RouterLink} to={generatePath(RoutePath.Block, { height: blockHeight.toString() })}>
<Text color={'blueText'} fontSize={'2xl'}>
<Trans i18nKey={'transactions.on_block_n'} height={blockHeight}>
On Block {{ height: blockHeight }}
</Trans>
</Text>
</Link>
<Text color={'lightText'}>
<Trans i18nKey={'transactions.transaction_index'} txIndex={txIndex}>
Transaction index: {{ txIndex }}
</Trans>
</Text>
<Text color={'lightText'}>
<Trans i18nKey={'transactions.created_on'} createdOn={createdOn}>
Created {{ createdOn }}
</Trans>
</Text>

<Card>
<CardBody>
<Text fontSize={'xl'}>{ensure0x(tx.txInfo.transactionHash)}</Text>
{process && (
<Text>
<Trans
i18nKey={'transactions.belongs_to_process'}
components={{
a: <Link as={RouterLink} to={generatePath(RoutePath.Process, { pid: process })} />,
}}
values={{ process }}
/>
</Text>
)}
{entity && (
<Text>
<Trans
i18nKey={'transactions.belong_to_organization'}
components={{
a: <Link as={RouterLink} to={generatePath(RoutePath.Organization, { pid: entity })} />,
}}
values={{ organization: entity }}
/>
</Text>
)}
{votePackage && (
<>
<Text>
<Trans i18nKey={'transactions.vote_package'}>Vote package:</Trans>
</Text>
<Code>{votePackage}</Code>
</>
)}
</CardBody>
</Card>
<ShowRawButton obj={rawTx} />
</Flex>
)
}
54 changes: 54 additions & 0 deletions src/components/Transactions/TransactionCard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Box, Card, CardBody, Flex, Link, Tag, Text } from '@chakra-ui/react'
import { Trans } from 'react-i18next'
import { ReducedTextAndCopy } from '~components/CopyButton'
import { IChainTxReference, TransactionType } from '@vocdoni/sdk'
import React from 'react'
import { generatePath, Link as RouterLink } from 'react-router-dom'
import { RoutePath } from '~constants'

export const TransactionTypeBadge = ({ transactionType }: { transactionType: TransactionType }) => {
return (
<Tag bg={'#f3fccc'} color={'#74af07'} variant={'vocdoni'}>
{transactionType}
</Tag>
)
}

export const TransactionCard = ({
transactionIndex,
transactionType,
transactionNumber,
transactionHash,
blockHeight,
}: IChainTxReference) => {
return (
<Card>
<Link
as={RouterLink}
to={generatePath(RoutePath.Transaction, {
block: blockHeight.toString(),
index: transactionIndex.toString(),
})}
>
<CardBody>
<Flex gap={1} direction={'column'}>
<Flex gap={3} direction={'column'}>
<Box>
<TransactionTypeBadge transactionType={transactionType} />
</Box>
<Text fontWeight='bold'># {transactionNumber}</Text>
</Flex>
<Box fontSize={'sm'}>
<Flex gap={2} align={'center'}>
<Trans i18nKey='blocks.proposer'>Hash:</Trans>
<ReducedTextAndCopy color={'textAccent1'} toCopy={transactionHash}>
{transactionHash}
</ReducedTextAndCopy>
</Flex>
</Box>
</Flex>
</CardBody>
</Link>
</Card>
)
}
63 changes: 63 additions & 0 deletions src/components/Transactions/TransactionList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { generatePath, useNavigate, useParams } from 'react-router-dom'
import { RoutedPagination } from '~components/Pagination/Pagination'
import { RoutedPaginationProvider } from '~components/Pagination/PaginationProvider'
import { PaginationItemsPerPage, RoutePath } from '~constants'
import { LoadingCards } from '~src/layout/Loading'
import LoadingError from '~src/layout/LoadingError'
import { useTransactionList, useTransactionsCount } from '~queries/transactions'
import { TransactionCard } from '~components/Transactions/TransactionCard'
import { useTranslation } from 'react-i18next'
import { InputSearch } from '~src/layout/Inputs'

export const TransactionFilter = () => {
const { t } = useTranslation()
const navigate = useNavigate()
const { data, isLoading: isLoadingCount } = useTransactionsCount()

return (
<InputSearch
maxW={'300px'}
placeholder={t('transactions.search_tx')}
onChange={(value: string) => {
if (!data) {
return
}
const num = parseInt(value)
let page = 0 // By default return to first page
if (!isNaN(num) && num >= 0) {
page = Math.ceil((data - num + 1) / PaginationItemsPerPage)
}
navigate(generatePath(RoutePath.TransactionsList, { page: page.toString() }))
}}
debounceTime={500}
type={'number'}
/>
)
}

export const PaginatedTransactionList = () => {
const { page }: { page?: number } = useParams()
const { data: count, isLoading: isLoadingCount } = useTransactionsCount()

const totalPages = Math.ceil(count / PaginationItemsPerPage)

const currentPage = page && page > 0 ? Number(page - 1) : 0
const { data, isLoading: isLoadingTx, isError, error } = useTransactionList({ page: currentPage })

const isLoading = isLoadingCount || isLoadingTx

return (
<>
{isLoading && <LoadingCards />}
{!data || data?.transactions.length === 0 || (isError && <LoadingError error={error} />)}
{data && data.transactions.length > 0 && (
<RoutedPaginationProvider totalPages={totalPages} path={RoutePath.TransactionsList}>
{data.transactions.map((tx, i) => (
<TransactionCard key={i} {...tx} />
))}
<RoutedPagination />
</RoutedPaginationProvider>
)}
</>
)
}
5 changes: 5 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,9 @@ export enum RoutePath {
OrganizationsList = '/organizations/:page?/:query?',
Process = '/process/:pid',
ProcessesList = '/processes/:page?',
Transaction = '/transactions/:block/:index',
TransactionsList = '/transactions/:page?',
}

// Used to test if a string is base64 encoded. Used by b64ToHex
export const isB64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/
Loading
Loading