Skip to content
Open
Show file tree
Hide file tree
Changes from 33 commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
d45777e
feat: headless connection handling
chakra-guy Aug 26, 2025
ecbcb51
chore: tidy and revert some changes
chakra-guy Aug 26, 2025
29f423f
chore: tidy and revert some changes
chakra-guy Aug 26, 2025
855538d
fix: lint
chakra-guy Aug 26, 2025
e41952f
fix: test
chakra-guy Aug 26, 2025
d334490
feat: ui integration
chakra-guy Aug 26, 2025
9694bb5
chore: tidy
chakra-guy Aug 26, 2025
bb91e79
fix: lint
chakra-guy Aug 26, 2025
d7d5d15
fix: test
chakra-guy Aug 26, 2025
9ecdc20
fix: lint
chakra-guy Aug 26, 2025
cae9e08
fix: test
chakra-guy Aug 26, 2025
a1094e3
fix: test
chakra-guy Aug 26, 2025
d5218ae
fix: test
chakra-guy Aug 26, 2025
d6597b5
fix: lint
chakra-guy Aug 26, 2025
6f8e949
fix: test/lint
chakra-guy Aug 26, 2025
bafb39c
fix: test/lint
chakra-guy Aug 26, 2025
c10bdfa
fix: test/lint
chakra-guy Aug 26, 2025
36f594b
fix: lint
chakra-guy Aug 26, 2025
2b54787
Merge branch 'main' into ts/sdk-connect-v2/ui-integration
chakra-guy Sep 9, 2025
b4175ad
fix type
chakra-guy Sep 9, 2025
b279bad
fix: pr comment
chakra-guy Sep 9, 2025
0e3b230
fix: pr comments
chakra-guy Sep 10, 2025
80315ac
feat: add resume and reconnect logic
chakra-guy Sep 10, 2025
a9564ab
Merge branch 'main' into ts/sdk-connect-v2/resume-and-reconnect
chakra-guy Sep 12, 2025
d3bef95
tidy
chakra-guy Sep 12, 2025
135242a
fix: lint/test
chakra-guy Sep 12, 2025
4d080d5
tests
chakra-guy Sep 12, 2025
ac874d3
fix: lint
chakra-guy Sep 12, 2025
3bf4f40
fix: lint
chakra-guy Sep 12, 2025
b4621ea
fix: sonarcloud comments
chakra-guy Sep 12, 2025
f09ea0c
fix: lint
chakra-guy Sep 12, 2025
ed1e9ef
pr comments
chakra-guy Sep 16, 2025
275177e
feat: hooking up the requests/responses with the bridge
chakra-guy Sep 16, 2025
6a93ad6
fixes/tidy
chakra-guy Sep 16, 2025
720be35
fix bugs/refactor
chakra-guy Sep 17, 2025
6e324e7
tidy
chakra-guy Sep 17, 2025
a9b33f3
multichain
chakra-guy Sep 17, 2025
cf346cc
revert
chakra-guy Sep 17, 2025
b358a86
multichain
chakra-guy Sep 18, 2025
347a5e1
improvements
chakra-guy Sep 18, 2025
f2abed5
tidy
chakra-guy Sep 18, 2025
20dcf70
fix: pr comment
chakra-guy Sep 18, 2025
478041c
cursor commet
chakra-guy Sep 19, 2025
fd27ebe
revert change
chakra-guy Sep 19, 2025
071750a
refactor
chakra-guy Sep 19, 2025
511d26a
Merge branch 'main' into ts/sdk-connect-v2/rpc-message-handling
chakra-guy Sep 19, 2025
a768428
fix merge conflict mistake
chakra-guy Sep 19, 2025
07b03b7
tests
chakra-guy Sep 19, 2025
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
4 changes: 2 additions & 2 deletions app/core/BackgroundBridge/BackgroundBridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ export class BackgroundBridge extends EventEmitter {
this.onUnlock.bind(this),
);

if (!this.isMMSDK && !this.isWalletConnect) {
if (!this.isWalletConnect) {
this.multichainSubscriptionManager = new MultichainSubscriptionManager({
getNetworkClientById:
Engine.context.NetworkController.getNetworkClientById.bind(
Expand Down Expand Up @@ -462,7 +462,7 @@ export class BackgroundBridge extends EventEmitter {
this.sendStateUpdate,
);

if (!this.isMMSDK && !this.isWalletConnect) {
if (!this.isWalletConnect) {
controllerMessenger.unsubscribe(
`${PermissionController.name}:stateChange`,
this.handleCaipSessionScopeChanges,
Expand Down
172 changes: 172 additions & 0 deletions app/core/SDKConnectV2/adapters/rpc-bridge-adapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import EventEmitter from 'eventemitter2';
import BackgroundBridge from '../../BackgroundBridge/BackgroundBridge';
import { Connection } from '../services/connection';
import { IRPCBridgeAdapter } from '../types/rpc-bridge-adapter';
import Engine from '../../Engine';
import AppConstants from '../../AppConstants';
import getRpcMethodMiddleware from '../../RPCMethods/RPCMethodMiddleware';
import { ImageSourcePropType } from 'react-native';

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export class RPCBridgeAdapter
extends EventEmitter
implements IRPCBridgeAdapter
{
private client: BackgroundBridge | null = null;
private queue: unknown[] = [];
private processing = false;
private connection: Connection;

constructor(connection: Connection) {
super();
this.connection = connection;
this.initialize();
}

/**
* Sends a request to the background bridge.
*/
public send(request: unknown): void {
this.queue.push(request);
this.processQueue(); // Attempt to process the request immediately
}

/**
* Asynchronously sets up listeners for wallet state changes.
*/
private async initialize() {
while (!Engine.context?.KeyringController) {
await wait(10);
}

const messenger = Engine.controllerMessenger;
messenger.subscribe('KeyringController:lock', this.onLock);
messenger.subscribe('KeyringController:unlock', this.onUnlock);
}

/**
* Handles the wallet lock event.
*/
private onLock = () => {
console.warn('[SDKConnectV2] Wallet locked.');
// TODO: What do we do here? Do we reject the queue? Do we discard the background bridge client?
};

/**
* Handles the wallet unlock event.
*/
private onUnlock = () => {
console.warn(
'[SDKConnectV2] Wallet unlocked. Attempting to process queue.',
);
// The unlock event is a signal to try processing whatever is in the queue.
this.processQueue();
};

/**
* The processQueue will process the queue of requests in a FIFO manner.
*/
private async processQueue(): Promise<void> {
// Gate 1: Don't run if already processing or if the queue is empty
if (this.processing || this.queue.length === 0) {
console.warn(
'[SDKConnectV2] Processing halted: Queue is empty or already processing.',
);
return;
}

// Gate 2: Don't process requests if the wallet is locked
if (!Engine.context.KeyringController.isUnlocked()) {
console.warn('[SDKConnectV2] Processing halted: Wallet is locked.');
return;
}

this.processing = true;

try {
if (!this.client) {
this.client = this.createClient();
}

while (this.queue.length > 0) {
const request = this.queue.shift();
if (this.client && request) {
this.client.onMessage({
name: 'metamask-provider',
data: request,
});
}
}
} catch (error) {
console.error('[SDKConnectV2] Error during queue processing:', error);
// TODO: What do we do here? Do we reject the request? Do we reject the full queue? Do we wait or return an error to the dapp?
// TODO: Do we use "@metamask/rpc-errors" here?
} finally {
this.processing = false;
}
}

/**
* Creates a new BackgroundBridge instance configured for our use case.
*/
private createClient(): BackgroundBridge {
console.warn('[SDKConnectV2] Creating BackgroundBridge client.');
const middlewareHostname = `${AppConstants.MM_SDK.SDK_REMOTE_ORIGIN}${this.connection.id}`;

return new BackgroundBridge({
webview: null,
isRemoteConn: true,
isMMSDK: true,
channelId: this.connection.id,
url: this.connection.metadata.dapp.url,
remoteConnHost: this.connection.metadata.dapp.url,
sendMessage: (response: unknown) => {
this.emit('response', response);
},
getRpcMethodMiddleware: ({
getProviderState,
}: {
getProviderState: any;
}) =>
getRpcMethodMiddleware({
hostname: middlewareHostname,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this be the origin value? previously connection.origin?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sadly I don't think we can do that. A bunch of old code relies on the middlewareHostname to have this very specific format for routing. It's kinda silly..

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More context: a bunch of routing and UI code relies on this prefix

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm... Well I've made this change to setupBridge and I don't think I saw any issues come out of it. Does this seem right or wrong?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! If that works we should be fine (OR we might have regressions on the sdk v1 we don't know about). Will try this out though!

Copy link
Contributor Author

@chakra-guy chakra-guy Sep 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: it looks like connection.origin (from V1) is the same as middlewareHostname (from V2) under the hood.

this.host = `${AppConstants.MM_SDK.SDK_REMOTE_ORIGIN}${this.channelId}`;

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: In the end I decided to not shoehorn, but the have a clean separation between v1 and v2.

071750a

channelId: this.connection.id,
getProviderState,
isMMSDK: true,
url: { current: this.connection.metadata.dapp.url },
title: { current: this.connection.metadata.dapp.name },
icon: {
current: this.connection.metadata.dapp.icon as ImageSourcePropType,
},
navigation: null,
isHomepage: () => false,
fromHomepage: { current: false },
tabId: '',
isWalletConnect: false,
analytics: {
isRemoteConn: true,
platform:
this.connection.metadata.sdk.platform ??
AppConstants.MM_SDK.UNKNOWN_PARAM,
},
toggleUrlModal: () => null,
injectHomePageScripts: () => null,
}),
isMainFrame: true,
getApprovedHosts: () => ({
[this.connection.metadata.dapp.url]: true,
}),
isWalletConnect: false,
wcRequestActions: undefined,
});
}

public dispose(): void {
const messenger = Engine.controllerMessenger;
messenger.unsubscribe('KeyringController:lock', this.onLock);
messenger.unsubscribe('KeyringController:unlock', this.onUnlock);
this.client?.onDisconnect();
this.removeAllListeners();
}
}
Loading
Loading