import type { AgentProfile } from '../types' import { createPublicClient, http } from 'viem' import { baseSepolia } from 'viem/chains' const CACHE_TTL = 10 * 60 * 1000 // 10 minutes interface CachedBalance { balance: number // ETH balance in wei as a number (>0 means funded) fetchedAt: number } const balanceCache = new Map() function getRpcClient() { return createPublicClient({ chain: baseSepolia, transport: http(process.env.BASE_SEPOLIA_RPC_URL || 'https://sepolia.base.org'), }) } export async function refreshOnChainData(address: string): Promise { try { const client = getRpcClient() const raw = await client.getBalance({ address: address as `0x${string}` }) balanceCache.set(address, { balance: Number(raw), fetchedAt: Date.now() }) } catch { // On failure, keep old cached value (or leave absent — score will default to 0) } } export function onChainScore(agent: AgentProfile): number { const monthsOld = (Date.now() - agent.createdAt) / (30 * 24 * 60 * 60 * 1000) const age = Math.min(5, monthsOld * 0.5) const txCount = Math.min(5, Math.log10(Math.max(1, agent.totalRequests)) * 2.5) const diversity = Math.min(5, (agent.counterparties.length / 10) * 5) const cached = balanceCache.get(agent.address) const fresh = cached && (Date.now() - cached.fetchedAt) < CACHE_TTL const balance = fresh ? (cached.balance > 0 ? 5 : 0) : 0 return Math.min(20, age + txCount + diversity + balance) }