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

Allow export token holders to CSV #1850

Merged
merged 1 commit into from
Apr 23, 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
6 changes: 6 additions & 0 deletions lib/api/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,12 @@ export const RESOURCES = {
path: '/api/v2/config/backend-version',
},

// CSV EXPORT
csv_export_token_holders: {
path: '/api/v2/tokens/:hash/holders/csv',
pathParams: [ 'hash' as const ],
},

// OTHER
api_v2_key: {
path: '/api/v2/key',
Expand Down
4 changes: 4 additions & 0 deletions types/client/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@ export type CsvExportParams = {
type: 'logs';
filterType?: 'topic';
filterValue?: string;
} | {
type: 'holders';
filterType?: undefined;
filterValue?: undefined;
}
25 changes: 13 additions & 12 deletions ui/csvExport/CsvExportForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ interface Props {
filterType?: CsvExportParams['filterType'] | null;
filterValue?: CsvExportParams['filterValue'] | null;
fileNameTemplate: string;
exportType: CsvExportParams['type'] | undefined;
}

const CsvExportForm = ({ hash, resource, filterType, filterValue, fileNameTemplate }: Props) => {
const CsvExportForm = ({ hash, resource, filterType, filterValue, fileNameTemplate, exportType }: Props) => {
const formApi = useForm<FormFields>({
mode: 'onBlur',
defaultValues: {
Expand All @@ -36,10 +37,10 @@ const CsvExportForm = ({ hash, resource, filterType, filterValue, fileNameTempla

const onFormSubmit: SubmitHandler<FormFields> = React.useCallback(async(data) => {
try {
const url = buildUrl(resource, undefined, {
const url = buildUrl(resource, { hash } as never, {
address_id: hash,
from_period: data.from,
to_period: data.to,
from_period: exportType !== 'holders' ? data.from : null,
to_period: exportType !== 'holders' ? data.to : null,
filter_type: filterType,
filter_value: filterValue,
recaptcha_response: data.reCaptcha,
Expand All @@ -56,11 +57,11 @@ const CsvExportForm = ({ hash, resource, filterType, filterValue, fileNameTempla
}

const blob = await response.blob();
downloadBlob(
blob,
`${ fileNameTemplate }_${ hash }_${ data.from }_${ data.to }
${ filterType && filterValue ? '_with_filter_type_' + filterType + '_value_' + filterValue : '' }.csv`,
);
const fileName = exportType === 'holders' ?
`${ fileNameTemplate }_${ hash }.csv` :
// eslint-disable-next-line max-len
`${ fileNameTemplate }_${ hash }_${ data.from }_${ data.to }${ filterType && filterValue ? '_with_filter_type_' + filterType + '_value_' + filterValue : '' }.csv`;
downloadBlob(blob, fileName);

} catch (error) {
toast({
Expand All @@ -73,7 +74,7 @@ const CsvExportForm = ({ hash, resource, filterType, filterValue, fileNameTempla
});
}

}, [ fileNameTemplate, hash, resource, filterType, filterValue, toast ]);
}, [ resource, hash, exportType, filterType, filterValue, fileNameTemplate, toast ]);

return (
<FormProvider { ...formApi }>
Expand All @@ -82,8 +83,8 @@ const CsvExportForm = ({ hash, resource, filterType, filterValue, fileNameTempla
onSubmit={ handleSubmit(onFormSubmit) }
>
<Flex columnGap={ 5 } rowGap={ 3 } flexDir={{ base: 'column', lg: 'row' }} alignItems={{ base: 'flex-start', lg: 'center' }} flexWrap="wrap">
<CsvExportFormField name="from" formApi={ formApi }/>
<CsvExportFormField name="to" formApi={ formApi }/>
{ exportType !== 'holders' && <CsvExportFormField name="from" formApi={ formApi }/> }
{ exportType !== 'holders' && <CsvExportFormField name="to" formApi={ formApi }/> }
<CsvExportFormReCaptcha formApi={ formApi }/>
</Flex>
<Button
Expand Down
51 changes: 26 additions & 25 deletions ui/pages/CsvExport.pw.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,39 @@
import { test, expect } from '@playwright/experimental-ct-react';
import { Box } from '@chakra-ui/react';
import React from 'react';

import * as addressMock from 'mocks/address/address';
import TestApp from 'playwright/TestApp';
import buildApiUrl from 'playwright/utils/buildApiUrl';
import * as tokenMock from 'mocks/tokens/tokenInfo';
import { test, expect } from 'playwright/lib';
import * as configs from 'playwright/utils/configs';

import CsvExport from './CsvExport';

const ADDRESS_API_URL = buildApiUrl('address', { hash: addressMock.hash });
const hooksConfig = {
router: {
query: { address: addressMock.hash, type: 'transactions', filterType: 'address', filterValue: 'from' },
isReady: true,
},
};

test.beforeEach(async({ page }) => {
await page.route(ADDRESS_API_URL, (route) => route.fulfill({
status: 200,
body: JSON.stringify(addressMock.withName),
}));
});
test('base view +@mobile +@dark-mode', async({ render, page, mockApiResponse }) => {
const hooksConfig = {
router: {
query: { address: addressMock.hash, type: 'transactions', filterType: 'address', filterValue: 'from' },
},
};
await mockApiResponse('address', addressMock.validator, { pathParams: { hash: addressMock.hash } });

const component = await render(<Box sx={{ '.recaptcha': { w: '304px', h: '78px' } }}><CsvExport/></Box>, { hooksConfig });

test('base view +@mobile +@dark-mode', async({ mount, page }) => {
await expect(component).toHaveScreenshot({
mask: [ page.locator('.recaptcha') ],
maskColor: configs.maskColor,
});
});

const component = await mount(
<TestApp>
<CsvExport/>
</TestApp>,
{ hooksConfig },
);
test('token holders', async({ render, page, mockApiResponse }) => {
const hooksConfig = {
router: {
query: { address: addressMock.hash, type: 'holders' },
},
};
await mockApiResponse('address', addressMock.token, { pathParams: { hash: addressMock.hash } });
await mockApiResponse('token', tokenMock.tokenInfo, { pathParams: { hash: addressMock.hash } });

await page.waitForResponse('https://www.google.com/recaptcha/api2/**');
const component = await render(<Box sx={{ '.recaptcha': { w: '304px', h: '78px' } }}><CsvExport/></Box>, { hooksConfig });

await expect(component).toHaveScreenshot({
mask: [ page.locator('.recaptcha') ],
Expand Down
59 changes: 51 additions & 8 deletions ui/pages/CsvExport.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { nbsp } from 'lib/html-entities';
import CsvExportForm from 'ui/csvExport/CsvExportForm';
import ContentLoader from 'ui/shared/ContentLoader';
import AddressEntity from 'ui/shared/entities/address/AddressEntity';
import TokenEntity from 'ui/shared/entities/token/TokenEntity';
import PageTitle from 'ui/shared/Page/PageTitle';

interface ExportTypeEntity {
Expand Down Expand Up @@ -53,6 +54,11 @@ const EXPORT_TYPES: Record<CsvExportParams['type'], ExportTypeEntity> = {
fileNameTemplate: 'logs',
filterType: 'topic',
},
holders: {
text: 'holders',
resource: 'csv_export_token_holders',
fileNameTemplate: 'holders',
},
};

const isCorrectExportType = (type: string): type is CsvExportParams['type'] => Object.keys(EXPORT_TYPES).includes(type);
Expand All @@ -75,6 +81,15 @@ const CsvExport = () => {
},
});

const tokenQuery = useApiQuery('token', {
pathParams: { hash: addressHash },
queryOptions: {
enabled: Boolean(addressHash) && exportTypeParam === 'holders',
},
});

const isLoading = addressQuery.isPending || (exportTypeParam === 'holders' && tokenQuery.isPending);

const backLink = React.useMemo(() => {
const hasGoBackLink = appProps.referrer && appProps.referrer.includes('/address');

Expand Down Expand Up @@ -111,31 +126,49 @@ const CsvExport = () => {
const content = (() => {
throwOnResourceLoadError(addressQuery);

if (addressQuery.isPending) {
if (isLoading) {
return <ContentLoader/>;
}

return (
<CsvExportForm
hash={ addressHash }
resource={ exportType.resource }
exportType={ isCorrectExportType(exportTypeParam) ? exportTypeParam : undefined }
filterType={ filterType }
filterValue={ filterValue }
fileNameTemplate={ exportType.fileNameTemplate }
/>
);
})();

return (
<>
<PageTitle
title="Export data to CSV file"
backLink={ backLink }
/>
const description = (() => {
if (isLoading) {
return null;
}

if (exportTypeParam === 'holders') {
return (
<Flex mb={ 10 } whiteSpace="pre-wrap" flexWrap="wrap">
<span>Export { exportType.text } for token </span>
<TokenEntity
token={ tokenQuery.data }
truncation={ isMobile ? 'constant' : 'dynamic' }
w="min-content"
noCopy
noSymbol
/>
<span> to CSV file. </span>
<span>Exports are limited to the last 10K { exportType.text }.</span>
</Flex>
);
}

return (
<Flex mb={ 10 } whiteSpace="pre-wrap" flexWrap="wrap">
<span>Export { exportType.text } for address </span>
<AddressEntity
address={{ hash: addressHash, is_contract: true, implementation_name: null }}
address={ addressQuery.data }
truncation={ isMobile ? 'constant' : 'dynamic' }
noCopy
/>
Expand All @@ -144,6 +177,16 @@ const CsvExport = () => {
<span>to CSV file. </span>
<span>Exports are limited to the last 10K { exportType.text }.</span>
</Flex>
);
})();

return (
<>
<PageTitle
title="Export data to CSV file"
backLink={ backLink }
/>
{ description }
{ content }
</>
);
Expand Down
29 changes: 28 additions & 1 deletion ui/pages/Token.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import * as tokenStubs from 'stubs/token';
import { getTokenHoldersStub } from 'stubs/token';
import { generateListStub } from 'stubs/utils';
import AddressContract from 'ui/address/AddressContract';
import AddressCsvExportLink from 'ui/address/AddressCsvExportLink';
import AddressQrCode from 'ui/address/details/AddressQrCode';
import AccountActionsMenu from 'ui/shared/AccountActionsMenu/AccountActionsMenu';
import TextAd from 'ui/shared/ad/TextAd';
Expand All @@ -45,6 +46,12 @@ import TokenVerifiedInfo from 'ui/token/TokenVerifiedInfo';

export type TokenTabs = 'token_transfers' | 'holders' | 'inventory';

const TABS_RIGHT_SLOT_PROPS = {
display: 'flex',
alignItems: 'center',
columnGap: 4,
};

const TokenPageContent = () => {
const [ isQueryEnabled, setIsQueryEnabled ] = React.useState(false);
const [ totalSupplySocket, setTotalSupplySocket ] = React.useState<number>();
Expand Down Expand Up @@ -294,6 +301,25 @@ const TokenPageContent = () => {
</Flex>
);

const tabsRightSlot = React.useMemo(() => {
if (isMobile) {
return null;
}

return (
<>
{ tab === 'holders' && (
<AddressCsvExportLink
address={ hashString }
params={{ type: 'holders' }}
isLoading={ pagination?.isLoading }
/>
) }
{ pagination?.isVisible && <Pagination { ...pagination }/> }
</>
);
}, [ hashString, isMobile, pagination, tab ]);

return (
<>
<TextAd mb={ 6 }/>
Expand Down Expand Up @@ -323,7 +349,8 @@ const TokenPageContent = () => {
<RoutedTabs
tabs={ tabs }
tabListProps={ tabListProps }
rightSlot={ !isMobile && pagination?.isVisible ? <Pagination { ...pagination }/> : null }
rightSlot={ tabsRightSlot }
rightSlotProps={ TABS_RIGHT_SLOT_PROPS }
stickyEnabled={ !isMobile }
/>
) }
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions ui/token/TokenHolders/TokenHolders.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import React from 'react';
import type { TokenInfo } from 'types/api/token';

import useIsMobile from 'lib/hooks/useIsMobile';
import AddressCsvExportLink from 'ui/address/AddressCsvExportLink';
import ActionBar from 'ui/shared/ActionBar';
import DataFetchAlert from 'ui/shared/DataFetchAlert';
import DataListDisplay from 'ui/shared/DataListDisplay';
Expand All @@ -27,6 +28,11 @@ const TokenHoldersContent = ({ holdersQuery, token }: Props) => {

const actionBar = isMobile && holdersQuery.pagination.isVisible && (
<ActionBar mt={ -6 }>
<AddressCsvExportLink
address={ token?.address }
params={{ type: 'holders' }}
isLoading={ holdersQuery.pagination.isLoading }
/>
<Pagination ml="auto" { ...holdersQuery.pagination }/>
</ActionBar>
);
Expand Down
Loading