;
! function() {
    try {
        var e = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof global ? global : "undefined" != typeof window ? window : "undefined" != typeof self ? self : {},
            n = (new e.Error).stack;
        n && ((e._debugIds || (e._debugIds = {}))[n] = "63422170-5fdd-ac05-2d95-9a1e0df60ff7")
    } catch (e) {}
}();
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push(["object" == typeof document ? document.currentScript : void 0, 451742, e => {
    "use strict";
    var t = e.i(970863),
        s = e.i(455872),
        i = e.i(640793);
    let r = (e, t) => {
        let {
            wait: s,
            options: r
        } = (e => {
            let {
                wait: t,
                mode: s = "trailing"
            } = e;
            return {
                wait: t,
                options: { ..."leading" === s && {
                        leading: !0
                    },
                    ..."trailing" === s && {
                        trailing: !0
                    }
                }
            }
        })(t);
        return (0, i.throttle)(e, s, r)
    };
    var a = e.i(930896),
        o = e.i(402675),
        n = e.i(429694);
    class c {
        static aggregate(e, t, i) {
            let r = (0, s.getPrecisionFromTickSize)(i),
                a = (0, s.getPrecisionFromTickSize)(t),
                o = [...e.zero.bidArray || []],
                n = [...e.zero.askArray || []],
                l = c._side(o, "desc", t, "bid"),
                u = c._side(n, "asc", t, "ask"),
                h = c._invertSide(l, "asc", a, r),
                d = c._invertSide(u, "desc", a, r);
            return {
                zero: {
                    askArray: u,
                    bidArray: l,
                    bestAsk: e.zero.bestAsk,
                    bestBid: e.zero.bestBid,
                    spread: e.zero.spread,
                    midpoint: e.zero.midpoint
                },
                one: {
                    askArray: h,
                    bidArray: d,
                    bestAsk: e.one.bestAsk,
                    bestBid: e.one.bestBid,
                    spread: e.one.spread,
                    midpoint: e.one.midpoint
                },
                activeTickSize: t,
                state: this._state(e.zero.bestAsk, e.zero.bestBid)
            }
        }
        static _state(e, t) {
            return e && t && t >= e ? "crossed" : "valid"
        }
        static _side(e, t, s, i) {
            let r = new Map;
            for (let t = 0; t < e.length; t++) {
                let a = e[t],
                    o = (0, n.getBucketForPrice)(a.price, "bid" === i ? "bid" : "ask", s, s),
                    c = r.get(o) || {
                        price: o,
                        size: 0,
                        value: 0,
                        includedLevels: []
                    };
                c.size += parseFloat(a.size), c.value += parseFloat(a.value), c.includedLevels.push(a.price), r.set(o, c)
            }
            let a = Array.from(r.values()).map(e => ({
                price: e.price,
                size: `${e.size}`,
                value: e.value.toFixed(2),
                netSize: "0",
                netValue: "0",
                includedLevels: e.includedLevels
            }));
            a.sort((e, s) => "asc" === t ? parseFloat(e.price) - parseFloat(s.price) : parseFloat(s.price) - parseFloat(e.price));
            let o = 0,
                c = 0;
            for (let e = 0; e < a.length; e++) {
                let t = parseFloat(a[e].size),
                    s = parseFloat(a[e].value);
                o += t, c += s, a[e].netSize = o.toFixed(2), a[e].netValue = c.toFixed(2)
            }
            return a
        }
        static _invertSide(e, t, s, i) {
            let r = 10 ** -s,
                a = new Map;
            for (let t = 0; t < e.length; t++) {
                let o = e[t],
                    {
                        _price: n,
                        price: l
                    } = c._invertPrice(o.price, s, r),
                    u = a.get(l) || {
                        price: l,
                        size: 0,
                        value: 0,
                        includedLevels: []
                    };
                u.size += parseFloat(o.size), u.value += n * parseFloat(o.size), u.includedLevels.push(...o.includedLevels.map(e => c._invertPrice(e, i).price)), a.set(l, u)
            }
            let o = Array.from(a.values()).map(e => ({
                    price: e.price,
                    size: `${e.size}`,
                    value: e.value.toFixed(2),
                    netSize: "0",
                    netValue: "0",
                    includedLevels: e.includedLevels
                })).sort((e, s) => "asc" === t ? parseFloat(e.price) - parseFloat(s.price) : parseFloat(s.price) - parseFloat(e.price)),
                n = 0,
                l = 0;
            for (let e = 0; e < o.length; e++) {
                let t = parseFloat(o[e].size),
                    s = parseFloat(o[e].value);
                n += t, l += s, o[e].netSize = n.toFixed(2), o[e].netValue = l.toFixed(2)
            }
            return o
        }
        static _invertPrice(e, t, s) {
            let i = 1 - parseFloat(e || "0"),
                r = s ? ? 10 ** -t,
                a = Math.min(1 - r, Math.max(r, i));
            return {
                _price: a,
                price: a.toFixed(t)
            }
        }
    }
    var l = e.i(177217),
        u = e.i(573346);
    class h {#
        e;
        constructor(e) {
            this.#e = e
        }
        async fetchLastTradedPrice(e) {
            try {
                let t = await this.#e.get(`/last-trade-price?token_id=${e.assetId}`);
                if (!t.data) return {
                    status: "failure",
                    message: "Failed to fetch last traded price"
                };
                let s = {
                    [e.assetId]: t.data
                };
                return e.onSuccess ? .(s), {
                    status: "success",
                    data: s
                }
            } catch (e) {
                return {
                    status: "failure",
                    message: e instanceof Error ? e.message : "Failed to fetch last traded price"
                }
            }
        }
        async fetchLastTradedPrices(e) {
            try {
                let t = await this.#e.post("/last-trades-prices", e.assetIds.map(e => ({
                    token_id: e
                })));
                if (!t.data) return {
                    status: "failure",
                    message: "Failed to fetch last traded prices"
                };
                let s = t.data.reduce((e, t) => (e[t.token_id.toLowerCase()] = {
                    price: t.price,
                    side: t.side ? t.side : u.Side.BUY
                }, e), {});
                return e.onSuccess ? .(s), {
                    status: "success",
                    data: s
                }
            } catch (e) {
                return {
                    status: "failure",
                    message: e instanceof Error ? e.message : "Failed to fetch last traded prices"
                }
            }
        }
    }
    class d {#
        e;
        constructor(e) {
            this.#e = e
        }
        async fetchBook(e) {
            try {
                let t = await this.#e.get(`/book?token_id=${e.assetId}`);
                if (!t.data) return {
                    status: "failure",
                    message: "Book not found"
                };
                let s = {
                    [String(t.data.asset_id || "").toLowerCase()]: t.data
                };
                return e.onSuccess ? .(s), {
                    status: "success",
                    data: s
                }
            } catch (e) {
                return {
                    status: "failure",
                    message: e instanceof Error ? e.message : "Failed to fetch book"
                }
            }
        }
        async fetchBooks(e) {
            try {
                let t = await this.#e.post("/books?token_ids", e.assetIds.map(e => ({
                    token_id: e
                })));
                if (!t.data) return {
                    status: "failure",
                    message: "Failed to fetch books"
                };
                let s = {};
                return t.data.forEach(e => {
                    s[String(e.asset_id || "").toLowerCase()] = e
                }), e.onSuccess ? .(s), {
                    status: "success",
                    data: s
                }
            } catch (e) {
                return {
                    status: "failure",
                    message: e instanceof Error ? e.message : "Failed to fetch books"
                }
            }
        }
    }
    class p {#
        t;#
        s;
        constructor({
            url: e
        }) {
            const t = l.default.create({
                baseURL: e
            });
            this.#t = new d(t), this.#s = new h(t)
        }
        async fetchBook(e) {
            return this.#t.fetchBook(e)
        }
        async fetchBooks(e) {
            return this.#t.fetchBooks(e)
        }
        async fetchLastTradedPrice(e) {
            return this.#s.fetchLastTradedPrice(e)
        }
        async fetchLastTradedPrices(e) {
            return this.#s.fetchLastTradedPrices(e)
        }
    }
    let g = e => "asset" === e.type ? {
            assetId: e.asset.id,
            tickSize: e.asset.tickSize ? ? void 0
        } : {
            assetId: e.market.clobTokenIds ? .[0] ? .toLowerCase() ? ? "",
            tickSize: e.market.orderPriceMinTickSize ? ? void 0
        },
        k = e => "asset" === e.type ? e.assets.reduce((e, t) => (e[t.id] = {
            tickSize: t.tickSize ? ? void 0
        }, e), {}) : e.markets.reduce((e, t) => {
            let s = Array.isArray(t.clobTokenIds) ? t.clobTokenIds[0] : "";
            return s && (e[s] = {
                tickSize: t.orderPriceMinTickSize ? ? void 0
            }), e
        }, {}),
        m = ({
            type: e,
            book: t,
            tickSizes: i
        }) => ({
            type: e,
            assetId: String(t.asset_id || "").toLowerCase(),
            ts: parseInt(t.timestamp ? ? "0", 10) || Date.now(),
            hash: t.hash,
            data: {
                event_type: "book",
                ...t
            },
            tickSize: (({
                book: e,
                tickSizes: t
            }) => {
                if (t.market) return t.market;
                let i = t.market ? ? .01;
                if (e.asks.length) {
                    let t = (0, s.getPrecisionFromPrice)(e.asks[0].price);
                    2 === t ? i = .01 : 3 === t && (i = .001)
                }
                if (e.bids.length && .001 !== i) {
                    let t = (0, s.getPrecisionFromPrice)(e.bids[0].price);
                    2 === t ? i = .01 : 3 === t && (i = .001)
                }
                return i
            })({
                book: t,
                tickSizes: i
            })
        }),
        f = e => {
            let {
                book: t,
                minified: s,
                last: i
            } = e, r = [];
            return t && t.assets.forEach(({
                id: e,
                key: s
            }) => {
                r.push({
                    id: e,
                    key: s,
                    type: "book",
                    status: {
                        fetch: t.status
                    }
                })
            }), s && s.assets.forEach(({
                id: e,
                key: t
            }) => {
                r.push({
                    id: e,
                    key: t,
                    type: "minified",
                    status: {
                        fetch: s.status
                    }
                })
            }), i && i.assets.forEach(({
                id: e,
                key: t
            }) => {
                r.push({
                    id: e,
                    key: t,
                    type: "last-price",
                    status: {
                        fetch: i.status
                    }
                })
            }), r
        },
        b = e => {
            let {
                book: t,
                minified: s
            } = e, i = [];
            return t && t.assets.forEach(({
                id: e,
                key: s
            }) => {
                i.push({
                    id: e,
                    key: s,
                    type: "book",
                    status: {
                        poll: t.status
                    }
                })
            }), s && s.assets.forEach(({
                id: e,
                key: t
            }) => {
                i.push({
                    id: e,
                    key: t,
                    type: "minified",
                    status: {
                        poll: s.status
                    }
                })
            }), i
        },
        y = e => "markets" === e.mode ? e.markets.reduce((e, s) => {
            let i = (0, t.getAssetId)(s);
            return i && "" !== i && e.push(i), e
        }, []) : e.assetIds,
        S = (e, t) => {
            let s = y(e),
                i = y(t);
            return {
                previous: s.filter(e => !i.includes(e)),
                current: i.filter(e => !s.includes(e))
            }
        };
    class A {#
        i;
        constructor({
            clobRestApiUrl: e
        }) {
            this.#i = new p({
                url: e
            })
        }
        async fetchBook(e) {
            let {
                assetId: t
            } = g(e);
            if (!t) return {
                status: "failure",
                message: "no asset id"
            };
            this.onFetchStatusChange(f({
                book: {
                    assets: [{
                        id: t,
                        key: t
                    }],
                    status: "fetching"
                }
            }));
            let s = await this.#i.fetchBook({
                assetId: t,
                onSuccess: e => this.onFetchBooks(e)
            });
            return this.onFetchStatusChange(f({
                book: {
                    assets: [{
                        id: t,
                        key: t
                    }],
                    status: s.status
                }
            })), s
        }
        async fetchBooks(e, t = !0) {
            let s = k("asset" === e.type ? {
                    type: "asset",
                    assets: e.book.map(e => ({
                        id: e
                    }))
                } : {
                    type: "market",
                    markets: e.book
                }),
                i = k("asset" === e.type ? {
                    type: "asset",
                    assets: e.minified.map(e => ({
                        id: e
                    }))
                } : {
                    type: "market",
                    markets: e.minified
                }),
                r = Object.keys(s),
                a = Object.keys(i),
                o = [...new Set([...r, ...a])];
            if (!o.length) return {
                status: "success",
                data: {}
            };
            t && this.onFetchStatusChange(f({
                book: {
                    assets: r.map(e => ({
                        id: e,
                        key: e
                    })),
                    status: "fetching"
                },
                minified: {
                    assets: a.map(e => ({
                        id: e,
                        key: e
                    })),
                    status: "fetching"
                }
            }));
            let n = await this.#i.fetchBooks({
                assetIds: o
            });
            if ("success" === n.status) {
                let {
                    book: e,
                    minified: t
                } = Object.entries(n.data).reduce((e, [t, s]) => (r.includes(t) && (e.book[t] = s), a.includes(t) && (e.minified[t] = s), e), {
                    book: {},
                    minified: {}
                });
                Object.keys(e).length && this.onFetchBooks(e), Object.keys(t).length && this.onFetchMinifiedBooks(t)
            }
            return t && this.onFetchStatusChange(f({
                book: {
                    assets: r.map(e => ({
                        id: e,
                        key: e
                    })),
                    status: n.status
                },
                minified: {
                    assets: a.map(e => ({
                        id: e,
                        key: e
                    })),
                    status: n.status
                }
            })), n
        }
        async fetchLastPrice(e) {
            let {
                assetId: t
            } = g(e);
            if (!t) return {
                status: "failure",
                message: "no asset id"
            };
            this.onFetchStatusChange(f({
                last: {
                    assets: [{
                        id: t,
                        key: t
                    }],
                    status: "fetching"
                }
            }));
            let s = await this.#i.fetchLastTradedPrice({
                assetId: t,
                onSuccess: e => this.onFetchLastPrices(e)
            });
            return this.onFetchStatusChange(f({
                last: {
                    assets: [{
                        id: t,
                        key: t
                    }],
                    status: s.status
                }
            })), s
        }
        async fetchLastPrices(e, t = !0) {
            let s = Object.keys(k(e));
            if (!s.length) return {
                status: "success",
                data: {}
            };
            t && this.onFetchStatusChange(f({
                last: {
                    assets: s.map(e => ({
                        id: e,
                        key: e
                    })),
                    status: "fetching"
                }
            }));
            let i = await this.#i.fetchLastTradedPrices({
                assetIds: s,
                onSuccess: e => this.onFetchLastPrices(e)
            });
            return t && this.onFetchStatusChange(f({
                last: {
                    assets: s.map(e => ({
                        id: e,
                        key: e
                    })),
                    status: i.status
                }
            })), i
        }
        async fetchAll(e, t = !1) {
            let s = "asset" === e.book.type ? e.book.assets.map(e => e.id) : e.book.markets.map(e => e.clobTokenIds ? .[0] ? ? ""),
                i = "asset" === e.minified.type ? e.minified.assets.map(e => e.id) : e.minified.markets.map(e => e.clobTokenIds ? .[0] ? ? ""),
                r = [];
            if (t) {
                r = "asset" === e.lastPrices.type ? e.lastPrices.assets.map(e => e.id) : e.lastPrices.markets.map(e => e.clobTokenIds ? .[0] ? ? "");
                let t = f({ ...s.length && {
                        book: {
                            assets: s.map(e => ({
                                id: e,
                                key: e
                            })),
                            status: "fetching"
                        }
                    },
                    ...i.length && {
                        minified: {
                            assets: i.map(e => ({
                                id: e,
                                key: e
                            })),
                            status: "fetching"
                        }
                    },
                    ...r.length && {
                        last: {
                            assets: r.map(e => ({
                                id: e,
                                key: e
                            })),
                            status: "fetching"
                        }
                    }
                });
                t.length && this.onFetchStatusChange(t)
            }
            let [a, o] = await Promise.all([this.fetchBooks({
                type: "asset",
                book: s,
                minified: i
            }, !t), this.fetchLastPrices(e.lastPrices, !t)]);
            if (t) {
                let e = f({ ...s.length && {
                        book: {
                            assets: s.map(e => ({
                                id: e,
                                key: e
                            })),
                            status: a.status
                        }
                    },
                    ...i.length && {
                        minified: {
                            assets: i.map(e => ({
                                id: e,
                                key: e
                            })),
                            status: a.status
                        }
                    },
                    ...r.length && {
                        last: {
                            assets: r.map(e => ({
                                id: e,
                                key: e
                            })),
                            status: o.status
                        }
                    }
                });
                e.length && this.onFetchStatusChange(e)
            }
            return {
                book: a,
                lastPrices: o
            }
        }
        onFetchStatusChange = () => {};
        onFetchBooks = () => {};
        onFetchMinifiedBooks = () => {};
        onFetchLastPrices = () => {}
    }
    class z {
        status = "idle";
        queue;#
        r = 0;#
        a = null;
        constructor({
            queue: e,
            intervalMs: t
        }) {
            this.queue = e, this.#r = t
        }
        start() {
            this.status = "polling", this.#a && clearInterval(this.#a), this.#a = setInterval(() => {
                this.#o()
            }, this.#r)
        }
        stop() {
            this.status = "idle", this.#a && clearInterval(this.#a), this.#a = null
        }
        reset() {
            this.getStatus().polling.clear()
        }
        add(e) {
            let t = b({
                [e.type]: {
                    assets: e.data.map(e => ({
                        id: e.assetId,
                        key: e.key
                    })),
                    status: "start"
                }
            });
            t.length && this.onPollingStatusChange(t)
        }
        remove(e) {
            let t = b({
                [e.type]: {
                    assets: e.data.map(e => ({
                        id: e.assetId,
                        key: e.key
                    })),
                    status: "stop"
                }
            });
            t.length && this.onPollingStatusChange(t)
        }#
        o() {
            Array.from(this.getStatus().polling.entries()).forEach(([e, {
                book: t,
                bestPrices: s
            }]) => {
                t.size > 0 && this.queue.enqueue({
                    type: "book",
                    assetId: e
                }), s.size > 0 && this.queue.enqueue({
                    type: "minified",
                    assetId: e
                }), this.queue.enqueue({
                    type: "last-price",
                    assetId: e
                })
            }), this.queue.flush({
                type: "all",
                mode: "debounce"
            })
        }
        onPollingStatusChange = () => {};
        getStatus = () => ({
            status: new Map,
            polling: new Map
        })
    }
    var v = e.i(553512);
    class P {
        api;#
        n;#
        c;#
        l;#
        u = 0;#
        h = 0;
        constructor({
            api: e,
            throttleMs: t,
            debounceMs: s
        }) {
            this.api = e, this.#n = new Set, this.#c = new Set, this.#l = new Set, this.#u = t, this.#h = s
        }
        enqueue(e) {
            "book" === e.type && this.#d(e.assetId) ? this.#n.add(e.assetId) : "minified" === e.type && this.#d(e.assetId) ? this.#c.add(e.assetId) : "last-price" === e.type && this.#p(e.assetId) && this.#l.add(e.assetId)
        }
        dequeue(e) {
            "book" === e.type ? this.#n.delete(e.assetId) : "minified" === e.type ? this.#c.delete(e.assetId) : "last-price" === e.type && this.#l.delete(e.assetId)
        }
        clear(e) {
            ("book" === e.type || "all" === e.type) && this.#n.clear(), ("minified" === e.type || "all" === e.type) && this.#c.clear(), ("last-price" === e.type || "all" === e.type) && this.#l.clear()
        }
        flush(e) {
            "book" === e.type || "minified" === e.type ? "throttle" === e.mode ? this.#g() : "debounce" === e.mode ? this.#k() : this.#m() : "last-price" === e.type ? "throttle" === e.mode ? this.#f() : "debounce" === e.mode ? this.#b() : this.#y() : "throttle" === e.mode ? this.#S() : "debounce" === e.mode ? this.#A() : this.#z()
        }#
        m() {
            let e = Array.from(this.#n.values()),
                t = Array.from(this.#c.values());
            this.#n.clear(), this.#c.clear(), (e.length || t.length) && this.api.fetchBooks({
                type: "asset",
                book: e,
                minified: t
            })
        }#
        y() {
            let e = Array.from(this.#l.values());
            this.#l.clear(), e.length && this.api.fetchLastPrices({
                type: "asset",
                assets: e.map(e => ({
                    id: e
                }))
            })
        }#
        z() {
            let e = Array.from(this.#n.values()),
                t = Array.from(this.#c.values()),
                s = Array.from(this.#l.values());
            this.#n.clear(), this.#c.clear(), this.#l.clear(), (e.length || t.length || s.length) && this.api.fetchAll({
                book: {
                    type: "asset",
                    assets: e.map(e => ({
                        id: e
                    }))
                },
                minified: {
                    type: "asset",
                    assets: t.map(e => ({
                        id: e
                    }))
                },
                lastPrices: {
                    type: "asset",
                    assets: s.map(e => ({
                        id: e
                    }))
                }
            }, !0)
        }#
        g = r(() => {
            this.#m()
        }, {
            wait: this.#u,
            mode: "trailing"
        });#
        f = r(() => {
            this.#y()
        }, {
            wait: this.#u,
            mode: "trailing"
        });#
        k = (0, v.debounce)(() => {
            this.#m()
        }, {
            wait: this.#h,
            mode: "trailing"
        });#
        b = (0, v.debounce)(() => {
            this.#y()
        }, {
            wait: this.#h,
            mode: "trailing"
        });#
        S = r(() => {
            this.#z()
        }, {
            wait: this.#u,
            mode: "trailing"
        });#
        A = (0, v.debounce)(() => {
            this.#z()
        }, {
            wait: this.#h,
            mode: "trailing"
        });#
        d(e) {
            let t = this.getStatus().status.get(e);
            return !t || "success" === t.book.status || "queued" !== t.book.status && "fetching" !== t.book.status
        }#
        p(e) {
            let t = this.getStatus().status.get(e);
            return !t || "success" !== t.lastPrice.status
        }
        getStatus = () => ({
            status: new Map,
            polling: new Map
        })
    }
    class F {
        static build(e, t = .01) {
            let i = (0, s.getPrecisionFromTickSize)(t),
                r = Array.from(e.bids.entries()).sort((e, t) => parseFloat(t[0]) - parseFloat(e[0])),
                a = Array.from(e.asks.entries()).sort((e, t) => parseFloat(e[0]) - parseFloat(t[0])),
                o = this._parseSide(r),
                n = this._parseSide(a),
                c = this._invertSide(n, "bid", i),
                l = this._invertSide(o, "ask", i),
                u = this._clamp(n.length ? parseFloat(n[0].price) : null, i),
                h = this._clamp(o.length ? parseFloat(o[0].price) : null, i),
                d = this._clamp(l.length ? parseFloat(l[0].price) : null, i),
                p = this._clamp(c.length ? parseFloat(c[0].price) : null, i),
                g = this._clamp(u.valid && h.valid ? Math.max(u.number - h.number, 0) : null, i),
                k = this._clamp(u.valid && h.valid ? (u.number + h.number) / 2 : null, i),
                m = this._clamp(d.valid && p.valid ? (d.number + p.number) / 2 : null, i);
            return {
                zero: {
                    askArray: n,
                    bidArray: o,
                    bestAsk: u.number,
                    bestBid: h.number,
                    spread: g.number,
                    midpoint: k.number
                },
                one: {
                    askArray: l,
                    bidArray: c,
                    bestAsk: d.number,
                    bestBid: p.number,
                    spread: g.number,
                    midpoint: m.number
                },
                activeTickSize: t,
                state: this._state(u, h)
            }
        }
        static _state(e, t) {
            return e.number && t.number && t.number >= e.number ? "crossed" : "valid"
        }
        static _parseSide(e) {
            let t = 0,
                s = 0;
            return e.map(([e, i]) => {
                let r = parseFloat(i),
                    a = parseFloat(e) * r;
                return t += r, s += a, {
                    price: e,
                    size: `${r}`,
                    value: a.toFixed(2),
                    netSize: t.toFixed(2),
                    netValue: s.toFixed(2),
                    includedLevels: []
                }
            })
        }
        static _invertSide(e, t, s) {
            return [...e.reduce((e, t) => {
                let i = this._invertPrice(t.price, s);
                return i.valid && e.push({
                    price: i.string,
                    size: t.size,
                    value: t.value,
                    netValue: t.netValue,
                    netSize: t.netSize,
                    includedLevels: []
                }), e
            }, [])].sort((e, s) => "ask" === t ? parseFloat(e.price) - parseFloat(s.price) : parseFloat(s.price) - parseFloat(e.price)).reduce((e, {
                price: t,
                size: s,
                includedLevels: i
            }) => {
                let r = parseFloat(t),
                    a = parseFloat(s),
                    o = r * a;
                return e.cumulativeValue += o, e.cumulativeSize += a, e.result.push({
                    price: t,
                    size: s,
                    value: o.toFixed(2),
                    includedLevels: i,
                    netValue: e.cumulativeValue.toFixed(2),
                    netSize: e.cumulativeSize.toFixed(2)
                }), e
            }, {
                result: [],
                cumulativeValue: 0,
                cumulativeSize: 0
            }).result
        }
        static _invertPrice(e, t) {
            if (null === e) return {
                valid: !1,
                number: null,
                string: null
            };
            let s = parseFloat(e);
            return Number.isFinite(s) ? this._clamp(Math.max(1 - s, 0), t) : {
                valid: !1,
                number: null,
                string: null
            }
        }
        static _clamp(e, t) {
            if (null === e || !Number.isFinite(e)) return {
                valid: !1,
                number: null,
                string: null
            };
            let s = e.toFixed(t);
            return {
                valid: !0,
                number: parseFloat(s),
                string: s
            }
        }
    }
    class B {
        static project(e, t = {}) {
            let i = t.tickSize ? ? e.activeTickSize ? ? .01,
                r = this._side(e.zero.askArray, t.minified ? t => t.slice(0, Math.max(5, 10 - e.zero.bidArray.length)) : void 0),
                a = this._side(e.zero.bidArray, t.minified ? e => e.slice(0, Math.max(5, 10 - r.rows.length)) : void 0),
                o = this._side(e.one.askArray, t.minified ? t => t.slice(0, Math.max(5, 10 - e.one.bidArray.length)) : void 0),
                n = this._side(e.one.bidArray, t.minified ? e => e.slice(0, Math.max(5, 10 - o.rows.length)) : void 0),
                c = {
                    asks: r,
                    bids: a,
                    spread: e.zero.spread,
                    midpoint: e.zero.midpoint,
                    totalBidCount: e.zero.bidArray.length,
                    totalAskCount: e.zero.askArray.length
                },
                l = {
                    asks: o,
                    bids: n,
                    spread: e.one.spread,
                    midpoint: e.one.midpoint,
                    totalBidCount: e.one.bidArray.length,
                    totalAskCount: e.one.askArray.length
                },
                u = (0, s.getPrecisionFromTickSize)(i);
            return {
                tickSize: i,
                zero: c,
                one: l,
                bestPrices: {
                    "~zero": {
                        buy: null !== e.zero.bestAsk ? e.zero.bestAsk.toFixed(u) : null,
                        sell: null !== e.zero.bestBid ? e.zero.bestBid.toFixed(u) : null
                    },
                    "~one": {
                        buy: null !== e.one.bestAsk ? e.one.bestAsk.toFixed(u) : null,
                        sell: null !== e.one.bestBid ? e.one.bestBid.toFixed(u) : null
                    }
                },
                ts: t.ts ? ? Date.now()
            }
        }
        static _side(e, t = e => e) {
            let s = [],
                i = 0,
                r = 0;
            for (let t = 0; t < e.length; t++) {
                let a = e[t],
                    o = this._micro(a.size),
                    n = this._micro(a.value);
                i += o, r += n, s.push({
                    price: a.price,
                    size: o,
                    value: n,
                    netSize: i,
                    netValue: r,
                    includedLevels: a.includedLevels
                })
            }
            let a = e[0] ? .price,
                o = s.length ? s[s.length - 1].netSize : 0,
                n = s.length ? s[s.length - 1].netValue : 0;
            return {
                rows: t(s),
                bestPrice: a,
                hasLiquidity: s.length > 0,
                totalSize: o,
                totalValue: n
            }
        }
        static _micro(e) {
            let t = parseFloat(e || "0");
            return Number.isFinite(t) ? t : 0
        }
    }
    class T {
        static delta(e, t) {
            let s = this._clone(e),
                i = new Set;
            return t.price_changes.forEach(e => {
                let t = 0 === parseFloat(e.size);
                e.side ? .toUpperCase ? .() === "BUY" ? t ? s.bids.delete(e.price) : s.bids.set(e.price, e.size) : t ? s.asks.delete(e.price) : s.asks.set(e.price, e.size), i.add(e.price)
            }), {
                next: s,
                changed: i
            }
        }
        static snapshot(e) {
            let t = {
                bids: new Map,
                asks: new Map
            };
            for (let s = 0; s < (e.bids ? .length ? ? 0); s++) {
                let i = e.bids[s];
                t.bids.set(i.price, i.size)
            }
            for (let s = 0; s < (e.asks ? .length ? ? 0); s++) {
                let i = e.asks[s];
                t.asks.set(i.price, i.size)
            }
            let s = new Set;
            return t.bids.forEach((e, t) => s.add(t)), t.asks.forEach((e, t) => s.add(t)), {
                next: t,
                changed: s
            }
        }
        static _clone(e) {
            return {
                bids: e ? .bids ? new Map(e.bids) : new Map,
                asks: e ? .asks ? new Map(e.asks) : new Map
            }
        }
    }
    class w {#
        v = [];
        push(e) {
            if (Array.isArray(e)) {
                e.length && this.#v.push(...e);
                return
            }
            e && this.#v.push(e)
        }
        isEmpty() {
            return 0 === this.#v.length
        }
        size() {
            return this.#v.length
        }
        drain() {
            if (!this.#v.length) return [];
            let e = this.#v;
            return this.#v = [], e
        }
        drainBy(e) {
            if (!this.#v.length) return [];
            let t = [];
            "asset" === e.type && t.push(...e.ids);
            let s = new Set(t),
                {
                    removing: i,
                    remaining: r
                } = this.#v.reduce((e, t) => (s.has(t.assetId) ? e.removing.push(t) : e.remaining.push(t), e), {
                    removing: [],
                    remaining: []
                });
            return this.#v = r, i
        }
        process(e) {
            let t = this.drain();
            if (!t.length) return [];
            let i = {},
                r = {};
            t.forEach(t => {
                if (i[t.assetId] || (i[t.assetId] = {
                        snapshots: [],
                        deltas: [],
                        last: [],
                        ticks: [],
                        minified: []
                    }), "book" === t.type || "minified" === t.type) {
                    let a = t.assetId;
                    .01 === (e.marketTickSizeByAsset.get(a) ? ? .01) && (t.data.asks.some(e => 3 === (0, s.getPrecisionFromPrice)(e.price)) || t.data.bids.some(e => 3 === (0, s.getPrecisionFromPrice)(e.price))) && (r[a] = .001, i[t.assetId].ticks.push({
                        type: "tick-size-change",
                        assetId: a,
                        ts: t.ts,
                        data: {
                            new_tick_size: "0.001"
                        }
                    })), "book" === t.type ? i[t.assetId].snapshots.push(t) : "minified" === t.type && i[t.assetId].minified.push(t)
                } else if ("price_change" === t.type) {
                    let a = t.assetId;
                    .01 === (e.marketTickSizeByAsset.get(a) ? ? .01) && t.data.price_changes.some(e => 3 === (0, s.getPrecisionFromPrice)(e.price)) && (r[a] = .001, i[t.assetId].ticks.push({
                        type: "tick-size-change",
                        assetId: a,
                        ts: t.ts,
                        data: {
                            new_tick_size: "0.001"
                        }
                    })), i[t.assetId].deltas.push(t)
                } else "last-trade-price" === t.type ? i[t.assetId].last.push(t) : "tick-size-change" === t.type && (r[t.assetId] = parseFloat(t.data.new_tick_size), i[t.assetId].ticks.push(t))
            }), Object.entries(r).forEach(([t, s]) => {
                e.marketTickSizeByAsset.set(t, s)
            });
            let a = [];
            return Object.entries(i).forEach(([t, s]) => {
                s.ticks.forEach(s => {
                    let i = e.project(t, "book");
                    "success" === i.status && i.data && a.push({
                        type: "tick-size-change",
                        assetId: t,
                        newTickSize: parseFloat(s.data.new_tick_size),
                        snapshot: i.data,
                        ts: Date.now(),
                        origin: "market"
                    })
                });
                let i = e.assetLastBookTs.get(t) ? ? 0,
                    o = !1;
                s.snapshots.length && (o = !0, s.snapshots.forEach(s => {
                    e.priceMaps[t] = T.snapshot(s.data).next, e.snapshotRequired.add(t), i = Math.max(i, s.ts)
                }));
                let n = new Set,
                    c = new Map;
                if (s.deltas.length && (o = !0, s.deltas.forEach(s => {
                        if (s.ts <= i) return;
                        let r = T.delta(e.priceMaps[t], s.data);
                        e.priceMaps[t] = r.next, r.changed.forEach(e => {
                            n.add(e)
                        }), s.data.price_changes.forEach(e => {
                            let t = e.side ? .toLowerCase ? .() === "buy" ? "buy" : "sell";
                            c.set(e.price, t)
                        })
                    })), o || r[t]) {
                    e.assetLastBookTs.set(t, i);
                    let s = e.project(t, "book");
                    if ("success" === s.status && s.data) {
                        let e = s.data;
                        a.push({
                            type: "snapshot",
                            assetId: t,
                            data: e
                        })
                    }
                }
                if (s.last.forEach(s => {
                        let i = e.marketTickSizeByAsset.get(t) ? ? .01;
                        a.push({
                            type: "last-trade-price",
                            assetId: t,
                            price: s.data.price,
                            side: s.data.side,
                            ts: s.ts,
                            tickSize: i
                        })
                    }), s.minified.length) {
                    s.minified.forEach(s => {
                        e.priceMaps[t] = T.snapshot(s.data).next
                    });
                    let i = e.project(t, "minified");
                    "success" === i.status && i.data && a.push({
                        type: "minified",
                        assetId: t,
                        data: i.data
                    })
                }
            }), a
        }
    }
    var C = e.i(260536),
        _ = e.i(282750);
    class I {}
    class M extends I {#
        P = new Set;#
        e;#
        F;#
        B;
        constructor({
            url: e,
            log: t,
            callbacks: s
        }) {
            super(), this.#F = t, this.#B = s, this.#e = new _.WebsocketClient({
                url: e,
                autoReconnect: !1,
                ping: {
                    once: !1,
                    message: "PING",
                    respond: !0,
                    response: "PONG",
                    delay: 3e4
                },
                callbacks: {
                    onOpen: ({
                        event: e
                    }) => {
                        this.#B && this.#B.onOpen ? .(e), this.#T(), this.#F && this.#F("debug", "[ClobTransport][onOpen] WebSocket opened", {
                            event: JSON.stringify(e)
                        })
                    },
                    onClose: ({
                        event: e
                    }) => {
                        this.#B && this.#B.onClose ? .(e), this.#T(), this.#F && this.#F("debug", "[ClobTransport][onClose] WebSocket closed", {
                            event: JSON.stringify(e)
                        })
                    },
                    onError: ({
                        event: e
                    }) => {
                        this.#B ? .onError ? .(e), this.#T(), this.#F && this.#F("error", "[ClobTransport][onError] WebSocket error", {
                            event: JSON.stringify(e)
                        })
                    },
                    onStatusChange: ({
                        status: e
                    }) => {
                        this.#T(), this.#F && this.#F("debug", "[ClobTransport][onStatusChange] status", {
                            status: e
                        })
                    },
                    onMessage: ({
                        event: e
                    }) => {
                        let t = this.#w(e);
                        if ("failure" === t.status) {
                            this.#F && this.#F("error", "[ClobTransport][onMessage] failed to parse message", {
                                event: JSON.stringify(e.data)
                            });
                            return
                        }
                        this.#B ? .onMessage && t.events.length && this.#B.onMessage({
                            "~raw": e,
                            events: t.events
                        })
                    }
                }
            })
        }
        subscribe(e) {
            this.#P = new Set(e), this.#T(), this.#e.subscribe(JSON.stringify({
                type: "markets",
                assets_ids: e
            }))
        }
        unsubscribe(e) {
            this.#P = new Set(e), this.#T(), this.#e.unsubscribe(JSON.stringify({
                type: "markets",
                operation: "unsubscribe",
                assets_ids: e
            }))
        }
        disconnect() {
            this.#e.disconnect()
        }
        terminate() {
            this.disconnect()
        }
        ping() {
            this.#e.ping()
        }
        update(e) {
            if (!this.#e.state.connected) return;
            let t = e.previous.filter(t => !e.current.includes(t)),
                s = e.current.filter(t => !e.previous.includes(t));
            s.length && this.#e.send(JSON.stringify({
                type: "markets",
                operation: "subscribe",
                assets_ids: s
            })), t.length && this.#e.send(JSON.stringify({
                type: "markets",
                operation: "unsubscribe",
                assets_ids: t
            })), this.#P = new Set(e.current), this.#T()
        }
        get state() {
            return {
                subscribedAssetIds: this.#P,
                ...this.#e.state
            }
        }
        get connected() {
            return this.#e.connected
        }#
        T() {
            this.#B ? .onStateChange && this.#B.onStateChange(this.state)
        }#
        w(e) {
            try {
                let t = [],
                    s = (0, C.parseMessageEvent)(e);
                if ("string" === s.type || "ping" === s.type || "pong" === s.type) return {
                    status: "success",
                    events: t
                };
                if ("message" === s.type) return (Array.isArray(s.data) ? s.data : [s.data]).forEach(e => {
                    var s;
                    let i, r = (s = this.#P, i = [], e ? "book" === e.event_type ? (({
                        event: e,
                        subscribedAssetIds: t
                    }) => {
                        let s = [],
                            i = String(e.asset_id || "").toLowerCase();
                        if (t.has(i)) {
                            let t = parseInt(e.timestamp ? ? "0", 10) || Date.now();
                            s.push({
                                type: "book",
                                assetId: i,
                                ts: t,
                                hash: e.hash,
                                data: e
                            })
                        }
                        return s
                    })({
                        event: e,
                        subscribedAssetIds: s
                    }) : "price_change" === e.event_type ? (({
                        event: e,
                        subscribedAssetIds: t
                    }) => {
                        let s = [],
                            i = (Array.isArray(e.price_changes) ? e.price_changes : []).filter(e => {
                                let s = String(e.asset_id || "").toLowerCase();
                                return t.has(s)
                            });
                        if (!i.length) return s;
                        let r = String(i[0].asset_id || "").toLowerCase(),
                            a = parseInt(e.timestamp ? ? "0", 10) || Date.now();
                        return s.push({
                            type: "price_change",
                            assetId: r,
                            ts: a,
                            data: {
                                price_changes: i.map(e => ({
                                    price: e.price,
                                    size: e.size,
                                    side: e.side
                                }))
                            }
                        }), s
                    })({
                        event: e,
                        subscribedAssetIds: s
                    }) : "last_trade_price" === e.event_type ? (({
                        event: e,
                        subscribedAssetIds: t
                    }) => {
                        let s = [],
                            i = String(e.asset_id || "").toLowerCase();
                        return t.has(i) && s.push({
                            type: "last-trade-price",
                            assetId: i,
                            ts: Date.now(),
                            data: {
                                price: e.price,
                                side: e.side
                            }
                        }), s
                    })({
                        event: e,
                        subscribedAssetIds: s
                    }) : "tick_size_change" === e.event_type ? (({
                        event: e,
                        subscribedAssetIds: t
                    }) => {
                        let s = [],
                            i = String(e.asset_id || "").toLowerCase();
                        return t.has(i) && s.push({
                            type: "tick-size-change",
                            assetId: i,
                            ts: Date.now(),
                            data: {
                                new_tick_size: e.new_tick_size,
                                old_tick_size: e.old_tick_size
                            }
                        }), s
                    })({
                        event: e,
                        subscribedAssetIds: s
                    }) : i : i);
                    r.length && t.push(...r)
                }), {
                    status: "success",
                    events: t
                };
                return {
                    status: "failure",
                    error: s.error
                }
            } catch (e) {
                return {
                    status: "failure",
                    error: e
                }
            }
        }
    }
    class L {#
        C = 320;#
        _ = new Map;#
        I = null;#
        M = new w;#
        L;#
        Q;#
        E;#
        q = null;#
        O = {};#
        x = new Map;#
        U = new Map;#
        j = new Set;#
        R;#
        D;#
        W = new Set;#
        N = new Set;#
        J = new Map;#
        V = new Map;#
        K;#
        $;#
        G;#
        Y;#
        H = null;#
        X = !1;
        constructor({
            clobRestApiUrl: e,
            clobWsApiUrl: t,
            options: s
        }) {
            const {
                batchIntervalMs: i = 320,
                queue: r,
                polling: a
            } = s ? ? {}, o = r ? ? {
                throttleMs: 400,
                debounceMs: 400
            }, n = a ? ? {
                intervalMs: 15e3
            };
            this.#C = i, this.#R = t, this.#D = e, this.#K = o, this.#$ = n, this.#L = new A({
                clobRestApiUrl: e
            }), this.#Q = new P({
                api: this.#L,
                ...o
            }), this.#E = new z({
                queue: this.#Q,
                ...n
            })
        }
        async initialize() {
            this.#L = new A({
                clobRestApiUrl: this.#D
            }), this.#L.onFetchStatusChange = e => this.#Z(e), this.#L.onFetchBooks = e => this.#ee(e), this.#L.onFetchMinifiedBooks = e => this.#et(e), this.#L.onFetchLastPrices = e => this.#es(e), this.#Q = new P({
                api: this.#L,
                ...this.#K
            }), this.#Q.getStatus = () => ({
                status: this.#J,
                polling: this.#V
            }), this.#E = new z({
                queue: this.#Q,
                ...this.#$
            }), this.#E.onPollingStatusChange = e => this.#Z(e), this.#E.getStatus = () => ({
                status: this.#J,
                polling: this.#V
            }), this.#E.start()
        }
        async subscribe(e) {
            let t = this.prepareSubscription(e);
            return "update" === t.type ? this.updateSubscription(t) : this.createSubscription(t)
        }
        async unsubscribe() {
            let e = this.#Y;
            return e ? this.#I && this.#I.connected ? (e && this.#I.connected && this.#I.update(S(e, {
                mode: "assetIds",
                assetIds: []
            })), this.#Y = void 0, {
                status: "success"
            }) : {
                status: "error",
                message: "no transport or not connected"
            } : {
                status: "error",
                message: "no connection params"
            }
        }
        async pause() {
            this.#G = this.#Y;
            let e = await this.unsubscribe();
            if ("error" === e.status) return e
        }
        async resume(e) {
            let t = e ? ? this.#G;
            return t ? (this.#Y = t, this.#G = void 0, this.#I ? .connected && this.#I.update({
                previous: [],
                current: y(t)
            }), {
                status: "success"
            }) : {
                status: "error",
                message: "no paused connection params"
            }
        }
        async update(e) {
            if (!this.#I || !this.#I.connected) return this.subscribe({ ...e,
                reset: !0
            });
            let s = this.#Y ? ? {
                mode: "assetIds",
                assetIds: []
            };
            return this.#Y = e, "markets" === e.mode && e.markets.forEach(e => {
                this.#x.set((0, t.getAssetId)(e), e.orderPriceMinTickSize)
            }), this.#I.update(S(s, this.#Y)), {
                status: "success",
                type: "update"
            }
        }
        async disconnect() {
            try {
                return this.#ei(), this.#I && this.#I.disconnect(), this.#I = null, {
                    status: "success"
                }
            } catch (e) {
                return this.logger && this.logger("error", "[BookWorker][disconnect] Failed to disconnect from the book websocket", {
                    error: String(e)
                }), {
                    status: "error",
                    message: e.message
                }
            }
        }
        async terminate() {
            try {
                return this.#Q.clear({
                    type: "all"
                }), this.disconnect()
            } catch (e) {
                return this.logger && this.logger("error", "[BookWorker][terminate] Failed to terminate the book websocket", {
                    error: e
                }), {
                    status: "error",
                    message: e.message
                }
            }
        }
        async getState() {
            if (!this.#I) return;
            let e = this.#I.state;
            return {
                transportState: {
                    subscribedAssetIds: Array.from(e.subscribedAssetIds),
                    connected: e.connected,
                    status: e.status,
                    readyState: e.readyState
                },
                socketState: {
                    readyState: e.readyState,
                    connected: e.readyState === a.WebsocketReadyStates.Connected
                },
                internalState: {
                    timerActive: this.#X,
                    hasTimerInterval: !!this.#q,
                    tickSize: Object.fromEntries(this.#x),
                    connectionParams: this.#Y,
                    pausedConnectionParams: this.#G
                }
            }
        }
        async ping() {
            try {
                return this.#I && this.#I.ping(), {
                    status: "success"
                }
            } catch (e) {
                return this.logger && this.logger("error", "[BookWorker][ping] Failed to ping the book websocket", {
                    error: String(e)
                }), {
                    status: "error",
                    message: e.message
                }
            }
        }
        async fetchBook(e) {
            try {
                return await this.#L.fetchBook(e)
            } catch (e) {
                throw this.logger && this.logger("error", "[BookWorker][fetchBook] Failed to fetch the book", {
                    error: String(e)
                }), e
            }
        }
        async queueFetchBook(e) {
            let t = g(e);
            t.tickSize && this.conditionallyUpdateTickSize(t.assetId, t.tickSize), this.#Q.enqueue({
                type: "book",
                assetId: t.assetId
            }), this.#Q.flush({
                type: "book",
                mode: "debounce"
            })
        }
        async queueFetchBooks(e) {
            let t = k(e);
            Object.keys(t).forEach(e => {
                let s = t[e].tickSize;
                s && this.conditionallyUpdateTickSize(e, s), this.#Q.enqueue({
                    type: "book",
                    assetId: e
                })
            }), this.#Q.flush({
                type: "book",
                mode: "debounce"
            })
        }
        async fetchBooks(e) {
            try {
                return await this.#L.fetchBooks(e)
            } catch (e) {
                throw this.logger && this.logger("error", "Failed to fetch the books", {
                    error: String(e)
                }), e
            }
        }
        async queueFetchMinifiedBook(e) {
            let t = g(e);
            t.tickSize && this.conditionallyUpdateTickSize(t.assetId, t.tickSize), this.#Q.enqueue({
                type: "minified",
                assetId: t.assetId
            }), this.#Q.flush({
                type: "minified",
                mode: "debounce"
            })
        }
        async queueFetchMinifiedBooks(e) {
            let t = k(e);
            Object.keys(t).forEach(e => {
                t[e].tickSize && this.conditionallyUpdateTickSize(e, t[e].tickSize), this.#Q.enqueue({
                    type: "minified",
                    assetId: e
                }), this.#Q.flush({
                    type: "minified",
                    mode: "debounce"
                })
            })
        }
        async fetchLastPrice(e) {
            try {
                return await this.#L.fetchLastPrice(e)
            } catch (e) {
                throw this.logger && this.logger("error", "[BookWorker][fetchLastPrice] Failed to fetch the last price", {
                    error: String(e)
                }), e
            }
        }
        async queueFetchLastPrice(e) {
            let t = g(e);
            t.tickSize && this.conditionallyUpdateTickSize(t.assetId, t.tickSize), this.#Q.enqueue({
                type: "last-price",
                assetId: t.assetId
            }), this.#Q.flush({
                type: "last-price",
                mode: "debounce"
            })
        }
        async queueFetchLastPrices(e) {
            let t = k(e);
            Object.keys(t).forEach(e => {
                let s = t[e].tickSize;
                s && this.conditionallyUpdateTickSize(e, s), this.#Q.enqueue({
                    type: "last-price",
                    assetId: e
                })
            }), this.#Q.flush({
                type: "last-price",
                mode: "debounce"
            })
        }
        async fetchLastPrices(e) {
            try {
                return await this.#L.fetchLastPrices(e)
            } catch (e) {
                throw this.logger && this.logger("error", "[BookWorker][fetchLastPrices] Failed to fetch the last prices", {
                    error: String(e)
                }), e
            }
        }
        async fetchBestPrices(e) {
            try {
                let t = await this.#L.fetchBooks({
                    type: "asset",
                    book: e,
                    minified: []
                });
                if ("success" === t.status) {
                    let e;
                    return {
                        status: "success",
                        data: (e = t.data, Object.values(e).reduce((e, t) => {
                            let s, i, r, a;
                            return t.bids.length && (i = parseFloat(t.bids.map(e => parseFloat(e.price)).sort((e, t) => t - e)[0].toFixed(2))), t.asks.length && (s = parseFloat(t.asks.map(e => parseFloat(e.price)).sort((e, t) => e - t)[0].toFixed(2))), void 0 !== i && (r = parseFloat((1 - i).toFixed(2))), void 0 !== s && (a = parseFloat((1 - s).toFixed(2))), void 0 !== s && void 0 !== i && void 0 !== r && void 0 !== a && (e[t.asset_id] = {
                                zero: {
                                    ask: s,
                                    bid: i
                                },
                                one: {
                                    ask: r,
                                    bid: a
                                }
                            }), e
                        }, {}))
                    }
                }
                return t
            } catch (e) {
                throw this.logger && this.logger("error", "Failed to fetch the books", {
                    error: String(e)
                }), e
            }
        }
        async queueFetch(e) {
            e.book && this.queueFetchBooks(e.book), e.minified && this.queueFetchMinifiedBooks(e.minified), e.lastPrices && this.queueFetchLastPrices(e.lastPrices)
        }
        async startPolling(e) {
            e.data.forEach(e => {
                e.tickSize && this.#x.set(e.assetId, e.tickSize)
            }), this.#E.add(e)
        }
        async stopPolling(e) {
            this.#E.remove(e)
        }
        async updatePolling(e) {
            let t = [],
                s = [],
                i = [],
                r = [];
            e.forEach(e => {
                "minified" === e.type ? e.data.forEach(e => {
                    "add" === e.mode ? t.push(e) : "remove" === e.mode && s.push(e)
                }) : "book" === e.type && e.data.forEach(e => {
                    "add" === e.mode ? i.push(e) : "remove" === e.mode && r.push(e)
                })
            }), t.length > 0 && this.#E.add({
                type: "minified",
                data: t
            }), i.length > 0 && this.#E.add({
                type: "book",
                data: i
            }), s.length > 0 && this.#E.remove({
                type: "minified",
                data: s
            }), r.length > 0 && this.#E.remove({
                type: "book",
                data: r
            })
        }
        async clearPolling() {
            this.#E.reset()
        }
        async getActiveAssets() {
            let e = Array.from(this.#E.getStatus().polling.entries()).reduce((e, [t, s]) => (s.book.size > 0 && s.bestPrices.size > 0 && e.push(t), e), []);
            return {
                subscribed: Array.from(this.#I ? .state.subscribedAssetIds ? ? []),
                polling: e
            }
        }
        project(e) {
            try {
                let t = e.assetId.toLowerCase(),
                    s = this.#O[t];
                if (!s) return {
                    status: "error",
                    message: "no book"
                };
                let {
                    marketTickSize: i,
                    activeTickSize: r,
                    isAggregated: a
                } = this.#er(t), o = F.build(s, i), n = a ? c.aggregate(o, r, i) : o, l = B.project(n, {
                    tickSize: r,
                    ts: Date.now()
                });
                return {
                    status: "success",
                    data: l
                }
            } catch (e) {
                return this.logger && this.logger("error", "[BookWorker][project] Failed to project the book", {
                    error: String(e)
                }), {
                    status: "error",
                    message: e.message
                }
            }
        }
        conditionallyUpdateTickSize(e, t) {
            if (t) {
                let s = this.#x.get(e);
                s ? t < s && this.#x.set(e, t) : this.#x.set(e, t)
            }
        }
        onUserTickSizeChange(e, t) {
            let s = this.#U.get(e),
                i = this.#x.get(e);
            return i ? (t >= i && this.#U.set(e, t), {
                status: "success",
                market: void 0,
                user: {
                    from: s,
                    to: this.#U.get(e)
                }
            }) : {
                status: "error",
                message: "no market tick size"
            }
        }
        onMarketTickSizeChange(e, t) {
            let s = this.#x.get(e),
                i = this.#U.get(e);
            return this.#x.set(e, t), !i || i >= t || this.#U.delete(e), {
                status: "success",
                market: {
                    from: s,
                    to: this.#x.get(e)
                },
                user: {
                    from: i,
                    to: this.#U.get(e)
                }
            }
        }
        onTickSizeChange({
            assetId: e,
            tickSize: t,
            origin: s
        }) {
            if (!this.#O[e]) return {
                status: "error",
                message: "no book"
            };
            let i = "user" === s ? this.onUserTickSizeChange(e, t) : this.onMarketTickSizeChange(e, t),
                r = this.project({
                    assetId: e
                });
            return "success" !== r.status ? r : (this.onBookEvents && this.onBookEvents([{
                type: "tick-size-change",
                assetId: e,
                origin: s,
                newTickSize: t,
                snapshot: r.data,
                ts: Date.now()
            }]), i)
        }
        async setUserTickSize(e) {
            return this.onTickSizeChange({ ...e,
                origin: "user"
            })
        }
        async setMarketTickSize(e) {
            return this.onTickSizeChange({ ...e,
                origin: "market"
            })
        }
        async sendMessage(e) {
            this.#M.push(e)
        }
        async keepAlive(e = !1) {
            return this.#I && this.#I.connected ? this.#Y ? (e && this.#I.ping(), {
                status: "success"
            }) : {
                status: "error",
                message: "no connection params"
            } : {
                status: "error",
                message: "no transport or not connected"
            }
        }
        async getLoggedAssets() {
            return Array.from(this.#N)
        }
        async toggleLogAsset(e, t) {
            return t ? this.#N.add(e) : this.#N.delete(e), this.getLoggedAssets()
        }
        updateCachedTickSizes(e) {
            e.markets.forEach(e => {
                let s = (0, t.getAssetId)(e);
                s && "" !== s && this.#x.set(s, e.orderPriceMinTickSize)
            })
        }
        prepareSubscription(e) {
            e.apiUrl && (this.#D = e.apiUrl), void 0 !== e.interval && (this.#C = e.interval);
            let t = this.#Y;
            this.#Y = e;
            let s = y(e);
            return (this.#ea(s), "markets" === e.mode && this.updateCachedTickSizes(e), this.#I ? .connected && t && !e.reset) ? {
                type: "update",
                current: e,
                previous: t,
                assetIds: s,
                transport: this.#I
            } : {
                type: "create",
                current: e,
                assetIds: s
            }
        }
        async getOrCreateTransport(e) {
            this.#I && (this.#ei(), this.#I.disconnect(), await new Promise(e => setTimeout(e, 500)), this.#I = null);
            let t = new M({
                url: this.#R,
                log: (e, t, s) => {
                    this.logger && this.logger(e, t, s)
                },
                callbacks: {
                    onMessage: ({
                        events: e
                    }) => {
                        this.#eo(e)
                    },
                    onError: () => {
                        (!this.#H || Date.now() - this.#H > 1e4) && this.#Y && (this.subscribe({ ...this.#Y,
                            reset: !0
                        }), this.logger && this.logger("debug", "[BookWorker][Transport][onErrorCallback] Forced reconnect", {
                            lastForcedReconnectTs: this.#H
                        }))
                    },
                    onOpen: () => {
                        this.#en(), e && t.subscribe(e)
                    },
                    onStateChange: e => {
                        this.onWebsocketStateChange && this.onWebsocketStateChange(e)
                    }
                }
            });
            return t
        }
        async createSubscription(e) {
            try {
                return this.logger && this.logger("debug", "[BookWorker][createClobSubscription] creating subscription...", {
                    params: JSON.stringify(e.current)
                }), this.#I = await this.getOrCreateTransport(e.assetIds), {
                    status: "success",
                    type: "create"
                }
            } catch (t) {
                return this.logger && this.logger("error", "[BookWorker][createClobSubscription] Failed to create clob subscription", {
                    error: String(t),
                    params: JSON.stringify(e.current)
                }), {
                    status: "error",
                    message: t.message
                }
            }
        }
        async updateSubscription(e) {
            try {
                return this.logger && this.logger("debug", "[BookWorker][updateClobSubscription] updating subscription...", {
                    from: JSON.stringify(e.previous),
                    to: JSON.stringify(e.current)
                }), e.transport.update(S(e.previous, e.current)), {
                    status: "success",
                    type: "update"
                }
            } catch (t) {
                return this.logger && this.logger("error", "[BookWorker][updateClobSubscription] Failed to update clob subscription", {
                    error: String(t),
                    params: JSON.stringify(e.current)
                }), {
                    status: "error",
                    message: t.message
                }
            }
        }#
        en() {
            this.#q && clearInterval(this.#q), this.#X = !0, this.#q = setInterval(() => {
                this.#o()
            }, this.#C)
        }#
        ei() {
            this.#q && clearInterval(this.#q), this.#q = null, this.#X = !1
        }
        async# o() {
            try {
                if (this.#M.isEmpty()) return;
                let e = !1,
                    t = this.#M.process({
                        priceMaps: this.#O,
                        assetLastBookTs: this.#_,
                        snapshotRequired: this.#j,
                        marketTickSizeByAsset: this.#x,
                        project: (t, s) => {
                            let {
                                marketTickSize: i,
                                activeTickSize: r,
                                isAggregated: a
                            } = this.#er(t), o = this.#O[t] ? ? {
                                bids: new Map,
                                asks: new Map
                            }, n = F.build(o, i);
                            "crossed" === n.state && (e = !0);
                            let l = a ? c.aggregate(n, r, i) : n,
                                u = B.project(l, {
                                    tickSize: r,
                                    ts: Date.now(),
                                    minified: "minified" === s
                                });
                            return this.#N.has(t) && this.#ec(t, o, n, l, u), {
                                status: "success",
                                data: u
                            }
                        }
                    });
                if (this.#j.clear(), e) {
                    let e = this.#H,
                        t = Date.now();
                    if ((!e || t - e > 1e4) && this.#Y) return this.subscribe({ ...this.#Y,
                        reset: !0
                    }), {
                        status: "crossed",
                        data: "forcing reconnect"
                    }
                }
                return t.length && this.onBookEvents && this.onBookEvents(t), {
                    status: "success"
                }
            } catch (e) {
                return this.logger && this.logger("error", "Failed to flush the queue", {
                    error: String(e)
                }), {
                    status: "error",
                    message: e.message
                }
            }
        }#
        er(e) {
            let t = this.#U.get(e),
                i = this.#x.get(e),
                r = this.#O[e] ? ? {
                    bids: new Map,
                    asks: new Map
                },
                a = i ? ? .01;
            if (!i) {
                if (r.asks.size > 0) {
                    let e = (0, s.getPrecisionFromPrice)(r.asks.keys().next().value);
                    2 === e ? a = .01 : 3 === e && (a = .001)
                } else if (r.bids.size > 0) {
                    let e = (0, s.getPrecisionFromPrice)(r.bids.keys().next().value);
                    2 === e ? a = .01 : 3 === e && (a = .001)
                }
            }
            let o = t ? ? a,
                n = o >= a ? o : a,
                c = n > a;
            return {
                marketTickSize: a,
                userTickSize: o,
                activeTickSize: n,
                isAggregated: c
            }
        }#
        ec = r((e, t, s, i, r) => {
            console.log("[ORDER BOOK UPDATE]", JSON.stringify({
                assetId: e,
                levels: t,
                book: s,
                aggregated: i,
                projected: r
            }))
        }, {
            wait: 1e3,
            mode: "trailing"
        });#
        ea(e) {
            let t = new Set(this.#W);
            this.#W.clear(), e.forEach(e => {
                this.#W.add(e)
            });
            let s = (0, o.difference)(Array.from(t), e);
            this.#M.drainBy({
                type: "asset",
                ids: s
            }), s.reduce((e, t) => {
                let {
                    marketTickSize: s,
                    activeTickSize: i,
                    isAggregated: r
                } = this.#er(t);
                return this.#O[t] ? ? new Map, this.#O[t] && delete this.#O[t], e
            }, [])
        }#
        eo(e) {
            e ? .length && this.#M.push(e)
        }#
        ee(e) {
            Object.values(e).forEach(e => {
                let t = this.#er(e.asset_id);
                this.#M.push(m({
                    type: "book",
                    book: e,
                    tickSizes: {
                        market: t.marketTickSize,
                        user: t.userTickSize
                    }
                }))
            }), this.#o()
        }#
        et(e) {
            Object.values(e).forEach(e => {
                let t = this.#er(e.asset_id),
                    s = m({
                        type: "minified",
                        book: e,
                        tickSizes: {
                            market: t.marketTickSize,
                            user: t.userTickSize
                        }
                    });
                this.#M.push(s)
            }), this.#o()
        }#
        es(e) {
            Object.entries(e).forEach(([e, t]) => {
                this.#M.push({
                    type: "last-trade-price",
                    assetId: e,
                    ts: Date.now(),
                    data: {
                        price: t.price,
                        side: t.side
                    }
                })
            }), this.#o()
        }#
        Z(e) {
            var t, s;
            let i, r, a = (t = this.#J, s = this.#V, i = Date.now(), r = [], e.forEach(e => {
                let {
                    id: a,
                    key: o,
                    type: n,
                    status: c
                } = e, l = t.get(a), u = s.get(a), h = "idle", d = "idle", p = !1, g = !1;
                if (e.status) {
                    let e = l ? .book ? ? {
                            status: ("book" === n || "all" === n) && c.fetch ? c.fetch : "idle",
                            queued: 0,
                            fetching: 0,
                            completed: 0
                        },
                        s = l ? .lastPrice ? ? {
                            status: ("last-price" === n || "all" === n) && c.fetch ? c.fetch : "idle",
                            queued: 0,
                            fetching: 0,
                            completed: 0
                        },
                        r = {
                            book: { ...e,
                                ...("book" === n || "minified" === n || "all" === n) && {
                                    status: c.fetch ? ? "idle",
                                    ..."queued" === c.fetch && {
                                        queued: i
                                    },
                                    ..."fetching" === c.fetch && {
                                        fetching: i
                                    },
                                    ..."success" === c.fetch && {
                                        completed: i
                                    }
                                }
                            },
                            lastPrice: { ...s,
                                ...("last-price" === n || "all" === n) && {
                                    status: c.fetch ? ? "idle",
                                    ..."queued" === c.fetch && {
                                        queued: i
                                    },
                                    ..."fetching" === c.fetch && {
                                        fetching: i
                                    },
                                    ..."success" === c.fetch && {
                                        completed: i
                                    }
                                }
                            }
                        };
                    t.set(a, r), h = r.lastPrice.status, d = r.book.status
                } else h = l ? .lastPrice.status ? ? "idle", d = l ? .book.status ? ? "idle";
                if (c.poll) {
                    let e = new Set(Array.from(u ? .book ? ? [])),
                        t = new Set(Array.from(u ? .bestPrices ? ? []));
                    "start" === c.poll && ("book" === n && (e.add(o), p = !0), "minified" === n && (t.add(o), g = !0)), "stop" === c.poll && ("book" === n && (e.delete(o), p = !1), "minified" === n && (t.delete(o), g = !1)), 0 === e.size && s.delete(a), 0 === t.size && s.delete(a), (e.size > 0 || t.size > 0) && s.set(a, {
                        book: e,
                        bestPrices: t
                    })
                } else p = (u ? .book.size ? ? 0) > 0, g = (u ? .bestPrices.size ? ? 0) > 0;
                r.push({
                    assetId: a,
                    book: d,
                    lastPrice: h,
                    polling: p || g
                })
            }), r);
            this.onFetchStatusChange && this.onFetchStatusChange(a)
        }
        onBookEvents = null;
        onWebsocketStateChange = null;
        logger = null;
        onFetchStatusChange = null
    }
    var Q = e.i(552470),
        E = e.i(631222);
    Q.expose(new L({
        clobRestApiUrl: E.CLOB_API_URL,
        clobWsApiUrl: E.WEBSOCKET_MARKET
    })), e.s([], 451742)
}]);

//# debugId=63422170-5fdd-ac05-2d95-9a1e0df60ff7