Skip to content

Commit

Permalink
Fix/dw bugs (#2709)
Browse files Browse the repository at this point in the history
* fix(dw): account creation

* fix(dw): session + db migration

* fix(dw): database connection

* fix(dw): use navigate

* chore(dw): clean up

* fix(dw): improve ttl + navigation fix

* fix(dw): check both quesrystring and # for tx

* feat(dw): delete profile and account discovery

* chore(dw): clean up

* feat(dw): add retry and skip in tx pipeline

* refactor(dw): rename usenavigation
  • Loading branch information
javadkh2 authored Dec 4, 2024
1 parent 293eb82 commit e10488a
Show file tree
Hide file tree
Showing 52 changed files with 891 additions and 432 deletions.
5 changes: 3 additions & 2 deletions packages/apps/dev-wallet/src/App/Layout/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import {
} from '@kadena/kode-ui/patterns';
import classNames from 'classnames';
import { FC, useMemo } from 'react';
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom';
import { Link, Outlet, useLocation } from 'react-router-dom';
import { usePatchedNavigate } from '../../utils/usePatchedNavigate';
import { SideBar } from './SideBar';
import {
isExpandedMainClass,
Expand All @@ -26,7 +27,7 @@ import {
export const Layout: FC = () => {
const { theme, setTheme } = useTheme();
const location = useLocation();
const navigate = useNavigate();
const navigate = usePatchedNavigate();
const { isExpanded } = useLayout();

const innerLocation = useMemo(
Expand Down
5 changes: 3 additions & 2 deletions packages/apps/dev-wallet/src/App/Layout/SideBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,16 @@ import {
useLayout,
} from '@kadena/kode-ui/patterns';
import { FC } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Link } from 'react-router-dom';
import { usePatchedNavigate } from '../../utils/usePatchedNavigate';
import { BetaHeader } from '../BetaHeader';
import { KLogo } from './KLogo';

export const SideBar: FC = () => {
const { theme, setTheme } = useTheme();
const { isExpanded } = useLayout();
const { lockProfile, profileList, unlockProfile, profile } = useWallet();
const navigate = useNavigate();
const navigate = usePatchedNavigate();

const toggleTheme = (): void => {
const newTheme = theme === Themes.dark ? Themes.light : Themes.dark;
Expand Down
8 changes: 4 additions & 4 deletions packages/apps/dev-wallet/src/App/routes.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { FC, PropsWithChildren, useEffect, useState } from 'react';
import {
createBrowserRouter,
createMemoryRouter,
createRoutesFromElements,
Navigate,
Outlet,
Route,
RouterProvider,
createBrowserRouter,
createMemoryRouter,
createRoutesFromElements,
useLocation,
} from 'react-router-dom';

Expand Down Expand Up @@ -39,8 +39,8 @@ import { HomePage } from '../pages/home/home-page';
import { SelectProfile } from '../pages/select-profile/select-profile';
import { UnlockProfile } from '../pages/unlock-profile/unlock-profile';
import { getScriptType } from '../utils/window';
import { Layout } from './Layout/Layout';
import { LayoutMini } from './layout-mini';
import { Layout } from './Layout/Layout';

const Redirect: FC<
PropsWithChildren<{
Expand Down
3 changes: 3 additions & 0 deletions packages/apps/dev-wallet/src/App/session.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ export const SessionProvider: FC<PropsWithChildren> = ({ children }) => {
const [loaded, setLoaded] = useState(false);
useLayoutEffect(() => {
const events = ['visibilitychange', 'touchstart', 'keydown', 'click'];
let removeListener = () => {};
const run = async () => {
await Session.load();
removeListener = Session.ListenToExternalChanges();
// console.log('Session is loaded', Session.get('profileId'));
events.forEach((event) => {
document.addEventListener(event, Session.renew);
Expand All @@ -39,6 +41,7 @@ export const SessionProvider: FC<PropsWithChildren> = ({ children }) => {
events.forEach((event) => {
document.removeEventListener(event, Session.renew);
});
removeListener();
};
}, []);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ export const AccountBalanceDistribution: FC<IProps> = ({
network: activeNetwork!,
redistribution,
mapKeys,
creationTime: Math.round(Date.now() / 1000),
});

onRedistribution(groupId);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useWallet } from '@/modules/wallet/wallet.hook';
import { usePatchedNavigate } from '@/utils/usePatchedNavigate';
import {
MonoCheck,
MonoSettings,
Expand All @@ -12,15 +13,14 @@ import {
IButtonProps,
} from '@kadena/kode-ui';
import { FC } from 'react';
import { useNavigate } from 'react-router-dom';

export const NetworkSelector: FC<{
showLabel?: boolean;
variant: IButtonProps['variant'];
isCompact?: IButtonProps['isCompact'];
}> = ({ showLabel = true, variant, isCompact = false }) => {
const { networks, activeNetwork, setActiveNetwork } = useWallet();
const navigate = useNavigate();
const navigate = usePatchedNavigate();

const handleNetworkUpdate = (uuid: string) => {
const network = networks.find((network) => network.uuid === uuid);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useWallet } from '@/modules/wallet/wallet.hook';
import { IProfile } from '@/modules/wallet/wallet.repository';
import { getWebAuthnPass } from '@/modules/wallet/wallet.service';
import { usePatchedNavigate } from '@/utils/usePatchedNavigate';
import { MonoMoreHoriz } from '@kadena/kode-icons/system';
import {
Button,
Expand All @@ -10,7 +11,6 @@ import {
Stack,
} from '@kadena/kode-ui';
import { FC } from 'react';
import { useNavigate } from 'react-router-dom';
import { Profile } from './components/Profile';
import { profileClass, profileListClass } from './components/style.css';

Expand All @@ -25,7 +25,7 @@ export const ProfileChanger: FC = () => {
unlockProfile,
lockProfile,
} = useWallet();
const navigate = useNavigate();
const navigate = usePatchedNavigate();

const handleSelect = async (profile: Pick<IProfile, 'options' | 'uuid'>) => {
if (profile.options.authMode === 'WEB_AUTHN') {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { IProfile } from '@/modules/wallet/wallet.repository.ts';
import { getErrorMessage } from '@/utils/getErrorMessage.ts';
import {
Button,
Dialog,
Heading,
Notification,
Radio,
RadioGroup,
Stack,
Text,
TextField,
} from '@kadena/kode-ui';
import React from 'react';
import React, { useState } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { unlockPrompt } from './style.css.ts';

Expand All @@ -23,7 +25,7 @@ export const UnlockPrompt: React.FC<{
}: {
password: string;
keepOpen: 'session' | 'short-time' | 'never';
}) => void;
}) => Promise<void>;
reject: (reason: any) => void;
storePassword?: boolean;
}> = ({
Expand All @@ -34,6 +36,7 @@ export const UnlockPrompt: React.FC<{
profile,
storePassword = true,
}) => {
const [error, setError] = useState<string>();
const { control, register, handleSubmit } = useForm({
defaultValues: {
keepOpen: rememberPassword || 'session',
Expand All @@ -49,7 +52,9 @@ export const UnlockPrompt: React.FC<{
>
<form
onSubmit={handleSubmit((data) => {
resolve(data);
resolve(data).catch((e) => {
setError(getErrorMessage(e, 'Password in not correct'));
});
})}
>
<Stack flexDirection={'column'} gap={'md'}>
Expand Down Expand Up @@ -93,6 +98,14 @@ export const UnlockPrompt: React.FC<{
)}
/>
)}
{error && (
<Notification intent="negative" role="alert">
<Stack flexDirection={'column'} gap={'sm'}>
<Text>{error}</Text>
<Text>Please try again!</Text>
</Stack>
</Notification>
)}
<Stack gap={'sm'}>
<Button variant="transparent" type="reset" onClick={reject}>
Cancel
Expand Down
1 change: 0 additions & 1 deletion packages/apps/dev-wallet/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ export const config = {
},
SESSION: {
TTL: 30 * 60 * 1000, // 30 minutes
ENCRYPT_SESSION: false,
},
BACKUP: {
BACKUP_INTERVAL: 1000 * 60 * 60 * 12, // 12 hours
Expand Down
3 changes: 2 additions & 1 deletion packages/apps/dev-wallet/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ const loadingContent = document.getElementById('loading-content');
// the entry file for the dev wallet app
// TODO: we need to do setup app here like service worker, etc
async function bootstrap() {
const mainModule = import('./App/main');
await registerServiceWorker();
addBootTheme();
import('./App/main').then(async ({ renderApp }) => {
mainModule.then(async ({ renderApp }) => {
if (loadingContent) {
loadingContent.innerHTML = '';
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,9 +222,10 @@ interface Guard {
export const hasSameGuard = (a?: Guard, b?: Guard) => {
const getKeys = (key: ISigner) =>
typeof key === 'string' ? key : key.pubKey;
const aKeys = a ? a.keys.map(getKeys).sort() : [];

const aKeys = a ? a.keys.map(getKeys).sort() : [];
const bKeys = b ? b.keys.map(getKeys).sort() : [];

return (
aKeys.length === bKeys.length &&
aKeys.every((key) => bKeys.includes(key)) &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ export interface TransferData {
gasPrice: string;
gasLimit: string;
type: 'safeTransfer' | 'normalTransfer';
ttl: string;
ttl: number;
creationTime?: number;
}

export interface IActivity {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { usePatchedNavigate } from '@/utils/usePatchedNavigate';
import { IPactCommand, IUnsignedCommand } from '@kadena/client';
import {
FC,
Expand All @@ -7,7 +8,6 @@ import {
useEffect,
useState,
} from 'react';
import { useNavigate } from 'react-router-dom';
import { addTransaction } from '../transaction/transaction.service';
import { useWallet } from '../wallet/wallet.hook';

Expand Down Expand Up @@ -58,7 +58,7 @@ export const CommunicationProvider: FC<
PropsWithChildren<{ setOrigin: (pathname: string) => void }>
> = ({ setOrigin, children }) => {
const [requests] = useState(() => new Map<string, Request>());
const navigate = useNavigate();
const navigate = usePatchedNavigate();
const { isUnlocked, accounts, profile, networks, activeNetwork } =
useWallet();

Expand Down
19 changes: 10 additions & 9 deletions packages/apps/dev-wallet/src/modules/db/backup/backup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,16 @@ const importProfiles = async (
await Promise.all(profiles.map(async (profile) => put('profile', profile)));
};

export const profileTables = [
'encryptedValue',
'keySource',
'account',
'watched-account',
'keyset',
'transaction',
'activity',
] as const;

const importProfileRelatedTables = async ({
backup,
profileUUIds,
Expand All @@ -185,15 +195,6 @@ const importProfileRelatedTables = async ({
transaction: IDBTransaction;
networkRemap: Record<UUID, UUID>;
}) => {
const profileTables = [
'encryptedValue',
'keySource',
'account',
'watched-account',
'keyset',
'transaction',
'activity',
] as const;
const put = putItem(db, transaction);

await profileTables.map(async (table) => {
Expand Down
23 changes: 5 additions & 18 deletions packages/apps/dev-wallet/src/modules/db/db.provider.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { BootContent } from '@/Components/BootContent/BootContent';
import { sleep } from '@/utils/helpers';
import { Stack, Text } from '@kadena/kode-ui';
import { FC, ReactNode, useEffect, useState } from 'react';
import { FC, ReactNode, useEffect, useRef, useState } from 'react';
import { addDefaultFungibles } from '../account/account.repository';
import { addDefaultNetworks } from '../network/network.repository';
import { closeDatabaseConnections, setupDatabase } from './db.service';
import { setupDatabase } from './db.service';

const renderDefaultError = ({ message }: Error) => (
<Stack
Expand All @@ -28,10 +28,13 @@ export const DatabaseProvider: FC<{
fallback = <Text>initializing database ...</Text>,
renderError = renderDefaultError,
}) => {
const setupRef = useRef(false);
const [initialized, setInitialized] = useState(false);
const [errorObject, setErrorObject] = useState<Error>();

useEffect(() => {
if (setupRef.current) return;
setupRef.current = true;
const setupDataBase = async () => {
console.log('setting up database');
const db = await setupDatabase();
Expand All @@ -47,26 +50,10 @@ export const DatabaseProvider: FC<{
}
};

const closeConnectionsCallback = () => {
if (document.hidden) {
// close all connections when app is hidden; since open connections will block other tabs from accessing the database
closeDatabaseConnections();
}
};

document.addEventListener('visibilitychange', closeConnectionsCallback);

setupDataBase().catch((e) => {
console.log(e);
setErrorObject(e);
});

return () => {
document.removeEventListener(
'visibilitychange',
closeConnectionsCallback,
);
};
}, []);

if (errorObject) {
Expand Down
Loading

0 comments on commit e10488a

Please sign in to comment.