import { i as createPublicClient, n as http } from "./_esm-BKtdEVdT.mjs";
import { a as mainnet, c as base, i as optimism, l as arbitrum, n as sepolia, o as linea, r as polygon, s as baseSepolia } from "./chains-Bx4KIVmV.mjs";
import { s as isDelegationMode } from "./policy-types-Cspw-8fF.mjs";
import { t as getPolicyStore } from "./policy-store-Buwyt3oE.mjs";
import { a as getDelegatedPolicies, g as NATIVE_PERIOD_ENFORCER_ABI, h as LIMITED_CALLS_ENFORCER_ABI, m as ERC20_PERIOD_ENFORCER_ABI, p as DELEGATION_CONTRACTS } from "./delegation-service-BCFUCnJs.mjs";
import { n as getDelegationStore } from "./delegation-store-CLeIO327.mjs";
//#region extensions/crypto/src/services/delegation-monitor.ts
/**
* Delegation Monitor
*
* Tracks remaining budget, expiry, and health of active delegations.
* Emits warnings when:
*   - A delegation is within 20% of its spending limit
*   - A delegation expires within 24 hours
*   - A delegation has been revoked on-chain
*
* The monitor runs periodically via the event bus / heartbeat service,
* or can be invoked on-demand via /delegate status.
*/
/** Warn when usage exceeds this percentage of limit. */
const SPENDING_WARN_THRESHOLD = .8;
/** Critical when usage exceeds this percentage. */
const SPENDING_CRITICAL_THRESHOLD = .95;
/** Warn when delegation expires within this many seconds. */
const EXPIRY_WARN_SEC = 86400;
/** Critical when delegation expires within this many seconds. */
const EXPIRY_CRITICAL_SEC = 3600;
/**
* Check all active delegations for the given user and return health + alerts.
*/
function checkDelegations(userId) {
	if (!isDelegationMode()) return {
		health: [],
		alerts: []
	};
	const policies = getDelegatedPolicies(userId);
	const store = getPolicyStore();
	const health = [];
	const alerts = [];
	for (const policy of policies) {
		const info = policy.delegation;
		if (!info) continue;
		const h = buildHealth(policy, info, store, userId);
		health.push(h);
		const policyAlerts = generateAlerts(h, policy.name);
		alerts.push(...policyAlerts);
	}
	return {
		health,
		alerts
	};
}
function buildHealth(policy, info, store, userId) {
	let spentUsd = null;
	let limitUsd = null;
	let usagePercent = null;
	let expiresInSec = null;
	let actionsUsed = null;
	let actionsLimit = null;
	for (const rule of policy.rules) {
		if (rule.type === "spending_limit") {
			limitUsd = rule.maxAmountUsd;
			const periodMs = getPeriodMs(rule.period);
			spentUsd = store.getSpendInWindow(userId, policy.id, periodMs);
			usagePercent = limitUsd > 0 ? spentUsd / limitUsd * 100 : null;
		}
		if (rule.type === "rate_limit") {
			actionsLimit = rule.maxCalls;
			actionsUsed = store.getCallsInWindow(userId, policy.id, rule.periodMs);
		}
	}
	if (info.expiresAt) {
		const expiryMs = new Date(info.expiresAt).getTime();
		if (!isNaN(expiryMs)) {
			const remainingMs = expiryMs - Date.now();
			expiresInSec = Math.max(0, Math.floor(remainingMs / 1e3));
		}
	}
	return {
		policyId: policy.id,
		policyName: policy.name,
		chainId: info.chainId,
		status: info.status,
		spentUsd,
		limitUsd,
		usagePercent,
		expiresInSec,
		actionsUsed,
		actionsLimit
	};
}
function generateAlerts(h, policyName) {
	const alerts = [];
	if (h.status === "revoked") alerts.push({
		severity: "critical",
		policyId: h.policyId,
		policyName,
		chainId: h.chainId,
		message: `Delegation "${policyName}" has been revoked on-chain.`,
		action: "Create a new delegation with `/delegate create`."
	});
	if (h.status === "expired") alerts.push({
		severity: "critical",
		policyId: h.policyId,
		policyName,
		chainId: h.chainId,
		message: `Delegation "${policyName}" has expired.`,
		action: "Create a new delegation with `/delegate create`."
	});
	if (h.usagePercent !== null) {
		if (h.usagePercent >= SPENDING_CRITICAL_THRESHOLD * 100) alerts.push({
			severity: "critical",
			policyId: h.policyId,
			policyName,
			chainId: h.chainId,
			message: `Spending at ${h.usagePercent.toFixed(0)}% of limit for "${policyName}".`,
			action: "Consider increasing the limit or creating a new delegation."
		});
		else if (h.usagePercent >= SPENDING_WARN_THRESHOLD * 100) alerts.push({
			severity: "warning",
			policyId: h.policyId,
			policyName,
			chainId: h.chainId,
			message: `Spending at ${h.usagePercent.toFixed(0)}% of limit for "${policyName}".`,
			action: "Monitor spending or adjust limits."
		});
	}
	if (h.actionsUsed !== null && h.actionsLimit !== null && h.actionsLimit > 0) {
		const pct = h.actionsUsed / h.actionsLimit * 100;
		if (pct >= SPENDING_CRITICAL_THRESHOLD * 100) alerts.push({
			severity: "critical",
			policyId: h.policyId,
			policyName,
			chainId: h.chainId,
			message: `${h.actionsUsed}/${h.actionsLimit} actions used for "${policyName}".`,
			action: "Create a new delegation to continue operating."
		});
		else if (pct >= SPENDING_WARN_THRESHOLD * 100) alerts.push({
			severity: "warning",
			policyId: h.policyId,
			policyName,
			chainId: h.chainId,
			message: `${h.actionsUsed}/${h.actionsLimit} actions used for "${policyName}".`,
			action: "Approaching action limit."
		});
	}
	if (h.expiresInSec !== null) {
		if (h.expiresInSec <= EXPIRY_CRITICAL_SEC) alerts.push({
			severity: "critical",
			policyId: h.policyId,
			policyName,
			chainId: h.chainId,
			message: `Delegation "${policyName}" expires in ${formatDuration(h.expiresInSec)}.`,
			action: "Renew immediately with `/delegate create`."
		});
		else if (h.expiresInSec <= EXPIRY_WARN_SEC) alerts.push({
			severity: "warning",
			policyId: h.policyId,
			policyName,
			chainId: h.chainId,
			message: `Delegation "${policyName}" expires in ${formatDuration(h.expiresInSec)}.`,
			action: "Plan renewal with `/delegate create`."
		});
	}
	return alerts;
}
function formatDuration(seconds) {
	if (seconds <= 0) return "expired";
	if (seconds < 60) return `${seconds}s`;
	if (seconds < 3600) return `${Math.round(seconds / 60)}m`;
	if (seconds < 86400) return `${Math.round(seconds / 3600)}h`;
	return `${Math.round(seconds / 86400)}d`;
}
function getPeriodMs(period) {
	switch (period) {
		case "hourly": return 3600 * 1e3;
		case "daily": return 1440 * 60 * 1e3;
		case "weekly": return 10080 * 60 * 1e3;
		case "monthly": return 720 * 60 * 60 * 1e3;
		default: return 1440 * 60 * 1e3;
	}
}
const CHAIN_CONFIGS = {
	1: mainnet,
	8453: base,
	42161: arbitrum,
	10: optimism,
	137: polygon,
	59144: linea,
	11155111: sepolia,
	84532: baseSepolia
};
const _clientCache = /* @__PURE__ */ new Map();
function getMonitorClient(chainId) {
	let client = _clientCache.get(chainId);
	if (client) return client;
	const chain = CHAIN_CONFIGS[chainId];
	if (!chain) return null;
	client = createPublicClient({
		chain,
		transport: http()
	});
	_clientCache.set(chainId, client);
	return client;
}
/**
* Read on-chain enforcer state for a delegation.
*
* Queries the enforcer contracts that track cumulative usage:
* - NativeTokenPeriodTransferEnforcer.spentMap → ETH spent
* - ERC20PeriodTransferEnforcer.spentMap → ERC-20 spent
* - LimitedCallsEnforcer.callCounts → call count
*
* Compares on-chain state with local tracking and flags drift.
* All reads are best-effort: RPC errors are caught silently.
*/
async function readOnChainUsage(policyId, delegationHash, chainId, localHealth) {
	const client = getMonitorClient(chainId);
	const result = {
		nativeSpentWei: null,
		erc20Spent: null,
		callCount: null,
		driftDetected: false,
		queriedAt: Date.now()
	};
	if (!client || !delegationHash || delegationHash === "0x") return result;
	const dmAddr = DELEGATION_CONTRACTS.DelegationManager;
	try {
		const [spent] = await client.readContract({
			address: DELEGATION_CONTRACTS.NativeTokenPeriodTransferEnforcer,
			abi: NATIVE_PERIOD_ENFORCER_ABI,
			functionName: "spentMap",
			args: [dmAddr, delegationHash]
		});
		result.nativeSpentWei = spent;
	} catch {}
	try {
		const [spent] = await client.readContract({
			address: DELEGATION_CONTRACTS.ERC20PeriodTransferEnforcer,
			abi: ERC20_PERIOD_ENFORCER_ABI,
			functionName: "spentMap",
			args: [dmAddr, delegationHash]
		});
		result.erc20Spent = spent;
	} catch {}
	try {
		result.callCount = await client.readContract({
			address: DELEGATION_CONTRACTS.LimitedCallsEnforcer,
			abi: LIMITED_CALLS_ENFORCER_ABI,
			functionName: "callCounts",
			args: [dmAddr, delegationHash]
		});
	} catch {}
	result.driftDetected = false;
	const driftNotes = [];
	if (result.callCount !== null && localHealth.actionsUsed !== null) {
		const onChainCalls = Number(result.callCount);
		if (onChainCalls !== localHealth.actionsUsed) driftNotes.push(`calls: local=${localHealth.actionsUsed}, on-chain=${onChainCalls}`);
	}
	if (result.nativeSpentWei !== null && result.nativeSpentWei > 0n) {
		if (localHealth.spentUsd === null || localHealth.spentUsd === 0) driftNotes.push("on-chain shows ETH spending but local tracking is empty");
	}
	if (driftNotes.length > 0) {
		result.driftDetected = true;
		result.driftDetails = driftNotes.join("; ");
	}
	return result;
}
/**
* Enhanced health check that includes on-chain state reads.
* Slower than checkDelegations (makes RPC calls) — use for /delegate status detail.
*/
async function checkDelegationsWithOnChain(userId) {
	const base = checkDelegations(userId);
	if (base.health.length === 0) return base;
	const delegationStore = getDelegationStore();
	return {
		health: await Promise.all(base.health.map(async (h) => {
			if (!delegationStore.load(h.policyId)) return h;
			const hash = getDelegatedPolicies(userId).find((p) => p.id === h.policyId)?.delegation?.hash;
			if (!hash || hash === "0x") return h;
			try {
				const onChain = await readOnChainUsage(h.policyId, hash, h.chainId, h);
				h.onChain = onChain;
				if (onChain.driftDetected && onChain.driftDetails) base.alerts.push({
					severity: "warning",
					policyId: h.policyId,
					policyName: h.policyName,
					chainId: h.chainId,
					message: `Usage drift detected for "${h.policyName}": ${onChain.driftDetails}`,
					action: "Local tracking may be stale. On-chain enforcers have the authoritative state."
				});
			} catch {}
			return h;
		})),
		alerts: base.alerts
	};
}
//#endregion
export { checkDelegationsWithOnChain };

//# sourceMappingURL=delegation-monitor-D_r4Dy66.mjs.map