import { c as stringEnum, i as jsonResult, o as readNumberParam, r as errorResult, s as readStringParam, u as Type } from "../../tool-helpers-CVAcqiCy.mjs";
import { getWalletState, requirePublicClient, requireWalletClient } from "../services/walletconnect-service.mjs";
import { getCredentialVault } from "../services/credential-vault.mjs";
import { guardedFetch } from "../services/endpoint-allowlist.mjs";
import { checkBalance } from "../services/safety-service.mjs";
//#region extensions/crypto/src/tools/clawnch-info.ts
/**
* Clawnch Info Tool — On-chain reads, portfolio, vault claims, agent management.
*
* Consolidates read-heavy operations that were previously missing:
*   - token_info: On-chain token details via ClawnchReader
*   - portfolio: Token discovery + portfolio view via ClawnchPortfolio
*   - vault_claim: Check/claim vested vault allocations
*   - agent_register: Register as a verified Clawnch agent
*   - agent_status: Check agent registration status
*   - platform_stats: Clawnch platform statistics
*   - list_tokens: List tokens deployed through Clawnch
*
* Most actions are read-only (no gas). vault_claim and agent_register
* are write operations that go through ClawnchConnect.
*/
const CLAWNCH_API_URL = process.env.CLAWNCHER_API_URL || "https://clawn.ch";
const ClawnchInfoSchema = Type.Object({
	action: stringEnum([
		"token_info",
		"portfolio",
		"vault_claim",
		"agent_register",
		"agent_status",
		"platform_stats",
		"list_tokens"
	], { description: "token_info: on-chain token details. portfolio: discovered tokens + values. vault_claim: check/claim vault allocation. agent_register: register as Clawnch agent. agent_status: check registration. platform_stats: Clawnch stats. list_tokens: deployed tokens." }),
	token: Type.Optional(Type.String({ description: "Token contract address (for token_info, vault_claim)." })),
	address: Type.Optional(Type.String({ description: "Wallet address (for portfolio, agent_status). Defaults to connected wallet." })),
	agent_name: Type.Optional(Type.String({ description: "Agent display name (for agent_register)." })),
	agent_description: Type.Optional(Type.String({ description: "Agent description (for agent_register)." })),
	page: Type.Optional(Type.Number({ description: "Page number for list_tokens (default: 1)." })),
	page_size: Type.Optional(Type.Number({ description: "Items per page for list_tokens (default: 20)." }))
});
function createClawnchInfoTool() {
	return {
		name: "clawnch_info",
		label: "Clawnch Info",
		ownerOnly: true,
		description: "On-chain token information, portfolio discovery, vault claims, and Clawnch platform data. Most actions are read-only (no gas cost). vault_claim and agent_register are write operations requiring a connected wallet.",
		parameters: ClawnchInfoSchema,
		execute: async (_toolCallId, args) => {
			const params = args;
			const action = readStringParam(params, "action", { required: true });
			try {
				switch (action) {
					case "token_info": return handleTokenInfo(params);
					case "portfolio": return handlePortfolio(params);
					case "vault_claim": return handleVaultClaim(params);
					case "agent_register": return handleAgentRegister(params);
					case "agent_status": return handleAgentStatus(params);
					case "platform_stats": return handlePlatformStats();
					case "list_tokens": return handleListTokens(params);
					default: return errorResult(`Unknown action: ${action}`);
				}
			} catch (err) {
				return errorResult(`Clawnch info failed: ${err instanceof Error ? err.message : String(err)}`);
			}
		}
	};
}
async function handleTokenInfo(params) {
	const tokenAddress = readStringParam(params, "token", { required: true });
	let publicClient;
	try {
		publicClient = requirePublicClient();
	} catch {
		return errorResult("Public client not initialized. Connect a wallet first or ensure the wallet service is started.");
	}
	const { ClawnchReader } = await import("../../dist-CXAY4yCt.mjs");
	const details = await new ClawnchReader({
		publicClient,
		network: "mainnet"
	}).getTokenDetails(tokenAddress);
	if (!details) return errorResult(`Token not found or unreadable: ${tokenAddress}`);
	return jsonResult({
		address: tokenAddress,
		name: details.name,
		symbol: details.symbol,
		decimals: details.decimals,
		totalSupply: details.totalSupply?.toString(),
		owner: details.owner,
		isClawnchToken: details.isClawnchToken ?? false,
		creator: details.creator,
		launchDate: details.launchDate,
		liquidityLocked: details.liquidityLocked,
		taxBuy: details.taxBuy,
		taxSell: details.taxSell,
		maxWallet: details.maxWallet,
		vault: details.vault ? {
			hasVault: true,
			lockupEndTime: details.vault.lockupEndTime,
			vestingDuration: details.vault.vestingDuration,
			totalAllocation: details.vault.totalAllocation?.toString()
		} : { hasVault: false }
	});
}
async function handlePortfolio(params) {
	const state = getWalletState();
	const address = readStringParam(params, "address") ?? state.address;
	if (!address) return errorResult("No address provided and no wallet connected.");
	let publicClient;
	try {
		publicClient = requirePublicClient();
	} catch {
		return errorResult("Public client not initialized. Connect a wallet first or ensure the wallet service is started.");
	}
	const { ClawnchPortfolio } = await import("../../dist-CXAY4yCt.mjs");
	const discovered = await new ClawnchPortfolio({
		publicClient,
		network: "mainnet"
	}).discoverTokens(address);
	const tokens = Array.isArray(discovered) ? discovered : discovered?.tokens ?? [];
	if (!tokens || tokens.length === 0) return jsonResult({
		address,
		totalValueUsd: 0,
		tokens: [],
		message: "No tokens discovered for this address."
	});
	if (typeof tokens[0] === "object" && tokens[0].valueUsd !== void 0) {
		const sorted = [...tokens].sort((a, b) => (b.valueUsd ?? 0) - (a.valueUsd ?? 0));
		return jsonResult({
			address,
			ethBalance: discovered.ethBalance?.toString(),
			ethValueUsd: discovered.ethValueUsd,
			totalValueUsd: discovered.totalValueUsd,
			tokenCount: sorted.length,
			tokens: sorted.map((t) => ({
				address: t.address,
				symbol: t.symbol,
				name: t.name,
				balance: t.balanceFormatted,
				priceUsd: t.priceUsd,
				valueUsd: t.valueUsd,
				isClawnchToken: t.isClawnchToken ?? false
			}))
		});
	}
	return jsonResult({
		address,
		tokenCount: tokens.length,
		tokenAddresses: tokens,
		message: "Token addresses discovered. Use token_info action to get details for each."
	});
}
async function handleVaultClaim(params) {
	const tokenAddress = readStringParam(params, "token", { required: true });
	if (!getWalletState().connected) return errorResult("No wallet connected. Use clawnchconnect tool to connect first.");
	const publicClient = requirePublicClient();
	const { ClawnchReader } = await import("../../dist-CXAY4yCt.mjs");
	const vault = await new ClawnchReader({
		publicClient,
		network: "mainnet"
	}).getVaultAllocation(tokenAddress);
	if (!vault) return jsonResult({
		token: tokenAddress,
		hasVault: false,
		message: "No vault allocation exists for this token."
	});
	const { formatEther } = await import("../../_esm-BrzUp3yp.mjs").then((n) => n.t);
	const status = {
		token: tokenAddress,
		hasVault: true,
		totalAllocation: formatEther(vault.amountTotal),
		claimed: formatEther(vault.amountClaimed),
		available: formatEther(vault.amountAvailable),
		percentVested: vault.percentVested,
		isUnlocked: vault.isUnlocked,
		isFullyVested: vault.isFullyVested
	};
	if (!vault.isUnlocked) {
		status.lockupEnds = (/* @__PURE__ */ new Date(Number(vault.lockupEndTime) * 1e3)).toISOString();
		status.message = "Vault is still locked. Cannot claim yet.";
		return jsonResult(status);
	}
	if (vault.amountAvailable === 0n) {
		status.message = vault.isFullyVested ? "Fully vested and fully claimed. Nothing left." : "No tokens available to claim yet. Vesting in progress.";
		return jsonResult(status);
	}
	const safety = await checkBalance({ requiredEth: 0 });
	if (!safety.safe) {
		status.message = `Cannot claim: ${safety.blockers.join("; ")}`;
		return jsonResult(status);
	}
	const wallet = requireWalletClient();
	const { ClawncherClaimer } = await import("../../dist-CXAY4yCt.mjs");
	const result = await new ClawncherClaimer({
		wallet,
		publicClient,
		network: "mainnet"
	}).claimVault(tokenAddress);
	await result.wait();
	status.claimExecuted = true;
	status.txHash = result.txHash;
	status.amountClaimed = formatEther(vault.amountAvailable);
	status.message = `Successfully claimed ${formatEther(vault.amountAvailable)} tokens.`;
	return jsonResult(status);
}
async function handleAgentRegister(params) {
	const state = getWalletState();
	if (!state.connected) return errorResult("No wallet connected. Use clawnchconnect tool to connect first.");
	const agentName = readStringParam(params, "agent_name", { required: true });
	const agentDescription = readStringParam(params, "agent_description") ?? "";
	const apiKey = getCredentialVault().getSecret("clawnch.apiKey", "clawnch-info");
	if (!apiKey) return errorResult("CLAWNCH_API_KEY not set. Required for agent registration.");
	const wallet = requireWalletClient();
	const publicClient = requirePublicClient();
	const { ClawnchApiDeployer } = await import("../../dist-CXAY4yCt.mjs");
	new ClawnchApiDeployer({
		apiBaseUrl: CLAWNCH_API_URL,
		apiKey,
		wallet,
		publicClient
	});
	const result = await ClawnchApiDeployer.register({
		address: state.address,
		name: agentName,
		description: agentDescription,
		apiKey,
		apiBaseUrl: CLAWNCH_API_URL
	});
	return jsonResult({
		status: "registered",
		agentId: result.agentId,
		address: state.address,
		name: agentName,
		verified: result.verified
	});
}
async function handleAgentStatus(params) {
	const state = getWalletState();
	const address = readStringParam(params, "address") ?? state.address;
	if (!address) return errorResult("No address provided and no wallet connected.");
	const apiKey = getCredentialVault().getSecret("clawnch.apiKey", "clawnch-info");
	if (!apiKey) return errorResult("CLAWNCH_API_KEY not set. Required for agent status queries.");
	const apiBaseUrl = CLAWNCH_API_URL;
	try {
		const response = await guardedFetch(`${apiBaseUrl}/api/agents/${address}`, {
			headers: {
				"x-api-key": apiKey,
				Accept: "application/json"
			},
			signal: AbortSignal.timeout(15e3)
		});
		if (!response.ok) {
			if (response.status === 404) return jsonResult({
				address,
				registered: false,
				agentId: null,
				name: null,
				verified: false,
				registeredAt: null,
				tokenAddress: null
			});
			throw new Error(`API returned ${response.status}: ${await response.text()}`);
		}
		const agentStatus = await response.json();
		return jsonResult({
			address,
			registered: agentStatus.registeredAt != null,
			agentId: agentStatus.agentId,
			name: agentStatus.name,
			verified: agentStatus.verified,
			registeredAt: agentStatus.registeredAt,
			tokenAddress: agentStatus.tokenAddress
		});
	} catch (err) {
		return errorResult(`Failed to query agent status for ${address}: ${err instanceof Error ? err.message : String(err)}`);
	}
}
async function handlePlatformStats() {
	const apiUrl = CLAWNCH_API_URL;
	try {
		const response = await guardedFetch(`${apiUrl}/api/stats`, {
			headers: { Accept: "application/json" },
			signal: AbortSignal.timeout(15e3)
		});
		if (!response.ok) return errorResult(`Platform stats unavailable: HTTP ${response.status}`);
		const stats = await response.json();
		return jsonResult({
			platform: "Clawnch",
			totalTokensDeployed: stats.totalTokens,
			totalAgents: stats.totalAgents,
			totalVolumeUsd: stats.totalVolumeUsd,
			totalLiquidityUsd: stats.totalLiquidityUsd,
			activeTokens24h: stats.activeTokens24h,
			topTokens: stats.topTokens?.slice(0, 5)
		});
	} catch (err) {
		return errorResult(`Platform stats failed: ${err instanceof Error ? err.message : String(err)}`);
	}
}
async function handleListTokens(params) {
	const page = readNumberParam(params, "page") ?? 1;
	const pageSize = readNumberParam(params, "page_size") ?? 20;
	const apiUrl = CLAWNCH_API_URL;
	try {
		const response = await guardedFetch(`${apiUrl}/api/tokens?${new URLSearchParams({
			page: page.toString(),
			pageSize: pageSize.toString()
		})}`, {
			headers: { Accept: "application/json" },
			signal: AbortSignal.timeout(15e3)
		});
		if (!response.ok) return errorResult(`Token list unavailable: HTTP ${response.status}`);
		const data = await response.json();
		return jsonResult({
			page,
			pageSize,
			total: data.total,
			totalPages: Math.ceil(data.total / pageSize),
			tokens: (data.tokens ?? []).map((t) => ({
				address: t.address,
				name: t.name,
				symbol: t.symbol,
				creator: t.creator,
				launchDate: t.launchDate,
				priceUsd: t.priceUsd,
				marketCap: t.marketCapUsd,
				volume24h: t.volume24hUsd,
				holderCount: t.holderCount
			}))
		});
	} catch (err) {
		return errorResult(`Token list failed: ${err instanceof Error ? err.message : String(err)}`);
	}
}
//#endregion
export { createClawnchInfoTool };

//# sourceMappingURL=clawnch-info.mjs.map