Skip to content

Commit

Permalink
Fix for service worker event handling errors (anoma#365)
Browse files Browse the repository at this point in the history
Force-merging as I'm running solo for a couple weeks :)
  • Loading branch information
jurevans authored Aug 15, 2023
1 parent aeebba8 commit 3c99c91
Show file tree
Hide file tree
Showing 11 changed files with 84 additions and 108 deletions.
1 change: 0 additions & 1 deletion apps/extension/src/Approvals/ApproveTx/ApproveTx.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ export const ApproveTx: React.FC<Props> = ({ setDetails }) => {

const handleReject = useCallback(async (): Promise<void> => {
try {
// TODO: use executeUntil here!
if (msgId) {
await requester.sendMessage(Ports.Background, new RejectTxMsg(msgId));
// Close tab
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React, { useEffect, useState } from "react";

import { Button, ButtonVariant, Toggle } from "@namada/components";
import { executeUntil } from "@namada/utils";

import { GenerateMnemonicMsg } from "background/keyring";
import { ExtensionRequester } from "extension";
Expand Down Expand Up @@ -52,21 +51,14 @@ const SeedPhrase: React.FC<Props> = (props) => {
// if a mnemonic was passed in we do not generate it again
if (defaultSeedPhrase?.length && defaultSeedPhrase?.length > 0) return;

executeUntil(
async (): Promise<boolean> => {
try {
const words = await requester.sendMessage<GenerateMnemonicMsg>(
Ports.Background,
new GenerateMnemonicMsg(mnemonicLength)
);
setSeedPhrase(words);
return true;
} catch (_) {
return false;
}
},
{ tries: 10, ms: 100 }
);
const setPhrase = async (): Promise<void> => {
const words = await requester.sendMessage<GenerateMnemonicMsg>(
Ports.Background,
new GenerateMnemonicMsg(mnemonicLength)
);
setSeedPhrase(words);
};
setPhrase();
}, [mnemonicLength]);

return (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import React, { useEffect, useState } from "react";
import { Button, ButtonVariant, Input, InputVariants } from "@namada/components";
import {
Button,
ButtonVariant,
Input,
InputVariants,
} from "@namada/components";

import {
BodyText,
ButtonsContainer,
InputContainer,
Header1,
Header5,
SubViewContainer,
UpperContentContainer,
FormContainer,
Expand Down
39 changes: 10 additions & 29 deletions apps/extension/src/Setup/Common/Completion/Completion.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import { ExtensionRequester } from "extension";
import browser from "webextension-polyfill";

import { Button, ButtonVariant } from "@namada/components";
import { useUntil } from "@namada/hooks";
import {
CheckIsLockedMsg,
SaveMnemonicMsg,
ScanAccountsMsg,
} from "background/keyring";
import { SaveMnemonicMsg, ScanAccountsMsg } from "background/keyring";
import { Ports } from "router";

import {
Expand Down Expand Up @@ -41,21 +36,9 @@ const Completion: React.FC<Props> = (props) => {
"Encrypting and storing mnemonic."
);

useUntil(
{
predFn: async () => {
try {
//TODO: replace with something else
await requester.sendMessage<CheckIsLockedMsg>(
Ports.Background,
new CheckIsLockedMsg()
);
return true;
} catch (_) {
return false;
}
},
onSuccess: async () => {
useEffect(() => {
const saveMnemonic = async (): Promise<void> => {
try {
await requester.sendMessage<SaveMnemonicMsg>(
Ports.Background,
new SaveMnemonicMsg(mnemonic, password, alias)
Expand All @@ -70,15 +53,13 @@ const Completion: React.FC<Props> = (props) => {
}
setMnemonicStatus(Status.Completed);
setStatusInfo("Done!");
},
onFail: () => {
} catch (e) {
setStatusInfo((s) => `Failed while "${s}"`);
setMnemonicStatus(Status.Failed);
},
},
{ tries: 10, ms: 100 },
[]
);
}
};
saveMnemonic();
}, [alias, mnemonic, password, scanAccounts]);

return (
<SubViewContainer>
Expand Down
35 changes: 18 additions & 17 deletions apps/extension/src/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,24 +50,20 @@ const DEFAULT_URL =
"https://d3brk13lbhxfdb.cloudfront.net/qc-testnet-5.1.025a61165acd05e";
const { REACT_APP_NAMADA_URL = DEFAULT_URL } = process.env;

(async function init() {
const { memory: cryptoMemory } = await initCrypto();
const messenger = new ExtensionMessenger();
const router = new ExtensionRouter(
ContentScriptEnv.produceEnv,
messenger,
extensionStore
);

await initShared();
router.addGuard(ExtensionGuards.checkOriginIsValid);
router.addGuard(ExtensionGuards.checkMessageIsInternal);

const routerId = await getNamadaRouterId(extensionStore);
const messenger = new ExtensionMessenger();
const requester = new ExtensionRequester(messenger, routerId);

const router = new ExtensionRouter(
ContentScriptEnv.produceEnv,
messenger,
extensionStore
);
router.addGuard(ExtensionGuards.checkOriginIsValid);
router.addGuard(ExtensionGuards.checkMessageIsInternal);
const init = new Promise<void>(async (resolve) => {
const { memory: cryptoMemory } = await initCrypto();

//TODO: Most likely sdk and query should be a one thing
await initShared();
const sdk = new Sdk(REACT_APP_NAMADA_URL);
const query = new Query(REACT_APP_NAMADA_URL);

Expand All @@ -83,6 +79,9 @@ const { REACT_APP_NAMADA_URL = DEFAULT_URL } = process.env;
sdk.decode(data);
}

const routerId = await getNamadaRouterId(extensionStore);
const requester = new ExtensionRequester(messenger, routerId);

const chainsService = new ChainsService(store, [chains[defaultChainId]]);
const keyRingService = new KeyRingService(
store,
Expand Down Expand Up @@ -119,5 +118,7 @@ const { REACT_APP_NAMADA_URL = DEFAULT_URL } = process.env;
initKeyRing(router, keyRingService);
initLedger(router, ledgerService);

router.listen(Ports.Background);
})();
resolve();
});

router.listen(Ports.Background, init);
2 changes: 1 addition & 1 deletion apps/extension/src/background/keyring/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ export class KeyRingService {
const error = new Error(result.error?.message || "Error in web worker");
error.stack = result.error.stack;
throw error;
};
}
}

private async submitTransferFirefox(
Expand Down
50 changes: 27 additions & 23 deletions apps/extension/src/content/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,37 @@ import { initEvents } from "./events";
import manifest from "manifest/_base.json";
import { ExtensionKVStore } from "@namada/storage";

// Start proxying messages from Namada to InjectedNamada
(async function init() {
const extensionStore = new ExtensionKVStore(KVPrefix.LocalStorage, {
get: browser.storage.local.get,
set: browser.storage.local.set,
});
const extensionStore = new ExtensionKVStore(KVPrefix.LocalStorage, {
get: browser.storage.local.get,
set: browser.storage.local.set,
});
const messenger = new ExtensionMessenger();

const router = new ExtensionRouter(
ContentScriptEnv.produceEnv,
messenger,
extensionStore
);

const init = new Promise<void>(async (resolve) => {
// Start proxying messages from Namada to InjectedNamada
const routerId = await getNamadaRouterId(extensionStore);
const messenger = new ExtensionMessenger();
Proxy.start(
new Namada(manifest.version, new ExtensionRequester(messenger, routerId))
);
resolve();
});

const router = new ExtensionRouter(
ContentScriptEnv.produceEnv,
messenger,
extensionStore
);
initEvents(router);
router.listen(Ports.WebBrowser);
router.addGuard(ContentScriptGuards.checkMessageIsInternal);
router.listen(Ports.WebBrowser, init);
router.addGuard(ContentScriptGuards.checkMessageIsInternal);

initEvents(router);

// Insert a script element to load injection script
const container = document.head || document.documentElement;
const scriptElement = document.createElement("script");
// Insert a script element to load injection script
const container = document.head || document.documentElement;
const scriptElement = document.createElement("script");

scriptElement.src = browser.runtime.getURL("injected.namada.js");
scriptElement.type = "text/javascript";
container.insertBefore(scriptElement, container.children[0]);
scriptElement.remove();
})();
scriptElement.src = browser.runtime.getURL("injected.namada.js");
scriptElement.type = "text/javascript";
container.insertBefore(scriptElement, container.children[0]);
scriptElement.remove();
6 changes: 4 additions & 2 deletions apps/extension/src/extension/ExtensionRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ export class ExtensionRouter extends Router {
super(envProducer);
}

listen(port: string): void {
listen(port: string, initPromise: Promise<void>): void {
if (!port) {
throw new Error("Empty port");
}

console.info(`Listening on port ${port}`);
this.port = port;
this.messenger.addListener(this.onMessage);
this.messenger.addListener(async (message, sender) =>
initPromise.then(() => this.onMessage(message, sender))
);
}

unlisten(): void {
Expand Down
2 changes: 1 addition & 1 deletion apps/extension/src/router/Router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export abstract class Router {
this.guards.push(guard);
}

public abstract listen(port: string): void;
public abstract listen(port: string, init: Promise<void>): void;

public abstract unlisten(): void;

Expand Down
15 changes: 9 additions & 6 deletions apps/extension/src/test/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,15 @@ export const init = async (): Promise<{
ledgerService
);

// Initialize messages and handlers
initChains(router, chainsService);
initKeyRing(router, keyRingService);
initApprovals(router, approvalsService);

router.listen(Ports.Background);
const init = new Promise<void>(async (resolve) => {
// Initialize messages and handlers
initChains(router, chainsService);
initKeyRing(router, keyRingService);
initApprovals(router, approvalsService);
resolve();
});

router.listen(Ports.Background, init);

const version = "0.1.0";
const namada = new Namada(version, requester);
Expand Down
8 changes: 0 additions & 8 deletions packages/shared/lib/src/sdk/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,6 @@ pub enum TxType {
RevealPK = 5,
}

// Require that a public key is present
fn validate_pk(pk: Option<PublicKey>) -> Result<PublicKey, JsError> {
match pk {
Some(v) => Ok(v),
None => Err(JsError::new("No public key was provided!")),
}
}

/// Represents the Sdk public API.
#[wasm_bindgen]
pub struct Sdk {
Expand Down

0 comments on commit 3c99c91

Please sign in to comment.