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

Feat: Multiple tokens form #17

Closed
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 package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@hookform/resolvers": "^3.3.4",
"@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-switch": "^1.0.3",
"@tanstack/react-query": "5.24.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
Expand Down
122 changes: 122 additions & 0 deletions pnpm-lock.yaml

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

81 changes: 55 additions & 26 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@ import { Textarea } from '@/components/ui/textarea';
import { toast } from 'sonner';
import dictionary from '@/dictionary/en.json';
import { TokenDetails } from '@/types/tokenDetails-response';
import { HoldersForm } from '@/components/HoldersForm';
import { FormData, HoldersForm } from '@/components/HoldersForm';
import { Switch } from '@/components/ui/switch';

const App = () => {
const [tokenDetails, setTokenDetails] = useState<TokenDetails>();
const [tokenId, setTokenId] = useState<string>('');
const [minAmount, setMinAmount] = useState<number | null>(null);
const [formData, setFormData] = useState<FormData['formData']>([]);
const [data, setData] = useState<Balance[]>([]);
const [shouldFetch, setShouldFetch] = useState(false);
const [responses, setResponses] = useState<Balance[][]>([]);
const [shouldFetch, setShouldFetch] = useState<boolean>(false);
const [isAllConditionsRequired, setIsAllConditionsRequired] = useState<boolean>(true);

const copyToClipboard = async (textToCopy: string) => {
if (navigator.clipboard && window.isSecureContext) {
Expand All @@ -43,7 +45,7 @@ const App = () => {
}
};

const createFetchUrl = () => {
const createFetchUrl = (tokenId: string, minAmount: string) => {
if (Boolean(tokenDetails?.type === 'FUNGIBLE_COMMON')) {
// Move digits to the right to match the token's decimals
const amount = Number(minAmount) * Math.pow(10, Number(tokenDetails?.decimals));
Expand All @@ -53,22 +55,48 @@ const App = () => {
return `${nodeUrl}/api/v1/tokens/${tokenId}/balances?account.balance=gte:${minAmount}&limit=100`;
};

const fetchData = async (url: string) => {
try {
const response = await fetch(url);
const filterData = (responses: Balance[][], isAllConditionsRequired: boolean): Balance[] => {
let data = responses.flatMap((response) => response);

if (!response.ok) {
throw new Error(`${dictionary.httpError} ${response.status}`);
}
if (isAllConditionsRequired) {
return data.filter(
(balance, index, self) =>
self.findIndex((b) => b.account === balance.account) === index &&
responses.every((response) => response.some((b) => b.account === balance.account)),
);
} else {
return data.filter((balance, index, self) => self.findIndex((b) => b.account === balance.account) === index);
}
};
Comment on lines +58 to +70

Choose a reason for hiding this comment

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

Maybe write a unit test for it


const fetchData = async (url: string): Promise<Balance[]> => {
const response = await fetch(url);

const data = await response.json();
if (!response.ok) {
throw new Error(`${dictionary.httpError} ${response.status}`);
}

setData((prevData: Balance[]) => [...prevData, ...data?.balances]);
const data = await response.json();

if (data.links.next) {
await fetchData(`${nodeUrl}${data.links.next}`);
}
let nextData: Balance[] = [];
if (data.links.next) {
nextData = await fetchData(`${nodeUrl}${data.links.next}`);
}

return [...data.balances, ...nextData];
};

const fetchAllData = async () => {
try {
const responses = await Promise.all(
formData.map(async (item) => {
const { tokenId, minAmount } = item;
return fetchData(createFetchUrl(tokenId, minAmount));
}),
);

setResponses(responses);
setData(filterData(responses, isAllConditionsRequired));
return data;
} catch (error) {
throw error;
Expand All @@ -80,7 +108,7 @@ const App = () => {
retry: 0,
throwOnError: false,
queryKey: ['balancesList'],
queryFn: () => fetchData(createFetchUrl()),
queryFn: () => fetchAllData(),
});

useEffect(() => {
Expand All @@ -97,21 +125,22 @@ const App = () => {
if (!isFetching && isFetched) setShouldFetch(false);
}, [isFetched, isFetching]);

useEffect(() => {
setData(filterData(responses, isAllConditionsRequired));
}, [isAllConditionsRequired]);

return (
<div className="container mx-auto">
<h1 className="mt-20 scroll-m-20 text-center text-4xl font-extrabold tracking-tight lg:text-5xl">{dictionary.title}</h1>
<p className="text-center leading-7 [&:not(:first-child)]:mt-6">{dictionary.description}</p>

<div className="mt-5 flex items-center justify-center space-x-2">
<Switch id="isAllConditionsRequired" onCheckedChange={setIsAllConditionsRequired} checked={isAllConditionsRequired} />
<Label htmlFor="isAllConditionsRequired">{dictionary.isAllConditionsRequiredLabel}</Label>
</div>

<div className="mb-20 mt-5">
<HoldersForm
setTokenId={setTokenId}
setMinAmount={setMinAmount}
setData={setData}
setShouldFetch={setShouldFetch}
setTokenDetails={setTokenDetails}
tokenDetails={tokenDetails}
isBalancesFetching={isFetching}
/>
<HoldersForm setFormData={setFormData} setData={setData} setShouldFetch={setShouldFetch} isBalancesFetching={isFetching} setTokenDetails={setTokenDetails} tokenDetails={tokenDetails} />
</div>

{isFetched || isFetching ? (
Expand Down
Loading