Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
8 changes: 8 additions & 0 deletions .changeset/terminal-core-lifetime.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@walletconnect/core": minor
"@walletconnect/sign-client": minor
"@walletconnect/types": minor
"@walletconnect/utils": minor
---

Add explicit terminal disposal for Core and SignClient, including owned request cancellation, listener and timer cleanup, and draining admitted storage mutations. SignClient disposal preserves a separately owned shared Core.
13 changes: 13 additions & 0 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@

Core for WalletConnect Protocol

## Lifetime

`core.dispose()` permanently closes that instance. It cancels pending connection attempts, removes network listeners, stops timers and drains admitted storage work. Construct a fresh instance to reopen persisted state. Ordinary `relayer.transportClose()` and `transportOpen()` retain their reconnect behavior.

A Core can be shared by multiple clients, including through global Core reuse. Its owner decides when to dispose it. When shutting down an exclusively owned client and Core, start both disposals before awaiting completion so pending protocol requests can be cancelled while local writes drain.

```ts
const clientClosing = client.dispose();
await Promise.all([clientClosing, core.dispose()]);
```

Keep the supplied storage available until both promises settle. Disposal preserves persisted sessions and keys for a future instance. Protocol messages already handed to the transport may have been delivered.

## License

WalletConnect Community License
3 changes: 3 additions & 0 deletions packages/core/src/controllers/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,10 @@ export class Crypto implements ICrypto {
}

public init: ICrypto["init"] = async () => {
this.core.assertActive();
if (!this.initialized) {
await this.keychain.init();
this.core.assertActive();
this.initialized = true;
}
};
Expand Down Expand Up @@ -205,6 +207,7 @@ export class Crypto implements ICrypto {
}

private isInitialized() {
this.core.assertActive();
if (!this.initialized) {
const { message } = getInternalError("NOT_INITIALIZED", this.name);
throw new Error(message);
Expand Down
54 changes: 41 additions & 13 deletions packages/core/src/controllers/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export class EventClient extends IEventClient {
private readonly storageVersion = EVENTS_STORAGE_VERSION;
private events = new Map<string, EventClientTypes.Event>();
private shouldPersist = false;
private readonly startup: Promise<void>;
constructor(
public core: ICore,
public logger: Logger,
Expand All @@ -27,23 +28,36 @@ export class EventClient extends IEventClient {
this.logger = generateChildLogger(logger, this.context);
this.telemetryEnabled = telemetryEnabled;
if (telemetryEnabled) {
this.restore().then(async () => {
await this.submit();
this.setEventListeners();
});
this.startup = this.restore()
.then(async () => {
await this.submit();
this.core.assertActive();
this.setEventListeners();
})
.catch((error) => {
if (!this.core.signal.aborted) this.logger.warn(error);
});
} else {
// overwrite any persisted events with an empty array
this.persist();
this.startup = this.persist().catch((error) => {
if (!this.core.signal.aborted) this.logger.warn(error);
});
}
}

public async dispose(): Promise<void> {
await this.startup;
this.events.clear();
}

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

public init: IEventClient["init"] = async (params) => {
this.core.assertActive();
if (isTestRun()) return;
const sdk = params?.sdk;
try {
Expand Down Expand Up @@ -72,6 +86,7 @@ export class EventClient extends IEventClient {
};

public createEvent: IEventClient["createEvent"] = (params) => {
this.core.assertActive();
const {
event = "ERROR",
type = "",
Expand Down Expand Up @@ -105,6 +120,7 @@ export class EventClient extends IEventClient {
};

public getEvent: IEventClient["getEvent"] = (params) => {
this.core.assertActive();
const { eventId, topic } = params;
if (eventId) {
return this.events.get(eventId);
Expand All @@ -122,13 +138,15 @@ export class EventClient extends IEventClient {
};

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

private setEventListeners = () => {
this.core.heartbeat.on(HEARTBEAT_EVENTS.pulse, async () => {
if (this.core.signal.aborted) return;
if (this.shouldPersist) await this.persist();
// cleanup events older than EVENTS_STORAGE_CLEANUP_INTERVAL
this.events.forEach((event) => {
Expand All @@ -151,6 +169,7 @@ export class EventClient extends IEventClient {
};

private addTrace = (eventId: string, trace: string) => {
this.core.assertActive();
const event = this.events.get(eventId);
if (!event) return;
event.props.properties.trace.push(trace);
Expand All @@ -159,6 +178,7 @@ export class EventClient extends IEventClient {
};

private setError = (eventId: string, errorType: string) => {
this.core.assertActive();
const event = this.events.get(eventId);
if (!event) return;
event.props.type = errorType;
Expand All @@ -168,14 +188,18 @@ export class EventClient extends IEventClient {
};

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

private restore = async () => {
try {
const events =
(await this.core.storage.getItem<EventClientTypes.Event[]>(this.storageKey)) || [];
(await this.core.run(() =>
this.core.storage.getItem<EventClientTypes.Event[]>(this.storageKey),
)) || [];
if (!events.length) return;
events.forEach((event) => {
this.events.set(event.eventId, {
Expand Down Expand Up @@ -205,6 +229,7 @@ export class EventClient extends IEventClient {

try {
const response = await this.sendEvent(eventsToSend);
this.core.assertActive();
if (response.ok) {
for (const event of eventsToSend) {
this.events.delete(event.eventId);
Expand All @@ -219,12 +244,15 @@ export class EventClient extends IEventClient {
private sendEvent = async (events: EventClientTypes.Event[]) => {
// if domain isn't available, set `sp` as `desktop` so data would be extracted on api side
const platform = this.getAppDomain() ? "" : "&sp=desktop";
const response = await fetch(
`${EVENTS_CLIENT_API_URL}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${RELAYER_SDK_VERSION}${platform}`,
{
method: "POST",
body: JSON.stringify(events),
},
const response = await this.core.run(() =>
fetch(
`${EVENTS_CLIENT_API_URL}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${RELAYER_SDK_VERSION}${platform}`,
{
method: "POST",
signal: this.core.signal,
body: JSON.stringify(events),
},
),
);
return response;
};
Expand Down
29 changes: 20 additions & 9 deletions packages/core/src/controllers/expirer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ export class Expirer extends IExpirer {
}

public init: IExpirer["init"] = async () => {
this.core.assertActive();
if (!this.initialized) {
this.logger.trace(`Initialized`);
await this.restore();
this.core.assertActive();
this.cached.forEach((expiration) => this.expirations.set(expiration.target, expiration));
this.cached = [];
this.registerEventListeners();
Expand Down Expand Up @@ -77,11 +79,12 @@ export class Expirer extends IExpirer {
const target = this.formatTarget(key);
const expiration = { target, expiry };
this.expirations.set(target, expiration);
this.checkExpiry(target, expiration);
this.checkExpiry(target, expiration, false);
this.events.emit(EXPIRER_EVENTS.created, {
target,
expiration,
} as ExpirerTypes.Created);
return this.persist();
};

public get: IExpirer["get"] = (key) => {
Expand All @@ -102,6 +105,7 @@ export class Expirer extends IExpirer {
expiration,
} as ExpirerTypes.Deleted);
}
return this.persist();
};

public on: IExpirer["on"] = (event, listener) => {
Expand Down Expand Up @@ -133,11 +137,15 @@ export class Expirer extends IExpirer {
}

private async setExpirations(expirations: ExpirerTypes.Expiration[]): Promise<void> {
await this.core.storage.setItem<ExpirerTypes.Expiration[]>(this.storageKey, expirations);
await this.core.run(() =>
this.core.storage.setItem<ExpirerTypes.Expiration[]>(this.storageKey, expirations),
);
}

private async getExpirations(): Promise<ExpirerTypes.Expiration[] | undefined> {
const expirations = await this.core.storage.getItem<ExpirerTypes.Expiration[]>(this.storageKey);
const expirations = await this.core.run(() =>
this.core.storage.getItem<ExpirerTypes.Expiration[]>(this.storageKey),
);
return expirations;
}

Expand Down Expand Up @@ -175,18 +183,23 @@ export class Expirer extends IExpirer {
return expiration;
}

private checkExpiry(target: string, expiration: ExpirerTypes.Expiration): void {
private checkExpiry(target: string, expiration: ExpirerTypes.Expiration, persist = true): void {
const { expiry } = expiration;
const msToTimeout = toMiliseconds(expiry) - Date.now();
if (msToTimeout <= 0) this.expire(target, expiration);
if (msToTimeout <= 0) this.expire(target, expiration, persist);
}

private expire(target: string, expiration: ExpirerTypes.Expiration): void {
private expire(target: string, expiration: ExpirerTypes.Expiration, persist: boolean): void {
this.expirations.delete(target);
this.events.emit(EXPIRER_EVENTS.expired, {
target,
expiration,
} as ExpirerTypes.Expired);
if (persist) {
this.persist().catch((error) => {
if (!this.core.signal.aborted) this.logger.warn(error);
});
}
}

private checkExpirations(): void {
Expand All @@ -201,23 +214,21 @@ export class Expirer extends IExpirer {
const eventName = EXPIRER_EVENTS.created;
this.logger.info(`Emitting ${eventName}`);
this.logger.debug({ type: "event", event: eventName, data: createdEvent });
this.persist();
});
this.events.on(EXPIRER_EVENTS.expired, (expiredEvent: ExpirerTypes.Expired) => {
const eventName = EXPIRER_EVENTS.expired;
this.logger.info(`Emitting ${eventName}`);
this.logger.debug({ type: "event", event: eventName, data: expiredEvent });
this.persist();
});
this.events.on(EXPIRER_EVENTS.deleted, (deletedEvent: ExpirerTypes.Deleted) => {
const eventName = EXPIRER_EVENTS.deleted;
this.logger.info(`Emitting ${eventName}`);
this.logger.debug({ type: "event", event: eventName, data: deletedEvent });
this.persist();
});
}

private isInitialized() {
this.core.assertActive();
if (!this.initialized) {
const { message } = getInternalError("NOT_INITIALIZED", this.name);
throw new Error(message);
Expand Down
24 changes: 17 additions & 7 deletions packages/core/src/controllers/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ export class JsonRpcHistory extends IJsonRpcHistory {
}

public init: IJsonRpcHistory["init"] = async () => {
this.core.assertActive();
if (!this.initialized) {
this.logger.trace(`Initialized`);
await this.restore();
this.core.assertActive();
this.cached.forEach((record) => this.records.set(record.id, record));
this.cached = [];
this.registerEventListeners();
Expand Down Expand Up @@ -79,7 +81,7 @@ export class JsonRpcHistory extends IJsonRpcHistory {
this.isInitialized();
this.logger.debug(`Setting JSON-RPC request history record`);
this.logger.trace({ type: "method", method: "set", topic, request, chainId });
if (this.records.has(request.id)) return;
if (this.records.has(request.id)) return Promise.resolve();
const record: JsonRpcRecord = {
id: request.id,
topic,
Expand All @@ -88,8 +90,9 @@ export class JsonRpcHistory extends IJsonRpcHistory {
expiry: calcExpiry(THIRTY_DAYS),
};
this.records.set(record.id, record);
this.persist();
const persisted = this.persist();
this.events.emit(HISTORY_EVENTS.created, record);
return persisted;
};

public resolve: IJsonRpcHistory["resolve"] = async (response) => {
Expand All @@ -98,13 +101,15 @@ export class JsonRpcHistory extends IJsonRpcHistory {
this.logger.trace({ type: "method", method: "update", response });
if (!this.records.has(response.id)) return;
const record = await this.getRecord(response.id);
this.core.assertActive();
if (typeof record.response !== "undefined") return;
record.response = isJsonRpcError(response)
? { error: response.error }
: { result: response.result };
this.records.set(record.id, record);
this.persist();
const persisted = this.persist();
this.events.emit(HISTORY_EVENTS.updated, record);
await persisted;
};

public get: IJsonRpcHistory["get"] = async (topic, id) => {
Expand All @@ -126,7 +131,7 @@ export class JsonRpcHistory extends IJsonRpcHistory {
this.events.emit(HISTORY_EVENTS.deleted, record);
}
});
this.persist();
return this.persist();
};

public exists: IJsonRpcHistory["exists"] = async (topic, id) => {
Expand Down Expand Up @@ -155,11 +160,13 @@ export class JsonRpcHistory extends IJsonRpcHistory {
// ---------- Private ----------------------------------------------- //

private async setJsonRpcRecords(records: JsonRpcRecord[]): Promise<void> {
await this.core.storage.setItem<JsonRpcRecord[]>(this.storageKey, records);
await this.core.run(() => this.core.storage.setItem<JsonRpcRecord[]>(this.storageKey, records));
}

private async getJsonRpcRecords(): Promise<JsonRpcRecord[] | undefined> {
const records = await this.core.storage.getItem<JsonRpcRecord[]>(this.storageKey);
const records = await this.core.run(() =>
this.core.storage.getItem<JsonRpcRecord[]>(this.storageKey),
);
return records;
}

Expand Down Expand Up @@ -234,14 +241,17 @@ export class JsonRpcHistory extends IJsonRpcHistory {
}
});
if (deleted) {
this.persist();
this.persist().catch((error) => {
if (!this.core.signal.aborted) this.logger.warn(error);
});
}
} catch (e) {
this.logger.warn(e);
}
}

private isInitialized() {
this.core.assertActive();
if (!this.initialized) {
const { message } = getInternalError("NOT_INITIALIZED", this.name);
throw new Error(message);
Expand Down
Loading
Loading