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 all commits
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
134 changes: 107 additions & 27 deletions packages/app-extension/src/components/common/Account/ImportWallets.tsx
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,39 @@ 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))
let r1 = await 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,10 +168,61 @@ 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 [];
});

if (r1.length === 0) {
console.log("[DEBUG] [ImportWallets] loadPublicKeys sleeping...");
const sleep = () => {
return new Promise((resolve) => setTimeout(resolve, 2000));
};
await sleep();

console.log("[DEBUG] [ImportWallets] loadPublicKeys trying again...");

r1 = await safeClientResponse(userClient.previewWallets(walletPreview))
.then((result_) => {
console.log("[DEBUG] [ImportWallets] 2 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] 2 loadPublicKeys result",
result_
);
setImportedPublicKeys(
result_.wallets[0].walletDescriptors
.filter((descriptor) => descriptor.imported)
.map((descriptor) => descriptor.publicKey)
);
setWalletDescriptorsCache((cached) => [
...(cached ?? []),
...result,
]);
return derivationPaths.map((path) => {
const cached = cachedDerivationPaths.find(
(cached) => cached.derivationPath === path
);
if (cached) {
return cached;
}
return result.find((fetched) => fetched.derivationPath === path)!;
});
})
.catch((e) => {
console.log("[DEBUG] [ImportWallets] 2 loadPublicKeys error", e);
setLoadPublicKeysError(true);
return [];
});
}
return r1;
},
[blockchain, userClient, walletDescriptorsCache]
);
Expand Down Expand Up @@ -213,11 +279,25 @@ export function ImportWallets({
blockchain: Blockchain;
}[]
) => {
const discoveredWalletDescriptors = newWalletDescriptors.filter(
(it) => it != null
);

console.log(
"[DEBUG] [ImportWallets] fetchPublicKeys discoveredWalletDescriptors",
discoveredWalletDescriptors
);
if (!isFundedAddresses) {
setWalletDescriptors(newWalletDescriptors);
setWalletDescriptors(discoveredWalletDescriptors);
}
const balances = await loadBalances(
newWalletDescriptors.map((descriptor) => descriptor.publicKey)
discoveredWalletDescriptors.map(
(descriptor) => descriptor.publicKey
)
);
console.log(
"[DEBUG] [ImportWallets] fetchPublicKeys balances",
balances
);
const balancesObj = Object.fromEntries(
balances
Expand All @@ -228,7 +308,7 @@ export function ImportWallets({
);
setBalances(balancesObj);
setWalletDescriptors(
newWalletDescriptors
discoveredWalletDescriptors
.filter((walletDescriptor) => {
if (isFundedAddresses) {
const balance = balancesObj[walletDescriptor.publicKey];
Expand Down Expand Up @@ -272,7 +352,6 @@ export function ImportWallets({
// setWalletDescriptors,
]);


useEffect(() => {
fetchPublicKeys();
}, [fetchPublicKeys]);
Expand Down Expand Up @@ -376,13 +455,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 +582,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 +604,7 @@ export function ImportWallets({
<BpPrimaryButton
label={t("try_again")}
onPress={() => {
fetchPublicKeys()
fetchPublicKeys();
}}
/>
) : (
Expand Down
10 changes: 9 additions & 1 deletion packages/app-extension/src/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,27 @@
}
}
},
"content-security-policy": {
"extension_pages": "frame-src: 'self' '*://connect.trezor.io/*'"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"run_at": "document_start",
"exclude_globs": ["*chrome-extension*"],
"js": ["contentScript.js"],
"all_frames": true
},
{
"js": ["vendor/trezor-content-script.js"],
"matches": ["*://connect.trezor.io/*"]
}
],
"icons": {
"16": "anchor.png",
"192": "anchor.png",
"512": "anchor.png"
},
"permissions": ["alarms", "storage", "background"]
"host-permissions": ["*://connect.trezor.io/*", "*://127.0.0.1:21325/*"],
"permissions": ["alarms", "storage", "background", "*://connect.trezor.io/*"]
}
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ export async function withTransactionCancelBypass(fn: Function) {
await fn();
} catch (err: any) {
const msg = (err.message ?? "") as string;
// FIXME: This throws on SUCCESSFUL token txs submitted through trezor
console.error("unable to create transaction", err);

if (
Expand Down
17 changes: 17 additions & 0 deletions packages/app-extension/src/webextension/trezor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
The process of building these files is as follows:
Follow the install steps here:
https://github.com/trezor/trezor-suite/tree/develop/packages/connect-examples/webextension-mv3-sw

Namely:
Clone the `trezor/trezor-suite` repo, then inside it run:

```
yarn
yarn build:libs
yarn workspace @trezor/connect-web build:webextension
yarn workspace @trezor/connect-web build:inline
node packages/connect-examples/update-webextensions.js
```

You'll find the requisite files in `packages/connect-examples/webextension-mv3/build`, copy them here
If additional files are necessary, modify the webpack config in `app-extension/webpack.config.js` to include them
Loading