Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Trezor Integration #4296

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .husky/pre-commit
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
. "$(dirname "$0")/_/husky.sh"

npx lint-staged
node scripts/sync-expo-deps.js --dry-run
#node scripts/sync-expo-deps.js --dry-run
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This script references files I don't have upon cloning the repo and prevented me from commiting at all 🤔

source scripts/verify_workspace_package.sh
1 change: 1 addition & 0 deletions packages/app-extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"@solana/web3.js": "^1.63.1",
"@tanstack/react-query": "^5.17.19",
"@testing-library/jest-dom": "^5.11.4",
"@trezor/connect-web": "^9.1.12",
"@uidotdev/usehooks": "^2.4.1",
"bip39": "^3.1.0",
"click-to-react-component": "^1.1.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ export const KeyringTypeSelector = ({
onPress={() => onNext("ledger")}
textAlign="left"
/>
<BpSecondaryButton
iconBefore={<_HardwareIcon />}
label={t("have_hardware_wallet_trezor")}
justifyContent="flex-start"
onPress={() => onNext("trezor")}
textAlign="left"
/>

<BpSecondaryButton
iconBefore={<_KeyIcon />}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
} from "@coral-xyz/common";
import { useTranslation } from "@coral-xyz/i18n";
import { useOnboarding } from "@coral-xyz/recoil";
import { useTheme,XStack, YStack } from "@coral-xyz/tamagui";
import { useTheme, XStack, YStack } from "@coral-xyz/tamagui";

import { useSteps } from "../../../hooks/useSteps";
import { CreatePassword } from "../../common/Account/CreatePassword";
Expand Down Expand Up @@ -139,7 +139,9 @@ export const OnboardAccount = ({
/>,
]
: []),
...(keyringType === "mnemonic" || keyringType === "ledger"
...(keyringType === "mnemonic" ||
keyringType === "ledger" ||
keyringType === "trezor"
? // if were importing mnemonic of ledger we need to select the blockchiain
[
<BlockchainSelector
Expand All @@ -151,12 +153,15 @@ export const OnboardAccount = ({
}}
onNext={nextStep}
/>,
...(keyringType === "ledger" || action === "import"
...(keyringType === "ledger" ||
keyringType === "trezor" ||
action === "import"
? [
<ImportWallets
allowMultiple
autoSelect
newAccount
device={keyringType === "mnemonic" ? undefined : keyringType}
key="ImportWallets"
blockchain={blockchain!}
mnemonic={mnemonic!}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,13 @@ export function ImportMnemonic({
blockchain,
inputMnemonic,
ledger,
trezor,
publicKey,
}: {
blockchain: Blockchain;
inputMnemonic: boolean;
ledger?: boolean;
trezor?: boolean;
publicKey?: string;
keyringExists?: boolean;
}) {
Expand All @@ -140,6 +142,8 @@ export function ImportMnemonic({
publicKey ?? null
);
const navigation = useNavigation<any>();
const isHardware = ledger === true || trezor === true;
const device = ledger ? "ledger" : trezor ? "trezor" : undefined;

const closeParentDrawer = () => {
navigation.popToTop();
Expand All @@ -158,6 +162,12 @@ export function ImportMnemonic({
device: "ledger",
...walletDescriptor,
};
} else if (trezor) {
return {
type: BlockchainWalletInitType.HARDWARE,
device: "trezor",
...walletDescriptor,
};
} else if (mnemonic === true) {
return {
type: BlockchainWalletInitType.MNEMONIC,
Expand Down Expand Up @@ -215,7 +225,8 @@ export function ImportMnemonic({
key="ImportWallets"
fullscreen={false}
blockchain={blockchain}
mnemonic={ledger ? undefined : mnemonic}
mnemonic={isHardware ? undefined : mnemonic}
device={device}
recovery={publicKey}
onNext={async (walletDescriptors: Array<WalletDescriptor>) => {
await onComplete(walletDescriptors);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ const fundedAddressesLabel = "Funded Addresses";
export function ImportWallets({
blockchain,
mnemonic,
device,
onNext,
// onError,
allowMultiple = true,
Expand All @@ -54,6 +55,7 @@ export function ImportWallets({
allowMultiple?: boolean;
autoSelect?: boolean;
fullscreen?: boolean;
device?: "ledger" | "trezor";
}) {
const userClient = useRecoilValue(userClientAtom);
const blockchainConfig = useRecoilValue(blockchainConfigAtom(blockchain));
Expand Down Expand Up @@ -117,26 +119,37 @@ export function ImportWallets({
const walletPreview =
mnemonic === undefined
? ({
type: BlockchainWalletPreviewType.HARDWARE,
derivationPaths: fetchDerivationPaths,
blockchain,
} as BlockchainWalletPublicKeyRequest<BlockchainWalletPreviewType.HARDWARE>)
type: BlockchainWalletPreviewType.HARDWARE,
derivationPaths: fetchDerivationPaths,
device: device,
blockchain,
} as BlockchainWalletPublicKeyRequest<BlockchainWalletPreviewType.HARDWARE>)
: ({
type: BlockchainWalletPreviewType.MNEMONIC,
mnemonic: typeof mnemonic === "string" ? mnemonic : undefined,
derivationPaths: fetchDerivationPaths,
blockchain,
} as BlockchainWalletPublicKeyRequest<BlockchainWalletPreviewType.MNEMONIC>);
type: BlockchainWalletPreviewType.MNEMONIC,
mnemonic: typeof mnemonic === "string" ? mnemonic : undefined,
derivationPaths: fetchDerivationPaths,
blockchain,
} as BlockchainWalletPublicKeyRequest<BlockchainWalletPreviewType.MNEMONIC>);
console.log(
"[DEBUG] [ImportWallets] loadPublicKeys walletPreview",
walletPreview
);
console.log(
"[DEBUG] [ImportWallets] loadPublicKeys userClient",
userClient
);

return safeClientResponse(userClient.previewWallets(walletPreview))
.then((result_) => {
setLoadPublicKeysError(false)
console.log("[DEBUG] [ImportWallets] loadPublicKeys success");
setLoadPublicKeysError(false);
const result = result_.wallets[0].walletDescriptors.map(
(descriptor) => ({
...descriptor,
mnemonic, // bring back option for mnemonic === true to differentiat privatkey_derived & mnemnoic
})
) as WalletDescriptor[];
console.log("[DEBUG] [ImportWallets] loadPublicKeys result", result_);
setImportedPublicKeys(
result_.wallets[0].walletDescriptors
.filter((descriptor) => descriptor.imported)
Expand All @@ -153,9 +166,10 @@ export function ImportWallets({
return result.find((fetched) => fetched.derivationPath === path)!;
});
})
.catch(() => {
setLoadPublicKeysError(true)
return []
.catch((e) => {
console.log("[DEBUG] [ImportWallets] loadPublicKeys error", e);
setLoadPublicKeysError(true);
return [];
});
},
[blockchain, userClient, walletDescriptorsCache]
Expand Down Expand Up @@ -213,12 +227,20 @@ export function ImportWallets({
blockchain: Blockchain;
}[]
) => {
console.log(
"[DEBUG] [ImportWallets] fetchPublicKeys newWalletDescriptors",
newWalletDescriptors
);
if (!isFundedAddresses) {
setWalletDescriptors(newWalletDescriptors);
}
const balances = await loadBalances(
newWalletDescriptors.map((descriptor) => descriptor.publicKey)
);
console.log(
"[DEBUG] [ImportWallets] fetchPublicKeys balances",
balances
);
const balancesObj = Object.fromEntries(
balances
.sort((a, b) =>
Expand Down Expand Up @@ -272,7 +294,6 @@ export function ImportWallets({
// setWalletDescriptors,
]);


useEffect(() => {
fetchPublicKeys();
}, [fetchPublicKeys]);
Expand Down Expand Up @@ -376,13 +397,14 @@ export function ImportWallets({
const renderItem = useCallback(
(item: WalletDescriptor) => {
const { publicKey, derivationPath } = item;
const displayBalance = `${balances?.[publicKey]
? (+ethers.utils.formatUnits(
balances?.[publicKey],
decimals
)).toFixed(4)
: "-"
} ${symbol}`;
const displayBalance = `${
balances?.[publicKey]
? (+ethers.utils.formatUnits(
balances?.[publicKey],
decimals
)).toFixed(4)
: "-"
} ${symbol}`;

const label = formatWalletAddress(item.publicKey, 5);
const disabled = isDisabledPublicKey(publicKey);
Expand Down Expand Up @@ -502,7 +524,7 @@ export function ImportWallets({
<YStack f={1} width="100%">
<Scrollbar style={{ flex: 1 }}>
{walletDescriptors === null ||
(balances === null && isFundedAddresses) ? (
(balances === null && isFundedAddresses) ? (
<Loader />
) : !derivationPathInputError && walletDescriptors.length > 0 ? (
<YStack space="$2" paddingHorizontal="$4">
Expand All @@ -524,7 +546,7 @@ export function ImportWallets({
<BpPrimaryButton
label={t("try_again")}
onPress={() => {
fetchPublicKeys()
fetchPublicKeys();
}}
/>
) : (
Expand Down
9 changes: 8 additions & 1 deletion packages/app-extension/src/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,26 @@
}
}
},
"content-security-policy": {
"extension_pages": "'frame-src': 'self' 'https://connect.trezor.io/*' 'https://connect.trezor.io/'"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"run_at": "document_start",
"exclude_globs": ["*chrome-extension*"],
"js": ["contentScript.js"],
"all_frames": true
},
{
"matches": ["*://connect.trezor.io/*/popup.html"],
"js": ["vendor/trezor-content-script.js"]
}
],
"icons": {
"16": "anchor.png",
"192": "anchor.png",
"512": "anchor.png"
},
"permissions": ["alarms", "storage", "background"]
"permissions": ["alarms", "storage", "background", "*://connect.trezor.io/*"]
}
2 changes: 2 additions & 0 deletions packages/app-extension/src/webextension/trezor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Contents of this directory copied directly from
https://github.com/trezor/connect/tree/develop/src/js/plugins/webextension
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
Passing messages from background script to popup
*/

let port = chrome.runtime.connect({ name: "trezor-connect" });
port.onMessage.addListener((message) => {
window.postMessage(message, window.location.origin);
});
port.onDisconnect.addListener(() => {
port = null;
});

/*
Passing messages from popup to background script
*/

window.addEventListener("message", (event) => {
if (port && event.source === window && event.data) {
port.postMessage({ data: event.data });
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta
name="viewport"
content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"
/>
<title>TrezorConnect | Trezor</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="Trezor [email protected]" />
<meta name="robots" content="noindex, nofollow" />
<meta name="title" content="Trezor Connect" />
<meta name="theme-color" content="#ffffff" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
position: relative;
width: 100%;
height: 100%;
min-height: 500px;
min-width: 328px;
}
</style>
</head>
<body>
<script
type="text/javascript"
src="./vendor/trezor-usb-permissions.js"
></script>
</body>
</html>
Loading