Skip to content

Commit

Permalink
chore: create domains store, send error code
Browse files Browse the repository at this point in the history
  • Loading branch information
kyranjamie committed Apr 22, 2022
1 parent c3e9693 commit beb2a51
Show file tree
Hide file tree
Showing 11 changed files with 82 additions and 53 deletions.
6 changes: 5 additions & 1 deletion src/app/common/actions/send-request-account-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,9 @@ export function sendRequestAccountResponseToTab(args: SendRequestAccountResponse
dataPublicKey: account.dataPublicKey,
};

return sendMessageToTab(parseInt(tabId), id, [safeAccountKeys]);
return sendMessageToTab(parseInt(tabId), id, { result: [safeAccountKeys] });
}

export function sendUserDeniesAccountRequest({ tabId, id }: { tabId: string; id: string }) {
return sendMessageToTab(parseInt(tabId), id, { error: { code: 4000, message: 'lskdjflksjdfl' } });
}
22 changes: 20 additions & 2 deletions src/app/pages/choose-account-request/account-request.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { logger } from '@shared/logger';

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 { 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 {
sendRequestAccountResponseToTab,
sendUserDeniesAccountRequest,
} from '@app/common/actions/send-request-account-response';

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

export function AccountRequest() {
const accounts = useAccounts();
Expand All @@ -29,6 +34,19 @@ export function AccountRequest() {
window.close();
};

const handleUnmount = () => {
if (!tabId || !id) {
logger.error('Missing either tabId or uuid. Both values are necessary to respond to app');
return;
}
sendUserDeniesAccountRequest({ tabId, id });
};

useEffect(() => {
window.addEventListener('beforeunload', handleUnmount);
return () => window.removeEventListener('beforeunload', handleUnmount);
}, []);

return (
<AccountPickerLayout appName={appName}>
<AccountPicker
Expand Down
Empty file.
Empty file.
19 changes: 19 additions & 0 deletions src/app/store/apps/apps.slice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { createEntityAdapter, createSlice } from '@reduxjs/toolkit';

interface AppDetails {
domain: string;
}

const appsAdapter = createEntityAdapter<AppDetails>({
selectId: entity => entity.domain,
});

export const initialAppsState = appsAdapter.getInitialState();

export const appsSlice = createSlice({
name: 'apps',
initialState: appsAdapter.getInitialState(),
reducers: {
appConnected: appsAdapter.addOne,
},
});
2 changes: 2 additions & 0 deletions src/app/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ import { inMemoryKeySlice } from './in-memory-key/in-memory-key.slice';
import { ExtensionStorage } from './utils/extension-storage';
import { onboardingSlice } from './onboarding/onboarding.slice';
import { analyticsSlice } from './analytics/analytics.slice';
import { appsSlice } from './apps/apps.slice';

const storage = new ExtensionStorage(chrome.storage.local, chrome.runtime);

const rootReducer = combineReducers({
apps: appsSlice.reducer,
keys: keySlice.reducer,
chains: combineReducers({
stx: stxChainSlice.reducer,
Expand Down
9 changes: 1 addition & 8 deletions src/background/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { logger } from '@shared/logger';
import {
CONTENT_SCRIPT_PORT,
LegacyMessageFromContentScript,
MESSAGE_SOURCE,
RpcMethods,
SupportedRpcMessages,
} from '@shared/message-types';
Expand Down Expand Up @@ -44,6 +43,7 @@ chrome.runtime.onInstalled.addListener(details => {
chrome.runtime.onConnect.addListener(port =>
Sentry.wrap(() => {
if (port.name !== CONTENT_SCRIPT_PORT) return;

port.onMessage.addListener(
(message: LegacyMessageFromContentScript | SupportedRpcMessages, port) => {
if (inferLegacyMessage(message)) {
Expand All @@ -59,16 +59,9 @@ chrome.runtime.onConnect.addListener(port =>
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
1 change: 0 additions & 1 deletion src/background/legacy-external-message-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export function inferLegacyMessage(message: any): message is LegacyMessageFromCo
// Now that we use a RPC communication style, we can infer
// legacy message types by presence of an id
// Types incorrectly state this is `undefined`
// @ts-ignore
return !Object.hasOwn(message, 'id');
}

Expand Down
40 changes: 12 additions & 28 deletions src/inpage/inpage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,18 @@ import {
LegacyMessageToContentScript,
MESSAGE_SOURCE,
RpcMethodNames,
RpcRequestArgs,
RpcResponseArgs,
TransactionResponseMessage,
} from '@shared/message-types';
import { logger } from '@shared/logger';

declare global {
interface Crypto {
randomUUID: () => string;
}
}

type CallableMethods = keyof typeof ExternalMethods;

interface ExtensionResponse {
Expand Down Expand Up @@ -109,19 +117,17 @@ const provider: StacksProvider = {
});
},

async request(method: RpcMethodNames, params?: any[]) {
async request(method: RpcMethodNames, params?: any[]): Promise<RpcResponseArgs> {
return new Promise((resolve, _reject) => {
const id = crypto.randomUUID();
const event = new CustomEvent<RpcEventArgs>(DomEventName.rpcRequest, {
const event = new CustomEvent<RpcRequestArgs>(DomEventName.rpcRequest, {
detail: { jsonrpc: '2.0', id, method, params },
});
document.dispatchEvent(event);
const handleMessage = (event: MessageEvent<any>) => {
console.log(event);
if (event.data.id !== id) return;

window.removeEventListener('message', handleMessage);
resolve(event.data.result);
resolve(event.data);
};
window.addEventListener('message', handleMessage);
});
Expand All @@ -137,28 +143,6 @@ const provider: StacksProvider = {
},
};
},
} as StacksProvider & { request(): Promise<void> };
} as StacksProvider & { request(): Promise<RpcResponseArgs> };

window.StacksProvider = provider;

interface RpcRequestArgs {
method: RpcMethodNames;
params?: any[];
}

interface RpcEventArgs extends RpcRequestArgs {
jsonrpc: '2.0';
id: string;
}

declare global {
interface Crypto {
randomUUID: () => string;
}
}

// declare global {
// interface Window {
// StacksProvider?: Provider;
// }
// }
34 changes: 22 additions & 12 deletions src/shared/message-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,28 @@ export interface Message<Methods extends ExtensionMethods, Payload = undefined>

//
// RPC Methods, SIP pending
interface RpcBaseArgs {
jsonrpc: '2.0';
id: string;
}

export interface RpcRequestArgs extends RpcBaseArgs {
method: RpcMethodNames;
params?: any[];
}

interface RpcSuccessResponseArgs extends RpcBaseArgs {
results: any;
}

interface RpcErrorResponseArgs extends RpcBaseArgs {
error: {
code: number;
message: string;
};
}

export type RpcResponseArgs = RpcSuccessResponseArgs | RpcErrorResponseArgs;

export enum RpcMethods {
stx_requestAccounts,
Expand All @@ -55,18 +77,6 @@ type TestAction = RpcMessage<'stx_testAnotherMethod'>;

export type SupportedRpcMessages = RequestAccounts | TestAction;

// interface SupportedMessagesReturnTypeMap {
// [RpcMethods.stx_requestAccounts]: { xxx: string };
// [RpcMethods.stx_testAnotherMethod]: { yyy: string };
// }

// function xx<Method extends keyof SupportedMessagesReturnTypeMap >(): // method: RpcMethods
// SupportedMessagesReturnTypeMap[Method] {

// }

// xx('stx_requestAccounts');

//
// Deprecated methods
type AuthenticationRequestMessage = Message<ExternalMethods.authenticationRequest, string>;
Expand Down
2 changes: 1 addition & 1 deletion src/shared/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,5 @@ export function sendMessageToBackground(message: BackgroundActions) {
}

export function sendMessageToTab(tabId: number, id: string, message: object) {
return chrome.tabs.sendMessage(tabId, { source: MESSAGE_SOURCE, id, result: message });
return chrome.tabs.sendMessage(tabId, { source: MESSAGE_SOURCE, id, ...message });
}

0 comments on commit beb2a51

Please sign in to comment.