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: events sdk #5188

Merged
merged 15 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

87 changes: 87 additions & 0 deletions packages/core/src/constants/events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
export const EVENT_CLIENT_CONTEXT = "event-client";

export const EVENT_CLIENT_PAIRING_TRACES = {
pairing_started: "pairing_started",
pairing_uri_validation_success: "pairing_uri_validation_success",
pairing_uri_not_expired: "pairing_uri_not_expired",
store_new_pairing: "store_new_pairing",
subscribing_pairing_topic: "subscribing_pairing_topic",
subscribe_pairing_topic_success: "subscribe_pairing_topic_success",
existing_pairing: "existing_pairing",
pairing_not_expired: "pairing_not_expired",
emit_inactive_pairing: "emit_inactive_pairing",
emit_session_proposal: "emit_session_proposal",
subscribing_to_pairing_topic: "subscribing_to_pairing_topic",
};

export const EVENT_CLIENT_PAIRING_ERRORS = {
no_wss_connection: "no_wss_connection",
no_internet_connection: "no_internet_connection",
malformed_pairing_uri: "malformed_pairing_uri",
active_pairing_already_exists: "active_pairing_already_exists",
subscribe_pairing_topic_failure: "subscribe_pairing_topic_failure",
pairing_expired: "pairing_expired",
proposal_expired: "proposal_expired",
proposal_listener_not_found: "proposal_listener_not_found",
};

export const EVENT_CLIENT_SESSION_TRACES = {
session_approve_started: "session_approve_started",
proposal_not_expired: "proposal_not_expired",
session_namespaces_validation_success: "session_namespaces_validation_success",
create_session_topic: "create_session_topic",
subscribing_session_topic: "subscribing_session_topic",
subscribe_session_topic_success: "subscribe_session_topic_success",
publishing_session_approve: "publishing_session_approve",
session_approve_publish_success: "session_approve_publish_success",
store_session: "store_session",
publishing_session_settle: "publishing_session_settle",
session_settle_publish_success: "session_settle_publish_success",
};

export const EVENT_CLIENT_SESSION_ERRORS = {
no_internet_connection: "no_internet_connection",
no_wss_connection: "no_wss_connection",
proposal_expired: "proposal_expired",
subscribe_session_topic_failure: "subscribe_session_topic_failure",
session_approve_publish_failure: "session_approve_publish_failure",
session_settle_publish_failure: "session_settle_publish_failure",
session_approve_namespace_validation_failure: "session_approve_namespace_validation_failure",
proposal_not_found: "proposal_not_found",
};

export const EVENT_CLIENT_AUTHENTICATE_TRACES = {
authenticated_session_approve_started: "authenticated_session_approve_started",
authenticated_session_not_expired: "authenticated_session_not_expired",
chains_caip2_compliant: "chains_caip2_compliant",
chains_evm_compliant: "chains_evm_compliant",
create_authenticated_session_topic: "create_authenticated_session_topic",
cacaos_verified: "cacaos_verified",
store_authenticated_session: "store_authenticated_session",
subscribing_authenticated_session_topic: "subscribing_authenticated_session_topic",
subscribe_authenticated_session_topic_success: "subscribe_authenticated_session_topic_success",
publishing_authenticated_session_approve: "publishing_authenticated_session_approve",
authenticated_session_approve_publish_success: "authenticated_session_approve_publish_success",
};

export const EVENT_CLIENT_AUTHENTICATE_ERRORS = {
no_internet_connection: "no_internet_connection",
no_wss_connection: "no_wss_connection",
missing_session_authenticate_request: "missing_session_authenticate_request",
session_authenticate_request_expired: "session_authenticate_request_expired",
chains_caip2_compliant_failure: "chains_caip2_compliant_failure",
chains_evm_compliant_failure: "chains_evm_compliant_failure",
invalid_cacao: "invalid_cacao",
subscribe_authenticated_session_topic_failure: "subscribe_authenticated_session_topic_failure",
authenticated_session_approve_publish_failure: "authenticated_session_approve_publish_failure",
authenticated_session_pending_request_not_found:
"authenticated_session_pending_request_not_found",
};

export const EVENTS_STORAGE_VERSION = 0.1;

export const EVENTS_STORAGE_CONTEXT = "event-client";

export const EVENTS_STORAGE_CLEANUP_INTERVAL = 86400;

export const EVENTS_CLIENT_API_URL = "https://pulse.walletconnect.com/batch";
1 change: 1 addition & 0 deletions packages/core/src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ export * from "./history";
export * from "./expirer";
export * from "./verify";
export * from "./echo";
export * from "./events";
200 changes: 200 additions & 0 deletions packages/core/src/controllers/events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
import { generateChildLogger, Logger } from "@walletconnect/logger";
import { ICore, IEventClient, EventClientTypes } from "@walletconnect/types";
import { uuidv4 } from "@walletconnect/utils";
import {
CORE_STORAGE_PREFIX,
EVENTS_CLIENT_API_URL,
EVENTS_STORAGE_CLEANUP_INTERVAL,
EVENTS_STORAGE_CONTEXT,
EVENTS_STORAGE_VERSION,
RELAYER_SDK_VERSION,
} from "../constants";
import { HEARTBEAT_EVENTS } from "@walletconnect/heartbeat";
import { fromMiliseconds } from "@walletconnect/time";

export class EventClient extends IEventClient {
public readonly context = EVENTS_STORAGE_CONTEXT;
private readonly storagePrefix = CORE_STORAGE_PREFIX;
private readonly storageVersion = EVENTS_STORAGE_VERSION;

private events = new Map<string, EventClientTypes.Event>();
private toPersist = false;
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
constructor(public core: ICore, public logger: Logger, telemetryEnabled = true) {
super(core, logger, telemetryEnabled);
this.logger = generateChildLogger(logger, this.context);
if (telemetryEnabled) {
this.restore().then(async () => {
await this.submit();
this.setEventListeners();
});
} else {
// overwrite any persisted events with an empty array
this.persist();
}
}

get storageKey() {
return (
this.storagePrefix + this.storageVersion + this.core.customStoragePrefix + "//" + this.context
);
}

public createEvent: IEventClient["createEvent"] = (params) => {
const {
event = "ERROR",
type = "",
properties: { topic, trace },
} = params;
const eventId = uuidv4();
const bundleId = this.core.projectId || "";
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
const timestamp = Date.now();
const props = {
event,
type,
properties: {
topic,
trace,
},
};
const eventObj = {
eventId,
bundleId,
timestamp,
props,
...this.setMethods(eventId),
};

if (this.telemetryEnabled) {
this.events.set(eventId, eventObj);
this.toPersist = true;
}

return eventObj;
};

public getEvent: IEventClient["getEvent"] = (params) => {
const { eventId, topic } = params;
if (eventId) {
return this.events.get(eventId);
}
const event = Array.from(this.events.values()).find(
(event) => event.props.properties.topic === topic,
);

if (!event) return;

return {
...event,
...this.setMethods(event.eventId),
};
};

public deleteEvent: IEventClient["deleteEvent"] = (params) => {
const { eventId } = params;
this.events.delete(eventId);
this.toPersist = true;
};

private setEventListeners = () => {
this.core.heartbeat.on(HEARTBEAT_EVENTS.pulse, async () => {
if (this.toPersist) await this.persist();
// cleanup events older than EVENTS_STORAGE_CLEANUP_INTERVAL
this.events.forEach((event) => {
if (
fromMiliseconds(Date.now()) - fromMiliseconds(event.timestamp) >
EVENTS_STORAGE_CLEANUP_INTERVAL
) {
this.events.delete(event.eventId);
this.toPersist = true;
}
});
});
};

private setMethods = (eventId: string) => {
return {
addTrace: (trace: string) => this.addTrace(eventId, trace),
setError: (errorType: string) => this.setError(eventId, errorType),
};
};

private addTrace = async (eventId: string, trace: string) => {
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
const event = this.events.get(eventId);
if (!event) return;
return await new Promise<void>((resolve) => {
event.props.properties.trace.push(trace);
this.events.set(eventId, event);
this.toPersist = true;
resolve();
});
};

private setError = async (eventId: string, errorType: string) => {
const event = this.events.get(eventId);
if (!event) return;
return await new Promise<void>((resolve) => {
event.props.type = errorType;
event.timestamp = Date.now();
this.events.set(eventId, event);
this.toPersist = true;
resolve();
});
};

private persist = async () => {
await this.core.storage.setItem(this.storageKey, Array.from(this.events.values()));
this.toPersist = false;
};

private restore = async () => {
try {
const events =
(await this.core.storage.getItem<EventClientTypes.Event[]>(this.storageKey)) || [];
if (!events.length) return;
events.forEach((event) => {
this.events.set(event.eventId, {
...event,
...this.setMethods(event.eventId),
});
});
} catch (error) {
this.logger.warn(error);
}
};

private submit = async () => {
if (!this.telemetryEnabled) return;

if (this.events.size === 0) return;

const eventsToSend = [];
// exclude events without type as they can be considered `in progress`
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
for (const [_, event] of this.events) {
if (event.props.type) {
eventsToSend.push(event);
}
}

if (eventsToSend.length === 0) return;

try {
const response = await fetch(EVENTS_CLIENT_API_URL, {
Copy link
Member

Choose a reason for hiding this comment

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

priority should be set to low

ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
method: "POST",
body: JSON.stringify(eventsToSend),
headers: {
"x-project-id": `${this.core.projectId}`,
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
"x-sdk-type": "events_sdk",
"x-sdk-version": `js-${RELAYER_SDK_VERSION}`,
},
});
if (response.ok) {
for (const event of eventsToSend) {
this.events.delete(event.eventId);
this.toPersist = true;
ganchoradkov marked this conversation as resolved.
Show resolved Hide resolved
}
}
} catch (error) {
this.logger.warn(error);
}
};
}
1 change: 1 addition & 0 deletions packages/core/src/controllers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export * from "./history";
export * from "./expirer";
export * from "./verify";
export * from "./echo";
export * from "./events";
Loading
Loading