Skip to content

Commit

Permalink
Fix/ext dapp account bug (#6412)
Browse files Browse the repository at this point in the history
* fix: log

* fix: ext dapp account bug

(cherry picked from commit d8f050db1b3457ca0e273430abe880be0c1753c2)

* fix: lint

* fix: network change save to db
  • Loading branch information
sidmorizon authored Dec 26, 2024
1 parent 3cd6641 commit 7ef94b3
Show file tree
Hide file tree
Showing 10 changed files with 268 additions and 39 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { cloneDeep } from 'lodash';

import { backgroundMethod } from '@onekeyhq/shared/src/background/backgroundDecorators';
import {
EAppEventBusNames,
Expand Down Expand Up @@ -144,7 +146,7 @@ export class SimpleDbEntityAccountSelector extends SimpleDbEntityBase<IAccountSe
sceneName,
sceneUrl,
});
return selectedAccountsMap?.[num];
return cloneDeep(selectedAccountsMap?.[num]);
}

async getGlobalDeriveType({
Expand Down
1 change: 1 addition & 0 deletions packages/kit-bg/src/providers/ProviderApiEthereum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
providerApiMethod,
} from '@onekeyhq/shared/src/background/backgroundDecorators';
import { IMPL_EVM } from '@onekeyhq/shared/src/engine/engineConsts';
import errorUtils from '@onekeyhq/shared/src/errors/utils/errorUtils';
import {
EAppEventBusNames,
appEventBus,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,18 +230,48 @@ function AccountSelectorEffectsCmp({ num }: { num: number }) {
}),
[actions, num, sceneName, sceneUrl],
);
const syncSceneData = useCallback(
async (eventPayload: {
selectedAccount: IAccountSelectorSelectedAccount;
sceneName: EAccountSelectorSceneName;
sceneUrl?: string | undefined;
num: number;
}) => {
if (
sceneName === EAccountSelectorSceneName.discover &&
eventPayload &&
eventPayload.selectedAccount &&
eventPayload.sceneName === sceneName &&
eventPayload.sceneUrl === sceneUrl &&
// @ts-ignore
eventPayload?.$$isRemoteEvent
) {
await actions.current.updateSelectedAccount({
num: eventPayload.num,
builder: () => eventPayload.selectedAccount,
updateMeta: {
eventEmitDisabled: true, // avoid infinite loop: event -> updateSelectedAccount -> event
},
});
}

await syncHomeAndSwap(eventPayload);
},
[actions, sceneName, sceneUrl, syncHomeAndSwap],
);

useEffect(() => {
appEventBus.on(
EAppEventBusNames.AccountSelectorSelectedAccountUpdate,
syncHomeAndSwap,
syncSceneData,
);
return () => {
appEventBus.off(
EAppEventBusNames.AccountSelectorSelectedAccountUpdate,
syncHomeAndSwap,
syncSceneData,
);
};
}, [syncHomeAndSwap]);
}, [syncSceneData]);

useEffect(() => {
void (async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,44 @@
import { useEffect } from 'react';

import { useDebugComponentRemountLog } from '@onekeyhq/shared/src/utils/debug/debugUtils';
import networkUtils from '@onekeyhq/shared/src/utils/networkUtils';
import { EAccountSelectorSceneName } from '@onekeyhq/shared/types';

import {
useAccountSelectorActions,
useAccountSelectorSceneInfo,
useAccountSelectorStorageReadyAtom,
useSelectedAccount,
} from '../../../states/jotai/contexts/accountSelector';

import { useAccountSelectorAvailableNetworks } from './useAccountSelectorAvailableNetworks';

export function useAutoSelectNetwork({ num }: { num: number }) {
const {
selectedAccount: { networkId },
} = useSelectedAccount({ num });
const { selectedAccount } = useSelectedAccount({ num });
const { networkId } = selectedAccount;

const [isReady] = useAccountSelectorStorageReadyAtom();
const { networkIds, defaultNetworkId } = useAccountSelectorAvailableNetworks({
num,
});

const { sceneName, sceneUrl } = useAccountSelectorSceneInfo();

const actions = useAccountSelectorActions();

if (sceneName === EAccountSelectorSceneName.discover) {
// console.log('useAutoSelectNetwork::: sceneName', {
// selectedAccount,
// sceneName,
// sceneUrl,
// networkId,
// networkIds,
// defaultNetworkId,
// isReady,
// num,
// });
}

// ** auto select first network if no network selected yet
useEffect(() => {
if (!isReady) {
Expand All @@ -40,14 +57,38 @@ export function useAutoSelectNetwork({ num }: { num: number }) {
usedNetworkId = defaultNetworkId;
}
}

if (
usedNetworkId &&
sceneName === EAccountSelectorSceneName.discover &&
networkUtils.isAllNetwork({ networkId: usedNetworkId })
) {
usedNetworkId = '';
}

if (usedNetworkId) {
if (sceneName === EAccountSelectorSceneName.discover) {
// console.log(
// 'useAutoSelectNetwork::: updateSelectedAccountNetwork',
// usedNetworkId,
// );
}

void actions.current.updateSelectedAccountNetwork({
num,
networkId: usedNetworkId,
});
}
}
}, [actions, defaultNetworkId, isReady, networkId, networkIds, num]);
}, [
actions,
defaultNetworkId,
isReady,
networkId,
networkIds,
num,
sceneName,
]);

// TODO UI unmount & mount unexpectedly, cause hooks rerun
// TODO useUpdateEffect()
Expand Down
61 changes: 55 additions & 6 deletions packages/kit/src/states/jotai/contexts/accountSelector/actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import accountSelectorUtils from '@onekeyhq/shared/src/utils/accountSelectorUtil
import accountUtils from '@onekeyhq/shared/src/utils/accountUtils';
import bufferUtils from '@onekeyhq/shared/src/utils/bufferUtils';
import { memoFn } from '@onekeyhq/shared/src/utils/cacheUtils';
import networkUtils from '@onekeyhq/shared/src/utils/networkUtils';
import timerUtils from '@onekeyhq/shared/src/utils/timerUtils';
import {
EAccountSelectorAutoSelectTriggerBy,
Expand Down Expand Up @@ -90,6 +91,7 @@ export type IAccountSelectorSyncFromSceneParams = {
sceneNum: number;
};
num: number;
withNetworkSync?: boolean;
};

export type IFinalizeWalletSetupCreateWalletResult = {
Expand Down Expand Up @@ -294,6 +296,11 @@ class AccountSelectorActions extends ContextJotaiActionsBase {
},
);

getCurrentSceneInfo = contextAtomMethod(async (get) => {
const contextData = get(accountSelectorContextDataAtom());
return contextData;
});

updateSelectedAccount = contextAtomMethod(
async (
get,
Expand All @@ -306,7 +313,7 @@ class AccountSelectorActions extends ContextJotaiActionsBase {
) => IAccountSelectorSelectedAccount;
},
) => {
const contextData = get(accountSelectorContextDataAtom());
const sceneInfo = await this.getCurrentSceneInfo.call(set);
// if (!contextData) {
// return;
// }
Expand All @@ -319,6 +326,13 @@ class AccountSelectorActions extends ContextJotaiActionsBase {
return;
}

if (
sceneInfo?.sceneName === EAccountSelectorSceneName.discover &&
newSelectedAccount?.indexedAccountId === 'hd-1--0'
) {
// debugger;
}

const newNetworkId = newSelectedAccount?.networkId;
const oldNetworkId = oldSelectedAccount?.networkId;
const newDeriveType = newSelectedAccount?.deriveType;
Expand Down Expand Up @@ -348,13 +362,13 @@ class AccountSelectorActions extends ContextJotaiActionsBase {
}
};

if (contextData?.sceneName) {
await fixDeriveTypeByGlobal({ sceneName: contextData?.sceneName });
if (sceneInfo?.sceneName) {
await fixDeriveTypeByGlobal({ sceneName: sceneInfo?.sceneName });

const shouldUseGlobalDeriveType =
await backgroundApiProxy.serviceAccountSelector.shouldUseGlobalDeriveType(
{
sceneName: contextData?.sceneName,
sceneName: sceneInfo?.sceneName,
},
);
if (!shouldUseGlobalDeriveType && newSelectedAccount?.networkId) {
Expand Down Expand Up @@ -1326,6 +1340,19 @@ class AccountSelectorActions extends ContextJotaiActionsBase {

// **** emit event
if (!eventEmitDisabled) {
if (
networkUtils.isAllNetwork({
networkId: payload.selectedAccount?.networkId,
})
) {
// debugger;
}
if (sceneName === EAccountSelectorSceneName.discover) {
if (payload?.selectedAccount?.indexedAccountId === 'hd-1--0') {
// alert('AccountSelectorSelectedAccountUpdate');
// debugger;
}
}
appEventBus.emit(
EAppEventBusNames.AccountSelectorSelectedAccountUpdate,
payload,
Expand Down Expand Up @@ -1366,7 +1393,12 @@ class AccountSelectorActions extends ContextJotaiActionsBase {
);

syncFromScene = contextAtomMethod(
async (get, set, { from, num }: IAccountSelectorSyncFromSceneParams) => {
async (
get,
set,
{ from, num, withNetworkSync }: IAccountSelectorSyncFromSceneParams,
) => {
const sceneInfo = await this.getCurrentSceneInfo.call(set);
const { sceneName, sceneUrl, sceneNum } = from;

const selectedAccount =
Expand All @@ -1378,7 +1410,24 @@ class AccountSelectorActions extends ContextJotaiActionsBase {

await this.updateSelectedAccount.call(set, {
num,
builder: (v) => selectedAccount || v,
builder: (v) => {
if (selectedAccount) {
// networkId won't be synced in default
if (!withNetworkSync) {
selectedAccount.networkId = v?.networkId;
}
if (
sceneInfo?.sceneName === EAccountSelectorSceneName.discover &&
networkUtils.isAllNetwork({
networkId: selectedAccount.networkId,
})
) {
selectedAccount.networkId = v?.networkId;
}
return selectedAccount;
}
return v;
},
});
},
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ function DAppAccountListInitFromHome({
// required delay here, should be called after AccountSelectEffects AutoSelect
await timerUtils.wait(600);
if (shouldSyncFromHome) {
// alert('syncFromScene home');
await actions.current.syncFromScene({
from: {
sceneName: EAccountSelectorSceneName.home,
Expand Down
75 changes: 75 additions & 0 deletions packages/kit/src/views/DAppConnection/dappTest.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<!DOCTYPE html>
<html>
<head>
<title>ETH DApp Demo</title>
</head>
<body>
<div>
<input type="checkbox" id="autoSign" checked>
<label for="autoSign">连接后自动签名</label>
</div>
<button id="connectBtn">Connect Wallet</button>
<button id="signBtn">Sign Message</button>
<p id="status"></p>

<script>
let account = null;
const connectBtn = document.getElementById('connectBtn');
const signBtn = document.getElementById('signBtn');
const statusText = document.getElementById('status');
const autoSignCheckbox = document.getElementById('autoSign');

// 页面加载时从 localStorage 读取状态
const savedAutoSign = localStorage.getItem('autoSign');
if (savedAutoSign !== null) {
autoSignCheckbox.checked = savedAutoSign === 'true';
}

// 监听复选框变化,保存到 localStorage
autoSignCheckbox.addEventListener('change', (event) => {
localStorage.setItem('autoSign', event.target.checked);
});

async function connectWallet() {
try {
// 检查是否安装了 MetaMask
if (typeof window.ethereum === 'undefined') {
throw new Error('请安装 MetaMask!');
}

// 请求连接钱包
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts',
});

account = accounts[0];
statusText.textContent = `已连接: ${account}`;

// 根据勾选状态决定是否自动签名
if (autoSignCheckbox.checked) {
await requestSign();
}
} catch (err) {
statusText.textContent = `错误: ${err.message}`;
}
}

async function requestSign() {
try {
const message = '请签名以验证您的身份776655';
const signature = await window.ethereum.request({
method: 'personal_sign',
params: [message, account],
});

statusText.textContent += `\n签名成功: ${signature}`;
} catch (err) {
statusText.textContent += `\n签名失败: ${err.message}`;
}
}

connectBtn.addEventListener('click', connectWallet);
signBtn.addEventListener('click', requestSign);
</script>
</body>
</html>
Loading

0 comments on commit 7ef94b3

Please sign in to comment.