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

Feat: MV3 migration #219

Merged
merged 5 commits into from
Aug 29, 2024
Merged
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
27 changes: 23 additions & 4 deletions packages/sysweb3-core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { parseJsonRecursively } from './utils';

interface IStateStorageClient {
getItem(key: string): string | null;
removeItem(key: string): void;
Expand Down Expand Up @@ -25,7 +27,7 @@ const defaultStorage =
typeof window !== 'undefined' ? window.localStorage : undefined;

const StateStorageDb = (
storageClient: IStateStorageClient | undefined = defaultStorage
storageClient: any | undefined = defaultStorage
): IKeyValueDb => {
let keyPrefix = 'sysweb3-';

Expand All @@ -45,12 +47,26 @@ const StateStorageDb = (
const set = (key: string, value: any) => {
if (!storageClient) return;

if ('set' in storageClient) {
storageClient.set({ [keyPrefix + key]: value });
return;
}

storageClient.setItem(keyPrefix + key, JSON.stringify(value));
};

const get = (key: string): any => {
const get = async (key: string): Promise<any> => {
if (!storageClient) return;

if ('get' in storageClient) {
const value = await storageClient.get(keyPrefix + key);
if (value) {
const result = parseJsonRecursively(value);
return result[keyPrefix + key];
}
return {};
}

const value = storageClient.getItem(keyPrefix + key);
if (value) {
return JSON.parse(value);
Expand All @@ -59,6 +75,10 @@ const StateStorageDb = (

const deleteItem = (key: string) => {
if (!storageClient) return;
if ('remove' in storageClient) {
storageClient.remove(keyPrefix + key);
return;
}

storageClient.removeItem(keyPrefix + key);
};
Expand Down Expand Up @@ -109,9 +129,8 @@ const CrossPlatformDi = () => {
};
};

const crossPlatformDi = CrossPlatformDi();

const SysWeb3Di = () => {
const crossPlatformDi = CrossPlatformDi();
const getStateStorageDb = (): IKeyValueDb => {
return crossPlatformDi.getStateStorageDb();
};
Expand Down
18 changes: 18 additions & 0 deletions packages/sysweb3-core/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export function parseJsonRecursively(jsonString: string) {
try {
const parsed = JSON.parse(jsonString);

if (typeof parsed === 'object' && parsed !== null) {
Object.keys(parsed).forEach((key) => {
if (typeof parsed[key] === 'string') {
parsed[key] = parseJsonRecursively(parsed[key]);
}
});
}

return parsed;
} catch (error) {
// if not a valid JSON, return the param
return jsonString;
}
}
3 changes: 2 additions & 1 deletion packages/sysweb3-keyring/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"@pollum-io/sysweb3-network": "^1.0.95",
"@pollum-io/sysweb3-utils": "^1.1.232",
"@trezor/connect-web": "^9.1.5",
"@trezor/connect-webextension": "^9.3.0",
"@trezor/utxo-lib": "^1.0.12",
"axios": "^1.6.0",
"bip32-path": "^0.4.2",
Expand Down Expand Up @@ -62,4 +63,4 @@
"@types/lodash": "^4.14.200",
"@types/node": "^20.8.10"
}
}
}
26 changes: 13 additions & 13 deletions packages/sysweb3-keyring/src/keyring-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export class KeyringManager implements IKeyringManager {
//local variables
private hd: SyscoinHDSigner | null;
private syscoinSigner: SyscoinMainSigner | undefined;
private trezorSigner: TrezorKeyring;
public trezorSigner: TrezorKeyring;
public ledgerSigner: LedgerKeyring;
private memMnemonic: string;
private memPassword: string;
Expand Down Expand Up @@ -265,10 +265,10 @@ export class KeyringManager implements IKeyringManager {
}
}

private recoverLastSessionPassword(pwd: string): string {
private async recoverLastSessionPassword(pwd: string) {
//As before locking the wallet we always keep the value of the last currentSessionSalt correctly stored in vault,
//we use the value in vault instead of the one present in the class to get the last correct value for sessionPassword
const initialVaultKeys = this.storage.get('vault-keys');
const initialVaultKeys = await this.storage.get('vault-keys');

//Here we need to validate if user has the currentSessionSalt in the vault-keys, because for Pali Users that
//already has accounts created in some old version this value will not be in the storage. So we need to check it
Expand Down Expand Up @@ -297,8 +297,8 @@ export class KeyringManager implements IKeyringManager {
wallet?: IWalletState | null;
}> => {
try {
const { hash, salt } = this.storage.get('vault-keys');
const utf8ErrorData = this.storage.get('utf8Error');
const { hash, salt } = await this.storage.get('vault-keys');
const utf8ErrorData = await this.storage.get('utf8Error');
const hasUtf8Error = utf8ErrorData ? utf8ErrorData.hasUtf8Error : false;
const hashPassword = this.encryptSHA512(password, salt);

Expand All @@ -311,7 +311,7 @@ export class KeyringManager implements IKeyringManager {
let wallet: IWalletState | null = null;

if (hashPassword === hash) {
this.sessionPassword = this.recoverLastSessionPassword(password);
this.sessionPassword = await this.recoverLastSessionPassword(password);

const isHdCreated = !!this.hd;

Expand Down Expand Up @@ -339,7 +339,7 @@ export class KeyringManager implements IKeyringManager {
await this.restoreWallet(isHdCreated, password);
}

this.updateWalletKeys(password);
await this.updateWalletKeys(password);
}

return {
Expand Down Expand Up @@ -400,7 +400,7 @@ export class KeyringManager implements IKeyringManager {
if (!this.memPassword) {
throw new Error('Create a password first');
}
let { mnemonic } = getDecryptedVault(this.memPassword);
let { mnemonic } = await getDecryptedVault(this.memPassword);
mnemonic = CryptoJS.AES.decrypt(mnemonic, this.memPassword).toString(
CryptoJS.enc.Utf8
);
Expand Down Expand Up @@ -527,14 +527,14 @@ export class KeyringManager implements IKeyringManager {
this.sessionPassword
).toString();

public getSeed = (pwd: string) => {
public getSeed = async (pwd: string) => {
const genPwd = this.encryptSHA512(pwd, this.currentSessionSalt);
if (!this.sessionPassword) {
throw new Error('Unlock wallet first');
} else if (this.sessionPassword !== genPwd) {
throw new Error('Invalid password');
}
let { mnemonic } = getDecryptedVault(pwd);
let { mnemonic } = await getDecryptedVault(pwd);
mnemonic = CryptoJS.AES.decrypt(mnemonic, pwd).toString(CryptoJS.enc.Utf8);

return mnemonic;
Expand Down Expand Up @@ -1627,7 +1627,7 @@ export class KeyringManager implements IKeyringManager {

private async restoreWallet(hdCreated: boolean, pwd: string) {
if (!this.sessionMnemonic) {
let { mnemonic } = getDecryptedVault(pwd);
let { mnemonic } = await getDecryptedVault(pwd);
mnemonic = CryptoJS.AES.decrypt(mnemonic, pwd).toString(
CryptoJS.enc.Utf8
);
Expand Down Expand Up @@ -1696,7 +1696,7 @@ export class KeyringManager implements IKeyringManager {

private async updateWalletKeys(pwd: string) {
try {
const vaultKeys = this.storage.get('vault-keys');
const vaultKeys = await this.storage.get('vault-keys');

//Update values
this.guaranteeUpdatedPrivateValues(pwd);
Expand All @@ -1716,7 +1716,7 @@ export class KeyringManager implements IKeyringManager {
let decryptedXprv = '';

if (!isBitcoinBased) {
let { mnemonic } = getDecryptedVault(pwd);
let { mnemonic } = await getDecryptedVault(pwd);
mnemonic = CryptoJS.AES.decrypt(mnemonic, pwd).toString(
CryptoJS.enc.Utf8
);
Expand Down
2 changes: 1 addition & 1 deletion packages/sysweb3-keyring/src/ledger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ export class LedgerKeyring {
true
).toString('hex');

let messageHash = null;
let messageHash: string | null = null;

if (primaryType !== 'EIP712Domain') {
messageHash = TypedDataUtils.hashStruct(
Expand Down
11 changes: 11 additions & 0 deletions packages/sysweb3-keyring/src/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,17 @@ export class CustomJsonRpcProvider extends ethers.providers.JsonRpcProvider {
this.signal = signal;
this._pendingBatchAggregator = null;
this._pendingBatch = null;

this.bindMethods();
}

private bindMethods() {
const proto = Object.getPrototypeOf(this);
for (const key of Object.getOwnPropertyNames(proto)) {
if (typeof this[key] === 'function' && key !== 'constructor') {
this[key] = this[key].bind(this);
}
}
}

private throttledRequest = <T>(requestFn: () => Promise<T>): Promise<T> => {
Expand Down
4 changes: 2 additions & 2 deletions packages/sysweb3-keyring/src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ export const setEncryptedVault = (decryptedVault: any, pwd: string) => {
storage.set('vault', encryptedVault.toString());
};

export const getDecryptedVault = (pwd: string) => {
const vault = storage.get('vault');
export const getDecryptedVault = async (pwd: string) => {
const vault = await storage.get('vault');

const decryptedVault = CryptoJS.AES.decrypt(vault, pwd).toString(
CryptoJS.enc.Utf8
Expand Down
23 changes: 11 additions & 12 deletions packages/sysweb3-keyring/src/trezor/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import TrezorConnect, {
DEVICE_EVENT,
EthereumTransaction,
EthereumTransactionEIP1559,
} from '@trezor/connect-web';
// @ts-ignore
} from '@trezor/connect-webextension';
import { address } from '@trezor/utxo-lib';
import bitcoinops from 'bitcoin-ops';
import { Transaction, payments, script } from 'bitcoinjs-lib';
Expand Down Expand Up @@ -72,7 +73,6 @@ export class TrezorKeyring {
this.model = event.payload.features.model;
}
});
this.init();
}

/**
Expand All @@ -82,16 +82,15 @@ export class TrezorKeyring {
* @returns true, if trezor was initialized successfully and false, if some error happen
*/

private async init() {
if (window) {
window.TrezorConnect = TrezorConnect;
}
public async init() {
try {
await TrezorConnect.init({
manifest: TREZOR_CONNECT_MANIFEST,
lazyLoad: true,
popup: true,
connectSrc: 'https://connect.trezor.io/9/',
_extendWebextensionLifetime: true,
transports: ['BridgeTransport', 'WebUsbTransport'], // Transport protocols to be used
});
return true;
} catch (error) {
Expand Down Expand Up @@ -138,14 +137,14 @@ export class TrezorKeyring {
path: keypath,
coin: coin,
})
.then((response) => {
.then((response: any) => {
if (response.success) {
resolve(response.payload);
}
// @ts-ignore
reject(response.payload.error);
})
.catch((error) => {
.catch((error: any) => {
console.error('TrezorConnectError', error);
reject(error);
});
Expand Down Expand Up @@ -638,7 +637,7 @@ export class TrezorKeyring {
message: Web3.utils.stripHexPrefix(message),
hex: true,
})
.then((response) => {
.then((response: any) => {
if (response.success) {
if (
address &&
Expand All @@ -655,7 +654,7 @@ export class TrezorKeyring {
);
}
})
.catch((e) => {
.catch((e: any) => {
reject(new Error(e.toString() || 'Unknown error'));
});
// This is necessary to avoid popup collision
Expand Down Expand Up @@ -703,7 +702,7 @@ export class TrezorKeyring {
true
).toString('hex');

let messageHash = null;
let messageHash: string | null = null;

if (primaryType !== 'EIP712Domain') {
messageHash = TypedDataUtils.hashStruct(
Expand Down Expand Up @@ -860,7 +859,7 @@ export class TrezorKeyring {
})),
});
if (success) {
return payload.map((item) => item.address);
return payload.map((item: any) => item.address);
}
} catch (error) {
return error;
Expand Down
2 changes: 2 additions & 0 deletions packages/sysweb3-keyring/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
} from 'web3-core';

import { LedgerKeyring } from './ledger';
import { TrezorKeyring } from './trezor';
import { INetwork, INetworkType } from '@pollum-io/sysweb3-network';
import {
ITokenMint,
Expand Down Expand Up @@ -208,6 +209,7 @@ export interface IKeyringManager {
isUnlocked: () => boolean;
logout: () => void;
ledgerSigner: LedgerKeyring;
trezorSigner: TrezorKeyring;
setActiveAccount: (
accountId: number,
accountType: KeyringAccountType
Expand Down
7 changes: 5 additions & 2 deletions packages/sysweb3-keyring/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@
"outDir": "dist/cjs",
"declarationDir": "dist/types",
"resolveJsonModule": true,
"noImplicitAny": false,
"strictPropertyInitialization": false
},
"include": ["src"]
}
"include": [
"src"
]
}
Loading
Loading