Skip to content

Commit

Permalink
refactor: account selection page, part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
kyranjamie committed Apr 21, 2022
1 parent 75c6615 commit 6cc06f5
Show file tree
Hide file tree
Showing 18 changed files with 103 additions and 41 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,12 @@
"@sentry/tracing": "6.16.1",
"@stacks/blockchain-api-client": "0.65.0",
"@stacks/common": "3.0.0",
"@stacks/storage": "3.2.0",
"@stacks/connect": "6.4.0",
"@stacks/connect-ui": "5.2.0",
"@stacks/encryption": "3.0.0",
"@stacks/network": "3.0.0",
"@stacks/rpc-client": "1.0.3",
"@stacks/storage": "3.2.0",
"@stacks/transactions": "3.0.0",
"@stacks/ui": "7.10.0",
"@stacks/ui-core": "7.3.0",
Expand Down Expand Up @@ -253,6 +253,7 @@
"ts-node": "10.4",
"ts-unused-exports": "7.0.3",
"tsconfig-paths-webpack-plugin": "3.5.2",
"type-fest": "2.12.2",
"typescript": "4.5.4",
"vm-browserify": "1.1.2",
"web-ext": "6.2.0",
Expand Down
18 changes: 18 additions & 0 deletions src/app/common/actions/send-request-account-response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { SoftwareWalletAccountWithAddress } from '@app/store/accounts/account.models';
import { sendMessageToTab } from '@shared/messages';

interface SendRequestAccountResponseToTabArgs {
tabId: string;
id: string;
account: SoftwareWalletAccountWithAddress;
}
export function sendRequestAccountResponseToTab(args: SendRequestAccountResponseToTabArgs) {
const { tabId, id, account } = args;

const safeAccountKeys = {
stxPublicKey: account.stxPublicKey,
dataPublicKey: account.dataPublicKey,
};

return sendMessageToTab(parseInt(tabId), id, safeAccountKeys);
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function useSaveAuthRequest() {
appURL: new URL(origin),
});

navigate(RouteUrls.ChooseAccount);
navigate(RouteUrls.AccountAuthentication);
},
[saveAuthRequest, navigate]
);
Expand Down
8 changes: 4 additions & 4 deletions src/app/common/hooks/use-key-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { clearSessionLocalData } from '@app/common/store-utils';
import { createNewAccount, stxChainActions } from '@app/store/chains/stx-chain.actions';
import { keyActions } from '@app/store/keys/key.actions';
import { useAnalytics } from './analytics/use-analytics';
import { sendMessage } from '@shared/messages';
import { sendMessageToBackground } from '@shared/messages';
import { InternalMethods } from '@shared/message-types';
import { inMemoryKeyActions } from '@app/store/in-memory-key/in-memory-key.actions';

Expand All @@ -23,7 +23,7 @@ export function useKeyActions() {

generateWalletKey() {
const secretKey = generateSecretKey(256);
sendMessage({
sendMessageToBackground({
method: InternalMethods.ShareInMemoryKeyToBackground,
payload: { secretKey, keyId: 'default' },
});
Expand All @@ -45,12 +45,12 @@ export function useKeyActions() {
async signOut() {
void analytics.track('sign_out');
dispatch(keyActions.signOut());
sendMessage({ method: InternalMethods.RemoveInMemoryKeys, payload: undefined });
sendMessageToBackground({ method: InternalMethods.RemoveInMemoryKeys, payload: undefined });
clearSessionLocalData();
},

lockWallet() {
sendMessage({ method: InternalMethods.RemoveInMemoryKeys, payload: undefined });
sendMessageToBackground({ method: InternalMethods.RemoveInMemoryKeys, payload: undefined });
return dispatch(inMemoryKeyActions.lockWallet());
},
}),
Expand Down
6 changes: 1 addition & 5 deletions src/app/features/account-picker/accounts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,7 @@ const AccountItem = memo((props: AccountItemProps) => {
/>
}
>
<AccountTitle
name={name}
{...getLoadingProps(showLoadingProps)}
account={account}
/>
<AccountTitle name={name} account={account} />
</Suspense>
<Stack alignItems="center" spacing="6px" isInline>
<Caption fontSize={0} {...getLoadingProps(showLoadingProps)}>
Expand Down
30 changes: 16 additions & 14 deletions src/app/pages/choose-account-request/account-request.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,39 @@ import { useRouteHeader } from '@app/common/hooks/use-route-header';
import { useAppDetails } from '@app/common/hooks/auth/use-app-details';
import { Header } from '@app/components/header';
import { AccountPicker } from '@app/features/account-picker/accounts';
import { useOnboardingState } from '@app/common/hooks/auth/use-onboarding-state';
import { useAccounts } from '@app/store/accounts/account.hooks';
import { AccountPickerLayout } from '@app/features/account-picker/account-picker.layout';
import { logger } from '@shared/logger';
import { sendRequestAccountResponseToTab } from '@app/common/actions/send-request-account-response';

import { useAccountRequestSearchParams } from './use-account-request-search-params';

export function AccountRequest() {
const accounts = useAccounts();
const { name: appName } = useAppDetails();
const { decodedAuthRequest } = useOnboardingState();
// const [selectedAccountIndex, setSelectedAccountIndex] = useState<number | null>(null);

const { tabId, id } = useAccountRequestSearchParams();

useRouteHeader(<Header hideActions />);

const returnAccountDetailsToApp = async (index: number) => {
// setSelectedAccountIndex(index);
// await finishSignIn(index);
};
if (!tabId || !id) {
logger.error('Missing either tabId or uuid. Both necessary to respond to app');
return;
}

// const handleUnmount = useCallback(async () => {
// cancelAuthentication();
// }, [cancelAuthentication]);
if (!accounts) return;

// useEffect(() => {
// window.addEventListener('beforeunload', handleUnmount);
// return () => window.removeEventListener('beforeunload', handleUnmount);
// }, [handleUnmount]);
console.log('xxxxxx', accounts[index]);
sendRequestAccountResponseToTab({ tabId, id, account: accounts[index] });
// window.close();
};

return (
<AccountPickerLayout appName={appName}>
<AccountPicker
onAccountSelected={index => returnAccountDetailsToApp(index)}
selectedAccountIndex={0}
selectedAccountIndex={null}
/>
</AccountPickerLayout>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useMemo } from 'react';
import { useSearchParams } from 'react-router-dom';

export function useAccountRequestSearchParams() {
const [searchParams] = useSearchParams();

return useMemo(
() => ({
tabId: searchParams.get('tabId'),
id: searchParams.get('id'),
}),
[searchParams]
);
}
2 changes: 1 addition & 1 deletion src/app/pages/home/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export function Home() {
);

useEffect(() => {
if (decodedAuthRequest) navigate(RouteUrls.ChooseAccount);
if (decodedAuthRequest) navigate(RouteUrls.AccountAuthentication);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

Expand Down
2 changes: 1 addition & 1 deletion src/app/pages/onboarding/set-password/set-password.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export const SetPasswordPage = () => {
if (!wallet) return;
const { accounts } = wallet;
if (accounts && accounts.length > 1) {
navigate(RouteUrls.ChooseAccount);
navigate(RouteUrls.AccountAuthentication);
} else {
await finishSignIn(0);
}
Expand Down
2 changes: 1 addition & 1 deletion src/app/pages/unlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export function Unlock(): JSX.Element {
await unlockWallet(password);

if (decodedAuthRequest) {
navigate(RouteUrls.ChooseAccount);
navigate(RouteUrls.AccountAuthentication);
} else {
navigate(RouteUrls.Home);
}
Expand Down
13 changes: 12 additions & 1 deletion src/app/routes/app-routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { RouteUrls } from '@shared/route-urls';
import { useOnWalletLock } from './hooks/use-on-wallet-lock';
import { useOnSignOut } from './hooks/use-on-sign-out';
import { OnboardingGate } from './onboarding-gate';
import { AccountRequest } from '@app/pages/choose-account-request/account-request';

export function AppRoutes(): JSX.Element | null {
const { pathname } = useLocation();
Expand Down Expand Up @@ -108,7 +109,7 @@ export function AppRoutes(): JSX.Element | null {
}
/>
<Route
path={RouteUrls.ChooseAccount}
path={RouteUrls.AccountAuthentication}
element={
<AccountGate>
<Suspense fallback={<></>}>
Expand All @@ -117,6 +118,16 @@ export function AppRoutes(): JSX.Element | null {
</AccountGate>
}
/>
<Route
path={RouteUrls.AccountRequest}
element={
<AccountGate>
<Suspense fallback={<></>}>
<AccountRequest />
</Suspense>
</AccountGate>
}
/>
<Route
path={RouteUrls.Receive}
element={
Expand Down
6 changes: 3 additions & 3 deletions src/app/store/keys/key.actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { AppThunk } from '@app/store';
import { stxChainSlice } from '../chains/stx-chain.slice';
import { defaultKeyId, keySlice } from './key.slice';
import { selectCurrentKey } from './key.selectors';
import { sendMessage } from '@shared/messages';
import { sendMessageToBackground } from '@shared/messages';
import { InternalMethods } from '@shared/message-types';
import { inMemoryKeySlice } from '../in-memory-key/in-memory-key.slice';
import { selectDefaultWalletKey } from '../in-memory-key/in-memory-key.selectors';
Expand Down Expand Up @@ -35,7 +35,7 @@ const setWalletEncryptionPassword = (password: string): AppThunk => {
const { encryptedSecretKey, salt } = await encryptMnemonic({ secretKey, password });
const highestAccountIndex = await restoredWalletHighestGeneratedAccountIndex(secretKey);

sendMessage({
sendMessageToBackground({
method: InternalMethods.ShareInMemoryKeyToBackground,
payload: { secretKey, keyId: defaultKeyId },
});
Expand Down Expand Up @@ -63,7 +63,7 @@ const unlockWalletAction = (password: string): AppThunk => {

const { secretKey } = await decryptMnemonic({ password, ...currentKey });

sendMessage({
sendMessageToBackground({
method: InternalMethods.ShareInMemoryKeyToBackground,
payload: { secretKey: secretKey, keyId: defaultKeyId },
});
Expand Down
17 changes: 13 additions & 4 deletions src/background/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
handleLegacyExternalMethodFormat,
inferLegacyMessage,
} from './legacy-external-message-handler';
import { popupCenter } from './popup-center';

initSentry();
initContextMenuActions();
Expand Down Expand Up @@ -55,11 +56,19 @@ chrome.runtime.onConnect.addListener(port =>

switch (message.method) {
case RpcMethods[RpcMethods.stx_requestAccounts]: {
chrome.tabs.sendMessage(port.sender.tab.id, {
source: MESSAGE_SOURCE,
id: message.id,
results: { publicKey: 'sldkfjs' },
const params = new URLSearchParams();
params.set('tabId', port.sender.tab.id.toString());
params.set('id', message.id);
console.log(params.toString());
popupCenter({
url: `/popup-center.html#${RouteUrls.AccountRequest}?${params.toString()}`,
});

// chrome.tabs.sendMessage(port.sender.tab.id, {
// source: MESSAGE_SOURCE,
// id: message.id,
// results: { publicKey: 'sldkfjs' },
// });
break;
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/inpage/inpage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,11 @@ const provider: StacksProvider = {
});
document.dispatchEvent(event);
const handleMessage = (event: MessageEvent<any>) => {
console.log(event);
if (event.data.id !== id) return;

window.removeEventListener('message', handleMessage);
resolve(event.data);
resolve(event.data.result);
};
window.addEventListener('message', handleMessage);
});
Expand Down
8 changes: 6 additions & 2 deletions src/shared/messages.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ExtensionMethods, InternalMethods, Message } from '@shared/message-types';
import { ExtensionMethods, InternalMethods, Message, MESSAGE_SOURCE } from '@shared/message-types';

/**
* Vault <-> Background Script
Expand Down Expand Up @@ -28,6 +28,10 @@ export type BackgroundActions =
| RequestInMemoryKeys
| RemoveInMemoryKeys;

export function sendMessage(message: BackgroundActions) {
export function sendMessageToBackground(message: BackgroundActions) {
return chrome.runtime.sendMessage(message);
}

export function sendMessageToTab(tabId: number, id: string, message: object) {
return chrome.tabs.sendMessage(tabId, { source: MESSAGE_SOURCE, id, result: message });
}
3 changes: 2 additions & 1 deletion src/shared/route-urls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ export enum RouteUrls {
Home = '/',
AddNetwork = '/add-network',
Buy = '/buy',
ChooseAccount = '/choose-account',
AccountAuthentication = '/authenticate-account',
AccountRequest = '/request-account',
Receive = '/receive',
Send = '/send',
SignOutConfirm = '/sign-out',
Expand Down
2 changes: 1 addition & 1 deletion test-app/src/components/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const Home: React.FC = () => {
getStacksProvider()
.request('stx_requestAccounts')
.then(resp => {
setAccount([resp]);
setAccount(resp);
console.log('request acct resp', resp);
});
}}
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -18839,6 +18839,11 @@ [email protected], type-detect@^4.0.8:
resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c"
integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==

[email protected]:
version "2.12.2"
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-2.12.2.tgz#80a53614e6b9b475eb9077472fb7498dc7aa51d0"
integrity sha512-qt6ylCGpLjZ7AaODxbpyBZSs9fCI9SkL3Z9q2oxMBQhs/uyY+VD8jHA8ULCGmWQJlBgqvO3EJeAngOHD8zQCrQ==

type-fest@^0.13.1:
version "0.13.1"
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.13.1.tgz#0172cb5bce80b0bd542ea348db50c7e21834d934"
Expand Down

0 comments on commit 6cc06f5

Please sign in to comment.