const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["chunks/cardano_serialization_lib-BCNxyBHd.js","chunks/__vite-plugin-wasm-helper-D7K_KhUE.js","chunks/cardano_message_signing-CcrxYRax.js"])))=>i.map(i=>d[i]);
import { f as k, g as q, _ as P } from "./request-fingerprint-BANtRL63.js";
import { C as T, a as V, b as C, __tla as __tla_0 } from "../background.js";
import { Z as G, $ as F, a0 as z, ac as L, ad as $, ae as X, b as j, af as Z, ag as J, __tla as __tla_1 } from "./cardano-e2kMgYtl.js";
import { extractMnemonic as Q } from "./export-mnemonic-96pGaLLi.js";
import "./_virtual_wxt-plugins-CDnz5Vh6.js";
let Ae, Ce, ve, xe, be, He, Ee, Ke, Ie, Re, Pe, Se, Te, x, ae, ue, de, We, Me;
let __tla = Promise.all([
    (()=>{
        try {
            return __tla_0;
        } catch  {}
    })(),
    (()=>{
        try {
            return __tla_1;
        } catch  {}
    })()
]).then(async ()=>{
    const A = {
        wallets: [
            {
                id: 0,
                name: "Wallet 1",
                accounts: [
                    {
                        index: 0,
                        name: "Account 1"
                    }
                ],
                activeAccountIndex: 0,
                nextAccountIndex: 1
            }
        ],
        activeId: 0,
        nextId: 1,
        walletKind: "password"
    };
    let I = null, v = null;
    function Y() {
        return !I || !v ? null : {
            key: I,
            salt: v
        };
    }
    async function ee() {
        I = null, v = null, await k.removeItem("session:vaultKeyBytes"), await k.removeItem("session:vaultSalt");
    }
    async function te() {
        return await k.getItem("local:encryptedVault");
    }
    async function ne() {
        const e = await k.getItem("local:walletMetadata");
        return e ? {
            ...e,
            wallets: Array.isArray(e.wallets) ? e.wallets : [
                ...A.wallets
            ],
            activeId: typeof e.activeId == "number" ? e.activeId : A.activeId,
            nextId: typeof e.nextId == "number" ? e.nextId : A.nextId,
            walletKind: e.walletKind ?? "password",
            socialAuth: (e.walletKind ?? "password") === "social-web3auth" ? e.socialAuth : void 0
        } : {
            ...A,
            wallets: [
                ...A.wallets
            ]
        };
    }
    async function se() {
        let e = Y();
        if (!e) {
            const n = await k.getItem("session:vaultKeyBytes"), s = await k.getItem("session:vaultSalt");
            if (n && s) {
                const r = await G(n, !0);
                I = r, v = s, e = {
                    key: r,
                    salt: s
                };
            }
        }
        if (!e) return null;
        const t = await te();
        if (!t) return null;
        try {
            let n;
            if (t.version >= 2) {
                const r = F(t.salt), a = new Uint8Array(1 + r.length);
                a[0] = t.version, a.set(r, 1), n = a;
            }
            const s = await z(e.key, t.ciphertext, t.iv, n);
            return JSON.parse(s);
        } catch  {
            return await ee(), null;
        }
    }
    const re = 1440 * 60 * 1e3;
    function _(e) {
        return {
            ok: !0,
            result: e
        };
    }
    function g(e) {
        return {
            ok: !1,
            error: e
        };
    }
    x = function(e, t) {
        return g({
            kind: "APIError",
            code: e,
            info: t
        });
    };
    ae = function() {
        return x(-3, "Cardano browser-wallet support is disabled in this build.");
    };
    We = function(e) {
        return Date.now() - e.connectedAt > re;
    };
    function B(e) {
        const t = e.trim();
        return t.startsWith("0x") || t.startsWith("0X") ? t.slice(2).toLowerCase() : t.toLowerCase();
    }
    function oe(e) {
        return /^[0-9a-fA-F]*$/.test(e) && e.length % 2 === 0;
    }
    function m(e) {
        const t = B(e);
        if (!oe(t)) throw new Error("Invalid hex string");
        const n = new Uint8Array(t.length / 2);
        for(let s = 0; s < t.length; s += 2)n[s / 2] = Number.parseInt(t.slice(s, s + 2), 16);
        return n;
    }
    function w(e) {
        return Array.from(e, (t)=>t.toString(16).padStart(2, "0")).join("");
    }
    async function b() {
        return P(()=>import("./cardano_serialization_lib-BCNxyBHd.js").then(async (m)=>{
                await m.__tla;
                return m;
            }), __vite__mapDeps([0,1]));
    }
    async function ie() {
        return P(()=>import("./cardano_message_signing-CcrxYRax.js").then(async (m)=>{
                await m.__tla;
                return m;
            }), __vite__mapDeps([2,1]));
    }
    function H(e, t) {
        return w(e.Address.from_bech32(t).to_bytes());
    }
    async function ce() {
        const e = await ne(), t = e.wallets.find((n)=>n.id === e.activeId) ?? e.wallets[0];
        return {
            walletId: t?.id ?? 0,
            accountIndex: t?.activeAccountIndex ?? 0
        };
    }
    de = async function() {
        const e = await q(), { walletId: t, accountIndex: n } = await ce();
        return {
            walletId: t,
            accountIndex: n,
            network: e.environment
        };
    };
    ue = async function(e) {
        if (!T) return null;
        const [{ walletId: t, accountIndex: n, network: s }, r, a] = await Promise.all([
            de(),
            se(),
            b()
        ]);
        if (!r) return null;
        const o = Q(r, t), c = await L(o, n, s), y = e?.includeSigningKeys ? await $(o, n) : void 0;
        return {
            walletId: t,
            accountIndex: n,
            network: s,
            addresses: c,
            baseAddressHex: H(a, c.baseAddress),
            changeAddressHex: H(a, c.changeAddress),
            rewardAddressHex: H(a, c.rewardAddress),
            signingKeys: y
        };
    };
    Me = function(e, t) {
        return e.walletId === t.walletId && e.accountIndex === t.accountIndex && e.network === t.network;
    };
    function N(e) {
        e && (e.paymentExtendedPrivateKey.fill(0), e.stakeExtendedPrivateKey.fill(0));
    }
    function U(e) {
        if (e == null) return _(void 0);
        if (!e || typeof e != "object") return g({
            kind: "PaginateError",
            maxSize: C
        });
        const t = e, n = Number(t.page), s = Number(t.limit);
        return !Number.isInteger(n) || !Number.isInteger(s) || n < 0 || s <= 0 || s > C ? g({
            kind: "PaginateError",
            maxSize: C
        }) : _({
            page: n,
            limit: s
        });
    }
    function D(e, t) {
        if (!t) return e;
        const n = t.page * t.limit;
        return e.slice(n, n + t.limit);
    }
    function O(e, t) {
        const n = e.Value.new(e.BigNum.from_str("0")), s = e.MultiAsset.new();
        for (const r of t){
            if (r.unit === "lovelace") {
                n.set_coin(e.BigNum.from_str(r.quantity));
                continue;
            }
            const a = r.unit.slice(0, 56), o = r.unit.slice(56), c = e.ScriptHash.from_bytes(m(a)), y = s.get(c) ?? e.Assets.new();
            y.insert(e.AssetName.new(m(o)), e.BigNum.from_str(r.quantity)), s.insert(c, y);
        }
        return s.len() > 0 && n.set_multiasset(s), n;
    }
    function le(e, t) {
        const n = new Map;
        n.set("lovelace", BigInt(t.coin().to_str()));
        const s = t.multiasset();
        if (!s) return n;
        const r = s.keys();
        for(let a = 0; a < r.len(); a += 1){
            const o = r.get(a), c = s.get(o);
            if (!c) continue;
            const y = c.keys();
            for(let h = 0; h < y.len(); h += 1){
                const u = y.get(h), i = `${o.to_hex()}${w(u.name())}`;
                n.set(i, BigInt(c.get(u)?.to_str() ?? "0"));
            }
        }
        return n;
    }
    function ye(e) {
        const t = new Map;
        for (const n of e)for (const s of n.amount){
            const r = t.get(s.unit) ?? 0n;
            t.set(s.unit, r + BigInt(s.quantity));
        }
        return t;
    }
    function _e(e, t) {
        for (const [n, s] of t)if ((e.get(n) ?? 0n) < s) return !1;
        return !0;
    }
    function W(e, t) {
        if (!t) return e;
        const n = [], s = new Map;
        for (const r of e){
            n.push(r);
            for (const a of r.amount){
                const o = s.get(a.unit) ?? 0n;
                s.set(a.unit, o + BigInt(a.quantity));
            }
            if (_e(s, t)) return n;
        }
        return null;
    }
    function M(e, t) {
        const n = e.TransactionInput.new(e.TransactionHash.from_bytes(m(t.tx_hash)), t.tx_index), s = e.TransactionOutput.new(e.Address.from_bech32(t.address), O(e, t.amount));
        return w(e.TransactionUnspentOutput.new(n, s).to_bytes());
    }
    function fe(e, t) {
        return t.map((n)=>({
                ...n,
                address: e
            }));
    }
    async function K(e) {
        const t = await J(e.addresses.baseAddress, void 0, e.network);
        return fe(e.addresses.baseAddress, t);
    }
    function he(e) {
        return e.map((t)=>({
                txHash: t.tx_hash,
                outputIndex: t.tx_index,
                address: t.address
            }));
    }
    function ge(e, t) {
        const n = t.trim();
        if (!n) throw new Error("Address is required");
        if (n.startsWith("addr") || n.startsWith("stake")) {
            const r = e.Address.from_bech32(n);
            return {
                cslAddress: r,
                addressHex: w(r.to_bytes())
            };
        }
        const s = m(n);
        return {
            cslAddress: e.Address.from_bytes(s),
            addressHex: B(n)
        };
    }
    function pe(e, t) {
        const n = e.RewardAddress.from_address(t);
        if (n) {
            const o = n.payment_cred();
            return o.kind() !== 0 ? null : {
                kind: "reward",
                hash: o.to_keyhash()?.to_hex() ?? ""
            };
        }
        const s = e.BaseAddress.from_address(t);
        if (s) {
            const o = s.payment_cred();
            return o.kind() !== 0 ? null : {
                kind: "payment",
                hash: o.to_keyhash()?.to_hex() ?? ""
            };
        }
        const r = e.EnterpriseAddress.from_address(t);
        if (r) {
            const o = r.payment_cred();
            return o.kind() !== 0 ? null : {
                kind: "payment",
                hash: o.to_keyhash()?.to_hex() ?? ""
            };
        }
        const a = e.PointerAddress.from_address(t);
        if (a) {
            const o = a.payment_cred();
            return o.kind() !== 0 ? null : {
                kind: "payment",
                hash: o.to_keyhash()?.to_hex() ?? ""
            };
        }
        return null;
    }
    function me(e, t, n) {
        if (!t.signingKeys) return g({
            kind: "DataSignError",
            code: 1,
            info: "Cardano signing keys are unavailable for this session."
        });
        const s = e.PublicKey.from_bytes(t.signingKeys.paymentPublicKey).hash().to_hex(), r = e.PublicKey.from_bytes(t.signingKeys.stakePublicKey).hash().to_hex(), a = pe(e, n);
        return a ? a.kind === "reward" ? a.hash !== r ? g({
            kind: "DataSignError",
            code: 1,
            info: "Wallet does not control the requested reward address."
        }) : _({
            keyType: "reward",
            privateKeyBytes: new Uint8Array(t.signingKeys.stakeExtendedPrivateKey),
            publicKeyBytes: t.signingKeys.stakePublicKey
        }) : a.hash !== s ? g({
            kind: "DataSignError",
            code: 1,
            info: "Wallet does not control the requested payment address."
        }) : _({
            keyType: "payment",
            privateKeyBytes: new Uint8Array(t.signingKeys.paymentExtendedPrivateKey),
            publicKeyBytes: t.signingKeys.paymentPublicKey
        }) : g({
            kind: "DataSignError",
            code: 2,
            info: "Address is not a public-key Cardano address."
        });
    }
    function we(e, t) {
        const n = [], s = e.body().inputs();
        for(let u = 0; u < s.len(); u += 1){
            const i = s.get(u), d = i.transaction_id().to_hex(), l = Number(i.index()), f = t.find((p)=>p.txHash === d && p.outputIndex === l);
            f && n.push(f.address);
        }
        const r = e.body(), a = r.certs();
        if (a) for(let u = 0; u < a.len(); u += 1){
            const i = a.get(u);
            switch(i.kind()){
                case 1:
                    {
                        const l = i.as_stake_deregistration()?.stake_credential()?.to_keyhash()?.to_hex();
                        l && n.push(l);
                        break;
                    }
                case 2:
                    {
                        const l = i.as_stake_delegation()?.stake_credential()?.to_keyhash()?.to_hex();
                        l && n.push(l);
                        break;
                    }
                case 3:
                    {
                        const d = i.as_pool_registration()?.pool_params(), l = d?.pool_owners();
                        if (l) for(let p = 0; p < l.len(); p += 1)n.push(l.get(p).to_hex());
                        const f = d?.operator().to_hex();
                        f && n.push(f);
                        break;
                    }
                case 4:
                    {
                        const d = i.as_pool_retirement()?.pool().to_hex();
                        d && n.push(d);
                        break;
                    }
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                case 11:
                    {
                        const d = i.as_unreg_cert?.()?.stake_credential?.()?.to_keyhash?.()?.to_hex?.() ?? i.as_vote_deleg_cert?.()?.stake_credential?.()?.to_keyhash?.()?.to_hex?.() ?? i.as_stake_vote_deleg_cert?.()?.stake_credential?.()?.to_keyhash?.()?.to_hex?.() ?? i.as_stake_reg_deleg_cert?.()?.stake_credential?.()?.to_keyhash?.()?.to_hex?.() ?? i.as_vote_reg_deleg_cert?.()?.stake_credential?.()?.to_keyhash?.()?.to_hex?.() ?? i.as_stake_vote_reg_deleg_cert?.()?.stake_credential?.()?.to_keyhash?.()?.to_hex?.();
                        d && n.push(d);
                        break;
                    }
                case 12:
                    {
                        const d = i.as_auth_committee_hot_cert?.()?.committee_cold_credential?.()?.to_keyhash?.()?.to_hex?.();
                        d && n.push(d);
                        break;
                    }
                case 13:
                    {
                        const d = i.as_resign_committee_cold_cert?.()?.committee_cold_credential?.()?.to_keyhash?.()?.to_hex?.();
                        d && n.push(d);
                        break;
                    }
                case 14:
                case 15:
                case 16:
                    {
                        const d = i.as_reg_drep_cert?.()?.drep_credential?.()?.to_keyhash?.()?.to_hex?.() ?? i.as_unreg_drep_cert?.()?.drep_credential?.()?.to_keyhash?.()?.to_hex?.() ?? i.as_update_drep_cert?.()?.drep_credential?.()?.to_keyhash?.()?.to_hex?.();
                        d && n.push(d);
                        break;
                    }
            }
        }
        const o = r.withdrawals();
        if (o) {
            const u = o.keys();
            for(let i = 0; i < u.len(); i += 1){
                const l = u.get(i).payment().to_keyhash()?.to_hex();
                l && n.push(l);
            }
        }
        const c = e.witness_set().native_scripts();
        if (c) {
            const u = (i)=>{
                for(let d = 0; d < i.len(); d += 1){
                    const l = i.get(d);
                    if (l.kind() === 0) {
                        const f = l.as_script_pubkey?.()?.ed25519_key_hash?.()?.to_hex?.();
                        f && n.push(f);
                        continue;
                    }
                    if (l.kind() === 1) {
                        u(l.as_script_all().native_scripts());
                        continue;
                    }
                    if (l.kind() === 2) {
                        u(l.as_script_any().native_scripts());
                        continue;
                    }
                    l.kind() === 3 && u(l.as_script_n_of_k().native_scripts());
                }
            };
            u(c);
        }
        const y = r.required_signers();
        if (y) for(let u = 0; u < y.len(); u += 1)n.push(y.get(u).to_hex());
        const h = r.collateral();
        if (h) for(let u = 0; u < h.len(); u += 1){
            const i = h.get(u), d = i.transaction_id().to_hex(), l = Number(i.index()), f = t.find((p)=>p.txHash === d && p.outputIndex === l);
            f && n.push(f.address);
        }
        return [
            ...new Set(n)
        ];
    }
    function ke(e, t, n) {
        return e.map((s)=>s === n ? t : s);
    }
    xe = async function(e = V) {
        return _(e);
    };
    be = async function(e) {
        return _(Z(e.network));
    };
    Ae = async function(e) {
        try {
            const t = await b(), n = await K(e), s = ye(n), r = O(t, Array.from(s.entries(), ([a, o])=>({
                    unit: a,
                    quantity: o.toString()
                })));
            return _(w(r.to_bytes()));
        } catch (t) {
            return x(-2, t instanceof Error ? t.message : "Failed to load Cardano balance.");
        }
    };
    Ie = async function(e, t) {
        try {
            const n = await b(), s = U(t?.paginate);
            if (!s.ok) return s;
            const r = await K(e);
            let a = null;
            if (t?.amount) {
                const c = n.Value.from_bytes(m(t.amount));
                a = le(n, c);
            }
            const o = W(r, a);
            return _(o ? D(o, s.result).map((c)=>M(n, c)) : null);
        } catch (n) {
            return x(-1, n instanceof Error ? n.message : "Failed to load Cardano UTxOs.");
        }
    };
    ve = async function(e, t) {
        try {
            const s = (await K(e)).filter((c)=>c.amount.length === 1 && c.amount[0]?.unit === "lovelace");
            if (s.length === 0) return _(null);
            let r = null;
            if (t?.amount != null) {
                const c = (typeof t.amount == "number", BigInt(t.amount));
                r = new Map([
                    [
                        "lovelace",
                        c
                    ]
                ]);
            }
            const a = W(s, r);
            if (!a) return _(null);
            const o = await b();
            return _(a.map((c)=>M(o, c)));
        } catch (n) {
            return x(-1, n instanceof Error ? n.message : "Failed to load Cardano collateral inputs.");
        }
    };
    Ke = async function(e, t) {
        const n = U(t);
        return n.ok ? _(D([
            e.baseAddressHex
        ], n.result)) : n;
    };
    Ee = async function(e) {
        return _(e.changeAddressHex === e.baseAddressHex ? [] : [
            e.changeAddressHex
        ]);
    };
    Ce = async function(e) {
        return _(e.changeAddressHex);
    };
    He = async function(e) {
        return _([
            e.rewardAddressHex
        ]);
    };
    Se = async function(e, t) {
        if (!e.signingKeys) return g({
            kind: "TxSignError",
            code: 1,
            info: "Cardano signing keys are unavailable for this session."
        });
        const { partialSign: n = !1 } = t;
        try {
            const s = await b(), r = s.Transaction.from_bytes(m(t.tx)), a = await K(e), o = he(a), c = s.PrivateKey.from_extended_bytes(new Uint8Array(e.signingKeys.paymentExtendedPrivateKey)), y = s.PrivateKey.from_extended_bytes(new Uint8Array(e.signingKeys.stakeExtendedPrivateKey)), h = c.to_public().hash().to_hex(), u = y.to_public().hash().to_hex(), i = ke(we(r, o), h, e.addresses.baseAddress), d = new Set([
                h,
                u
            ]), l = [
                ...new Set(i)
            ].filter((E)=>d.has(E));
            if (l.length === 0) return c.free(), y.free(), g({
                kind: "TxSignError",
                code: 1,
                info: "Wallet could not sign any key required by this transaction."
            });
            if (!n && l.length !== new Set(i).size) return c.free(), y.free(), g({
                kind: "TxSignError",
                code: 1,
                info: "Wallet cannot fully sign this transaction."
            });
            const f = s.TransactionHash.from_bytes(j(r.body().to_bytes(), {
                dkLen: 32
            })), p = s.TransactionWitnessSet.new(), S = s.Vkeywitnesses.new();
            for (const E of l){
                const R = E === h ? c : y;
                S.add(s.make_vkey_witness(f, R));
            }
            return p.set_vkeys(S), c.free(), y.free(), _(w(p.to_bytes()));
        } catch (s) {
            return g({
                kind: "TxSignError",
                code: 1,
                info: s instanceof Error ? s.message : "Wallet could not sign this transaction."
            });
        } finally{
            N(e.signingKeys);
        }
    };
    Pe = async function(e, t) {
        if (!e.signingKeys) return g({
            kind: "DataSignError",
            code: 1,
            info: "Cardano signing keys are unavailable for this session."
        });
        try {
            const [n, s] = await Promise.all([
                b(),
                ie()
            ]), { cslAddress: r, addressHex: a } = ge(n, t.address), o = me(n, e, r);
            if (!o.ok) return o;
            const c = s.HeaderMap.new();
            c.set_algorithm_id(s.Label.from_algorithm_id(s.AlgorithmId.EdDSA)), c.set_header(s.Label.new_text("address"), s.CBORValue.new_bytes(m(a)));
            const y = s.Headers.new(s.ProtectedHeaderMap.new(c), s.HeaderMap.new()), h = s.COSESign1Builder.new(y, m(t.payload), !1), u = n.PrivateKey.from_extended_bytes(o.result.privateKeyBytes), i = h.make_data_to_sign().to_bytes(), d = u.sign(i).to_bytes(), l = h.build(d), f = s.COSEKey.new(s.Label.from_key_type(s.KeyType.OKP));
            return f.set_algorithm_id(s.Label.from_algorithm_id(s.AlgorithmId.EdDSA)), f.set_header(s.Label.new_int(s.Int.new_negative(s.BigNum.from_str("1"))), s.CBORValue.new_int(s.Int.new_i32(s.CurveType.Ed25519))), f.set_header(s.Label.new_int(s.Int.new_negative(s.BigNum.from_str("2"))), s.CBORValue.new_bytes(o.result.publicKeyBytes)), u.free(), _({
                signature: w(l.to_bytes()),
                key: w(f.to_bytes())
            });
        } catch (n) {
            return g({
                kind: "DataSignError",
                code: 1,
                info: n instanceof Error ? n.message : "Wallet could not sign the requested payload."
            });
        } finally{
            N(e.signingKeys);
        }
    };
    Te = async function(e, t) {
        try {
            const n = await X(t.tx, void 0, e.network);
            return _(n);
        } catch (n) {
            return g({
                kind: "TxSendError",
                code: 2,
                info: n instanceof Error ? n.message : "Wallet could not submit the Cardano transaction."
            });
        }
    };
    Re = async function(e, t, n) {
        if (!T) return ae();
        if (e === "getExtensions") return xe(n?.enabledExtensions);
        const r = await ue({
            includeSigningKeys: e === "signTx" || e === "signData"
        });
        if (!r) return x(-3, "Wallet is locked. Unlock 1AM and reconnect.");
        switch(e){
            case "getNetworkId":
                return be(r);
            case "getUtxos":
                return Ie(r, t ?? {});
            case "getCollateral":
                return ve(r, t ?? {});
            case "getBalance":
                return Ae(r);
            case "getUsedAddresses":
                return Ke(r, t);
            case "getUnusedAddresses":
                return Ee(r);
            case "getChangeAddress":
                return Ce(r);
            case "getRewardAddresses":
                return He(r);
            case "signTx":
                return Se(r, t ?? {
                    tx: ""
                });
            case "signData":
                return Pe(r, t ?? {
                    address: "",
                    payload: ""
                });
            case "submitTx":
                return Te(r, t ?? {
                    tx: ""
                });
            default:
                return x(-1, `Unsupported Cardano CIP method: ${e}`);
        }
    };
});
export { Ae as cardanoCipGetBalance, Ce as cardanoCipGetChangeAddress, ve as cardanoCipGetCollateral, xe as cardanoCipGetExtensions, be as cardanoCipGetNetworkId, He as cardanoCipGetRewardAddresses, Ee as cardanoCipGetUnusedAddresses, Ke as cardanoCipGetUsedAddresses, Ie as cardanoCipGetUtxos, Re as cardanoCipHandleMethod, Pe as cardanoCipSignData, Se as cardanoCipSignTx, Te as cardanoCipSubmitTx, x as createCardanoApiError, ae as createCardanoProviderDisabledError, ue as getActiveCardanoWalletContext, de as getCurrentCardanoWalletScope, We as isCardanoCipConnectionExpired, Me as isCardanoConnectionCurrent, __tla };
