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: full deeplink protocol #992

Merged
merged 10 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { CommunicationLayerMessage } from '../../../types/CommunicationLayerMess
import { EventType } from '../../../types/EventType';
import { logger } from '../../../utils/logger';

export function handleWalletInitMessage(
export async function handleWalletInitMessage(
instance: RemoteCommunication,
message: CommunicationLayerMessage,
) {
Expand All @@ -19,32 +19,36 @@ export function handleWalletInitMessage(
'chainId' in data &&
'walletKey' in data
) {
// Persist channel config
const { channelConfig } = instance.state;
logger.RemoteCommunication(
`WALLET_INIT: channelConfig`,
JSON.stringify(channelConfig, null, 2),
);
try {
// Persist channel config
const { channelConfig } = instance.state;
logger.RemoteCommunication(
`WALLET_INIT: channelConfig`,
JSON.stringify(channelConfig, null, 2),
);

if (channelConfig) {
const accounts = data.accounts as string[];
const chainId = data.chainId as string;
const walletKey = data.walletKey as string;
if (channelConfig) {
const accounts = data.accounts as string[];
const chainId = data.chainId as string;
const walletKey = data.walletKey as string;

instance.state.storageManager?.persistChannelConfig({
...channelConfig,
otherKey: walletKey,
relayPersistence: true,
});
await instance.state.storageManager?.persistChannelConfig({
...channelConfig,
otherKey: walletKey,
relayPersistence: true,
});

instance.state.storageManager?.persistAccounts(accounts);
instance.state.storageManager?.persistChainId(chainId);
}
await instance.state.storageManager?.persistAccounts(accounts);
await instance.state.storageManager?.persistChainId(chainId);
}

instance.emit(EventType.WALLET_INIT, {
accounts: data.accounts,
chainId: data.chainId,
});
instance.emit(EventType.WALLET_INIT, {
accounts: data.accounts,
chainId: data.chainId,
});
} catch (error) {
console.error('RemoteCommunication::on "wallet_init" -- error', error);
}
} else {
console.error(
'RemoteCommunication::on "wallet_init" -- invalid data format',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,24 @@ import { handleJoinChannelResults } from './handleJoinChannelResult';
*
* @param instance The current instance of the SocketService.
*/
export function resume(instance: SocketService) {
export function resume(instance: SocketService): void {
const { state, remote } = instance;
const { socket, channelId, context, keyExchange, isOriginator } = state;
const { isOriginator: remoteIsOriginator } = remote.state;

logger.SocketService(
`[SocketService: resume()] context=${context} connected=${
`[SocketService: resume()] channelId=${channelId} context=${context} connected=${
socket?.connected
} manualDisconnect=${state.manualDisconnect} resumed=${
state.resumed
} keysExchanged=${keyExchange?.areKeysExchanged()}`,
);

if (!channelId) {
logger.SocketService(`[SocketService: resume()] channelId is not defined`);
throw new Error('ChannelId is not defined');
}

if (socket?.connected) {
logger.SocketService(`[SocketService: resume()] already connected.`);
socket.emit(MessageType.PING, {
Expand All @@ -35,6 +40,15 @@ export function resume(instance: SocketService) {
context: 'on_channel_config',
message: '',
});

if (!remote.hasRelayPersistence() && !keyExchange?.areKeysExchanged()) {
// Always try to recover key exchange from both side (wallet / dapp)
if (isOriginator) {
instance.sendMessage({ type: MessageType.READY });
} else {
keyExchange?.start({ isOriginator: false });
}
}
} else {
socket?.connect();

Expand All @@ -51,7 +65,11 @@ export function resume(instance: SocketService) {
},
async (
error: string | null,
result?: { ready: boolean; persistence?: boolean; walletKey?: string },
result?: {
ready: boolean;
persistence?: boolean;
walletKey?: string;
},
) => {
try {
await handleJoinChannelResults(instance, error, result);
Expand All @@ -62,17 +80,6 @@ export function resume(instance: SocketService) {
);
}

// Always try to recover key exchange from both side (wallet / dapp)
if (keyExchange?.areKeysExchanged()) {
if (!isOriginator) {
instance.sendMessage({ type: MessageType.READY });
}
} else if (!isOriginator) {
keyExchange?.start({
isOriginator: isOriginator ?? false,
});
}

state.manualDisconnect = false;
state.resumed = true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ export function handleSendMessage(
message: CommunicationLayerMessage,
) {
if (!instance.state.channelId) {
logger.SocketService(
`handleSendMessage: no channelId - Create a channel first`,
);
throw new Error('Create a channel first');
}

Expand Down
13 changes: 9 additions & 4 deletions packages/sdk-socket-server-next/src/protocol/handleMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,16 @@ export const handleMessage = async ({
);

// broadcast that the channel supports relayPersistence
socket.broadcast
.to(channelId)
.emit(`config-${channelId}`, { persistence: true });
socket.broadcast.to(channelId).emit(`config-${channelId}`, {
persistence: true,
walletKey: channelConfig.walletKey,
});

// also inform current client
socket.emit(`config-${channelId}`, { persistence: true });
socket.emit(`config-${channelId}`, {
persistence: true,
walletKey: channelConfig.walletKey,
});
}
return;
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ export function onMessage(
}

if (!message?.name) {
logger(
`[RCPMS: onMessage()] ignore message without name message=${message}`,
);
logger(`[RCPMS: onMessage()] ignore message without name`, message);
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export async function write(
const isSecure = instance.state.platformManager?.isSecure();
const mobileWeb = instance.state.platformManager?.isMobileWeb() ?? false;

const activeDeeplinkProtocol = deeplinkProtocol && mobileWeb;
const activeDeeplinkProtocol = deeplinkProtocol && mobileWeb && authorized;
console.warn(
`[RCPMS: write()] activeDeeplinkProtocol=${activeDeeplinkProtocol}`,
);
Expand All @@ -65,22 +65,6 @@ export async function write(
logger(`[RCPMS: _write()] error sending message`, err);
});

// Keep this for now as reference -- it should become unnecessary if we send via deeplink
// if (!socketConnected && !isRemoteReady) {
// // Invalid connection status
// logger(
// `[RCPMS: _write()] invalid connection status targetMethod=${targetMethod} socketConnected=${socketConnected} ready=${isRemoteReady} providerConnected=${provider.isConnected()}`,
// );
// return callback();
// }
if (!socketConnected && isRemoteReady) {
// Shouldn't happen -- needs to refresh
console.warn(
`[RCPMS: _write()] invalid socket status -- shouldn't happen`,
);
return callback();
}

if (!isSecure) {
// Redirect early if nodejs or browser...
logger(
Expand All @@ -90,7 +74,6 @@ export async function write(
}
}

// Check if should open app
const pubKey = instance.state.remote?.getKeyInfo()?.ecies.public ?? '';
let urlParams = encodeURI(
`channelId=${channelId}&pubkey=${pubKey}&comm=socket&t=d&v=2`,
Expand All @@ -106,18 +89,21 @@ export async function write(
);
}
const encoded = base64Encode(encrypted);
console.warn(`[RCPMS: _write()] rpc`, data?.data, jsonrpc);
urlParams += `&scheme=${deeplinkProtocol}&rpc=${encoded}`;
}

console.log(`[RCPMS: _write()] urlParams=${urlParams}`);
if (!instance.state.platformManager?.isMetaMaskInstalled()) {
logger(
`[RCPMS: _write()] prevent deeplink until installation is completed.`,
);
return callback();
}

if (METHODS_TO_REDIRECT[targetMethod]) {
logger(
`[RCPMS: _write()] redirect link for '${targetMethod}' socketConnected=${socketConnected} connect?${urlParams}`,
);

// Use otp to re-enable host approval
instance.state.platformManager?.openDeeplink(
`${METAMASK_CONNECT_BASE_URL}?${urlParams}`,
`${METAMASK_DEEPLINK_BASE}?${urlParams}`,
Expand Down
Loading