starknetkit
Version:
<!-- logo --> <p align="center"> <img width='300' src="https://starknetkit-website-git-blo-1541-argentlabs.vercel.app/starknetKit-logo.svg"> </p>
1,417 lines • 130 kB
JavaScript
var Ct = Object.defineProperty;
var xt = (e, t, r) => t in e ? Ct(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r;
var d = (e, t, r) => (xt(e, typeof t != "symbol" ? t + "" : t, r), r);
import { shortString as J, constants as Q, WalletAccount as $t, num as Ot } from "starknet";
import { C as Lt, d as Ut, e as we, a as W, U as Yt } from "./connector-4bc69b15.js";
const nt = "0.10.0", Qt = {
version: nt
};
var P = /* @__PURE__ */ ((e) => (e.SUCCESS = "SUCCESS", e.NOT_CONNECTED = "NOT_CONNECTED", e.ERROR = "ERROR", e.CANCELED = "CANCELED", e.USER_INTERACTION_REQUIRED = "USER_INTERACTION_REQUIRED", e))(P || {});
function Pt(e) {
return Array.isArray(e) ? e : [e];
}
function Bt(e) {
const t = e.pathname.split("/");
if (e.hostname === "localhost" || e.hostname === "127.0.0.1" || e.hostname === "0.0.0.0") {
if (typeof XMLHttpRequest > "u")
return console.warn(
`Cannot make synchronous HTTP call in Node.js environment for ${e.toString()}`
), J.encodeShortString("LOCALHOST");
const r = new XMLHttpRequest();
r.open("POST", e.toString(), !1), r.setRequestHeader("Content-Type", "application/json");
const n = JSON.stringify({
jsonrpc: "2.0",
method: "starknet_chainId",
params: [],
id: 1
});
try {
if (r.send(n), r.status === 200) {
const i = JSON.parse(r.responseText);
if (i.result)
return i.result;
}
throw new Error(
`Failed to get chain ID from ${e.toString()}: ${r.status} ${r.statusText}`
);
} catch (i) {
throw new Error(`Failed to connect to ${e.toString()}: ${i}`);
}
}
if (t.includes("starknet")) {
if (t.includes("mainnet"))
return Q.StarknetChainId.SN_MAIN;
if (t.includes("sepolia"))
return Q.StarknetChainId.SN_SEPOLIA;
} else if (t.length >= 3) {
const r = t[2];
if (t.includes("katana"))
return J.encodeShortString(
`WP_${r.toUpperCase().replace(/-/g, "_")}`
);
if (t.includes("mainnet"))
return J.encodeShortString(
`GG_${r.toUpperCase().replace(/-/g, "_")}`
);
}
throw new Error(`Chain ${e.toString()} not supported`);
}
let D = class it extends Error {
constructor() {
super("Not ready to connect"), Object.setPrototypeOf(this, it.prototype);
}
};
const Rt = "https://x.cartridge.gg", _t = {
ACCOUNTS: "accounts"
}, Zt = "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODAwIiBoZWlnaHQ9IjgwMCIgdmlld0JveD0iMCAwIDgwMCA4MDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGZpbHRlcj0idXJsKCNmaWx0ZXIwX2RfNTExMl83ODIpIj4KPHBhdGggZD0iTTQ2OS4yMzYgNzBDNDgyLjM5IDcwIDQ5My4wNTMgODAuNjYzIDQ5My4wNTMgOTMuODE2NFYxNDcuMTQ3TDUxNS4zMzggMTQ3LjE0N0w1MTUuNDI4IDE0Ny4xNDdMNTE1LjU1NCAxNDcuMTQ3TDUxNS44MjYgMTQ3LjE0OUM1MTYuMDE2IDE0Ny4xNTEgNTE2LjIyNSAxNDcuMTUzIDUxNi40NTEgMTQ3LjE1N0M1MTYuOTA0IDE0Ny4xNjQgNTE3LjQyOCAxNDcuMTc2IDUxOC4wMiAxNDcuMTk1QzUxOS4yMDEgMTQ3LjIzNCA1MjAuNjYgMTQ3LjMwNCA1MjIuMzYxIDE0Ny40MjRDNTI1Ljc0MSAxNDcuNjYzIDUzMC4xODUgMTQ4LjExNCA1MzUuMzYzIDE0OC45NjlDNTQ1LjAwMSAxNTAuNTYyIDU1OC41NTYgMTUzLjc4IDU3Mi45MTggMTYwLjYwM0w3MzAuNDIgMjI2LjY3MUw3MzIuMTAxIDIyNy41MDVDNzcxLjc4NyAyNDcuMTc3IDc4OS45OTMgMjg2LjI5NiA3ODkuOTkzIDMyMi4wMzZWNTg1Ljg2NUM3ODkuOTkzIDU4Ni4wNTQgNzg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aWx0ZXIgaWQ9ImZpbHRlcjBfZF81MTEyXzc4MiIgeD0iLTQiIHk9IjAiIHdpZHRoPSI4MDgiIGhlaWdodD0iODA4IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUNvbG9yTWF0cml4IGluPSJTb3VyY2VBbHBoYSIgdHlwZT0ibWF0cml4IiB2YWx1ZXM9IjAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDEyNyAwIiByZXN1bHQ9ImhhcmRBbHBoYSIvPgo8ZmVPZmZzZXQgZHk9IjQiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iMiIvPgo8ZmVDb21wb3NpdGUgaW4yPSJoYXJkQWxwaGEiIG9wZXJhdG9yPSJvdXQiLz4KPGZlQ29sb3JNYXRyaXggdHlwZT0ibWF0cml4IiB2YWx1ZXM9IjAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAuMjUgMCIvPgo8ZmVCbGVuZCBtb2RlPSJub3JtYWwiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9ImVmZmVjdDFfZHJvcFNoYWRvd181MTEyXzc4MiIvPgo8ZmVCbGVuZCBtb2RlPSJub3JtYWwiIGluPSJTb3VyY2VHcmFwaGljIiBpbjI9ImVmZmVjdDFfZHJvcFNoYWRvd181MTEyXzc4MiIgcmVzdWx0PSJzaGFwZSIvPgo8L2ZpbHRlcj4KPC9kZWZzPgo8L3N2Zz4K";
function Wt() {
}
class Vt {
constructor() {
d(this, "m_lastPromise", Promise.resolve());
}
/**
* Acquire lock
* @param [bypass=false] option to skip lock acquisition
*/
async obtain(t = !1) {
let r = Wt;
if (t)
return r;
const n = this.m_lastPromise;
return this.m_lastPromise = new Promise((i) => r = i), await n, r;
}
}
const Ft = new Vt();
let Gt = class {
constructor() {
d(this, "id", "controller");
d(this, "name", "Controller");
d(this, "version", Qt.version);
d(this, "icon", Zt);
d(this, "account");
d(this, "subscriptions", []);
d(this, "_probePromise", null);
d(this, "request", async (t) => {
switch (t.type) {
case "wallet_getPermissions":
return await this.safeProbe(), this.account ? [_t.ACCOUNTS] : [];
case "wallet_requestAccounts": {
if (this.account)
return [this.account.address];
const n = t.params && t.params.silent_mode;
return this.account = await this.safeProbe(), !this.account && !n && (this.account = await this.connect()), this.account ? [this.account.address] : [];
}
case "wallet_watchAsset":
throw {
code: 63,
message: "An unexpected error occurred",
data: "wallet_watchAsset not implemented"
};
case "wallet_addStarknetChain": {
let n = t.params;
return this.addStarknetChain(n);
}
case "wallet_switchStarknetChain": {
let n = t.params;
return this.switchStarknetChain(n.chainId);
}
case "wallet_requestChainId":
if (!this.account)
throw {
code: 63,
message: "An unexpected error occurred",
data: "Account not initialized"
};
return await this.account.getChainId();
case "wallet_deploymentData":
throw {
code: 63,
message: "An unexpected error occurred",
data: "wallet_deploymentData not implemented"
};
case "wallet_addInvokeTransaction":
if (!this.account)
throw {
code: 63,
message: "An unexpected error occurred",
data: "Account not initialized"
};
let r = t.params;
return await this.account.execute(
r.calls.map((n) => ({
contractAddress: n.contract_address,
entrypoint: n.entry_point,
calldata: n.calldata
}))
);
case "wallet_addDeclareTransaction":
throw {
code: 63,
message: "An unexpected error occurred",
data: "wallet_addDeclareTransaction not implemented"
};
case "wallet_signTypedData": {
if (!this.account)
throw {
code: 63,
message: "An unexpected error occurred",
data: "Account not initialized"
};
return await this.account.signMessage(t.params);
}
case "wallet_supportedSpecs":
return [];
case "wallet_supportedWalletApi":
return [];
default:
throw {
code: 63,
message: "An unexpected error occurred",
data: `Unknown RPC call type: ${t.type}`
};
}
});
d(this, "on", (t, r) => {
if (t !== "accountsChanged" && t !== "networkChanged")
throw new Error(`Unknown event: ${t}`);
this.subscriptions.push({ type: t, handler: r });
});
d(this, "off", (t, r) => {
if (t !== "accountsChanged" && t !== "networkChanged")
throw new Error(`Unknown event: ${t}`);
const n = this.subscriptions.findIndex(
(i) => i.type === t && i.handler === r
);
n >= 0 && this.subscriptions.splice(n, 1);
});
}
async safeProbe() {
if (this.account)
return this.account;
if (this._probePromise)
return this._probePromise;
const t = await Ft.obtain();
return await new Promise(async (r) => {
try {
this._probePromise = this.probe();
const n = await this._probePromise;
r(n);
} finally {
this._probePromise = null;
}
}).finally(() => {
t();
});
}
emitNetworkChanged(t) {
this.subscriptions.filter((r) => r.type === "networkChanged").forEach((r) => {
r.handler(t);
});
}
emitAccountsChanged(t) {
this.subscriptions.filter((r) => r.type === "accountsChanged").forEach((r) => {
r.handler(t);
});
}
};
class Qe extends $t {
constructor(r, n, i, o, s, a) {
super({
provider: { nodeUrl: n },
walletProvider: r,
address: i
});
d(this, "keychain");
d(this, "modal");
d(this, "options");
this.keychain = o, this.options = s, this.modal = a;
}
/**
* Invoke execute function in account contract
*
* @param calls the invocation object or an array of them, containing:
* - contractAddress - the address of the contract
* - entrypoint - the entrypoint of the contract
* - calldata - (defaults to []) the calldata
* - signature - (defaults to []) the signature
* @param abis (optional) the abi of the contract for better displaying
*
* @returns response from addTransaction
*/
async execute(r) {
return r = Pt(r), new Promise(async (n, i) => {
const o = await this.keychain.execute(
r,
void 0,
void 0,
!1,
this.options?.feeSource
);
if (o.code === P.SUCCESS) {
n(o);
return;
}
if (this.options?.propagateSessionErrors && o.code !== P.USER_INTERACTION_REQUIRED) {
i(o.error);
return;
}
this.modal.open();
const s = await this.keychain.execute(
r,
void 0,
void 0,
!0,
o.error
);
if (s.code === P.SUCCESS) {
n(s), this.modal.close();
return;
}
i(s.error);
});
}
/**
* Sign an JSON object for off-chain usage with the starknet private key and return the signature
* This adds a message prefix so it cant be interchanged with transactions
*
* @param json - JSON object to be signed
* @returns the signature of the JSON object
* @throws {Error} if the JSON object is not a valid JSON
*/
async signMessage(r) {
return new Promise(async (n, i) => {
const o = await this.keychain.signMessage(r, "", !0);
if (!("code" in o)) {
n(o);
return;
}
this.modal.open();
const s = await this.keychain.signMessage(r, "", !1);
"code" in s ? i(s.error) : n(s), this.modal.close();
});
}
}
var C;
(function(e) {
e.Call = "call", e.Reply = "reply", e.Syn = "syn", e.SynAck = "synAck", e.Ack = "ack";
})(C || (C = {}));
var U;
(function(e) {
e.Fulfilled = "fulfilled", e.Rejected = "rejected";
})(U || (U = {}));
var q;
(function(e) {
e.ConnectionDestroyed = "ConnectionDestroyed", e.ConnectionTimeout = "ConnectionTimeout", e.NoIframeSrc = "NoIframeSrc";
})(q || (q = {}));
var Ie;
(function(e) {
e.DataCloneError = "DataCloneError";
})(Ie || (Ie = {}));
var O;
(function(e) {
e.Message = "message";
})(O || (O = {}));
const Ht = (e, t) => {
const r = [];
let n = !1;
return {
destroy(i) {
n || (n = !0, t(`${e}: Destroying connection`), r.forEach((o) => {
o(i);
}));
},
onDestroy(i) {
n ? i() : r.push(i);
}
};
}, Jt = (e) => (...t) => {
e && console.log("[Penpal]", ...t);
}, Xt = {
"http:": "80",
"https:": "443"
}, qt = /^(https?:)?\/\/([^/:]+)?(:(\d+))?/, Kt = ["file:", "data:"], er = (e) => {
if (e && Kt.find((a) => e.startsWith(a)))
return "null";
const t = document.location, r = qt.exec(e);
let n, i, o;
r ? (n = r[1] ? r[1] : t.protocol, i = r[2], o = r[4]) : (n = t.protocol, i = t.hostname, o = t.port);
const s = o && o !== Xt[n] ? `:${o}` : "";
return `${n}//${i}${s}`;
}, Pe = ({ name: e, message: t, stack: r }) => ({
name: e,
message: t,
stack: r
}), tr = (e) => {
const t = new Error();
return Object.keys(e).forEach((r) => t[r] = e[r]), t;
}, rr = (e, t, r) => {
const { localName: n, local: i, remote: o, originForSending: s, originForReceiving: a } = e;
let h = !1;
const c = (l) => {
if (l.source !== o || l.data.penpal !== C.Call)
return;
if (a !== "*" && l.origin !== a) {
r(`${n} received message from origin ${l.origin} which did not match expected origin ${a}`);
return;
}
const u = l.data, { methodName: w, args: g, id: f } = u;
r(`${n}: Received ${w}() call`);
const A = (N) => (k) => {
if (r(`${n}: Sending ${w}() reply`), h) {
r(`${n}: Unable to send ${w}() reply due to destroyed connection`);
return;
}
const p = {
penpal: C.Reply,
id: f,
resolution: N,
returnValue: k
};
N === U.Rejected && k instanceof Error && (p.returnValue = Pe(k), p.returnValueIsError = !0);
try {
o.postMessage(p, s);
} catch (M) {
if (M.name === Ie.DataCloneError) {
const v = {
penpal: C.Reply,
id: f,
resolution: U.Rejected,
returnValue: Pe(M),
returnValueIsError: !0
};
o.postMessage(v, s);
}
throw M;
}
};
new Promise((N) => N(t[w].call(t, l.origin).apply(t, g))).then(A(U.Fulfilled), A(U.Rejected));
};
return i.addEventListener(O.Message, c), () => {
h = !0, i.removeEventListener(O.Message, c);
};
};
let nr = 0;
const ir = () => ++nr, ot = ".", st = (e) => e ? e.split(ot) : [], or = (e) => e.join(ot), sr = (e, t) => {
const r = st(t || "");
return r.push(e), or(r);
}, ar = (e, t, r) => {
const n = st(t);
return n.reduce((i, o, s) => (typeof i[o] > "u" && (i[o] = {}), s === n.length - 1 && (i[o] = r), i[o]), e), e;
}, at = (e, t) => {
const r = {};
return Object.keys(e).forEach((n) => {
const i = e[n], o = sr(n, t);
typeof i == "object" && Object.assign(r, at(i, o)), typeof i == "function" && (r[o] = i);
}), r;
}, cr = (e) => {
const t = {};
for (const r in e)
ar(t, r, e[r]);
return t;
}, hr = (e, t, r, n, i) => {
const { localName: o, local: s, remote: a, originForSending: h, originForReceiving: c } = t;
let l = !1;
i(`${o}: Connecting call sender`);
const u = (g) => (...f) => {
i(`${o}: Sending ${g}() call`);
let A;
try {
a.closed && (A = !0);
} catch {
A = !0;
}
if (A && n(), l) {
const N = new Error(`Unable to send ${g}() call due to destroyed connection`);
throw N.code = q.ConnectionDestroyed, N;
}
return new Promise((N, k) => {
const p = ir(), M = (T) => {
if (T.source !== a || T.data.penpal !== C.Reply || T.data.id !== p)
return;
if (c !== "*" && T.origin !== c) {
i(`${o} received message from origin ${T.origin} which did not match expected origin ${c}`);
return;
}
const ue = T.data;
i(`${o}: Received ${g}() reply`), s.removeEventListener(O.Message, M);
let de = ue.returnValue;
ue.returnValueIsError && (de = tr(de)), (ue.resolution === U.Fulfilled ? N : k)(de);
};
s.addEventListener(O.Message, M);
const v = {
penpal: C.Call,
id: p,
methodName: g,
args: f
};
a.postMessage(v, h);
});
}, w = r.reduce((g, f) => (g[f] = u(f), g), {});
return Object.assign(e, cr(w)), () => {
l = !0;
};
}, lr = (e, t, r, n, i) => {
const { destroy: o, onDestroy: s } = n;
let a, h;
const c = {};
return (l) => {
if (t !== "*" && l.origin !== t) {
i(`Parent: Handshake - Received ACK message from origin ${l.origin} which did not match expected origin ${t}`);
return;
}
i("Parent: Handshake - Received ACK");
const u = {
localName: "Parent",
local: window,
remote: l.source,
originForSending: r,
originForReceiving: t
};
a && a(), a = rr(u, e, i), s(a), h && h.forEach((g) => {
delete c[g];
}), h = l.data.methodNames;
const w = hr(c, u, h, o, i);
return s(w), c;
};
}, ur = (e, t, r, n) => (i) => {
if (!i.source)
return;
if (r !== "*" && i.origin !== r) {
e(`Parent: Handshake - Received SYN message from origin ${i.origin} which did not match expected origin ${r}`);
return;
}
e("Parent: Handshake - Received SYN, responding with SYN-ACK");
const o = {
penpal: C.SynAck,
methodNames: Object.keys(t)
};
i.source.postMessage(o, n);
}, dr = 6e4, wr = (e, t) => {
const { destroy: r, onDestroy: n } = t, i = setInterval(() => {
e.isConnected || (clearInterval(i), r());
}, dr);
n(() => {
clearInterval(i);
});
}, gr = (e, t) => {
let r;
return e !== void 0 && (r = window.setTimeout(() => {
const n = new Error(`Connection timed out after ${e}ms`);
n.code = q.ConnectionTimeout, t(n);
}, e)), () => {
clearTimeout(r);
};
}, yr = (e) => {
if (!e.src && !e.srcdoc) {
const t = new Error("Iframe must have src or srcdoc property defined.");
throw t.code = q.NoIframeSrc, t;
}
}, fr = (e) => {
let { iframe: t, methods: r = {}, childOrigin: n, timeout: i, debug: o = !1 } = e;
const s = Jt(o), a = Ht("Parent", s), { onDestroy: h, destroy: c } = a;
n || (yr(t), n = er(t.src));
const l = n === "null" ? "*" : n, u = at(r), w = ur(s, u, n, l), g = lr(u, n, l, a, s);
return {
promise: new Promise((f, A) => {
const N = gr(i, c), k = (p) => {
if (!(p.source !== t.contentWindow || !p.data)) {
if (p.data.penpal === C.Syn) {
w(p);
return;
}
if (p.data.penpal === C.Ack) {
const M = g(p);
M && (N(), f(M));
return;
}
}
};
window.addEventListener(O.Message, k), s("Parent: Awaiting handshake"), wr(t, a), h((p) => {
window.removeEventListener(O.Message, k), p && A(p);
});
}),
destroy() {
c();
}
};
};
class pr {
constructor({
id: t,
url: r,
preset: n,
onClose: i,
onConnect: o,
methods: s = {}
}) {
d(this, "url");
d(this, "iframe");
d(this, "container");
d(this, "onClose");
d(this, "child");
d(this, "closeTimeout");
if (typeof document > "u" || typeof window > "u")
return;
n && r.searchParams.set("preset", n), this.url = r;
const a = document.createElement("iframe");
a.src = r.toString(), a.id = t, a.style.border = "none", a.sandbox.add("allow-forms"), a.sandbox.add("allow-popups"), a.sandbox.add("allow-popups-to-escape-sandbox"), a.sandbox.add("allow-scripts"), a.sandbox.add("allow-same-origin"), a.allow = "publickey-credentials-create *; publickey-credentials-get *; clipboard-write", document.hasStorageAccess && a.sandbox.add("allow-storage-access-by-user-activation");
const h = document.createElement("div");
h.id = "controller", h.style.position = "fixed", h.style.height = "100%", h.style.width = "100%", h.style.top = "0", h.style.left = "0", h.style.zIndex = "10000", h.style.backgroundColor = "rgba(0,0,0,0.6)", h.style.display = "none", h.style.alignItems = "center", h.style.justifyContent = "center", h.style.transition = "opacity 0.2s ease", h.style.opacity = "0", h.style.pointerEvents = "auto", h.appendChild(a), h.addEventListener("click", (u) => {
u.target === h && (t === "controller-keychain" && this.child && this.child.reset?.().catch((w) => console.error("Error resetting context:", w)), this.close());
}), this.iframe = a, this.container = h, fr({
iframe: this.iframe,
methods: {
close: (u) => () => this.close(),
reload: (u) => () => window.location.reload(),
...s
}
}).promise.then((u) => {
this.child = u, o(u);
}), this.resize(), window.addEventListener("resize", () => this.resize());
const c = new MutationObserver(() => {
if (typeof document > "u")
return;
const u = document.getElementById("controller");
document.body && t === "controller-keychain" && !u && (document.body.appendChild(h), c.disconnect());
});
c.observe(document.documentElement, {
childList: !0,
subtree: !0
});
const l = document.getElementById("controller");
document.body && t === "controller-keychain" && !l && document.body.appendChild(h), this.onClose = i;
}
open() {
!this.container || typeof document > "u" || !document.body || (this.closeTimeout && (clearTimeout(this.closeTimeout), this.closeTimeout = void 0), document.body.style.overflow = "hidden", this.container.style.display = "flex", requestAnimationFrame(() => {
this.container && (this.container.style.opacity = "1");
}));
}
close() {
!this.container || typeof document > "u" || !document.body || (this.onClose?.(), document.body.style.overflow = "auto", this.container.style.opacity = "0", this.closeTimeout = setTimeout(() => {
this.container && (this.container.style.display = "none"), this.closeTimeout = void 0;
}, 200));
}
sendBackward() {
this.container && (this.container.style.zIndex = "9999");
}
sendForward() {
this.container && (this.container.style.zIndex = "10000");
}
resize() {
if (!(!this.iframe || typeof window > "u")) {
if (this.iframe.style.userSelect = "none", window.innerWidth < 768) {
this.iframe.style.height = "100%", this.iframe.style.width = "100%", this.iframe.style.borderRadius = "0";
return;
}
this.iframe.style.height = "600px", this.iframe.style.width = "432px", this.iframe.style.borderRadius = "8px";
}
}
isOpen() {
return this.container?.style.display !== "none";
}
}
const mr = "6.13.7";
function Be(e, t, r) {
for (let n in t) {
let i = t[n];
Object.defineProperty(e, n, { enumerable: !0, value: i, writable: !1 });
}
}
function _(e) {
if (e == null)
return "null";
if (Array.isArray(e))
return "[ " + e.map(_).join(", ") + " ]";
if (e instanceof Uint8Array) {
const t = "0123456789abcdef";
let r = "0x";
for (let n = 0; n < e.length; n++)
r += t[e[n] >> 4], r += t[e[n] & 15];
return r;
}
if (typeof e == "object" && typeof e.toJSON == "function")
return _(e.toJSON());
switch (typeof e) {
case "boolean":
case "symbol":
return e.toString();
case "bigint":
return BigInt(e).toString();
case "number":
return e.toString();
case "string":
return JSON.stringify(e);
case "object": {
const t = Object.keys(e);
return t.sort(), "{ " + t.map((r) => `${_(r)}: ${_(e[r])}`).join(", ") + " }";
}
}
return "[ COULD NOT SERIALIZE ]";
}
function Nr(e, t, r) {
let n = e;
{
const o = [];
if (r) {
if ("message" in r || "code" in r || "name" in r)
throw new Error(`value will overwrite populated values: ${_(r)}`);
for (const s in r) {
if (s === "shortMessage")
continue;
const a = r[s];
o.push(s + "=" + _(a));
}
}
o.push(`code=${t}`), o.push(`version=${mr}`), o.length && (e += " (" + o.join(", ") + ")");
}
let i;
switch (t) {
case "INVALID_ARGUMENT":
i = new TypeError(e);
break;
case "NUMERIC_FAULT":
case "BUFFER_OVERRUN":
i = new RangeError(e);
break;
default:
i = new Error(e);
}
return Be(i, { code: t }), r && Object.assign(i, r), i.shortMessage == null && Be(i, { shortMessage: n }), i;
}
function Mr(e, t, r, n) {
if (!e)
throw Nr(t, r, n);
}
function F(e, t, r, n) {
Mr(e, t, "INVALID_ARGUMENT", { argument: r, value: n });
}
["NFD", "NFC", "NFKD", "NFKC"].reduce((e, t) => {
try {
if ("test".normalize(t) !== "test")
throw new Error("bad");
if (t === "NFD" && "é".normalize("NFD") !== "é")
throw new Error("broken");
e.push(t);
} catch {
}
return e;
}, []);
function Ir(e, t, r) {
if (e instanceof Uint8Array)
return e;
if (typeof e == "string" && e.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)) {
const n = new Uint8Array((e.length - 2) / 2);
let i = 2;
for (let o = 0; o < n.length; o++)
n[o] = parseInt(e.substring(i, i + 2), 16), i += 2;
return n;
}
F(!1, "invalid BytesLike value", t || "value", e);
}
function ke(e, t) {
return Ir(e, t);
}
const Re = "0123456789abcdef";
function Ar(e) {
const t = ke(e);
let r = "0x";
for (let n = 0; n < t.length; n++) {
const i = t[n];
r += Re[(i & 240) >> 4] + Re[i & 15];
}
return r;
}
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function jr(e) {
return e instanceof Uint8Array || ArrayBuffer.isView(e) && e.constructor.name === "Uint8Array";
}
function _e(e) {
if (!Number.isSafeInteger(e) || e < 0)
throw new Error("positive integer expected, got " + e);
}
function ie(e, ...t) {
if (!jr(e))
throw new Error("Uint8Array expected");
if (t.length > 0 && !t.includes(e.length))
throw new Error("Uint8Array expected of length " + t + ", got length=" + e.length);
}
function Ze(e, t = !0) {
if (e.destroyed)
throw new Error("Hash instance has been destroyed");
if (t && e.finished)
throw new Error("Hash#digest() has already been called");
}
function Dr(e, t) {
ie(e);
const r = t.outputLen;
if (e.length < r)
throw new Error("digestInto() expects output buffer of length at least " + r);
}
function br(e) {
return new Uint32Array(e.buffer, e.byteOffset, Math.floor(e.byteLength / 4));
}
function ct(...e) {
for (let t = 0; t < e.length; t++)
e[t].fill(0);
}
const Er = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
function kr(e) {
return e << 24 & 4278190080 | e << 8 & 16711680 | e >>> 8 & 65280 | e >>> 24 & 255;
}
function zr(e) {
for (let t = 0; t < e.length; t++)
e[t] = kr(e[t]);
return e;
}
const We = Er ? (e) => e : zr;
function vr(e) {
if (typeof e != "string")
throw new Error("string expected");
return new Uint8Array(new TextEncoder().encode(e));
}
function ht(e) {
return typeof e == "string" && (e = vr(e)), ie(e), e;
}
class Tr {
}
function Sr(e) {
const t = (n) => e().update(ht(n)).digest(), r = e();
return t.outputLen = r.outputLen, t.blockLen = r.blockLen, t.create = () => e(), t;
}
const te = /* @__PURE__ */ BigInt(2 ** 32 - 1), Ve = /* @__PURE__ */ BigInt(32);
function Cr(e, t = !1) {
return t ? { h: Number(e & te), l: Number(e >> Ve & te) } : { h: Number(e >> Ve & te) | 0, l: Number(e & te) | 0 };
}
function xr(e, t = !1) {
const r = e.length;
let n = new Uint32Array(r), i = new Uint32Array(r);
for (let o = 0; o < r; o++) {
const { h: s, l: a } = Cr(e[o], t);
[n[o], i[o]] = [s, a];
}
return [n, i];
}
const $r = (e, t, r) => e << r | t >>> 32 - r, Or = (e, t, r) => t << r | e >>> 32 - r, Lr = (e, t, r) => t << r - 32 | e >>> 64 - r, Ur = (e, t, r) => e << r - 32 | t >>> 64 - r, Yr = BigInt(0), V = BigInt(1), Qr = BigInt(2), Pr = BigInt(7), Br = BigInt(256), Rr = BigInt(113), lt = [], ut = [], dt = [];
for (let e = 0, t = V, r = 1, n = 0; e < 24; e++) {
[r, n] = [n, (2 * r + 3 * n) % 5], lt.push(2 * (5 * n + r)), ut.push((e + 1) * (e + 2) / 2 % 64);
let i = Yr;
for (let o = 0; o < 7; o++)
t = (t << V ^ (t >> Pr) * Rr) % Br, t & Qr && (i ^= V << (V << /* @__PURE__ */ BigInt(o)) - V);
dt.push(i);
}
const wt = xr(dt, !0), _r = wt[0], Zr = wt[1], Fe = (e, t, r) => r > 32 ? Lr(e, t, r) : $r(e, t, r), Ge = (e, t, r) => r > 32 ? Ur(e, t, r) : Or(e, t, r);
function Wr(e, t = 24) {
const r = new Uint32Array(10);
for (let n = 24 - t; n < 24; n++) {
for (let s = 0; s < 10; s++)
r[s] = e[s] ^ e[s + 10] ^ e[s + 20] ^ e[s + 30] ^ e[s + 40];
for (let s = 0; s < 10; s += 2) {
const a = (s + 8) % 10, h = (s + 2) % 10, c = r[h], l = r[h + 1], u = Fe(c, l, 1) ^ r[a], w = Ge(c, l, 1) ^ r[a + 1];
for (let g = 0; g < 50; g += 10)
e[s + g] ^= u, e[s + g + 1] ^= w;
}
let i = e[2], o = e[3];
for (let s = 0; s < 24; s++) {
const a = ut[s], h = Fe(i, o, a), c = Ge(i, o, a), l = lt[s];
i = e[l], o = e[l + 1], e[l] = h, e[l + 1] = c;
}
for (let s = 0; s < 50; s += 10) {
for (let a = 0; a < 10; a++)
r[a] = e[s + a];
for (let a = 0; a < 10; a++)
e[s + a] ^= ~r[(a + 2) % 10] & r[(a + 4) % 10];
}
e[0] ^= _r[n], e[1] ^= Zr[n];
}
ct(r);
}
class ze extends Tr {
// NOTE: we accept arguments in bytes instead of bits here.
constructor(t, r, n, i = !1, o = 24) {
if (super(), this.pos = 0, this.posOut = 0, this.finished = !1, this.destroyed = !1, this.enableXOF = !1, this.blockLen = t, this.suffix = r, this.outputLen = n, this.enableXOF = i, this.rounds = o, _e(n), !(0 < t && t < 200))
throw new Error("only keccak-f1600 function is supported");
this.state = new Uint8Array(200), this.state32 = br(this.state);
}
clone() {
return this._cloneInto();
}
keccak() {
We(this.state32), Wr(this.state32, this.rounds), We(this.state32), this.posOut = 0, this.pos = 0;
}
update(t) {
Ze(this), t = ht(t), ie(t);
const { blockLen: r, state: n } = this, i = t.length;
for (let o = 0; o < i; ) {
const s = Math.min(r - this.pos, i - o);
for (let a = 0; a < s; a++)
n[this.pos++] ^= t[o++];
this.pos === r && this.keccak();
}
return this;
}
finish() {
if (this.finished)
return;
this.finished = !0;
const { state: t, suffix: r, pos: n, blockLen: i } = this;
t[n] ^= r, r & 128 && n === i - 1 && this.keccak(), t[i - 1] ^= 128, this.keccak();
}
writeInto(t) {
Ze(this, !1), ie(t), this.finish();
const r = this.state, { blockLen: n } = this;
for (let i = 0, o = t.length; i < o; ) {
this.posOut >= n && this.keccak();
const s = Math.min(n - this.posOut, o - i);
t.set(r.subarray(this.posOut, this.posOut + s), i), this.posOut += s, i += s;
}
return t;
}
xofInto(t) {
if (!this.enableXOF)
throw new Error("XOF is not possible for this instance");
return this.writeInto(t);
}
xof(t) {
return _e(t), this.xofInto(new Uint8Array(t));
}
digestInto(t) {
if (Dr(t, this), this.finished)
throw new Error("digest() was already called");
return this.writeInto(t), this.destroy(), t;
}
digest() {
return this.digestInto(new Uint8Array(this.outputLen));
}
destroy() {
this.destroyed = !0, ct(this.state);
}
_cloneInto(t) {
const { blockLen: r, suffix: n, outputLen: i, rounds: o, enableXOF: s } = this;
return t || (t = new ze(r, n, i, s, o)), t.state32.set(this.state32), t.pos = this.pos, t.posOut = this.posOut, t.finished = this.finished, t.rounds = o, t.suffix = n, t.outputLen = i, t.enableXOF = s, t.destroyed = this.destroyed, t;
}
}
const Vr = (e, t, r) => Sr(() => new ze(t, e, r)), Fr = Vr(1, 136, 256 / 8);
let gt = !1;
const yt = function(e) {
return Fr(e);
};
let ft = yt;
function K(e) {
const t = ke(e, "data");
return Ar(ft(t));
}
K._ = yt;
K.lock = function() {
gt = !0;
};
K.register = function(e) {
if (gt)
throw new TypeError("keccak256 is locked");
ft = e;
};
Object.freeze(K);
const Gr = BigInt(0), Hr = BigInt(36);
function He(e) {
e = e.toLowerCase();
const t = e.substring(2).split(""), r = new Uint8Array(40);
for (let i = 0; i < 40; i++)
r[i] = t[i].charCodeAt(0);
const n = ke(K(r));
for (let i = 0; i < 40; i += 2)
n[i >> 1] >> 4 >= 8 && (t[i] = t[i].toUpperCase()), (n[i >> 1] & 15) >= 8 && (t[i + 1] = t[i + 1].toUpperCase());
return "0x" + t.join("");
}
const ve = {};
for (let e = 0; e < 10; e++)
ve[String(e)] = String(e);
for (let e = 0; e < 26; e++)
ve[String.fromCharCode(65 + e)] = String(10 + e);
const Je = 15;
function Jr(e) {
e = e.toUpperCase(), e = e.substring(4) + e.substring(0, 2) + "00";
let t = e.split("").map((n) => ve[n]).join("");
for (; t.length >= Je; ) {
let n = t.substring(0, Je);
t = parseInt(n, 10) % 97 + t.substring(n.length);
}
let r = String(98 - parseInt(t, 10) % 97);
for (; r.length < 2; )
r = "0" + r;
return r;
}
const Xr = function() {
const e = {};
for (let t = 0; t < 36; t++) {
const r = "0123456789abcdefghijklmnopqrstuvwxyz"[t];
e[r] = BigInt(t);
}
return e;
}();
function qr(e) {
e = e.toLowerCase();
let t = Gr;
for (let r = 0; r < e.length; r++)
t = t * Hr + Xr[e[r]];
return t;
}
function x(e) {
if (F(typeof e == "string", "invalid address", "address", e), e.match(/^(0x)?[0-9a-fA-F]{40}$/)) {
e.startsWith("0x") || (e = "0x" + e);
const t = He(e);
return F(!e.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || t === e, "bad address checksum", "address", e), t;
}
if (e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {
F(e.substring(2, 4) === Jr(e), "bad icap checksum", "address", e);
let t = qr(e.substring(4)).toString(16);
for (; t.length < 40; )
t = "0" + t;
return He("0x" + t);
}
F(!1, "invalid address", "address", e);
}
class Kr {
constructor() {
d(this, "type", "argent");
d(this, "platform", "starknet");
d(this, "wallet");
d(this, "account");
d(this, "connectedAccounts", []);
}
isAvailable() {
return typeof window < "u" && !!window.starknet_argentX;
}
getInfo() {
const t = this.isAvailable();
return {
type: this.type,
available: t,
version: t ? window.starknet_argentX?.version || "Unknown" : void 0,
chainId: t ? window.starknet_argentX?.chainId : void 0,
name: "Argent",
platform: this.platform
};
}
async connect() {
if (this.account)
return { success: !0, wallet: this.type, account: this.account };
try {
if (!this.isAvailable())
throw new Error("Argent is not available");
const t = window.starknet_argentX;
if (!t)
throw new Error("No wallet found");
const r = await t.request({
type: "wallet_requestAccounts",
params: { silent_mode: !1 }
});
if (!r || r.length === 0)
throw new Error("No accounts found");
return this.wallet = t, this.account = r[0], this.connectedAccounts = r, { success: !0, wallet: this.type, account: this.account };
} catch (t) {
return console.error("Error connecting to Argent:", t), {
success: !1,
wallet: this.type,
error: t.message || "Unknown error"
};
}
}
getConnectedAccounts() {
return this.connectedAccounts;
}
async signTypedData(t) {
try {
if (!this.isAvailable() || !this.wallet)
throw new Error("Argent is not connected");
const r = await this.wallet.request({
type: "wallet_signTypedData",
params: t
});
return { success: !0, wallet: this.type, result: r };
} catch (r) {
return console.error("Error signing typed data with Argent:", r), {
success: !1,
wallet: this.type,
error: r.message || "Unknown error"
};
}
}
async sendTransaction(t) {
if (!this.wallet)
throw new Error("No wallet found");
try {
const r = await this.wallet.request({
type: "wallet_addInvokeTransaction",
params: {
calls: t
}
});
return {
success: !0,
wallet: this.type,
result: r
};
} catch (r) {
return console.error("Error sending transaction with Argent:", r), {
success: !1,
wallet: this.type,
error: r.message || "Unknown error"
};
}
}
async switchChain(t) {
if (!this.wallet)
throw new Error("No wallet found");
return await this.wallet.request({
type: "wallet_switchStarknetChain",
params: {
chainId: t
}
});
}
async getBalance(t) {
try {
if (!this.isAvailable() || !this.wallet)
throw new Error("Argent is not connected");
return {
success: !0,
wallet: this.type,
result: "Implement based on Argent API"
};
} catch (r) {
return console.error("Error getting balance from Argent:", r), {
success: !1,
wallet: this.type,
error: r.message || "Unknown error"
};
}
}
async waitForTransaction(t, r) {
return {
success: !1,
wallet: this.type,
error: "waitForTransaction not supported for Argent wallet"
};
}
}
function en(e) {
if (typeof window > "u")
return;
const t = (r) => e(r.detail);
return window.addEventListener("eip6963:announceProvider", t), window.dispatchEvent(new CustomEvent("eip6963:requestProvider")), () => window.removeEventListener("eip6963:announceProvider", t);
}
function tn() {
const e = /* @__PURE__ */ new Set();
let t = [];
const r = () => en((i) => {
t.some(({ info: o }) => o.uuid === i.info.uuid) || (t = [...t, i], e.forEach((o) => o(t, { added: [i] })));
});
let n = r();
return {
_listeners() {
return e;
},
clear() {
e.forEach((i) => i([], { removed: [...t] })), t = [];
},
destroy() {
this.clear(), e.clear(), n?.();
},
findProvider({ rdns: i }) {
return t.find((o) => o.info.rdns === i);
},
getProviders() {
return t;
},
reset() {
this.clear(), n?.(), n = r();
},
subscribe(i, { emitImmediately: o } = {}) {
return e.add(i), o && i(t, { added: t }), () => e.delete(i);
}
};
}
const rn = {
"0x1": "ethereum",
// ethereum mainnet
"0xaa36a7": "ethereum",
// ethereum sepolia
"0x14a34": "base",
// base mainnet
"0x2105": "base",
// base sepolia
"0x66eee": "arbitrum",
// arbitrum mainnet
"0xa4b1": "arbitrum",
// arbitrum sepolia
"0xa": "optimism",
// op mainnet
"0xaa37dc": "optimism",
// op sepolia
[Q.StarknetChainId.SN_MAIN]: "starknet",
[Q.StarknetChainId.SN_SEPOLIA]: "starknet"
}, ge = (e) => {
const t = Ot.toHex(e), r = rn[t];
return r || console.warn(`Unknown chain ID: ${t}`), r;
};
class Te {
constructor() {
d(this, "platform");
d(this, "account");
d(this, "store", tn());
d(this, "provider");
d(this, "connectedAccounts", []);
d(this, "initialized", !1);
this.initializeIfAvailable();
}
getProvider() {
return this.provider || (this.provider = this.store.getProviders().find((t) => t.info.rdns === this.rdns)), this.provider;
}
getEthereumProvider() {
const t = this.getProvider();
return t ? t.provider : this.rdns === "io.metamask" && typeof window < "u" && window.ethereum?.isMetaMask ? window.ethereum : null;
}
initializeIfAvailable() {
this.getProvider() && !this.initialized && (this.initialized = !0, this.initializeProvider());
}
initializeProvider() {
const t = this.getProvider();
t && (t.provider.request({
method: "eth_accounts"
}).then((r) => {
this.connectedAccounts = r.map(x), r.length > 0 && (this.account = x(r[0]));
}).catch(console.error), t.provider.request({
method: "eth_chainId"
}).then((r) => {
this.platform = ge(r);
}).catch(console.error), t.provider?.on("chainChanged", (r) => {
this.platform = ge(r);
}), t.provider?.on("accountsChanged", (r) => {
r && (this.connectedAccounts = r.map((n) => x(n)), this.account = r.length > 0 ? x(r[0]) : void 0);
}));
}
isAvailable() {
const t = this.getProvider();
return !t && this.rdns === "io.metamask" && typeof window < "u" ? !!window.ethereum?.isMetaMask : (t && !this.initialized && this.initializeIfAvailable(), typeof window < "u" && !!t);
}
getInfo() {
const t = this.isAvailable();
return {
type: this.type,
available: t,
version: t ? window.ethereum?.version || "Unknown" : void 0,
chainId: t ? window.ethereum?.chainId : void 0,
name: this.displayName,
platform: this.platform,
connectedAccounts: this.connectedAccounts
};
}
getConnectedAccounts() {
return this.connectedAccounts;
}
async connect(t) {
if (t && this.connectedAccounts.includes(x(t)) && (this.account = x(t)), this.account)
return { success: !0, wallet: this.type, account: this.account };
try {
if (!this.isAvailable())
throw new Error(`${this.displayName} is not available`);
let r;
const n = this.getProvider();
if (n ? r = n.provider : this.rdns === "io.metamask" && window.ethereum?.isMetaMask && (r = window.ethereum), !r)
throw new Error(`${this.displayName} provider not found`);
const i = await r.request({
method: "eth_requestAccounts"
});
if (i && i.length > 0)
return this.account = x(i[0]), this.connectedAccounts = i.map(x), !n && this.rdns === "io.metamask" && (this.provider = {
info: {
uuid: "metamask-fallback",
name: "MetaMask",
icon: "data:image/svg+xml;base64,",
rdns: "io.metamask"
},
provider: r
}, this.initializeIfAvailable()), { success: !0, wallet: this.type, account: this.account };
throw new Error("No accounts found");
} catch (r) {
return console.error(`Error connecting to ${this.displayName}:`, r), {
success: !1,
wallet: this.type,
error: r.message || "Unknown error"
};
}
}
async signTransaction(t) {
try {
if (!this.isAvailable() || !this.account)
throw new Error(`${this.displayName} is not connected`);
const r = this.getEthereumProvider();
if (!r)
throw new Error(`${this.displayName} is not connected`);
const n = await r.request({
method: "eth_sendTransaction",
params: [t]
});
return { success: !0, wallet: this.type, result: n };
} catch (r) {
return console.error(
`Error signing transaction with ${this.displayName}:`,
r
), {
success: !1,
wallet: this.type,
error: r.message || "Unknown error"
};
}
}
async signMessage(t, r) {
try {
if (!this.isAvailable() || !this.account)
throw new Error(`${this.displayName} is not connected`);
const n = this.getEthereumProvider();
if (!n)
throw new Error(`${this.displayName} provider not found`);
const i = await n.request({
method: "personal_sign",
params: [t, r || this.account]
});
return { success: !0, wallet: this.type, result: i };
} catch (n) {
return console.error(`Error signing message with ${this.displayName}:`, n), {
success: !1,
wallet: this.type,
error: n.message || "Unknown error"
};
}
}
async signTypedData(t) {
try {
if (!this.isAvailable() || !this.account)
throw new Error(`${this.displayName} is not connected`);
const r = this.getEthereumProvider();
if (!r)
throw new Error(`${this.displayName} is not connected`);
const n = await r.request({
method: "eth_signTypedData_v4",
params: [this.account, JSON.stringify(t)]
});
return { success: !0, wallet: this.type, result: n };
} catch (r) {
return console.error(
`Error signing typed data with ${this.displayName}:`,
r
), {
success: !1,
wallet: this.type,
error: r.message || "Unknown error"
};
}
}
async sendTransaction(t) {
try {
if (!this.isAvailable() || !this.account)
throw new Error(`${this.displayName} is not connected`);
const r = this.getEthereumProvider();
if (!r)
throw new Error(`${this.displayName} is not connected`);
const n = await r.request({
method: "eth_sendTransaction",
params: [t]
});
return { success: !0, wallet: this.type, result: n };
} catch (r) {
return console.error(
`Error sending transaction with ${this.displayName}:`,
r
), {
success: !1,
wallet: this.type,
error: r.message || "Unknown error"
};
}
}
async switchChain(t) {
try {
if (!this.isAvailable())
throw new Error(`${this.displayName} is not available`);
const r = this.getEthereumProvider();
if (!r)
throw new Error(`${this.displayName} is not connected`);
try {
return await r.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: t }]
}), this.platform = ge(t), !0;
} catch (n) {
throw n.code === 4902 && console.warn(`Chain not added to ${this.displayName}`), n;
}
} catch (r) {
return console.error(`Error switching chain for ${this.displayName}:`, r), !1;
}
}
async getBalance(t) {
try {
if (!this.isAvailable() || !this.account)
throw new Error(`${this.displayName} is not connected`);
if (t)
return {
success: !1,
wallet: this.type,
error: "Not implemented for ERC20"
};
{
const r = this.getEthereumProvider();
if (!r)
throw new Error(`${this.displayName} is not connected`);
const n = await r.request({
method: "eth_getBalance",
params: [this.account, "latest"]
});
return { success: !0, wallet: this.type, result: n };
}
} catch (r) {
return console.error(`Error getting balance from ${this.displayName}:`, r), {
success: !1,
wallet: this.type,
error: r.message || "Unknown error"
};
}
}
async waitForTransaction(t, r = 6e4) {
try {
if (!this.isAvailable())
throw new Error(`${this.displayName} is not connected`);
const n = this.getEthereumProvider();
if (!n)
throw new Error(`${this.displayName} is not connected`);
const i = Date.now(), o = 1e3;
for (; Date.now() - i < r; ) {
const s = await n.request({
method: "eth_getTransactionReceipt",
params: [t]
});
if (s)
return {
success: !0,
wallet: this.type,
result: s
};
await new Promise((a) => setTimeout(a, o));
}
throw new Error("Transaction confirmation timed out");
} catch (n) {
return console.error(
`Error waiting for transaction with ${this.displayName}:`,
n
), {
success: !1,
wallet: this.type,
error: n.message || "Unknown error"
};
}
}
}
class nn extends Te {
constructor() {
super(...arguments);
d(this,