Skip to content

Commit

Permalink
Optimize Dapp lifecycle handler
Browse files Browse the repository at this point in the history
  • Loading branch information
saltict committed Dec 17, 2023
1 parent f947d18 commit c39ce52
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 44 deletions.
2 changes: 0 additions & 2 deletions packages/extension-base/src/background/handlers/Tabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,6 @@ export default class Tabs {
return this.redirectIfPhishing(url);
}

// Todo: MV3 fix connect dapps with chains requests

switch (type) {
case 'pub(authorize.tab)':
return this.authorize(url, request as RequestAuthorizeTab);
Expand Down
3 changes: 3 additions & 0 deletions packages/extension-base/src/koni/background/handlers/Tabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1044,6 +1044,9 @@ export default class KoniTabs {
return this.redirectIfPhishing(url);
}

// Wait for account ready and chain ready
await Promise.all([this.#koniState.eventService.waitAccountReady, this.#koniState.eventService.waitChainReady]);

if (type !== 'pub(authorize.tabV2)' && !this.isEvmPublicRequest(type, request as RequestArguments)) {
await this.#koniState.ensureUrlAuthorizedV2(url)
.catch((e: Error) => {
Expand Down
22 changes: 0 additions & 22 deletions packages/extension-base/src/koni/background/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,6 @@ export const tabs = new KoniTabs(state);
export const mobile = new Mobile(state);
export const nftHandler = new NftHandler();

// Migration
// async function makeSureStateReady () {
// const poll = (resolve: (value: unknown) => void) => {
// if (state.isReady()) {
// resolve(true);
// } else {
// console.log('Waiting for State is ready...');
// setTimeout(() => poll(resolve), 400);
// }
// };
//
// return new Promise(poll);
// }

// makeSureStateReady().then(() => {
// const migration = new Migration(state);
//
// migration.run().catch((err) => console.warn(err));
// }).catch((e) => console.warn(e));

export default function handlers<TMessageType extends MessageTypes> ({ id, message, request }: TransportRequestMessage<TMessageType>, port: chrome.runtime.Port, extensionPortName = PORT_EXTENSION): void {
const isMobile = port.name === PORT_MOBILE;
const isExtension = port.name === extensionPortName;
Expand All @@ -48,8 +28,6 @@ export default function handlers<TMessageType extends MessageTypes> ({ id, messa
: (sender.tab && sender.tab.url) || sender.url || '<unknown>';
const source = `${from}: ${id}: ${message}`;

// console.log(` [in] ${source}`); // :: ${JSON.stringify(request)}`);

const promise = isMobile
? mobile.handle(id, message, request, port)
: isExtension
Expand Down
42 changes: 22 additions & 20 deletions packages/extension-koni/src/helper/ActionHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export class ActionHandler {
// Common handlers
private waitStartHandler = createPromiseHandler<() => void>();
private waitInstallHandler = createPromiseHandler<(details: chrome.runtime.InstalledDetails) => void>();
private waitActiveHandler = createPromiseHandler<boolean>();

// Port handlers
private portHandler?: HandlerMethod;
Expand All @@ -26,8 +27,8 @@ export class ActionHandler {
private waitFirstTrigger = createPromiseHandler<void>();
public waitFirstActiveMessage = this.waitFirstTrigger.promise;

private wakeUpHandler?: () => void;
private sleepHandler?: () => void;
private wakeUpHandler?: () => Promise<void>;
private sleepHandler?: () => Promise<void>;
private isActive = false;
private sleepTimeout?: NodeJS.Timeout;

Expand Down Expand Up @@ -72,20 +73,27 @@ export class ActionHandler {
}).catch(console.error);
}

setWakeUpHandler (handler: () => void): void {
setWakeUpHandler (handler: () => Promise<void>): void {
this.wakeUpHandler = handler;
}

setSleepHandler (handler: () => void): void {
setSleepHandler (handler: () => Promise<void>): void {
this.sleepHandler = handler;
}

private _getPortId (port: chrome.runtime.Port): string {
return `${port.sender?.documentId || 'extension-popup'}`;
}

private _onPortMessage (port: chrome.runtime.Port, data: TransportRequestMessage<keyof RequestSignatures>, portId: string): void {
if (!this.connectionMap[portId] && data?.message && data.message !== 'pub(phishing.redirectIfDenied)') {
private async _onPortMessage (port: chrome.runtime.Port, data: TransportRequestMessage<keyof RequestSignatures>, portId: string) {
// message and disconnect handlers
if (!this.portHandler) {
this.portHandler = await this.waitPortHandler.promise;
}

const requireActive = data.message !== 'pub(phishing.redirectIfDenied)';

if (!this.connectionMap[portId] && data?.message && requireActive) {
this.connectionMap[portId] = port.name;

if (!this.firstTrigger) {
Expand All @@ -101,32 +109,26 @@ export class ActionHandler {

if (!this.isActive) {
this.isActive = true;
this.wakeUpHandler && this.wakeUpHandler();
this.wakeUpHandler && await this.wakeUpHandler();
this.waitActiveHandler.resolve(true);
}
}

// message and disconnect handlers
const handlerPromise = this.waitPortHandler.promise;

if (this.portHandler) {
this.portHandler(data, port);
} else {
handlerPromise.then((handler) => {
handler(data, port);
}).catch(console.error);
}
this.portHandler(data, port);
}

private _onPortDisconnect (port: chrome.runtime.Port, portId: string): void {
private _onPortDisconnect (port: chrome.runtime.Port, portId: string) {
if (this.connectionMap[portId]) {
delete this.connectionMap[portId];

// Set timeout to sleep
if (Object.keys(this.connectionMap).length === 0) {
this.sleepTimeout && clearTimeout(this.sleepTimeout);
this.sleepTimeout = setTimeout(() => {
// Reset active status
this.isActive = false;
this.sleepHandler && this.sleepHandler();
this.waitActiveHandler = createPromiseHandler<boolean>();
this.sleepHandler && this.sleepHandler().catch(console.error);
}, SLEEP_TIMEOUT);
}
}
Expand All @@ -137,7 +139,7 @@ export class ActionHandler {
const portId = this._getPortId(port);

port.onMessage.addListener((data: TransportRequestMessage<keyof RequestSignatures>) => {
this._onPortMessage(port, data, portId);
this._onPortMessage(port, data, portId).catch(console.error);
});

port.onDisconnect.addListener(() => {
Expand Down

0 comments on commit c39ce52

Please sign in to comment.