starknetkit
Version:
<!-- logo --> <p align="center"> <img width='300' src="https://starknetkit-website-git-blo-1541-argentlabs.vercel.app/starknetKit-logo.svg"> </p>
387 lines (386 loc) • 11.9 kB
JavaScript
var A = Object.defineProperty;
var k = (a, n, s) => n in a ? A(a, n, { enumerable: !0, configurable: !0, writable: !0, value: s }) : a[n] = s;
var u = (a, n, s) => (k(a, typeof n != "symbol" ? n + "" : n, s), s);
import { constants as v, WalletAccount as O } from "starknet";
import { C as U, a as d, b as g, U as C } from "./connector-d58f0dd8.js";
import { s as E, M as D, T as N, t as _, m as R, a as T, g as S, D as x } from "./trpc-870d4938.js";
import { P as H, r as M } from "./lastConnected-c0cae438.js";
class L extends Error {
constructor(s, t) {
super(s);
u(this, "code");
this.name = "ConnectAndSignSessionError", this.code = t;
}
}
class B extends Error {
constructor(s, t) {
super(s);
u(this, "code");
this.name = "WebwalletError", this.code = t;
}
}
const q = 385, G = 775, j = 385, z = 440, $ = 420, F = 438, m = [], X = (a, n) => ({
...a,
getLoginStatus: () => n.getLoginStatus.mutate(),
connectWebwallet: (t = {}) => {
const { theme: e } = t;
return n.connectWebwallet.mutate({
theme: e
});
},
connectAndSignSession: (t) => n.connectAndSignSession.mutate(t),
connectWebwalletSSO: (t, e) => n.connectWebwalletSSO.mutate({ token: t, authorizedPartyId: e }),
async request(t) {
switch (t.type) {
case "wallet_requestAccounts":
return n.requestAccounts.mutate(t.params);
case "wallet_signTypedData": {
const e = t.params, o = e?.primaryType === "Session" && e?.domain.name === "SessionAccount.session";
E({
width: j,
height: z,
location: o ? "/signSessionKeys" : "/signMessage"
});
const r = Array.isArray(t.params) ? t.params : [t.params];
return n.signTypedData.mutate(r);
}
case "wallet_getPermissions":
return n.getPermissions.mutate();
case "wallet_addInvokeTransaction": {
const e = t.params.calls;
return E({
width: q,
height: G,
location: "/review"
}), { transaction_hash: await n.addInvokeTransaction.mutate(e) };
}
case "wallet_requestChainId":
return await n.requestChainId.mutate();
case "wallet_addStarknetChain":
return n.addStarknetChain.mutate(t.params);
case "wallet_switchStarknetChain":
return n.switchStarknetChain.mutate(t.params);
case "wallet_watchAsset":
return n.watchAsset.mutate();
case "wallet_deploymentData":
return n.deploymentData.mutate();
default:
throw new Error("not implemented");
}
},
on: (t, e) => {
if (t === "accountsChanged")
m.push({
type: t,
handler: e
});
else if (t === "networkChanged")
m.push({
type: t,
handler: e
});
else
throw new Error(`Unknwown event: ${t}`);
},
off: (t, e) => {
if (t !== "accountsChanged" && t !== "networkChanged")
throw new Error(`Unknwown event: ${t}`);
const o = m.findIndex(
(r) => r.type === t && r.handler === e
);
o >= 0 && m.splice(o, 1);
}
}), J = (a) => {
a.style.display = "none", a.style.borderRadius = "40px", a.style.inset = "0", a.style.position = "fixed", a.style.top = "50%", a.style.left = "50%", a.style.transform = "translate(-50%, -50%)", a.style.backgroundColor = "transparent", a.style.zIndex = "999999", a.style.height = `${F}px`, a.style.width = `${$}px`;
}, K = (a, n) => {
a.style.display = "block", n.style.display = "block";
}, Q = (a, n) => {
a.style.display = "none", n.style.display = "none";
}, V = (a, n, s) => {
a.style.width = `${n}px`, a.style.height = `${s}px`;
}, I = "argent-webwallet-iframe", Y = async (a, n) => {
const s = "argent-webwallet-backdrop", t = new URL(a);
t.pathname = "/iframes/comms", a = t.toString();
const e = document.createElement("iframe");
e.src = a, e.loading = "eager", e.sandbox.add(
"allow-scripts",
"allow-same-origin",
"allow-forms",
"allow-top-navigation",
"allow-popups"
), e.allow = "clipboard-write", e.id = I, e.setAttribute("allowtransparency", "true"), e.setAttribute("transparent", "true"), J(e), e.style.display = n ? "block" : "none";
const o = document.createElement("div");
o.id = s, o.style.position = "fixed", o.style.inset = "0", o.style.backgroundColor = "rgba(0,0,0,0.5)", o.style.zIndex = "999998", o.style.width = "100dvw", o.style.height = "100dvh", o.style.backdropFilter = "blur(4px)";
const r = document.getElementById(I);
return r && (r.remove(), document.getElementById(s)?.remove()), window.document.body.appendChild(e), await new Promise((i, c) => {
const w = setTimeout(
() => c(new Error("Timeout while loading an iframe")),
2e4
);
e.addEventListener("load", async () => {
clearTimeout(w), i();
});
}), window.document.body.appendChild(o), { iframe: e, backdrop: o };
}, y = async (a, n, s) => {
const t = typeof window < "u" ? window : void 0;
if (!t)
throw new Error("window is not defined");
const e = X(
{
host: t.location.origin,
id: "argentWebWallet",
icon: "https://www.ready.co/favicon.ico",
name: "Web Wallet",
version: "1.0.0"
},
n
);
if (s) {
const { iframe: o, backdrop: r } = s;
n.updateModal.subscribe(void 0, {
onData(i) {
switch (i.action) {
case "show":
K(o, r);
break;
case "hide":
Q(o, r);
break;
case "updateSize":
V(o, i.width, i.height);
break;
}
}
});
}
return e;
}, W = "allowed-dapps", Z = async (a) => {
const n = a === v.NetworkName.SN_MAIN ? D : N;
try {
const t = await (await caches.open(W)).match(n);
if (t) {
const w = parseInt(
t.headers.get("X-Cache-Timestamp") ?? "0",
10
);
if (((/* @__PURE__ */ new Date()).getTime() - w) / (1e3 * 60 * 60) < 24)
return t.json();
}
const e = await fetch(n), o = new Headers(e.headers);
o.set("X-Cache-Timestamp", (/* @__PURE__ */ new Date()).getTime().toString());
const r = await e.json(), i = new Response(JSON.stringify(r), {
status: e.status,
statusText: e.statusText,
headers: o
});
return await (await caches.open(W)).put(n, i), r;
} catch (s) {
throw new Error(s);
}
}, tt = async (a) => new Promise((n) => {
if (!a)
return n(!1);
try {
navigator.webkitTemporaryStorage.queryUsageAndQuota(
(t, e) => {
n(
Math.round(e / (1024 * 1024)) < Math.round(
(performance?.memory?.jsHeapSizeLimit ?? 1073741824) / (1024 * 1024)
) * 2
);
},
() => n(!1)
);
} catch {
n(!1);
}
}), et = async (a) => {
const { userAgent: n } = navigator, s = !!(navigator.vendor && navigator.vendor.indexOf("Google") === 0 && navigator.brave === void 0 && !n.match(/Edg/) && !n.match(/OPR/)), t = await tt(s);
if (!s || t) {
const r = _({});
return await y(
a,
r,
void 0
);
}
const e = R(a), { allowedDapps: o } = await Z(e);
if (o.includes(window.location.hostname)) {
const r = "argent-webwallet-backdrop", i = "argent-webwallet-iframe", c = document.getElementById(r), w = document.getElementById(i);
w && w && c && (w.remove(), c.remove());
const { iframe: p, backdrop: f } = await Y(a, !1), b = _({
iframe: p.contentWindow ?? void 0
});
return await y(
a,
b,
{ iframe: p, backdrop: f }
);
} else {
const r = _({});
return await y(
a,
r,
void 0
);
}
}, P = "webwallet_logout";
let l = null, h = null;
class lt extends U {
constructor(s = {}) {
super();
u(this, "_wallet", null);
u(this, "_options");
this._options = s;
}
available() {
return !0;
}
async ready() {
if (this._wallet || await this.ensureWallet(), this._wallet)
try {
return (await this._wallet.request({
type: "wallet_getPermissions"
})).includes(H.ACCOUNTS);
} catch {
return !1;
}
else
return this._wallet = null, h = null, !1;
}
get id() {
return this._wallet = l, this._wallet?.id || "argentWebWallet";
}
get name() {
return this._wallet = l, this._wallet?.name || "Web Wallet";
}
get icon() {
return {
light: T,
dark: T
};
}
get wallet() {
if (!this._wallet)
throw new d();
return this._wallet;
}
get title() {
return "Email";
}
get subtitle() {
return "Powered by Ready";
}
async connectAndSignSession({
callbackData: s,
approvalRequests: t,
sessionTypedData: e
}) {
if (this._wallet || await this.ensureWallet(), !this._wallet)
throw new g();
try {
return await this._wallet.connectAndSignSession({
callbackData: s,
approvalRequests: t,
sessionTypedData: e,
theme: this._options.theme
});
} catch (o) {
if (o instanceof Error && (o.constructor.name === "TRPCClientError" || o.name === "TRPCClientError")) {
const r = o, i = r.shape.data.webwalletErrorMessage || r.message, c = r.shape.data.webwalletErrorCode || r.shape.message;
throw new L(i, c);
}
throw new Error(o instanceof Error ? o.message : String(o));
}
}
async connect(s = {}) {
if (this._wallet || await this.ensureWallet(), !this._wallet)
throw new g();
try {
let t, e;
if (this._options.ssoToken) {
const r = await this._wallet.connectWebwalletSSO(
this._options.ssoToken,
this._options.authorizedPartyId
);
t = r.account, e = r.chainId;
} else {
const r = await this._wallet.connectWebwallet({
theme: this._options.theme
});
t = r.account, e = r.chainId;
}
if (!t || !e)
return {};
const o = S(e);
return h = t[0], {
account: t[0],
chainId: BigInt(o)
};
} catch {
throw new C();
}
}
async request(s) {
if (this._wallet || await this.ensureWallet(), !this._wallet)
throw new d();
try {
return await this._wallet.request(s);
} catch (t) {
if (t instanceof Error && (t.constructor.name === "TRPCClientError" || t.name === "TRPCClientError")) {
const e = t, o = e.shape.data.webwalletErrorMessage || e.message, r = e.shape.data.webwalletErrorCode || e.shape.message;
throw r === "USER_LOGGED_OUT" && (l = null, h = null, this._wallet = null, document.dispatchEvent(new Event(P))), new B(o, r);
}
throw new C();
}
}
async disconnect() {
if (!this.available() && !this._wallet)
throw new g();
l = null, h = null, this._wallet = l, M();
}
async account(s) {
if (this._wallet = l, !this._wallet)
throw new d();
if (!h)
throw new d();
return new O(s, this._wallet, h, void 0);
}
async chainId() {
if (!this._wallet)
throw new d();
const s = await this._wallet.request({
type: "wallet_requestChainId"
}), t = S(s);
return BigInt(t);
}
async initEventListener(s) {
if (this._wallet = l, !this._wallet)
throw new d();
this._wallet.on("accountsChanged", s);
}
async removeEventListener(s) {
if (this._wallet = l, !this._wallet)
throw new d();
this._wallet.off("accountsChanged", s), l = null, h = null, this._wallet = null;
}
async ensureWallet() {
const s = this._options.url || x;
E({
origin: s,
location: "/interstitialLogin"
}), l = await et(s) ?? null, this._wallet = l;
}
}
const ct = (a) => {
document.addEventListener(P, () => {
a();
});
};
export {
L as ConnectAndSignSessionError,
P as WEBWALLET_LOGOUT_EVENT,
lt as WebWalletConnector,
B as WebwalletError,
ct as handleWebwalletLogoutEvent
};