Skip to content

Commit

Permalink
feat: move tu provider listener
Browse files Browse the repository at this point in the history
  • Loading branch information
karczuRF committed Nov 8, 2024
1 parent 1dc4699 commit 9cbb4ca
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 16 deletions.
18 changes: 2 additions & 16 deletions src/providers/tari_universe/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ import {
ProviderRequest,
ProviderMethodNames,
ProviderReturnType,
ProviderResponse,
TariUniverseProviderParameters,
WindowSize,
} from "./types";
import { TariProvider } from "../index";
import { AccountsGetBalancesResponse, SubstateType } from "@tari-project/wallet_jrpc_client";
import { sendProviderCall } from "./utils";

export class TariUniverseProvider implements TariProvider {
public providerName = "TariUniverse";
Expand All @@ -39,21 +39,7 @@ export class TariUniverseProvider implements TariProvider {
req: Omit<ProviderRequest<MethodName>, "id">,
): Promise<ProviderReturnType<MethodName>> {
const id = ++this.__id;
return new Promise<ProviderReturnType<MethodName>>(function (resolve, reject) {
const event_ref = function (resp: MessageEvent<ProviderResponse<MethodName>>) {
if (resp.data.resultError) {
window.removeEventListener("message", event_ref);
reject(resp.data.resultError);
}
if (resp && resp.data && resp.data.id && resp.data.id == id && resp.data.type === "provider-call") {
window.removeEventListener("message", event_ref);
resolve(resp.data.result);
}
};
window.addEventListener("message", event_ref, false);

window.parent.postMessage({ ...req, id, type: "provider-call" }, "*");
});
return sendProviderCall(req, id);
}

public isConnected(): boolean {
Expand Down
23 changes: 23 additions & 0 deletions src/providers/tari_universe/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ProviderMethodNames, ProviderRequest, ProviderResponse, ProviderReturnType } from "./types";

export function sendProviderCall<MethodName extends ProviderMethodNames>(
req: Omit<ProviderRequest<MethodName>, "id">,
id: number,
): Promise<ProviderReturnType<MethodName>> {
return new Promise<ProviderReturnType<MethodName>>((resolve, reject) => {
const event_ref = (resp: MessageEvent<ProviderResponse<MethodName>>) => {
if (resp.data.resultError) {
window.removeEventListener("message", event_ref);
reject(resp.data.resultError);
}
if (resp && resp.data && resp.data.id && resp.data.id === id && resp.data.type === "provider-call") {
window.removeEventListener("message", event_ref);
resolve(resp.data.result);
}
};

window.addEventListener("message", event_ref, false);

window.parent.postMessage({ ...req, id, type: "provider-call" }, "*");
});
}

0 comments on commit 9cbb4ca

Please sign in to comment.