"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CloseOutWumbo = exports.Recoup = exports.TokenHandler = void 0;
//@ts-ignore
const BrowserOnly_1 = __importDefault(require("@docusaurus/BrowserOnly"));
const react_1 = __importStar(require("react"));
const wallet_adapter_react_1 = require("@solana/wallet-adapter-react");
const wallet_adapter_react_ui_1 = require("@solana/wallet-adapter-react-ui");
const react_2 = require("@strata-foundation/react");
const spl_token_bonding_1 = require("@strata-foundation/spl-token-bonding");
const react_3 = require("@strata-foundation/react");
//@ts-ignore
const styles_module_css_1 = __importDefault(require("./styles.module.css"));
const wallet_adapter_base_1 = require("@solana/wallet-adapter-base");
const spl_token_1 = require("@solana/spl-token");
const react_4 = require("@chakra-ui/react");
const closeOutWumboSubmit_1 = require("./closeOutWumboSubmit");
const OPEN_COLLECTIVE = "3cYa5WvT2bgXSLxxu9XDJSHV3x5JZGM91Nc3B7jYhBL7";
const MainnetGuard = ({ children = null }) => {
    const { endpoint, setClusterOrEndpoint } = (0, react_3.useEndpoint)();
    if (endpoint.includes("devnet")) {
        return (react_1.default.createElement("div", { className: styles_module_css_1.default.container },
            react_1.default.createElement("h3", null, "Recoup SOL from Wumbo"),
            react_1.default.createElement("button", { onClick: () => {
                    setClusterOrEndpoint(wallet_adapter_base_1.WalletAdapterNetwork.Mainnet);
                }, className: "white button button--primary" }, "Switch to Mainnet")));
    }
    return children;
};
exports.TokenHandler = react_1.default.memo(({ token, setAmountByToken }) => {
    var _a, _b;
    const { publicKey: tokenBondingKey, targetMint } = token.tokenBonding;
    const unixTime = (0, react_2.useSolanaUnixTime)();
    const { pricing, loading: loadingPricing } = (0, react_2.useBondingPricing)(tokenBondingKey);
    const solAmount = pricing === null || pricing === void 0 ? void 0 : pricing.swap((0, spl_token_bonding_1.toNumber)(token.account.amount, token.mint), targetMint, spl_token_1.NATIVE_MINT, true, unixTime);
    (0, react_1.useEffect)(() => {
        if (solAmount) {
            setAmountByToken(token, solAmount);
        }
    }, [solAmount, setAmountByToken]);
    return (react_1.default.createElement(react_4.Box, null,
        react_1.default.createElement(react_4.Stack, { direction: "row", spacing: 4, align: "center" },
            react_1.default.createElement(react_4.Avatar, { src: token.image, size: "sm" }),
            react_1.default.createElement(react_4.Stack, { direction: "column", spacing: 0, fontSize: "sm" },
                react_1.default.createElement(react_4.Text, { fontWeight: 600 }, (_b = (_a = token.metadata) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.name),
                react_1.default.createElement(react_4.Text, { color: "gray.500" },
                    solAmount,
                    " SOL")))));
});
const Recoup = () => {
    const { connected, publicKey } = (0, wallet_adapter_react_1.useWallet)();
    const { tokenBondingSdk, loading: sdkLoading } = (0, react_2.useStrataSdks)();
    const { handleErrors } = (0, react_2.useErrorHandler)();
    const [amountsByToken, setAmountsByToken] = (0, react_1.useState)({});
    const [status, setStatus] = (0, react_1.useState)(null);
    const [isCalculatingTokens, setIsCalculatingTokens] = (0, react_1.useState)(true);
    const openCollectiveKey = (0, react_2.usePublicKey)(OPEN_COLLECTIVE);
    const { info: openCollective } = (0, react_2.useCollective)(openCollectiveKey);
    const { data: tokens, loading: loading1, error, } = (0, react_2.useUserTokensWithMeta)(publicKey || undefined);
    const setAmountByToken = (0, react_1.useCallback)((token, amount) => {
        if (token && amount) {
            setAmountsByToken((old) => (Object.assign(Object.assign({}, old), { [token.publicKey.toBase58()]: amount })));
        }
    }, []);
    const open = (0, react_1.useMemo)(() => tokens.find(({ account }) => account.mint.equals(openCollective.mint)), [tokens]);
    const hasOpenAmount = (0, react_1.useMemo)(() => open && (0, spl_token_bonding_1.toNumber)(open.account.amount, open.mint) > 0, [open]);
    const openCollectiveTokens = (0, react_1.useMemo)(() => tokens.filter((token) => !!token.tokenRef &&
        token.tokenRef.collective.equals(openCollectiveKey) &&
        (0, spl_token_bonding_1.toNumber)(token.account.amount, token.mint) > 0), [tokens]);
    (0, react_1.useEffect)(() => {
        if (Object.values(amountsByToken).length ===
            (openCollectiveTokens === null || openCollectiveTokens === void 0 ? void 0 : openCollectiveTokens.length) + (hasOpenAmount ? 1 : 0)) {
            setIsCalculatingTokens(false);
        }
    }, [amountsByToken, hasOpenAmount, openCollectiveTokens]);
    handleErrors(error);
    const handleSubmit = (0, react_1.useCallback)(() => {
        (0, closeOutWumboSubmit_1.closeOutWumboSubmit)({
            tokenBondingSdk,
            tokens: hasOpenAmount
                ? [open, ...openCollectiveTokens]
                : openCollectiveTokens,
            expectedOutputAmountByToken: amountsByToken,
            setStatus,
        });
    }, [open, hasOpenAmount, openCollectiveTokens, amountsByToken]);
    const loading = sdkLoading || loading1 || isCalculatingTokens;
    const connectedLoading = connected && publicKey && loading;
    const connectedNotLoading = !loading && connected && publicKey;
    const isSuccessful = status == "successful";
    const isOrphaned = status == "orphaned";
    return (react_1.default.createElement("div", { className: styles_module_css_1.default.container },
        react_1.default.createElement("h3", null, "Recoup SOL from Wumbo"),
        !connected && (react_1.default.createElement(wallet_adapter_react_ui_1.WalletModalProvider, null,
            react_1.default.createElement(wallet_adapter_react_ui_1.WalletMultiButton, null))),
        connectedLoading && react_1.default.createElement("span", null, "Loading..."),
        connectedNotLoading &&
            !(hasOpenAmount || openCollectiveTokens.length) && (react_1.default.createElement("span", null, "No tokens relating to Wumbo/OPEN found. Make sure you have the wallet that you used with Wumbo/OPEN, then refresh this page.")),
        error && react_1.default.createElement("span", { style: { color: "red" } }, error.toString()),
        connectedNotLoading && !isSuccessful && !isOrphaned && (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement(react_4.SimpleGrid, { columns: { base: 1, md: 2 }, gap: 2 },
                hasOpenAmount && (react_1.default.createElement(exports.TokenHandler, { token: open, setAmountByToken: setAmountByToken })),
                openCollectiveTokens.map((token) => (react_1.default.createElement(exports.TokenHandler, { key: token.publicKey.toBase58(), token: token, setAmountByToken: setAmountByToken })))),
            react_1.default.createElement(react_4.Stack, { mt: 4, gap: 2 },
                react_1.default.createElement(react_4.Alert, { status: "info", variant: "subtle", flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center", height: "200px" },
                    react_1.default.createElement(react_4.AlertIcon, { boxSize: "30px", mr: 0 }),
                    react_1.default.createElement(react_4.AlertTitle, { mt: 4, mb: 1, fontSize: "lg" },
                        Object.values(amountsByToken).reduce((acc, amount) => acc + amount, 0),
                        " ",
                        "SOL"),
                    react_1.default.createElement(react_4.AlertDescription, { maxWidth: "sm" }, "Ready to be Recouped. Thanks for giving Wumbo a try. Our team greatly appreciated you and your early support!")),
                react_1.default.createElement(react_4.Button, { size: "lg", colorScheme: "orange", disabled: loading || status !== null, isLoading: status !== null, loadingText: status, onClick: handleSubmit, _hover: { cursor: "pointer" } }, "Recoup SOL")))),
        connectedNotLoading && isSuccessful && (react_1.default.createElement(react_4.Alert, { status: "success", variant: "subtle", flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center", height: "200px" },
            react_1.default.createElement(react_4.AlertIcon, { boxSize: "30px", mr: 0 }),
            react_1.default.createElement(react_4.AlertTitle, { mt: 4, mb: 1, fontSize: "lg" }, "SOL Recouped"),
            react_1.default.createElement(react_4.AlertDescription, { maxWidth: "sm" }, "Thanks for giving Wumbo a try. Our team greatly appreciated you and your early support!"))),
        connectedNotLoading && isOrphaned && (react_1.default.createElement(react_4.Alert, { status: "warning", variant: "subtle", flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center", height: "200px" },
            react_1.default.createElement(react_4.AlertIcon, { boxSize: "30px", mr: 0 }),
            react_1.default.createElement(react_4.AlertTitle, { mt: 4, mb: 1, fontSize: "lg" }, "Something went wrong"),
            react_1.default.createElement(react_4.AlertDescription, { maxWidth: "sm" }, "I looks like we were unable to recoup the full amount of SOL, one or multiple of the transactions may have failed. Please refresh and try again.")))));
};
exports.Recoup = Recoup;
const CloseOutWumbo = () => (react_1.default.createElement(BrowserOnly_1.default, { fallback: react_1.default.createElement("div", null, "...") }, () => (react_1.default.createElement(MainnetGuard, null,
    react_1.default.createElement(exports.Recoup, null)))));
exports.CloseOutWumbo = CloseOutWumbo;
//# sourceMappingURL=index.js.map