Skip to content

Commit

Permalink
refactor: updates transport types to const and moves link mode listen…
Browse files Browse the repository at this point in the history
…ers inside sign client engine
  • Loading branch information
ganchoradkov committed Aug 28, 2024
1 parent 97f06f7 commit 5125309
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 80 deletions.
5 changes: 5 additions & 0 deletions packages/core/src/constants/relayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,8 @@ export const RELAYER_SDK_VERSION = "2.15.1";

// delay to wait before closing the transport connection after init if not active
export const RELAYER_TRANSPORT_CUTOFF = 10_000;

export const TRANSPORT_TYPES = {
link_mode: "link_mode",
relay: "relay",
} as const;
3 changes: 2 additions & 1 deletion packages/core/src/controllers/pairing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import {
PAIRING_EVENTS,
EVENT_CLIENT_PAIRING_TRACES,
EVENT_CLIENT_PAIRING_ERRORS,
TRANSPORT_TYPES,
} from "../constants";
import { Store } from "../controllers/store";

Expand Down Expand Up @@ -294,7 +295,7 @@ export class Pairing implements IPairing {
if (!this.pairings.keys.includes(topic)) return;

// Do not handle link-mode messages
if (transportType === "link-mode") return;
if (transportType === TRANSPORT_TYPES.link_mode) return;

// messages of certain types should be ignored as they are handled by their respective SDKs
if (this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(message))) return;
Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/controllers/subscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
SUBSCRIBER_STORAGE_VERSION,
PENDING_SUB_RESOLUTION_TIMEOUT,
RELAYER_EVENTS,
TRANSPORT_TYPES,
} from "../constants";
import { SubscriberTopicMap } from "./topicmap";

Expand Down Expand Up @@ -223,7 +224,7 @@ export class Subscriber extends ISubscriber {
relay: RelayerTypes.ProtocolOptions,
transportType: RelayerTypes.TransportType = "relay",
) {
if (transportType !== "link-mode") {
if (transportType === TRANSPORT_TYPES.relay) {
await this.restartToComplete();
}
const api = getRelayProtocolApi(relay.protocol);
Expand All @@ -238,7 +239,7 @@ export class Subscriber extends ISubscriber {
try {
const subId = hashMessage(topic + this.clientId);
// only attempt to subscribe if there is internet connection
if (transportType === "link-mode" && !this.relayer.connected) {
if (transportType === TRANSPORT_TYPES.link_mode && !this.relayer.connected) {
return subId;
}
const subscribe = await createExpiringPromise(
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
CORE_STORAGE_OPTIONS,
CORE_VERSION,
RELAYER_DEFAULT_RELAY_URL,
TRANSPORT_TYPES,
WALLETCONNECT_CLIENT_ID,
WALLETCONNECT_LINK_MODE_APPS,
} from "./constants";
Expand Down Expand Up @@ -176,7 +177,7 @@ export class Core extends ICore {
topic,
message,
publishedAt: Date.now(),
transportType: "link-mode" as const,
transportType: TRANSPORT_TYPES.link_mode,
};

this.relayer.onLinkMessageEvent(payload, { sessionExists });
Expand Down
34 changes: 1 addition & 33 deletions packages/sign-client/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
pino,
} from "@walletconnect/logger";
import { SignClientTypes, ISignClient, ISignClientEvents, EngineTypes } from "@walletconnect/types";
import { getAppMetadata, getSearchParamFromURL, isReactNative } from "@walletconnect/utils";
import { getAppMetadata } from "@walletconnect/utils";
import { EventEmitter } from "events";
import { SIGN_CLIENT_DEFAULT, SIGN_CLIENT_PROTOCOL, SIGN_CLIENT_VERSION } from "./constants";
import { AuthStore, Engine, PendingRequest, Proposal, Session } from "./controllers";
Expand Down Expand Up @@ -253,42 +253,10 @@ export class SignClient extends ISignClient {
await this.auth.init();
this.logger.info(`SignClient Initialization Success`);
this.engine.processRelayMessageCache();
this.registerLinkModeListeners();
} catch (error: any) {
this.logger.info(`SignClient Initialization Failure`);
this.logger.error(error.message);
throw error;
}
}

private handleLinkModeMessage = ({ url }: { url: string }) => {
if (!url || !url.includes("wc_ev") || !url.includes("topic")) return;

const topic = getSearchParamFromURL(url, "topic") || "";
const message = decodeURIComponent(getSearchParamFromURL(url, "wc_ev") || "");

const sessionExists = this.session.keys.includes(topic);

if (sessionExists) {
this.session.update(topic, { transportType: "link-mode" });
}

this.core.dispatchEnvelope({ topic, message, sessionExists });
};

private registerLinkModeListeners = async () => {
if (process.env.IS_VITEST || (isReactNative() && this.metadata.redirect?.linkMode)) {
// global.Linking is set by react-native-compat
if (typeof (global as any)?.Linking !== "undefined") {
// set URL listener
(global as any).Linking.addEventListener("url", this.handleLinkModeMessage, this.name);

// check for initial URL -> cold boots
const initialUrl = await (global as any).Linking.getInitialURL();
if (initialUrl) {
this.handleLinkModeMessage({ url: initialUrl });
}
}
}
};
}
76 changes: 59 additions & 17 deletions packages/sign-client/src/controllers/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
PAIRING_EVENTS,
RELAYER_DEFAULT_PROTOCOL,
RELAYER_EVENTS,
TRANSPORT_TYPES,
VERIFY_SERVER,
} from "@walletconnect/core";

Expand Down Expand Up @@ -93,6 +94,8 @@ import {
getLinkModeURL,
BASE64,
BASE64URL,
getSearchParamFromURL,
isReactNative,
} from "@walletconnect/utils";
import EventEmmiter from "events";
import {
Expand Down Expand Up @@ -154,6 +157,7 @@ export class Engine extends IEngine {
this.registerRelayerEvents();
this.registerExpirerEvents();
this.registerPairingEvents();
await this.registerLinkModeListeners();
this.client.core.pairing.register({ methods: Object.keys(ENGINE_RPC_OPTS) });
this.initialized = true;
setTimeout(() => {
Expand Down Expand Up @@ -232,7 +236,7 @@ export class Engine extends IEngine {
pairingTopic: proposal.pairingTopic,
requiredNamespaces: proposal.requiredNamespaces,
optionalNamespaces: proposal.optionalNamespaces,
transportType: "relay" as RelayerTypes.TransportType,
transportType: TRANSPORT_TYPES.relay,
};
await this.client.session.set(session.topic, completeSession);
await this.setExpiry(session.topic, session.expiry);
Expand Down Expand Up @@ -337,7 +341,7 @@ export class Engine extends IEngine {
...(sessionProperties && { sessionProperties }),
...(sessionConfig && { sessionConfig }),
};
const transportType = "relay";
const transportType = TRANSPORT_TYPES.relay;
event.addTrace(EVENT_CLIENT_SESSION_TRACES.subscribing_session_topic);
try {
await this.client.core.relayer.subscribe(sessionTopic, { transportType });
Expand All @@ -361,7 +365,7 @@ export class Engine extends IEngine {
metadata: proposer.metadata,
},
controller: selfPublicKey,
transportType: "relay" as RelayerTypes.TransportType,
transportType: TRANSPORT_TYPES.relay,
};
await this.client.session.set(sessionTopic, session);

Expand Down Expand Up @@ -535,7 +539,7 @@ export class Engine extends IEngine {
const { chainId, request, topic, expiry = ENGINE_RPC_OPTS.wc_sessionRequest.req.ttl } = params;
const session = this.client.session.get(topic);

if (session?.transportType === "relay") {
if (session?.transportType === TRANSPORT_TYPES.relay) {
await this.confirmOnlineStateOrThrow();
}
console.log("request transport type", session?.transportType);
Expand Down Expand Up @@ -631,7 +635,7 @@ export class Engine extends IEngine {
const { id } = response;
const session = this.client.session.get(topic);

if (session.transportType === "relay") {
if (session.transportType === TRANSPORT_TYPES.relay) {
await this.confirmOnlineStateOrThrow();
}

Expand Down Expand Up @@ -743,9 +747,11 @@ export class Engine extends IEngine {
const isLinkMode =
walletUniversalLink && this.client.core.linkModeSupportedApps.includes(walletUniversalLink);

const transportType: RelayerTypes.TransportType = isLinkMode ? "link-mode" : "relay";
const transportType: RelayerTypes.TransportType = isLinkMode
? TRANSPORT_TYPES.link_mode
: TRANSPORT_TYPES.relay;

if (transportType === "relay") {
if (transportType === TRANSPORT_TYPES.relay) {
await this.confirmOnlineStateOrThrow();
}

Expand Down Expand Up @@ -979,7 +985,7 @@ export class Engine extends IEngine {
this.client.core.addLinkModeSupportedApp(responder.metadata.redirect.universal);

this.client.session.update(sessionTopic, {
transportType: "link-mode",
transportType: TRANSPORT_TYPES.link_mode,
});
}

Expand Down Expand Up @@ -1079,8 +1085,8 @@ export class Engine extends IEngine {
throw new Error(`Could not find pending auth request with id ${id}`);
}

const transportType = pendingRequest.transportType || "relay";
if (transportType === "relay") {
const transportType = pendingRequest.transportType || TRANSPORT_TYPES.relay;
if (transportType === TRANSPORT_TYPES.relay) {
await this.confirmOnlineStateOrThrow();
}

Expand Down Expand Up @@ -1237,7 +1243,7 @@ export class Engine extends IEngine {
throw new Error(`Could not find pending auth request with id ${id}`);
}

if (pendingRequest.transportType === "relay") {
if (pendingRequest.transportType === TRANSPORT_TYPES.relay) {
await this.confirmOnlineStateOrThrow();
}

Expand Down Expand Up @@ -1404,7 +1410,7 @@ export class Engine extends IEngine {
};

private setAuthRequest: EnginePrivate["setAuthRequest"] = async (id, params) => {
const { request, pairingTopic, transportType = "relay" } = params;
const { request, pairingTopic, transportType = TRANSPORT_TYPES.relay } = params;
this.client.core.expirer.set(id, request.expiryTimestamp);
await this.client.auth.requests.set(id, {
authPayload: request.authPayload,
Expand Down Expand Up @@ -1631,7 +1637,7 @@ export class Engine extends IEngine {

const payload = await this.client.core.crypto.decode(topic, message, {
receiverPublicKey: publicKey,
encoding: transportType === "link-mode" ? BASE64URL : BASE64,
encoding: transportType === TRANSPORT_TYPES.link_mode ? BASE64URL : BASE64,
});
console.log("on relay message", payload.id, transportType);
try {
Expand Down Expand Up @@ -1901,7 +1907,7 @@ export class Engine extends IEngine {
},
...(sessionProperties && { sessionProperties }),
...(sessionConfig && { sessionConfig }),
transportType: "relay" as RelayerTypes.TransportType,
transportType: TRANSPORT_TYPES.relay,
};
const target = engineEvent("session_connect");
const listeners = this.events.listenerCount(target);
Expand Down Expand Up @@ -2126,7 +2132,10 @@ export class Engine extends IEngine {
};
await this.setPendingSessionRequest(request);

if (transportType === "link-mode" && session.peer.metadata.redirect?.universal) {
if (
transportType === TRANSPORT_TYPES.link_mode &&
session.peer.metadata.redirect?.universal
) {
// save app as supported for link mode
this.client.core.addLinkModeSupportedApp(session.peer.metadata.redirect?.universal);
}
Expand Down Expand Up @@ -2238,7 +2247,7 @@ export class Engine extends IEngine {
transportType,
});

if (transportType === "link-mode" && requester.metadata.redirect?.universal) {
if (transportType === TRANSPORT_TYPES.link_mode && requester.metadata.redirect?.universal) {
// save app as supported for link mode
this.client.core.addLinkModeSupportedApp(requester.metadata.redirect.universal);
}
Expand Down Expand Up @@ -2865,7 +2874,7 @@ export class Engine extends IEngine {
peerMetadata?: CoreTypes.Metadata,
transportType?: RelayerTypes.TransportType,
): boolean => {
if (!peerMetadata || transportType !== "link-mode") return false;
if (!peerMetadata || transportType !== TRANSPORT_TYPES.link_mode) return false;

return (
this.client.metadata?.redirect?.linkMode === true &&
Expand All @@ -2887,4 +2896,37 @@ export class Engine extends IEngine {
? peerMetadata?.redirect?.universal
: undefined;
};

private handleLinkModeMessage = ({ url }: { url: string }) => {
if (!url || !url.includes("wc_ev") || !url.includes("topic")) return;

const topic = getSearchParamFromURL(url, "topic") || "";
const message = decodeURIComponent(getSearchParamFromURL(url, "wc_ev") || "");

const sessionExists = this.client.session.keys.includes(topic);

if (sessionExists) {
this.client.session.update(topic, { transportType: TRANSPORT_TYPES.link_mode });
}

this.client.core.dispatchEnvelope({ topic, message, sessionExists });
};

private registerLinkModeListeners = async () => {
if (process?.env?.IS_VITEST || (isReactNative() && this.client.metadata.redirect?.linkMode)) {
console.log("registering link mode listeners");
const linking = (global as any)?.Linking;
// global.Linking is set by react-native-compat
if (typeof linking !== "undefined") {
// set URL listener
linking.addEventListener("url", this.handleLinkModeMessage, this.client.name);

// check for initial URL -> cold boots
const initialUrl = await linking.getInitialURL();
if (initialUrl) {
this.handleLinkModeMessage({ url: initialUrl });
}
}
}
};
}
25 changes: 3 additions & 22 deletions packages/sign-client/test/sdk/link-mode.spec.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,9 @@
import {
formatJsonRpcError,
formatJsonRpcResult,
JsonRpcError,
} from "@walletconnect/jsonrpc-utils";
import {
buildAuthObject,
generateRandomBytes32,
getSdkError,
populateAuthPayload,
} from "@walletconnect/utils";
import { formatJsonRpcResult } from "@walletconnect/jsonrpc-utils";
import { buildAuthObject, populateAuthPayload } from "@walletconnect/utils";
import { beforeAll, describe, expect, it } from "vitest";
import { Wallet as CryptoWallet } from "@ethersproject/wallet";
import { SignClient } from "../../src";
import {
initTwoClients,
testConnectMethod,
deleteClients,
throttle,
TEST_REQUEST_PARAMS,
TEST_SIGN_CLIENT_OPTIONS_B,
TEST_SIGN_CLIENT_OPTIONS_A,
TEST_SIGN_CLIENT_OPTIONS,
TEST_APP_METADATA_B,
} from "../shared";
import { throttle, TEST_SIGN_CLIENT_OPTIONS, TEST_APP_METADATA_B } from "../shared";

describe("Sign Client Link Mode", () => {
let cryptoWallet: CryptoWallet;
Expand Down
7 changes: 3 additions & 4 deletions packages/types/src/core/relayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@ export declare namespace RelayerTypes {
attestation?: string;
}

export type TransportType = "relay" | "link_mode";

export interface SubscribeOptions {
relay?: ProtocolOptions;
transportType?: "relay" | "link-mode";
transportType?: TransportType;
}

export interface UnsubscribeOptions {
Expand All @@ -41,9 +43,6 @@ export declare namespace RelayerTypes {
message: string;
opts?: RelayerTypes.PublishOptions;
}

export type TransportType = "relay" | "link-mode";

export interface MessageEvent {
topic: string;
message: string;
Expand Down

0 comments on commit 5125309

Please sign in to comment.