Skip to content

Commit

Permalink
Merge branch 'develop' into feat/bridge-v2
Browse files Browse the repository at this point in the history
  • Loading branch information
vvvvvv1vvvvvv committed Nov 11, 2024
2 parents ed2d6b0 + 7da003c commit 30ecb71
Show file tree
Hide file tree
Showing 18 changed files with 126 additions and 119 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"@rabby-wallet/rabby-action": "0.1.4",
"@rabby-wallet/rabby-api": "0.8.4",
"@rabby-wallet/rabby-security-engine": "2.0.7",
"@rabby-wallet/rabby-swap": "0.0.40",
"@rabby-wallet/rabby-swap": "0.0.42",
"@rabby-wallet/widgets": "1.0.9",
"@rematch/core": "2.2.0",
"@rematch/select": "3.1.2",
Expand Down
14 changes: 13 additions & 1 deletion src/background/controller/provider/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -473,13 +473,25 @@ class ProviderController extends BaseController {
reported: false,
};

let signedTx;
try {
const signedTx = await keyringService.signTransaction(
signedTx = await keyringService.signTransaction(
keyring,
tx,
txParams.from,
opts
);
} catch (e) {
const errObj =
typeof e === 'object'
? { message: e.message }
: ({ message: e } as any);
errObj.method = EVENTS.COMMON_HARDWARE.REJECTED;

throw errObj;
}

try {
if (
currentAccount.type === KEYRING_TYPE.GnosisKeyring ||
currentAccount.type === KEYRING_TYPE.CoboArgusKeyring
Expand Down
20 changes: 13 additions & 7 deletions src/background/controller/provider/rpcFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,15 +263,21 @@ const flowContext = flow
})
.then(resolve)
.catch((e: any) => {
const payload = {
method: EVENTS.SIGN_FINISHED,
params: {
success: false,
errorMsg: e?.message || JSON.stringify(e),
},
};
if (e.method) {
payload.method = e.method;
payload.params = e.message;
}

Sentry.captureException(e);
if (isSignApproval(approvalType)) {
eventBus.emit(EVENTS.broadcastToUI, {
method: EVENTS.SIGN_FINISHED,
params: {
success: false,
errorMsg: e?.message || JSON.stringify(e),
},
});
eventBus.emit(EVENTS.broadcastToUI, payload);
}
})
);
Expand Down
38 changes: 12 additions & 26 deletions src/background/service/keyring/eth-ledger-keyring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,10 +159,19 @@ class LedgerBridgeKeyring {
const path = hdPath ? this._toLedgerPath(hdPath) : this.hdPath;

await this.makeApp();
const res = await this.app!.getAddress(path, false, true);
const { address } = res;
let res: { address: string };
try {
res = await this.app!.getAddress(path, false, true);
} catch (e) {
if (e.name === 'DisconnectedDeviceDuringOperation') {
await this.cleanUp();
return this.unlock(hdPath, force);
} else {
throw e;
}
}

return address;
return res?.address;
}

addAccounts(n = 1) {
Expand Down Expand Up @@ -235,7 +244,6 @@ class LedgerBridgeKeyring {
signTransaction(address, tx) {
return this.signHelper.invoke(async () => {
// make sure the previous transaction is cleaned up
await this._reconnect();

// transactions built with older versions of ethereumjs-tx have a
// getChainId method that newer versions do not. Older versions are mutable
Expand Down Expand Up @@ -296,20 +304,6 @@ class LedgerBridgeKeyring {
});
}

async _reconnect() {
await this.cleanUp();

let count = 0;
// wait connect the WebHID
while (!this.app) {
await this.makeApp();
await new Promise((resolve) => setTimeout(resolve, 100));
if (count++ > 50) {
throw new Error('Ledger: Failed to connect to Ledger');
}
}
}

async _signTransaction(address, rawTxHex, handleSigning) {
const hdPath = await this.unlockAccountByAddress(address);
await this.makeApp(true);
Expand All @@ -326,8 +320,6 @@ class LedgerBridgeKeyring {
throw new Error(
err.toString() || 'Ledger: Unknown error while signing transaction'
);
} finally {
this.cleanUp();
}
}

Expand All @@ -338,7 +330,6 @@ class LedgerBridgeKeyring {
// For personal_sign, we need to prefix the message:
async signPersonalMessage(withAccount, message) {
return this.signHelper.invoke(async () => {
await this._reconnect();
try {
await this.makeApp(true);
const hdPath = await this.unlockAccountByAddress(withAccount);
Expand Down Expand Up @@ -369,8 +360,6 @@ class LedgerBridgeKeyring {
throw new Error(
e.toString() || 'Ledger: Unknown error while signing message'
);
} finally {
this.cleanUp();
}
});
}
Expand All @@ -397,7 +386,6 @@ class LedgerBridgeKeyring {

async signTypedData(withAccount, data, options: any = {}) {
return this.signHelper.invoke(async () => {
await this._reconnect();
const isV4 = options.version === 'V4';
if (!isV4) {
throw new Error(
Expand Down Expand Up @@ -471,8 +459,6 @@ class LedgerBridgeKeyring {
throw new Error(
e.toString() || 'Ledger: Unknown error while signing message'
);
} finally {
this.cleanUp();
}
});
}
Expand Down
15 changes: 1 addition & 14 deletions src/background/service/keyring/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ export const throwError = (error, method = EVENTS.COMMON_HARDWARE.REJECTED) => {
method,
params: error,
});
throw new Error(error);
};

export class SignHelper {
signFn: any;
errorEventName: string;
Expand All @@ -27,18 +25,7 @@ export class SignHelper {
}

async invoke(fn: () => Promise<any>) {
return new Promise((resolve) => {
this.signFn = async () => {
try {
const result = await fn();
resolve(result);
} catch (e) {
Sentry.captureException(e);
throwError(e?.message ?? e, this.errorEventName);
}
};
this.signFn();
});
return fn();
}
}

Expand Down
6 changes: 6 additions & 0 deletions src/constant/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1480,6 +1480,12 @@ export const DEX = {
name: 'Odos',
chains: DEX_SUPPORT_CHAINS[DEX_ENUM.ODOS],
},
[DEX_ENUM.ZEROXAPIV2]: {
id: DEX_ENUM.ZEROXAPIV2,
logo: Logo0X,
name: '0x',
chains: DEX_SUPPORT_CHAINS[DEX_ENUM.ZEROXAPIV2],
},
};

export const DEX_WITH_WRAP = {
Expand Down
2 changes: 1 addition & 1 deletion src/ui/utils/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const useApproval = () => {
approvalId?: string
) => {
// handle connect
if (!(await deviceConnect(data?.type))) {
if (!(await deviceConnect(data))) {
return;
}

Expand Down
59 changes: 30 additions & 29 deletions src/ui/utils/sendTransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,44 +445,45 @@ export const sendTransaction = async ({
}
};

wallet.reportStats('signTransaction', {
type: currentAccount.brandName,
category: KEYRING_CATEGORY_MAP[currentAccount.type],
chainId: chain.serverId,
createdBy: ga ? 'rabby' : 'dapp',
source: ga?.source || '',
trigger: ga?.trigger || '',
networkType: chain?.isTestnet ? 'Custom Network' : 'Integrated Network',
});

// submit tx
let hash = '';
try {
hash = await Promise.race([
wallet.ethSendTransaction({
data: {
$ctx: {
ga,
},
params: [transaction],
},
session: INTERNAL_REQUEST_SESSION,
approvalRes: {
...transaction,
signingTxId,
logId: logId,
lowGasDeadline,
isGasLess,
isGasAccount: autoUseGasAccount ? canUseGasAccount : isGasAccount,
pushType,
hash = await wallet.ethSendTransaction({
data: {
$ctx: {
ga,
},
pushed: false,
result: undefined,
}),
new Promise((_, reject) => {
eventBus.once(EVENTS.LEDGER.REJECTED, async (data) => {
if (signingTxId != null) {
wallet.removeSigningTx(signingTxId);
}
reject(new Error(data));
});
}),
]);
params: [transaction],
},
session: INTERNAL_REQUEST_SESSION,
approvalRes: {
...transaction,
signingTxId,
logId: logId,
lowGasDeadline,
isGasLess,
isGasAccount: autoUseGasAccount ? canUseGasAccount : isGasAccount,
pushType,
},
pushed: false,
result: undefined,
});
await handleSendAfter();
} catch (e) {
await handleSendAfter();
const err = new Error(e.message);
err.name = FailedCode.SubmitTxFailed;
eventBus.emit(EVENTS.COMMON_HARDWARE.REJECTED, e.message);
throw err;
}

Expand Down
29 changes: 17 additions & 12 deletions src/ui/utils/useDeviceConnect.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { KEYRING_CLASS } from '@/constant';
import React from 'react';
import { useLedgerStatus } from '../component/ConnectStatus/useLedgerStatus';
import { useCommonPopupView } from './WalletContext';
import { useSessionStatus } from '../component/WalletConnect/useSessionStatus';
import { useCommonPopupView, useWallet } from './WalletContext';
import { useCurrentAccount } from '../hooks/backgroundState/useAccount';
import { useImKeyStatus } from '../component/ConnectStatus/useImKeyStatus';

Expand All @@ -12,29 +11,35 @@ import { useImKeyStatus } from '../component/ConnectStatus/useImKeyStatus';
*/
export const useDeviceConnect = () => {
const ledgerStatus = useLedgerStatus();
const account = useCurrentAccount();
const walletConnectStatus = useSessionStatus(account!);
const imKeyStatus = useImKeyStatus();
const { activePopup, setAccount } = useCommonPopupView();
const wallet = useWallet();
const currentAccount = useCurrentAccount();

/**
* @returns {boolean} true if connected, false if not connected and popup is shown
*/
const connect = React.useCallback(
async (type: string) => {
async (data: any) => {
if (!data) return;
const { type, account, isGnosis } = data;

if (type === KEYRING_CLASS.HARDWARE.LEDGER) {
if (ledgerStatus.status === 'DISCONNECTED') {
activePopup('Ledger');
return false;
}
} else if (type === KEYRING_CLASS.WALLETCONNECT) {
if (
!walletConnectStatus.status ||
walletConnectStatus.status === 'DISCONNECTED'
) {
if (account) {
const acc = isGnosis ? account : currentAccount;
const status = await wallet.getWalletConnectSessionStatus(
acc.address,
acc.brandName
);

if (!status || status === 'DISCONNECTED') {
if (acc) {
setAccount({
...account,
...acc,
type,
});
}
Expand All @@ -50,7 +55,7 @@ export const useDeviceConnect = () => {

return true;
},
[ledgerStatus, walletConnectStatus, imKeyStatus, account]
[ledgerStatus, imKeyStatus]
);

return connect;
Expand Down
5 changes: 1 addition & 4 deletions src/ui/views/Approval/components/LedgerHardwareWaiting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,10 +152,7 @@ const LedgerHardwareWaiting = ({ params }: { params: ApprovalParams }) => {
method: params?.extra?.signTextMethod,
});
}
eventBus.addEventListener(EVENTS.LEDGER.REJECT_APPROVAL, (data) => {
rejectApproval(data, false, true);
});
eventBus.addEventListener(EVENTS.LEDGER.REJECTED, async (data) => {
eventBus.addEventListener(EVENTS.COMMON_HARDWARE.REJECTED, async (data) => {
setErrorMessage(data);
if (/DisconnectedDeviceDuringOperation/i.test(data)) {
await rejectApproval('User rejected the request.');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,10 @@ export const MiniLedgerAction: React.FC<Props> = ({
}
};

eventBus.addEventListener(EVENTS.LEDGER.REJECTED, listener);
eventBus.addEventListener(EVENTS.COMMON_HARDWARE.REJECTED, listener);

return () => {
eventBus.removeEventListener(EVENTS.LEDGER.REJECTED, listener);
eventBus.removeEventListener(EVENTS.COMMON_HARDWARE.REJECTED, listener);
};
}, []);

Expand All @@ -106,7 +106,7 @@ export const MiniLedgerAction: React.FC<Props> = ({

React.useEffect(() => {
if (task.status === 'active' && status === 'DISCONNECTED') {
eventBus.emit(EVENTS.LEDGER.REJECTED, 'DISCONNECTED');
eventBus.emit(EVENTS.COMMON_HARDWARE.REJECTED, 'DISCONNECTED');
}
}, [task.status, status]);
const { t } = useTranslation();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const BalanceChangeWrapper: React.FC<Props> = ({
balanceChange.receive_nft_list.length +
balanceChange.receive_token_list.length +
balanceChange.send_nft_list.length +
balanceChange.send_nft_list.length <=
balanceChange.send_token_list.length <=
0
) {
return true;
Expand Down
Loading

0 comments on commit 30ecb71

Please sign in to comment.