const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["chunks/cardano-cip-BB6SQToS.js","chunks/request-fingerprint-BANtRL63.js","chunks/cardano-e2kMgYtl.js","chunks/export-mnemonic-96pGaLLi.js","chunks/_virtual_wxt-plugins-CDnz5Vh6.js"])))=>i.map(i=>d[i]);
import { b as ae, W as He, l as Ce, c as Xe, O as Ve, K as Ye, r as Ke, i as ze, g as B, _ as $e, E as je, a as Qe } from "./chunks/request-fingerprint-BANtRL63.js";
import { i as Ze } from "./chunks/_virtual_wxt-plugins-CDnz5Vh6.js";
let nt, dn, un;
let __tla = (async ()=>{
    function Je(e) {
        return e == null || typeof e == "function" ? {
            main: e
        } : e;
    }
    let et, tt, b, C, de, G, ot, st, Te, ge, me, rt, at, it, ct, ne, T, oe;
    et = {};
    tt = et;
    nt = tt.WXT_ENABLE_CARDANO_CIP_PROVIDER !== "false";
    dn = [];
    un = 100;
    b = 2147483647;
    C = 36;
    de = 1;
    G = 26;
    ot = 38;
    st = 700;
    Te = 72;
    ge = 128;
    me = "-";
    rt = /^xn--/;
    at = /[^\0-\x7F]/;
    it = /[\x2E\u3002\uFF0E\uFF61]/g;
    ct = {
        overflow: "Overflow: input needs wider integers to process",
        "not-basic": "Illegal input >= 0x80 (not a basic code point)",
        "invalid-input": "Invalid input"
    };
    ne = C - de;
    T = Math.floor;
    oe = String.fromCharCode;
    function N(e) {
        throw new RangeError(ct[e]);
    }
    function lt(e, t) {
        const o = [];
        let n = e.length;
        for(; n--;)o[n] = t(e[n]);
        return o;
    }
    function ye(e, t) {
        const o = e.split("@");
        let n = "";
        o.length > 1 && (n = o[0] + "@", e = o[1]), e = e.replace(it, ".");
        const a = e.split("."), u = lt(a, t).join(".");
        return n + u;
    }
    function Ne(e) {
        const t = [];
        let o = 0;
        const n = e.length;
        for(; o < n;){
            const a = e.charCodeAt(o++);
            if (a >= 55296 && a <= 56319 && o < n) {
                const u = e.charCodeAt(o++);
                (u & 64512) == 56320 ? t.push(((a & 1023) << 10) + (u & 1023) + 65536) : (t.push(a), o--);
            } else t.push(a);
        }
        return t;
    }
    const dt = (e)=>String.fromCodePoint(...e), ut = function(e) {
        return e >= 48 && e < 58 ? 26 + (e - 48) : e >= 65 && e < 91 ? e - 65 : e >= 97 && e < 123 ? e - 97 : C;
    }, pe = function(e, t) {
        return e + 22 + 75 * (e < 26) - ((t != 0) << 5);
    }, Re = function(e, t, o) {
        let n = 0;
        for(e = o ? T(e / st) : e >> 1, e += T(e / t); e > ne * G >> 1; n += C)e = T(e / ne);
        return T(n + (ne + 1) * e / (e + ot));
    }, Le = function(e) {
        const t = [], o = e.length;
        let n = 0, a = ge, u = Te, i = e.lastIndexOf(me);
        i < 0 && (i = 0);
        for(let c = 0; c < i; ++c)e.charCodeAt(c) >= 128 && N("not-basic"), t.push(e.charCodeAt(c));
        for(let c = i > 0 ? i + 1 : 0; c < o;){
            const s = n;
            for(let d = 1, l = C;; l += C){
                c >= o && N("invalid-input");
                const p = ut(e.charCodeAt(c++));
                p >= C && N("invalid-input"), p > T((b - n) / d) && N("overflow"), n += p * d;
                const f = l <= u ? de : l >= u + G ? G : l - u;
                if (p < f) break;
                const _ = C - f;
                d > T(b / _) && N("overflow"), d *= _;
            }
            const r = t.length + 1;
            u = Re(n - s, r, s == 0), T(n / r) > b - a && N("overflow"), a += T(n / r), n %= r, t.splice(n++, 0, a);
        }
        return String.fromCodePoint(...t);
    }, ve = function(e) {
        const t = [];
        e = Ne(e);
        const o = e.length;
        let n = ge, a = 0, u = Te;
        for (const s of e)s < 128 && t.push(oe(s));
        const i = t.length;
        let c = i;
        for(i && t.push(me); c < o;){
            let s = b;
            for (const d of e)d >= n && d < s && (s = d);
            const r = c + 1;
            s - n > T((b - a) / r) && N("overflow"), a += (s - n) * r, n = s;
            for (const d of e)if (d < n && ++a > b && N("overflow"), d === n) {
                let l = a;
                for(let p = C;; p += C){
                    const f = p <= u ? de : p >= u + G ? G : p - u;
                    if (l < f) break;
                    const _ = l - f, h = C - f;
                    t.push(oe(pe(f + _ % h, 0))), l = T(_ / h);
                }
                t.push(oe(pe(l, 0))), u = Re(a, r, c === i), a = 0, ++c;
            }
            ++a, ++n;
        }
        return t.join("");
    }, ft = function(e) {
        return ye(e, function(t) {
            return rt.test(t) ? Le(t.slice(4).toLowerCase()) : t;
        });
    }, pt = function(e) {
        return ye(e, function(t) {
            return at.test(t) ? "xn--" + ve(t) : t;
        });
    }, At = {
        version: "2.3.1",
        ucs2: {
            decode: Ne,
            encode: dt
        },
        decode: Le,
        encode: ve,
        toASCII: pt,
        toUnicode: ft
    }, _t = "https://raw.githubusercontent.com/webisoftSoftware/1AM-app-registery/main/phishing-list.json", x = "local:phishingList", se = "local:phishingListTs", Et = 3600 * 1e3, Oe = {
        version: 0,
        blockedDomains: [],
        blockedAddresses: [],
        protectedDomains: [
            "midnight.network",
            "1am.xyz",
            "zkmint.1am.xyz",
            "dominion.fun",
            "proofstation.io",
            "midnightexplorer.com"
        ]
    };
    async function be() {
        try {
            const t = (await chrome.storage.local.get(se))[se];
            if (t && Date.now() - t < Et) {
                const n = (await chrome.storage.local.get(x))[x];
                if (n?.blockedDomains) return re(n);
            }
        } catch  {}
        try {
            const e = await fetch(_t, {
                cache: "no-cache"
            });
            if (e.ok) {
                const t = await e.json();
                if (t?.blockedDomains) return await chrome.storage.local.set({
                    [x]: t,
                    [se]: Date.now()
                }).catch((o)=>{
                    console.warn("[1AM] Failed to cache phishing list:", o);
                }), re(t);
            }
        } catch  {}
        try {
            const t = (await chrome.storage.local.get(x))[x];
            if (t?.blockedDomains) return re(t);
        } catch  {}
        return Oe;
    }
    function re(e) {
        const t = new Set([
            ...Oe.protectedDomains,
            ...e.protectedDomains ?? []
        ]);
        return {
            ...e,
            protectedDomains: Array.from(t)
        };
    }
    const ke = {
        а: "a",
        е: "e",
        о: "o",
        р: "p",
        с: "c",
        у: "y",
        х: "x",
        і: "i",
        ј: "j",
        һ: "h",
        ѕ: "s",
        є: "e",
        ї: "i",
        ґ: "r",
        ь: "b",
        α: "a",
        ε: "e",
        ο: "o",
        ρ: "p",
        κ: "k",
        ν: "v",
        ω: "w",
        ι: "i",
        τ: "t",
        í: "i",
        ì: "i",
        ï: "i",
        î: "i",
        ı: "i",
        á: "a",
        à: "a",
        ä: "a",
        â: "a",
        ã: "a",
        ā: "a",
        é: "e",
        è: "e",
        ë: "e",
        ê: "e",
        ē: "e",
        ó: "o",
        ò: "o",
        ö: "o",
        ô: "o",
        õ: "o",
        ō: "o",
        ú: "u",
        ù: "u",
        ü: "u",
        û: "u",
        ū: "u",
        ý: "y",
        ÿ: "y",
        ń: "n",
        ñ: "n",
        ň: "n",
        ć: "c",
        č: "c",
        ç: "c",
        ś: "s",
        š: "s",
        ź: "z",
        ž: "z",
        ł: "l",
        ĺ: "l",
        ľ: "l",
        đ: "d",
        ď: "d",
        ť: "t",
        ř: "r",
        ａ: "a",
        ｂ: "b",
        ｃ: "c",
        ｄ: "d",
        ｅ: "e",
        ｆ: "f",
        ｇ: "g",
        ｈ: "h",
        ｉ: "i",
        ｊ: "j",
        ｋ: "k",
        ｌ: "l",
        ｍ: "m",
        ｎ: "n",
        ｏ: "o",
        0: "o",
        o: "o",
        1: "l"
    }, ht = /[\u0400-\u04FF]/, Dt = /[\u0370-\u03FF]/, Pt = /[a-zA-Z\u00C0-\u024F]/;
    function It(e) {
        let t = "";
        for (const o of e)t += ke[o] ?? o;
        return t.toLowerCase();
    }
    function wt(e) {
        try {
            return At.toUnicode(e);
        } catch  {
            return e;
        }
    }
    function Ae(e) {
        const t = Pt.test(e), o = ht.test(e), n = Dt.test(e);
        return [
            t,
            o,
            n
        ].filter(Boolean).length > 1;
    }
    function St(e) {
        for (const t of e)if (ke[t] && t.charCodeAt(0) > 127) return !0;
        return !1;
    }
    function Ct(e, t) {
        const o = e.length, n = t.length;
        if (o === 0) return n;
        if (n === 0) return o;
        if (e === t) return 0;
        const a = Array.from({
            length: n + 1
        }, (u, i)=>i);
        for(let u = 1; u <= o; u++){
            let i = u - 1;
            a[0] = u;
            for(let c = 1; c <= n; c++){
                const s = e[u - 1] === t[c - 1] ? 0 : 1, r = Math.min(a[c] + 1, a[c - 1] + 1, i + s);
                i = a[c], a[c] = r;
            }
        }
        return a[n];
    }
    function _e(e) {
        const t = e.split(".");
        return t.length <= 2 ? t[0] : t[t.length - 2];
    }
    function xe(e, t) {
        let o;
        try {
            o = new URL(e).hostname.toLowerCase();
        } catch  {
            return {
                status: "blocked",
                reason: "Invalid origin URL"
            };
        }
        const n = wt(o), a = new Set(t.blockedDomains.map((c)=>c.toLowerCase()));
        if (a.has(o)) return {
            status: "blocked",
            reason: `${o} is a known phishing site`
        };
        const u = o.split(".");
        for(let c = 1; c < u.length - 1; c++){
            const s = u.slice(c).join(".");
            if (a.has(s)) return {
                status: "blocked",
                reason: `${o} is on a known phishing domain`
            };
        }
        if (St(n) || Ae(n)) {
            const c = It(n);
            for (const s of t.protectedDomains){
                const r = s.toLowerCase();
                if (c === r) return {
                    status: "suspicious",
                    reason: `This domain uses characters that impersonate "${s}"`,
                    lookalike: s
                };
                if (c.endsWith("." + r)) return {
                    status: "suspicious",
                    reason: `This domain uses characters that impersonate "${s}"`,
                    lookalike: s
                };
            }
            if (Ae(n)) return {
                status: "suspicious",
                reason: "This domain mixes character sets (e.g. Latin and Cyrillic) — a common phishing technique",
                lookalike: c
            };
        }
        const i = _e(o);
        for (const c of t.protectedDomains){
            const s = _e(c);
            if (s.length < 4 || i === s || o === c) continue;
            const r = Ct(i, s);
            if (r > 0 && r <= 2) {
                const l = o.split(".").slice(-1)[0], p = c.split(".").slice(-1)[0];
                if (l === p || new Set([
                    "com",
                    "net",
                    "org",
                    "io",
                    "xyz",
                    "fun",
                    "app",
                    "network",
                    "fi",
                    "co"
                ]).has(l)) return {
                    status: "suspicious",
                    reason: `"${o}" looks very similar to "${c}" (possible typosquatting)`,
                    lookalike: c
                };
            }
        }
        return {
            status: "clean"
        };
    }
    const Tt = async (e, t)=>{
        if (!e.openPopup) return !1;
        await e.setPopup({
            popup: t
        });
        try {
            return await e.openPopup(), !0;
        } finally{
            try {
                await e.setPopup({
                    popup: ""
                });
            } catch  {}
        }
    };
    function gt(e) {
        return e.walletExists ? e.sidePanelEnabled && e.sidePanelSupported ? "sidepanel" : "popup" : "welcome";
    }
    const mt = "0000000000000000000000000000000000000000000000000000000000000000", Ee = 1000000000000000n, ie = "mn", yt = "shield-addr", Nt = "shield-cpk", Rt = "shield-epk", Lt = 64, vt = new Set([
        "DAPP_GET_SHIELDED_BALANCES",
        "DAPP_GET_UNSHIELDED_BALANCES",
        "DAPP_GET_DUST_BALANCE",
        "DAPP_GET_SHIELDED_ADDRESSES",
        "DAPP_GET_UNSHIELDED_ADDRESS",
        "DAPP_GET_DUST_ADDRESS",
        "DAPP_GET_TX_HISTORY"
    ]);
    function Ot(e) {
        return vt.has(e);
    }
    function m(e) {
        return {
            success: !0,
            data: e
        };
    }
    function W(e, t) {
        return {
            success: !1,
            error: {
                code: e,
                reason: t
            }
        };
    }
    function he(e, t = 0n) {
        if (typeof e != "string" || !/^-?\d+$/.test(e)) return t;
        try {
            return BigInt(e);
        } catch  {
            return t;
        }
    }
    function bt(e) {
        return e === "FAILURE" ? {
            status: "discarded"
        } : e === "SUCCESS" || e === "PARTIAL_SUCCESS" ? {
            status: "finalized",
            executionStatus: {}
        } : {
            status: "pending"
        };
    }
    function kt(e, t) {
        return t === "mainnet" ? `${ie}_${e}` : `${ie}_${e}_${t}`;
    }
    function De(e, t, o) {
        return ae.encode(kt(e, t), ae.toWords(o), !1);
    }
    function xt(e, t) {
        const o = ae.decodeToBytes(e), [n, a, u] = o.prefix.split("_");
        if (n !== ie || a !== yt || u !== (t === "mainnet" ? void 0 : t)) throw new Error("Shielded address prefix mismatch");
        if (o.bytes.length !== Lt) throw new Error("Shielded address bytes invalid");
        const c = o.bytes.subarray(0, 32), s = o.bytes.subarray(32, 64);
        return {
            shieldedCoinPublicKey: De(Nt, t, c),
            shieldedEncryptionPublicKey: De(Rt, t, s)
        };
    }
    function Mt(e) {
        const { type: t, payload: o, state: n, networkId: a, dustSponsorship: u } = e;
        switch(t){
            case "DAPP_GET_SHIELDED_BALANCES":
                return m({
                    ...n.shieldedBalances
                });
            case "DAPP_GET_UNSHIELDED_BALANCES":
                return m({
                    ...n.unshieldedBalances
                });
            case "DAPP_GET_DUST_BALANCE":
                {
                    const i = he(n.dustBalance), c = he(n.unshieldedBalances[mt] ?? "0");
                    return m(u && i === 0n ? {
                        cap: Ee.toString(),
                        balance: Ee.toString()
                    } : {
                        cap: c.toString(),
                        balance: i.toString()
                    });
                }
            case "DAPP_GET_SHIELDED_ADDRESSES":
                {
                    if (!n.shieldedAddress) return W("InternalError", "Wallet is syncing — shielded address not yet available");
                    try {
                        const { shieldedCoinPublicKey: i, shieldedEncryptionPublicKey: c } = xt(n.shieldedAddress, a);
                        return m({
                            shieldedAddress: n.shieldedAddress,
                            shieldedCoinPublicKey: i,
                            shieldedEncryptionPublicKey: c
                        });
                    } catch  {
                        return W("InternalError", "Shielded address cache is invalid");
                    }
                }
            case "DAPP_GET_UNSHIELDED_ADDRESS":
                return n.unshieldedAddress ? m({
                    unshieldedAddress: n.unshieldedAddress
                }) : W("InternalError", "Wallet is syncing — unshielded address not yet available");
            case "DAPP_GET_DUST_ADDRESS":
                return n.dustAddress ? m({
                    dustAddress: n.dustAddress
                }) : W("InternalError", "Wallet is syncing — dust address not yet available");
            case "DAPP_GET_TX_HISTORY":
                {
                    const i = o ?? {}, c = Math.max(Number(i.pageNumber) || 1, 1), s = Math.min(Math.max(Number(i.pageSize) || 10, 1), 100), r = (c - 1) * s, d = [
                        ...n.transactions
                    ].sort((l, p)=>p.timestamp - l.timestamp).slice(r, r + s).map((l)=>({
                            txHash: l.hash,
                            txStatus: bt(l.status)
                        }));
                    return m(d);
                }
        }
    }
    let X = null;
    async function Me() {
        return X || (X = await be()), X;
    }
    setInterval(()=>{
        be().then((e)=>{
            X = e;
        }).catch((e)=>{
            console.warn("[1AM Background] Failed to refresh phishing list:", e);
        });
    }, 3600 * 1e3);
    const Ue = 100, E = new Map, P = new Map;
    async function $() {
        try {
            const e = Array.from(E.entries());
            await chrome.storage.session.set({
                _connectedDApps: e
            });
        } catch (e) {
            console.warn("[1AM Background] Failed to persist connected DApps:", e);
        }
    }
    async function Ut() {
        try {
            const t = (await chrome.storage.session.get("_connectedDApps"))._connectedDApps;
            t && t.forEach(([o, n])=>E.set(o, n));
        } catch (e) {
            console.warn("[1AM Background] Failed to restore connected DApps:", e);
        }
    }
    async function M() {
        try {
            const e = Array.from(P.entries());
            await chrome.storage.session.set({
                _connectedCardanoDApps: e
            });
        } catch (e) {
            console.warn("[1AM Background] Failed to persist connected Cardano DApps:", e);
        }
    }
    async function Gt() {
        try {
            const t = (await chrome.storage.session.get("_connectedCardanoDApps"))._connectedCardanoDApps;
            t && t.forEach(([o, n])=>P.set(o, n));
        } catch (e) {
            console.warn("[1AM Background] Failed to restore connected Cardano DApps:", e);
        }
    }
    const S = new Map, Bt = 10, y = new Map, qt = 1e4, Wt = 20, F = new Map;
    function V(e) {
        const t = Date.now(), n = (F.get(e) || []).filter((a)=>t - a < qt);
        return n.length === 0 && F.delete(e), n.length >= Wt ? (F.set(e, n), !0) : (n.push(t), F.set(e, n), !1);
    }
    const U = new Set, Ft = 300 * 1e3, Ge = new Set([
        "DAPP_MAKE_TRANSFER",
        "DAPP_BALANCE_UNSEALED_TX",
        "DAPP_BALANCE_SEALED_TX",
        "DAPP_SUBMIT_TRANSACTION"
    ]), ce = 6e4, R = new Map;
    function Be(e, t, o) {
        return Qe(e, t, o, 512);
    }
    async function qe() {
        try {
            const e = Array.from(R.entries());
            await chrome.storage.session.set({
                _payloadFps: e
            });
        } catch (e) {
            console.warn("[1AM Background] Failed to persist payload fingerprints:", e);
        }
    }
    async function Ht() {
        try {
            const t = (await chrome.storage.session.get("_payloadFps"))._payloadFps;
            if (t) {
                const o = Date.now();
                for (const [n, a] of t)o - a < ce && R.set(n, a);
            }
        } catch (e) {
            console.warn("[1AM Background] Failed to restore payload fingerprints:", e);
        }
    }
    function Xt(e, t, o) {
        if (!Ge.has(t)) return !0;
        const n = Date.now(), a = Be(e, t, o), u = R.get(a);
        if (u && n - u < ce) return !1;
        if (R.set(a, n), qe(), R.size > 50) for (const [i, c] of R)n - c > ce && R.delete(i);
        return !0;
    }
    function Vt(e, t, o) {
        Ge.has(t) && (R.delete(Be(e, t, o)), qe());
    }
    async function Pe() {
        try {
            const e = Array.from(U);
            await chrome.storage.session.set({
                _replayIds: e
            });
        } catch (e) {
            console.warn("[1AM] Failed to persist replay IDs:", e);
        }
    }
    async function Yt() {
        try {
            const t = (await chrome.storage.session.get("_replayIds"))._replayIds;
            t && t.forEach((o)=>U.add(o));
        } catch (e) {
            console.warn("[1AM] Failed to load replay IDs:", e);
        }
    }
    let g = null, Y = !1, K = null;
    const j = [], Q = [], Z = [];
    function L(e, t) {
        const o = e.indexOf(t);
        o >= 0 && e.splice(o, 1);
    }
    async function Kt(e) {
        const t = e.sender?.tab?.id, o = e.sender?.tab?.windowId;
        if (typeof t == "number") {
            try {
                const [n] = await chrome.tabs.query({
                    active: !0,
                    lastFocusedWindow: !0
                });
                n?.id != null && n.id !== t && (K = n.id);
            } catch  {}
            try {
                await chrome.tabs.update(t, {
                    active: !0
                });
            } catch  {}
        }
        if (typeof o == "number") try {
            await chrome.windows.update(o, {
                focused: !0
            });
        } catch  {}
    }
    function ue(e) {
        for (const t of j)try {
            return t.postMessage(e), !0;
        } catch  {
            L(j, t);
        }
        for (const t of Z)try {
            return t.postMessage(e), !0;
        } catch  {
            L(Z, t);
        }
        for (const t of Q)try {
            return t.postMessage(e), Kt(t), !0;
        } catch  {
            L(Q, t);
        }
        return !1;
    }
    async function Ie(e, t) {
        let o = 50;
        for(let n = 0; n < 10; n++){
            if (ue(e)) {
                const a = I.findIndex((u)=>u.requestId === t);
                a >= 0 && I.splice(a, 1);
                return;
            }
            await new Promise((a)=>setTimeout(a, o)), o = Math.min(o * 2, 800);
        }
    }
    const I = [];
    async function J() {
        const e = await B(), t = je[e.environment];
        return {
            networkId: t.networkId,
            configuration: {
                indexerUri: t.indexerHttpUrl,
                indexerWsUri: t.indexerWsUrl,
                proverServerUri: e.proofServerUrl,
                substrateNodeUri: t.nodeUrl,
                networkId: t.networkId
            }
        };
    }
    async function fe() {
        return new Promise((e)=>{
            chrome.storage.local.get("encryptedVault", (t)=>{
                const o = t?.encryptedVault;
                e(o?.version === 1 || o?.version === 2);
            });
        });
    }
    async function zt() {
        const e = chrome.runtime.getURL("/fullpage.html?mode=welcome"), t = await chrome.tabs.query({
            url: chrome.runtime.getURL("/fullpage.html*")
        });
        if (t.length > 0 && t[0].id != null) {
            await chrome.tabs.update(t[0].id, {
                active: !0
            }), t[0].windowId != null && await chrome.windows.update(t[0].windowId, {
                focused: !0
            });
            return;
        }
        await chrome.tabs.create({
            url: e
        });
    }
    async function We() {
        try {
            if (await Tt(chrome.action, "popup.html")) return;
        } catch  {}
        await chrome.windows.create({
            url: chrome.runtime.getURL("/popup.html"),
            type: "popup",
            width: 400,
            height: 640,
            focused: !0
        });
    }
    async function $t(e) {
        const t = await fe(), o = t ? await B() : null, n = gt({
            walletExists: t,
            sidePanelEnabled: !!o?.sidePanelEnabled,
            sidePanelSupported: !!chrome.sidePanel
        });
        if (await le(), n === "welcome") {
            await zt();
            return;
        }
        n !== "sidepanel" && await We();
    }
    async function le() {
        const e = await fe(), t = e ? await B() : null, o = e && !!t?.sidePanelEnabled && !!chrome.sidePanel;
        try {
            await chrome.action.setPopup({
                popup: ""
            }), chrome.sidePanel && (await chrome.sidePanel.setPanelBehavior({
                openPanelOnActionClick: o
            }), o ? await chrome.sidePanel.setOptions({
                path: "sidepanel.html",
                enabled: !0
            }) : await chrome.sidePanel.setOptions({
                enabled: !1
            })), !e && chrome.sidePanel && await chrome.sidePanel.setOptions({
                enabled: !1
            });
        } catch (n) {
            console.error("[1AM Background] sidePanel config error:", n);
        }
    }
    const jt = Je({
        type: "module",
        main () {
            chrome.storage.session?.setAccessLevel?.({
                accessLevel: "TRUSTED_CONTEXTS"
            }), Yt(), Ht(), Ut(), Gt(), le(), chrome.action.onClicked.addListener((s)=>{
                $t().catch((r)=>{
                    console.error("[1AM Background] Failed to open wallet action:", r);
                });
            });
            const e = [];
            let t = null, o = null;
            const n = [], a = [], u = 25e4;
            chrome.runtime.onConnect.addListener((s)=>{
                if (s.name === "wallet-ui-popup") {
                    if (!s.sender?.url?.startsWith(i)) {
                        s.disconnect();
                        return;
                    }
                    j.push(s), s.onDisconnect.addListener(()=>L(j, s)), z();
                } else if (s.name === "wallet-ui-sidepanel") {
                    if (!s.sender?.url?.startsWith(i)) {
                        s.disconnect();
                        return;
                    }
                    Z.push(s), s.onDisconnect.addListener(()=>L(Z, s)), z();
                } else if (s.name === "wallet-ui-fullpage") {
                    if (!s.sender?.url?.startsWith(i)) {
                        s.disconnect();
                        return;
                    }
                    Q.push(s), s.onDisconnect.addListener(()=>L(Q, s)), z();
                } else if (s.name === He) {
                    if (!s.sender?.url?.startsWith(i)) {
                        s.disconnect();
                        return;
                    }
                    e.push(s), s.onDisconnect.addListener(()=>L(e, s)), Ce().then((r)=>{
                        if (r) try {
                            s.postMessage({
                                type: "WALLET_STATE_UPDATE",
                                state: r
                            });
                        } catch  {}
                    }), s.onMessage.addListener((r)=>{
                        if (r.type === "CMD_WALLET_STATE_BROADCAST") {
                            const d = r.state;
                            d.timestamp = Date.now(), Xe(d);
                            for (const l of e)if (l !== s) try {
                                l.postMessage({
                                    type: "WALLET_STATE_UPDATE",
                                    state: d
                                });
                            } catch  {}
                        }
                    });
                } else if (s.name === Ve) {
                    if (!s.sender?.url?.startsWith(i)) {
                        s.disconnect();
                        return;
                    }
                    s.onMessage.addListener((r)=>{
                        r.type === "OWNERSHIP_REQUEST" && (t ? (n.push({
                            port: s,
                            contextId: r.contextId
                        }), s.postMessage({
                            type: "OWNERSHIP_GRANT",
                            role: "secondary",
                            primaryContextId: t
                        })) : (t = r.contextId, o = s, s.postMessage({
                            type: "OWNERSHIP_GRANT",
                            role: "primary",
                            primaryContextId: null
                        })));
                    }), s.onDisconnect.addListener(()=>{
                        if (o === s) {
                            t = null, o = null;
                            const r = n.shift();
                            if (r) {
                                t = r.contextId, o = r.port;
                                try {
                                    r.port.postMessage({
                                        type: "OWNERSHIP_REVOKE",
                                        newPrimaryContextId: r.contextId
                                    });
                                } catch  {}
                            }
                        } else {
                            const r = n.findIndex((d)=>d.port === s);
                            r >= 0 && n.splice(r, 1);
                        }
                    });
                } else if (s.name === Ye) {
                    if (!s.sender?.url?.startsWith(i)) {
                        s.disconnect();
                        return;
                    }
                    a.push(s);
                    const r = setTimeout(()=>{
                        try {
                            s.disconnect();
                        } catch  {}
                    }, u);
                    s.onDisconnect.addListener(()=>{
                        clearTimeout(r), L(a, s);
                    });
                }
            });
            const i = chrome.runtime.getURL("");
            function c(s) {
                return !!s.url && s.url.startsWith(i);
            }
            chrome.runtime.onMessage.addListener((s, r, d)=>{
                if (s.type === "SIDE_PANEL_SETTING_CHANGED") return c(r) && (le(), d({
                    success: !0
                })), !1;
                if (s.type === "WALLET_TAB_READY") return c(r) && (g = r.tab?.id || null, Y = !1, Qt(), d({
                    success: !0
                })), !1;
                if (s.type === "WALLET_RESPONSE" && "requestId" in s) {
                    if (!c(r)) return !1;
                    if (Zt(s), K != null && r.tab?.url?.includes("/fullpage.html")) {
                        const l = K;
                        K = null, chrome.tabs.update(l, {
                            active: !0
                        }).catch(()=>{});
                    }
                    return d({
                        success: !0
                    }), !1;
                }
                if (s.type === "GET_PENDING_APPROVAL" && "requestId" in s) {
                    if (!c(r)) return !1;
                    const l = S.get(s.requestId ?? "");
                    return !l || l.responseToken !== s.responseToken ? (d({
                        success: !1
                    }), !1) : (d({
                        success: !0,
                        approval: {
                            requestId: s.requestId,
                            responseToken: l.responseToken,
                            type: l.messageType,
                            origin: l.origin
                        }
                    }), !1);
                }
                if ("origin" in s) {
                    const l = s;
                    if (r.frameId !== void 0 && r.frameId !== 0) return d(A("InvalidRequest", "Requests from iframes are not allowed")), !1;
                    if (!r.url) return d(A("InvalidRequest", "Cannot verify sender")), !1;
                    if (new URL(r.url).origin !== l.origin) return d(A("InvalidRequest", "Origin mismatch")), !1;
                    const _ = new Set([
                        "DAPP_PROVING_PROVE",
                        "DAPP_PROVING_CHECK",
                        "CARDANO_CIP_SIGN_TX",
                        "CARDANO_CIP_SUBMIT_TX"
                    ]).has(l.type) ? 16 * 1024 * 1024 : 512 * 1024;
                    try {
                        if (l.payload && JSON.stringify(l.payload).length > _) return d(A("InvalidRequest", "Payload too large")), !1;
                    } catch  {
                        return d(A("InvalidRequest", "Invalid payload")), !1;
                    }
                    return tn(l).then((h)=>{
                        d(h);
                    }).catch((h)=>{
                        console.error("[1AM Background] DApp request failed:", h), d(A("InternalError", "Request failed"));
                    }), !0;
                }
                return !1;
            }), chrome.tabs.onRemoved.addListener((s)=>{
                s === g && (g = null);
            });
        }
    });
    async function z() {
        const e = [
            ...I
        ];
        for (const t of e){
            const o = {
                type: "DAPP_REQUEST",
                requestId: t.requestId,
                responseToken: t.responseToken,
                messageType: t.type,
                origin: t.origin,
                payload: t.payload,
                ...t.phishing && t.phishing.status !== "clean" ? {
                    _phishing: t.phishing
                } : {}
            };
            if (ue(o)) {
                const n = I.findIndex((a)=>a.requestId === t.requestId);
                n >= 0 && I.splice(n, 1);
            }
        }
    }
    async function Qt() {
        if (await z(), !(!g || I.length === 0)) for (const e of [
            ...I
        ])try {
            await chrome.tabs.sendMessage(g, {
                type: "DAPP_REQUEST",
                requestId: e.requestId,
                responseToken: e.responseToken,
                messageType: e.type,
                origin: e.origin,
                payload: e.payload,
                ...e.phishing && e.phishing.status !== "clean" ? {
                    _phishing: e.phishing
                } : {}
            });
            const t = I.findIndex((o)=>o.requestId === e.requestId);
            t >= 0 && I.splice(t, 1);
        } catch (t) {
            console.error("[1AM Background] Failed to send queued request:", t);
        }
    }
    function Zt(e) {
        const t = S.get(e.requestId);
        if (t) {
            if (t.responseToken !== e.responseToken) {
                console.warn("[1AM Background] Ignoring wallet response with invalid response token");
                return;
            }
            clearTimeout(t.timeout), S.delete(e.requestId), t.resolve(e.data);
        }
    }
    const Jt = {
        CARDANO_CIP_GET_EXTENSIONS: "getExtensions",
        CARDANO_CIP_GET_NETWORK_ID: "getNetworkId",
        CARDANO_CIP_GET_UTXOS: "getUtxos",
        CARDANO_CIP_GET_COLLATERAL: "getCollateral",
        CARDANO_CIP_GET_BALANCE: "getBalance",
        CARDANO_CIP_GET_USED_ADDRESSES: "getUsedAddresses",
        CARDANO_CIP_GET_UNUSED_ADDRESSES: "getUnusedAddresses",
        CARDANO_CIP_GET_CHANGE_ADDRESS: "getChangeAddress",
        CARDANO_CIP_GET_REWARD_ADDRESSES: "getRewardAddresses",
        CARDANO_CIP_SIGN_TX: "signTx",
        CARDANO_CIP_SIGN_DATA: "signData",
        CARDANO_CIP_SUBMIT_TX: "submitTx"
    };
    function O(e) {
        return k({
            ok: !0,
            result: e
        });
    }
    function w(e) {
        return k({
            ok: !1,
            error: e
        });
    }
    async function en(e, t) {
        const { type: o, origin: n, payload: a } = e;
        if (!nt) return w({
            kind: "APIError",
            code: -3,
            info: "Cardano browser-wallet support is disabled in this build."
        });
        const u = await Me(), i = xe(n, u);
        if (i.status === "blocked") return w({
            kind: "APIError",
            code: -3,
            info: i.reason
        });
        if (new Set([
            "CARDANO_CIP_IS_ENABLED",
            "CARDANO_CIP_GET_EXTENSIONS",
            "CARDANO_CIP_GET_NETWORK_ID",
            "CARDANO_CIP_GET_UTXOS",
            "CARDANO_CIP_GET_COLLATERAL",
            "CARDANO_CIP_GET_BALANCE",
            "CARDANO_CIP_GET_USED_ADDRESSES",
            "CARDANO_CIP_GET_UNUSED_ADDRESSES",
            "CARDANO_CIP_GET_CHANGE_ADDRESS",
            "CARDANO_CIP_GET_REWARD_ADDRESSES"
        ]).has(o) && V(n)) return w({
            kind: "APIError",
            code: -2,
            info: "Rate limited."
        });
        const { getActiveCardanoWalletContext: s, getCurrentCardanoWalletScope: r, isCardanoConnectionCurrent: d, isCardanoCipConnectionExpired: l, cardanoCipHandleMethod: p } = await $e(async ()=>{
            const { getActiveCardanoWalletContext: D, getCurrentCardanoWalletScope: v, isCardanoConnectionCurrent: te, isCardanoCipConnectionExpired: q, cardanoCipHandleMethod: Fe } = await import("./chunks/cardano-cip-BB6SQToS.js").then(async (m)=>{
                await m.__tla;
                return m;
            });
            return {
                getActiveCardanoWalletContext: D,
                getCurrentCardanoWalletScope: v,
                isCardanoConnectionCurrent: te,
                isCardanoCipConnectionExpired: q,
                cardanoCipHandleMethod: Fe
            };
        }, __vite__mapDeps([0,1,2,3,4]));
        if (o === "CARDANO_CIP_IS_ENABLED") {
            const D = P.get(n);
            if (!D) return O(!1);
            if (l(D)) return P.delete(n), M(), O(!1);
            const v = await r();
            return d(D, v) ? await s() ? O(!0) : O(!1) : (P.delete(n), M(), O(!1));
        }
        if (o === "CARDANO_CIP_ENABLE") {
            if (!await fe()) return w({
                kind: "APIError",
                code: -3,
                info: "1AM does not have a wallet yet."
            });
            const D = await ee(o, n, a, i);
            if (!D.success) return w({
                kind: "APIError",
                code: -3,
                info: D.error?.reason || "User rejected the connection request."
            });
            const v = await r(), te = {
                origin: n,
                connectedAt: Date.now(),
                walletId: v.walletId,
                accountIndex: v.accountIndex,
                network: v.network,
                enabledExtensions: []
            };
            if (P.size >= Ue && !P.has(n)) {
                const q = P.keys().next().value;
                q && P.delete(q);
            }
            return P.set(n, te), M(), O({
                enabledExtensions: []
            });
        }
        const f = P.get(n);
        if (!f) return w({
            kind: "APIError",
            code: -3,
            info: "Not connected to the Cardano wallet. Call enable() first."
        });
        if (l(f)) return P.delete(n), M(), w({
            kind: "APIError",
            code: -3,
            info: "Connection expired — please reconnect."
        });
        const _ = await r();
        if (!d(f, _)) return P.delete(n), M(), w({
            kind: "APIError",
            code: -4,
            info: "Active wallet, account, or network changed — please reconnect."
        });
        if (o === "CARDANO_CIP_SIGN_TX" || o === "CARDANO_CIP_SIGN_DATA") {
            const D = await ee(o, n, a, i);
            if (!D.success) return w({
                kind: "APIError",
                code: -3,
                info: D.error?.reason || "User rejected the signing request."
            });
        }
        const h = Jt[o];
        return h ? k(await p(h, a, f)) : w({
            kind: "APIError",
            code: -1,
            info: `Unsupported Cardano wallet request: ${o}`
        });
    }
    async function tn(e, t) {
        const { type: o, origin: n, payload: a } = e;
        if (o.startsWith("CARDANO_CIP_")) return en(e);
        try {
            const u = await Me(), i = xe(n, u);
            if (i.status === "blocked") return A("InvalidRequest", i.reason);
            switch(o){
                case "DAPP_GET_CONFIGURATION":
                    return V(n) ? A("InternalError", "Rate limited") : on(n);
                case "DAPP_GET_CONNECTION_STATUS":
                    return V(n) ? A("InternalError", "Rate limited") : sn(n);
                case "DAPP_HINT_USAGE":
                    return rn(n, a);
            }
            if (o === "DAPP_CONNECT") {
                const r = await ee(o, n, a, i);
                if (r.success && r.data && r.data.authorized) {
                    const { networkId: d } = await J(), l = Ke(r, d), p = {
                        origin: n,
                        networkId: l,
                        connectedAt: Date.now(),
                        permissions: []
                    };
                    if (E.size >= Ue && !E.has(n)) {
                        const f = E.keys().next().value;
                        f && E.delete(f);
                    }
                    E.set(n, p), $();
                }
                return r;
            }
            if (!new Set([
                "DAPP_GET_SHIELDED_BALANCES",
                "DAPP_GET_UNSHIELDED_BALANCES",
                "DAPP_GET_DUST_BALANCE",
                "DAPP_GET_SHIELDED_ADDRESSES",
                "DAPP_GET_UNSHIELDED_ADDRESS",
                "DAPP_GET_DUST_ADDRESS",
                "DAPP_GET_TX_HISTORY",
                "DAPP_SIGN_DATA",
                "DAPP_MAKE_TRANSFER",
                "DAPP_MAKE_INTENT",
                "DAPP_BALANCE_UNSEALED_TX",
                "DAPP_BALANCE_SEALED_TX",
                "DAPP_SUBMIT_TRANSACTION",
                "DAPP_PROVING_CHECK",
                "DAPP_PROVING_PROVE"
            ]).has(o)) return A("InvalidRequest", "Unknown request type");
            if (new Set([
                "DAPP_GET_SHIELDED_BALANCES",
                "DAPP_GET_UNSHIELDED_BALANCES",
                "DAPP_GET_DUST_BALANCE",
                "DAPP_GET_SHIELDED_ADDRESSES",
                "DAPP_GET_UNSHIELDED_ADDRESS",
                "DAPP_GET_DUST_ADDRESS",
                "DAPP_GET_TX_HISTORY"
            ]).has(o) && V(n)) return A("InternalError", "Rate limited");
            if (Ot(o)) {
                const r = E.get(n);
                if (!r) return A("Disconnected", "Not connected to wallet");
                const { networkId: d } = await J();
                if (r.networkId !== d) return E.delete(n), $(), A("Disconnected", "Network changed — please reconnect");
                const p = (await chrome.storage.local.get("walletMetadata")).walletMetadata, f = p?.wallets?.find((D)=>D.id === p.activeId), _ = await Ce(Number.MAX_SAFE_INTEGER, p?.activeId, f?.activeAccountIndex, d);
                if (!_ || !ze(_, d)) return A("InternalError", "Wallet data unavailable. Open 1AM to refresh wallet state.");
                const h = await B();
                return Mt({
                    type: o,
                    payload: a,
                    state: _,
                    networkId: d,
                    dustSponsorship: h.dustSponsorship
                });
            }
            return ee(o, n, a, i);
        } catch (u) {
            return console.error(`[1AM Background] Error handling ${o}:`, u), A("InternalError", "Request failed");
        }
    }
    async function ee(e, t, o, n) {
        const a = e.startsWith("CARDANO_CIP_");
        if (e !== "DAPP_CONNECT" && !a) {
            const l = E.get(t);
            if (!l) return A("Disconnected", "Not connected to wallet");
            const p = 1440 * 60 * 1e3;
            if (Date.now() - l.connectedAt > p) return E.delete(t), $(), A("Disconnected", "Connection expired — please reconnect");
            const { networkId: f } = await J();
            if (l.networkId !== f) return E.delete(t), $(), A("Disconnected", "Network changed — please reconnect");
        }
        if (!Xt(t, e, o)) return A("InvalidRequest", "Duplicate request — identical transaction already in progress");
        const u = (y.get(t) || 0) + 1;
        if (y.set(t, u), u > Bt) return y.set(t, u - 1), A("InternalError", "Too many pending requests");
        const i = we(), c = we();
        if (U.has(i)) return y.set(t, (y.get(t) || 1) - 1), A("InternalError", "Duplicate request");
        U.add(i), Pe(), setTimeout(()=>{
            U.delete(i), Pe();
        }, Ft);
        const s = ()=>{
            const l = y.get(t) || 1;
            l <= 1 ? y.delete(t) : y.set(t, l - 1);
        }, r = new Promise((l)=>{
            const p = (_)=>{
                s(), Vt(t, e, o), l(_);
            }, f = setTimeout(()=>{
                S.delete(i);
                const _ = I.findIndex((h)=>h.requestId === i);
                _ >= 0 && I.splice(_, 1), p(A("InternalError", "Request timed out"));
            }, 12e4);
            S.set(i, {
                resolve: p,
                reject: ()=>{},
                timeout: f,
                responseToken: c,
                messageType: e,
                origin: t
            });
        }), d = {
            type: "DAPP_REQUEST",
            requestId: i,
            responseToken: c,
            messageType: e,
            origin: t,
            payload: o,
            ...n && n.status !== "clean" ? {
                _phishing: n
            } : {}
        };
        if (!ue(d) && !await nn(d)) {
            if (I.length >= 50) {
                s();
                const f = S.get(i);
                return f && (clearTimeout(f.timeout), S.delete(i)), A("InternalError", "Too many queued requests");
            }
            const p = S.get(i)?.resolve;
            if (p && I.push({
                requestId: i,
                responseToken: c,
                type: e,
                origin: t,
                payload: o,
                phishing: n,
                resolve: p
            }), !Y) {
                Y = !0;
                try {
                    if ((await B()).sidePanelEnabled && chrome.sidePanel) {
                        const [_] = await chrome.tabs.query({
                            active: !0,
                            currentWindow: !0
                        });
                        _?.id && await chrome.sidePanel.open({
                            tabId: _.id
                        }), await Ie(d, i);
                    } else await We(), await Ie(d, i);
                } catch  {
                    try {
                        g = (await chrome.windows.create({
                            url: chrome.runtime.getURL("/popup.html"),
                            type: "popup",
                            width: 400,
                            height: 640,
                            focused: !0
                        }))?.tabs?.[0]?.id ?? null;
                    } catch  {
                        const f = S.get(i);
                        f && (clearTimeout(f.timeout), S.delete(i), f.resolve(A("InternalError", "Open your 1AM wallet to process this request")));
                    }
                } finally{
                    Y = !1;
                }
            }
        }
        return r;
    }
    async function nn(e) {
        if (g) try {
            return await chrome.tabs.sendMessage(g, e), !0;
        } catch  {
            g = null;
        }
        try {
            const t = await chrome.tabs.query({
                url: chrome.runtime.getURL("*")
            });
            for (const o of t)if (o.id) return g = o.id, await chrome.tabs.sendMessage(o.id, e), !0;
            return !1;
        } catch  {
            return !1;
        }
    }
    function we() {
        const e = new Uint8Array(8);
        crypto.getRandomValues(e);
        const t = Array.from(e, (o)=>o.toString(16).padStart(2, "0")).join("");
        return `${Date.now()}-${t}`;
    }
    function k(e) {
        return {
            success: !0,
            data: e
        };
    }
    function A(e, t) {
        return {
            success: !1,
            error: {
                code: e,
                reason: t
            }
        };
    }
    async function on(e) {
        if (!E.has(e)) return A("Disconnected", "Not connected to wallet");
        const { configuration: t } = await J();
        return k(t);
    }
    function sn(e) {
        const t = E.get(e);
        return t ? k({
            status: "connected",
            networkId: t.networkId
        }) : A("Disconnected", "Not connected");
    }
    function rn(e, t) {
        return E.has(e) ? k() : A("Disconnected", "Not connected to wallet");
    }
    function H(e, ...t) {}
    const an = {
        debug: (...e)=>H(console.debug, ...e),
        log: (...e)=>H(console.log, ...e),
        warn: (...e)=>H(console.warn, ...e),
        error: (...e)=>H(console.error, ...e)
    };
    let Se;
    try {
        Ze(), Se = jt.main(), Se instanceof Promise && console.warn("The background's main() function return a promise, but it must be synchronous");
    } catch (e) {
        throw an.error("The background crashed on startup!"), e;
    }
})();
export { nt as C, dn as a, un as b, __tla };
