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:add dapp-connected-management #1509

Closed
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@ class ProviderApiWalletConnect extends WalletConnectClientForWallet {
({ connector }: IWalletConnectClientEventDestroy) => {
if (connector) {
this.removeConnectedAccounts(connector);
// passively disconnects the walletConnect, does not perform connector.killsession() in _destroyConnector,so here close session
this.backgroundApi.serviceDapp.closeWalletConnectedSession(
connector.session,
);
}
},
);
Expand Down
41 changes: 12 additions & 29 deletions packages/kit/src/background/services/ServiceDapp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,6 @@ import { SendRoutes } from '@onekeyhq/kit/src/views/Send/types';
import platformEnv from '@onekeyhq/shared/src/platformEnv';

import { ModalRoutes, RootRoutes } from '../../routes/routesEnum';
import {
dappCloseWalletConnectSession,
dappSaveWalletConnectSession,
dappUpdateWalletConnectSession,
} from '../../store/reducers/dapp';
import { backgroundClass, backgroundMethod } from '../decorators';
import { IDappSourceInfo } from '../IBackgroundApi';
import {
Expand Down Expand Up @@ -89,21 +84,6 @@ class ServiceDapp extends ServiceBase {
this.backgroundApi.dispatch(dappRemoveSiteConnections(payload));
}

@backgroundMethod()
updateWalletConnectedSession(session: IWalletConnectSession) {
this.backgroundApi.dispatch(dappUpdateWalletConnectSession(session));
}

@backgroundMethod()
saveWalletConnectedSession(session: IWalletConnectSession) {
this.backgroundApi.dispatch(dappSaveWalletConnectSession(session));
}

@backgroundMethod()
closeWalletConnectedSession(session: IWalletConnectSession) {
this.backgroundApi.dispatch(dappCloseWalletConnectSession(session));
}

@backgroundMethod()
async cancellConnectedSite(payload: DappSiteConnection): Promise<void> {
// check walletConnect
Expand All @@ -113,20 +93,22 @@ class ServiceDapp extends ServiceBase {
payload.site.origin
) {
this.backgroundApi.walletConnect.disconnect();
} else {
this.removeConnectedAccounts({
origin: payload.site.origin,
networkImpl: payload.networkImpl,
addresses: [payload.address],
});
}
this.removeConnectedAccounts({
origin: payload.site.origin,
networkImpl: payload.networkImpl,
addresses: [payload.address],
});
await this.backgroundApi.serviceAccount.notifyAccountsChanged();
}

@backgroundMethod()
manuallyAddInpageCannected(request: CommonRequestParams['request']) {
if (request.origin) {
this.openConnectionModal(request);
async updateWalletConnectSession() {
ezailWang marked this conversation as resolved.
Show resolved Hide resolved
if (this.backgroundApi.walletConnect.connector) {
const { session } = this.backgroundApi.walletConnect.connector;
return Promise.resolve(
this.backgroundApi.walletConnect.connector.connected ? session : null,
);
}
}

Expand Down Expand Up @@ -154,6 +136,7 @@ class ServiceDapp extends ServiceBase {
return Boolean(accounts && accounts.length);
}

@backgroundMethod()
openConnectionModal(request: CommonRequestParams['request']) {
return this.openModal({
request,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,6 @@ import * as cryptoLib from '@walletconnect/iso-crypto';
import SocketTransport from '@walletconnect/socket-transport';
import { toLower } from 'lodash';

import backgroundApiProxy from '../../background/instance/backgroundApiProxy';
import {
closeWalletConnectSession,
updateWalletConnectSession,
} from '../../store/reducers/walletConnectSession';

import {
WALLET_CONNECT_BRIDGE,
WALLET_CONNECT_PROTOCOL,
Expand Down Expand Up @@ -121,23 +115,6 @@ export class OneKeyWalletConnector extends Connector {
}
}

override approveSession(sessionStatus: ISessionStatus): void {
super.approveSession(sessionStatus);
backgroundApiProxy.serviceDapp.saveWalletConnectedSession(this.session);
}

override updateSession(sessionStatus: ISessionStatus): void {
super.updateSession(sessionStatus);
backgroundApiProxy.serviceDapp.updateWalletConnectedSession(this.session);
}

override async killSession(
sessionError?: ISessionError | undefined,
): Promise<void> {
await super.killSession(sessionError);
backgroundApiProxy.serviceDapp.closeWalletConnectedSession(this.session);
}

once(event: string, listener: (...args: any[]) => void) {
let executed = false;
const listenerOnce = (...args: any[]) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { IMPL_EVM } from '@onekeyhq/engine/src/constants';
import debugLogger from '@onekeyhq/shared/src/logger/debugLogger';

import { backgroundMethod } from '../../background/decorators';
import backgroundApiProxy from '../../background/instance/backgroundApiProxy';
import { getActiveWalletAccount } from '../../hooks/redux';

import { OneKeyWalletConnector } from './OneKeyWalletConnector';
import {
Expand Down Expand Up @@ -97,6 +99,16 @@ export abstract class WalletConnectClientForWallet extends WalletConnectClientBa
} catch (error) {
debugLogger.walletConnect.info('walletConnect.connect reject', error);
connector.rejectSession(error as any);
} finally {
// walletConnect session update to update connecttions
const { accountAddress, networkImpl } = getActiveWalletAccount();
ezailWang marked this conversation as resolved.
Show resolved Hide resolved
backgroundApiProxy.serviceDapp.saveConnectedAccounts({
site: {
origin,
},
networkImpl,
address: accountAddress,
});
}
}
}
61 changes: 0 additions & 61 deletions packages/kit/src/store/reducers/dapp.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { PayloadAction, createSlice } from '@reduxjs/toolkit';

import type { IWalletConnectSession } from '@walletconnect/types';

export type DappSiteInfo = {
origin: string;
hostname?: string;
Expand All @@ -28,12 +26,10 @@ export type DappSiteConnection = DappSiteConnectionSavePayload & {

export type DappInitialState = {
connections: DappSiteConnection[];
walletConnectSessions: IWalletConnectSession[];
};

const initialState: DappInitialState = {
connections: [],
walletConnectSessions: [],
};

export const dappSlicer = createSlice({
Expand Down Expand Up @@ -83,70 +79,13 @@ export const dappSlicer = createSlice({
info.lastTime = Date.now();
state.connections = connections;
},
dappUpdateWalletConnectSession(
state,
action: PayloadAction<IWalletConnectSession>,
) {
const { payload } = action;
let sessions = [...state.walletConnectSessions];
sessions = sessions.map((session) => {
if (session.peerMeta?.url === payload.peerMeta?.url) {
Object.assign(session, payload);
}
return session;
});
sessions = sessions.filter((session) => session.connected);
state.walletConnectSessions = sessions;
},
dappSaveWalletConnectSession(
state,
action: PayloadAction<IWalletConnectSession>,
) {
const { payload } = action;
const sessions = [...state.walletConnectSessions];
// save only connected session
if (payload.connected) {
if (
sessions.find(
(session) => session.peerMeta?.url === payload.peerMeta?.url,
)
) {
this.dappUpdateWalletConnectSession(state, action);
} else {
sessions.push(payload);
}
}
state.walletConnectSessions = sessions;
},
dappCloseWalletConnectSession(
state,
action: PayloadAction<IWalletConnectSession>,
) {
const { payload } = action;
if (!payload) {
this.dappClearWalletConnectSession(state);
} else {
let sessions = [...state.walletConnectSessions];
sessions = sessions.filter(
(session) => session.peerMeta?.url !== payload.peerMeta?.url,
);
state.walletConnectSessions = sessions;
}
},
dappClearWalletConnectSession(state) {
state.walletConnectSessions = [];
},
},
});

export const {
dappSaveSiteConnection,
dappClearSiteConnection,
dappRemoveSiteConnections,
dappUpdateWalletConnectSession,
dappSaveWalletConnectSession,
dappCloseWalletConnectSession,
dappClearWalletConnectSession,
} = dappSlicer.actions;

export default dappSlicer.reducer;
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ const AddConnectionSiteDialog: FC<AddConnectionSideDialogProps> = ({
) {
origin = `https://${origin}`;
}
backgroundApiProxy.serviceDapp.manuallyAddInpageCannected({
origin,
});
backgroundApiProxy.serviceDapp.openConnectionModal({ origin });
}
closeOverlay();
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { FC, useCallback } from 'react';
import React, { FC, useCallback, useEffect, useState } from 'react';

import { Image } from 'native-base';
import { useIntl } from 'react-intl';
Expand All @@ -22,11 +22,19 @@ import { ConnectedSitesHeaderProps } from '../types';
import type { IWalletConnectSession } from '@walletconnect/types';

const ConnectedSitesHeader: FC<ConnectedSitesHeaderProps> = ({
walletConnectSessions = [],
connections,
onAddConnectSite,
onDisConnectWalletConnected,
}) => {
const intl = useIntl();
const [walletConnectSessions, setSessions] = useState<
IWalletConnectSession[]
>(() => []);
useEffect(() => {
backgroundApiProxy.serviceDapp.updateWalletConnectSession().then((s) => {
setSessions(() => (s ? [s] : []));
});
}, [connections]);

const renderItem: ListRenderItem<IWalletConnectSession> = useCallback(
({ item, index }) => {
Expand Down
18 changes: 8 additions & 10 deletions packages/kit/src/views/ManageConnectedSites/ConnectedSites.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ import { showOverlay } from '../../utils/overlayUtils';
import AddConnectionSiteDialog from './Component/AddConnectionSite';
import ConnectedSitesHeader from './Component/ConnectedSitesHeader';

import type { IWalletConnectSession } from '@walletconnect/types';

const sortConnectionsSite = (connections: DappSiteConnection[]) => {
let parseConnections: DappSiteConnection[] = JSON.parse(
ezailWang marked this conversation as resolved.
Show resolved Hide resolved
JSON.stringify(connections),
Expand All @@ -45,13 +43,13 @@ const sortConnectionsSite = (connections: DappSiteConnection[]) => {

export default function ConnectedSites() {
const intl = useIntl();
const connections: DappSiteConnection[] = sortConnectionsSite(
useAppSelector((s) => s.dapp.connections),
);

const walletConnectSessions = useAppSelector(
(s) => s.dapp.walletConnectSessions,
const connections: DappSiteConnection[] = useAppSelector(
(s) => s.dapp.connections,
);
const sortConnections = sortConnectionsSite(connections);
ezailWang marked this conversation as resolved.
Show resolved Hide resolved
// const walletConnectSessions = useAppSelector(
// (s) => s.dapp.walletConnectSessions,
// );

const openDeleteDialog = useCallback(
(dappName: string, disconnect: () => Promise<any>) => {
Expand Down Expand Up @@ -176,12 +174,12 @@ export default function ConnectedSites() {
ListHeaderComponent:
connections.length > 0 ? (
<ConnectedSitesHeader
walletConnectSessions={walletConnectSessions}
connections={connections}
onDisConnectWalletConnected={openDeleteDialog}
onAddConnectSite={openAddDialog}
/>
) : null,
data: connections,
data: sortConnections,
// @ts-ignore
renderItem,
ListEmptyComponent: (
Expand Down
4 changes: 2 additions & 2 deletions packages/kit/src/views/ManageConnectedSites/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { IWalletConnectSession } from '@walletconnect/types';
import { DappSiteConnection } from '../../store/reducers/dapp';

export enum ManageConnectedSitesRoutes {
ManageConnectedSitesModel = 'ManageConnectedSitesModal',
Expand All @@ -14,7 +14,7 @@ export type ConnectedSitesHeaderProps = {
disconnect: () => Promise<any>,
) => void;
onAddConnectSite: () => void;
walletConnectSessions: IWalletConnectSession[];
connections: DappSiteConnection[];
};

export type AddConnectionSideDialogProps = {
Expand Down