"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.disconnectWalletConnectSession = exports.getActiveWalletConnectSessions = exports.createWalletConnectSession = exports.createWalletConnectClient = void 0;
const sign_client_1 = require("@walletconnect/sign-client");
const defaultDappMetadata_js_1 = require("../../utils/defaultDappMetadata.js");
const constants_js_1 = require("../constants.js");
const session_store_js_1 = require("./session-store.js");
/**
 * Creates a new WalletConnect client for interacting with another application.
 * @param options - The options to use to create the WalletConnect client.
 *
 * @returns The WalletConnect client. Use this client to connect to a WalletConnect URI with {@link createWalletConnectSession}.
 * @example
 * ```ts
 * import { createWalletConnectClient } from "thirdweb/wallets/wallet-connect";
 *
 * const client = await createWalletConnectClient({
 *   wallet: wallet,
 *   client: client,
 * });
 * ```
 * Pass custom handlers:
 * ```ts
 * import { createWalletConnectClient } from "thirdweb/wallets/wallet-connect";
 *
 * const client = await createWalletConnectClient({
 *   wallet: wallet,
 *   client: client,
 *   requestHandlers: {
 *     eth_signTransaction: ({ transaction }) => {
 *       // handle transaction signing
 *     },
 *   },
 * });
 * ```
 * Pass connect and disconnect callbacks:
 * ```ts
 * import { createWalletConnectClient } from "thirdweb/wallets/wallet-connect";
 *
 * const client = await createWalletConnectClient({
 *   wallet: wallet,
 *   client: client,
 *   onConnect: (session) => {
 *     console.log("Connected to WalletConnect", session);
 *   },
 *   onDisconnect: (session) => {
 *     console.log("Disconnected from WalletConnect", session);
 *   },
 * });
 * ```
 * @wallets
 */
async function createWalletConnectClient(options) {
    const { wallet, requestHandlers, onConnect, onDisconnect } = options;
    (0, session_store_js_1.initializeSessionStore)({ clientId: options.client.clientId });
    const defaults = (0, defaultDappMetadata_js_1.getDefaultAppMetadata)();
    const walletConnectClient = await sign_client_1.SignClient.init({
        projectId: options.projectId ?? constants_js_1.DEFAULT_PROJECT_ID,
        metadata: {
            name: options.appMetadata?.name ?? defaults.name,
            url: options.appMetadata?.url ?? defaults.url,
            description: options.appMetadata?.description ?? defaults.description,
            icons: [options.appMetadata?.logoUrl ?? defaults.logoUrl],
        },
    });
    walletConnectClient.on("session_proposal", async (event) => {
        const { onSessionProposal } = await Promise.resolve().then(() => require("./session-proposal.js"));
        onSessionProposal({
            wallet,
            walletConnectClient,
            event,
            onConnect,
        });
    });
    walletConnectClient.on("session_request", async (event) => {
        const { fulfillRequest } = await Promise.resolve().then(() => require("./session-request.js"));
        console.log("Received session request", event);
        fulfillRequest({
            wallet,
            walletConnectClient,
            event,
            handlers: requestHandlers,
        });
    });
    walletConnectClient.on("session_event", async (_event) => {
        // TODO
    });
    walletConnectClient.on("session_ping", (_event) => {
        // TODO
    });
    walletConnectClient.on("session_delete", async (event) => {
        await disconnectWalletConnectSession({
            session: { topic: event.topic },
            walletConnectClient,
        });
    });
    // Disconnects can come from the user or the connected app, so we inject the callback to ensure its always triggered
    const _disconnect = walletConnectClient.disconnect;
    walletConnectClient.disconnect = async (args) => {
        const result = await _disconnect(args);
        if (onDisconnect) {
            disconnectHook({ topic: args.topic, onDisconnect });
        }
        return result;
    };
    return walletConnectClient;
}
exports.createWalletConnectClient = createWalletConnectClient;
/**
 * Initiates a new WalletConnect session for interacting with another application.
 * @param options - The options to use to create the WalletConnect session.
 * @example
 * ```ts
 * import { createWalletConnectClient, createWalletConnectSession } from "thirdweb/wallets/wallet-connect";
 *
 * const client = await createWalletConnectClient({
 *   wallet: wallet,
 *   client: client,
 * });
 *
 * const session = await createWalletConnectSession({
 *   walletConnectClient: client,
 *   uri: "wc:...",
 * });
 * ```
 * @wallets
 */
function createWalletConnectSession(options) {
    const { uri, walletConnectClient } = options;
    walletConnectClient.core.pairing.pair({ uri });
}
exports.createWalletConnectSession = createWalletConnectSession;
/**
 * Retrieves all active WalletConnect sessions.
 * @returns All active WalletConnect sessions.
 * @example
 * ```ts
 * import { getActiveWalletConnectSessions } from "thirdweb/wallets/wallet-connect";
 *
 * const sessions = await getActiveWalletConnectSessions();
 * ```
 * @wallets
 */
async function getActiveWalletConnectSessions() {
    return (0, session_store_js_1.getSessions)();
}
exports.getActiveWalletConnectSessions = getActiveWalletConnectSessions;
/**
 * Disconnects a WalletConnect session.
 * @param options - The options to use to disconnect the WalletConnect session.
 * @example
 * ```ts
 * import { disconnectWalletConnectSession } from "thirdweb/wallets/wallet-connect";
 *
 * await disconnectWalletConnectSession({
 *   session: { topic: "..." },
 *   walletConnectClient: wcClient,
 * });
 * ```
 * @wallets
 */
async function disconnectWalletConnectSession(options) {
    try {
        await options.walletConnectClient.disconnect({
            topic: options.session.topic,
            reason: {
                code: 6000,
                message: "Replaced by new session",
            },
        });
    }
    catch {
        // ignore, the session doesn't exist already
    }
    (0, session_store_js_1.removeSession)(options.session);
}
exports.disconnectWalletConnectSession = disconnectWalletConnectSession;
/**
 * @internal
 */
async function disconnectHook(options) {
    const { topic, onDisconnect } = options;
    const sessions = await (0, session_store_js_1.getSessions)();
    onDisconnect(sessions.find((s) => s.topic === topic) ?? {
        topic,
    });
}
//# sourceMappingURL=index.js.map