import { r as getTokenPriceUsd } from "./dexscreener-service-BSUiBkYa.mjs";
import { t as getRpcManager } from "./rpc-provider-BELb8v5m.mjs";
//#region extensions/crypto/src/services/gas-estimator.ts
/**
* Gas Estimation Service — real-time gas prices, cost estimation, and
* gas-inclusive swap comparison.
*
* Provides:
* - Multi-chain gas price tracking (fast/standard/slow)
* - Transaction cost estimation in USD
* - Gas-inclusive swap comparison (net output = output - gas cost)
* - EIP-1559 priority fee estimation
* - Historical gas trend tracking
*
* Uses on-chain RPC calls for accurate data, not third-party gas APIs.
*/
/** Typical gas limits for common EVM operations. */
const GAS_LIMITS = {
	ETH_TRANSFER: 21e3,
	ERC20_TRANSFER: 65e3,
	ERC20_APPROVE: 46e3,
	UNISWAP_V2_SWAP: 15e4,
	UNISWAP_V3_SWAP: 184e3,
	UNISWAP_V4_SWAP: 17e4,
	DEX_SWAP_SIMPLE: 2e5,
	DEX_SWAP_MULTI_HOP: 35e4,
	ADD_LIQUIDITY_V3: 5e5,
	REMOVE_LIQUIDITY_V3: 3e5,
	BRIDGE_DEPOSIT: 25e4,
	PERMIT2_APPROVE: 8e4,
	CONTRACT_DEPLOY: 2e6,
	NFT_MINT: 12e4
};
const NATIVE_TOKEN = {
	1: "ETH",
	8453: "ETH",
	42161: "ETH",
	10: "ETH",
	137: "MATIC"
};
const CHAIN_NAMES = {
	1: "ethereum",
	8453: "base",
	42161: "arbitrum",
	10: "optimism",
	137: "polygon"
};
var GasEstimator = class {
	config;
	cache = /* @__PURE__ */ new Map();
	constructor(config = {}) {
		this.config = {
			blockSamples: config.blockSamples ?? 5,
			cacheTtlMs: config.cacheTtlMs ?? 12e3
		};
	}
	/**
	* Get current gas prices for a chain (with caching).
	* Uses EIP-1559 fee history for accurate priority fee estimation.
	*/
	async getGasPrice(chainId = 8453) {
		const cached = this.cache.get(chainId);
		if (cached && Date.now() < cached.expiresAt) return cached.gasPrice;
		const client = await getRpcManager().getClient(chainId);
		const [feeHistory, nativePrice] = await Promise.all([client.getFeeHistory({
			blockCount: this.config.blockSamples,
			rewardPercentiles: [
				10,
				50,
				90
			]
		}).catch(() => null), this.getNativeTokenPrice(chainId)]);
		let baseFee;
		let slow;
		let standard;
		let fast;
		if (feeHistory?.baseFeePerGas?.length) {
			const latestBaseFee = feeHistory.baseFeePerGas[feeHistory.baseFeePerGas.length - 1];
			baseFee = Number(latestBaseFee) / 1e9;
			const rewards = feeHistory.reward ?? [];
			if (rewards.length > 0) {
				slow = this.averageReward(rewards, 0);
				standard = this.averageReward(rewards, 1);
				fast = this.averageReward(rewards, 2);
			} else {
				slow = .01;
				standard = .05;
				fast = .1;
			}
		} else {
			const gasPrice = await client.getGasPrice();
			baseFee = Number(gasPrice) / 1e9;
			slow = 0;
			standard = 0;
			fast = baseFee * .1;
		}
		const gasPrice = {
			baseFee: Math.round(baseFee * 1e3) / 1e3,
			slow: Math.round(slow * 1e3) / 1e3,
			standard: Math.round(standard * 1e3) / 1e3,
			fast: Math.round(fast * 1e3) / 1e3,
			totalSlow: Math.round((baseFee + slow) * 1e3) / 1e3,
			totalStandard: Math.round((baseFee + standard) * 1e3) / 1e3,
			totalFast: Math.round((baseFee + fast) * 1e3) / 1e3,
			nativeTokenPriceUsd: nativePrice,
			chain: CHAIN_NAMES[chainId] ?? String(chainId),
			chainId,
			timestamp: Date.now()
		};
		this.cache.set(chainId, {
			gasPrice,
			expiresAt: Date.now() + this.config.cacheTtlMs
		});
		return gasPrice;
	}
	/**
	* Estimate the gas cost for a specific operation in USD.
	*/
	async estimateCost(operation, chainId = 8453) {
		const gasUnits = typeof operation === "number" ? operation : GAS_LIMITS[operation] ?? 2e5;
		const opName = typeof operation === "string" ? operation : `custom (${operation} gas)`;
		const gas = await this.getGasPrice(chainId);
		const costSlowNative = gas.totalSlow * gasUnits / 1e9;
		const costStdNative = gas.totalStandard * gasUnits / 1e9;
		const costFastNative = gas.totalFast * gasUnits / 1e9;
		return {
			gasUnits,
			costSlowUsd: Math.round(costSlowNative * gas.nativeTokenPriceUsd * 1e4) / 1e4,
			costStandardUsd: Math.round(costStdNative * gas.nativeTokenPriceUsd * 1e4) / 1e4,
			costFastUsd: Math.round(costFastNative * gas.nativeTokenPriceUsd * 1e4) / 1e4,
			costNativeToken: Math.round(costStdNative * 1e8) / 1e8,
			operation: opName
		};
	}
	/**
	* Compare swap quotes with gas costs factored in.
	* Takes raw aggregator quotes and produces a gas-inclusive ranking.
	*/
	async compareSwapsGasInclusive(quotes, chainId = 8453) {
		const gas = await this.getGasPrice(chainId);
		const comparisons = quotes.map((q) => {
			const outputValueUsd = Number(q.buyAmount) / 10 ** q.buyTokenDecimals * q.buyTokenPriceUsd;
			const gasUnits = parseInt(q.gasEstimate ?? "200000", 10);
			const gasCostUsd = gas.totalStandard * gasUnits / 1e9 * gas.nativeTokenPriceUsd;
			return {
				aggregator: q.aggregator,
				outputAmount: q.buyAmount,
				outputValueUsd: Math.round(outputValueUsd * 100) / 100,
				gasCostUsd: Math.round(gasCostUsd * 1e4) / 1e4,
				netOutputUsd: Math.round((outputValueUsd - gasCostUsd) * 100) / 100,
				rank: 0
			};
		});
		comparisons.sort((a, b) => b.netOutputUsd - a.netOutputUsd);
		comparisons.forEach((c, i) => {
			c.rank = i + 1;
		});
		return comparisons;
	}
	/**
	* Get gas cost estimates for common operations on a chain.
	* Useful for the `/gas` command or a setup screen.
	*/
	async getCommonCosts(chainId = 8453) {
		return {
			gasPrice: await this.getGasPrice(chainId),
			costs: await Promise.all([
				"ETH_TRANSFER",
				"ERC20_TRANSFER",
				"DEX_SWAP_SIMPLE",
				"DEX_SWAP_MULTI_HOP",
				"BRIDGE_DEPOSIT",
				"ADD_LIQUIDITY_V3"
			].map((op) => this.estimateCost(op, chainId)))
		};
	}
	/** Clear the gas price cache. */
	clearCache() {
		this.cache.clear();
	}
	averageReward(rewards, index) {
		const values = rewards.map((r) => Number(r[index] ?? 0n) / 1e9);
		return values.reduce((a, b) => a + b, 0) / values.length;
	}
	async getNativeTokenPrice(chainId) {
		const token = NATIVE_TOKEN[chainId] ?? "ETH";
		try {
			const { priceUsd } = await getTokenPriceUsd(token, CHAIN_NAMES[chainId] ?? "base");
			return priceUsd;
		} catch {
			return 0;
		}
	}
};
let _instance = null;
function getGasEstimator(config) {
	if (!_instance) _instance = new GasEstimator(config);
	return _instance;
}
//#endregion
export { getGasEstimator };

//# sourceMappingURL=gas-estimator-BArMNHAU.mjs.map