Skip to content

Commit

Permalink
feat: refactored clientLoader, useState order
Browse files Browse the repository at this point in the history
  • Loading branch information
tuul-wq committed Jul 2, 2024
1 parent bd2d76b commit ab2994b
Show file tree
Hide file tree
Showing 16 changed files with 92 additions and 73 deletions.
22 changes: 11 additions & 11 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,24 @@ import { setupStaticController } from './static.js';

const app = express();

const production = process.env.NODE_ENV === 'production';
const isProd = process.env.NODE_ENV === 'production';

// Special permission for mercuryo widget
if (production) {
app.use(
expressCspHeader({
directives: {
'frame-src': [SELF, 'https://widget.mercuryo.io'],
'frame-ancestors': [SELF, 'https://widget.mercuryo.io'],
},
}),
);
if (isProd) {
const mercurioHandler = expressCspHeader({
directives: {
'frame-src': [SELF, 'https://widget.mercuryo.io'],
'frame-ancestors': [SELF, 'https://widget.mercuryo.io'],
},
});

app.use(mercurioHandler);
}

app.disable('x-powered-by');

setupHealthcheckController(app);
await setupStaticController(app, production);
await setupStaticController(app, isProd);

const port = process.env.PORT || 3000;
app.listen(port, '0.0.0.0', () => {
Expand Down
1 change: 1 addition & 0 deletions server/static.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createRequestHandler } from '@remix-run/express';

/**
* @param {import('express').Application} app
* @param {boolean} production
*/
export const setupStaticController = async (app, production) => {
const viteDevServer = production
Expand Down
12 changes: 5 additions & 7 deletions src/app/routes/exchange/select.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Link, useNavigate } from 'react-router-dom';

import { type LoaderFunction, json } from '@remix-run/node';
import { useLoaderData } from '@remix-run/react';
import { type ClientLoaderFunction, useLoaderData } from '@remix-run/react';
import { $path } from 'remix-routes';

import { useGlobalContext } from '@/common/providers';
Expand All @@ -18,15 +17,14 @@ const skippedBuyAssets = ['WND', 'USDT'];
export const clientLoader = (({ request }) => {
const url = new URL(request.url);

return json({
type: url.searchParams.get('type') || '',
});
}) satisfies LoaderFunction;
return { type: url.searchParams.get('type') || '' };
}) satisfies ClientLoaderFunction;

const Page = () => {
const { type } = useLoaderData<typeof clientLoader>();

const navigate = useNavigate();
const { assets } = useGlobalContext();
const { type } = useLoaderData<typeof clientLoader>();

const exchangeAssets = assets.filter(i => !skippedBuyAssets.includes(i.asset.symbol));

Expand Down
3 changes: 2 additions & 1 deletion src/app/routes/exchange/widget.$chainId.$assetId.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,11 @@ export const clientLoader = (async ({ params, serverLoader }) => {
}) satisfies ClientLoaderFunction;

const Page = () => {
const { chainId, assetId, mercuryoSecret, mercuryoWidgetId } = useLoaderData<typeof clientLoader>();

const navigate = useNavigate();
const { webApp } = useTelegram();
const { assets } = useGlobalContext();
const { chainId, assetId, mercuryoSecret, mercuryoWidgetId } = useLoaderData<typeof clientLoader>();

const [root, setRoot] = useState<HTMLElement | null>(null);
const [done, setDone] = useState(false);
Expand Down
21 changes: 11 additions & 10 deletions src/app/routes/gifts/details.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { BackButton } from '@/common/telegram/BackButton';
import { type TgLink } from '@/common/telegram/types.ts';
import { GiftDetails, Icon } from '@/components';

// Query params for /gifts/details?seed=__value__&symbol=__value&balance=__value__
export type SearchParams = {
seed: string;
symbol: string;
Expand All @@ -28,21 +29,21 @@ const Page = () => {
const { botUrl, appName } = useLoaderData<typeof loader>();

const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { webApp } = useTelegram();
const [searchParams] = useSearchParams();

const [link, setLink] = useState<TgLink | null>(null);

useEffect(() => {
setLink(
createTgLink({
secret: searchParams.get('seed') as string,
symbol: searchParams.get('symbol') as string,
amount: searchParams.get('balance') as string,
botUrl,
appName,
}),
);
const tgLink = createTgLink({
secret: searchParams.get('seed') as string,
symbol: searchParams.get('symbol') as string,
amount: searchParams.get('balance') as string,
botUrl,
appName,
});

setLink(tgLink);
}, []);

const canShowGifDetails = Boolean(link) && Boolean(webApp);
Expand Down
3 changes: 2 additions & 1 deletion src/app/routes/onboarding/restore.$mnemonic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ export const clientLoader = (({ params }) => {
}) satisfies ClientLoaderFunction;

const Page = () => {
const { mnemonic } = useLoaderData<typeof clientLoader>();

const navigate = useNavigate();
const { user } = useTelegram();
const { mnemonic } = useLoaderData<typeof clientLoader>();
const { setPublicKey } = useGlobalContext();

const [password, setPassword] = useState('');
Expand Down
3 changes: 2 additions & 1 deletion src/app/routes/settings/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ export const loader = () => {
};

const Page = () => {
const { version } = useLoaderData<typeof loader>();

const navigate = useNavigate();
const { webApp } = useTelegram();
const { version } = useLoaderData<typeof loader>();

const [isPopoverCurrencyOpen, setIsPopoverCurrencyOpen] = useState(false);
const [isPopoverLanguageOpen, setIsPopoverLanguageOpen] = useState(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const Page = () => {
const { chainId, assetId, amount, address } = useLoaderData<typeof clientLoader>();

const navigate = useNavigate();
const { sendTransaction } = useExtrinsic();
const { sendTransfer } = useExtrinsic();
const { getAssetHubFee } = useAssetHub();
const { assets } = useGlobalContext();

Expand All @@ -45,23 +45,20 @@ const Page = () => {
}, []);

const mainCallback = () => {
if (!selectedAsset) {
return;
}
if (!selectedAsset) return;

sendTransaction({
sendTransfer({
destinationAddress: address,
chainId: chainId as ChainId,
transferAll: false,
transferAmount: formatAmount(amount, selectedAsset.asset!.precision),
asset: selectedAsset.asset,
})
.then(() => {
navigate(
$path('/transfer/direct/:chainId/:assetId/:address/:amount/result', { chainId, assetId, amount, address }),
);
const params = { chainId, assetId, amount, address };
navigate($path('/transfer/direct/:chainId/:assetId/:address/:amount/result', params));
})
.catch(error => alert(`Error: ${error.message}\nTry to relaod`));
.catch(error => alert(`Error: ${error.message}\nTry to reload`));
};

const symbol = selectedAsset?.asset?.symbol;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export const clientLoader = (({ params }) => {

const Page = () => {
const { address, amount, assetId, chainId } = useLoaderData<typeof clientLoader>();

const navigate = useNavigate();
const { assets } = useGlobalContext();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { pickAsset } from '@/common/utils';
import { HeadlineText, Identicon, TruncateAddress } from '@/components';
import { AmountDetails } from '@/components/AmountDetails';

// Query params for /transfer/direct/:chainId/:assetId/amount?amount=__value__
export type SearchParams = {
amount: string;
};
Expand All @@ -26,9 +27,10 @@ export const clientLoader = (({ params, request }) => {
}) satisfies ClientLoaderFunction;

const Page = () => {
const { chainId, assetId, address, amount: transferAmount } = useLoaderData<typeof clientLoader>();

const navigate = useNavigate();
const { assets } = useGlobalContext();
const { chainId, assetId, address, amount: transferAmount } = useLoaderData<typeof clientLoader>();

const selectedAsset = pickAsset(chainId, assetId, assets);

Expand All @@ -44,25 +46,21 @@ const Page = () => {
isAmountValid,
} = useAmountLogic({ selectedAsset });

// Set amount from query params (Mercurio page does this)
// Set amount from query params (/exchange/widget Mercurio page does this)
useEffect(() => {
handleChange(transferAmount);
}, [transferAmount]);

const navigateToConfirm = () => {
const params = { chainId, assetId, address, amount };
navigate($path('/transfer/direct/:chainId/:assetId/:address/:amount/confirmation', params));
};

return (
<>
<MainButton
disabled={!isAmountValid || !Number(fee) || isAccountTerminate || isPending}
onClick={() => {
navigate(
$path('/transfer/direct/:chainId/:assetId/:address/:amount/confirmation', {
chainId,
assetId,
address,
amount,
}),
);
}}
onClick={navigateToConfirm}
/>
<BackButton onClick={() => navigate($path('/transfer/direct/:chainId/:assetId/address', { chainId, assetId }))} />
<div className="grid grid-cols-[40px,1fr,auto] items-center">
Expand Down
10 changes: 9 additions & 1 deletion src/app/routes/transfer/gift/$chainId.$assetId/amount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export const clientLoader = (({ params }) => {

const Page = () => {
const { chainId, assetId } = useLoaderData<typeof clientLoader>();

const { assets } = useGlobalContext();
const navigate = useNavigate();

Expand Down Expand Up @@ -46,13 +47,20 @@ const Page = () => {
setIsAmountValid(Boolean(maxAmountToSend) && +maxAmountToSend >= deposit);
};

const navigateToCreate = () => {
const params = { chainId, assetId };
const query = { amount, fee: (fee || '0').toString() };

navigate($path('/transfer/gift/:chainId/:assetId/create', params, query));
};

return (
<>
<MainButton
text="Create gift"
disabled={!isAmountValid || !Number(fee) || isAccountTerminate}
progress={isPending}
onClick={() => navigate($path('/transfer/gift/:chainId/:assetId/:amount/create', { chainId, assetId, amount }))}
onClick={navigateToCreate}
/>
<BackButton onClick={() => navigate($path('/transfer/gift/token-select'))} />
<div className="grid grid-cols-[40px,1fr,auto] items-center">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,38 @@ import { backupGifts, pickAsset } from '@/common/utils';
import { createGiftWallet } from '@/common/wallet';
import { GiftDetails, HeadlineText, LottiePlayer } from '@/components';

// Query params for /transfer/gift/:chainId/:assetId/create?amount=__value__&fee=__value__
export type SearchParams = {
amount: string;
fee: string;
};

export const loader = (() => {
return json({
botUrl: process.env.PUBLIC_BOT_ADDRESS,
appName: process.env.PUBLIC_WEB_APP_ADDRESS,
});
}) satisfies LoaderFunction;

export const clientLoader = (async ({ params, serverLoader }) => {
export const clientLoader = (async ({ request, params, serverLoader }) => {
const serverData = await serverLoader<typeof loader>();
const data = $params('/transfer/gift/:chainId/:assetId/:amount/create', params);

const url = new URL(request.url);
const data = {
...$params('/transfer/gift/:chainId/:assetId/create', params),
amount: url.searchParams.get('amount') || '0',
fee: Number(url.searchParams.get('fee') || 0),
};

return { ...serverData, ...data };
}) satisfies ClientLoaderFunction;

const Page = () => {
const { botUrl, appName, chainId, assetId, amount, fee } = useLoaderData<typeof clientLoader>();

const { webApp } = useTelegram();
const { sendGift } = useExtrinsic();
const { assets } = useGlobalContext();
const { botUrl, appName, chainId, assetId, amount } = useLoaderData<typeof clientLoader>();

const [loading, setLoading] = useState(true);
const [link, setLink] = useState<TgLink | null>(null);
Expand All @@ -47,15 +60,15 @@ const Page = () => {

const giftWallet = createGiftWallet(selectedAsset.addressPrefix);

sendGift(selectedAsset, giftWallet.address)
sendGift({ ...selectedAsset, amount, fee }, giftWallet.address)
.then(() => {
backupGifts(giftWallet.address, giftWallet.secret, selectedAsset as TransferAsset);
const tgLink = createTgLink({
botUrl,
appName,
amount,
secret: giftWallet.secret,
symbol: selectedAsset?.asset?.symbol as string,
symbol: selectedAsset.asset.symbol,
});

setLink(tgLink);
Expand Down
7 changes: 3 additions & 4 deletions src/common/_temp_hooks/useAmountLogic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ import { type TransferAsset } from '@/common/types';
import { formatAmount, formatBalance, isStatemineAsset } from '@/common/utils';
import { useAssetHub } from '@/common/utils/hooks/useAssetHub.ts';

type AmountPageLogic = {
type AmountLogicParams = {
selectedAsset?: TransferAsset;
};

export function useAmountLogic({ selectedAsset }: AmountPageLogic) {
export function useAmountLogic({ selectedAsset }: AmountLogicParams) {
const { getAssetHubFee } = useAssetHub();
const { getTransactionFee } = useExtrinsic();
const { getExistentialDeposit, getExistentialDepositStatemine } = useQueryService();
const { getAssetHubFee } = useAssetHub();

const [amount, setAmount] = useState<string>(selectedAsset?.amount || '');
const [fee, setFee] = useState<number>();
Expand Down Expand Up @@ -73,7 +73,6 @@ export function useAmountLogic({ selectedAsset }: AmountPageLogic) {
.then(({ fee, formattedDeposit }) => {
setFee(fee);
setDeposit(formattedDeposit);
// setSelectedAsset(prev => ({ ...prev, fee }));
})
.finally(() => {
setPending(false);
Expand Down
2 changes: 1 addition & 1 deletion src/common/chainRegistry/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ export type Asset = {
precision: number;
priceId?: string;
type?: string;
name?: string;
typeExtras?: {
assetId: string;
};
name?: string;
};

export type Chain = {
Expand Down
Loading

0 comments on commit ab2994b

Please sign in to comment.