Skip to content

Commit

Permalink
Manage network change
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben-Rey committed Oct 14, 2024
1 parent 056a0f7 commit 2b8cc60
Show file tree
Hide file tree
Showing 11 changed files with 2,035 additions and 3,188 deletions.
5,011 changes: 1,904 additions & 3,107 deletions front/package-lock.json

Large diffs are not rendered by default.

25 changes: 18 additions & 7 deletions front/src/components/ScheduleForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@ import { AllowanceButton } from './AllowanceButton';
import { tipsModeDesc, vestingModeDesc } from '@/const/tooltips';
import { RepeatInput } from './RepeatInput';
import { CreateScheduleButton } from './CreateScheduleButton';
import { useNetworkStore } from '@/store/network';

export function ScheduleForm() {
const { connectedAccount } = useAccountStore();
const { connectedAccount, network: walletNetwork } = useAccountStore();
const { scheduleInfo, setScheduleInfo } = useSchedule();
const { tokens } = useTokenStore();
const [isVesting, setVesting] = useState<boolean>(scheduleInfo.isVesting);

const { network } = useNetworkStore();

const selectedToken = tokens.find(
(token) => token.address === scheduleInfo.asset.address,
);
Expand Down Expand Up @@ -52,6 +55,9 @@ export function ScheduleForm() {
!isAllowanceSufficient && !isMasToken,
].some(Boolean);

const isRightNetwork = network === walletNetwork;
const formDisabled = !connectedAccount || !isRightNetwork;

const handleModeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const isChecked = e.target.checked;
const value = e.target.value;
Expand All @@ -66,13 +72,18 @@ export function ScheduleForm() {

return (
<section className="max-w-2xl w-full mx-auto rounded-2xl shadow-lg p-7 bg-white -mt-40">
{walletNetwork && !isRightNetwork && (
<p className="text-red-500 text-center p-6">
Please switch your wallet to {network}
</p>
)}
<Card customClass="bg-transparent grid grid-flow-row gap-4">
<SelectMode
isVesting={isVesting}
handleModeChange={handleModeChange}
tipsModeDesc={tipsModeDesc}
vestingModeDesc={vestingModeDesc}
disabled={!connectedAccount}
disabled={formDisabled}
/>

<div className="grid grid-cols-6 gap-2">
Expand All @@ -85,11 +96,11 @@ export function ScheduleForm() {
parseUnits(amount, scheduleInfo.asset.decimals),
);
}}
disabled={!connectedAccount}
disabled={formDisabled}
/>
</div>
<div className="col-span-2">
<SelectAsset isVesting={isVesting} disabled={!connectedAccount} />
<SelectAsset isVesting={isVesting} disabled={formDisabled} />
</div>
</div>

Expand All @@ -99,7 +110,7 @@ export function ScheduleForm() {
onAddressChange={(address) => {
setScheduleInfo('recipient', address);
}}
disabled={!connectedAccount}
disabled={formDisabled}
/>
</div>

Expand All @@ -109,7 +120,7 @@ export function ScheduleForm() {
onRecurrenceChange={(value: bigint) => {
setScheduleInfo('interval', BigInt(value));
}}
disabled={!connectedAccount}
disabled={formDisabled}
/>
</div>

Expand All @@ -119,7 +130,7 @@ export function ScheduleForm() {
onValueChange={(value: string) => {
setScheduleInfo('occurrences', BigInt(value));
}}
disabled={!connectedAccount}
disabled={formDisabled}
/>
</div>
</div>
Expand Down
10 changes: 5 additions & 5 deletions front/src/components/ScheduleTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import { truncateAddress } from '@/utils/address';
import { formatAmount, toast } from '@massalabs/react-ui-kit';
import CheckBox from './CheckBox';
import useSchedule from '@/hooks/useSchedule';
import { MasToken, supportedTokens } from '../const/assets';
import { MasToken } from '../const/assets';
import ScheduleHistory from '@/components/ScheduleHistory';
import { getTokenInfo } from '@/utils/assets';
import { getRecurrenceFromPeriods } from './Recurrence';
import { useTokenStore } from '@/store/token';

interface ScheduleTableProps {
schedules: Schedule[];
Expand Down Expand Up @@ -64,9 +64,9 @@ const TableRow: React.FC<TableRowProps> = ({
isSelected,
onCheckboxChange,
}) => {
const { tokens } = useTokenStore();
const asset =
supportedTokens.find((token) => token.address === schedule.tokenAddress) ||
MasToken;
tokens.find((token) => token.address === schedule.tokenAddress) || MasToken;
const formattedAmount = formatAmount(schedule.amount, asset.decimals);
const isMas = schedule.tokenAddress === '';
return (
Expand Down Expand Up @@ -95,7 +95,7 @@ const TableRow: React.FC<TableRowProps> = ({
<CopyableAddress
label="Token address"
address={asset.address}
value={getTokenInfo(asset.address).symbol}
value={asset.symbol}
/>
)}
</td>
Expand Down
5 changes: 3 additions & 2 deletions front/src/components/SelectAsset.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { useState } from 'react';
import { supportedTokens, MasToken } from '../const/assets';
import { Asset } from '@massalabs/react-ui-kit/src/lib/token/models/AssetModel';
import { AssetSelector } from '@massalabs/react-ui-kit/src/lib/token/AssetSelector';
import useSchedule from '../hooks/useSchedule';
import { InputLabel } from './InputLabel';
import { useTokenStore } from '@/store/token';

export default function SelectAsset({
isVesting,
Expand All @@ -12,7 +12,8 @@ export default function SelectAsset({
isVesting: boolean;
disabled: boolean;
}): JSX.Element {
const tokens = isVesting ? [MasToken] : supportedTokens;
const { tokens: supportedTokens, mas } = useTokenStore.getState();
const tokens = isVesting ? [mas] : supportedTokens;
const [selectedAsset, setSelectedAsset] = useState<Asset>(tokens[0]);
const { setScheduleInfo } = useSchedule();

Expand Down
87 changes: 42 additions & 45 deletions front/src/const/assets.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,45 @@
import { Asset } from '@massalabs/react-ui-kit/src/lib/token/models/AssetModel';

// buildnet
export const supportedTokens: Asset[] = [
{
name: 'tDAI.s',
address: 'AS12LpYyAjYRJfYhyu7fkrS224gMdvFHVEeVWoeHZzMdhis7UZ3Eb',
symbol: 'tDAI.s',
decimals: 18,
balance: 0n,
allowance: 0n,
chainId: 0,
},
{
name: 'Wrapped MASSA',
address: 'AS12FW5Rs5YN2zdpEnqwj4iHUUPt9R4Eqjq2qtpJFNKW3mn33RuLU',
symbol: 'WMAS',
decimals: 9,
balance: 0n,
allowance: 0n,
chainId: 0,
},
];

// mainnet
// export const supportedTokens: Asset[] = [
// {
// name: 'DAI.e',
// address: 'AS1ZGF1upwp9kPRvDKLxFAKRebgg7b3RWDnhgV7VvdZkZsUL7Nuv',
// symbol: 'DAI.e',
// decimals: 18,
// balance: 0n,
// allowance: 0n,
// chainId: 0,
// },
// {
// name: 'Wrapped MASSA',
// address: 'AS12U4TZfNK7qoLyEERBBRDMu8nm5MKoRzPXDXans4v9wdATZedz9',
// symbol: 'WMAS',
// decimals: 9,
// balance: 0n,
// allowance: 0n,
// chainId: 0,
// },
// ];
export const supportedTokens = {
buildnet: [
{
name: 'tDAI.s',
address: 'AS12LpYyAjYRJfYhyu7fkrS224gMdvFHVEeVWoeHZzMdhis7UZ3Eb',
symbol: 'tDAI.s',
decimals: 18,
balance: 0n,
allowance: 0n,
chainId: 0,
},
{
name: 'Wrapped MASSA',
address: 'AS12FW5Rs5YN2zdpEnqwj4iHUUPt9R4Eqjq2qtpJFNKW3mn33RuLU',
symbol: 'WMAS',
decimals: 9,
balance: 0n,
allowance: 0n,
chainId: 0,
},
],
mainnet: [
{
name: 'DAI.e',
address: 'AS1ZGF1upwp9kPRvDKLxFAKRebgg7b3RWDnhgV7VvdZkZsUL7Nuv',
symbol: 'DAI.e',
decimals: 18,
balance: 0n,
allowance: 0n,
chainId: 0,
},
{
name: 'Wrapped MASSA',
address: 'AS12U4TZfNK7qoLyEERBBRDMu8nm5MKoRzPXDXans4v9wdATZedz9',
symbol: 'WMAS',
decimals: 9,
balance: 0n,
allowance: 0n,
chainId: 0,
},
],
};

export const MasToken = {
name: 'MAS',
Expand Down
17 changes: 15 additions & 2 deletions front/src/hooks/useAccountAsync.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ type SavedAccount = {
};

const useAccountSync = () => {
const { connectedAccount, setConnectedAccount } = useAccountStore();
const {
connectedAccount,
setConnectedAccount,
setCurrentWallet,
setWallets,
} = useAccountStore();

const [savedAccount, setSavedAccount] = useLocalStorage<SavedAccount>(
'saved-account',
Expand All @@ -36,17 +41,25 @@ const useAccountSync = () => {
if (connectedAccount) return;

getWallets().then((wallets) => {
setWallets(wallets);
for (const wallet of wallets) {
wallet.accounts().then((accounts) => {
const acc = accounts.find((a) => a.address === address);
if (acc) {
setConnectedAccount(acc);
setCurrentWallet(wallet);
return;
}
});
}
});
}, [savedAccount, connectedAccount, setConnectedAccount]);
}, [
savedAccount,
connectedAccount,
setConnectedAccount,
setCurrentWallet,
setWallets,
]);
};

export default useAccountSync;
13 changes: 12 additions & 1 deletion front/src/hooks/useInit.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { useEffect } from 'react';
import { useAccountStore } from '@massalabs/react-ui-kit';
import { toast, useAccountStore } from '@massalabs/react-ui-kit';
import { initApp } from '@/store/store';
import { useSchedulerStore } from '@/store/scheduler';
import { useNetworkStore } from '@/store/network';

export const useInit = () => {
const { connectedAccount } = useAccountStore();
Expand All @@ -20,4 +21,14 @@ export const useInit = () => {
}
};
}, [eventPollerStop]);

const { network: n } = useAccountStore();
const { network } = useNetworkStore();

useEffect(() => {
if (!n) return;
if (n !== network) {
toast.error(`Please switch to ${network} network`);
}
}, [network, n]);
};
4 changes: 2 additions & 2 deletions front/src/store/scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Args, Slot } from '@massalabs/massa-web3';

import { Asset } from '@massalabs/react-ui-kit/src/lib/token/models/AssetModel';
import { Schedule } from '@/serializable/Schedule';
import { supportedTokens } from '@/const/assets';
import { MasToken } from '@/const/assets';
import { useAccountStore } from '@massalabs/react-ui-kit';

export type ScheduleInfo = {
Expand Down Expand Up @@ -44,7 +44,7 @@ const defaultScheduleInfo: ScheduleInfo = {
interval: 5400n,
recipient: '',
spender: '',
asset: supportedTokens[0],
asset: MasToken,
occurrences: 4n,
tolerance: 3n,
};
Expand Down
27 changes: 17 additions & 10 deletions front/src/store/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,32 @@ import { useAccountStore, formatAmount, toast } from '@massalabs/react-ui-kit';
import { useSchedulerStore } from './scheduler';
import { useTokenStore } from './token';
import { getTokenInfo } from '@/utils/assets';
import { useNetworkStore } from './network';

export async function initApp() {
const { connectedAccount } = useAccountStore.getState();
if (!connectedAccount) return;

await Promise.all([
initTokens(),
initSchedules(connectedAccount),
initPollEvent(connectedAccount),
]);
await initTokens();
await initSchedules(connectedAccount);
await initPollEvent(connectedAccount);
}

async function initTokens() {
const { refreshBalances } = useTokenStore.getState();
await refreshBalances();
const { init } = useTokenStore.getState();
await init();
}

async function initSchedules(connectedAccount: Provider) {
const { setSchedulerAddress, getBySpender } = useSchedulerStore.getState();
setSchedulerAddress(schedulerAddress);
const { tokens } = useTokenStore.getState();
const { setSchedulerAddress, getBySpender, scheduleInfo, setScheduleInfo } =
useSchedulerStore.getState();
const { network } = useNetworkStore.getState();
setSchedulerAddress(schedulerAddress[network]);

scheduleInfo.asset = tokens[0];
setScheduleInfo('asset', tokens[0]);

await getBySpender(connectedAccount.address);
}

Expand Down Expand Up @@ -57,6 +63,7 @@ async function initPollEvent(connectedAccount: Provider) {

function handleTransferEvents(data: SCEvent[], schedules: Schedule[]) {
const { refreshBalances } = useTokenStore.getState();
const { tokens } = useTokenStore.getState();

for (const event of data) {
const match = event.data?.match(/Transfer:([^]+)/);
Expand All @@ -67,7 +74,7 @@ function handleTransferEvents(data: SCEvent[], schedules: Schedule[]) {
const schedule = schedules.find((s) => s.id === BigInt(scheduleId));

if (schedule) {
const { decimals, symbol } = getTokenInfo(schedule.tokenAddress);
const { decimals, symbol } = getTokenInfo(schedule.tokenAddress, tokens);
const formattedAmount = formatAmount(schedule.amount, decimals).preview;

toast.success(
Expand Down
Loading

0 comments on commit 2b8cc60

Please sign in to comment.