import { n as __exportAll } from "./chunk-BEJ448es.mjs";
import { t as getCredentialVault } from "./credential-vault-UHPbPQ5Y.mjs";
import { r as guardedFetch } from "./endpoint-allowlist-C4ojr3jY.mjs";
import { a as BankrServerError, i as BankrReadOnlyError, n as BankrAuthError, r as BankrRateLimitError, t as BankrAccessError } from "./bankr-types-E81UZ9-c.mjs";
//#region extensions/crypto/src/services/bankr-api.ts
/**
* Bankr Agent API Client — shared client for all Bankr Agent API calls.
*
* Every tool and service that talks to api.bankr.bot uses this module.
* Handles authentication, error mapping, and job polling.
*
* Base URL: https://api.bankr.bot
* Auth: X-API-Key header with bk_... key
*/
var bankr_api_exports = /* @__PURE__ */ __exportAll({
	bankrCancelJob: () => bankrCancelJob,
	bankrDeployToken: () => bankrDeployToken,
	bankrGet: () => bankrGet,
	bankrPollJob: () => bankrPollJob,
	bankrPost: () => bankrPost,
	bankrPrompt: () => bankrPrompt,
	bankrPromptAndPoll: () => bankrPromptAndPoll,
	bankrSign: () => bankrSign,
	getBankrApiKey: () => getBankrApiKey,
	getBankrBalances: () => getBankrBalances,
	getBankrUserInfo: () => getBankrUserInfo,
	hasBankrApi: () => hasBankrApi
});
const BANKR_API = "https://api.bankr.bot";
const DEFAULT_POLL_INTERVAL_MS = 2e3;
const DEFAULT_POLL_TIMEOUT_MS = 12e4;
function getBankrApiKey() {
	return getCredentialVault().getSecret("bankr.apiKey", "bankr-api");
}
function hasBankrApi() {
	return !!getBankrApiKey();
}
function requireBankrApiKey() {
	const key = getBankrApiKey();
	if (!key) throw new BankrAuthError("BANKR_API_KEY not set. Connect via /connect_bankr or set the env var.");
	return key;
}
async function handleResponse(res) {
	if (res.ok) {
		const text = await res.text();
		if (!text) return null;
		try {
			return JSON.parse(text);
		} catch {
			return text;
		}
	}
	const body = await res.text().catch(() => "");
	switch (res.status) {
		case 401: throw new BankrAuthError();
		case 402: throw new BankrAuthError("LLM credits exhausted. Top up at bankr.bot/llm");
		case 403: {
			const lower = body.toLowerCase();
			if (lower.includes("read-only") || lower.includes("readonly")) throw new BankrReadOnlyError();
			throw new BankrAccessError();
		}
		case 429: {
			let resetAt = Date.now() + 6e4;
			let limit = 0;
			let used = 0;
			try {
				const parsed = JSON.parse(body);
				resetAt = parsed.resetAt ?? resetAt;
				limit = parsed.limit ?? 0;
				used = parsed.used ?? 0;
			} catch {}
			throw new BankrRateLimitError(resetAt, limit, used);
		}
		default:
			if (res.status >= 500) throw new BankrServerError(res.status, body || "Bankr API server error");
			throw new Error(`Bankr API error ${res.status}: ${body}`);
	}
}
const BANKR_REQUEST_TIMEOUT_MS = 3e4;
async function bankrGet(path) {
	const key = requireBankrApiKey();
	return handleResponse(await guardedFetch(`${BANKR_API}${path}`, {
		method: "GET",
		headers: {
			"X-API-Key": key,
			"Content-Type": "application/json"
		},
		signal: AbortSignal.timeout(BANKR_REQUEST_TIMEOUT_MS)
	}));
}
async function bankrPost(path, body) {
	const key = requireBankrApiKey();
	return handleResponse(await guardedFetch(`${BANKR_API}${path}`, {
		method: "POST",
		headers: {
			"X-API-Key": key,
			"Content-Type": "application/json"
		},
		body: JSON.stringify(body),
		signal: AbortSignal.timeout(BANKR_REQUEST_TIMEOUT_MS)
	}));
}
async function getBankrUserInfo() {
	const raw = await bankrGet("/agent/me");
	return {
		wallets: raw.wallets ?? [],
		bankrClub: raw.bankrClub ?? false,
		socialAccounts: raw.socialAccounts ?? [],
		refCode: raw.refCode
	};
}
async function getBankrBalances(chains) {
	const raw = await bankrGet(`/agent/balances${chains?.length ? `?chains=${chains.join(",")}` : ""}`);
	const normalizedChains = [];
	let grandTotal = 0;
	if (raw.balances) for (const [chainName, chainData] of Object.entries(raw.balances)) {
		const tokens = (chainData.tokenBalances ?? []).map((entry) => ({
			symbol: entry.token?.baseToken?.symbol ?? "UNKNOWN",
			name: entry.token?.baseToken?.name ?? "Unknown",
			address: entry.address ?? entry.token?.baseToken?.address ?? "",
			balance: entry.token?.balance ?? 0,
			balanceUsd: entry.token?.balanceUSD ?? 0,
			price: entry.token?.baseToken?.price ?? 0,
			decimals: entry.token?.baseToken?.decimals ?? 18
		}));
		const totalUsd = parseFloat(chainData.total ?? "0");
		grandTotal += totalUsd;
		normalizedChains.push({
			chain: chainName,
			nativeBalance: chainData.nativeBalance ?? "0",
			nativeBalanceUsd: parseFloat(chainData.nativeUsd ?? "0"),
			tokens,
			totalUsd
		});
	}
	return {
		chains: normalizedChains,
		totalUsd: grandTotal
	};
}
async function bankrPrompt(prompt, threadId) {
	const body = { prompt };
	if (threadId) body.threadId = threadId;
	return bankrPost("/agent/prompt", body);
}
/**
* Poll a Bankr job until it completes or fails.
* Default: poll every 2s, timeout after 120s.
*/
async function bankrPollJob(jobId, timeoutMs = DEFAULT_POLL_TIMEOUT_MS, intervalMs = DEFAULT_POLL_INTERVAL_MS) {
	const deadline = Date.now() + timeoutMs;
	while (Date.now() < deadline) {
		const result = await bankrGet(`/agent/job/${jobId}`);
		if (result.status === "completed" || result.status === "failed" || result.status === "cancelled") return result;
		await new Promise((resolve) => setTimeout(resolve, intervalMs));
	}
	try {
		await bankrCancelJob(jobId);
	} catch {}
	return {
		jobId,
		status: "failed",
		error: `Job timed out after ${Math.round(timeoutMs / 1e3)}s. The operation may still be processing on Bankr's side.`
	};
}
/**
* Submit a prompt and poll until completion. Convenience wrapper.
*/
async function bankrPromptAndPoll(prompt, opts) {
	const { jobId, threadId } = await bankrPrompt(prompt, opts?.threadId);
	const result = await bankrPollJob(jobId, opts?.timeoutMs);
	result.threadId = threadId;
	return result;
}
async function bankrCancelJob(jobId) {
	await bankrPost(`/agent/job/${jobId}/cancel`, {});
}
async function bankrSign(req) {
	return bankrPost("/agent/sign", req);
}
async function bankrDeployToken(opts) {
	return bankrPost("/token-launches/deploy", opts);
}
//#endregion
export { hasBankrApi as n, bankr_api_exports as t };

//# sourceMappingURL=bankr-api-ClsXaFmq.mjs.map