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: add balance logic #20

Merged
merged 3 commits into from
Dec 14, 2023
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
Binary file removed src/common/assets/fonts/Inter/Inter-400.woff2
Binary file not shown.
Binary file removed src/common/assets/fonts/Inter/Inter-500.woff2
Binary file not shown.
Binary file removed src/common/assets/fonts/Inter/Inter-600.woff2
Binary file not shown.
Binary file removed src/common/assets/fonts/Inter/Inter-800.woff2
Binary file not shown.
8 changes: 0 additions & 8 deletions src/common/chainRegistry/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,6 @@ export type Asset = {
precision: number;
};

export type AssetWithBalance = Asset & {
name: string;
balance: string;
assetId: number;
symbol: string;
precision: number;
};

export type Chain = {
chainId: ChainId;
name: string;
Expand Down
13 changes: 10 additions & 3 deletions src/common/providers/contextProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
import React, { createContext, useContext, useState } from 'react';
import { HexString } from '../types';
import { AssetAccount, HexString } from '../types';

export interface IContext {
publicKey?: HexString;
assets: AssetAccount[] | [];
setPublicKey: React.Dispatch<React.SetStateAction<HexString | undefined>>;
setAssets: React.Dispatch<React.SetStateAction<AssetAccount[]>>;
}

export const GlobalContext = createContext<IContext>({ setPublicKey: () => {} });
export const GlobalContext = createContext<IContext>({
assets: [],
setPublicKey: () => {},
setAssets: () => {},
});

export const GlobalStateProvider = ({ children }: { children: React.ReactNode }) => {
const [publicKey, setPublicKey] = useState<HexString>();
const [assets, setAssets] = useState<AssetAccount[]>([]);

const value = { publicKey, setPublicKey };
const value = { publicKey, assets, setPublicKey, setAssets };

return <GlobalContext.Provider value={value}>{children}</GlobalContext.Provider>;
};
Expand Down
9 changes: 9 additions & 0 deletions src/common/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ export type ChainAssetAccount = {
chainId: ChainId;
assetId: AssetId;
publicKey: PublicKey;
symbol: string;
name: string;
precision: number;
};

export type AssetAccount = ChainAssetAccount & {
address: Address;
totalBalance?: string;
transferableBalance?: string;
};

export type StateResolution<T> = { resolve: (value: T) => void; reject: () => void };
Expand Down
15 changes: 15 additions & 0 deletions src/common/utils/balance.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import BigNumber from 'bignumber.js';
import { AssetAccount } from '../types';
import { Chain } from '../chainRegistry/types';
import { IAssetBalance } from '../balances/types';

const ZERO_BALANCE = '0';

Expand Down Expand Up @@ -122,3 +125,15 @@ export const formatFiatBalance = (balance = '0', precision = 0): FormattedBalanc
decimalPlaces,
};
};

export const updateAssetsBalance = (prevAssets: AssetAccount[], chain: Chain, balance: IAssetBalance) => {
return prevAssets.map((asset) =>
asset?.chainId === chain.chainId
? {
...asset,
totalBalance: balance.total().toString(),
transferableBalance: balance.transferable().toString(),
}
: asset,
);
};
8 changes: 3 additions & 5 deletions src/common/wallet/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,9 @@ export const resetWallet = () => {
window.Telegram.WebApp.CloudStorage.removeItem(MNEMONIC_STORE);
};

export const initializeWalletFromCloud = (password: string, encryptedMnemonic: string): boolean => {
export const initializeWalletFromCloud = (password: string, encryptedMnemonic: string): Wallet | null => {
const mnemonic = AES.decrypt(encryptedMnemonic, password).toString(CryptoJS.enc.Utf8);
if (!mnemonic) return false;
if (!mnemonic) return null;

createWallet(mnemonic);

return true;
return createWallet(mnemonic);
};
23 changes: 14 additions & 9 deletions src/components/AssetsList/Asset.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,33 @@
import { cnTw } from '@/common/utils/twMerge';
import { formatBalance } from '@/common/utils/balance';
import Icon from '../Icon/Icon';
import { CaptionText } from '../Typography';

import { Shimmering, CaptionText, Icon } from '@/components';

type Props = {
value: string;
asset: any;
balance?: string;
name?: string;
className?: string;
showIcon?: boolean;
imgClassName?: string;
wrapperClassName?: string;
};

export const AssetBalance = ({ value, asset, className, imgClassName }: Props) => {
export const AssetBalance = ({ balance, asset, name, className, imgClassName }: Props) => {
const { precision, symbol } = asset;
const { formattedValue, suffix } = formatBalance(value, precision);
const { formattedValue, suffix } = formatBalance(balance, precision);

return (
<span className={cnTw('flex items-center gap-x-2', className)}>
<Icon name={symbol} size={40} alt="logo" className={imgClassName} />
<Icon name={symbol} size={40} alt={name} className={imgClassName} />
<CaptionText>{symbol}</CaptionText>
<CaptionText>
{formattedValue} {suffix}
</CaptionText>
{balance === undefined ? (
<Shimmering width={100} height={20} />
) : (
<CaptionText>
{formattedValue} {suffix}
</CaptionText>
)}
</span>
);
};
34 changes: 18 additions & 16 deletions src/components/AssetsList/AssetsList.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
import { AssetWithBalance } from '@/common/chainRegistry/types';
import { useGlobalContext } from '@/common/providers/contextProvider';
import { AssetBalance } from './Asset';

type Props = {
assets: AssetWithBalance[];
};
const AssetsList = () => {
const { assets } = useGlobalContext();
const sortedAssets = assets.sort((a, b) => a.symbol.localeCompare(b.symbol));

const AssetsList = ({ assets }: Props) => (
<div className="flex flex-col gap-6 mt-4">
{assets.map((asset) => (
<AssetBalance
asset={asset}
value={asset.balance}
className="grid grid-cols-[50px,1fr,auto] items-center"
key={asset.assetId}
/>
))}
</div>
);
return (
<div className="flex flex-col gap-6 mt-4">
{sortedAssets.map((asset) => (
<AssetBalance
asset={asset}
balance={asset.totalBalance}
className="grid grid-cols-[50px,1fr,auto] items-center"
name={asset.name}
key={asset.chainId}
/>
))}
</div>
);
};

export default AssetsList;
2 changes: 1 addition & 1 deletion src/components/PasswordForm/PasswordForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export default function PasswordForm({ onSubmit }: PasswordFormProps) {
onClear={() => setConfirmPassword('')}
/>
<BodyText align="left" as="span" className={cnTw('self-start mt-4', VariantStyles[hintColor])}>
<ul className="list-disc space-y-1 ml-5 mb-1">
<ul className="list-disc space-y-1 ml-5 mb-1">
<li>8 characters minimum</li>
<li>Include at least 1 number (0-9)</li>
<li>Include at least 1 letter (a-z)</li>
Expand Down
18 changes: 18 additions & 0 deletions src/components/Shimmering/Shimmering.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { cnTw } from '@/common/utils/twMerge';

type Props = {
width?: number;
height?: number;
circle?: boolean;
className?: string;
};

const Shimmering = ({ width, height, circle, className }: Props) => (
<span
className={cnTw('h-full w-full block spektr-shimmer', circle ? 'rounded-full' : 'rounded-[10px]', className)}
style={{ width: `${width}px`, height: `${circle ? width : height}px` }}
data-testid="shimmer"
/>
);

export default Shimmering;
2 changes: 2 additions & 0 deletions src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import Price from './Price/Price';
import AssetsList from './AssetsList/AssetsList';
import Plate from './Plate/Plate';
import PasswordForm from './PasswordForm/PasswordForm';
import Shimmering from './Shimmering/Shimmering';

export {
FootnoteText,
Expand All @@ -28,4 +29,5 @@ export {
AssetsList,
Plate,
PasswordForm,
Shimmering,
};
3 changes: 2 additions & 1 deletion src/pages/globals.css
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
@import '../styles/fonts.css';
@import '../styles/Shimmering.css';

@tailwind base;
@tailwind components;
Expand Down Expand Up @@ -98,4 +99,4 @@ body {
--white-white900: #ffffff;

--pink-pink600: #ff007a;
}
}
2 changes: 1 addition & 1 deletion src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default function App() {

useEffect(() => {
setPublicKey(wallet?.publicKey);
}, [wallet]);
}, []);

return wallet ? <DashboardMainPage /> : <OnboardingStartPage />;
}
2 changes: 1 addition & 1 deletion src/pages/onboarding/create-wallet/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default function CreateWalletPage() {
MainButton?.show();
MainButton?.setText('Get started');
MainButton?.hideProgress();
}, 2500);
}, 3000);

return () => {
MainButton?.setText('Continue');
Expand Down
49 changes: 16 additions & 33 deletions src/screens/dashboard/main/DashboardMain.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,63 +15,46 @@ import { Paths } from '@/common/routing';
import { useGlobalContext } from '@/common/providers/contextProvider';
import { useTelegram } from '@/common/providers/telegramProvider';
import { BodyText, CaptionText, Icon, AssetsList, Plate, Price } from '@/components';

// TODO: remove temp mock
const mockAssets = [
{
name: 'polkadot',
symbol: 'DOT',
balance: '0',
assetId: 123,
precision: 10,
},
{
name: 'kusama',
symbol: 'KSM',
balance: '0',
assetId: 234,
precision: 5,
},
{
name: 'westend',
symbol: 'WND',
balance: '0',
assetId: 345,
precision: 10,
},
];
import { updateAssetsBalance } from '@/common/utils/balance';

export const DashboardMain = () => {
const router = useRouter();
const { getAllChains } = useChainRegistry();
const { subscribeBalance } = useBalances();
const extrinsicService = useExtrinsicProvider();
const { publicKey } = useGlobalContext();
const { publicKey, setAssets, assets } = useGlobalContext();
const { user, MainButton } = useTelegram();

useEffect(() => {
MainButton?.hide();
if (!publicKey) {
if (!publicKey || assets.length) {
return;
}
(async () => {
const chains = await getAllChains();
console.info(`All chains ${chains}`);
console.info(`Found all ${chains.length} chains`);

for (const chain of chains) {
const account: ChainAssetAccount = {
chainId: chain.chainId,
assetId: chain.assets[0].assetId,
publicKey: publicKey,
name: chain.name,
assetId: chain.assets[0].assetId,
symbol: chain.assets[0].symbol,
precision: chain.assets[0].precision,
};

const address = encodeAddress(publicKey, chain.addressPrefix);
setAssets((prevAssets) => [...prevAssets, { ...account, address }]);

subscribeBalance(account, (balance: IAssetBalance) => {
console.log(`Balance ${address} => ${balance.total().toString()}`);
console.info(`${address} ${chain.name} => balance: ${balance.total().toString()}`);

setAssets((prevAssets) => updateAssetsBalance(prevAssets, chain, balance));
});
}
})();
}, []);
}, [publicKey]);

function clearWallet() {
resetWallet();
Expand Down Expand Up @@ -115,7 +98,7 @@ export const DashboardMain = () => {
<div className="min-h-screen flex flex-col p-4">
<div className="grid grid-cols-[auto,1fr,auto] gap-2 mb-6">
<Avatar src={user?.photo_url} className="w-10 h-10" name={user?.first_name[0]} />
<CaptionText className="self-center">Good morning, {user?.first_name || 'friend'}</CaptionText>
<CaptionText className="self-center">Hello, {user?.first_name || 'friend'}</CaptionText>
<Icon name="settings" size={40} />
</div>
<Plate className="p-4 flex flex-col items-center mb-2">
Expand All @@ -129,7 +112,7 @@ export const DashboardMain = () => {
</Plate>
<Plate className="p-4 flex flex-col mb-2">
<CaptionText>Assets</CaptionText>
<AssetsList assets={mockAssets} />
<AssetsList />
</Plate>

<button className="btn btn-blue mt-4" onClick={() => clearWallet()}>
Expand Down
10 changes: 7 additions & 3 deletions src/screens/onboarding/restore/RestoreWallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';

import { useTelegram } from '@/common/providers/telegramProvider';
import { useGlobalContext } from '@/common/providers/contextProvider';
import { Avatar, Input } from '@nextui-org/react';
import { BodyText, TitleText } from '@/components/Typography';
import { Paths } from '@/common/routing';
Expand All @@ -15,6 +16,8 @@ type Props = {
export const RestoreWalletPage = ({ mnemonic }: Props) => {
const router = useRouter();
const { MainButton, user } = useTelegram();
const { setPublicKey } = useGlobalContext();

const [password, setPassword] = useState('');
const [isPasswordValid, setIsPasswordValid] = useState(true);

Expand All @@ -33,10 +36,11 @@ export const RestoreWalletPage = ({ mnemonic }: Props) => {

return;
}
const isWalletInitialized = initializeWalletFromCloud(password, mnemonic);
setIsPasswordValid(isWalletInitialized);
const wallet = initializeWalletFromCloud(password, mnemonic);
setIsPasswordValid(Boolean(wallet));

if (isWalletInitialized) {
if (wallet) {
setPublicKey(wallet?.publicKey);
router.push(Paths.DASHBOARD);
}
});
Expand Down
Loading
Loading