@hypurrquant/defi-cli 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/executor.ts","../../defi-core/src/types.ts","../../defi-core/src/error.ts","../../defi-core/src/json.ts","../../defi-core/src/erc20.ts","../../defi-core/src/provider.ts","../../defi-core/src/multicall.ts","../../defi-core/src/registry/chain.ts","../../defi-core/src/registry/protocol.ts","../../defi-core/src/registry/registry.ts","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/error.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/util.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/date.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/primitive.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/extract.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/struct.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/parse.js","../src/table.ts","../src/output.ts","../src/commands/status.ts","../src/agent.ts","../src/commands/schema.ts","../../defi-protocols/src/factory.ts","../../defi-protocols/src/dex/uniswap_v3.ts","../../defi-protocols/src/dex/uniswap_v2.ts","../../defi-protocols/src/dex/algebra_v3.ts","../../defi-protocols/src/dex/tick_math.ts","../../defi-protocols/src/dex/balancer_v3.ts","../../defi-protocols/src/dex/curve.ts","../../defi-protocols/src/dex/solidly.ts","../../defi-protocols/src/dex/thena_cl.ts","../../defi-protocols/src/dex/hybra_gauge.ts","../../defi-protocols/src/dex/woofi.ts","../../defi-protocols/src/dex/solidly_gauge.ts","../../defi-protocols/src/dex/masterchef.ts","../../defi-protocols/src/dex/merchant_moe_lb.ts","../../defi-protocols/src/dex/kittenswap_farming.ts","../../defi-protocols/src/lending/aave_v3.ts","../../defi-protocols/src/lending/aave_v2.ts","../../defi-protocols/src/lending/aave_oracle.ts","../../defi-protocols/src/lending/compound_v2.ts","../../defi-protocols/src/lending/compound_v3.ts","../../defi-protocols/src/lending/euler_v2.ts","../../defi-protocols/src/lending/morpho.ts","../../defi-protocols/src/cdp/felix.ts","../../defi-protocols/src/cdp/felix_oracle.ts","../../defi-protocols/src/vault/erc4626.ts","../../defi-protocols/src/liquid_staking/generic_lst.ts","../../defi-protocols/src/liquid_staking/sthype.ts","../../defi-protocols/src/liquid_staking/kinetiq.ts","../../defi-protocols/src/yield_source/pendle.ts","../../defi-protocols/src/yield_source/generic_yield.ts","../../defi-protocols/src/derivatives/hlp.ts","../../defi-protocols/src/derivatives/generic_derivatives.ts","../../defi-protocols/src/options/rysk.ts","../../defi-protocols/src/options/generic_options.ts","../../defi-protocols/src/nft/erc721.ts","../../defi-protocols/src/dex/dex_price.ts","../src/commands/dex.ts","../src/commands/gauge.ts","../src/commands/lending.ts","../src/commands/cdp.ts","../src/commands/staking.ts","../src/commands/vault.ts","../src/commands/yield.ts","../src/commands/portfolio.ts","../src/portfolio-tracker.ts","../src/commands/monitor.ts","../src/commands/alert.ts","../src/commands/scan.ts","../src/commands/arb.ts","../src/commands/positions.ts","../src/commands/price.ts","../src/commands/wallet.ts","../src/commands/token.ts","../src/commands/whales.ts","../src/commands/compare.ts","../src/commands/swap.ts","../src/commands/bridge.ts","../src/commands/nft.ts","../src/commands/farm.ts","../src/commands/farming.ts","../src/commands/setup.ts","../src/commands/lb.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { createRequire } from \"node:module\";\nimport { Executor } from \"./executor.js\";\nimport { parseOutputMode } from \"./output.js\";\nimport type { OutputMode } from \"./output.js\";\nimport { runAgent } from \"./agent.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\n\nconst _require = createRequire(import.meta.url);\nconst _pkg = _require(\"../package.json\") as { version: string };\n\nimport { registerStatus } from \"./commands/status.js\";\nimport { registerSchema } from \"./commands/schema.js\";\nimport { registerDex } from \"./commands/dex.js\";\nimport { registerGauge } from \"./commands/gauge.js\";\nimport { registerLending } from \"./commands/lending.js\";\nimport { registerCdp } from \"./commands/cdp.js\";\nimport { registerStaking } from \"./commands/staking.js\";\nimport { registerVault } from \"./commands/vault.js\";\nimport { registerYield } from \"./commands/yield.js\";\nimport { registerPortfolio } from \"./commands/portfolio.js\";\nimport { registerMonitor } from \"./commands/monitor.js\";\nimport { registerAlert } from \"./commands/alert.js\";\nimport { registerScan } from \"./commands/scan.js\";\nimport { registerArb } from \"./commands/arb.js\";\nimport { registerPositions } from \"./commands/positions.js\";\nimport { registerPrice } from \"./commands/price.js\";\nimport { registerWallet } from \"./commands/wallet.js\";\nimport { registerToken } from \"./commands/token.js\";\nimport { registerWhales } from \"./commands/whales.js\";\nimport { registerCompare } from \"./commands/compare.js\";\nimport { registerSwap } from \"./commands/swap.js\";\nimport { registerBridge } from \"./commands/bridge.js\";\nimport { registerNft } from \"./commands/nft.js\";\nimport { registerFarm } from \"./commands/farm.js\";\nimport { registerFarming } from \"./commands/farming.js\";\nimport { registerSetup } from \"./commands/setup.js\";\nimport { registerLB } from \"./commands/lb.js\";\n\nconst BANNER = `\n ██████╗ ███████╗███████╗██╗ ██████╗██╗ ██╗\n ██╔══██╗██╔════╝██╔════╝██║ ██╔════╝██║ ██║\n ██║ ██║█████╗ █████╗ ██║ ██║ ██║ ██║\n ██║ ██║██╔══╝ ██╔══╝ ██║ ██║ ██║ ██║\n ██████╔╝███████╗██║ ██║ ╚██████╗███████╗██║\n ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝╚══════╝╚═╝\n\n 2 chains · 23 protocols · by HypurrQuant\n\n Scan exploits, swap tokens, bridge assets, track whales,\n compare yields — all from your terminal.\n`;\n\nexport const program = new Command()\n .name(\"defi\")\n .description(\"DeFi CLI — Multi-chain DeFi toolkit\")\n .version(_pkg.version)\n .addHelpText(\"before\", BANNER)\n .option(\"--json\", \"Output as JSON\")\n .option(\"--ndjson\", \"Output as newline-delimited JSON\")\n .option(\"--fields <fields>\", \"Select specific output fields (comma-separated)\")\n .option(\"--chain <chain>\", \"Target chain\", \"hyperevm\")\n .option(\"--dry-run\", \"Dry-run mode (default, no broadcast)\", true)\n .option(\"--broadcast\", \"Actually broadcast the transaction\");\n\n// Helper: read global output mode from the root program options\nfunction getOutputMode(): OutputMode {\n const opts = program.opts<{\n json?: boolean;\n ndjson?: boolean;\n fields?: string;\n }>();\n return parseOutputMode(opts);\n}\n\n// Build executor from global options (lazy — must be called inside action handler, not at registration)\nfunction makeExecutor(): Executor {\n const opts = program.opts<{ broadcast?: boolean; chain?: string }>();\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(opts.chain ?? \"hyperevm\");\n return new Executor(!!opts.broadcast, chain.effectiveRpcUrl(), chain.explorer_url);\n}\n\n// Register all commands\nregisterStatus(program, getOutputMode);\nregisterSchema(program, getOutputMode);\nregisterDex(program, getOutputMode, makeExecutor);\nregisterGauge(program, getOutputMode, makeExecutor);\nregisterLending(program, getOutputMode, makeExecutor);\nregisterCdp(program, getOutputMode, makeExecutor);\nregisterStaking(program, getOutputMode, makeExecutor);\nregisterVault(program, getOutputMode, makeExecutor);\nregisterYield(program, getOutputMode, makeExecutor);\nregisterPortfolio(program, getOutputMode);\nregisterMonitor(program, getOutputMode);\nregisterAlert(program, getOutputMode);\nregisterScan(program, getOutputMode);\nregisterArb(program, getOutputMode, makeExecutor);\nregisterPositions(program, getOutputMode);\nregisterPrice(program, getOutputMode);\nregisterWallet(program, getOutputMode);\nregisterToken(program, getOutputMode, makeExecutor);\nregisterWhales(program, getOutputMode);\nregisterCompare(program, getOutputMode);\nregisterSwap(program, getOutputMode, makeExecutor);\nregisterBridge(program, getOutputMode);\nregisterNft(program, getOutputMode);\nregisterFarm(program, getOutputMode, makeExecutor);\nregisterFarming(program, getOutputMode, makeExecutor);\nregisterLB(program, getOutputMode, makeExecutor);\nregisterSetup(program);\n\n// Agent mode command\nprogram\n .command(\"agent\")\n .description(\"Agent mode: read JSON commands from stdin (for AI agents)\")\n .action(async () => {\n // Registry loading is not yet wired — stub for now\n const executor = makeExecutor();\n process.stderr.write(\"Agent mode: reading JSON commands from stdin...\\n\");\n // TODO: wire registry when registry loading is available in TS\n // await runAgent(registry, executor);\n process.stderr.write(\"Agent mode not yet fully implemented in TS port.\\n\");\n process.exit(1);\n });\n","import { createPublicClient, createWalletClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport { TxStatus } from \"@hypurrquant/defi-core\";\nimport type { ActionResult, DeFiTx } from \"@hypurrquant/defi-core\";\n\nconst ERC20_ABI = parseAbi([\n \"function allowance(address owner, address spender) external view returns (uint256)\",\n \"function approve(address spender, uint256 amount) external returns (bool)\",\n]);\n\n/** Gas buffer multiplier: 120% over estimated gas (20% headroom) */\nconst GAS_BUFFER_BPS = 12000n;\n\n/** Default max priority fee (tip) in wei — 20 gwei (safe for Mantle + EVM chains) */\nconst DEFAULT_PRIORITY_FEE_WEI = 20_000_000_000n;\n\n/** Max gas limit cap — Mantle uses high gas units (up to 5B for complex txs) */\nconst MAX_GAS_LIMIT = 5_000_000_000n; // 5B\n\nexport class Executor {\n readonly dryRun: boolean;\n readonly rpcUrl: string | undefined;\n readonly explorerUrl: string | undefined;\n\n constructor(broadcast: boolean, rpcUrl?: string, explorerUrl?: string) {\n this.dryRun = !broadcast;\n this.rpcUrl = rpcUrl;\n this.explorerUrl = explorerUrl;\n }\n\n /** Apply 20% buffer to a gas estimate */\n private static applyGasBuffer(gas: bigint): bigint {\n return (gas * GAS_BUFFER_BPS) / 10000n;\n }\n\n /**\n * Check allowance for a single token/spender pair and send an approve tx if needed.\n * Only called in broadcast mode (not dry-run).\n */\n private async checkAndApprove(\n token: Address,\n spender: Address,\n amount: bigint,\n owner: Address,\n publicClient: ReturnType<typeof createPublicClient>,\n walletClient: ReturnType<typeof createWalletClient>,\n ): Promise<void> {\n const allowance = await publicClient.readContract({\n address: token,\n abi: ERC20_ABI,\n functionName: \"allowance\",\n args: [owner, spender],\n });\n\n if (allowance >= amount) return;\n\n process.stderr.write(\n ` Approving ${amount} of ${token} for ${spender}...\\n`,\n );\n\n const approveData = encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [spender, amount],\n });\n\n const rpcUrl = this.rpcUrl!;\n const gasLimit = await (async () => {\n try {\n const estimated = await publicClient.estimateGas({\n to: token,\n data: approveData,\n account: owner,\n });\n const buffered = Executor.applyGasBuffer(estimated);\n return buffered > MAX_GAS_LIMIT ? MAX_GAS_LIMIT : buffered;\n } catch {\n return 80_000n;\n }\n })();\n\n const [maxFeePerGas, maxPriorityFeePerGas] = await this.fetchEip1559Fees(rpcUrl);\n\n const approveTxHash = await walletClient.sendTransaction({\n chain: null,\n account: walletClient.account!,\n to: token,\n data: approveData,\n gas: gasLimit > 0n ? gasLimit : undefined,\n maxFeePerGas: maxFeePerGas > 0n ? maxFeePerGas : undefined,\n maxPriorityFeePerGas: maxPriorityFeePerGas > 0n ? maxPriorityFeePerGas : undefined,\n });\n\n const approveTxUrl = this.explorerUrl\n ? `${this.explorerUrl}/tx/${approveTxHash}`\n : undefined;\n process.stderr.write(` Approve tx: ${approveTxHash}\\n`);\n if (approveTxUrl) process.stderr.write(` Explorer: ${approveTxUrl}\\n`);\n\n await publicClient.waitForTransactionReceipt({ hash: approveTxHash });\n process.stderr.write(\n ` Approved ${amount} of ${token} for ${spender}\\n`,\n );\n }\n\n /** Fetch EIP-1559 fee params from the network. Returns [maxFeePerGas, maxPriorityFeePerGas]. */\n private async fetchEip1559Fees(rpcUrl: string): Promise<[bigint, bigint]> {\n try {\n const client = createPublicClient({ transport: http(rpcUrl) });\n const gasPrice = await client.getGasPrice();\n let priorityFee = DEFAULT_PRIORITY_FEE_WEI;\n try {\n priorityFee = await client.estimateMaxPriorityFeePerGas();\n } catch {\n // fallback to default\n }\n const maxFee = gasPrice * 2n + priorityFee;\n return [maxFee, priorityFee];\n } catch {\n return [0n, 0n];\n }\n }\n\n /** Estimate gas dynamically with buffer, falling back to a hardcoded estimate */\n private async estimateGasWithBuffer(\n rpcUrl: string,\n tx: DeFiTx,\n from: `0x${string}`,\n ): Promise<bigint> {\n try {\n const client = createPublicClient({ transport: http(rpcUrl) });\n const estimated = await client.estimateGas({\n to: tx.to,\n data: tx.data,\n value: tx.value,\n account: from,\n });\n if (estimated > 0n) {\n const buffered = Executor.applyGasBuffer(estimated);\n return buffered > MAX_GAS_LIMIT ? MAX_GAS_LIMIT : buffered;\n }\n } catch {\n // fallback: apply buffer to the hint too\n if (tx.gas_estimate) {\n return Executor.applyGasBuffer(BigInt(tx.gas_estimate));\n }\n }\n return 0n;\n }\n\n /** Simulate a transaction via eth_call + eth_estimateGas */\n private async simulate(tx: DeFiTx): Promise<ActionResult> {\n const rpcUrl = this.rpcUrl;\n if (!rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL — cannot simulate. Set HYPEREVM_RPC_URL.\");\n }\n\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n const from: `0x${string}` = privateKey\n ? privateKeyToAccount(privateKey as `0x${string}`).address\n : \"0x0000000000000000000000000000000000000001\";\n\n // Check approvals before simulation\n if (tx.approvals && tx.approvals.length > 0) {\n const pendingApprovals: Array<{ token: string; spender: string; needed: string; current: string }> = [];\n for (const approval of tx.approvals) {\n try {\n const allowance = await client.readContract({\n address: approval.token,\n abi: ERC20_ABI,\n functionName: \"allowance\",\n args: [from as `0x${string}`, approval.spender],\n });\n if (allowance < approval.amount) {\n pendingApprovals.push({\n token: approval.token,\n spender: approval.spender,\n needed: approval.amount.toString(),\n current: allowance.toString(),\n });\n }\n } catch { /* skip check on error */ }\n }\n if (pendingApprovals.length > 0) {\n return {\n tx_hash: undefined,\n status: TxStatus.NeedsApproval,\n gas_used: tx.gas_estimate,\n description: tx.description,\n details: {\n to: tx.to,\n from,\n data: tx.data,\n value: tx.value.toString(),\n mode: \"simulated\",\n result: \"needs_approval\",\n pending_approvals: pendingApprovals,\n hint: \"Use --broadcast to auto-approve and execute\",\n },\n };\n }\n }\n\n try {\n await client.call({ to: tx.to, data: tx.data, value: tx.value, account: from });\n\n const gasEstimate = await this.estimateGasWithBuffer(rpcUrl, tx, from);\n const [maxFee, priorityFee] = await this.fetchEip1559Fees(rpcUrl);\n\n return {\n tx_hash: undefined,\n status: \"simulated\" as TxStatus,\n gas_used: gasEstimate > 0n ? Number(gasEstimate) : undefined,\n description: tx.description,\n details: {\n to: tx.to,\n from,\n data: tx.data,\n value: tx.value.toString(),\n gas_estimate: gasEstimate.toString(),\n max_fee_per_gas_gwei: (Number(maxFee) / 1e9).toFixed(4),\n max_priority_fee_gwei: (Number(priorityFee) / 1e9).toFixed(4),\n mode: \"simulated\",\n result: \"success\",\n },\n };\n } catch (e: unknown) {\n const errMsg = String(e);\n const revertReason = extractRevertReason(errMsg);\n\n return {\n tx_hash: undefined,\n status: \"simulation_failed\" as TxStatus,\n gas_used: tx.gas_estimate,\n description: tx.description,\n details: {\n to: tx.to,\n from,\n data: tx.data,\n value: tx.value.toString(),\n mode: \"simulated\",\n result: \"revert\",\n revert_reason: revertReason,\n },\n };\n }\n }\n\n async execute(tx: DeFiTx): Promise<ActionResult> {\n if (this.dryRun) {\n if (this.rpcUrl) {\n return this.simulate(tx);\n }\n\n return {\n tx_hash: undefined,\n status: \"dry_run\" as TxStatus,\n gas_used: tx.gas_estimate,\n description: tx.description,\n details: {\n to: tx.to,\n data: tx.data,\n value: tx.value.toString(),\n mode: \"dry_run\",\n },\n };\n }\n\n // === Broadcast mode ===\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n if (!privateKey) {\n throw DefiError.invalidParam(\n \"DEFI_PRIVATE_KEY environment variable not set. Required for --broadcast.\",\n );\n }\n\n const account = privateKeyToAccount(privateKey as `0x${string}`);\n\n const rpcUrl = this.rpcUrl;\n if (!rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured for broadcasting\");\n }\n\n const publicClient = createPublicClient({ transport: http(rpcUrl) });\n const walletClient = createWalletClient({ account, transport: http(rpcUrl) });\n\n // Execute pre-transactions (e.g. farming approval)\n if (tx.pre_txs && tx.pre_txs.length > 0) {\n for (const preTx of tx.pre_txs) {\n process.stderr.write(` Pre-tx: ${preTx.description}...\\n`);\n const preGas = await this.estimateGasWithBuffer(rpcUrl, preTx, account.address);\n const preTxHash = await walletClient.sendTransaction({\n chain: null,\n to: preTx.to,\n data: preTx.data,\n value: preTx.value,\n gas: preGas > 0n ? preGas : undefined,\n });\n const preTxUrl = this.explorerUrl ? `${this.explorerUrl}/tx/${preTxHash}` : undefined;\n process.stderr.write(` Pre-tx sent: ${preTxHash}\\n`);\n if (preTxUrl) process.stderr.write(` Explorer: ${preTxUrl}\\n`);\n const preReceipt = await publicClient.waitForTransactionReceipt({ hash: preTxHash });\n if (preReceipt.status !== \"success\") {\n throw new DefiError(\"TX_FAILED\", `Pre-transaction failed: ${preTx.description}`);\n }\n process.stderr.write(` Pre-tx confirmed\\n`);\n }\n }\n\n // Auto-approve ERC20 tokens if needed\n if (tx.approvals && tx.approvals.length > 0) {\n for (const approval of tx.approvals) {\n await this.checkAndApprove(\n approval.token,\n approval.spender,\n approval.amount,\n account.address,\n publicClient,\n walletClient,\n );\n }\n }\n\n // Dynamic gas estimation with buffer\n const gasLimit = await this.estimateGasWithBuffer(rpcUrl, tx, account.address);\n\n // EIP-1559 gas pricing\n const [maxFeePerGas, maxPriorityFeePerGas] = await this.fetchEip1559Fees(rpcUrl);\n\n process.stderr.write(`Broadcasting transaction to ${rpcUrl}...\\n`);\n if (gasLimit > 0n) {\n process.stderr.write(` Gas limit: ${gasLimit} (with 20% buffer)\\n`);\n }\n\n const txHash = await walletClient.sendTransaction({\n chain: null,\n to: tx.to,\n data: tx.data,\n value: tx.value,\n gas: gasLimit > 0n ? gasLimit : undefined,\n maxFeePerGas: maxFeePerGas > 0n ? maxFeePerGas : undefined,\n maxPriorityFeePerGas: maxPriorityFeePerGas > 0n ? maxPriorityFeePerGas : undefined,\n });\n\n const txUrl = this.explorerUrl ? `${this.explorerUrl}/tx/${txHash}` : undefined;\n process.stderr.write(`Transaction sent: ${txHash}\\n`);\n if (txUrl) process.stderr.write(`Explorer: ${txUrl}\\n`);\n process.stderr.write(\"Waiting for confirmation...\\n\");\n\n const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });\n\n const status = receipt.status === \"success\" ? \"confirmed\" : \"failed\";\n\n // Extract minted NFT tokenId from Transfer(from=0x0) events\n let mintedTokenId: string | undefined;\n if (receipt.status === \"success\" && receipt.logs) {\n const TRANSFER_TOPIC = \"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\";\n const ZERO_TOPIC = \"0x0000000000000000000000000000000000000000000000000000000000000000\";\n for (const log of receipt.logs) {\n if (\n log.topics.length >= 4 &&\n log.topics[0] === TRANSFER_TOPIC &&\n log.topics[1] === ZERO_TOPIC // from = address(0) → mint\n ) {\n mintedTokenId = BigInt(log.topics[3]!).toString();\n break;\n }\n }\n }\n\n const details: Record<string, string | undefined> = {\n to: tx.to,\n from: account.address,\n block_number: receipt.blockNumber?.toString(),\n gas_limit: gasLimit.toString(),\n gas_used: receipt.gasUsed?.toString(),\n explorer_url: txUrl,\n mode: \"broadcast\",\n };\n if (mintedTokenId) {\n details.minted_token_id = mintedTokenId;\n process.stderr.write(` Minted NFT tokenId: ${mintedTokenId}\\n`);\n }\n\n return {\n tx_hash: txHash,\n status: status as TxStatus,\n gas_used: receipt.gasUsed ? Number(receipt.gasUsed) : undefined,\n description: tx.description,\n details,\n };\n }\n}\n\n/** Extract a human-readable revert reason from an RPC error message */\nfunction extractRevertReason(err: string): string {\n for (const marker of [\"execution reverted:\", \"revert:\", \"Error(\"]) {\n const pos = err.indexOf(marker);\n if (pos !== -1) return err.slice(pos);\n }\n return err.length > 200 ? err.slice(0, 200) + \"...\" : err;\n}\n","import type { Address, Hex } from \"viem\";\n\n// === Transaction Types ===\n\n/** A built DeFi transaction ready for simulation or broadcast */\nexport interface DeFiTx {\n description: string;\n to: Address;\n data: Hex;\n value: bigint;\n gas_estimate?: number;\n /** ERC20 approvals to check and send before broadcasting this tx */\n approvals?: Array<{\n token: Address;\n spender: Address;\n amount: bigint;\n }>;\n /** Pre-transactions to execute before the main tx (e.g. farming approval) */\n pre_txs?: DeFiTx[];\n}\n\n/** Result of executing or simulating a transaction */\nexport interface ActionResult {\n tx_hash?: string;\n status: TxStatus;\n gas_used?: number;\n description: string;\n details: Record<string, unknown>;\n}\n\n/** Transaction status (serde: snake_case) */\nexport enum TxStatus {\n DryRun = \"dry_run\",\n Simulated = \"simulated\",\n SimulationFailed = \"simulation_failed\",\n NeedsApproval = \"needs_approval\",\n Pending = \"pending\",\n Confirmed = \"confirmed\",\n Failed = \"failed\",\n}\n\n// === Token Types ===\n\n/** Token amount with decimals-aware formatting */\nexport interface TokenAmount {\n token: Address;\n symbol: string;\n amount: bigint;\n decimals: number;\n}\n\nexport function formatHuman(t: TokenAmount): string {\n const divisor = 10n ** BigInt(t.decimals);\n const whole = t.amount / divisor;\n const frac = t.amount % divisor;\n return `${whole}.${frac.toString().padStart(t.decimals, \"0\")} ${t.symbol}`;\n}\n\n/** Slippage tolerance in basis points */\nexport interface Slippage {\n bps: number;\n}\n\nexport function newSlippage(bps: number): Slippage {\n return { bps };\n}\n\nexport function defaultSwapSlippage(): Slippage {\n return { bps: 50 };\n}\n\nexport function applyMinSlippage(slippage: Slippage, amount: bigint): bigint {\n return (amount * BigInt(10000 - slippage.bps)) / 10000n;\n}\n\n// === Oracle / Price Types ===\n\nexport interface PriceData {\n source: string;\n source_type: string;\n asset: Address;\n price_usd: bigint;\n price_f64: number;\n block_number?: number;\n timestamp?: number;\n}\n\n// === DEX Types ===\n\nexport interface SwapParams {\n protocol: string;\n token_in: Address;\n token_out: Address;\n amount_in: bigint;\n slippage: Slippage;\n recipient: Address;\n deadline?: number;\n}\n\nexport interface QuoteParams {\n protocol: string;\n token_in: Address;\n token_out: Address;\n amount_in: bigint;\n}\n\nexport interface QuoteResult {\n protocol: string;\n amount_out: bigint;\n price_impact_bps?: number;\n fee_bps?: number;\n route: string[];\n}\n\nexport interface AddLiquidityParams {\n protocol: string;\n token_a: Address;\n token_b: Address;\n amount_a: bigint;\n amount_b: bigint;\n recipient: Address;\n /** Optional lower tick for concentrated LP (defaults to full range) */\n tick_lower?: number;\n /** Optional upper tick for concentrated LP (defaults to full range) */\n tick_upper?: number;\n /** ±N% concentrated range around current price (e.g. 2 for ±2%) */\n range_pct?: number;\n /** Optional pool address for tick detection / single-side LP */\n pool?: Address;\n}\n\nexport interface RemoveLiquidityParams {\n protocol: string;\n token_a: Address;\n token_b: Address;\n liquidity: bigint;\n recipient: Address;\n}\n\n// === Lending Types ===\n\nexport interface SupplyParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n on_behalf_of: Address;\n}\n\nexport interface BorrowParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n interest_rate_mode: InterestRateMode;\n on_behalf_of: Address;\n}\n\n/** Interest rate mode (serde: snake_case) */\nexport enum InterestRateMode {\n Variable = \"variable\",\n Stable = \"stable\",\n}\n\nexport interface RepayParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n interest_rate_mode: InterestRateMode;\n on_behalf_of: Address;\n}\n\nexport interface WithdrawParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n to: Address;\n}\n\nexport interface LendingRates {\n protocol: string;\n asset: Address;\n supply_apy: number;\n borrow_variable_apy: number;\n borrow_stable_apy?: number;\n utilization: number;\n total_supply: bigint;\n total_borrow: bigint;\n /** Reward token addresses for supply-side incentives */\n supply_reward_tokens?: string[];\n /** Reward token addresses for borrow-side incentives */\n borrow_reward_tokens?: string[];\n /** Emissions per second per supply reward token (raw uint256 as string) */\n supply_emissions_per_second?: string[];\n /** Emissions per second per borrow reward token (raw uint256 as string) */\n borrow_emissions_per_second?: string[];\n /** Supply-side incentive APY (%) from reward token emissions */\n supply_incentive_apy?: number;\n /** Borrow-side incentive APY (%) from reward token emissions (negative = subsidized) */\n borrow_incentive_apy?: number;\n}\n\nexport interface UserPosition {\n protocol: string;\n user: Address;\n supplies: PositionAsset[];\n borrows: PositionAsset[];\n health_factor?: number;\n net_apy?: number;\n}\n\nexport interface PositionAsset {\n asset: Address;\n symbol: string;\n amount: bigint;\n value_usd?: number;\n}\n\n// === CDP Types ===\n\nexport interface OpenCdpParams {\n protocol: string;\n collateral: Address;\n collateral_amount: bigint;\n debt_amount: bigint;\n recipient: Address;\n}\n\nexport interface AdjustCdpParams {\n protocol: string;\n cdp_id: bigint;\n collateral_delta?: bigint;\n debt_delta?: bigint;\n add_collateral: boolean;\n add_debt: boolean;\n}\n\nexport interface CloseCdpParams {\n protocol: string;\n cdp_id: bigint;\n}\n\nexport interface CdpInfo {\n protocol: string;\n cdp_id: bigint;\n collateral: TokenAmount;\n debt: TokenAmount;\n collateral_ratio: number;\n liquidation_price?: number;\n}\n\n// === Liquid Staking Types ===\n\nexport interface StakeParams {\n protocol: string;\n amount: bigint;\n recipient: Address;\n}\n\nexport interface UnstakeParams {\n protocol: string;\n amount: bigint;\n recipient: Address;\n}\n\nexport interface StakingInfo {\n protocol: string;\n staked_token: Address;\n liquid_token: Address;\n exchange_rate: number;\n apy?: number;\n total_staked: bigint;\n}\n\n// === Vault Types (ERC-4626) ===\n\nexport interface VaultInfo {\n protocol: string;\n vault_address: Address;\n asset: Address;\n total_assets: bigint;\n total_supply: bigint;\n apy?: number;\n}\n\n// === Derivatives Types ===\n\nexport interface DerivativesPositionParams {\n protocol: string;\n market: string;\n size: bigint;\n collateral: bigint;\n is_long: boolean;\n}\n\n// === Options Types ===\n\nexport interface OptionParams {\n protocol: string;\n underlying: Address;\n strike_price: bigint;\n expiry: number;\n is_call: boolean;\n amount: bigint;\n}\n\n// === ve(3,3) Types ===\n\n/** A pool that has an active emission gauge */\nexport interface GaugedPool {\n pool: Address;\n gauge: Address;\n token0: string; // symbol\n token1: string; // symbol\n type: \"V2\" | \"CL\";\n tickSpacing?: number; // for CL pools\n stable?: boolean; // for V2 pools\n}\n\nexport interface RewardInfo {\n token: Address;\n symbol: string;\n amount: bigint;\n value_usd?: number;\n}\n\nexport interface GaugeInfo {\n gauge: Address;\n pool: Address;\n total_staked: bigint;\n reward_rate: bigint;\n rewards: RewardInfo[];\n}\n\nexport interface VeNftInfo {\n token_id: bigint;\n amount: bigint;\n unlock_time: number;\n voting_power: bigint;\n}\n\n// === Yield Types ===\n\nexport interface YieldInfo {\n protocol: string;\n pool: string;\n apy: number;\n tvl: bigint;\n tokens: Address[];\n}\n\n// === Portfolio Tracker Types ===\nexport interface PortfolioSnapshot {\n timestamp: number;\n chain: string;\n wallet: string;\n tokens: TokenBalance[];\n defi_positions: DefiPosition[];\n total_value_usd: number;\n}\n\nexport interface TokenBalance {\n token: string;\n symbol: string;\n balance: bigint;\n value_usd: number;\n price_usd: number;\n}\n\nexport interface DefiPosition {\n protocol: string;\n type: \"lending_supply\" | \"lending_borrow\" | \"lp\" | \"staking\" | \"vault\";\n asset: string;\n amount: bigint;\n value_usd: number;\n}\n\nexport interface PortfolioPnL {\n period: string;\n start_value_usd: number;\n end_value_usd: number;\n pnl_usd: number;\n pnl_pct: number;\n token_changes: TokenChange[];\n}\n\nexport interface TokenChange {\n symbol: string;\n balance_change: bigint;\n value_change_usd: number;\n}\n","import type { Address } from \"viem\";\n\nexport type DefiErrorCode =\n | \"PROTOCOL_NOT_FOUND\"\n | \"TOKEN_NOT_FOUND\"\n | \"CHAIN_NOT_FOUND\"\n | \"INSUFFICIENT_BALANCE\"\n | \"INSUFFICIENT_ALLOWANCE\"\n | \"SLIPPAGE_EXCEEDED\"\n | \"SIMULATION_FAILED\"\n | \"ABI_ERROR\"\n | \"REGISTRY_ERROR\"\n | \"RPC_ERROR\"\n | \"PROVIDER_ERROR\"\n | \"CONTRACT_ERROR\"\n | \"INVALID_PARAM\"\n | \"UNSUPPORTED\"\n | \"TX_FAILED\"\n | \"INTERNAL\";\n\nexport class DefiError extends Error {\n readonly code: DefiErrorCode;\n\n constructor(code: DefiErrorCode, message: string) {\n super(message);\n this.name = \"DefiError\";\n this.code = code;\n }\n\n static protocolNotFound(name: string): DefiError {\n return new DefiError(\"PROTOCOL_NOT_FOUND\", `Protocol not found: ${name}`);\n }\n\n static tokenNotFound(name: string): DefiError {\n return new DefiError(\"TOKEN_NOT_FOUND\", `Token not found: ${name}`);\n }\n\n static chainNotFound(name: string): DefiError {\n return new DefiError(\"CHAIN_NOT_FOUND\", `Chain not found: ${name}`);\n }\n\n static insufficientBalance(needed: string, available: string): DefiError {\n return new DefiError(\n \"INSUFFICIENT_BALANCE\",\n `Insufficient balance: need ${needed}, have ${available}`,\n );\n }\n\n static insufficientAllowance(spender: Address): DefiError {\n return new DefiError(\n \"INSUFFICIENT_ALLOWANCE\",\n `Insufficient allowance for spender ${spender}`,\n );\n }\n\n static slippageExceeded(expected: string, actual: string): DefiError {\n return new DefiError(\n \"SLIPPAGE_EXCEEDED\",\n `Slippage exceeded: expected ${expected}, got ${actual}`,\n );\n }\n\n static simulationFailed(reason: string): DefiError {\n return new DefiError(\n \"SIMULATION_FAILED\",\n `Transaction simulation failed: ${reason}`,\n );\n }\n\n static abiError(reason: string): DefiError {\n return new DefiError(\"ABI_ERROR\", `ABI encoding error: ${reason}`);\n }\n\n static registryError(reason: string): DefiError {\n return new DefiError(\"REGISTRY_ERROR\", `Registry error: ${reason}`);\n }\n\n static rpcError(reason: string): DefiError {\n return new DefiError(\"RPC_ERROR\", `RPC error: ${reason}`);\n }\n\n static providerError(reason: string): DefiError {\n return new DefiError(\"PROVIDER_ERROR\", `Provider error: ${reason}`);\n }\n\n static contractError(reason: string): DefiError {\n return new DefiError(\"CONTRACT_ERROR\", `Contract error: ${reason}`);\n }\n\n static invalidParam(reason: string): DefiError {\n return new DefiError(\"INVALID_PARAM\", `Invalid parameter: ${reason}`);\n }\n\n static unsupported(operation: string): DefiError {\n return new DefiError(\n \"UNSUPPORTED\",\n `Unsupported operation: ${operation}`,\n );\n }\n\n static internal(reason: string): DefiError {\n return new DefiError(\"INTERNAL\", `Internal error: ${reason}`);\n }\n\n toJSON() {\n return { error: this.message };\n }\n}\n\nexport type Result<T> = T;\n","/**\n * BigInt JSON serialization utilities.\n *\n * Rust's alloy U256 (backed by ruint) serializes to JSON as 0x-prefixed\n * lowercase hex strings (e.g., \"0x75bcd15\"). We must match this exactly\n * for behavioral parity.\n */\n\n/** JSON replacer for Rust parity — bigint becomes 0x-hex string */\nexport function jsonReplacer(_key: string, value: unknown): unknown {\n if (typeof value === \"bigint\") {\n return \"0x\" + value.toString(16);\n }\n return value;\n}\n\n/** JSON replacer for SDK consumers — bigint becomes decimal string */\nexport function jsonReplacerDecimal(_key: string, value: unknown): unknown {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n}\n\n/** Stringify with decimal bigint handling */\nexport function jsonStringify(data: unknown, pretty = true): string {\n return pretty\n ? JSON.stringify(data, jsonReplacerDecimal, 2)\n : JSON.stringify(data, jsonReplacerDecimal);\n}\n\n/** Parse a 0x-hex or decimal string to bigint */\nexport function parseBigInt(value: string): bigint {\n if (value.startsWith(\"0x\") || value.startsWith(\"0X\")) {\n return BigInt(value);\n }\n return BigInt(value);\n}\n","import type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport type { DeFiTx } from \"./types.js\";\n\nconst erc20Abi = parseAbi([\n \"function name() view returns (string)\",\n \"function symbol() view returns (string)\",\n \"function decimals() view returns (uint8)\",\n \"function totalSupply() view returns (uint256)\",\n \"function balanceOf(address account) view returns (uint256)\",\n \"function transfer(address to, uint256 amount) returns (bool)\",\n \"function allowance(address owner, address spender) view returns (uint256)\",\n \"function approve(address spender, uint256 amount) returns (bool)\",\n \"function transferFrom(address from, address to, uint256 amount) returns (bool)\",\n]);\n\nexport { erc20Abi };\n\nexport function buildApprove(\n token: Address,\n spender: Address,\n amount: bigint,\n): DeFiTx {\n const data = encodeFunctionData({\n abi: erc20Abi,\n functionName: \"approve\",\n args: [spender, amount],\n });\n return {\n description: `Approve ${spender} to spend ${amount} of token ${token}`,\n to: token,\n data,\n value: 0n,\n gas_estimate: 60_000,\n };\n}\n\nexport function buildTransfer(\n token: Address,\n to: Address,\n amount: bigint,\n): DeFiTx {\n const data = encodeFunctionData({\n abi: erc20Abi,\n functionName: \"transfer\",\n args: [to, amount],\n });\n return {\n description: `Transfer ${amount} of token ${token} to ${to}`,\n to: token,\n data,\n value: 0n,\n gas_estimate: 65_000,\n };\n}\n","import { createPublicClient, http, type PublicClient } from \"viem\";\n\nconst providerCache = new Map<string, PublicClient>();\n\nexport function getProvider(rpcUrl: string): PublicClient {\n const cached = providerCache.get(rpcUrl);\n if (cached) return cached;\n\n const client = createPublicClient({ transport: http(rpcUrl) });\n providerCache.set(rpcUrl, client);\n return client;\n}\n\nexport function clearProviderCache(): void {\n providerCache.clear();\n}\n","import type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, decodeFunctionResult, parseAbi } from \"viem\";\nimport type { DeFiTx } from \"./types.js\";\nimport { getProvider } from \"./provider.js\";\n\nexport const MULTICALL3_ADDRESS: Address =\n \"0xcA11bde05977b3631167028862bE2a173976CA11\";\n\nconst multicall3Abi = parseAbi([\n \"struct Call3 { address target; bool allowFailure; bytes callData; }\",\n \"struct Result { bool success; bytes returnData; }\",\n \"function aggregate3(Call3[] calls) returns (Result[] returnData)\",\n]);\n\nexport function buildMulticall(calls: Array<[Address, Hex]>): DeFiTx {\n const mcCalls = calls.map(([target, callData]) => ({\n target,\n allowFailure: true,\n callData,\n }));\n\n const data = encodeFunctionData({\n abi: multicall3Abi,\n functionName: \"aggregate3\",\n args: [mcCalls],\n });\n\n return {\n description: `Multicall3 batch (${calls.length} calls)`,\n to: MULTICALL3_ADDRESS,\n data,\n value: 0n,\n };\n}\n\nexport async function multicallRead(\n rpcUrl: string,\n calls: Array<[Address, Hex]>,\n): Promise<(Hex | null)[]> {\n const client = getProvider(rpcUrl);\n\n const mcCalls = calls.map(([target, callData]) => ({\n target,\n allowFailure: true,\n callData,\n }));\n\n const result = await client.call({\n to: MULTICALL3_ADDRESS,\n data: encodeFunctionData({\n abi: multicall3Abi,\n functionName: \"aggregate3\",\n args: [mcCalls],\n }),\n });\n\n if (!result.data) return calls.map(() => null);\n\n const decoded = decodeFunctionResult({\n abi: multicall3Abi,\n functionName: \"aggregate3\",\n data: result.data,\n }) as Array<{ success: boolean; returnData: Hex }>;\n\n return decoded.map((r) => (r.success ? r.returnData : null));\n}\n\nexport function decodeU256(data: Hex | null): bigint {\n if (!data || data.length < 66) return 0n;\n return BigInt(data.slice(0, 66));\n}\n\nexport function decodeU128(data: Hex | null): bigint {\n if (!data || data.length < 66) return 0n;\n const val = BigInt(data.slice(0, 66));\n return val & ((1n << 128n) - 1n);\n}\n","export class ChainConfig {\n name!: string;\n chain_id!: number;\n rpc_url!: string;\n explorer_url?: string;\n native_token!: string;\n wrapped_native?: string;\n multicall3?: string;\n\n effectiveRpcUrl(): string {\n const chainEnv = this.name.toUpperCase().replace(/ /g, \"_\") + \"_RPC_URL\";\n return (\n process.env[chainEnv] ??\n process.env[\"HYPEREVM_RPC_URL\"] ??\n this.rpc_url\n );\n }\n}\n","import type { Address } from \"viem\";\n\nexport enum ProtocolCategory {\n Dex = \"dex\",\n Lending = \"lending\",\n Cdp = \"cdp\",\n Bridge = \"bridge\",\n LiquidStaking = \"liquid_staking\",\n YieldSource = \"yield_source\",\n YieldAggregator = \"yield_aggregator\",\n Vault = \"vault\",\n Derivatives = \"derivatives\",\n Options = \"options\",\n LiquidityManager = \"liquidity_manager\",\n Nft = \"nft\",\n Other = \"other\",\n}\n\nexport function protocolCategoryLabel(category: ProtocolCategory): string {\n switch (category) {\n case ProtocolCategory.Dex:\n return \"DEX\";\n case ProtocolCategory.Lending:\n return \"Lending\";\n case ProtocolCategory.Cdp:\n return \"CDP\";\n case ProtocolCategory.Bridge:\n return \"Bridge\";\n case ProtocolCategory.LiquidStaking:\n return \"Liquid Staking\";\n case ProtocolCategory.YieldSource:\n return \"Yield Source\";\n case ProtocolCategory.YieldAggregator:\n return \"Yield Aggregator\";\n case ProtocolCategory.Vault:\n return \"Vault\";\n case ProtocolCategory.Derivatives:\n return \"Derivatives\";\n case ProtocolCategory.Options:\n return \"Options\";\n case ProtocolCategory.LiquidityManager:\n return \"Liquidity Manager\";\n case ProtocolCategory.Nft:\n return \"NFT\";\n case ProtocolCategory.Other:\n return \"Other\";\n }\n}\n\nexport interface PoolInfo {\n name: string;\n address: Address;\n token0: string;\n token1: string;\n tick_spacing?: number;\n gauge?: Address;\n stable?: boolean;\n}\n\nexport interface ProtocolEntry {\n name: string;\n slug: string;\n category: ProtocolCategory;\n interface: string;\n chain: string;\n native?: boolean;\n contracts?: Record<string, Address>;\n pools?: PoolInfo[];\n description?: string;\n}\n","import { readFileSync, readdirSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { parse } from \"smol-toml\";\nimport { ChainConfig } from \"./chain.js\";\nimport type { TokenEntry } from \"./token.js\";\nimport { type ProtocolEntry, type PoolInfo, ProtocolCategory } from \"./protocol.js\";\n\nimport { existsSync } from \"fs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\n\n// Resolve config dir: works from src/ (vitest), dist/ (built), and npm bundle (npx)\nfunction findConfigDir(): string {\n const candidates = [\n resolve(__dirname, \"../../../config\"), // from dist/registry/ (monorepo build)\n resolve(__dirname, \"../../../../config\"), // from src/registry/ (vitest)\n resolve(__dirname, \"../config\"), // from dist/ (npm bundle — config at package root)\n resolve(__dirname, \"../../config\"), // from dist/subdir (npm bundle variant)\n ];\n for (const dir of candidates) {\n if (existsSync(resolve(dir, \"chains.toml\"))) return dir;\n }\n throw new Error(`Config directory not found. Searched: ${candidates.join(\", \")}`);\n}\n\nconst CONFIG_DIR = findConfigDir();\n\nfunction readToml(relPath: string): string {\n return readFileSync(resolve(CONFIG_DIR, relPath), \"utf-8\");\n}\n\ninterface ChainConfigWrapper {\n chain: Record<string, ChainConfig>;\n}\n\ninterface TokensWrapper {\n token: TokenEntry[];\n}\n\ninterface ProtocolWrapper {\n protocol: ProtocolEntry;\n}\n\nexport class Registry {\n chains: Map<string, ChainConfig>;\n tokens: Map<string, TokenEntry[]>;\n protocols: ProtocolEntry[];\n\n private constructor(\n chains: Map<string, ChainConfig>,\n tokens: Map<string, TokenEntry[]>,\n protocols: ProtocolEntry[],\n ) {\n this.chains = chains;\n this.tokens = tokens;\n this.protocols = protocols;\n }\n\n static loadEmbedded(): Registry {\n const chains = Registry.loadChains();\n const tokens = Registry.loadTokens();\n const protocols = Registry.loadProtocols();\n return new Registry(chains, tokens, protocols);\n }\n\n private static loadChains(): Map<string, ChainConfig> {\n const raw = parse(readToml(\"chains.toml\")) as unknown as ChainConfigWrapper;\n const map = new Map<string, ChainConfig>();\n for (const [key, data] of Object.entries(raw.chain)) {\n const cfg = Object.assign(new ChainConfig(), data);\n map.set(key, cfg);\n }\n return map;\n }\n\n private static loadTokens(): Map<string, TokenEntry[]> {\n // Dynamically discover all token files in config/tokens/\n const map = new Map<string, TokenEntry[]>();\n const tokensDir = resolve(CONFIG_DIR, \"tokens\");\n try {\n const files = readdirSync(tokensDir).filter(f => f.endsWith(\".toml\"));\n for (const file of files) {\n const chain = file.replace(\".toml\", \"\");\n try {\n const raw = parse(readToml(`tokens/${file}`)) as unknown as TokensWrapper;\n map.set(chain, raw.token);\n } catch { /* skip invalid token files */ }\n }\n } catch { /* tokens dir may not exist */ }\n return map;\n }\n\n private static loadProtocols(): ProtocolEntry[] {\n // Dynamically discover all protocol TOML files across all categories\n const protocols: ProtocolEntry[] = [];\n const protocolsDir = resolve(CONFIG_DIR, \"protocols\");\n const categories = [\"dex\", \"lending\", \"cdp\", \"vault\", \"liquid_staking\", \"yield_aggregator\", \"yield_source\", \"derivatives\", \"options\", \"nft\", \"bridge\"];\n\n for (const category of categories) {\n const catDir = resolve(protocolsDir, category);\n try {\n if (!existsSync(catDir)) continue;\n const files = readdirSync(catDir).filter(f => f.endsWith(\".toml\"));\n for (const file of files) {\n try {\n const raw = parse(readToml(`protocols/${category}/${file}`)) as unknown as ProtocolWrapper;\n protocols.push(raw.protocol);\n } catch { /* skip invalid protocol files */ }\n }\n } catch { /* category dir may not exist */ }\n }\n return protocols;\n }\n\n getChain(name: string): ChainConfig {\n const chain = this.chains.get(name);\n if (!chain) throw new Error(`Chain not found: ${name}`);\n return chain;\n }\n\n getProtocol(name: string): ProtocolEntry {\n const protocol = this.protocols.find(\n (p) =>\n p.name.toLowerCase() === name.toLowerCase() ||\n p.slug.toLowerCase() === name.toLowerCase(),\n );\n if (!protocol) throw new Error(`Protocol not found: ${name}`);\n return protocol;\n }\n\n getProtocolsByCategory(category: ProtocolCategory): ProtocolEntry[] {\n return this.protocols.filter((p) => p.category === category);\n }\n\n getProtocolsForChain(chain: string): ProtocolEntry[] {\n return this.protocols.filter(\n (p) => p.chain.toLowerCase() === chain.toLowerCase(),\n );\n }\n\n resolveToken(chain: string, symbol: string): TokenEntry {\n const tokens = this.tokens.get(chain);\n if (!tokens) throw new Error(`Chain not found: ${chain}`);\n const token = tokens.find(\n (t) => t.symbol.toLowerCase() === symbol.toLowerCase(),\n );\n if (!token) throw new Error(`Token not found: ${symbol}`);\n return token;\n }\n\n /**\n * Resolve a pool by name (e.g. \"WHYPE/USDC\") from a protocol's pool list.\n * Returns the pool info or throws if not found.\n */\n resolvePool(protocolSlug: string, poolName: string): PoolInfo {\n const protocol = this.getProtocol(protocolSlug);\n if (!protocol.pools || protocol.pools.length === 0) {\n throw new Error(`Protocol ${protocol.name} has no pools configured`);\n }\n const pool = protocol.pools.find(\n (p) => p.name.toLowerCase() === poolName.toLowerCase(),\n );\n if (!pool) {\n const available = protocol.pools.map(p => p.name).join(\", \");\n throw new Error(`Pool '${poolName}' not found in ${protocol.name}. Available: ${available}`);\n }\n return pool;\n }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nfunction getLineColFromPtr(string, ptr) {\n let lines = string.slice(0, ptr).split(/\\r\\n|\\n|\\r/g);\n return [lines.length, lines.pop().length + 1];\n}\nfunction makeCodeBlock(string, line, column) {\n let lines = string.split(/\\r\\n|\\n|\\r/g);\n let codeblock = '';\n let numberLen = (Math.log10(line + 1) | 0) + 1;\n for (let i = line - 1; i <= line + 1; i++) {\n let l = lines[i - 1];\n if (!l)\n continue;\n codeblock += i.toString().padEnd(numberLen, ' ');\n codeblock += ': ';\n codeblock += l;\n codeblock += '\\n';\n if (i === line) {\n codeblock += ' '.repeat(numberLen + column + 2);\n codeblock += '^\\n';\n }\n }\n return codeblock;\n}\nexport class TomlError extends Error {\n line;\n column;\n codeblock;\n constructor(message, options) {\n const [line, column] = getLineColFromPtr(options.toml, options.ptr);\n const codeblock = makeCodeBlock(options.toml, line, column);\n super(`Invalid TOML document: ${message}\\n\\n${codeblock}`, options);\n this.line = line;\n this.column = column;\n this.codeblock = codeblock;\n }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { TomlError } from './error.js';\nfunction isEscaped(str, ptr) {\n let i = 0;\n while (str[ptr - ++i] === '\\\\')\n ;\n return --i && (i % 2);\n}\nexport function indexOfNewline(str, start = 0, end = str.length) {\n let idx = str.indexOf('\\n', start);\n if (str[idx - 1] === '\\r')\n idx--;\n return idx <= end ? idx : -1;\n}\nexport function skipComment(str, ptr) {\n for (let i = ptr; i < str.length; i++) {\n let c = str[i];\n if (c === '\\n')\n return i;\n if (c === '\\r' && str[i + 1] === '\\n')\n return i + 1;\n if ((c < '\\x20' && c !== '\\t') || c === '\\x7f') {\n throw new TomlError('control characters are not allowed in comments', {\n toml: str,\n ptr: ptr,\n });\n }\n }\n return str.length;\n}\nexport function skipVoid(str, ptr, banNewLines, banComments) {\n let c;\n while ((c = str[ptr]) === ' ' || c === '\\t' || (!banNewLines && (c === '\\n' || c === '\\r' && str[ptr + 1] === '\\n')))\n ptr++;\n return banComments || c !== '#'\n ? ptr\n : skipVoid(str, skipComment(str, ptr), banNewLines);\n}\nexport function skipUntil(str, ptr, sep, end, banNewLines = false) {\n if (!end) {\n ptr = indexOfNewline(str, ptr);\n return ptr < 0 ? str.length : ptr;\n }\n for (let i = ptr; i < str.length; i++) {\n let c = str[i];\n if (c === '#') {\n i = indexOfNewline(str, i);\n }\n else if (c === sep) {\n return i + 1;\n }\n else if (c === end || (banNewLines && (c === '\\n' || (c === '\\r' && str[i + 1] === '\\n')))) {\n return i;\n }\n }\n throw new TomlError('cannot find end of structure', {\n toml: str,\n ptr: ptr\n });\n}\nexport function getStringEnd(str, seek) {\n let first = str[seek];\n let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2]\n ? str.slice(seek, seek + 3)\n : first;\n seek += target.length - 1;\n do\n seek = str.indexOf(target, ++seek);\n while (seek > -1 && first !== \"'\" && isEscaped(str, seek));\n if (seek > -1) {\n seek += target.length;\n if (target.length > 1) {\n if (str[seek] === first)\n seek++;\n if (str[seek] === first)\n seek++;\n }\n }\n return seek;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nlet DATE_TIME_RE = /^(\\d{4}-\\d{2}-\\d{2})?[T ]?(?:(\\d{2}):\\d{2}(?::\\d{2}(?:\\.\\d+)?)?)?(Z|[-+]\\d{2}:\\d{2})?$/i;\nexport class TomlDate extends Date {\n #hasDate = false;\n #hasTime = false;\n #offset = null;\n constructor(date) {\n let hasDate = true;\n let hasTime = true;\n let offset = 'Z';\n if (typeof date === 'string') {\n let match = date.match(DATE_TIME_RE);\n if (match) {\n if (!match[1]) {\n hasDate = false;\n date = `0000-01-01T${date}`;\n }\n hasTime = !!match[2];\n // Make sure to use T instead of a space. Breaks in case of extreme values otherwise.\n hasTime && date[10] === ' ' && (date = date.replace(' ', 'T'));\n // Do not allow rollover hours.\n if (match[2] && +match[2] > 23) {\n date = '';\n }\n else {\n offset = match[3] || null;\n date = date.toUpperCase();\n if (!offset && hasTime)\n date += 'Z';\n }\n }\n else {\n date = '';\n }\n }\n super(date);\n if (!isNaN(this.getTime())) {\n this.#hasDate = hasDate;\n this.#hasTime = hasTime;\n this.#offset = offset;\n }\n }\n isDateTime() {\n return this.#hasDate && this.#hasTime;\n }\n isLocal() {\n return !this.#hasDate || !this.#hasTime || !this.#offset;\n }\n isDate() {\n return this.#hasDate && !this.#hasTime;\n }\n isTime() {\n return this.#hasTime && !this.#hasDate;\n }\n isValid() {\n return this.#hasDate || this.#hasTime;\n }\n toISOString() {\n let iso = super.toISOString();\n // Local Date\n if (this.isDate())\n return iso.slice(0, 10);\n // Local Time\n if (this.isTime())\n return iso.slice(11, 23);\n // Local DateTime\n if (this.#offset === null)\n return iso.slice(0, -1);\n // Offset DateTime\n if (this.#offset === 'Z')\n return iso;\n // This part is quite annoying: JS strips the original timezone from the ISO string representation\n // Instead of using a \"modified\" date and \"Z\", we restore the representation \"as authored\"\n let offset = (+(this.#offset.slice(1, 3)) * 60) + +(this.#offset.slice(4, 6));\n offset = this.#offset[0] === '-' ? offset : -offset;\n let offsetDate = new Date(this.getTime() - (offset * 60e3));\n return offsetDate.toISOString().slice(0, -1) + this.#offset;\n }\n static wrapAsOffsetDateTime(jsDate, offset = 'Z') {\n let date = new TomlDate(jsDate);\n date.#offset = offset;\n return date;\n }\n static wrapAsLocalDateTime(jsDate) {\n let date = new TomlDate(jsDate);\n date.#offset = null;\n return date;\n }\n static wrapAsLocalDate(jsDate) {\n let date = new TomlDate(jsDate);\n date.#hasTime = false;\n date.#offset = null;\n return date;\n }\n static wrapAsLocalTime(jsDate) {\n let date = new TomlDate(jsDate);\n date.#hasDate = false;\n date.#offset = null;\n return date;\n }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { skipVoid } from './util.js';\nimport { TomlDate } from './date.js';\nimport { TomlError } from './error.js';\nlet INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\\d(_?\\d)*))$/;\nlet FLOAT_REGEX = /^[+-]?\\d(_?\\d)*(\\.\\d(_?\\d)*)?([eE][+-]?\\d(_?\\d)*)?$/;\nlet LEADING_ZERO = /^[+-]?0[0-9_]/;\nlet ESCAPE_REGEX = /^[0-9a-f]{2,8}$/i;\nlet ESC_MAP = {\n b: '\\b',\n t: '\\t',\n n: '\\n',\n f: '\\f',\n r: '\\r',\n e: '\\x1b',\n '\"': '\"',\n '\\\\': '\\\\',\n};\nexport function parseString(str, ptr = 0, endPtr = str.length) {\n let isLiteral = str[ptr] === '\\'';\n let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];\n if (isMultiline) {\n endPtr -= 2;\n if (str[ptr += 2] === '\\r')\n ptr++;\n if (str[ptr] === '\\n')\n ptr++;\n }\n let tmp = 0;\n let isEscape;\n let parsed = '';\n let sliceStart = ptr;\n while (ptr < endPtr - 1) {\n let c = str[ptr++];\n if (c === '\\n' || (c === '\\r' && str[ptr] === '\\n')) {\n if (!isMultiline) {\n throw new TomlError('newlines are not allowed in strings', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n }\n else if ((c < '\\x20' && c !== '\\t') || c === '\\x7f') {\n throw new TomlError('control characters are not allowed in strings', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n if (isEscape) {\n isEscape = false;\n if (c === 'x' || c === 'u' || c === 'U') {\n // Unicode escape\n let code = str.slice(ptr, (ptr += (c === 'x' ? 2 : c === 'u' ? 4 : 8)));\n if (!ESCAPE_REGEX.test(code)) {\n throw new TomlError('invalid unicode escape', {\n toml: str,\n ptr: tmp,\n });\n }\n try {\n parsed += String.fromCodePoint(parseInt(code, 16));\n }\n catch {\n throw new TomlError('invalid unicode escape', {\n toml: str,\n ptr: tmp,\n });\n }\n }\n else if (isMultiline && (c === '\\n' || c === ' ' || c === '\\t' || c === '\\r')) {\n // Multiline escape\n ptr = skipVoid(str, ptr - 1, true);\n if (str[ptr] !== '\\n' && str[ptr] !== '\\r') {\n throw new TomlError('invalid escape: only line-ending whitespace may be escaped', {\n toml: str,\n ptr: tmp,\n });\n }\n ptr = skipVoid(str, ptr);\n }\n else if (c in ESC_MAP) {\n // Classic escape\n parsed += ESC_MAP[c];\n }\n else {\n throw new TomlError('unrecognized escape sequence', {\n toml: str,\n ptr: tmp,\n });\n }\n sliceStart = ptr;\n }\n else if (!isLiteral && c === '\\\\') {\n tmp = ptr - 1;\n isEscape = true;\n parsed += str.slice(sliceStart, tmp);\n }\n }\n return parsed + str.slice(sliceStart, endPtr - 1);\n}\nexport function parseValue(value, toml, ptr, integersAsBigInt) {\n // Constant values\n if (value === 'true')\n return true;\n if (value === 'false')\n return false;\n if (value === '-inf')\n return -Infinity;\n if (value === 'inf' || value === '+inf')\n return Infinity;\n if (value === 'nan' || value === '+nan' || value === '-nan')\n return NaN;\n // Avoid FP representation of -0\n if (value === '-0')\n return integersAsBigInt ? 0n : 0;\n // Numbers\n let isInt = INT_REGEX.test(value);\n if (isInt || FLOAT_REGEX.test(value)) {\n if (LEADING_ZERO.test(value)) {\n throw new TomlError('leading zeroes are not allowed', {\n toml: toml,\n ptr: ptr,\n });\n }\n value = value.replace(/_/g, '');\n let numeric = +value;\n if (isNaN(numeric)) {\n throw new TomlError('invalid number', {\n toml: toml,\n ptr: ptr,\n });\n }\n if (isInt) {\n if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) {\n throw new TomlError('integer value cannot be represented losslessly', {\n toml: toml,\n ptr: ptr,\n });\n }\n if (isInt || integersAsBigInt === true)\n numeric = BigInt(value);\n }\n return numeric;\n }\n const date = new TomlDate(value);\n if (!date.isValid()) {\n throw new TomlError('invalid value', {\n toml: toml,\n ptr: ptr,\n });\n }\n return date;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseString, parseValue } from './primitive.js';\nimport { parseArray, parseInlineTable } from './struct.js';\nimport { skipVoid, skipUntil, skipComment, getStringEnd } from './util.js';\nimport { TomlError } from './error.js';\nfunction sliceAndTrimEndOf(str, startPtr, endPtr) {\n let value = str.slice(startPtr, endPtr);\n let commentIdx = value.indexOf('#');\n if (commentIdx > -1) {\n // The call to skipComment allows to \"validate\" the comment\n // (absence of control characters)\n skipComment(str, commentIdx);\n value = value.slice(0, commentIdx);\n }\n return [value.trimEnd(), commentIdx];\n}\nexport function extractValue(str, ptr, end, depth, integersAsBigInt) {\n if (depth === 0) {\n throw new TomlError('document contains excessively nested structures. aborting.', {\n toml: str,\n ptr: ptr\n });\n }\n let c = str[ptr];\n if (c === '[' || c === '{') {\n let [value, endPtr] = c === '['\n ? parseArray(str, ptr, depth, integersAsBigInt)\n : parseInlineTable(str, ptr, depth, integersAsBigInt);\n if (end) {\n endPtr = skipVoid(str, endPtr);\n if (str[endPtr] === ',')\n endPtr++;\n else if (str[endPtr] !== end) {\n throw new TomlError('expected comma or end of structure', {\n toml: str,\n ptr: endPtr,\n });\n }\n }\n return [value, endPtr];\n }\n let endPtr;\n if (c === '\"' || c === \"'\") {\n endPtr = getStringEnd(str, ptr);\n let parsed = parseString(str, ptr, endPtr);\n if (end) {\n endPtr = skipVoid(str, endPtr);\n if (str[endPtr] && str[endPtr] !== ',' && str[endPtr] !== end && str[endPtr] !== '\\n' && str[endPtr] !== '\\r') {\n throw new TomlError('unexpected character encountered', {\n toml: str,\n ptr: endPtr,\n });\n }\n endPtr += (+(str[endPtr] === ','));\n }\n return [parsed, endPtr];\n }\n endPtr = skipUntil(str, ptr, ',', end);\n let slice = sliceAndTrimEndOf(str, ptr, endPtr - (+(str[endPtr - 1] === ',')));\n if (!slice[0]) {\n throw new TomlError('incomplete key-value declaration: no value specified', {\n toml: str,\n ptr: ptr\n });\n }\n if (end && slice[1] > -1) {\n endPtr = skipVoid(str, ptr + slice[1]);\n endPtr += +(str[endPtr] === ',');\n }\n return [\n parseValue(slice[0], str, ptr, integersAsBigInt),\n endPtr,\n ];\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseString } from './primitive.js';\nimport { extractValue } from './extract.js';\nimport { getStringEnd, indexOfNewline, skipComment, skipVoid } from './util.js';\nimport { TomlError } from './error.js';\nlet KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \\t]*$/;\nexport function parseKey(str, ptr, end = '=') {\n let dot = ptr - 1;\n let parsed = [];\n let endPtr = str.indexOf(end, ptr);\n if (endPtr < 0) {\n throw new TomlError('incomplete key-value: cannot find end of key', {\n toml: str,\n ptr: ptr,\n });\n }\n do {\n let c = str[ptr = ++dot];\n // If it's whitespace, ignore\n if (c !== ' ' && c !== '\\t') {\n // If it's a string\n if (c === '\"' || c === '\\'') {\n if (c === str[ptr + 1] && c === str[ptr + 2]) {\n throw new TomlError('multiline strings are not allowed in keys', {\n toml: str,\n ptr: ptr,\n });\n }\n let eos = getStringEnd(str, ptr);\n if (eos < 0) {\n throw new TomlError('unfinished string encountered', {\n toml: str,\n ptr: ptr,\n });\n }\n dot = str.indexOf('.', eos);\n let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);\n let newLine = indexOfNewline(strEnd);\n if (newLine > -1) {\n throw new TomlError('newlines are not allowed in keys', {\n toml: str,\n ptr: ptr + dot + newLine,\n });\n }\n if (strEnd.trimStart()) {\n throw new TomlError('found extra tokens after the string part', {\n toml: str,\n ptr: eos,\n });\n }\n if (endPtr < eos) {\n endPtr = str.indexOf(end, eos);\n if (endPtr < 0) {\n throw new TomlError('incomplete key-value: cannot find end of key', {\n toml: str,\n ptr: ptr,\n });\n }\n }\n parsed.push(parseString(str, ptr, eos));\n }\n else {\n // Normal raw key part consumption and validation\n dot = str.indexOf('.', ptr);\n let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);\n if (!KEY_PART_RE.test(part)) {\n throw new TomlError('only letter, numbers, dashes and underscores are allowed in keys', {\n toml: str,\n ptr: ptr,\n });\n }\n parsed.push(part.trimEnd());\n }\n }\n // Until there's no more dot\n } while (dot + 1 && dot < endPtr);\n return [parsed, skipVoid(str, endPtr + 1, true, true)];\n}\nexport function parseInlineTable(str, ptr, depth, integersAsBigInt) {\n let res = {};\n let seen = new Set();\n let c;\n ptr++;\n while ((c = str[ptr++]) !== '}' && c) {\n if (c === ',') {\n throw new TomlError('expected value, found comma', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n else if (c === '#')\n ptr = skipComment(str, ptr);\n else if (c !== ' ' && c !== '\\t' && c !== '\\n' && c !== '\\r') {\n let k;\n let t = res;\n let hasOwn = false;\n let [key, keyEndPtr] = parseKey(str, ptr - 1);\n for (let i = 0; i < key.length; i++) {\n if (i)\n t = hasOwn ? t[k] : (t[k] = {});\n k = key[i];\n if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== 'object' || seen.has(t[k]))) {\n throw new TomlError('trying to redefine an already defined value', {\n toml: str,\n ptr: ptr,\n });\n }\n if (!hasOwn && k === '__proto__') {\n Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });\n }\n }\n if (hasOwn) {\n throw new TomlError('trying to redefine an already defined value', {\n toml: str,\n ptr: ptr,\n });\n }\n let [value, valueEndPtr] = extractValue(str, keyEndPtr, '}', depth - 1, integersAsBigInt);\n seen.add(value);\n t[k] = value;\n ptr = valueEndPtr;\n }\n }\n if (!c) {\n throw new TomlError('unfinished table encountered', {\n toml: str,\n ptr: ptr,\n });\n }\n return [res, ptr];\n}\nexport function parseArray(str, ptr, depth, integersAsBigInt) {\n let res = [];\n let c;\n ptr++;\n while ((c = str[ptr++]) !== ']' && c) {\n if (c === ',') {\n throw new TomlError('expected value, found comma', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n else if (c === '#')\n ptr = skipComment(str, ptr);\n else if (c !== ' ' && c !== '\\t' && c !== '\\n' && c !== '\\r') {\n let e = extractValue(str, ptr - 1, ']', depth - 1, integersAsBigInt);\n res.push(e[0]);\n ptr = e[1];\n }\n }\n if (!c) {\n throw new TomlError('unfinished array encountered', {\n toml: str,\n ptr: ptr,\n });\n }\n return [res, ptr];\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseKey } from './struct.js';\nimport { extractValue } from './extract.js';\nimport { skipVoid } from './util.js';\nimport { TomlError } from './error.js';\nfunction peekTable(key, table, meta, type) {\n let t = table;\n let m = meta;\n let k;\n let hasOwn = false;\n let state;\n for (let i = 0; i < key.length; i++) {\n if (i) {\n t = hasOwn ? t[k] : (t[k] = {});\n m = (state = m[k]).c;\n if (type === 0 /* Type.DOTTED */ && (state.t === 1 /* Type.EXPLICIT */ || state.t === 2 /* Type.ARRAY */)) {\n return null;\n }\n if (state.t === 2 /* Type.ARRAY */) {\n let l = t.length - 1;\n t = t[l];\n m = m[l].c;\n }\n }\n k = key[i];\n if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 /* Type.DOTTED */ && m[k]?.d) {\n return null;\n }\n if (!hasOwn) {\n if (k === '__proto__') {\n Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });\n Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });\n }\n m[k] = {\n t: i < key.length - 1 && type === 2 /* Type.ARRAY */\n ? 3 /* Type.ARRAY_DOTTED */\n : type,\n d: false,\n i: 0,\n c: {},\n };\n }\n }\n state = m[k];\n if (state.t !== type && !(type === 1 /* Type.EXPLICIT */ && state.t === 3 /* Type.ARRAY_DOTTED */)) {\n // Bad key type!\n return null;\n }\n if (type === 2 /* Type.ARRAY */) {\n if (!state.d) {\n state.d = true;\n t[k] = [];\n }\n t[k].push(t = {});\n state.c[state.i++] = (state = { t: 1 /* Type.EXPLICIT */, d: false, i: 0, c: {} });\n }\n if (state.d) {\n // Redefining a table!\n return null;\n }\n state.d = true;\n if (type === 1 /* Type.EXPLICIT */) {\n t = hasOwn ? t[k] : (t[k] = {});\n }\n else if (type === 0 /* Type.DOTTED */ && hasOwn) {\n return null;\n }\n return [k, t, state.c];\n}\nexport function parse(toml, { maxDepth = 1000, integersAsBigInt } = {}) {\n let res = {};\n let meta = {};\n let tbl = res;\n let m = meta;\n for (let ptr = skipVoid(toml, 0); ptr < toml.length;) {\n if (toml[ptr] === '[') {\n let isTableArray = toml[++ptr] === '[';\n let k = parseKey(toml, ptr += +isTableArray, ']');\n if (isTableArray) {\n if (toml[k[1] - 1] !== ']') {\n throw new TomlError('expected end of table declaration', {\n toml: toml,\n ptr: k[1] - 1,\n });\n }\n k[1]++;\n }\n let p = peekTable(k[0], res, meta, isTableArray ? 2 /* Type.ARRAY */ : 1 /* Type.EXPLICIT */);\n if (!p) {\n throw new TomlError('trying to redefine an already defined table or value', {\n toml: toml,\n ptr: ptr,\n });\n }\n m = p[2];\n tbl = p[1];\n ptr = k[1];\n }\n else {\n let k = parseKey(toml, ptr);\n let p = peekTable(k[0], tbl, m, 0 /* Type.DOTTED */);\n if (!p) {\n throw new TomlError('trying to redefine an already defined table or value', {\n toml: toml,\n ptr: ptr,\n });\n }\n let v = extractValue(toml, k[1], void 0, maxDepth, integersAsBigInt);\n p[1][p[0]] = v[0];\n ptr = v[1];\n }\n ptr = skipVoid(toml, ptr, true);\n if (toml[ptr] && toml[ptr] !== '\\n' && toml[ptr] !== '\\r') {\n throw new TomlError('each key-value declaration must be followed by an end-of-line', {\n toml: toml,\n ptr: ptr\n });\n }\n ptr = skipVoid(toml, ptr);\n }\n return res;\n}\n","import pc from \"picocolors\";\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\n\n/** Try to render a JSON value as a human-readable table. Returns null if shape isn't recognized. */\nexport function renderTable(value: JsonValue): string | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n\n const v = value as Record<string, JsonValue>;\n\n if (\"alerts\" in v && \"scan_duration_ms\" in v) return renderScan(v);\n if (\"holders\" in v) return renderWhales(v);\n if (\"opportunities\" in v && \"total_opportunities\" in v) return renderCompare(v);\n if (\"arb_opportunities\" in v && \"rates\" in v) return renderYieldScan(v);\n if (\"rates\" in v && \"asset\" in v) return renderYield(v);\n if (\"chains\" in v && \"total_alerts\" in v) return renderScanAll(v);\n if (\"chains\" in v && \"chains_scanned\" in v) return renderPositions(v);\n if (\"bridge\" in v && \"amount_out\" in v) return renderBridge(v);\n if (\"aggregator\" in v && \"amount_out\" in v) return renderSwap(v);\n if (\"protocols\" in v && \"summary\" in v) return renderStatus(v);\n if (\"token_balances\" in v && \"lending_positions\" in v) return renderPortfolio(v);\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Simple table helpers (no external dep)\n// ---------------------------------------------------------------------------\n\nfunction makeTable(headers: string[], rows: string[][]): string {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").replace(/\\x1b\\[[0-9;]*m/g, \"\").length))\n );\n\n const sep = \"┼\" + colWidths.map((w) => \"─\".repeat(w + 2)).join(\"┼\") + \"┼\";\n const topBorder = \"┌\" + colWidths.map((w) => \"─\".repeat(w + 2)).join(\"┬\") + \"┐\";\n const midBorder = \"├\" + colWidths.map((w) => \"─\".repeat(w + 2)).join(\"┼\") + \"┤\";\n const botBorder = \"└\" + colWidths.map((w) => \"─\".repeat(w + 2)).join(\"┴\") + \"┘\";\n\n function padCell(text: string, width: number): string {\n const visLen = text.replace(/\\x1b\\[[0-9;]*m/g, \"\").length;\n return text + \" \".repeat(Math.max(0, width - visLen));\n }\n\n const headerRow = \"│ \" + headers.map((h, i) => padCell(pc.bold(h), colWidths[i])).join(\" │ \") + \" │\";\n const dataRows = rows.map(\n (row) => \"│ \" + row.map((cell, i) => padCell(cell ?? \"\", colWidths[i])).join(\" │ \") + \" │\"\n );\n\n return [topBorder, headerRow, midBorder, ...dataRows, botBorder].join(\"\\n\");\n}\n\nfunction asStr(v: JsonValue | undefined): string {\n if (v === undefined || v === null) return \"?\";\n return String(v);\n}\n\nfunction asF64(v: JsonValue | undefined): number {\n if (typeof v === \"number\") return v;\n if (typeof v === \"string\") return parseFloat(v) || 0;\n return 0;\n}\n\nfunction asU64(v: JsonValue | undefined): number {\n if (typeof v === \"number\") return Math.floor(v);\n if (typeof v === \"string\") return parseInt(v, 10) || 0;\n return 0;\n}\n\nfunction asArr(v: JsonValue | undefined): JsonValue[] {\n if (Array.isArray(v)) return v;\n return [];\n}\n\nfunction asObj(v: JsonValue | undefined): Record<string, JsonValue> {\n if (v && typeof v === \"object\" && !Array.isArray(v)) return v as Record<string, JsonValue>;\n return {};\n}\n\nfunction formatPrice(v: JsonValue | undefined): string {\n const p = asF64(v);\n if (p === 0) return \"?\";\n return p > 1000 ? `$${p.toFixed(0)}` : `$${p.toFixed(4)}`;\n}\n\n// ---------------------------------------------------------------------------\n// Renderers\n// ---------------------------------------------------------------------------\n\nfunction renderScan(v: Record<string, JsonValue>): string {\n const chain = asStr(v[\"chain\"]);\n const ms = asU64(v[\"scan_duration_ms\"]);\n const count = asU64(v[\"alert_count\"]);\n let out = ` Scan: ${chain} (${ms} ms)\\n`;\n\n if (count > 0) {\n const rows = asArr(v[\"alerts\"]).map((a) => {\n const ao = asObj(a as JsonValue);\n const sev = asStr(ao[\"severity\"]);\n const color = sev === \"critical\" ? pc.red : sev === \"high\" ? pc.yellow : pc.cyan;\n return [\n color(sev.toUpperCase()),\n asStr(ao[\"pattern\"]),\n asStr(ao[\"asset\"]),\n formatPrice(ao[\"oracle_price\"]),\n formatPrice(ao[\"dex_price\"]),\n `${asF64(ao[\"deviation_pct\"]).toFixed(1)}%`,\n ];\n });\n out += makeTable([\"Severity\", \"Pattern\", \"Asset\", \"Oracle\", \"DEX\", \"Gap\"], rows);\n } else {\n out += ` ${count} alerts\\n`;\n }\n\n const data = asObj(v[\"data\"]);\n const o = Object.keys(asObj(data[\"oracle_prices\"])).length;\n const d = Object.keys(asObj(data[\"dex_prices\"])).length;\n const s = Object.keys(asObj(data[\"stablecoin_pegs\"])).length;\n out += `\\n Data: ${o} oracle, ${d} dex, ${s} stablecoin prices`;\n return out;\n}\n\nfunction renderScanAll(v: Record<string, JsonValue>): string {\n const total = asU64(v[\"total_alerts\"]);\n const scanned = asU64(v[\"chains_scanned\"]);\n const ms = asU64(v[\"scan_duration_ms\"]);\n\n const rows = asArr(v[\"chains\"]).map((c) => {\n const co = asObj(c as JsonValue);\n const alerts = asU64(co[\"alert_count\"]);\n const cms = asU64(co[\"scan_duration_ms\"]);\n const details = asArr(co[\"alerts\"])\n .map((a) => asStr(asObj(a as JsonValue)[\"asset\"]))\n .join(\", \") || \"clean\";\n const alertStr = alerts > 0 ? pc.yellow(String(alerts)) : pc.green(String(alerts));\n return [asStr(co[\"chain\"]), alertStr, `${cms}ms`, details];\n });\n\n return ` All-chain scan: ${scanned} chains, ${total} alerts, ${ms}ms\\n\\n` +\n makeTable([\"Chain\", \"Alerts\", \"Time\", \"Details\"], rows);\n}\n\nfunction renderWhales(v: Record<string, JsonValue>): string {\n const chain = asStr(v[\"chain\"]);\n const token = asStr(v[\"token\"]);\n\n const rows = asArr(v[\"holders\"]).map((h) => {\n const ho = asObj(h as JsonValue);\n const addr = asStr(ho[\"address\"]);\n const short = addr.length > 18 ? `${addr.slice(0, 10)}...${addr.slice(-6)}` : addr;\n return [String(asU64(ho[\"rank\"])), short, asF64(ho[\"balance\"]).toFixed(2)];\n });\n\n return ` ${chain} ${token} Top Holders\\n\\n` + makeTable([\"#\", \"Address\", `${token} Balance`], rows);\n}\n\nfunction renderYield(v: Record<string, JsonValue>): string {\n const chain = asStr(v[\"chain\"]);\n const asset = asStr(v[\"asset\"]);\n\n const rows = asArr(v[\"rates\"]).map((r) => {\n const ro = asObj(r as JsonValue);\n const supply = asF64(ro[\"supply_apy\"]);\n const borrow = asF64(ro[\"borrow_variable_apy\"]);\n const color = supply > 3 ? pc.green : supply > 1 ? pc.cyan : (s: string) => s;\n return [asStr(ro[\"protocol\"]), color(`${supply.toFixed(2)}%`), `${borrow.toFixed(2)}%`];\n });\n\n const best = asStr(v[\"best_supply\"]);\n return ` ${chain} ${asset} Yield Comparison (best: ${best})\\n\\n` +\n makeTable([\"Protocol\", \"Supply APY\", \"Borrow APY\"], rows);\n}\n\nfunction renderPositions(v: Record<string, JsonValue>): string {\n const addr = asStr(v[\"address\"]);\n const summary = asObj(v[\"summary\"]);\n const total = asF64(v[\"total_value_usd\"] ?? summary[\"total_value_usd\"]);\n const ms = asU64(v[\"scan_duration_ms\"]);\n const scanned = asU64(v[\"chains_scanned\"]);\n\n let out = ` Positions for ${addr.slice(0, 8)}...${addr.slice(-4)} (${ms}ms, ${scanned} chains)\\n Total: $${total.toFixed(2)}\\n\\n`;\n\n for (const c of asArr(v[\"chains\"])) {\n const co = asObj(c as JsonValue);\n const chain = asStr(co[\"chain\"]);\n const ctotal = asF64(co[\"chain_total_usd\"]);\n out += ` ${chain} ($${ctotal.toFixed(2)})\\n`;\n\n const rows: string[][] = [];\n for (const b of asArr(co[\"token_balances\"])) {\n const bo = asObj(b as JsonValue);\n rows.push([\"wallet\", asStr(bo[\"symbol\"]), pc.green(`$${asF64(bo[\"value_usd\"]).toFixed(2)}`)]);\n }\n for (const l of asArr(co[\"lending_positions\"])) {\n const lo = asObj(l as JsonValue);\n const coll = asF64(lo[\"collateral_usd\"]);\n const debt = asF64(lo[\"debt_usd\"]);\n rows.push([\"lending\", asStr(lo[\"protocol\"]), pc.cyan(`coll $${coll.toFixed(0)} debt $${debt.toFixed(0)}`)]);\n }\n out += makeTable([\"Type\", \"Asset/Protocol\", \"Value\"], rows) + \"\\n\";\n }\n return out;\n}\n\nfunction renderSwap(v: Record<string, JsonValue>): string {\n const from = asStr(v[\"from\"]);\n const to = asStr(v[\"to\"]);\n const amtIn = asF64(v[\"amount_in\"]);\n const amtOut = asF64(v[\"amount_out\"]);\n const impact = typeof v[\"price_impact_pct\"] === \"number\"\n ? `${asF64(v[\"price_impact_pct\"]).toFixed(4)}%`\n : \"n/a\";\n const agg = asStr(v[\"aggregator\"]);\n const chain = asStr(v[\"chain\"]);\n return ` Swap on ${chain} via ${agg}\\n\\n ${amtIn} ${from} -> ${amtOut.toFixed(6)} ${to}\\n Price impact: ${impact}\\n`;\n}\n\nfunction renderBridge(v: Record<string, JsonValue>): string {\n const from = asStr(v[\"from_chain\"]);\n const to = asStr(v[\"to_chain\"]);\n const token = asStr(v[\"token\"]);\n const amtIn = asF64(v[\"amount_in\"]);\n const amtOut = asF64(v[\"amount_out\"]);\n const cost = asF64(v[\"total_cost_usd\"]);\n const time = asU64(v[\"estimated_time_sec\"]);\n const bridge = asStr(v[\"bridge\"]);\n return ` Bridge ${from} -> ${to} via ${bridge}\\n\\n ${amtIn} ${token} -> ${amtOut.toFixed(6)} ${token}\\n Cost: $${cost.toFixed(2)} | Time: ${time}s\\n`;\n}\n\nfunction renderStatus(v: Record<string, JsonValue>): string {\n const chain = asStr(v[\"chain\"]);\n const summary = asObj(v[\"summary\"]);\n const totalP = asU64(summary[\"total_protocols\"]);\n const totalT = asU64(summary[\"total_tokens\"]);\n\n const rows = asArr(v[\"protocols\"]).map((p) => {\n const po = asObj(p as JsonValue);\n return [asStr(po[\"name\"]), asStr(po[\"category\"]), asStr(po[\"interface\"])];\n });\n\n const tokens = asArr(v[\"tokens\"]).map((t) => String(t)).filter(Boolean);\n let out = ` ${chain} — ${totalP} protocols`;\n if (tokens.length > 0) {\n out += `, ${totalT} tokens\\n Tokens: ${tokens.join(\", \")}`;\n }\n return `${out}\\n\\n` + makeTable([\"Protocol\", \"Category\", \"Interface\"], rows);\n}\n\nfunction renderCompare(v: Record<string, JsonValue>): string {\n const asset = asStr(v[\"asset\"]);\n const ms = asU64(v[\"scan_duration_ms\"]);\n const total = asU64(v[\"total_opportunities\"]);\n\n const rows = asArr(v[\"opportunities\"]).map((opp) => {\n const oo = asObj(opp as JsonValue);\n const typ = asStr(oo[\"type\"]);\n const apy = asF64(oo[\"apy\"]);\n const detail = asStr(oo[\"detail\"]);\n const risk = asStr(oo[\"risk\"]);\n const oppAsset = asStr(oo[\"asset\"]);\n\n const typeLabel = typ === \"perp_funding\" ? \"Perp Arb\"\n : typ === \"perp_rate\" ? \"Perp Rate\"\n : typ === \"lending_supply\" ? \"Lending\"\n : typ;\n\n const apyColor = Math.abs(apy) > 20 ? pc.green : Math.abs(apy) > 5 ? pc.cyan : (s: string) => s;\n const riskColor = risk === \"high\" ? pc.red : risk === \"medium\" ? pc.yellow : pc.green;\n\n return [typeLabel, oppAsset, apyColor(`${apy.toFixed(1)}%`), detail, riskColor(risk)];\n });\n\n return ` Yield Compare: ${asset} (${total} opportunities, ${ms}ms)\\n\\n` +\n makeTable([\"Type\", \"Asset\", \"APY\", \"Where\", \"Risk\"], rows);\n}\n\nfunction renderYieldScan(v: Record<string, JsonValue>): string {\n const asset = asStr(v[\"asset\"]);\n const ms = asU64(v[\"scan_duration_ms\"]);\n const best = asStr(v[\"best_supply\"]);\n\n const rows = asArr(v[\"rates\"]).map((r) => {\n const ro = asObj(r as JsonValue);\n const supply = asF64(ro[\"supply_apy\"]);\n const borrow = asF64(ro[\"borrow_variable_apy\"]);\n const color = supply > 3 ? pc.green : supply > 1 ? pc.cyan : (s: string) => s;\n return [asStr(ro[\"chain\"]), asStr(ro[\"protocol\"]), color(`${supply.toFixed(2)}%`), `${borrow.toFixed(2)}%`];\n });\n\n let out = ` ${asset} Yield Scan (${ms}ms) — Best: ${best}\\n\\n` +\n makeTable([\"Chain\", \"Protocol\", \"Supply APY\", \"Borrow APY\"], rows);\n\n const arbs = asArr(v[\"arb_opportunities\"]);\n if (arbs.length > 0) {\n const arbRows = arbs.map((a) => {\n const ao = asObj(a as JsonValue);\n const spread = asF64(ao[\"spread_pct\"]);\n const color = spread > 1 ? pc.green : pc.cyan;\n return [\n color(`+${spread.toFixed(2)}%`),\n `${asStr(ao[\"supply_protocol\"])} (${asStr(ao[\"supply_chain\"])})`,\n `${asStr(ao[\"borrow_protocol\"])} (${asStr(ao[\"borrow_chain\"])})`,\n asStr(ao[\"strategy\"]),\n ];\n });\n out += \"\\n Arb Opportunities\\n\\n\" + makeTable([\"Spread\", \"Supply @\", \"Borrow @\", \"Type\"], arbRows);\n }\n\n return out;\n}\n\nfunction renderPortfolio(v: Record<string, JsonValue>): string {\n return renderPositions(v);\n}\n","import { jsonStringify, jsonReplacerDecimal } from \"@hypurrquant/defi-core\";\nimport { renderTable } from \"./table.js\";\n\nexport interface OutputMode {\n json: boolean;\n ndjson: boolean;\n fields?: string[];\n}\n\nexport function parseOutputMode(opts: {\n json?: boolean;\n ndjson?: boolean;\n fields?: string;\n}): OutputMode {\n return {\n json: !!(opts.json || opts.ndjson),\n ndjson: !!opts.ndjson,\n fields: opts.fields\n ? opts.fields.split(\",\").map((f) => f.trim())\n : undefined,\n };\n}\n\nexport function formatOutput(value: unknown, mode: OutputMode): string {\n if (mode.ndjson) {\n return JSON.stringify(value, jsonReplacerDecimal);\n }\n\n if (mode.json) {\n let jsonVal = JSON.parse(jsonStringify(value));\n\n if (mode.fields && typeof jsonVal === \"object\" && jsonVal !== null && !Array.isArray(jsonVal)) {\n const filtered: Record<string, unknown> = {};\n for (const key of mode.fields) {\n if (key in jsonVal) filtered[key] = jsonVal[key];\n }\n jsonVal = filtered;\n }\n\n return JSON.stringify(jsonVal, null, 2);\n }\n\n // Human-readable: try table format, fallback to pretty JSON\n const jsonVal = JSON.parse(jsonStringify(value));\n const table = renderTable(jsonVal);\n if (table !== null) return table;\n return JSON.stringify(jsonVal, null, 2);\n}\n\nexport function printOutput(value: unknown, mode: OutputMode): void {\n console.log(formatOutput(value, mode));\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createPublicClient, http } from \"viem\";\n\ninterface ContractStatus {\n name: string;\n address: string;\n has_code?: boolean;\n status?: string;\n}\n\ninterface ProtocolStatus {\n slug: string;\n name: string;\n category: string;\n interface: string;\n contracts: ContractStatus[];\n}\n\ninterface StatusSummary {\n total_protocols: number;\n verified_contracts?: number;\n invalid_contracts?: number;\n placeholder_contracts?: number;\n}\n\ninterface StatusOutput {\n chain: string;\n chain_id: number;\n rpc_url: string;\n block_number?: number;\n protocols: ProtocolStatus[];\n summary: StatusSummary;\n}\n\nfunction isPlaceholder(addr: string): boolean {\n if (!addr.startsWith(\"0x\") || addr.length !== 42) return false;\n const hex = addr.slice(2).toLowerCase();\n return hex.slice(0, 36).split(\"\").every((c) => c === \"0\") && parseInt(hex.slice(36), 16) <= 0x10;\n}\n\nexport function registerStatus(\n parent: Command,\n getOpts: () => OutputMode,\n): void {\n parent\n .command(\"status\")\n .description(\"Show chain and protocol status\")\n .option(\"--verify\", \"Verify contract addresses on-chain\")\n .action(async (opts) => {\n const globalOpts = parent.opts<{ chain?: string }>();\n const chainName = globalOpts.chain ?? \"hyperevm\";\n\n const registry = Registry.loadEmbedded();\n const chainConfig = registry.getChain(chainName);\n const chainProtocols = registry.getProtocolsForChain(chainName);\n\n let blockNumber: number | undefined;\n let codeMap: Map<string, boolean> | undefined;\n let placeholderCount = 0;\n\n // Count placeholders\n for (const p of chainProtocols) {\n for (const addr of Object.values(p.contracts ?? {}) as string[]) {\n if (isPlaceholder(addr)) placeholderCount++;\n }\n }\n\n if (opts.verify) {\n const rpcUrl = chainConfig.effectiveRpcUrl();\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n try {\n const bn = await client.getBlockNumber();\n blockNumber = Number(bn);\n process.stderr.write(\n `Connected to ${rpcUrl} (block #${blockNumber}). Verifying contracts...\\n`,\n );\n } catch (e) {\n process.stderr.write(`Warning: could not get block number\\n`);\n }\n\n codeMap = new Map();\n const allAddrs: Array<{ key: string; addr: Address }> = [];\n\n for (const p of chainProtocols) {\n for (const [name, addr] of Object.entries(p.contracts ?? {}) as [string, string][]) {\n if (!isPlaceholder(addr)) {\n allAddrs.push({ key: `${p.name}:${name}`, addr: addr as Address });\n }\n }\n }\n\n // Batch verify in chunks of 20\n for (let i = 0; i < allAddrs.length; i += 20) {\n const chunk = allAddrs.slice(i, i + 20);\n const results = await Promise.all(\n chunk.map(async ({ key, addr }) => {\n try {\n const code = await client.getCode({ address: addr as `0x${string}` });\n return { key, hasCode: !!code && code !== \"0x\" };\n } catch {\n return { key, hasCode: false };\n }\n }),\n );\n for (const r of results) {\n codeMap.set(r.key, r.hasCode);\n }\n }\n }\n\n // Build output\n let verifiedCount = 0;\n let invalidCount = 0;\n\n const protocols: ProtocolStatus[] = chainProtocols.map((p) => {\n const contracts: ContractStatus[] = (Object.entries(p.contracts ?? {}) as [string, string][]).map(\n ([name, addr]) => {\n if (isPlaceholder(addr)) {\n return { name, address: addr, status: \"placeholder\" };\n }\n if (codeMap) {\n const hasCode = codeMap.get(`${p.name}:${name}`) ?? false;\n if (hasCode) verifiedCount++;\n else invalidCount++;\n return {\n name,\n address: addr,\n has_code: hasCode,\n status: hasCode ? \"verified\" : \"NO_CODE\",\n };\n }\n return { name, address: addr };\n },\n );\n\n return {\n slug: p.slug,\n name: p.name,\n category: p.category,\n interface: p.interface,\n contracts,\n };\n });\n\n const output: StatusOutput = {\n chain: chainConfig.name,\n chain_id: chainConfig.chain_id,\n rpc_url: chainConfig.effectiveRpcUrl(),\n ...(blockNumber !== undefined ? { block_number: blockNumber } : {}),\n protocols,\n summary: {\n total_protocols: protocols.length,\n ...(opts.verify\n ? {\n verified_contracts: verifiedCount,\n invalid_contracts: invalidCount,\n placeholder_contracts: placeholderCount,\n }\n : {}),\n },\n };\n\n printOutput(output, getOpts());\n });\n}\n","import * as readline from \"readline\";\nimport type { Executor } from \"./executor.js\";\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type { Registry } from \"@hypurrquant/defi-core\";\n\nexport interface AgentCommand {\n action: string;\n params: unknown;\n}\n\nexport interface AgentResponse {\n action: string;\n success: boolean;\n result?: unknown;\n error?: string;\n}\n\nexport async function runAgent(registry: Registry, executor: Executor): Promise<void> {\n const rl = readline.createInterface({ input: process.stdin, terminal: false });\n\n for await (const line of rl) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n let cmd: AgentCommand;\n try {\n cmd = JSON.parse(trimmed) as AgentCommand;\n } catch (e: unknown) {\n const resp: AgentResponse = {\n action: \"unknown\",\n success: false,\n error: `Invalid JSON: ${e instanceof Error ? e.message : String(e)}`,\n };\n console.log(JSON.stringify(resp));\n continue;\n }\n\n const resp = await dispatchCommand(cmd, registry, executor);\n console.log(JSON.stringify(resp));\n }\n}\n\nasync function dispatchCommand(\n cmd: AgentCommand,\n registry: Registry,\n executor: Executor,\n): Promise<AgentResponse> {\n try {\n const result = await handleAction(cmd.action, cmd.params, registry, executor);\n return { action: cmd.action, success: true, result };\n } catch (e: unknown) {\n return {\n action: cmd.action,\n success: false,\n error: e instanceof Error ? e.message : String(e),\n };\n }\n}\n\nasync function handleAction(\n action: string,\n params: unknown,\n registry: Registry,\n executor: Executor,\n): Promise<unknown> {\n const p = (params ?? {}) as Record<string, unknown>;\n\n switch (action) {\n case \"status\":\n return handleStatus(registry);\n\n case \"list_protocols\":\n return handleListProtocols(registry, p);\n\n case \"schema\":\n return handleSchema(p);\n\n case \"dex.swap\":\n case \"dex.quote\":\n case \"lending.supply\":\n case \"lending.borrow\":\n case \"lending.repay\":\n case \"lending.withdraw\":\n case \"staking.stake\":\n case \"staking.unstake\":\n case \"vault.deposit\":\n case \"vault.withdraw\":\n case \"cdp.open\":\n throw DefiError.unsupported(`Agent action '${action}' not yet implemented in TS port`);\n\n default:\n throw DefiError.unsupported(`Unknown action: ${action}`);\n }\n}\n\nfunction handleStatus(registry: Registry): unknown {\n const chain = registry.getChain(\"hyperevm\");\n const protocols = registry.protocols.map((p) => ({\n name: p.name,\n slug: p.slug,\n category: p.category,\n interface: p.interface,\n native: p.native,\n }));\n\n return {\n chain: chain.name,\n chain_id: chain.chain_id,\n protocol_count: protocols.length,\n protocols,\n };\n}\n\nfunction handleListProtocols(registry: Registry, params: Record<string, unknown>): unknown {\n const categoryFilter = typeof params[\"category\"] === \"string\" ? params[\"category\"] : undefined;\n\n const protocols = registry.protocols\n .filter((p) => !categoryFilter || p.category.toLowerCase() === categoryFilter.toLowerCase())\n .map((p) => ({\n name: p.name,\n slug: p.slug,\n category: p.category,\n interface: p.interface,\n }));\n\n return { protocols };\n}\n\nexport function handleSchema(params: Record<string, unknown>): unknown {\n const action = typeof params[\"action\"] === \"string\" ? params[\"action\"] : \"all\";\n\n switch (action) {\n case \"dex.swap\":\n return {\n action: \"dex.swap\",\n params: {\n protocol: { type: \"string\", required: true, description: \"Protocol slug (e.g. hyperswap-v3)\" },\n token_in: { type: \"string\", required: true, description: \"Input token symbol or address\" },\n token_out: { type: \"string\", required: true, description: \"Output token symbol or address\" },\n amount: { type: \"string\", required: true, description: \"Amount (human-readable, e.g. '1.5')\" },\n slippage_bps: { type: \"number\", required: false, default: 50, description: \"Slippage in basis points\" },\n recipient: { type: \"string\", required: false, description: \"Recipient address\" },\n },\n };\n\n case \"dex.quote\":\n return {\n action: \"dex.quote\",\n params: {\n protocol: { type: \"string\", required: true, description: \"Protocol slug\" },\n token_in: { type: \"string\", required: true, description: \"Input token symbol or address\" },\n token_out: { type: \"string\", required: true, description: \"Output token symbol or address\" },\n amount: { type: \"string\", required: true, description: \"Amount (human-readable)\" },\n },\n };\n\n case \"lending.supply\":\n case \"lending.borrow\":\n case \"lending.repay\":\n case \"lending.withdraw\":\n return {\n action,\n params: {\n protocol: { type: \"string\", required: true, description: \"Protocol slug\" },\n asset: { type: \"string\", required: true, description: \"Token symbol or address\" },\n amount: { type: \"string\", required: true, description: \"Amount (human-readable)\" },\n },\n };\n\n case \"staking.stake\":\n case \"staking.unstake\":\n return {\n action,\n params: {\n protocol: { type: \"string\", required: true, description: \"Protocol slug\" },\n amount: { type: \"string\", required: true, description: \"Amount (human-readable)\" },\n },\n };\n\n case \"vault.deposit\":\n case \"vault.withdraw\":\n return {\n action,\n params: {\n protocol: { type: \"string\", required: true, description: \"Protocol slug\" },\n amount: { type: \"string\", required: true, description: \"Amount (human-readable)\" },\n },\n };\n\n case \"cdp.open\":\n return {\n action: \"cdp.open\",\n params: {\n protocol: { type: \"string\", required: true, description: \"Protocol slug\" },\n collateral: { type: \"string\", required: true, description: \"Collateral token symbol or address\" },\n collateral_amount: { type: \"string\", required: true, description: \"Collateral amount (human-readable)\" },\n debt_amount: { type: \"string\", required: true, description: \"Debt amount (human-readable)\" },\n },\n };\n\n case \"status\":\n return { action: \"status\", params: {} };\n\n case \"list_protocols\":\n return {\n action: \"list_protocols\",\n params: {\n category: { type: \"string\", required: false, description: \"Filter by category (e.g. dex, lending, vault)\" },\n },\n };\n\n default:\n return {\n actions: [\n \"status\", \"list_protocols\", \"schema\",\n \"dex.swap\", \"dex.quote\",\n \"lending.supply\", \"lending.borrow\", \"lending.repay\", \"lending.withdraw\",\n \"staking.stake\", \"staking.unstake\",\n \"vault.deposit\", \"vault.withdraw\",\n \"cdp.open\",\n ],\n };\n }\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { handleSchema } from \"../agent.js\";\n\nexport function registerSchema(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"schema [command]\")\n .description(\"Output JSON schema for a command (agent-friendly)\")\n .option(\"--all\", \"Show all schemas\")\n .action(async (command: string | undefined, opts: { all?: boolean }) => {\n const mode = getOpts();\n const action = opts.all ? \"all\" : (command ?? \"all\");\n const params: Record<string, unknown> = { action };\n const schema = handleSchema(params);\n printOutput(schema, mode);\n });\n}\n","import { DefiError } from \"@hypurrquant/defi-core\";\nimport type { ProtocolEntry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\n\n// DEX adapters\nimport { UniswapV3Adapter } from \"./dex/uniswap_v3.js\";\nimport { UniswapV2Adapter } from \"./dex/uniswap_v2.js\";\nimport { AlgebraV3Adapter } from \"./dex/algebra_v3.js\";\nimport { BalancerV3Adapter } from \"./dex/balancer_v3.js\";\nimport { CurveStableSwapAdapter } from \"./dex/curve.js\";\nimport { SolidlyAdapter } from \"./dex/solidly.js\";\nimport { ThenaCLAdapter } from \"./dex/thena_cl.js\";\nimport { HybraGaugeAdapter } from \"./dex/hybra_gauge.js\";\nimport { WooFiAdapter } from \"./dex/woofi.js\";\nimport { SolidlyGaugeAdapter } from \"./dex/solidly_gauge.js\";\nimport { MasterChefAdapter } from \"./dex/masterchef.js\";\nimport { MerchantMoeLBAdapter } from \"./dex/merchant_moe_lb.js\";\nimport { KittenSwapFarmingAdapter } from \"./dex/kittenswap_farming.js\";\n\n// Trait interfaces\nimport type { IDex } from \"@hypurrquant/defi-core\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport type { ICdp } from \"@hypurrquant/defi-core\";\nimport type { IVault } from \"@hypurrquant/defi-core\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport type { IGaugeSystem } from \"@hypurrquant/defi-core\";\nimport type { IGauge } from \"@hypurrquant/defi-core\";\nimport type { IYieldSource } from \"@hypurrquant/defi-core\";\nimport type { IDerivatives } from \"@hypurrquant/defi-core\";\nimport type { IOptions } from \"@hypurrquant/defi-core\";\nimport type { IOracle } from \"@hypurrquant/defi-core\";\nimport type { INft } from \"@hypurrquant/defi-core\";\n\n// Lending adapters\nimport { AaveV3Adapter } from \"./lending/aave_v3.js\";\nimport { AaveV2Adapter } from \"./lending/aave_v2.js\";\nimport { AaveOracleAdapter } from \"./lending/aave_oracle.js\";\nimport { CompoundV2Adapter } from \"./lending/compound_v2.js\";\nimport { CompoundV3Adapter } from \"./lending/compound_v3.js\";\nimport { EulerV2Adapter } from \"./lending/euler_v2.js\";\nimport { MorphoBlueAdapter } from \"./lending/morpho.js\";\n\n// CDP adapters\nimport { FelixCdpAdapter } from \"./cdp/felix.js\";\nimport { FelixOracleAdapter } from \"./cdp/felix_oracle.js\";\n\n// Vault adapters\nimport { ERC4626VaultAdapter } from \"./vault/erc4626.js\";\n\n// Liquid staking adapters\nimport { GenericLstAdapter } from \"./liquid_staking/generic_lst.js\";\nimport { StHypeAdapter } from \"./liquid_staking/sthype.js\";\nimport { KinetiqAdapter } from \"./liquid_staking/kinetiq.js\";\n\n// Yield source adapters\nimport { PendleAdapter } from \"./yield_source/pendle.js\";\nimport { GenericYieldAdapter } from \"./yield_source/generic_yield.js\";\n\n// Derivatives adapters\nimport { HlpVaultAdapter } from \"./derivatives/hlp.js\";\nimport { GenericDerivativesAdapter } from \"./derivatives/generic_derivatives.js\";\n\n// Options adapters\nimport { RyskAdapter } from \"./options/rysk.js\";\nimport { GenericOptionsAdapter } from \"./options/generic_options.js\";\n\n// NFT adapters\nimport { ERC721Adapter } from \"./nft/erc721.js\";\n\n// ============================================================\n// DEX\n// ============================================================\n\n/** Create a Dex implementation from a protocol registry entry */\nexport function createDex(entry: ProtocolEntry, rpcUrl?: string): IDex {\n switch (entry.interface) {\n case \"uniswap_v3\":\n return new UniswapV3Adapter(entry, rpcUrl);\n case \"uniswap_v4\":\n throw DefiError.unsupported(\n `[${entry.name}] Uniswap V4 (singleton PoolManager) is not yet supported — use HyperSwap V3 or another V3-compatible DEX for quotes`,\n );\n case \"algebra_v3\":\n return new AlgebraV3Adapter(entry, rpcUrl);\n case \"uniswap_v2\":\n return new UniswapV2Adapter(entry, rpcUrl);\n case \"solidly_v2\":\n case \"solidly_cl\":\n return new SolidlyAdapter(entry, rpcUrl);\n case \"hybra\":\n return new ThenaCLAdapter(entry, rpcUrl);\n case \"curve_stableswap\":\n return new CurveStableSwapAdapter(entry);\n case \"balancer_v3\":\n return new BalancerV3Adapter(entry);\n case \"woofi\":\n return new WooFiAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`DEX interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// Lending\n// ============================================================\n\n/** Create a Lending implementation from a protocol registry entry */\nexport function createLending(entry: ProtocolEntry, rpcUrl?: string): ILending {\n switch (entry.interface) {\n case \"aave_v3\":\n case \"aave_v3_isolated\":\n return new AaveV3Adapter(entry, rpcUrl);\n case \"aave_v2\":\n return new AaveV2Adapter(entry, rpcUrl);\n case \"morpho_blue\":\n return new MorphoBlueAdapter(entry, rpcUrl);\n case \"euler_v2\":\n return new EulerV2Adapter(entry, rpcUrl);\n case \"compound_v2\":\n return new CompoundV2Adapter(entry, rpcUrl);\n case \"compound_v3\":\n return new CompoundV3Adapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Lending interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// CDP\n// ============================================================\n\n/** Create a CDP implementation from a protocol registry entry */\nexport function createCdp(entry: ProtocolEntry, rpcUrl?: string): ICdp {\n switch (entry.interface) {\n case \"liquity_v2\":\n return new FelixCdpAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`CDP interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// Vault\n// ============================================================\n\n/** Create a Vault implementation from a protocol registry entry */\nexport function createVault(entry: ProtocolEntry, rpcUrl?: string): IVault {\n switch (entry.interface) {\n case \"erc4626\":\n case \"beefy_vault\":\n return new ERC4626VaultAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Vault interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// Liquid Staking\n// ============================================================\n\n/** Create a LiquidStaking implementation from a protocol registry entry */\nexport function createLiquidStaking(entry: ProtocolEntry, rpcUrl?: string): ILiquidStaking {\n switch (entry.interface) {\n case \"kinetiq_staking\":\n return new KinetiqAdapter(entry, rpcUrl);\n case \"sthype_staking\":\n return new StHypeAdapter(entry, rpcUrl);\n case \"hyperbeat_lst\":\n case \"kintsu\":\n return new GenericLstAdapter(entry, rpcUrl);\n default:\n return new GenericLstAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// Gauge\n// ============================================================\n\n/** Create a GaugeSystem implementation from a protocol registry entry */\nexport function createGauge(entry: ProtocolEntry, rpcUrl?: string): IGaugeSystem {\n // Hybra has its own GaugeManager system\n if (entry.interface === \"hybra\" || entry.contracts?.[\"gauge_manager\"]) {\n return new HybraGaugeAdapter(entry, rpcUrl);\n }\n switch (entry.interface) {\n case \"solidly_v2\":\n case \"solidly_cl\":\n case \"algebra_v3\":\n return new SolidlyGaugeAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Gauge interface '${entry.interface}' not supported`);\n }\n}\n\n/** Create a MasterChef IGauge implementation from a protocol registry entry */\nexport function createMasterChef(entry: ProtocolEntry, rpcUrl?: string): IGauge {\n return new MasterChefAdapter(entry, rpcUrl);\n}\n\n// ============================================================\n// Yield Source (fallback to GenericYield)\n// ============================================================\n\n/** Create a YieldSource implementation — falls back to GenericYield for unknown interfaces */\nexport function createYieldSource(entry: ProtocolEntry, rpcUrl?: string): IYieldSource {\n switch (entry.interface) {\n case \"pendle_v2\":\n return new PendleAdapter(entry, rpcUrl);\n default:\n return new GenericYieldAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// Derivatives (fallback to GenericDerivatives)\n// ============================================================\n\n/** Create a Derivatives implementation — falls back to GenericDerivatives for unknown interfaces */\nexport function createDerivatives(entry: ProtocolEntry, rpcUrl?: string): IDerivatives {\n switch (entry.interface) {\n case \"hlp_vault\":\n return new HlpVaultAdapter(entry, rpcUrl);\n default:\n return new GenericDerivativesAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// Options (fallback to GenericOptions)\n// ============================================================\n\n/** Create an Options implementation — falls back to GenericOptions for unknown interfaces */\nexport function createOptions(entry: ProtocolEntry, rpcUrl?: string): IOptions {\n switch (entry.interface) {\n case \"rysk\":\n return new RyskAdapter(entry, rpcUrl);\n default:\n return new GenericOptionsAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// NFT\n// ============================================================\n\n/** Create an NFT implementation from a protocol registry entry */\nexport function createNft(entry: ProtocolEntry, rpcUrl?: string): INft {\n switch (entry.interface) {\n case \"erc721\":\n return new ERC721Adapter(entry, rpcUrl);\n case \"marketplace\":\n throw DefiError.unsupported(`NFT marketplace '${entry.name}' is not queryable as ERC-721. Use a specific collection address.`);\n default:\n throw DefiError.unsupported(`NFT interface '${entry.interface}' not supported`);\n }\n}\n\n// ============================================================\n// Oracle from Lending\n// ============================================================\n\n/** Create an Oracle from a lending protocol entry (Aave V3 forks have an oracle contract) */\nexport function createOracleFromLending(entry: ProtocolEntry, rpcUrl: string): IOracle {\n switch (entry.interface) {\n case \"aave_v3\":\n case \"aave_v3_isolated\":\n return new AaveOracleAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Oracle not available for lending interface '${entry.interface}'`);\n }\n}\n\n// ============================================================\n// Oracle from CDP\n// ============================================================\n\n/** Create an Oracle from a CDP protocol entry (Felix has its own PriceFeed contract) */\nexport function createOracleFromCdp(entry: ProtocolEntry, _asset: Address, rpcUrl: string): IOracle {\n switch (entry.interface) {\n case \"liquity_v2\":\n return new FelixOracleAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Oracle not available for CDP interface '${entry.interface}'`);\n }\n}\n\n// ============================================================\n// Merchant Moe LB\n// ============================================================\n\n/** Create a MerchantMoeLBAdapter for Liquidity Book operations */\nexport function createMerchantMoeLB(entry: ProtocolEntry, rpcUrl?: string): MerchantMoeLBAdapter {\n return new MerchantMoeLBAdapter(entry, rpcUrl);\n}\n\n// ============================================================\n// KittenSwap Algebra Farming\n// ============================================================\n\n/** Create a KittenSwapFarmingAdapter for Algebra eternal farming operations */\nexport function createKittenSwapFarming(entry: ProtocolEntry, rpcUrl: string): KittenSwapFarmingAdapter {\n const farmingCenter = entry.contracts?.[\"farming_center\"];\n if (!farmingCenter) {\n throw new DefiError(\"CONTRACT_ERROR\", `[${entry.name}] Missing 'farming_center' contract address`);\n }\n const eternalFarming = entry.contracts?.[\"eternal_farming\"];\n if (!eternalFarming) {\n throw new DefiError(\"CONTRACT_ERROR\", `[${entry.name}] Missing 'eternal_farming' contract address`);\n }\n const positionManager = entry.contracts?.[\"position_manager\"];\n if (!positionManager) {\n throw new DefiError(\"CONTRACT_ERROR\", `[${entry.name}] Missing 'position_manager' contract address`);\n }\n const factory = entry.contracts?.[\"factory\"] as Address | undefined;\n return new KittenSwapFarmingAdapter(entry.name, farmingCenter, eternalFarming, positionManager, rpcUrl, factory);\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst DEFAULT_FEE = 3000;\n\nconst swapRouterAbi = parseAbi([\n \"struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; }\",\n \"function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut)\",\n]);\n\nconst quoterAbi = parseAbi([\n \"struct QuoteExactInputSingleParams { address tokenIn; address tokenOut; uint256 amountIn; uint24 fee; uint160 sqrtPriceLimitX96; }\",\n \"function quoteExactInputSingle(QuoteExactInputSingleParams memory params) external returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\",\n]);\n\n// Ramses CL uses tickSpacing instead of fee in the quoter struct\nconst ramsesQuoterAbi = parseAbi([\n \"struct QuoteExactInputSingleParams { address tokenIn; address tokenOut; uint256 amountIn; int24 tickSpacing; uint160 sqrtPriceLimitX96; }\",\n \"function quoteExactInputSingle(QuoteExactInputSingleParams memory params) external returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\",\n]);\n\nconst positionManagerAbi = parseAbi([\n \"struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; }\",\n \"function mint(MintParams calldata params) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)\",\n]);\n\nexport class UniswapV3Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly quoter: Address | undefined;\n private readonly positionManager: Address | undefined;\n private readonly factory: Address | undefined;\n private readonly fee: number;\n private readonly rpcUrl: string | undefined;\n private readonly useTickSpacingQuoter: boolean;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.quoter = entry.contracts?.[\"quoter\"];\n this.positionManager = entry.contracts?.[\"position_manager\"];\n this.factory = entry.contracts?.[\"factory\"];\n this.fee = DEFAULT_FEE;\n this.rpcUrl = rpcUrl;\n // Ramses CL and similar forks use tickSpacing-based pool identification\n this.useTickSpacingQuoter = entry.contracts?.[\"pool_deployer\"] !== undefined\n || entry.contracts?.[\"gauge_factory\"] !== undefined;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n const amountOutMinimum = 0n;\n\n const data = encodeFunctionData({\n abi: swapRouterAbi,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n fee: this.fee,\n recipient: params.recipient,\n deadline,\n amountIn: params.amount_in,\n amountOutMinimum,\n sqrtPriceLimitX96: 0n,\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokenIn for tokenOut`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 200_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured\");\n }\n\n if (this.quoter) {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // Try tickSpacing-based quoter first for Ramses CL and similar forks\n if (this.useTickSpacingQuoter) {\n const tickSpacings = [1, 10, 50, 100, 200];\n const tsResults = await Promise.allSettled(\n tickSpacings.map(async (ts) => {\n const result = await client.call({\n to: this.quoter!,\n data: encodeFunctionData({\n abi: ramsesQuoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n amountIn: params.amount_in,\n tickSpacing: ts,\n sqrtPriceLimitX96: 0n,\n },\n ],\n }),\n });\n if (!result.data) return { amountOut: 0n, tickSpacing: ts };\n const [amountOut] = decodeAbiParameters(\n [{ name: \"amountOut\", type: \"uint256\" }],\n result.data,\n );\n return { amountOut, tickSpacing: ts };\n }),\n );\n\n let best = { amountOut: 0n, tickSpacing: 50 };\n for (const r of tsResults) {\n if (r.status === \"fulfilled\" && r.value.amountOut > best.amountOut) {\n best = r.value;\n }\n }\n\n if (best.amountOut > 0n) {\n return {\n protocol: this.protocolName,\n amount_out: best.amountOut,\n price_impact_bps: undefined,\n fee_bps: undefined,\n route: [`${params.token_in} -> ${params.token_out} (tickSpacing: ${best.tickSpacing})`],\n };\n }\n\n // tickSpacing-based protocol (Ramses CL): quoter returned no result.\n // Pool exists but has no liquidity in this fork snapshot.\n throw DefiError.rpcError(\n `[${this.protocolName}] No quote available — pool exists but has zero liquidity for this pair`,\n );\n }\n\n // Standard Uniswap V3 fee-based quoter\n const feeTiers = [500, 3000, 10000, 100];\n const results = await Promise.allSettled(\n feeTiers.map(async (fee) => {\n const result = await client.call({\n to: this.quoter!,\n data: encodeFunctionData({\n abi: quoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n amountIn: params.amount_in,\n fee,\n sqrtPriceLimitX96: 0n,\n },\n ],\n }),\n });\n if (!result.data) return { amountOut: 0n, fee };\n const [amountOut] = decodeAbiParameters(\n [{ name: \"amountOut\", type: \"uint256\" }],\n result.data,\n );\n return { amountOut, fee };\n }),\n );\n\n let best = { amountOut: 0n, fee: 3000 };\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value.amountOut > best.amountOut) {\n best = r.value;\n }\n }\n\n if (best.amountOut > 0n) {\n return {\n protocol: this.protocolName,\n amount_out: best.amountOut,\n price_impact_bps: undefined,\n fee_bps: Math.floor(best.fee / 10),\n route: [`${params.token_in} -> ${params.token_out} (fee: ${best.fee})`],\n };\n }\n }\n\n // Fallback: simulate swap via eth_call on the router\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const callData = encodeFunctionData({\n abi: swapRouterAbi,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n fee: this.fee,\n recipient: \"0x0000000000000000000000000000000000000001\",\n deadline: BigInt(\"18446744073709551615\"),\n amountIn: params.amount_in,\n amountOutMinimum: 0n,\n sqrtPriceLimitX96: 0n,\n },\n ],\n });\n\n let output: `0x${string}` | undefined;\n try {\n const result = await client.call({ to: this.router, data: callData });\n output = result.data;\n } catch (e: unknown) {\n const errMsg = String(e);\n if (errMsg.includes(\"STF\") || errMsg.includes(\"insufficient\")) {\n throw DefiError.unsupported(\n `[${this.protocolName}] quote unavailable — no quoter contract configured. Swap simulation requires token balance. Add a quoter address to the protocol config.`,\n );\n }\n throw DefiError.rpcError(`[${this.protocolName}] swap simulation for quote failed: ${errMsg}`);\n }\n\n const amountOut =\n output && output.length >= 66\n ? BigInt(output.slice(0, 66))\n : 0n;\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut,\n price_impact_bps: undefined,\n fee_bps: Math.floor(this.fee / 10),\n route: [`${params.token_in} -> ${params.token_out} (simulated)`],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const pm = this.positionManager;\n if (!pm) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Position manager address not configured\");\n }\n\n // Sort tokens (Uniswap V3 requires token0 < token1)\n const [token0, token1, rawAmount0, rawAmount1] =\n params.token_a.toLowerCase() < params.token_b.toLowerCase()\n ? [params.token_a, params.token_b, params.amount_a, params.amount_b]\n : [params.token_b, params.token_a, params.amount_b, params.amount_a];\n\n // V3 NPM mint: getLiquidityForAmounts uses min(L0, L1), so if either is 0\n // then liquidity=0 → revert. Use 1 wei minimum for single-side LP.\n const amount0 = rawAmount0 === 0n && rawAmount1 > 0n ? 1n : rawAmount0;\n const amount1 = rawAmount1 === 0n && rawAmount0 > 0n ? 1n : rawAmount1;\n\n const data = encodeFunctionData({\n abi: positionManagerAbi,\n functionName: \"mint\",\n args: [\n {\n token0,\n token1,\n fee: this.fee,\n tickLower: -887220,\n tickUpper: 887220,\n amount0Desired: amount0,\n amount1Desired: amount1,\n amount0Min: 0n,\n amount1Min: 0n,\n recipient: params.recipient,\n deadline: BigInt(\"18446744073709551615\"),\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity`,\n to: pm,\n data,\n value: 0n,\n gas_estimate: 500_000,\n approvals: [\n { token: token0, spender: pm, amount: amount0 },\n { token: token1, spender: pm, amount: amount1 },\n ],\n };\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] remove_liquidity requires tokenId — use NFT position manager directly`,\n );\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeFunctionResult, decodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts)\",\n \"function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB, uint256 liquidity)\",\n \"function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB)\",\n \"function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts)\",\n]);\n\nconst lbQuoterAbi = parseAbi([\n \"function findBestPathFromAmountIn(address[] calldata route, uint128 amountIn) external view returns ((address[] route, address[] pairs, uint256[] binSteps, uint256[] versions, uint128[] amounts, uint128[] virtualAmountsWithoutSlippage, uint128[] fees))\",\n]);\n\nexport class UniswapV2Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly rpcUrl: string | undefined;\n private readonly lbQuoter: Address | undefined;\n private readonly lbIntermediaries: Address[];\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.lbQuoter = entry.contracts?.[\"lb_quoter\"];\n this.rpcUrl = rpcUrl;\n\n // Collect LB intermediary tokens from contracts with \"lb_mid_\" prefix\n this.lbIntermediaries = [];\n if (entry.contracts) {\n for (const [key, addr] of Object.entries(entry.contracts)) {\n if (key.startsWith(\"lb_mid_\")) {\n this.lbIntermediaries.push(addr);\n }\n }\n }\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const amountOutMin = 0n;\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n const path: Address[] = [params.token_in, params.token_out];\n\n const data = encodeFunctionData({\n abi,\n functionName: \"swapExactTokensForTokens\",\n args: [params.amount_in, amountOutMin, path, params.recipient, deadline],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokens via V2`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 150_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured\");\n }\n\n // Try LB (Liquidity Book) quote first if lb_quoter is configured\n if (this.lbQuoter) {\n try {\n return await this.lbQuote(params);\n } catch {\n // Fall through to V2 quote\n }\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const path: Address[] = [params.token_in, params.token_out];\n\n const result = await client.call({\n to: this.router,\n data: encodeFunctionData({\n abi,\n functionName: \"getAmountsOut\",\n args: [params.amount_in, path],\n }),\n });\n\n if (!result.data) {\n throw DefiError.rpcError(`[${this.protocolName}] getAmountsOut returned no data`);\n }\n\n const decoded = decodeFunctionResult({\n abi,\n functionName: \"getAmountsOut\",\n data: result.data,\n }) as unknown as bigint[];\n\n const amountOut = decoded[decoded.length - 1];\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut,\n price_impact_bps: undefined,\n fee_bps: 30,\n route: [`${params.token_in} -> ${params.token_out}`],\n };\n }\n\n private async lbQuote(params: QuoteParams): Promise<QuoteResult> {\n const client = createPublicClient({ transport: http(this.rpcUrl!) });\n\n // Build candidate routes: direct + multi-hop through each intermediary\n const routes: Address[][] = [[params.token_in, params.token_out]];\n const tokenInLower = params.token_in.toLowerCase();\n const tokenOutLower = params.token_out.toLowerCase();\n for (const mid of this.lbIntermediaries) {\n if (mid.toLowerCase() !== tokenInLower && mid.toLowerCase() !== tokenOutLower) {\n routes.push([params.token_in, mid, params.token_out]);\n }\n }\n\n const lbResultParams = [\n {\n type: \"tuple\" as const,\n components: [\n { name: \"route\", type: \"address[]\" as const },\n { name: \"pairs\", type: \"address[]\" as const },\n { name: \"binSteps\", type: \"uint256[]\" as const },\n { name: \"versions\", type: \"uint256[]\" as const },\n { name: \"amounts\", type: \"uint128[]\" as const },\n { name: \"virtualAmountsWithoutSlippage\", type: \"uint128[]\" as const },\n { name: \"fees\", type: \"uint128[]\" as const },\n ],\n },\n ] as const;\n\n let bestOut = 0n;\n let bestRoute: Address[] = [];\n\n const results = await Promise.allSettled(\n routes.map(async (route) => {\n const result = await client.call({\n to: this.lbQuoter!,\n data: encodeFunctionData({\n abi: lbQuoterAbi,\n functionName: \"findBestPathFromAmountIn\",\n args: [route, params.amount_in],\n }),\n });\n if (!result.data) return { amountOut: 0n, route };\n const [quote] = decodeAbiParameters(lbResultParams, result.data);\n const amounts = quote.amounts;\n return { amountOut: amounts[amounts.length - 1], route };\n }),\n );\n\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value.amountOut > bestOut) {\n bestOut = r.value.amountOut;\n bestRoute = r.value.route;\n }\n }\n\n if (bestOut === 0n) {\n throw DefiError.rpcError(`[${this.protocolName}] LB quote returned zero for all routes`);\n }\n\n return {\n protocol: this.protocolName,\n amount_out: bestOut,\n price_impact_bps: undefined,\n fee_bps: undefined,\n route: [bestRoute.map((a) => a.slice(0, 10)).join(\" -> \") + \" (LB)\"],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"addLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n params.amount_a,\n params.amount_b,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity V2`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [\n { token: params.token_a, spender: this.router, amount: params.amount_a },\n { token: params.token_b, spender: this.router, amount: params.amount_b },\n ],\n };\n }\n\n async buildRemoveLiquidity(params: RemoveLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"removeLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n params.liquidity,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Remove liquidity V2`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeAbiParameters, concatHex, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport { rangeToTicks, alignTickUp, alignTickDown } from \"./tick_math.js\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"struct ExactInputSingleParams { address tokenIn; address tokenOut; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 limitSqrtPrice; }\",\n \"function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut)\",\n]);\n\n// Algebra Integral quoter: path = tokenIn(20) + deployer(20) + tokenOut(20) per hop\n// Returns arrays for multi-hop results\nconst algebraQuoterAbi = parseAbi([\n \"function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256[] memory amountOutList, uint256[] memory amountInList, uint160[] memory sqrtPriceX96AfterList, uint32[] memory initializedTicksCrossedList, uint256 gasEstimate, uint16[] memory feeList)\",\n]);\n\n// Algebra V2 / NEST-style quoter: single-hop struct\n// selector: 0x5e5e6e0f quoteExactInputSingle((address,address,uint256,uint160))\n// returns: (uint256 amountOut, uint256 amountIn, uint160 sqrtPriceX96After)\nconst algebraSingleQuoterAbi = parseAbi([\n \"function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint160 limitSqrtPrice) params) external returns (uint256 amountOut, uint256 amountIn, uint160 sqrtPriceX96After)\",\n]);\n\n// Algebra Integral NonfungiblePositionManager (includes deployer field for pool identification)\nconst algebraIntegralPmAbi = parseAbi([\n \"struct MintParams { address token0; address token1; address deployer; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; }\",\n \"function mint(MintParams calldata params) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)\",\n]);\n\n// Algebra V2 / NEST-style NonfungiblePositionManager (no deployer field)\nconst algebraV2PmAbi = parseAbi([\n \"struct MintParams { address token0; address token1; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; }\",\n \"function mint(MintParams calldata params) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)\",\n]);\n\nexport class AlgebraV3Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly quoter: Address | undefined;\n private readonly positionManager: Address | undefined;\n private readonly rpcUrl: string | undefined;\n // NEST and similar forks expose quoteExactInputSingle((address,address,uint256,uint160))\n // instead of path-based quoteExactInput. Detected by presence of pool_deployer in config.\n private readonly useSingleQuoter: boolean;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.quoter = entry.contracts?.[\"quoter\"];\n this.positionManager = entry.contracts?.[\"position_manager\"];\n this.rpcUrl = rpcUrl;\n // pool_deployer present → NEST-style single-hop struct quoter\n this.useSingleQuoter = entry.contracts?.[\"pool_deployer\"] !== undefined;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n const amountOutMinimum = 0n;\n\n const data = encodeFunctionData({\n abi,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n recipient: params.recipient,\n deadline,\n amountIn: params.amount_in,\n amountOutMinimum,\n limitSqrtPrice: 0n,\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokenIn for tokenOut`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 250_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured\");\n }\n if (!this.quoter) {\n throw DefiError.unsupported(\n `[${this.protocolName}] No quoter contract configured`,\n );\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // NEST and similar forks: use single-hop struct quoter\n if (this.useSingleQuoter) {\n const result = await client.call({\n to: this.quoter,\n data: encodeFunctionData({\n abi: algebraSingleQuoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n amountIn: params.amount_in,\n limitSqrtPrice: 0n,\n },\n ],\n }),\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] quoteExactInputSingle failed: ${e}`);\n });\n\n if (!result.data || result.data.length < 66) {\n throw DefiError.rpcError(`[${this.protocolName}] quoter returned empty data`);\n }\n\n const [amountOut] = decodeAbiParameters(\n [\n { name: \"amountOut\", type: \"uint256\" },\n { name: \"amountIn\", type: \"uint256\" },\n { name: \"sqrtPriceX96After\", type: \"uint160\" },\n ],\n result.data,\n );\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut as bigint,\n price_impact_bps: undefined,\n fee_bps: undefined,\n route: [`${params.token_in} -> ${params.token_out}`],\n };\n }\n\n // KittenSwap and standard Algebra Integral path: tokenIn(20) + deployer(20) + tokenOut(20) = 60 bytes\n // Standard pools use deployer=address(0) in path (CREATE2 salt without deployer prefix)\n const path = concatHex([params.token_in, zeroAddress as Address, params.token_out]);\n\n const result = await client.call({\n to: this.quoter,\n data: encodeFunctionData({\n abi: algebraQuoterAbi,\n functionName: \"quoteExactInput\",\n args: [path, params.amount_in],\n }),\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] quoteExactInput failed: ${e}`);\n });\n\n if (!result.data || result.data.length < 66) {\n throw DefiError.rpcError(`[${this.protocolName}] quoter returned empty data`);\n }\n\n // Decode first element: amountOutList is an array, take the last element\n const decoded = decodeAbiParameters(\n [\n { name: \"amountOutList\", type: \"uint256[]\" },\n { name: \"amountInList\", type: \"uint256[]\" },\n { name: \"sqrtPriceX96AfterList\", type: \"uint160[]\" },\n { name: \"initializedTicksCrossedList\", type: \"uint32[]\" },\n { name: \"gasEstimate\", type: \"uint256\" },\n { name: \"feeList\", type: \"uint16[]\" },\n ],\n result.data,\n );\n\n const amountOutList = decoded[0] as readonly bigint[];\n const feeList = decoded[5] as readonly number[];\n const amountOut = amountOutList[amountOutList.length - 1];\n const fee = feeList.length > 0 ? feeList[0] : undefined;\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut,\n price_impact_bps: undefined,\n fee_bps: fee !== undefined ? Math.floor(fee / 10) : undefined,\n route: [`${params.token_in} -> ${params.token_out}`],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const pm = this.positionManager;\n if (!pm) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Position manager address not configured\");\n }\n\n // Sort tokens (Algebra requires token0 < token1)\n const [token0, token1, rawAmount0, rawAmount1] =\n params.token_a.toLowerCase() < params.token_b.toLowerCase()\n ? [params.token_a, params.token_b, params.amount_a, params.amount_b]\n : [params.token_b, params.token_a, params.amount_b, params.amount_a];\n\n let tickLower = params.tick_lower ?? -887220;\n let tickUpper = params.tick_upper ?? 887220;\n\n // Auto tick detection: --range N% or single-side\n const isSingleSide = rawAmount0 === 0n || rawAmount1 === 0n;\n const needsAutoTick = (params.range_pct !== undefined) || (isSingleSide && !params.tick_lower && !params.tick_upper);\n\n if (needsAutoTick) {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required for auto tick detection\");\n const poolAddr = params.pool as Address | undefined;\n if (!poolAddr) throw new DefiError(\"CONTRACT_ERROR\", \"Pool address required (use --pool)\");\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const algebraPoolAbi = parseAbi([\n \"function globalState() view returns (uint160 price, int24 tick, uint16 lastFee, uint8 pluginConfig, uint16 communityFee, bool unlocked)\",\n \"function tickSpacing() view returns (int24)\",\n ]);\n const [globalState, spacing] = await Promise.all([\n client.readContract({ address: poolAddr, abi: algebraPoolAbi, functionName: \"globalState\" }),\n client.readContract({ address: poolAddr, abi: algebraPoolAbi, functionName: \"tickSpacing\" }),\n ]);\n const currentTick = Number(globalState[1]);\n const tickSpace = Number(spacing);\n\n if (params.range_pct !== undefined) {\n // ±N% concentrated range\n const range = rangeToTicks(currentTick, params.range_pct, tickSpace);\n tickLower = range.tickLower;\n tickUpper = range.tickUpper;\n } else if (rawAmount0 > 0n && rawAmount1 === 0n) {\n tickLower = alignTickUp(currentTick + tickSpace, tickSpace);\n tickUpper = 887220;\n } else {\n tickLower = -887220;\n tickUpper = alignTickDown(currentTick - tickSpace, tickSpace);\n }\n }\n\n const amount0 = rawAmount0;\n const amount1 = rawAmount1;\n\n // Algebra V2 (NEST-style, has pool_deployer) uses no deployer field in MintParams\n // Algebra Integral (KittenSwap) includes deployer field\n const data = this.useSingleQuoter\n ? encodeFunctionData({\n abi: algebraV2PmAbi,\n functionName: \"mint\",\n args: [{ token0, token1, tickLower, tickUpper, amount0Desired: amount0, amount1Desired: amount1, amount0Min: 0n, amount1Min: 0n, recipient: params.recipient, deadline: BigInt(\"18446744073709551615\") }],\n })\n : encodeFunctionData({\n abi: algebraIntegralPmAbi,\n functionName: \"mint\",\n args: [{ token0, token1, deployer: zeroAddress as Address, tickLower, tickUpper, amount0Desired: amount0, amount1Desired: amount1, amount0Min: 0n, amount1Min: 0n, recipient: params.recipient, deadline: BigInt(\"18446744073709551615\") }],\n });\n\n // Only add approvals for non-zero amounts\n const approvals: { token: Address; spender: Address; amount: bigint }[] = [];\n if (amount0 > 0n) approvals.push({ token: token0, spender: pm, amount: amount0 });\n if (amount1 > 0n) approvals.push({ token: token1, spender: pm, amount: amount1 });\n\n return {\n description: `[${this.protocolName}] Add liquidity [${tickLower}, ${tickUpper}]`,\n to: pm,\n data,\n value: 0n,\n gas_estimate: 500_000,\n approvals,\n };\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] remove_liquidity requires tokenId — use NFT position manager directly`,\n );\n }\n}\n","/**\n * Convert a ±percentage to tick delta.\n * tickDelta = ln(1 + pct/100) / ln(1.0001)\n */\nexport function pctToTickDelta(pct: number): number {\n return Math.round(Math.log(1 + pct / 100) / Math.log(1.0001));\n}\n\n/**\n * Align a tick down to the nearest multiple of tickSpacing.\n */\nexport function alignTickDown(tick: number, tickSpacing: number): number {\n return Math.floor(tick / tickSpacing) * tickSpacing;\n}\n\n/**\n * Align a tick up to the nearest multiple of tickSpacing.\n */\nexport function alignTickUp(tick: number, tickSpacing: number): number {\n return Math.ceil(tick / tickSpacing) * tickSpacing;\n}\n\n/**\n * Calculate ±pct% tick range centered on currentTick, aligned to tickSpacing.\n */\nexport function rangeToTicks(\n currentTick: number,\n rangePct: number,\n tickSpacing: number,\n): { tickLower: number; tickUpper: number } {\n const delta = pctToTickDelta(rangePct);\n return {\n tickLower: alignTickDown(currentTick - delta, tickSpacing),\n tickUpper: alignTickUp(currentTick + delta, tickSpacing),\n };\n}\n","import { encodeFunctionData, parseAbi, zeroAddress } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"function swapSingleTokenExactIn(address pool, address tokenIn, address tokenOut, uint256 exactAmountIn, uint256 minAmountOut, uint256 deadline, bool wethIsEth, bytes calldata userData) external returns (uint256 amountOut)\",\n]);\n\nexport class BalancerV3Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract\");\n }\n this.router = router;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const minAmountOut = 0n;\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n\n // Balancer V3 requires a pool address. For now use a simplified single-pool swap.\n // In production, the pool would be resolved from the registry or an on-chain query.\n const data = encodeFunctionData({\n abi,\n functionName: \"swapSingleTokenExactIn\",\n args: [\n zeroAddress, // TODO: resolve pool from registry\n params.token_in,\n params.token_out,\n params.amount_in,\n minAmountOut,\n deadline,\n false,\n \"0x\",\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} via Balancer V3`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote requires RPC`);\n }\n\n async buildAddLiquidity(_params: AddLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] add_liquidity requires pool-specific params`);\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] remove_liquidity requires pool-specific params`);\n }\n}\n","import { encodeFunctionData, parseAbi } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst poolAbi = parseAbi([\n \"function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256)\",\n \"function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256)\",\n \"function add_liquidity(uint256[2] amounts, uint256 min_mint_amount) external returns (uint256)\",\n \"function remove_liquidity(uint256 amount, uint256[2] min_amounts) external returns (uint256[2])\",\n]);\n\nexport class CurveStableSwapAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n // Direct pool exchange: swap token at index 0 for token at index 1.\n // The `router` address is treated as the pool address for direct swaps.\n // Callers should set the pool address as the \"router\" contract in the registry\n // when targeting a specific Curve pool.\n // Without prior quote, set min output to 0. Use quote() first for slippage protection.\n const minDy = 0n;\n\n const data = encodeFunctionData({\n abi: poolAbi,\n functionName: \"exchange\",\n args: [0n, 1n, params.amount_in, minDy],\n });\n\n return {\n description: `[${this.protocolName}] Curve pool exchange ${params.amount_in} tokens (index 0 -> 1)`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote requires RPC connection`);\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n // Add liquidity to a 2-token Curve pool\n const data = encodeFunctionData({\n abi: poolAbi,\n functionName: \"add_liquidity\",\n args: [[params.amount_a, params.amount_b], 0n],\n });\n\n return {\n description: `[${this.protocolName}] Curve add liquidity`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 400_000,\n };\n }\n\n async buildRemoveLiquidity(params: RemoveLiquidityParams): Promise<DeFiTx> {\n // Remove liquidity from a 2-token Curve pool\n const data = encodeFunctionData({\n abi: poolAbi,\n functionName: \"remove_liquidity\",\n args: [params.liquidity, [0n, 0n]],\n });\n\n return {\n description: `[${this.protocolName}] Curve remove liquidity`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, decodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError, multicallRead } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"struct Route { address from; address to; bool stable; }\",\n \"function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, (address from, address to, bool stable)[] calldata routes, address to, uint256 deadline) external returns (uint256[] memory amounts)\",\n \"function getAmountsOut(uint256 amountIn, (address from, address to, bool stable)[] calldata routes) external view returns (uint256[] memory amounts)\",\n \"function addLiquidity(address tokenA, address tokenB, bool stable, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB, uint256 liquidity)\",\n \"function removeLiquidity(address tokenA, address tokenB, bool stable, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB)\",\n]);\n\n// Velodrome V2 / Aerodrome style: Route includes factory address\nconst abiV2 = parseAbi([\n \"function getAmountsOut(uint256 amountIn, (address from, address to, bool stable, address factory)[] calldata routes) external view returns (uint256[] memory amounts)\",\n]);\n\nexport class SolidlyAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n /** Default to volatile (false). True for stablecoin pairs. */\n private readonly defaultStable: boolean;\n private readonly rpcUrl: string | undefined;\n /** Factory address — present on Velodrome V2 / Aerodrome forks */\n private readonly factory: Address | undefined;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.defaultStable = false;\n this.rpcUrl = rpcUrl;\n this.factory = entry.contracts?.[\"factory\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const amountOutMin = 0n;\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n\n const routes = [\n { from: params.token_in, to: params.token_out, stable: this.defaultStable },\n ];\n\n const data = encodeFunctionData({\n abi,\n functionName: \"swapExactTokensForTokens\",\n args: [params.amount_in, amountOutMin, routes, params.recipient, deadline],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokens via Solidly`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 200_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n private encodeV1(params: QuoteParams, stable: boolean): `0x${string}` {\n return encodeFunctionData({\n abi,\n functionName: \"getAmountsOut\",\n args: [params.amount_in, [{ from: params.token_in, to: params.token_out, stable }]],\n });\n }\n\n private encodeV2(params: QuoteParams, stable: boolean): `0x${string}` {\n return encodeFunctionData({\n abi: abiV2,\n functionName: \"getAmountsOut\",\n args: [params.amount_in, [{ from: params.token_in, to: params.token_out, stable, factory: this.factory! }]],\n });\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n\n // Build all route variant candidates in one multicall batch.\n // Order: V2 variants first (if factory present), then V1 volatile + stable.\n const candidates: Array<{ callData: `0x${string}`; stable: boolean }> = [\n { callData: this.encodeV1(params, false), stable: false },\n { callData: this.encodeV1(params, true), stable: true },\n ];\n if (this.factory) {\n candidates.unshift(\n { callData: this.encodeV2(params, false), stable: false },\n { callData: this.encodeV2(params, true), stable: true },\n );\n }\n\n const rawResults = await multicallRead(\n this.rpcUrl,\n candidates.map((c) => [this.router, c.callData]),\n );\n\n let bestOut = 0n;\n let bestStable = false;\n for (let i = 0; i < rawResults.length; i++) {\n const raw = rawResults[i];\n if (!raw) continue;\n try {\n const [amounts] = decodeAbiParameters(\n [{ name: \"amounts\", type: \"uint256[]\" }],\n raw,\n );\n const out = amounts.length >= 2 ? amounts[amounts.length - 1] : 0n;\n if (out > bestOut) {\n bestOut = out;\n bestStable = candidates[i].stable;\n }\n } catch {\n // Route failed — skip\n }\n }\n\n if (bestOut === 0n) {\n throw DefiError.rpcError(`[${this.protocolName}] getAmountsOut returned zero for all routes`);\n }\n\n return {\n protocol: this.protocolName,\n amount_out: bestOut,\n price_impact_bps: undefined,\n fee_bps: bestStable ? 4 : 20,\n route: [`${params.token_in} -> ${params.token_out} (stable: ${bestStable})`],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"addLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n this.defaultStable,\n params.amount_a,\n params.amount_b,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity (Solidly)`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 350_000,\n approvals: [\n { token: params.token_a, spender: this.router, amount: params.amount_a },\n { token: params.token_b, spender: this.router, amount: params.amount_b },\n ],\n };\n }\n\n async buildRemoveLiquidity(params: RemoveLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"removeLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n this.defaultStable,\n params.liquidity,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Remove liquidity (Solidly)`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport { rangeToTicks, alignTickUp, alignTickDown } from \"./tick_math.js\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\n// Thena V3 CL NonfungiblePositionManager (includes tickSpacing + sqrtPriceX96 in MintParams)\nconst thenaPmAbi = parseAbi([\n \"struct MintParams { address token0; address token1; int24 tickSpacing; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; uint160 sqrtPriceX96; }\",\n \"function mint(MintParams calldata params) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)\",\n]);\n\nconst thenaRouterAbi = parseAbi([\n \"struct ExactInputSingleParams { address tokenIn; address tokenOut; int24 tickSpacing; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; }\",\n \"function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut)\",\n]);\n\nconst thenaPoolAbi = parseAbi([\n \"function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, bool unlocked)\",\n \"function tickSpacing() view returns (int24)\",\n \"function token0() view returns (address)\",\n \"function token1() view returns (address)\",\n]);\n\nconst thenaFactoryAbi = parseAbi([\n \"function getPool(address tokenA, address tokenB, int24 tickSpacing) view returns (address)\",\n]);\n\nexport class ThenaCLAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly positionManager: Address | undefined;\n private readonly factory: Address | undefined;\n private readonly rpcUrl: string | undefined;\n private readonly defaultTickSpacing: number;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n this.router = router;\n this.positionManager = entry.contracts?.[\"position_manager\"];\n this.factory = entry.contracts?.[\"pool_factory\"];\n this.rpcUrl = rpcUrl;\n this.defaultTickSpacing = 50;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: thenaRouterAbi,\n functionName: \"exactInputSingle\",\n args: [{\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n tickSpacing: this.defaultTickSpacing,\n recipient: params.recipient,\n deadline: BigInt(params.deadline ?? 18446744073709551615n),\n amountIn: params.amount_in,\n amountOutMinimum: 0n,\n sqrtPriceLimitX96: 0n,\n }],\n });\n return {\n description: `[${this.protocolName}] Swap`,\n to: this.router, data, value: 0n, gas_estimate: 300_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote not yet implemented — use swap router`);\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const pm = this.positionManager;\n if (!pm) throw new DefiError(\"CONTRACT_ERROR\", \"Position manager not configured\");\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required\");\n\n // Sort tokens\n const [token0, token1, rawAmount0, rawAmount1] =\n params.token_a.toLowerCase() < params.token_b.toLowerCase()\n ? [params.token_a, params.token_b, params.amount_a, params.amount_b]\n : [params.token_b, params.token_a, params.amount_b, params.amount_a];\n\n // Resolve pool and tick range\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const poolAddr = params.pool as Address | undefined;\n let tickSpacing = this.defaultTickSpacing;\n let tickLower = params.tick_lower ?? 0;\n let tickUpper = params.tick_upper ?? 0;\n\n // If pool provided or we need to auto-detect ticks\n if (poolAddr || !params.tick_lower || !params.tick_upper) {\n let pool = poolAddr;\n if (!pool && this.factory) {\n pool = await client.readContract({\n address: this.factory, abi: thenaFactoryAbi, functionName: \"getPool\",\n args: [token0, token1, tickSpacing],\n }) as Address;\n if (pool === zeroAddress) throw new DefiError(\"CONTRACT_ERROR\", \"Pool not found\");\n }\n if (pool) {\n const [slot0, ts] = await Promise.all([\n client.readContract({ address: pool, abi: thenaPoolAbi, functionName: \"slot0\" }),\n client.readContract({ address: pool, abi: thenaPoolAbi, functionName: \"tickSpacing\" }),\n ]);\n const currentTick = Number((slot0 as readonly [bigint, number, ...unknown[]])[1]);\n tickSpacing = Number(ts);\n\n if (params.range_pct !== undefined) {\n // ±N% concentrated range\n const range = rangeToTicks(currentTick, params.range_pct, tickSpacing);\n tickLower = range.tickLower;\n tickUpper = range.tickUpper;\n } else if (!params.tick_lower && !params.tick_upper) {\n const isSingleSide = rawAmount0 === 0n || rawAmount1 === 0n;\n if (isSingleSide) {\n if (rawAmount0 > 0n) {\n tickLower = alignTickUp(currentTick + tickSpacing, tickSpacing);\n tickUpper = Math.floor(887272 / tickSpacing) * tickSpacing;\n } else {\n tickLower = Math.ceil(-887272 / tickSpacing) * tickSpacing;\n tickUpper = alignTickDown(currentTick - tickSpacing, tickSpacing);\n }\n } else {\n tickLower = Math.ceil(-887272 / tickSpacing) * tickSpacing;\n tickUpper = Math.floor(887272 / tickSpacing) * tickSpacing;\n }\n }\n }\n }\n\n // Apply explicit tick params (override auto-detected)\n if (params.tick_lower !== undefined) tickLower = params.tick_lower;\n if (params.tick_upper !== undefined) tickUpper = params.tick_upper;\n\n const data = encodeFunctionData({\n abi: thenaPmAbi,\n functionName: \"mint\",\n args: [{\n token0, token1,\n tickSpacing,\n tickLower, tickUpper,\n amount0Desired: rawAmount0,\n amount1Desired: rawAmount1,\n amount0Min: 0n, amount1Min: 0n,\n recipient: params.recipient,\n deadline: BigInt(\"18446744073709551615\"),\n sqrtPriceX96: 0n,\n }],\n });\n\n const approvals: { token: Address; spender: Address; amount: bigint }[] = [];\n if (rawAmount0 > 0n) approvals.push({ token: token0, spender: pm, amount: rawAmount0 });\n if (rawAmount1 > 0n) approvals.push({ token: token1, spender: pm, amount: rawAmount1 });\n\n return {\n description: `[${this.protocolName}] Add liquidity [${tickLower}, ${tickUpper}]`,\n to: pm, data, value: 0n, gas_estimate: 700_000, approvals,\n };\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] remove_liquidity requires tokenId`);\n }\n}\n","import { createPublicClient, decodeFunctionResult, encodeFunctionData, http, parseAbi, zeroAddress } from \"viem\";\nimport type { Address, Hex } from \"viem\";\n\nimport { DefiError, multicallRead } from \"@hypurrquant/defi-core\";\nimport type {\n IGaugeSystem,\n GaugedPool,\n ProtocolEntry,\n RewardInfo,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\n// Multicall decode helpers\nconst _addressDecodeAbi = parseAbi([\"function f() external view returns (address)\"]);\nfunction decodeAddress(data: Hex | null): Address | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _addressDecodeAbi, functionName: \"f\", data }) as Address;\n } catch {\n return null;\n }\n}\n\nconst _symbolDecodeAbi = parseAbi([\"function symbol() external view returns (string)\"]);\nfunction decodeSymbol(data: Hex | null): string {\n if (!data) return \"?\";\n try {\n return decodeFunctionResult({ abi: _symbolDecodeAbi, functionName: \"symbol\", data }) as string;\n } catch {\n return \"?\";\n }\n}\n\nconst gaugeManagerAbi = parseAbi([\n \"function gauges(address pool) view returns (address gauge)\",\n \"function isGauge(address gauge) view returns (bool)\",\n \"function isAlive(address gauge) view returns (bool)\",\n \"function claimRewards(address gauge, uint256[] tokenIds, uint8 redeemType) external\",\n]);\n\nconst gaugeCLAbi = parseAbi([\n \"function deposit(uint256 tokenId) external\",\n \"function withdraw(uint256 tokenId, uint8 redeemType) external\",\n \"function earned(uint256 tokenId) view returns (uint256)\",\n \"function balanceOf(uint256 tokenId) view returns (uint256)\",\n \"function rewardToken() view returns (address)\",\n]);\n\nconst nfpmAbi = parseAbi([\n \"function approve(address to, uint256 tokenId) external\",\n \"function getApproved(uint256 tokenId) view returns (address)\",\n]);\n\nconst veAbi = parseAbi([\n \"function create_lock(uint256 value, uint256 lock_duration) external returns (uint256)\",\n \"function increase_amount(uint256 tokenId, uint256 value) external\",\n \"function increase_unlock_time(uint256 tokenId, uint256 lock_duration) external\",\n \"function withdraw(uint256 tokenId) external\",\n]);\n\nconst voterAbi = parseAbi([\n \"function vote(uint256 tokenId, address[] pools, uint256[] weights) external\",\n \"function claimBribes(address[] bribes, address[][] tokens, uint256 tokenId) external\",\n \"function claimFees(address[] fees, address[][] tokens, uint256 tokenId) external\",\n]);\n\n/**\n * Hybra ve(3,3) Gauge adapter using GaugeManager pattern.\n * CL gauges require NFT deposit and claim goes through GaugeManager (not directly to gauge).\n */\nexport class HybraGaugeAdapter implements IGaugeSystem {\n private readonly protocolName: string;\n private readonly gaugeManager: Address;\n private readonly veToken: Address;\n private readonly voter: Address;\n private readonly positionManager: Address;\n private readonly poolFactory: Address | undefined;\n private readonly rpcUrl: string | undefined;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const gm = entry.contracts?.[\"gauge_manager\"];\n if (!gm) throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'gauge_manager' contract\");\n this.gaugeManager = gm;\n const ve = entry.contracts?.[\"ve_token\"];\n if (!ve) throw new DefiError(\"CONTRACT_ERROR\", \"Missing 've_token' contract\");\n this.veToken = ve;\n this.voter = entry.contracts?.[\"voter\"] ?? zeroAddress as Address;\n this.positionManager = entry.contracts?.[\"position_manager\"] ?? zeroAddress as Address;\n this.poolFactory = entry.contracts?.[\"pool_factory\"];\n this.rpcUrl = rpcUrl;\n }\n\n name(): string { return this.protocolName; }\n\n // ─── Gauge Discovery ──────────────────────────────────────\n\n async discoverGaugedPools(): Promise<GaugedPool[]> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required for gauge discovery\");\n if (!this.poolFactory) throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'pool_factory' contract\");\n\n const factoryAbi = parseAbi([\n \"function allPoolsLength() external view returns (uint256)\",\n \"function allPools(uint256) external view returns (address)\",\n ]);\n const poolAbi = parseAbi([\n \"function token0() external view returns (address)\",\n \"function token1() external view returns (address)\",\n ]);\n const erc20SymbolAbi = parseAbi([\"function symbol() external view returns (string)\"]);\n const gaugesAbi = parseAbi([\"function gauges(address pool) view returns (address gauge)\"]);\n\n // Step 1: get total pool count\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n let poolCount: bigint;\n try {\n poolCount = await client.readContract({\n address: this.poolFactory,\n abi: factoryAbi,\n functionName: \"allPoolsLength\",\n }) as bigint;\n } catch {\n return [];\n }\n\n const count = Number(poolCount);\n if (count === 0) return [];\n\n // Step 2: batch-fetch all pool addresses\n const poolAddressCalls: Array<[Address, Hex]> = [];\n for (let i = 0; i < count; i++) {\n poolAddressCalls.push([\n this.poolFactory,\n encodeFunctionData({ abi: factoryAbi, functionName: \"allPools\", args: [BigInt(i)] }),\n ]);\n }\n const poolAddressResults = await multicallRead(this.rpcUrl, poolAddressCalls);\n const pools: Address[] = poolAddressResults\n .map((r) => decodeAddress(r))\n .filter((a): a is Address => a !== null && a !== zeroAddress);\n\n if (pools.length === 0) return [];\n\n // Step 3: batch GaugeManager.gauges(pool) for all pools\n const gaugeCalls: Array<[Address, Hex]> = pools.map((pool) => [\n this.gaugeManager,\n encodeFunctionData({ abi: gaugesAbi, functionName: \"gauges\", args: [pool] }),\n ]);\n const gaugeResults = await multicallRead(this.rpcUrl, gaugeCalls);\n\n // Filter pools that have an active gauge\n const gaugedPools: Array<{ pool: Address; gauge: Address }> = [];\n for (let i = 0; i < pools.length; i++) {\n const gauge = decodeAddress(gaugeResults[i] ?? null);\n if (gauge && gauge !== zeroAddress) {\n gaugedPools.push({ pool: pools[i]!, gauge });\n }\n }\n\n if (gaugedPools.length === 0) return [];\n\n // Step 4: batch token0() and token1() for gauged pools\n const tokenCalls: Array<[Address, Hex]> = [];\n for (const { pool } of gaugedPools) {\n tokenCalls.push([pool, encodeFunctionData({ abi: poolAbi, functionName: \"token0\" })]);\n tokenCalls.push([pool, encodeFunctionData({ abi: poolAbi, functionName: \"token1\" })]);\n }\n const tokenResults = await multicallRead(this.rpcUrl, tokenCalls);\n\n // Step 5: collect unique token addresses and fetch symbols\n const tokenAddrs = new Set<Address>();\n for (let i = 0; i < gaugedPools.length; i++) {\n const t0 = decodeAddress(tokenResults[i * 2] ?? null);\n const t1 = decodeAddress(tokenResults[i * 2 + 1] ?? null);\n if (t0 && t0 !== zeroAddress) tokenAddrs.add(t0);\n if (t1 && t1 !== zeroAddress) tokenAddrs.add(t1);\n }\n\n const uniqueTokens = Array.from(tokenAddrs);\n const symbolCalls: Array<[Address, Hex]> = uniqueTokens.map((t) => [\n t,\n encodeFunctionData({ abi: erc20SymbolAbi, functionName: \"symbol\" }),\n ]);\n const symbolResults = await multicallRead(this.rpcUrl, symbolCalls);\n const symbolMap = new Map<Address, string>();\n for (let i = 0; i < uniqueTokens.length; i++) {\n symbolMap.set(uniqueTokens[i]!, decodeSymbol(symbolResults[i] ?? null));\n }\n\n // Step 6: assemble results\n const out: GaugedPool[] = [];\n for (let i = 0; i < gaugedPools.length; i++) {\n const { pool, gauge } = gaugedPools[i]!;\n const t0 = decodeAddress(tokenResults[i * 2] ?? null);\n const t1 = decodeAddress(tokenResults[i * 2 + 1] ?? null);\n out.push({\n pool,\n gauge,\n token0: t0 ? (symbolMap.get(t0) ?? t0.slice(0, 10)) : \"?\",\n token1: t1 ? (symbolMap.get(t1) ?? t1.slice(0, 10)) : \"?\",\n type: \"CL\",\n });\n }\n\n return out;\n }\n\n // ─── Gauge Lookup ──────────────────────────────────────────\n\n async resolveGauge(pool: Address): Promise<Address> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC required\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const gauge = await client.readContract({\n address: this.gaugeManager, abi: gaugeManagerAbi,\n functionName: \"gauges\", args: [pool],\n }) as Address;\n if (gauge === zeroAddress) throw new DefiError(\"CONTRACT_ERROR\", `No gauge for pool ${pool}`);\n return gauge;\n }\n\n // ─── CL Gauge: NFT Deposit/Withdraw ──────────────────────────\n\n async buildDeposit(gauge: Address, _amount: bigint, tokenId?: bigint): Promise<DeFiTx> {\n if (tokenId === undefined) throw new DefiError(\"CONTRACT_ERROR\", \"tokenId required for CL gauge deposit\");\n\n // Pre-tx: approve NFT to gauge\n const approveTx: DeFiTx = {\n description: `[${this.protocolName}] Approve NFT #${tokenId} to gauge`,\n to: this.positionManager,\n data: encodeFunctionData({ abi: nfpmAbi, functionName: \"approve\", args: [gauge, tokenId] }),\n value: 0n, gas_estimate: 80_000,\n };\n\n return {\n description: `[${this.protocolName}] Deposit NFT #${tokenId} to gauge`,\n to: gauge,\n data: encodeFunctionData({ abi: gaugeCLAbi, functionName: \"deposit\", args: [tokenId] }),\n value: 0n, gas_estimate: 500_000,\n pre_txs: [approveTx],\n };\n }\n\n async buildWithdraw(gauge: Address, _amount: bigint, tokenId?: bigint): Promise<DeFiTx> {\n if (tokenId === undefined) throw new DefiError(\"CONTRACT_ERROR\", \"tokenId required for CL gauge withdraw\");\n return {\n description: `[${this.protocolName}] Withdraw NFT #${tokenId} from gauge`,\n to: gauge,\n data: encodeFunctionData({ abi: gaugeCLAbi, functionName: \"withdraw\", args: [tokenId, 1] }),\n value: 0n, gas_estimate: 1_000_000,\n };\n }\n\n // ─── Claim: via GaugeManager ──────────────────────────────────\n\n async buildClaimRewards(gauge: Address, _account?: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] Use buildClaimRewardsByTokenId for CL gauges`);\n }\n\n async buildClaimRewardsByTokenId(gauge: Address, tokenId: bigint): Promise<DeFiTx> {\n return {\n description: `[${this.protocolName}] Claim rewards for NFT #${tokenId}`,\n to: this.gaugeManager,\n data: encodeFunctionData({\n abi: gaugeManagerAbi, functionName: \"claimRewards\",\n args: [gauge, [tokenId], 1], // redeemType=1\n }),\n value: 0n, gas_estimate: 1_000_000,\n };\n }\n\n // ─── Pending Rewards ──────────────────────────────────────────\n\n async getPendingRewards(gauge: Address, _user: Address): Promise<RewardInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] Use getPendingRewardsByTokenId for CL gauges`);\n }\n\n async getPendingRewardsByTokenId(gauge: Address, tokenId: bigint): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC required\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return await client.readContract({\n address: gauge, abi: gaugeCLAbi,\n functionName: \"earned\", args: [tokenId],\n }) as bigint;\n }\n\n // ─── VoteEscrow ──────────────────────────────────────────────\n\n async buildCreateLock(amount: bigint, lockDuration: number): Promise<DeFiTx> {\n return {\n description: `[${this.protocolName}] Create veNFT lock`,\n to: this.veToken,\n data: encodeFunctionData({ abi: veAbi, functionName: \"create_lock\", args: [amount, BigInt(lockDuration)] }),\n value: 0n, gas_estimate: 300_000,\n };\n }\n\n async buildIncreaseAmount(tokenId: bigint, amount: bigint): Promise<DeFiTx> {\n return {\n description: `[${this.protocolName}] Increase veNFT #${tokenId}`,\n to: this.veToken,\n data: encodeFunctionData({ abi: veAbi, functionName: \"increase_amount\", args: [tokenId, amount] }),\n value: 0n, gas_estimate: 200_000,\n };\n }\n\n async buildIncreaseUnlockTime(tokenId: bigint, lockDuration: number): Promise<DeFiTx> {\n return {\n description: `[${this.protocolName}] Extend veNFT #${tokenId} lock`,\n to: this.veToken,\n data: encodeFunctionData({ abi: veAbi, functionName: \"increase_unlock_time\", args: [tokenId, BigInt(lockDuration)] }),\n value: 0n, gas_estimate: 200_000,\n };\n }\n\n async buildWithdrawExpired(tokenId: bigint): Promise<DeFiTx> {\n return {\n description: `[${this.protocolName}] Withdraw expired veNFT #${tokenId}`,\n to: this.veToken,\n data: encodeFunctionData({ abi: veAbi, functionName: \"withdraw\", args: [tokenId] }),\n value: 0n, gas_estimate: 200_000,\n };\n }\n\n // ─── Voter ──────────────────────────────────────────────────\n\n async buildVote(tokenId: bigint, pools: Address[], weights: bigint[]): Promise<DeFiTx> {\n return {\n description: `[${this.protocolName}] Vote with veNFT #${tokenId}`,\n to: this.voter,\n data: encodeFunctionData({ abi: voterAbi, functionName: \"vote\", args: [tokenId, pools, weights] }),\n value: 0n, gas_estimate: 500_000,\n };\n }\n\n async buildClaimBribes(bribes: Address[], tokenId: bigint): Promise<DeFiTx> {\n const tokensPerBribe: Address[][] = bribes.map(() => []);\n return {\n description: `[${this.protocolName}] Claim bribes for veNFT #${tokenId}`,\n to: this.voter,\n data: encodeFunctionData({ abi: voterAbi, functionName: \"claimBribes\", args: [bribes, tokensPerBribe, tokenId] }),\n value: 0n, gas_estimate: 300_000,\n };\n }\n\n async buildClaimFees(fees: Address[], tokenId: bigint): Promise<DeFiTx> {\n const tokensPerFee: Address[][] = fees.map(() => []);\n return {\n description: `[${this.protocolName}] Claim fees for veNFT #${tokenId}`,\n to: this.voter,\n data: encodeFunctionData({ abi: voterAbi, functionName: \"claimFees\", args: [fees, tokensPerFee, tokenId] }),\n value: 0n, gas_estimate: 300_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, zeroAddress } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"function swap(address fromToken, address toToken, uint256 fromAmount, uint256 minToAmount, address to, address rebateTo) external payable returns (uint256 realToAmount)\",\n]);\n\nexport class WooFiAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract\");\n }\n this.router = router;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const minToAmount = 0n;\n\n const data = encodeFunctionData({\n abi,\n functionName: \"swap\",\n args: [\n params.token_in,\n params.token_out,\n params.amount_in,\n minToAmount,\n params.recipient,\n zeroAddress,\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} via WOOFi`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote requires RPC`);\n }\n\n async buildAddLiquidity(_params: AddLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] WOOFi does not support LP positions via router`);\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] WOOFi does not support LP positions via router`);\n }\n}\n","import { createPublicClient, decodeFunctionResult, encodeFunctionData, http, parseAbi, zeroAddress } from \"viem\";\nimport type { Address, Hex } from \"viem\";\n\nimport { DefiError, multicallRead } from \"@hypurrquant/defi-core\";\nimport type {\n IGaugeSystem,\n GaugedPool,\n ProtocolEntry,\n RewardInfo,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst gaugeAbi = parseAbi([\n \"function deposit(uint256 amount) external\",\n \"function depositFor(uint256 amount, uint256 tokenId) external\",\n \"function withdraw(uint256 amount) external\",\n \"function getReward() external\",\n \"function getReward(address account) external\",\n \"function getReward(address account, address[] tokens) external\",\n \"function getReward(uint256 tokenId) external\",\n \"function earned(address account) external view returns (uint256)\",\n \"function earned(address token, address account) external view returns (uint256)\",\n \"function earned(uint256 tokenId) external view returns (uint256)\",\n \"function rewardRate() external view returns (uint256)\",\n \"function rewardToken() external view returns (address)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function rewardsListLength() external view returns (uint256)\",\n \"function rewardData(address token) external view returns (uint256 periodFinish, uint256 rewardRate, uint256 lastUpdateTime, uint256 rewardPerTokenStored)\",\n \"function nonfungiblePositionManager() external view returns (address)\",\n]);\n\nconst veAbi = parseAbi([\n \"function create_lock(uint256 value, uint256 lock_duration) external returns (uint256)\",\n \"function increase_amount(uint256 tokenId, uint256 value) external\",\n \"function increase_unlock_time(uint256 tokenId, uint256 lock_duration) external\",\n \"function withdraw(uint256 tokenId) external\",\n \"function balanceOfNFT(uint256 tokenId) external view returns (uint256)\",\n \"function locked(uint256 tokenId) external view returns (uint256 amount, uint256 end)\",\n]);\n\nconst voterAbi = parseAbi([\n \"function vote(uint256 tokenId, address[] calldata pools, uint256[] calldata weights) external\",\n \"function claimBribes(address[] calldata bribes, address[][] calldata tokens, uint256 tokenId) external\",\n \"function claimFees(address[] calldata fees, address[][] calldata tokens, uint256 tokenId) external\",\n \"function gauges(address pool) external view returns (address)\",\n \"function gaugeForPool(address pool) external view returns (address)\",\n \"function poolToGauge(address pool) external view returns (address)\",\n]);\n\n// Multicall decode helpers\nconst _addressDecodeAbi = parseAbi([\"function f() external view returns (address)\"]);\nfunction decodeAddress(data: Hex | null): Address | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _addressDecodeAbi, functionName: \"f\", data }) as Address;\n } catch {\n return null;\n }\n}\n\nconst _symbolDecodeAbi = parseAbi([\"function symbol() external view returns (string)\"]);\nfunction decodeSymbol(data: Hex | null): string {\n if (!data) return \"?\";\n try {\n return decodeFunctionResult({ abi: _symbolDecodeAbi, functionName: \"symbol\", data }) as string;\n } catch {\n return \"?\";\n }\n}\n\nconst _boolDecodeAbi = parseAbi([\"function f() external view returns (bool)\"]);\nfunction decodeBoolean(data: Hex): boolean {\n try {\n return decodeFunctionResult({ abi: _boolDecodeAbi, functionName: \"f\", data }) as boolean;\n } catch {\n return false;\n }\n}\n\n// HyperEVM well-known token addresses for CL pool discovery\nconst HYPEREVM_TOKENS: Record<string, Address> = {\n WHYPE: \"0x5555555555555555555555555555555555555555\",\n USDC: \"0xb88339CB7199b77E23DB6E890353E22632Ba630f\",\n USDT0: \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\",\n UETH: \"0xBe6727B535545C67d5cAa73dEa54865B92CF7907\",\n UBTC: \"0x9FDBdA0A5e284c32744D2f17Ee5c74B284993463\",\n USDH: \"0x111111a1a0667d36bD57c0A9f569b98057111111\",\n USDe: \"0x5d3a1Ff2b6BAb83b63cd9AD0787074081a52ef34\",\n sUSDe: \"0x211Cc4DD073734dA055fbF44a2b4667d5E5fE5d2\",\n XAUt0: \"0xf4D9235269a96aaDaFc9aDAe454a0618eBE37949\",\n kHYPE: \"0xfD739d4e423301CE9385c1fb8850539D657C296D\",\n RAM: \"0x555570a286F15EbDFE42B66eDE2f724Aa1AB5555\",\n hyperRAM: \"0xAAAE8378809bb8815c08D3C59Eb0c7D1529aD769\",\n};\n\nconst CL_TICK_SPACINGS = [1, 5, 10, 50, 100, 200];\n\nexport class SolidlyGaugeAdapter implements IGaugeSystem {\n private readonly protocolName: string;\n private readonly voter: Address;\n private readonly veToken: Address;\n private readonly rpcUrl: string | undefined;\n private readonly clFactory: Address | undefined;\n private readonly v2Factory: Address | undefined;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const voter = entry.contracts?.[\"voter\"];\n if (!voter) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'voter' contract\");\n }\n const veToken = entry.contracts?.[\"ve_token\"];\n if (!veToken) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 've_token' contract\");\n }\n this.voter = voter;\n this.veToken = veToken;\n this.rpcUrl = rpcUrl;\n this.clFactory = entry.contracts?.[\"cl_factory\"] ?? entry.contracts?.[\"factory\"];\n this.v2Factory = entry.contracts?.[\"pair_factory\"] ?? entry.contracts?.[\"factory\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n /** Scan V2 and CL factories for pools that have active emission gauges. */\n async discoverGaugedPools(): Promise<GaugedPool[]> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required for gauge discovery\");\n\n const results: GaugedPool[] = [];\n\n await Promise.all([\n this._discoverV2GaugedPools(results),\n this._discoverCLGaugedPools(results),\n ]);\n\n return results;\n }\n\n private async _discoverV2GaugedPools(out: GaugedPool[]): Promise<void> {\n if (!this.rpcUrl || !this.v2Factory) return;\n\n const v2FactoryAbi = parseAbi([\n \"function allPairsLength() external view returns (uint256)\",\n \"function allPairs(uint256) external view returns (address)\",\n ]);\n const pairAbi = parseAbi([\n \"function token0() external view returns (address)\",\n \"function token1() external view returns (address)\",\n \"function stable() external view returns (bool)\",\n ]);\n const erc20SymbolAbi = parseAbi([\"function symbol() external view returns (string)\"]);\n\n // Step 1: get total pairs count\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n let pairCount: bigint;\n try {\n pairCount = await client.readContract({\n address: this.v2Factory,\n abi: v2FactoryAbi,\n functionName: \"allPairsLength\",\n }) as bigint;\n } catch {\n return;\n }\n\n const count = Number(pairCount);\n if (count === 0) return;\n\n // Step 2: batch-fetch all pair addresses\n const pairAddressCalls: Array<[Address, Hex]> = [];\n for (let i = 0; i < count; i++) {\n pairAddressCalls.push([\n this.v2Factory,\n encodeFunctionData({ abi: v2FactoryAbi, functionName: \"allPairs\", args: [BigInt(i)] }),\n ]);\n }\n const pairAddressResults = await multicallRead(this.rpcUrl, pairAddressCalls);\n const pairs: Address[] = pairAddressResults.map((r) => decodeAddress(r)).filter((a): a is Address => a !== null && a !== zeroAddress);\n\n if (pairs.length === 0) return;\n\n // Step 3: for each pair, call gaugeForPool on voter (fallback to poolToGauge)\n const gaugeForPoolAbi = parseAbi([\"function gaugeForPool(address) external view returns (address)\"]);\n const poolToGaugeAbi = parseAbi([\"function poolToGauge(address) external view returns (address)\"]);\n const gaugeCalls: Array<[Address, Hex]> = pairs.map((pair) => [\n this.voter,\n encodeFunctionData({ abi: gaugeForPoolAbi, functionName: \"gaugeForPool\", args: [pair] }),\n ]);\n let gaugeResults = await multicallRead(this.rpcUrl, gaugeCalls);\n\n // If all results are null (gaugeForPool not supported), try poolToGauge\n const allNullV2 = gaugeResults.every(r => !r || decodeAddress(r) === zeroAddress || decodeAddress(r) === null);\n if (allNullV2) {\n const fallbackCalls: Array<[Address, Hex]> = pairs.map((pair) => [\n this.voter,\n encodeFunctionData({ abi: poolToGaugeAbi, functionName: \"poolToGauge\", args: [pair] }),\n ]);\n gaugeResults = await multicallRead(this.rpcUrl, fallbackCalls);\n }\n\n // Filter only pairs that have a gauge\n const gaugedPairs: Array<{ pair: Address; gauge: Address }> = [];\n for (let i = 0; i < pairs.length; i++) {\n const gauge = decodeAddress(gaugeResults[i] ?? null);\n if (gauge && gauge !== zeroAddress) {\n gaugedPairs.push({ pair: pairs[i]!, gauge });\n }\n }\n\n if (gaugedPairs.length === 0) return;\n\n // Step 4: fetch token0, token1, stable for each gauged pair\n const metaCalls: Array<[Address, Hex]> = [];\n for (const { pair } of gaugedPairs) {\n metaCalls.push([pair, encodeFunctionData({ abi: pairAbi, functionName: \"token0\" })]);\n metaCalls.push([pair, encodeFunctionData({ abi: pairAbi, functionName: \"token1\" })]);\n metaCalls.push([pair, encodeFunctionData({ abi: pairAbi, functionName: \"stable\" })]);\n }\n const metaResults = await multicallRead(this.rpcUrl, metaCalls);\n\n // Step 5: collect unique token addresses and fetch symbols\n const tokenAddrs = new Set<Address>();\n for (let i = 0; i < gaugedPairs.length; i++) {\n const t0 = decodeAddress(metaResults[i * 3] ?? null);\n const t1 = decodeAddress(metaResults[i * 3 + 1] ?? null);\n if (t0 && t0 !== zeroAddress) tokenAddrs.add(t0);\n if (t1 && t1 !== zeroAddress) tokenAddrs.add(t1);\n }\n\n const uniqueTokens = Array.from(tokenAddrs);\n const symbolCalls: Array<[Address, Hex]> = uniqueTokens.map((t) => [\n t,\n encodeFunctionData({ abi: erc20SymbolAbi, functionName: \"symbol\" }),\n ]);\n const symbolResults = await multicallRead(this.rpcUrl, symbolCalls);\n const symbolMap = new Map<Address, string>();\n for (let i = 0; i < uniqueTokens.length; i++) {\n symbolMap.set(uniqueTokens[i]!, decodeSymbol(symbolResults[i] ?? null));\n }\n\n // Step 6: assemble results\n for (let i = 0; i < gaugedPairs.length; i++) {\n const { pair, gauge } = gaugedPairs[i]!;\n const t0 = decodeAddress(metaResults[i * 3] ?? null);\n const t1 = decodeAddress(metaResults[i * 3 + 1] ?? null);\n const stableRaw = metaResults[i * 3 + 2];\n const stable = stableRaw ? decodeBoolean(stableRaw) : false;\n out.push({\n pool: pair,\n gauge,\n token0: t0 ? (symbolMap.get(t0) ?? t0.slice(0, 10)) : \"?\",\n token1: t1 ? (symbolMap.get(t1) ?? t1.slice(0, 10)) : \"?\",\n type: \"V2\",\n stable,\n });\n }\n }\n\n private async _discoverCLGaugedPools(out: GaugedPool[]): Promise<void> {\n if (!this.rpcUrl || !this.clFactory) return;\n\n const clFactoryAbi = parseAbi([\n \"function getPool(address tokenA, address tokenB, int24 tickSpacing) external view returns (address pool)\",\n ]);\n const algebraFactoryAbi = parseAbi([\n \"function poolByPair(address tokenA, address tokenB) external view returns (address pool)\",\n ]);\n const poolAbi = parseAbi([\n \"function token0() external view returns (address)\",\n \"function token1() external view returns (address)\",\n ]);\n const erc20SymbolAbi = parseAbi([\"function symbol() external view returns (string)\"]);\n const gaugeForPoolAbi = parseAbi([\"function gaugeForPool(address) external view returns (address)\"]);\n const poolToGaugeAbi = parseAbi([\"function poolToGauge(address) external view returns (address)\"]);\n\n const tokenEntries = Object.entries(HYPEREVM_TOKENS);\n const tokenAddresses = tokenEntries.map(([, addr]) => addr);\n\n // Generate all unique token pairs\n const pairs: Array<[Address, Address]> = [];\n for (let i = 0; i < tokenAddresses.length; i++) {\n for (let j = i + 1; j < tokenAddresses.length; j++) {\n pairs.push([tokenAddresses[i]!, tokenAddresses[j]!]);\n }\n }\n\n // Detect factory type: try poolByPair (Algebra) — if it returns non-null, it's Algebra\n const isAlgebra = await (async () => {\n try {\n const [result] = await multicallRead(this.rpcUrl!, [[\n this.clFactory!,\n encodeFunctionData({ abi: algebraFactoryAbi, functionName: \"poolByPair\", args: [tokenAddresses[0]!, tokenAddresses[1]!] }),\n ]]);\n // If poolByPair returns any data (even zero address), it's Algebra\n return result !== null && result.length >= 66;\n } catch {\n return false;\n }\n })();\n\n // Build pool lookup calls\n const getPoolCalls: Array<[Address, Hex]> = [];\n const callMeta: Array<{ pairIdx: number; tickSpacing: number }> = [];\n\n if (isAlgebra) {\n // Algebra: one pool per pair (no tickSpacing)\n for (let p = 0; p < pairs.length; p++) {\n const [tokenA, tokenB] = pairs[p]!;\n getPoolCalls.push([\n this.clFactory!,\n encodeFunctionData({ abi: algebraFactoryAbi, functionName: \"poolByPair\", args: [tokenA!, tokenB!] }),\n ]);\n callMeta.push({ pairIdx: p, tickSpacing: 0 });\n }\n } else {\n // Uniswap-style: multiple tick spacings per pair\n for (let p = 0; p < pairs.length; p++) {\n const [tokenA, tokenB] = pairs[p]!;\n for (const ts of CL_TICK_SPACINGS) {\n getPoolCalls.push([\n this.clFactory!,\n encodeFunctionData({ abi: clFactoryAbi, functionName: \"getPool\", args: [tokenA!, tokenB!, ts] }),\n ]);\n callMeta.push({ pairIdx: p, tickSpacing: ts });\n }\n }\n }\n\n const getPoolResults = await multicallRead(this.rpcUrl, getPoolCalls);\n\n // Collect non-zero pool addresses\n const candidatePools: Array<{ pool: Address; tokenA: Address; tokenB: Address; tickSpacing: number }> = [];\n for (let i = 0; i < getPoolCalls.length; i++) {\n const pool = decodeAddress(getPoolResults[i] ?? null);\n if (pool && pool !== zeroAddress) {\n const { pairIdx, tickSpacing } = callMeta[i]!;\n const [tokenA, tokenB] = pairs[pairIdx]!;\n candidatePools.push({ pool, tokenA: tokenA!, tokenB: tokenB!, tickSpacing });\n }\n }\n\n if (candidatePools.length === 0) return;\n\n // Batch gauge lookup — try gaugeForPool first, fallback to poolToGauge\n const gaugeCalls: Array<[Address, Hex]> = candidatePools.map(({ pool }) => [\n this.voter,\n encodeFunctionData({ abi: gaugeForPoolAbi, functionName: \"gaugeForPool\", args: [pool] }),\n ]);\n let gaugeResults = await multicallRead(this.rpcUrl, gaugeCalls);\n\n // If all results are null (gaugeForPool not supported), try poolToGauge\n const allNull = gaugeResults.every(r => !r || decodeAddress(r) === zeroAddress || decodeAddress(r) === null);\n if (allNull) {\n const fallbackCalls: Array<[Address, Hex]> = candidatePools.map(({ pool }) => [\n this.voter,\n encodeFunctionData({ abi: poolToGaugeAbi, functionName: \"poolToGauge\", args: [pool] }),\n ]);\n gaugeResults = await multicallRead(this.rpcUrl, fallbackCalls);\n }\n\n // Filter to pools that have a gauge\n const gaugedCL: Array<{ pool: Address; gauge: Address; tokenA: Address; tokenB: Address; tickSpacing: number }> = [];\n for (let i = 0; i < candidatePools.length; i++) {\n const gauge = decodeAddress(gaugeResults[i] ?? null);\n if (gauge && gauge !== zeroAddress) {\n gaugedCL.push({ ...candidatePools[i]!, gauge });\n }\n }\n\n if (gaugedCL.length === 0) return;\n\n // Fetch token0/token1 from pool to get correct ordering, then symbols\n const tokenAddrsInPools = new Set<Address>();\n for (const { tokenA, tokenB } of gaugedCL) {\n tokenAddrsInPools.add(tokenA);\n tokenAddrsInPools.add(tokenB);\n }\n const uniqueTokens = Array.from(tokenAddrsInPools);\n const symbolCalls: Array<[Address, Hex]> = uniqueTokens.map((t) => [\n t,\n encodeFunctionData({ abi: erc20SymbolAbi, functionName: \"symbol\" }),\n ]);\n const symbolResults = await multicallRead(this.rpcUrl, symbolCalls);\n const symbolMap = new Map<Address, string>();\n for (let i = 0; i < uniqueTokens.length; i++) {\n symbolMap.set(uniqueTokens[i]!, decodeSymbol(symbolResults[i] ?? null));\n }\n\n // Also try to read actual token0/token1 ordering from the pool contract\n const poolTokenCalls: Array<[Address, Hex]> = [];\n for (const { pool } of gaugedCL) {\n poolTokenCalls.push([pool, encodeFunctionData({ abi: poolAbi, functionName: \"token0\" })]);\n poolTokenCalls.push([pool, encodeFunctionData({ abi: poolAbi, functionName: \"token1\" })]);\n }\n const poolTokenResults = await multicallRead(this.rpcUrl, poolTokenCalls);\n\n for (let i = 0; i < gaugedCL.length; i++) {\n const { pool, gauge, tokenA, tokenB, tickSpacing } = gaugedCL[i]!;\n const rawT0 = decodeAddress(poolTokenResults[i * 2] ?? null);\n const rawT1 = decodeAddress(poolTokenResults[i * 2 + 1] ?? null);\n const t0 = rawT0 && rawT0 !== zeroAddress ? rawT0 : tokenA;\n const t1 = rawT1 && rawT1 !== zeroAddress ? rawT1 : tokenB;\n out.push({\n pool,\n gauge,\n token0: symbolMap.get(t0) ?? t0.slice(0, 10),\n token1: symbolMap.get(t1) ?? t1.slice(0, 10),\n type: \"CL\",\n tickSpacing,\n });\n }\n }\n\n // IGauge\n\n async buildDeposit(gauge: Address, amount: bigint, tokenId?: bigint, lpToken?: Address): Promise<DeFiTx> {\n if (tokenId !== undefined) {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"depositFor\",\n args: [amount, tokenId],\n });\n return {\n description: `[${this.protocolName}] Deposit ${amount} LP to gauge (boost veNFT #${tokenId})`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n approvals: lpToken ? [{ token: lpToken, spender: gauge, amount }] : undefined,\n };\n }\n\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"deposit\",\n args: [amount],\n });\n return {\n description: `[${this.protocolName}] Deposit ${amount} LP to gauge`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n approvals: lpToken ? [{ token: lpToken, spender: gauge, amount }] : undefined,\n };\n }\n\n async buildWithdraw(gauge: Address, amount: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"withdraw\",\n args: [amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${amount} LP from gauge`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /**\n * Resolve gauge address from a pool address via voter contract.\n * Tries gaugeForPool (Ramses), poolToGauge (NEST), gauges (classic Solidly).\n */\n async resolveGauge(pool: Address): Promise<Address> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required for gauge lookup\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n for (const fn of [\"gaugeForPool\", \"poolToGauge\", \"gauges\"] as const) {\n try {\n const gauge = await client.readContract({\n address: this.voter,\n abi: voterAbi,\n functionName: fn,\n args: [pool],\n }) as Address;\n if (gauge !== zeroAddress) return gauge;\n } catch {\n // try next\n }\n }\n throw new DefiError(\"CONTRACT_ERROR\", `[${this.protocolName}] No gauge found for pool ${pool}`);\n }\n\n /**\n * Discover reward tokens for a gauge.\n * Returns { tokens, multiToken } where multiToken indicates getReward(account, tokens[]) support.\n */\n private async discoverRewardTokens(gauge: Address): Promise<{ tokens: Address[]; multiToken: boolean }> {\n if (!this.rpcUrl) return { tokens: [], multiToken: false };\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // 1. Try rewardsListLength — multi-token gauges (Ramses style)\n try {\n const len = await client.readContract({\n address: gauge,\n abi: gaugeAbi,\n functionName: \"rewardsListLength\",\n }) as bigint;\n\n if (Number(len) > 0) {\n // Discover via rewardData for known HyperEVM tokens\n const candidates: Address[] = [\n \"0x5555555555555555555555555555555555555555\", // WHYPE\n \"0x555570a286F15EbDFE42B66eDE2f724Aa1AB5555\", // xRAM\n \"0x067b0C72aa4C6Bd3BFEFfF443c536DCd6a25a9C8\", // HYBR\n \"0x07c57E32a3C29D5659bda1d3EFC2E7BF004E3035\", // NEST token\n ];\n const found: Address[] = [];\n for (const token of candidates) {\n try {\n const rd = await client.readContract({\n address: gauge,\n abi: gaugeAbi,\n functionName: \"rewardData\",\n args: [token],\n }) as readonly [bigint, bigint, bigint, bigint];\n if (rd[0] > 0n || rd[1] > 0n) found.push(token);\n } catch { /* not a reward */ }\n }\n if (found.length > 0) return { tokens: found, multiToken: true };\n return { tokens: [], multiToken: true }; // has rewards but couldn't enumerate\n }\n } catch {\n // no rewardsListLength\n }\n\n // 2. Fallback: rewardToken() — single-reward gauges (NEST / Hybra style)\n try {\n const rt = await client.readContract({\n address: gauge,\n abi: gaugeAbi,\n functionName: \"rewardToken\",\n }) as Address;\n if (rt !== zeroAddress) return { tokens: [rt], multiToken: false };\n } catch { /* no rewardToken */ }\n\n return { tokens: [], multiToken: false };\n }\n\n async buildClaimRewards(gauge: Address, account?: Address): Promise<DeFiTx> {\n if (!this.rpcUrl || !account) {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [account ?? zeroAddress],\n });\n return { description: `[${this.protocolName}] Claim gauge rewards`, to: gauge, data, value: 0n, gas_estimate: 200_000 };\n }\n\n const { tokens, multiToken } = await this.discoverRewardTokens(gauge);\n\n // Multi-token gauge (Ramses): getReward(account, tokens[])\n if (multiToken && tokens.length > 0) {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [account, tokens],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards (${tokens.length} tokens)`,\n to: gauge, data, value: 0n, gas_estimate: 300_000,\n };\n }\n\n // Single-token gauge (NEST / standard): getReward() with no args\n // Some gauges use getReward(account), but NEST-style uses getReward()\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards`,\n to: gauge, data, value: 0n, gas_estimate: 200_000,\n };\n }\n\n /**\n * Claim rewards for a CL gauge by NFT tokenId (Hybra V4 style).\n */\n async buildClaimRewardsByTokenId(gauge: Address, tokenId: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [tokenId],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards for NFT #${tokenId}`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async getPendingRewards(gauge: Address, user: Address): Promise<RewardInfo[]> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const results: RewardInfo[] = [];\n\n const { tokens, multiToken } = await this.discoverRewardTokens(gauge);\n\n if (multiToken && tokens.length > 0) {\n for (const token of tokens) {\n try {\n const earned = await client.readContract({\n address: gauge, abi: gaugeAbi, functionName: \"earned\", args: [token, user],\n }) as bigint;\n results.push({ token, symbol: token.slice(0, 10), amount: earned });\n } catch { /* skip */ }\n }\n } else if (tokens.length > 0) {\n // Single-token gauge: earned(account)\n try {\n const earned = await client.readContract({\n address: gauge, abi: gaugeAbi, functionName: \"earned\", args: [user],\n }) as bigint;\n results.push({ token: tokens[0]!, symbol: tokens[0]!.slice(0, 10), amount: earned });\n } catch { /* skip */ }\n } else {\n try {\n const earned = await client.readContract({\n address: gauge, abi: gaugeAbi, functionName: \"earned\", args: [user],\n }) as bigint;\n results.push({ token: zeroAddress as Address, symbol: \"unknown\", amount: earned });\n } catch { /* skip */ }\n }\n\n return results;\n }\n\n /**\n * Get pending rewards for a CL gauge NFT position (Hybra V4 style).\n */\n async getPendingRewardsByTokenId(gauge: Address, tokenId: bigint): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return await client.readContract({\n address: gauge,\n abi: gaugeAbi,\n functionName: \"earned\",\n args: [tokenId],\n }) as bigint;\n }\n\n // IVoteEscrow\n\n async buildCreateLock(amount: bigint, lockDuration: number): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"create_lock\",\n args: [amount, BigInt(lockDuration)],\n });\n return {\n description: `[${this.protocolName}] Create veNFT lock: ${amount} tokens for ${lockDuration}s`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildIncreaseAmount(tokenId: bigint, amount: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"increase_amount\",\n args: [tokenId, amount],\n });\n return {\n description: `[${this.protocolName}] Increase veNFT #${tokenId} by ${amount}`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildIncreaseUnlockTime(tokenId: bigint, lockDuration: number): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"increase_unlock_time\",\n args: [tokenId, BigInt(lockDuration)],\n });\n return {\n description: `[${this.protocolName}] Extend veNFT #${tokenId} lock by ${lockDuration}s`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildWithdrawExpired(tokenId: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"withdraw\",\n args: [tokenId],\n });\n return {\n description: `[${this.protocolName}] Withdraw expired veNFT #${tokenId}`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n // IVoter\n\n async buildVote(tokenId: bigint, pools: Address[], weights: bigint[]): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: voterAbi,\n functionName: \"vote\",\n args: [tokenId, pools, weights],\n });\n return {\n description: `[${this.protocolName}] Vote with veNFT #${tokenId}`,\n to: this.voter,\n data,\n value: 0n,\n gas_estimate: 500_000,\n };\n }\n\n async buildClaimBribes(bribes: Address[], tokenId: bigint): Promise<DeFiTx> {\n // claimBribes needs token arrays per bribe contract — simplified version\n const tokensPerBribe: Address[][] = bribes.map(() => []);\n const data = encodeFunctionData({\n abi: voterAbi,\n functionName: \"claimBribes\",\n args: [bribes, tokensPerBribe, tokenId],\n });\n return {\n description: `[${this.protocolName}] Claim bribes for veNFT #${tokenId}`,\n to: this.voter,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildClaimFees(fees: Address[], tokenId: bigint): Promise<DeFiTx> {\n const tokensPerFee: Address[][] = fees.map(() => []);\n const data = encodeFunctionData({\n abi: voterAbi,\n functionName: \"claimFees\",\n args: [fees, tokensPerFee, tokenId],\n });\n return {\n description: `[${this.protocolName}] Claim trading fees for veNFT #${tokenId}`,\n to: this.voter,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IGauge,\n ProtocolEntry,\n RewardInfo,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst masterchefAbi = parseAbi([\n \"function deposit(uint256 pid, uint256 amount) external\",\n \"function withdraw(uint256 pid, uint256 amount) external\",\n \"function claim(uint256[] calldata pids) external\",\n \"function pendingRewards(address account, uint256[] calldata pids) view returns (uint256[] memory moeRewards)\",\n \"function getNumberOfFarms() view returns (uint256)\",\n \"function getPidByPool(address pool) view returns (uint256)\",\n]);\n\nexport class MasterChefAdapter implements IGauge {\n private readonly protocolName: string;\n private readonly masterchef: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const masterchef = entry.contracts?.[\"masterchef\"];\n if (!masterchef) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'masterchef' contract\");\n }\n this.masterchef = masterchef;\n this.rpcUrl = rpcUrl;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n /**\n * Deposit LP tokens into a MasterChef farm.\n * `gauge` is the pool address (unused for calldata — MasterChef is the target).\n * `tokenId` carries the farm pid.\n */\n async buildDeposit(gauge: Address, amount: bigint, tokenId?: bigint): Promise<DeFiTx> {\n const pid = tokenId ?? 0n;\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"deposit\",\n args: [pid, amount],\n });\n return {\n description: `[${this.protocolName}] Deposit ${amount} LP to farm pid=${pid} (pool ${gauge})`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /**\n * Withdraw LP tokens from a MasterChef farm.\n * `gauge` is used to look up the pid description only; call site should pass pid via tokenId\n * on the deposit flow. Here pid defaults to 0 — callers should encode the pid in the gauge\n * address slot or wrap this adapter with a pid-aware helper.\n */\n async buildWithdraw(gauge: Address, amount: bigint): Promise<DeFiTx> {\n // IGauge interface does not carry tokenId on withdraw; default pid=0.\n // Callers that need a specific pid should call buildWithdrawPid directly.\n const pid = 0n;\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"withdraw\",\n args: [pid, amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${amount} LP from farm pid=${pid} (pool ${gauge})`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Withdraw LP tokens specifying a pid explicitly (MasterChef extension beyond IGauge). */\n async buildWithdrawPid(pid: bigint, amount: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"withdraw\",\n args: [pid, amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${amount} LP from farm pid=${pid}`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Claim pending MOE rewards. IGauge interface provides no pid — defaults to pid=0. */\n async buildClaimRewards(gauge: Address): Promise<DeFiTx> {\n const pid = 0n;\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"claim\",\n args: [[pid]],\n });\n return {\n description: `[${this.protocolName}] Claim MOE rewards for farm pid=${pid} (pool ${gauge})`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Claim pending MOE rewards for a specific pid (MasterChef extension beyond IGauge). */\n async buildClaimRewardsPid(pid: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"claim\",\n args: [[pid]],\n });\n return {\n description: `[${this.protocolName}] Claim MOE rewards for farm pid=${pid}`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Get pending MOE rewards for a user. Requires rpcUrl. */\n async getPendingRewards(_gauge: Address, user: Address): Promise<RewardInfo[]> {\n if (!this.rpcUrl) {\n throw DefiError.unsupported(`[${this.protocolName}] getPendingRewards requires RPC`);\n }\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const rewards = await client.readContract({\n address: this.masterchef,\n abi: masterchefAbi,\n functionName: \"pendingRewards\",\n args: [user, [0n]],\n });\n return (rewards as bigint[]).map((amount) => ({\n token: this.masterchef,\n symbol: \"MOE\",\n amount,\n }));\n }\n}\n","import {\n encodeFunctionData,\n decodeFunctionResult,\n parseAbi,\n createPublicClient,\n http,\n} from \"viem\";\nimport type { Address, Hex } from \"viem\";\n\nimport { DefiError, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { ProtocolEntry, DeFiTx, RewardInfo } from \"@hypurrquant/defi-core\";\n\n// ============================================================\n// ABIs\n// ============================================================\n\nconst lbRouterAbi = parseAbi([\n \"struct LiquidityParameters { address tokenX; address tokenY; uint256 binStep; uint256 amountX; uint256 amountY; uint256 amountXMin; uint256 amountYMin; uint256 activeIdDesired; uint256 idSlippage; int256[] deltaIds; uint256[] distributionX; uint256[] distributionY; address to; address refundTo; uint256 deadline; }\",\n \"function addLiquidity(LiquidityParameters calldata liquidityParameters) external returns (uint256 amountXAdded, uint256 amountYAdded, uint256 amountXLeft, uint256 amountYLeft, uint256[] memory depositIds, uint256[] memory liquidityMinted)\",\n \"function removeLiquidity(address tokenX, address tokenY, uint16 binStep, uint256 amountXMin, uint256 amountYMin, uint256[] memory ids, uint256[] memory amounts, address to, uint256 deadline) external returns (uint256 amountX, uint256 amountY)\",\n]);\n\nconst lbFactoryAbi = parseAbi([\n \"function getNumberOfLBPairs() external view returns (uint256)\",\n \"function getLBPairAtIndex(uint256 index) external view returns (address)\",\n]);\n\nconst lbPairAbi = parseAbi([\n \"function getLBHooksParameters() external view returns (bytes32)\",\n \"function getActiveId() external view returns (uint24)\",\n \"function getBinStep() external view returns (uint16)\",\n \"function getTokenX() external view returns (address)\",\n \"function getTokenY() external view returns (address)\",\n \"function balanceOf(address account, uint256 id) external view returns (uint256)\",\n \"function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory)\",\n]);\n\nconst lbRewarderAbi = parseAbi([\n \"function getRewardToken() external view returns (address)\",\n \"function getRewardedRange() external view returns (uint256 minBinId, uint256 maxBinId)\",\n \"function getPendingRewards(address user, uint256[] calldata ids) external view returns (uint256 pendingRewards)\",\n \"function claim(address user, uint256[] calldata ids) external\",\n \"function getPid() external view returns (uint256)\",\n \"function isStopped() external view returns (bool)\",\n \"function getLBPair() external view returns (address)\",\n \"function getMasterChef() external view returns (address)\",\n]);\n\nconst masterChefAbi = parseAbi([\n \"function getMoePerSecond() external view returns (uint256)\",\n \"function getTreasuryShare() external view returns (uint256)\",\n \"function getStaticShare() external view returns (uint256)\",\n \"function getVeMoe() external view returns (address)\",\n]);\n\nconst veMoeAbi = parseAbi([\n \"function getWeight(uint256 pid) external view returns (uint256)\",\n \"function getTotalWeight() external view returns (uint256)\",\n \"function getTopPoolIds() external view returns (uint256[] memory)\",\n]);\n\nconst lbPairBinAbi = parseAbi([\n \"function getBin(uint24 id) external view returns (uint128 reserveX, uint128 reserveY)\",\n \"function getActiveId() external view returns (uint24)\",\n]);\n\nconst lbQuoterAbi = parseAbi([\n \"function findBestPathFromAmountIn(address[] calldata route, uint128 amountIn) external view returns ((address[] route, address[] pairs, uint256[] binSteps, uint256[] versions, uint128[] amounts, uint128[] virtualAmountsWithoutSlippage, uint128[] fees))\",\n]);\n\nconst erc20Abi = parseAbi([\n \"function symbol() external view returns (string)\",\n]);\n\n// ============================================================\n// Types\n// ============================================================\n\nexport interface LBAddLiquidityParams {\n pool: Address;\n tokenX: Address;\n tokenY: Address;\n binStep: number;\n amountX: bigint;\n amountY: bigint;\n /** Number of bins on each side of active bin to distribute across (default: 5) */\n numBins?: number;\n /** Active bin id desired (defaults to on-chain query if rpcUrl provided) */\n activeIdDesired?: number;\n recipient: Address;\n deadline?: bigint;\n}\n\nexport interface LBRemoveLiquidityParams {\n tokenX: Address;\n tokenY: Address;\n binStep: number;\n binIds: number[];\n /** Amount of LB tokens to remove per bin (in order matching binIds) */\n amounts: bigint[];\n amountXMin?: bigint;\n amountYMin?: bigint;\n recipient: Address;\n deadline?: bigint;\n}\n\nexport interface LBPosition {\n binId: number;\n balance: bigint;\n}\n\nexport interface RewardedPool {\n pool: Address;\n rewarder: Address;\n rewardToken: Address;\n minBinId: number;\n maxBinId: number;\n pid: number;\n stopped: boolean;\n tokenX: Address;\n tokenY: Address;\n symbolX: string;\n symbolY: string;\n isTopPool: boolean;\n moePerDay: number;\n rangeTvlUsd: number;\n aprPercent: number;\n rewardedBins: number;\n}\n\n// ============================================================\n// Helpers\n// ============================================================\n\n/** Decode address using a generic address ABI */\nconst _addressAbi = parseAbi([\"function f() external view returns (address)\"]);\nfunction decodeAddressResult(data: Hex | null): Address | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _addressAbi, functionName: \"f\", data }) as Address;\n } catch {\n return null;\n }\n}\n\n/** Decode uint256 from multicall returnData */\nconst _uint256Abi = parseAbi([\"function f() external view returns (uint256)\"]);\nfunction decodeUint256Result(data: Hex | null): bigint | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _uint256Abi, functionName: \"f\", data }) as bigint;\n } catch {\n return null;\n }\n}\n\n/** Decode bool from multicall returnData */\nconst _boolAbi = parseAbi([\"function f() external view returns (bool)\"]);\nfunction decodeBoolResult(data: Hex | null): boolean | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _boolAbi, functionName: \"f\", data }) as boolean;\n } catch {\n return null;\n }\n}\n\n/** Decode string from multicall returnData */\nfunction decodeStringResult(data: Hex | null): string {\n if (!data) return \"?\";\n try {\n return decodeFunctionResult({ abi: erc20Abi, functionName: \"symbol\", data }) as string;\n } catch {\n return \"?\";\n }\n}\n\n/** Decode getRewardedRange (returns (uint256, uint256)) */\nconst _rangeAbi = parseAbi([\"function f() external view returns (uint256 minBinId, uint256 maxBinId)\"]);\nfunction decodeRangeResult(data: Hex | null): [bigint, bigint] | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _rangeAbi, functionName: \"f\", data }) as [bigint, bigint];\n } catch {\n return null;\n }\n}\n\n/** Decode getBin result (uint128, uint128) */\nconst _binAbi = parseAbi([\"function f() external view returns (uint128 reserveX, uint128 reserveY)\"]);\nfunction decodeBinResult(data: Hex | null): [bigint, bigint] | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _binAbi, functionName: \"f\", data }) as [bigint, bigint];\n } catch {\n return null;\n }\n}\n\n/** Decode uint256[] (e.g. getTopPoolIds) */\nconst _uint256ArrayAbi = parseAbi([\"function f() external view returns (uint256[] memory)\"]);\nfunction decodeUint256ArrayResult(data: Hex | null): bigint[] | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _uint256ArrayAbi, functionName: \"f\", data }) as bigint[];\n } catch {\n return null;\n }\n}\n\n/** Extract rewarder address from LB hooks params (lower 20 bytes of bytes32) */\nfunction extractRewarderAddress(hooksParams: Hex): Address | null {\n // hooksParams is a 32-byte hex string (0x + 64 hex chars)\n if (!hooksParams || hooksParams === \"0x0000000000000000000000000000000000000000000000000000000000000000\") {\n return null;\n }\n // Lower 20 bytes = last 40 hex characters of the 64-char data portion\n const hex = hooksParams.slice(2); // strip 0x\n if (hex.length < 64) return null;\n const addrHex = hex.slice(24, 64); // bytes 12..31 = lower 20 bytes\n if (addrHex === \"0000000000000000000000000000000000000000\") return null;\n return `0x${addrHex}` as Address;\n}\n\n/** Build uniform distribution arrays for LB add liquidity.\n *\n * Distribution rules:\n * - Bins strictly below active: only tokenY (distributionX[i]=0, distributionY[i]=share)\n * - Bin at active: tokenX and tokenY split 50/50\n * - Bins strictly above active: only tokenX (distributionX[i]=share, distributionY[i]=0)\n *\n * distributionX / distributionY sum to 1e18 respectively.\n */\nfunction buildUniformDistribution(\n deltaIds: number[],\n): { distributionX: bigint[]; distributionY: bigint[] } {\n const PRECISION = 10n ** 18n;\n const n = deltaIds.length;\n\n // Count how many bins receive X and Y\n const xBins = deltaIds.filter((d) => d >= 0).length; // active + above\n const yBins = deltaIds.filter((d) => d <= 0).length; // active + below\n\n const distributionX: bigint[] = [];\n const distributionY: bigint[] = [];\n\n for (const delta of deltaIds) {\n // X share: bins at or above active\n const xShare = delta >= 0 && xBins > 0 ? PRECISION / BigInt(xBins) : 0n;\n // Y share: bins at or below active\n const yShare = delta <= 0 && yBins > 0 ? PRECISION / BigInt(yBins) : 0n;\n distributionX.push(xShare);\n distributionY.push(yShare);\n }\n\n // Correct rounding on the active bin (index where delta === 0)\n // The sum must be exactly PRECISION; adjust the first qualifying element\n const xSum = distributionX.reduce((a, b) => a + b, 0n);\n const ySum = distributionY.reduce((a, b) => a + b, 0n);\n if (xSum > 0n && xSum !== PRECISION) {\n const firstX = distributionX.findIndex((v) => v > 0n);\n if (firstX !== -1) distributionX[firstX] += PRECISION - xSum;\n }\n if (ySum > 0n && ySum !== PRECISION) {\n const firstY = distributionY.findIndex((v) => v > 0n);\n if (firstY !== -1) distributionY[firstY] += PRECISION - ySum;\n }\n\n return { distributionX, distributionY };\n}\n\n// ============================================================\n// Adapter\n// ============================================================\n\nexport class MerchantMoeLBAdapter {\n private readonly protocolName: string;\n private readonly lbRouter: Address;\n private readonly lbFactory: Address;\n private readonly lbQuoter?: Address;\n private readonly rpcUrl?: string;\n /** WMNT address (lb_mid_wmnt in config) used for MOE price routing */\n private readonly wmnt?: Address;\n /** USDT address (lb_mid_usdt in config) used for MNT/USD price routing */\n private readonly usdt?: Address;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const lbRouter = entry.contracts?.[\"lb_router\"];\n if (!lbRouter) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'lb_router' contract address\");\n }\n const lbFactory = entry.contracts?.[\"lb_factory\"];\n if (!lbFactory) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'lb_factory' contract address\");\n }\n this.lbRouter = lbRouter;\n this.lbFactory = lbFactory;\n this.lbQuoter = entry.contracts?.[\"lb_quoter\"];\n this.wmnt = entry.contracts?.[\"lb_mid_wmnt\"];\n this.usdt = entry.contracts?.[\"lb_mid_usdt\"];\n this.rpcUrl = rpcUrl;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n private requireRpc(): string {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(`[${this.protocolName}] RPC URL required`);\n }\n return this.rpcUrl;\n }\n\n /**\n * Build an addLiquidity transaction for a Liquidity Book pair.\n * Distributes tokenX/tokenY uniformly across active bin ± numBins.\n */\n async buildAddLiquidity(params: LBAddLiquidityParams): Promise<DeFiTx> {\n const numBins = params.numBins ?? 5;\n const deadline = params.deadline ?? BigInt(\"18446744073709551615\");\n\n // Resolve active bin id\n let activeIdDesired = params.activeIdDesired;\n if (activeIdDesired === undefined) {\n const rpcUrl = this.requireRpc();\n const client = createPublicClient({ transport: http(rpcUrl) });\n const activeId = await client.readContract({\n address: params.pool,\n abi: lbPairAbi,\n functionName: \"getActiveId\",\n });\n activeIdDesired = activeId as number;\n }\n\n // Build delta IDs: [-numBins, ..., -1, 0, 1, ..., numBins]\n const deltaIds: number[] = [];\n for (let d = -numBins; d <= numBins; d++) {\n deltaIds.push(d);\n }\n\n const { distributionX, distributionY } = buildUniformDistribution(deltaIds);\n\n const data = encodeFunctionData({\n abi: lbRouterAbi,\n functionName: \"addLiquidity\",\n args: [\n {\n tokenX: params.tokenX,\n tokenY: params.tokenY,\n binStep: BigInt(params.binStep),\n amountX: params.amountX,\n amountY: params.amountY,\n amountXMin: 0n,\n amountYMin: 0n,\n activeIdDesired: BigInt(activeIdDesired),\n idSlippage: BigInt(numBins + 2),\n deltaIds: deltaIds.map(BigInt),\n distributionX,\n distributionY,\n to: params.recipient,\n refundTo: params.recipient,\n deadline,\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] LB addLiquidity ${params.amountX} tokenX + ${params.amountY} tokenY across ${deltaIds.length} bins`,\n to: this.lbRouter,\n data,\n value: 0n,\n gas_estimate: 800_000,\n approvals: [\n { token: params.tokenX, spender: this.lbRouter, amount: params.amountX },\n { token: params.tokenY, spender: this.lbRouter, amount: params.amountY },\n ],\n };\n }\n\n /**\n * Build a removeLiquidity transaction for specific LB bins.\n */\n async buildRemoveLiquidity(params: LBRemoveLiquidityParams): Promise<DeFiTx> {\n const deadline = params.deadline ?? BigInt(\"18446744073709551615\");\n\n const data = encodeFunctionData({\n abi: lbRouterAbi,\n functionName: \"removeLiquidity\",\n args: [\n params.tokenX,\n params.tokenY,\n params.binStep,\n params.amountXMin ?? 0n,\n params.amountYMin ?? 0n,\n params.binIds.map(BigInt),\n params.amounts,\n params.recipient,\n deadline,\n ],\n });\n\n return {\n description: `[${this.protocolName}] LB removeLiquidity from ${params.binIds.length} bins`,\n to: this.lbRouter,\n data,\n value: 0n,\n gas_estimate: 600_000,\n };\n }\n\n /**\n * Auto-detect bin IDs for a pool from the rewarder's rewarded range.\n * Falls back to active bin ± 50 scan if no rewarder exists.\n */\n private async autoDetectBins(pool: Address): Promise<number[]> {\n const rpcUrl = this.requireRpc();\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n const hooksParams = await client.readContract({\n address: pool,\n abi: lbPairAbi,\n functionName: \"getLBHooksParameters\",\n }) as Hex;\n\n const rewarder = extractRewarderAddress(hooksParams);\n if (rewarder) {\n const range = await client.readContract({\n address: rewarder,\n abi: lbRewarderAbi,\n functionName: \"getRewardedRange\",\n }) as [bigint, bigint];\n const min = Number(range[0]);\n const max = Number(range[1]);\n const ids: number[] = [];\n for (let b = min; b <= max; b++) ids.push(b);\n return ids;\n }\n\n // No rewarder: scan active bin ± 50\n const activeId = await client.readContract({\n address: pool,\n abi: lbPairAbi,\n functionName: \"getActiveId\",\n }) as number;\n const ids: number[] = [];\n for (let b = activeId - 50; b <= activeId + 50; b++) ids.push(b);\n return ids;\n }\n\n /**\n * Get pending MOE rewards for a user across specified bin IDs.\n * If binIds is omitted, auto-detects from the rewarder's rewarded range.\n * Reads the rewarder address from the pool's hooks parameters.\n */\n async getPendingRewards(user: Address, pool: Address, binIds?: number[]): Promise<RewardInfo[]> {\n const rpcUrl = this.requireRpc();\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n const hooksParams = await client.readContract({\n address: pool,\n abi: lbPairAbi,\n functionName: \"getLBHooksParameters\",\n }) as Hex;\n\n const rewarder = extractRewarderAddress(hooksParams);\n if (!rewarder) {\n return [];\n }\n\n // Auto-detect bins from rewarder range if not provided\n let resolvedBinIds = binIds;\n if (!resolvedBinIds || resolvedBinIds.length === 0) {\n const range = await client.readContract({\n address: rewarder,\n abi: lbRewarderAbi,\n functionName: \"getRewardedRange\",\n }) as [bigint, bigint];\n const min = Number(range[0]);\n const max = Number(range[1]);\n resolvedBinIds = [];\n for (let b = min; b <= max; b++) resolvedBinIds.push(b);\n }\n\n const [pending, rewardToken] = await Promise.all([\n client.readContract({\n address: rewarder,\n abi: lbRewarderAbi,\n functionName: \"getPendingRewards\",\n args: [user, resolvedBinIds.map(BigInt)],\n }),\n client.readContract({\n address: rewarder,\n abi: lbRewarderAbi,\n functionName: \"getRewardToken\",\n }),\n ]);\n\n return [\n {\n token: rewardToken as Address,\n symbol: \"MOE\",\n amount: pending as bigint,\n },\n ];\n }\n\n /**\n * Build a claim rewards transaction for specific LB bins.\n * If binIds is omitted, auto-detects from the rewarder's rewarded range.\n */\n async buildClaimRewards(user: Address, pool: Address, binIds?: number[]): Promise<DeFiTx> {\n const rpcUrl = this.requireRpc();\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n const hooksParams = await client.readContract({\n address: pool,\n abi: lbPairAbi,\n functionName: \"getLBHooksParameters\",\n }) as Hex;\n\n const rewarder = extractRewarderAddress(hooksParams);\n if (!rewarder) {\n throw new DefiError(\"CONTRACT_ERROR\", `[${this.protocolName}] Pool ${pool} has no active rewarder`);\n }\n\n // Auto-detect bins from rewarder range if not provided\n let resolvedBinIds = binIds;\n if (!resolvedBinIds || resolvedBinIds.length === 0) {\n const range = await client.readContract({\n address: rewarder,\n abi: lbRewarderAbi,\n functionName: \"getRewardedRange\",\n }) as [bigint, bigint];\n const min = Number(range[0]);\n const max = Number(range[1]);\n resolvedBinIds = [];\n for (let b = min; b <= max; b++) resolvedBinIds.push(b);\n }\n\n const data = encodeFunctionData({\n abi: lbRewarderAbi,\n functionName: \"claim\",\n args: [user, resolvedBinIds.map(BigInt)],\n });\n\n return {\n description: `[${this.protocolName}] LB claim rewards for ${resolvedBinIds.length} bins`,\n to: rewarder,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n /**\n * Discover all active rewarded LB pools by iterating the factory.\n * Uses 7 multicall batches to minimise RPC round-trips and avoid 429s.\n *\n * Batch 1: getNumberOfLBPairs(), then getLBPairAtIndex(i) for all i\n * Batch 2: getLBHooksParameters() for all pairs → extract rewarder addresses\n * Batch 3: isStopped/getRewardedRange/getRewardToken/getPid/getMasterChef for each rewarder\n * Batch 4: getTokenX/getTokenY for each rewarded pair, then symbol() for unique tokens\n * Batch 5: Bootstrap MasterChef→VeMoe, then getMoePerSecond/getTreasuryShare/getStaticShare/getTotalWeight/getTopPoolIds\n * Batch 6: VeMoe.getWeight(pid) for each rewarded pool\n * Batch 7: Pool.getBin(binId) for all bins in rewarded range of each pool\n * Price: LB Quoter findBestPathFromAmountIn for MOE/WMNT and WMNT/USDT prices\n */\n async discoverRewardedPools(): Promise<RewardedPool[]> {\n const rpcUrl = this.requireRpc();\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n // --- Batch 1a: get pair count ---\n const pairCount = await client.readContract({\n address: this.lbFactory,\n abi: lbFactoryAbi,\n functionName: \"getNumberOfLBPairs\",\n }) as bigint;\n\n const count = Number(pairCount);\n if (count === 0) return [];\n\n // --- Batch 1b: getLBPairAtIndex for all indices ---\n const batch1Calls: Array<[Address, Hex]> = Array.from({ length: count }, (_, i) => [\n this.lbFactory,\n encodeFunctionData({ abi: lbFactoryAbi, functionName: \"getLBPairAtIndex\", args: [BigInt(i)] }),\n ]);\n const batch1Results = await multicallRead(rpcUrl, batch1Calls);\n\n const pairAddresses: Address[] = batch1Results\n .map((r) => decodeAddressResult(r))\n .filter((a): a is Address => a !== null);\n\n if (pairAddresses.length === 0) return [];\n\n // --- Batch 2: getLBHooksParameters for all pairs ---\n const batch2Calls: Array<[Address, Hex]> = pairAddresses.map((pair) => [\n pair,\n encodeFunctionData({ abi: lbPairAbi, functionName: \"getLBHooksParameters\" }),\n ]);\n const batch2Results = await multicallRead(rpcUrl, batch2Calls);\n\n // Filter pairs with a rewarder\n const rewardedPairs: Array<{ pool: Address; rewarder: Address }> = [];\n for (let i = 0; i < pairAddresses.length; i++) {\n const raw = batch2Results[i];\n if (!raw) continue;\n // getLBHooksParameters returns bytes32 — decode as raw bytes32 value\n let hooksBytes: Hex;\n try {\n const _bytes32Abi = parseAbi([\"function f() external view returns (bytes32)\"]);\n hooksBytes = decodeFunctionResult({ abi: _bytes32Abi, functionName: \"f\", data: raw }) as Hex;\n } catch {\n continue;\n }\n const rewarder = extractRewarderAddress(hooksBytes);\n if (rewarder) {\n rewardedPairs.push({ pool: pairAddresses[i]!, rewarder });\n }\n }\n\n if (rewardedPairs.length === 0) return [];\n\n // --- Batch 3: rewarder details (5 calls per rewarder, interleaved) ---\n const batch3Calls: Array<[Address, Hex]> = [];\n for (const { rewarder } of rewardedPairs) {\n batch3Calls.push([rewarder, encodeFunctionData({ abi: lbRewarderAbi, functionName: \"isStopped\" })]);\n batch3Calls.push([rewarder, encodeFunctionData({ abi: lbRewarderAbi, functionName: \"getRewardedRange\" })]);\n batch3Calls.push([rewarder, encodeFunctionData({ abi: lbRewarderAbi, functionName: \"getRewardToken\" })]);\n batch3Calls.push([rewarder, encodeFunctionData({ abi: lbRewarderAbi, functionName: \"getPid\" })]);\n batch3Calls.push([rewarder, encodeFunctionData({ abi: lbRewarderAbi, functionName: \"getMasterChef\" })]);\n }\n const batch3Results = await multicallRead(rpcUrl, batch3Calls);\n\n // --- Batch 4a: getTokenX / getTokenY for rewarded pairs ---\n const batch4aCalls: Array<[Address, Hex]> = [];\n for (const { pool } of rewardedPairs) {\n batch4aCalls.push([pool, encodeFunctionData({ abi: lbPairAbi, functionName: \"getTokenX\" })]);\n batch4aCalls.push([pool, encodeFunctionData({ abi: lbPairAbi, functionName: \"getTokenY\" })]);\n }\n const batch4aResults = await multicallRead(rpcUrl, batch4aCalls);\n\n // Collect unique token addresses for symbol lookup\n const tokenXAddresses: Array<Address | null> = [];\n const tokenYAddresses: Array<Address | null> = [];\n for (let i = 0; i < rewardedPairs.length; i++) {\n tokenXAddresses.push(decodeAddressResult(batch4aResults[i * 2] ?? null));\n tokenYAddresses.push(decodeAddressResult(batch4aResults[i * 2 + 1] ?? null));\n }\n\n const uniqueTokens = Array.from(\n new Set([...tokenXAddresses, ...tokenYAddresses].filter((a): a is Address => a !== null)),\n );\n\n // --- Batch 4b: symbol() for each unique token ---\n const batch4bCalls: Array<[Address, Hex]> = uniqueTokens.map((token) => [\n token,\n encodeFunctionData({ abi: erc20Abi, functionName: \"symbol\" }),\n ]);\n const batch4bResults = await multicallRead(rpcUrl, batch4bCalls);\n const symbolMap = new Map<Address, string>();\n for (let i = 0; i < uniqueTokens.length; i++) {\n symbolMap.set(uniqueTokens[i]!, decodeStringResult(batch4bResults[i] ?? null));\n }\n\n // Extract per-pool data from batch 3 (5 calls per rewarder)\n const STRIDE3 = 5;\n const poolData: Array<{\n stopped: boolean;\n range: [bigint, bigint] | null;\n rewardToken: Address | null;\n pid: number;\n masterChef: Address | null;\n }> = [];\n for (let i = 0; i < rewardedPairs.length; i++) {\n const base = i * STRIDE3;\n poolData.push({\n stopped: decodeBoolResult(batch3Results[base] ?? null) ?? false,\n range: decodeRangeResult(batch3Results[base + 1] ?? null),\n rewardToken: decodeAddressResult(batch3Results[base + 2] ?? null),\n pid: Number(decodeUint256Result(batch3Results[base + 3] ?? null) ?? 0n),\n masterChef: decodeAddressResult(batch3Results[base + 4] ?? null),\n });\n }\n\n // --- Batch 5: Bootstrap MasterChef/VeMoe, then fetch global emission params ---\n // Find the first valid MasterChef address from the rewarders\n const masterChefAddr = poolData.map((d) => d.masterChef).find((a): a is Address => a !== null) ?? null;\n\n let moePerDay = 0;\n let topPoolIds = new Set<number>();\n let totalWeightRaw = 0n;\n let veMoeAddr: Address | null = null;\n\n if (masterChefAddr) {\n // First get VeMoe address from MasterChef\n veMoeAddr = await client.readContract({\n address: masterChefAddr,\n abi: masterChefAbi,\n functionName: \"getVeMoe\",\n }) as Address;\n\n // Batch 5: MasterChef global data + VeMoe global data\n const batch5Calls: Array<[Address, Hex]> = [\n [masterChefAddr, encodeFunctionData({ abi: masterChefAbi, functionName: \"getMoePerSecond\" })],\n [masterChefAddr, encodeFunctionData({ abi: masterChefAbi, functionName: \"getTreasuryShare\" })],\n [masterChefAddr, encodeFunctionData({ abi: masterChefAbi, functionName: \"getStaticShare\" })],\n [veMoeAddr, encodeFunctionData({ abi: veMoeAbi, functionName: \"getTotalWeight\" })],\n [veMoeAddr, encodeFunctionData({ abi: veMoeAbi, functionName: \"getTopPoolIds\" })],\n ];\n const batch5Results = await multicallRead(rpcUrl, batch5Calls);\n\n const moePerSecRaw = decodeUint256Result(batch5Results[0] ?? null) ?? 0n;\n const treasuryShareRaw = decodeUint256Result(batch5Results[1] ?? null) ?? 0n;\n const staticShareRaw = decodeUint256Result(batch5Results[2] ?? null) ?? 0n;\n totalWeightRaw = decodeUint256Result(batch5Results[3] ?? null) ?? 0n;\n const topPoolIdsRaw = decodeUint256ArrayResult(batch5Results[4] ?? null) ?? [];\n\n topPoolIds = new Set(topPoolIdsRaw.map(Number));\n\n // Shares are fixed-point 1e18 fractions\n const PRECISION = 10n ** 18n;\n // net_moe_per_sec = total × (1 - treasury) × (1 - static)\n // expressed in bigint arithmetic to avoid float truncation\n const netPerSec =\n (moePerSecRaw * (PRECISION - treasuryShareRaw) / PRECISION) *\n (PRECISION - staticShareRaw) / PRECISION;\n\n // Convert to human-readable MOE/day (MOE has 18 decimals)\n // This is the total net MOE/day that flows to dynamic (VeMoe) pools\n moePerDay = Number(netPerSec * 86400n) / 1e18;\n }\n\n // --- Batch 6: VeMoe.getWeight(pid) for each rewarded pool ---\n const weightByPid = new Map<number, bigint>();\n if (veMoeAddr && rewardedPairs.length > 0) {\n const batch6Calls: Array<[Address, Hex]> = poolData.map((d) => [\n veMoeAddr!,\n encodeFunctionData({ abi: veMoeAbi, functionName: \"getWeight\", args: [BigInt(d.pid)] }),\n ]);\n const batch6Results = await multicallRead(rpcUrl, batch6Calls);\n for (let i = 0; i < poolData.length; i++) {\n weightByPid.set(poolData[i]!.pid, decodeUint256Result(batch6Results[i] ?? null) ?? 0n);\n }\n }\n\n // --- Price: MOE and WMNT prices in USD via LB Quoter ---\n // Route: MOE → WMNT → USDT (MOE has 18 decimals, WMNT has 18, USDT has 6)\n let moePriceUsd = 0;\n let wmntPriceUsd = 0;\n const MOE_ADDR = \"0x4515A45337F461A11Ff0FE8aBF3c606AE5dC00c9\" as Address;\n if (this.lbQuoter && this.wmnt && this.usdt) {\n try {\n const [moeWmntQuote, wmntUsdtQuote] = await Promise.all([\n client.readContract({\n address: this.lbQuoter,\n abi: lbQuoterAbi,\n functionName: \"findBestPathFromAmountIn\",\n args: [[MOE_ADDR, this.wmnt], 10n ** 18n],\n }),\n client.readContract({\n address: this.lbQuoter,\n abi: lbQuoterAbi,\n functionName: \"findBestPathFromAmountIn\",\n args: [[this.wmnt, this.usdt], 10n ** 18n],\n }),\n ]);\n // amounts[last] is the output amount (USDT has 6 decimals, WMNT has 18)\n const moeInWmnt = Number((moeWmntQuote as unknown as { amounts: bigint[] }).amounts.at(-1) ?? 0n) / 1e18;\n wmntPriceUsd = Number((wmntUsdtQuote as unknown as { amounts: bigint[] }).amounts.at(-1) ?? 0n) / 1e6;\n moePriceUsd = moeInWmnt * wmntPriceUsd;\n } catch {\n // Price fetch failed — APR will be 0\n }\n }\n\n // --- Batch 7: Pool.getBin(binId) for all bins in rewarded range ---\n // Build flat list of (poolIndex, binId) for all rewarded bins\n type BinRequest = { poolIdx: number; binId: number };\n const binRequests: BinRequest[] = [];\n for (let i = 0; i < rewardedPairs.length; i++) {\n const range = poolData[i]!.range;\n if (!range) continue;\n const minBin = Number(range[0]);\n const maxBin = Number(range[1]);\n for (let b = minBin; b <= maxBin; b++) {\n binRequests.push({ poolIdx: i, binId: b });\n }\n }\n\n // Bin reserves keyed by pool index\n // reserveX[poolIdx][binId] and reserveY[poolIdx][binId]\n const binReservesX = new Map<number, Map<number, bigint>>();\n const binReservesY = new Map<number, Map<number, bigint>>();\n\n if (binRequests.length > 0) {\n const batch7Calls: Array<[Address, Hex]> = binRequests.map(({ poolIdx, binId }) => [\n rewardedPairs[poolIdx]!.pool,\n encodeFunctionData({ abi: lbPairBinAbi, functionName: \"getBin\", args: [binId] }),\n ]);\n const batch7Results = await multicallRead(rpcUrl, batch7Calls);\n\n for (let j = 0; j < binRequests.length; j++) {\n const { poolIdx, binId } = binRequests[j]!;\n const decoded = decodeBinResult(batch7Results[j] ?? null);\n if (!decoded) continue;\n if (!binReservesX.has(poolIdx)) {\n binReservesX.set(poolIdx, new Map());\n binReservesY.set(poolIdx, new Map());\n }\n binReservesX.get(poolIdx)!.set(binId, decoded[0]);\n binReservesY.get(poolIdx)!.set(binId, decoded[1]);\n }\n }\n\n // --- Assemble results ---\n // Token price classification by symbol (USD)\n // Stablecoins → $1; WMNT/MNT → wmntPriceUsd; MOE → moePriceUsd; unknown → 0\n const stableSymbols = new Set([\"USDT\", \"USDC\", \"MUSD\", \"AUSD\", \"USDY\", \"FDUSD\"]);\n const mntSymbols = new Set([\"WMNT\", \"MNT\"]);\n const moeSymbols = new Set([\"MOE\"]);\n // USDT/USDC on Mantle have 6 decimals; other stable tokens have 18\n const sixDecimalStables = new Set([\"USDT\", \"USDC\", \"FDUSD\"]);\n\n const getTokenPriceUsd = (sym: string): number => {\n if (stableSymbols.has(sym)) return 1;\n if (mntSymbols.has(sym)) return wmntPriceUsd;\n if (moeSymbols.has(sym)) return moePriceUsd;\n return 0;\n };\n\n const getTokenDecimals = (sym: string): number => {\n return sixDecimalStables.has(sym) ? 6 : 18;\n };\n\n const results: RewardedPool[] = [];\n for (let i = 0; i < rewardedPairs.length; i++) {\n const { pool, rewarder } = rewardedPairs[i]!;\n const data = poolData[i]!;\n\n const tokenX = tokenXAddresses[i] ?? (\"0x0000000000000000000000000000000000000000\" as Address);\n const tokenY = tokenYAddresses[i] ?? (\"0x0000000000000000000000000000000000000000\" as Address);\n const symX = symbolMap.get(tokenX) ?? \"?\";\n const symY = symbolMap.get(tokenY) ?? \"?\";\n\n const isTopPool = topPoolIds.has(data.pid);\n const weight = weightByPid.get(data.pid) ?? 0n;\n\n // Pool's MOE/day = total_net_moe_per_day × weight / total_weight\n // Only top pools (in VeMoe top list) receive dynamic emissions\n let poolMoePerDay = 0;\n if (isTopPool && totalWeightRaw > 0n && weight > 0n) {\n poolMoePerDay = moePerDay * (Number(weight) / Number(totalWeightRaw));\n }\n\n // Range TVL: sum bin reserves × token prices\n const rxMap = binReservesX.get(i);\n const ryMap = binReservesY.get(i);\n const range = data.range;\n let rangeTvlUsd = 0;\n let rewardedBins = 0;\n\n if (range) {\n const minBin = Number(range[0]);\n const maxBin = Number(range[1]);\n rewardedBins = maxBin - minBin + 1;\n if (rxMap && ryMap) {\n const priceX = getTokenPriceUsd(symX);\n const priceY = getTokenPriceUsd(symY);\n const decX = getTokenDecimals(symX);\n const decY = getTokenDecimals(symY);\n for (let b = minBin; b <= maxBin; b++) {\n const rx = rxMap.get(b) ?? 0n;\n const ry = ryMap.get(b) ?? 0n;\n rangeTvlUsd += (Number(rx) / 10 ** decX) * priceX;\n rangeTvlUsd += (Number(ry) / 10 ** decY) * priceY;\n }\n }\n }\n\n // APR = (poolMoePerDay * moePriceUsd * 365) / rangeTvlUsd * 100\n const aprPercent =\n rangeTvlUsd > 0 && moePriceUsd > 0\n ? (poolMoePerDay * moePriceUsd * 365 / rangeTvlUsd) * 100\n : 0;\n\n results.push({\n pool,\n rewarder,\n rewardToken: data.rewardToken ?? (\"0x0000000000000000000000000000000000000000\" as Address),\n minBinId: range ? Number(range[0]) : 0,\n maxBinId: range ? Number(range[1]) : 0,\n pid: data.pid,\n stopped: data.stopped,\n tokenX,\n tokenY,\n symbolX: symX,\n symbolY: symY,\n isTopPool,\n moePerDay: poolMoePerDay,\n rangeTvlUsd,\n aprPercent,\n rewardedBins,\n });\n }\n\n return results;\n }\n\n /**\n * Get a user's LB positions (bin balances) across a range of bin IDs.\n * If binIds is omitted, auto-detects from the rewarder's rewarded range (or active ± 50).\n */\n async getUserPositions(user: Address, pool: Address, binIds?: number[]): Promise<LBPosition[]> {\n const rpcUrl = this.requireRpc();\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n const resolvedBinIds = (binIds && binIds.length > 0) ? binIds : await this.autoDetectBins(pool);\n\n const accounts = resolvedBinIds.map(() => user);\n const ids = resolvedBinIds.map(BigInt);\n\n const balances = await client.readContract({\n address: pool,\n abi: lbPairAbi,\n functionName: \"balanceOfBatch\",\n args: [accounts, ids],\n }) as bigint[];\n\n return resolvedBinIds\n .map((binId, i) => ({ binId, balance: balances[i] ?? 0n }))\n .filter((p) => p.balance > 0n);\n }\n}\n","import {\n decodeAbiParameters,\n encodeFunctionData,\n encodeAbiParameters,\n http,\n createPublicClient,\n keccak256,\n parseAbi,\n decodeFunctionResult,\n zeroAddress,\n} from \"viem\";\nimport type { Address, Hex } from \"viem\";\n\nimport { DefiError, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { DeFiTx } from \"@hypurrquant/defi-core\";\n\n// ─── Constants ────────────────────────────────────────────────────────────────\n\n/** KITTEN reward token on Hyper EVM */\nconst KITTEN_TOKEN: Address = \"0x618275f8efe54c2afa87bfb9f210a52f0ff89364\";\n\n/** WHYPE bonus reward token */\nconst WHYPE_TOKEN: Address = \"0x5555555555555555555555555555555555555555\";\n\n/** Max nonce to scan when discovering incentive keys */\nconst MAX_NONCE_SCAN = 60;\n\n/** HyperEVM well-known token addresses for pool discovery (matches solidly_gauge.ts) */\nconst HYPEREVM_TOKENS: Address[] = [\n \"0x5555555555555555555555555555555555555555\", // WHYPE\n \"0xb88339CB7199b77E23DB6E890353E22632Ba630f\", // USDC\n \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\", // USDT0\n \"0xBe6727B535545C67d5cAa73dEa54865B92CF7907\", // UETH\n \"0x9FDBdA0A5e284c32744D2f17Ee5c74B284993463\", // UBTC\n \"0x111111a1a0667d36bD57c0A9f569b98057111111\", // USDH\n \"0x5d3a1Ff2b6BAb83b63cd9AD0787074081a52ef34\", // USDe\n \"0x211Cc4DD073734dA055fbF44a2b4667d5E5fE5d2\", // sUSDe\n \"0xf4D9235269a96aaDaFc9aDAe454a0618eBE37949\", // XAUt0\n \"0xfD739d4e423301CE9385c1fb8850539D657C296D\", // kHYPE\n KITTEN_TOKEN, // KITTEN\n];\n\n// ─── ABIs ─────────────────────────────────────────────────────────────────────\n\nconst farmingCenterAbi = parseAbi([\n \"function multicall(bytes[] calldata data) external payable returns (bytes[] memory results)\",\n \"function enterFarming((address rewardToken, address bonusRewardToken, address pool, uint256 nonce) key, uint256 tokenId) external\",\n \"function exitFarming((address rewardToken, address bonusRewardToken, address pool, uint256 nonce) key, uint256 tokenId) external\",\n \"function collectRewards((address rewardToken, address bonusRewardToken, address pool, uint256 nonce) key, uint256 tokenId) external\",\n \"function claimReward(address rewardToken, address to, uint128 amountRequested) external returns (uint256 reward)\",\n]);\n\nconst positionManagerAbi = parseAbi([\n \"function approveForFarming(uint256 tokenId, bool approve, address farmingAddress) external\",\n \"function farmingApprovals(uint256 tokenId) external view returns (address)\",\n]);\n\nconst eternalFarmingAbi = parseAbi([\n \"function incentives(bytes32 incentiveId) external view returns (uint256 totalReward, uint256 bonusReward, address virtualPoolAddress, uint24 minimalPositionWidth, bool deactivated, address pluginAddress)\",\n \"function getRewardInfo((address rewardToken, address bonusRewardToken, address pool, uint256 nonce) key, uint256 tokenId) external view returns (uint256 reward, uint256 bonusReward)\",\n]);\n\nconst algebraFactoryAbi = parseAbi([\n \"function poolByPair(address tokenA, address tokenB) external view returns (address pool)\",\n]);\n\n// Decode helpers\nconst _addressDecodeAbi = parseAbi([\"function f() external view returns (address)\"]);\nfunction decodeAddress(data: Hex | null): Address | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _addressDecodeAbi, functionName: \"f\", data }) as Address;\n } catch {\n return null;\n }\n}\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface IncentiveKey {\n rewardToken: Address;\n bonusRewardToken: Address;\n pool: Address;\n nonce: bigint;\n}\n\nexport interface FarmingPool {\n pool: Address;\n key: IncentiveKey;\n totalReward: bigint;\n bonusReward: bigint;\n active: boolean;\n}\n\n// ─── Helper ───────────────────────────────────────────────────────────────────\n\n/** Compute the incentiveId hash for an IncentiveKey (keccak256(abi.encode(key))) */\nfunction incentiveId(key: IncentiveKey): Hex {\n return keccak256(\n encodeAbiParameters(\n [\n { name: \"rewardToken\", type: \"address\" },\n { name: \"bonusRewardToken\", type: \"address\" },\n { name: \"pool\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n ],\n [key.rewardToken, key.bonusRewardToken, key.pool, key.nonce],\n ),\n );\n}\n\n/** Build the enterFarming calldata (without selector overhead — for use inside multicall) */\nfunction encodeEnterFarming(key: IncentiveKey, tokenId: bigint): Hex {\n return encodeFunctionData({\n abi: farmingCenterAbi,\n functionName: \"enterFarming\",\n args: [key, tokenId],\n });\n}\n\n/** Build the exitFarming calldata */\nfunction encodeExitFarming(key: IncentiveKey, tokenId: bigint): Hex {\n return encodeFunctionData({\n abi: farmingCenterAbi,\n functionName: \"exitFarming\",\n args: [key, tokenId],\n });\n}\n\n/** Build the collectRewards calldata */\nfunction encodeCollectRewards(key: IncentiveKey, tokenId: bigint): Hex {\n return encodeFunctionData({\n abi: farmingCenterAbi,\n functionName: \"collectRewards\",\n args: [key, tokenId],\n });\n}\n\n/** Build the claimReward calldata */\nfunction encodeClaimReward(rewardToken: Address, to: Address): Hex {\n return encodeFunctionData({\n abi: farmingCenterAbi,\n functionName: \"claimReward\",\n args: [rewardToken, to, 2n ** 128n - 1n], // max uint128\n });\n}\n\n/** Encode the top-level multicall wrapping an array of calldatas */\nfunction encodeMulticall(calls: Hex[]): Hex {\n return encodeFunctionData({\n abi: farmingCenterAbi,\n functionName: \"multicall\",\n args: [calls],\n });\n}\n\n// ─── Runtime cache ───────────────────────────────────────────────────────────\n\n/** Runtime cache: pool (lowercased) → discovered nonce. Avoids repeated scans within a session. */\nconst nonceCache = new Map<string, bigint>();\n\n// ─── Adapter ──────────────────────────────────────────────────────────────────\n\nexport class KittenSwapFarmingAdapter {\n private readonly protocolName: string;\n private readonly farmingCenter: Address;\n private readonly eternalFarming: Address;\n private readonly positionManager: Address;\n private readonly rpcUrl: string;\n private readonly factory: Address | undefined;\n\n constructor(\n protocolName: string,\n farmingCenter: Address,\n eternalFarming: Address,\n positionManager: Address,\n rpcUrl: string,\n factory?: Address,\n ) {\n this.protocolName = protocolName;\n this.farmingCenter = farmingCenter;\n this.eternalFarming = eternalFarming;\n this.positionManager = positionManager;\n this.rpcUrl = rpcUrl;\n this.factory = factory;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n /**\n * Discover the active IncentiveKey for a given pool.\n * 1. Check runtime cache\n * 2. Batch-query nonces 0-60 via single multicall (61 calls)\n * 3. Return first non-zero incentive (totalReward > 0 and not deactivated)\n */\n async discoverIncentiveKey(pool: Address): Promise<IncentiveKey | null> {\n const poolLc = pool.toLowerCase();\n\n // Fast path: runtime cache\n if (nonceCache.has(poolLc)) {\n return {\n rewardToken: KITTEN_TOKEN,\n bonusRewardToken: WHYPE_TOKEN,\n pool,\n nonce: nonceCache.get(poolLc)!,\n };\n }\n\n // Build 61 multicall calls for nonces 0-60\n const calls: Array<[Address, Hex]> = [];\n const nonces: bigint[] = [];\n for (let n = 0; n <= MAX_NONCE_SCAN; n++) {\n const nonce = BigInt(n);\n nonces.push(nonce);\n const key: IncentiveKey = {\n rewardToken: KITTEN_TOKEN,\n bonusRewardToken: WHYPE_TOKEN,\n pool,\n nonce,\n };\n calls.push([\n this.eternalFarming,\n encodeFunctionData({\n abi: eternalFarmingAbi,\n functionName: \"incentives\",\n args: [incentiveId(key)],\n }),\n ]);\n }\n\n const results = await multicallRead(this.rpcUrl, calls);\n\n for (let i = 0; i < results.length; i++) {\n const data = results[i];\n if (!data || data.length < 66) continue;\n\n try {\n const decoded = decodeAbiParameters(\n [\n { name: \"totalReward\", type: \"uint256\" },\n { name: \"bonusReward\", type: \"uint256\" },\n { name: \"virtualPoolAddress\", type: \"address\" },\n { name: \"minimalPositionWidth\", type: \"uint24\" },\n { name: \"deactivated\", type: \"bool\" },\n { name: \"pluginAddress\", type: \"address\" },\n ],\n data,\n );\n\n const totalReward = decoded[0] as bigint;\n const deactivated = decoded[4] as boolean;\n\n if (totalReward > 0n && !deactivated) {\n const nonce = nonces[i]!;\n nonceCache.set(poolLc, nonce);\n return {\n rewardToken: KITTEN_TOKEN,\n bonusRewardToken: WHYPE_TOKEN,\n pool,\n nonce,\n };\n }\n } catch {\n // skip decode errors\n }\n }\n\n return null;\n }\n\n /**\n * Build approveForFarming tx on the PositionManager.\n * Required before enterFarming if not already approved.\n */\n async buildApproveForFarming(tokenId: bigint): Promise<DeFiTx | null> {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const currentApproval = await client.readContract({\n address: this.positionManager,\n abi: positionManagerAbi,\n functionName: \"farmingApprovals\",\n args: [tokenId],\n }) as Address;\n\n if (currentApproval.toLowerCase() === this.farmingCenter.toLowerCase()) {\n return null; // Already approved\n }\n\n return {\n description: `[${this.protocolName}] Approve NFT #${tokenId} for farming`,\n to: this.positionManager,\n data: encodeFunctionData({\n abi: positionManagerAbi,\n functionName: \"approveForFarming\",\n args: [tokenId, true, this.farmingCenter],\n }),\n value: 0n,\n gas_estimate: 60_000,\n };\n }\n\n /**\n * Build enterFarming tx for a position NFT.\n * Checks farming approval first and returns pre_txs if needed.\n */\n async buildEnterFarming(\n tokenId: bigint,\n pool: Address,\n _owner: Address,\n ): Promise<DeFiTx> {\n const key = await this.discoverIncentiveKey(pool);\n if (!key) {\n throw new DefiError(\n \"CONTRACT_ERROR\",\n `[${this.protocolName}] No active incentive found for pool ${pool}`,\n );\n }\n\n const approveTx = await this.buildApproveForFarming(tokenId);\n\n return {\n description: `[${this.protocolName}] Enter farming for NFT #${tokenId} in pool ${pool}`,\n to: this.farmingCenter,\n data: encodeEnterFarming(key, tokenId),\n value: 0n,\n gas_estimate: 400_000,\n pre_txs: approveTx ? [approveTx] : undefined,\n };\n }\n\n /**\n * Build a tx that exits farming for a position NFT (unstakes).\n */\n async buildExitFarming(tokenId: bigint, pool: Address): Promise<DeFiTx> {\n const key = await this.discoverIncentiveKey(pool);\n if (!key) {\n throw new DefiError(\n \"CONTRACT_ERROR\",\n `[${this.protocolName}] No active incentive found for pool ${pool}`,\n );\n }\n\n return {\n description: `[${this.protocolName}] Exit farming for NFT #${tokenId} in pool ${pool}`,\n to: this.farmingCenter,\n data: encodeExitFarming(key, tokenId),\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n /**\n * Build a multicall tx that collects rewards for a staked position and claims them.\n * Pattern: multicall([collectRewards(key, tokenId), claimReward(KITTEN, owner, max), claimReward(WHYPE, owner, max)])\n */\n async buildCollectRewards(\n tokenId: bigint,\n pool: Address,\n owner: Address,\n ): Promise<DeFiTx> {\n const key = await this.discoverIncentiveKey(pool);\n if (!key) {\n throw new DefiError(\n \"CONTRACT_ERROR\",\n `[${this.protocolName}] No active incentive found for pool ${pool}`,\n );\n }\n\n const calls: Hex[] = [\n encodeCollectRewards(key, tokenId),\n encodeClaimReward(KITTEN_TOKEN, owner),\n encodeClaimReward(WHYPE_TOKEN, owner),\n ];\n\n return {\n description: `[${this.protocolName}] Collect + claim rewards for NFT #${tokenId} in pool ${pool}`,\n to: this.farmingCenter,\n data: encodeMulticall(calls),\n value: 0n,\n gas_estimate: 400_000,\n };\n }\n\n /**\n * Build a tx that only claims already-accumulated rewards (no position change needed).\n */\n async buildClaimReward(owner: Address): Promise<DeFiTx> {\n const calls: Hex[] = [\n encodeClaimReward(KITTEN_TOKEN, owner),\n encodeClaimReward(WHYPE_TOKEN, owner),\n ];\n\n return {\n description: `[${this.protocolName}] Claim KITTEN + WHYPE farming rewards to ${owner}`,\n to: this.farmingCenter,\n data: encodeMulticall(calls),\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /**\n * Query pending rewards for a staked position NFT.\n */\n async getPendingRewards(\n tokenId: bigint,\n pool: Address,\n ): Promise<{ reward: bigint; bonusReward: bigint }> {\n const key = await this.discoverIncentiveKey(pool);\n if (!key) {\n return { reward: 0n, bonusReward: 0n };\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const result = await client.readContract({\n address: this.eternalFarming,\n abi: eternalFarmingAbi,\n functionName: \"getRewardInfo\",\n args: [key, tokenId],\n }) as readonly [bigint, bigint];\n\n return { reward: result[0], bonusReward: result[1] };\n }\n\n /**\n * Discover all KittenSwap pools with active farming incentives.\n *\n * Steps:\n * 1. Generate all unique token pair combos from HYPEREVM_TOKENS (includes KITTEN)\n * 2. Batch poolByPair calls via multicall against the Algebra factory\n * 3. For each found pool, batch-scan nonces 0-60 via multicall\n * 4. Return enriched FarmingPool[] for pools with active incentives\n */\n async discoverFarmingPools(): Promise<FarmingPool[]> {\n if (!this.factory) {\n return [];\n }\n\n // Step 1: generate all unique token pairs\n const pairs: Array<[Address, Address]> = [];\n for (let i = 0; i < HYPEREVM_TOKENS.length; i++) {\n for (let j = i + 1; j < HYPEREVM_TOKENS.length; j++) {\n pairs.push([HYPEREVM_TOKENS[i]!, HYPEREVM_TOKENS[j]!]);\n }\n }\n\n // Step 2: batch poolByPair calls\n const poolByPairCalls: Array<[Address, Hex]> = pairs.map(([tokenA, tokenB]) => [\n this.factory!,\n encodeFunctionData({\n abi: algebraFactoryAbi,\n functionName: \"poolByPair\",\n args: [tokenA, tokenB],\n }),\n ]);\n\n const poolResults = await multicallRead(this.rpcUrl, poolByPairCalls);\n\n // Collect unique non-zero pool addresses\n const poolSet = new Set<string>();\n for (const data of poolResults) {\n const addr = decodeAddress(data);\n if (addr && addr !== zeroAddress) {\n poolSet.add(addr.toLowerCase());\n }\n }\n\n if (poolSet.size === 0) return [];\n\n const pools = Array.from(poolSet) as Address[];\n\n // Step 3: for each pool, batch-scan nonces 0-60 via a single multicall per pool.\n // We build all nonce calls for all pools in one big multicall to minimize RPC round-trips.\n const NONCE_COUNT = MAX_NONCE_SCAN + 1; // 61\n const allNonceCalls: Array<[Address, Hex]> = [];\n for (const pool of pools) {\n for (let n = 0; n <= MAX_NONCE_SCAN; n++) {\n const key: IncentiveKey = {\n rewardToken: KITTEN_TOKEN,\n bonusRewardToken: WHYPE_TOKEN,\n pool: pool as Address,\n nonce: BigInt(n),\n };\n allNonceCalls.push([\n this.eternalFarming,\n encodeFunctionData({\n abi: eternalFarmingAbi,\n functionName: \"incentives\",\n args: [incentiveId(key)],\n }),\n ]);\n }\n }\n\n const allNonceResults = await multicallRead(this.rpcUrl, allNonceCalls);\n\n // Step 4: find best active incentive per pool and build result\n const results: FarmingPool[] = [];\n\n for (let pi = 0; pi < pools.length; pi++) {\n const pool = pools[pi]! as Address;\n const poolLc = pool.toLowerCase();\n const base = pi * NONCE_COUNT;\n\n let bestKey: IncentiveKey | null = null;\n let bestTotalReward = 0n;\n let bestBonusReward = 0n;\n let bestActive = false;\n\n for (let n = 0; n <= MAX_NONCE_SCAN; n++) {\n const data = allNonceResults[base + n];\n if (!data || data.length < 66) continue;\n\n try {\n const decoded = decodeAbiParameters(\n [\n { name: \"totalReward\", type: \"uint256\" },\n { name: \"bonusReward\", type: \"uint256\" },\n { name: \"virtualPoolAddress\", type: \"address\" },\n { name: \"minimalPositionWidth\", type: \"uint24\" },\n { name: \"deactivated\", type: \"bool\" },\n { name: \"pluginAddress\", type: \"address\" },\n ],\n data,\n );\n\n const totalReward = decoded[0] as bigint;\n const bonusReward = decoded[1] as bigint;\n const deactivated = decoded[4] as boolean;\n\n if (totalReward > 0n) {\n const nonce = BigInt(n);\n const isActive = !deactivated;\n\n // Prefer active incentives; among active ones, prefer higher nonce (newer)\n if (!bestKey || (isActive && !bestActive) || (isActive === bestActive && nonce > bestKey.nonce)) {\n bestKey = {\n rewardToken: KITTEN_TOKEN,\n bonusRewardToken: WHYPE_TOKEN,\n pool,\n nonce,\n };\n bestTotalReward = totalReward;\n bestBonusReward = bonusReward;\n bestActive = isActive;\n }\n }\n } catch {\n // skip decode errors\n }\n }\n\n if (bestKey) {\n // Cache the discovered nonce\n nonceCache.set(poolLc, bestKey.nonce);\n results.push({\n pool,\n key: bestKey,\n totalReward: bestTotalReward,\n bonusReward: bestBonusReward,\n active: bestActive,\n });\n }\n }\n\n return results;\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, decodeFunctionResult, zeroAddress } from \"viem\";\nimport type { Address, Hex } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n multicallRead,\n decodeU256,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n InterestRateMode,\n} from \"@hypurrquant/defi-core\";\n\nconst POOL_ABI = parseAbi([\n \"function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external\",\n \"function borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf) external\",\n \"function repay(address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf) external returns (uint256)\",\n \"function withdraw(address asset, uint256 amount, address to) external returns (uint256)\",\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n \"function getReserveData(address asset) external view returns (uint256 configuration, uint128 liquidityIndex, uint128 currentLiquidityRate, uint128 variableBorrowIndex, uint128 currentVariableBorrowRate, uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, uint16 id, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress, uint128 accruedToTreasury, uint128 unbacked, uint128 isolationModeTotalDebt)\",\n]);\n\nconst ERC20_ABI = parseAbi([\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nconst INCENTIVES_ABI = parseAbi([\n \"function getIncentivesController() external view returns (address)\",\n]);\n\nconst REWARDS_CONTROLLER_ABI = parseAbi([\n \"function getRewardsByAsset(address asset) external view returns (address[])\",\n \"function getRewardsData(address asset, address reward) external view returns (uint256 index, uint256 emissionsPerSecond, uint256 lastUpdateTimestamp, uint256 distributionEnd)\",\n]);\n\nconst POOL_PROVIDER_ABI = parseAbi([\n \"function ADDRESSES_PROVIDER() external view returns (address)\",\n]);\n\nconst ADDRESSES_PROVIDER_ABI = parseAbi([\n \"function getPriceOracle() external view returns (address)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n \"function BASE_CURRENCY_UNIT() external view returns (uint256)\",\n]);\n\nconst ERC20_DECIMALS_ABI = parseAbi([\n \"function decimals() external view returns (uint8)\",\n]);\n\nfunction u256ToF64(v: bigint): number {\n const MAX_U128 = (1n << 128n) - 1n;\n if (v > MAX_U128) return Infinity;\n return Number(v);\n}\n\nfunction decodeAddress(data: Hex | null): Address | null {\n if (!data || data.length < 66) return null;\n // ABI-encoded address: 12 bytes padding + 20 bytes address (total 32 bytes = 64 hex chars + 0x)\n return `0x${data.slice(26, 66)}` as Address;\n}\n\nfunction decodeAddressArray(data: Hex | null): Address[] {\n if (!data) return [];\n try {\n return decodeFunctionResult({\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsByAsset\",\n data,\n }) as Address[];\n } catch {\n return [];\n }\n}\n\nfunction decodeReserveData(data: Hex | null): ReturnType<typeof decodeFunctionResult> | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({\n abi: POOL_ABI,\n functionName: \"getReserveData\",\n data,\n });\n } catch {\n return null;\n }\n}\n\nfunction decodeRewardsData(data: Hex | null): [bigint, bigint, bigint, bigint] | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsData\",\n data,\n }) as [bigint, bigint, bigint, bigint];\n } catch {\n return null;\n }\n}\n\nexport class AaveV3Adapter implements ILending {\n private readonly protocolName: string;\n private readonly pool: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const pool = entry.contracts?.[\"pool\"];\n if (!pool) throw DefiError.contractError(`[${entry.name}] Missing 'pool' contract address`);\n this.pool = pool;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"supply\",\n args: [params.asset, params.amount, params.on_behalf_of, 0],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [{ token: params.asset, spender: this.pool, amount: params.amount }],\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"borrow\",\n args: [params.asset, params.amount, rateMode, 0, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"repay\",\n args: [params.asset, params.amount, rateMode, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [{ token: params.asset, spender: this.pool, amount: params.amount }],\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n\n // Batch 1: getReserveData\n const reserveCallData = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"getReserveData\",\n args: [asset],\n });\n const [reserveRaw] = await multicallRead(this.rpcUrl, [\n [this.pool, reserveCallData],\n ]).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getReserveData failed: ${e}`);\n });\n\n const reserveDecoded = decodeReserveData(reserveRaw ?? null);\n if (!reserveDecoded) {\n throw DefiError.rpcError(`[${this.protocolName}] getReserveData returned no data`);\n }\n const result = reserveDecoded as [bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint, Address, Address, Address, Address, bigint, bigint, bigint];\n\n const RAY = 1e27;\n const SECONDS_PER_YEAR = 31536000;\n\n // Convert ray rate to APY: ((1 + rate/SECONDS_PER_YEAR)^SECONDS_PER_YEAR - 1) * 100\n const toApy = (rayRate: bigint): number => {\n const rate = Number(rayRate) / RAY;\n return (Math.pow(1 + rate / SECONDS_PER_YEAR, SECONDS_PER_YEAR) - 1) * 100;\n };\n\n const supplyRate = toApy(result[2]);\n const variableRate = toApy(result[4]);\n const stableRate = toApy(result[5]);\n\n const aTokenAddress = result[8] as Address;\n const variableDebtTokenAddress = result[10] as Address;\n\n // Batch 2: totalSupply for aToken + variableDebtToken\n const [supplyRaw, borrowRaw] = await multicallRead(this.rpcUrl, [\n [aTokenAddress, encodeFunctionData({ abi: ERC20_ABI, functionName: \"totalSupply\" })],\n [variableDebtTokenAddress, encodeFunctionData({ abi: ERC20_ABI, functionName: \"totalSupply\" })],\n ]);\n const totalSupply = decodeU256(supplyRaw ?? null);\n const totalBorrow = decodeU256(borrowRaw ?? null);\n\n const utilization = totalSupply > 0n\n ? Number((totalBorrow * 10000n) / totalSupply) / 100\n : 0;\n\n // Fetch incentive/reward data (best-effort, never breaks base rates)\n const supplyRewardTokens: string[] = [];\n const borrowRewardTokens: string[] = [];\n const supplyEmissions: string[] = [];\n const borrowEmissions: string[] = [];\n\n try {\n // Batch 3: getIncentivesController (single call)\n const [controllerRaw] = await multicallRead(this.rpcUrl, [\n [aTokenAddress, encodeFunctionData({ abi: INCENTIVES_ABI, functionName: \"getIncentivesController\" })],\n ]);\n const controllerAddr = decodeAddress(controllerRaw ?? null);\n\n if (controllerAddr && controllerAddr !== zeroAddress) {\n // Batch 4: getRewardsByAsset for aToken + variableDebtToken\n const [supplyRewardsRaw, borrowRewardsRaw] = await multicallRead(this.rpcUrl, [\n [controllerAddr, encodeFunctionData({ abi: REWARDS_CONTROLLER_ABI, functionName: \"getRewardsByAsset\", args: [aTokenAddress] })],\n [controllerAddr, encodeFunctionData({ abi: REWARDS_CONTROLLER_ABI, functionName: \"getRewardsByAsset\", args: [variableDebtTokenAddress] })],\n ]);\n const supplyRewards = decodeAddressArray(supplyRewardsRaw ?? null);\n const borrowRewards = decodeAddressArray(borrowRewardsRaw ?? null);\n\n // Batch 5: all getRewardsData calls for supply + borrow combined\n const rewardsDataCalls: Array<[Address, Hex]> = [\n ...supplyRewards.map((reward): [Address, Hex] => [\n controllerAddr,\n encodeFunctionData({ abi: REWARDS_CONTROLLER_ABI, functionName: \"getRewardsData\", args: [aTokenAddress, reward] }),\n ]),\n ...borrowRewards.map((reward): [Address, Hex] => [\n controllerAddr,\n encodeFunctionData({ abi: REWARDS_CONTROLLER_ABI, functionName: \"getRewardsData\", args: [variableDebtTokenAddress, reward] }),\n ]),\n ];\n\n if (rewardsDataCalls.length > 0) {\n const rewardsDataResults = await multicallRead(this.rpcUrl, rewardsDataCalls);\n\n const supplyDataResults = rewardsDataResults.slice(0, supplyRewards.length);\n const borrowDataResults = rewardsDataResults.slice(supplyRewards.length);\n\n for (let i = 0; i < supplyRewards.length; i++) {\n const data = decodeRewardsData(supplyDataResults[i] ?? null);\n if (data && data[1] > 0n) {\n supplyRewardTokens.push(supplyRewards[i]);\n supplyEmissions.push(data[1].toString());\n }\n }\n for (let i = 0; i < borrowRewards.length; i++) {\n const data = decodeRewardsData(borrowDataResults[i] ?? null);\n if (data && data[1] > 0n) {\n borrowRewardTokens.push(borrowRewards[i]);\n borrowEmissions.push(data[1].toString());\n }\n }\n }\n }\n } catch {\n // Incentives not supported by this deployment — silently ignore\n }\n\n // Calculate incentive APY from emissions using oracle prices\n let supplyIncentiveApy: number | undefined;\n let borrowIncentiveApy: number | undefined;\n\n const hasSupplyRewards = supplyRewardTokens.length > 0;\n const hasBorrowRewards = borrowRewardTokens.length > 0;\n\n if ((hasSupplyRewards || hasBorrowRewards) && totalSupply > 0n) {\n try {\n // Pool → AddressesProvider → Oracle (sequential, each depends on previous)\n const [providerRaw] = await multicallRead(this.rpcUrl, [\n [this.pool, encodeFunctionData({ abi: POOL_PROVIDER_ABI, functionName: \"ADDRESSES_PROVIDER\" })],\n ]);\n const providerAddr = decodeAddress(providerRaw ?? null);\n if (!providerAddr) throw new Error(\"No provider address\");\n\n const [oracleRaw] = await multicallRead(this.rpcUrl, [\n [providerAddr, encodeFunctionData({ abi: ADDRESSES_PROVIDER_ABI, functionName: \"getPriceOracle\" })],\n ]);\n const oracleAddr = decodeAddress(oracleRaw ?? null);\n if (!oracleAddr) throw new Error(\"No oracle address\");\n\n // Batch 6: assetPrice + BASE_CURRENCY_UNIT + asset decimals\n const [assetPriceRaw, baseCurrencyUnitRaw, assetDecimalsRaw] = await multicallRead(this.rpcUrl, [\n [oracleAddr, encodeFunctionData({ abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [asset] })],\n [oracleAddr, encodeFunctionData({ abi: ORACLE_ABI, functionName: \"BASE_CURRENCY_UNIT\" })],\n [asset, encodeFunctionData({ abi: ERC20_DECIMALS_ABI, functionName: \"decimals\" })],\n ]);\n\n const assetPrice = decodeU256(assetPriceRaw ?? null);\n const baseCurrencyUnit = decodeU256(baseCurrencyUnitRaw ?? null);\n // decimals() returns uint8, fits in lower bits of U256 slot\n const assetDecimals = assetDecimalsRaw ? Number(decodeU256(assetDecimalsRaw)) : 18;\n\n const priceUnit = Number(baseCurrencyUnit) || 1e8;\n const assetPriceF = Number(assetPrice) / priceUnit;\n const assetDecimalsDivisor = 10 ** assetDecimals;\n\n // Collect all unique reward tokens across supply + borrow\n const allRewardTokens = Array.from(new Set([...supplyRewardTokens, ...borrowRewardTokens])) as Address[];\n\n // Batch 7: price + decimals for all reward tokens combined\n const rewardPriceCalls: Array<[Address, Hex]> = allRewardTokens.flatMap((token): Array<[Address, Hex]> => [\n [oracleAddr, encodeFunctionData({ abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [token] })],\n [token, encodeFunctionData({ abi: ERC20_DECIMALS_ABI, functionName: \"decimals\" })],\n ]);\n\n const rewardPriceResults = rewardPriceCalls.length > 0\n ? await multicallRead(this.rpcUrl, rewardPriceCalls)\n : [];\n\n const rewardPriceMap = new Map<string, { price: bigint; decimals: number }>();\n for (let i = 0; i < allRewardTokens.length; i++) {\n const priceRaw = rewardPriceResults[i * 2] ?? null;\n const decimalsRaw = rewardPriceResults[i * 2 + 1] ?? null;\n const price = decodeU256(priceRaw);\n const decimals = decimalsRaw ? Number(decodeU256(decimalsRaw)) : 18;\n rewardPriceMap.set(allRewardTokens[i].toLowerCase(), { price, decimals });\n }\n\n // Supply-side incentive APY\n if (hasSupplyRewards) {\n let totalSupplyIncentiveUsdPerYear = 0;\n const totalSupplyUsd = (Number(totalSupply) / assetDecimalsDivisor) * assetPriceF;\n\n for (let i = 0; i < supplyRewardTokens.length; i++) {\n const emissionPerSec = BigInt(supplyEmissions[i]);\n const entry = rewardPriceMap.get(supplyRewardTokens[i].toLowerCase());\n const rewardPrice = entry?.price ?? 0n;\n const rewardDecimals = entry?.decimals ?? 18;\n if (rewardPrice > 0n) {\n const rewardPriceF = Number(rewardPrice) / priceUnit;\n const emissionPerYear = (Number(emissionPerSec) / (10 ** rewardDecimals)) * SECONDS_PER_YEAR;\n totalSupplyIncentiveUsdPerYear += emissionPerYear * rewardPriceF;\n }\n }\n if (totalSupplyUsd > 0) {\n supplyIncentiveApy = (totalSupplyIncentiveUsdPerYear / totalSupplyUsd) * 100;\n }\n }\n\n // Borrow-side incentive APY\n if (hasBorrowRewards && totalBorrow > 0n) {\n let totalBorrowIncentiveUsdPerYear = 0;\n const totalBorrowUsd = (Number(totalBorrow) / assetDecimalsDivisor) * assetPriceF;\n\n for (let i = 0; i < borrowRewardTokens.length; i++) {\n const emissionPerSec = BigInt(borrowEmissions[i]);\n const entry = rewardPriceMap.get(borrowRewardTokens[i].toLowerCase());\n const rewardPrice = entry?.price ?? 0n;\n const rewardDecimals = entry?.decimals ?? 18;\n if (rewardPrice > 0n) {\n const rewardPriceF = Number(rewardPrice) / priceUnit;\n const emissionPerYear = (Number(emissionPerSec) / (10 ** rewardDecimals)) * SECONDS_PER_YEAR;\n totalBorrowIncentiveUsdPerYear += emissionPerYear * rewardPriceF;\n }\n }\n if (totalBorrowUsd > 0) {\n borrowIncentiveApy = (totalBorrowIncentiveUsdPerYear / totalBorrowUsd) * 100;\n }\n }\n } catch {\n // Oracle not available — skip incentive APY calculation\n }\n }\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyRate,\n borrow_variable_apy: variableRate,\n borrow_stable_apy: stableRate,\n utilization,\n total_supply: totalSupply,\n total_borrow: totalBorrow,\n ...(hasSupplyRewards && {\n supply_reward_tokens: supplyRewardTokens,\n supply_emissions_per_second: supplyEmissions,\n }),\n ...(hasBorrowRewards && {\n borrow_reward_tokens: borrowRewardTokens,\n borrow_emissions_per_second: borrowEmissions,\n }),\n ...(supplyIncentiveApy !== undefined && { supply_incentive_apy: supplyIncentiveApy }),\n ...(borrowIncentiveApy !== undefined && { borrow_incentive_apy: borrowIncentiveApy }),\n };\n }\n\n async getUserPosition(user: Address): Promise<UserPosition> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getUserAccountData\",\n args: [user],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getUserAccountData failed: ${e}`);\n });\n\n const [totalCollateralBase, totalDebtBase, , , ltv, healthFactor] = result;\n const MAX_UINT256 = 2n ** 256n - 1n;\n const hf = healthFactor >= MAX_UINT256 ? Infinity : Number(healthFactor) / 1e18;\n const collateralUsd = u256ToF64(totalCollateralBase) / 1e8;\n const debtUsd = u256ToF64(totalDebtBase) / 1e8;\n const ltvBps = u256ToF64(ltv);\n\n const supplies = collateralUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Collateral\", amount: totalCollateralBase, value_usd: collateralUsd }]\n : [];\n const borrows = debtUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Debt\", amount: totalDebtBase, value_usd: debtUsd }]\n : [];\n\n return {\n protocol: this.protocolName,\n user,\n supplies,\n borrows,\n health_factor: hf,\n net_apy: ltvBps / 100,\n };\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n InterestRateMode,\n} from \"@hypurrquant/defi-core\";\n\n// V2 uses deposit/borrow/repay/withdraw (same as V3 for borrow/repay/withdraw)\nconst POOL_ABI = parseAbi([\n \"function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external\",\n \"function borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf) external\",\n \"function repay(address asset, uint256 amount, uint256 rateMode, address onBehalfOf) external returns (uint256)\",\n \"function withdraw(address asset, uint256 amount, address to) external returns (uint256)\",\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n // V2 getReserveData: 12 fields (no accruedToTreasury/unbacked/isolationModeTotalDebt)\n // positions: [0]=configuration, [1]=liquidityIndex, [2]=variableBorrowIndex,\n // [3]=currentLiquidityRate, [4]=currentVariableBorrowRate, [5]=currentStableBorrowRate,\n // [6]=lastUpdateTimestamp, [7]=aTokenAddress, [8]=stableDebtTokenAddress,\n // [9]=variableDebtTokenAddress, [10]=interestRateStrategyAddress, [11]=id\n \"function getReserveData(address asset) external view returns (uint256 configuration, uint128 liquidityIndex, uint128 variableBorrowIndex, uint128 currentLiquidityRate, uint128 currentVariableBorrowRate, uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress, uint8 id)\",\n]);\n\nconst ERC20_ABI = parseAbi([\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nfunction u256ToF64(v: bigint): number {\n const MAX_U128 = (1n << 128n) - 1n;\n if (v > MAX_U128) return Infinity;\n return Number(v);\n}\n\nexport class AaveV2Adapter implements ILending {\n private readonly protocolName: string;\n private readonly pool: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const pool = entry.contracts?.[\"pool\"];\n if (!pool) throw DefiError.contractError(`[${entry.name}] Missing 'pool' contract address`);\n this.pool = pool;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"deposit\",\n args: [params.asset, params.amount, params.on_behalf_of, 0],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [{ token: params.asset, spender: this.pool, amount: params.amount }],\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"borrow\",\n args: [params.asset, params.amount, rateMode, 0, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"repay\",\n args: [params.asset, params.amount, rateMode, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [{ token: params.asset, spender: this.pool, amount: params.amount }],\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getReserveData\",\n args: [asset],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getReserveData failed: ${e}`);\n });\n\n const RAY = 1e27;\n const SECONDS_PER_YEAR = 31536000;\n\n // Convert ray rate to APY: ((1 + rate/SECONDS_PER_YEAR)^SECONDS_PER_YEAR - 1) * 100\n const toApy = (rayRate: bigint): number => {\n const rate = Number(rayRate) / RAY;\n return (Math.pow(1 + rate / SECONDS_PER_YEAR, SECONDS_PER_YEAR) - 1) * 100;\n };\n\n // V2 field positions:\n // [3] = currentLiquidityRate, [4] = currentVariableBorrowRate, [5] = currentStableBorrowRate\n // [7] = aTokenAddress, [9] = variableDebtTokenAddress\n const supplyRate = toApy(result[3]);\n const variableRate = toApy(result[4]);\n const stableRate = toApy(result[5]);\n\n const aTokenAddress = result[7] as Address;\n const variableDebtTokenAddress = result[9] as Address;\n\n const [totalSupply, totalBorrow] = await Promise.all([\n client.readContract({\n address: aTokenAddress,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch(() => 0n),\n client.readContract({\n address: variableDebtTokenAddress,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch(() => 0n),\n ]);\n\n const utilization = totalSupply > 0n\n ? Number((totalBorrow * 10000n) / totalSupply) / 100\n : 0;\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyRate,\n borrow_variable_apy: variableRate,\n borrow_stable_apy: stableRate,\n utilization,\n total_supply: totalSupply,\n total_borrow: totalBorrow,\n };\n }\n\n async getUserPosition(user: Address): Promise<UserPosition> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getUserAccountData\",\n args: [user],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getUserAccountData failed: ${e}`);\n });\n\n const [totalCollateralBase, totalDebtBase, , , ltv, healthFactor] = result;\n const MAX_UINT256 = 2n ** 256n - 1n;\n const hf = healthFactor >= MAX_UINT256 ? Infinity : Number(healthFactor) / 1e18;\n // V2 returns values in ETH (18 decimals) vs V3's base currency (8 decimals)\n const collateralUsd = u256ToF64(totalCollateralBase) / 1e18;\n const debtUsd = u256ToF64(totalDebtBase) / 1e18;\n const ltvBps = u256ToF64(ltv);\n\n const supplies = collateralUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Collateral\", amount: totalCollateralBase, value_usd: collateralUsd }]\n : [];\n const borrows = debtUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Debt\", amount: totalDebtBase, value_usd: debtUsd }]\n : [];\n\n return {\n protocol: this.protocolName,\n user,\n supplies,\n borrows,\n health_factor: hf,\n net_apy: ltvBps / 100,\n };\n }\n}\n","import { createPublicClient, http, parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IOracle } from \"@hypurrquant/defi-core\";\nimport { DefiError, type ProtocolEntry, type PriceData } from \"@hypurrquant/defi-core\";\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n \"function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory)\",\n \"function BASE_CURRENCY_UNIT() external view returns (uint256)\",\n]);\n\nexport class AaveOracleAdapter implements IOracle {\n private readonly protocolName: string;\n private readonly oracle: Address;\n private readonly rpcUrl: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n if (!rpcUrl) throw DefiError.rpcError(`[${entry.name}] RPC URL required for oracle`);\n this.rpcUrl = rpcUrl;\n const oracle = entry.contracts?.[\"oracle\"];\n if (!oracle) throw DefiError.contractError(`[${entry.name}] Missing 'oracle' contract address`);\n this.oracle = oracle;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getPrice(asset: Address): Promise<PriceData> {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const baseUnit = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"BASE_CURRENCY_UNIT\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] BASE_CURRENCY_UNIT failed: ${e}`);\n });\n\n const priceVal = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [asset],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getAssetPrice failed: ${e}`);\n });\n\n const priceF64 = baseUnit > 0n ? Number(priceVal) / Number(baseUnit) : 0;\n const priceUsd = baseUnit > 0n\n ? (priceVal * (10n ** 18n)) / baseUnit\n : 0n;\n\n return {\n source: `${this.protocolName} Oracle`,\n source_type: \"oracle\",\n asset,\n price_usd: priceUsd,\n price_f64: priceF64,\n };\n }\n\n async getPrices(assets: Address[]): Promise<PriceData[]> {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const baseUnit = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"BASE_CURRENCY_UNIT\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] BASE_CURRENCY_UNIT failed: ${e}`);\n });\n\n const rawPrices = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"getAssetsPrices\",\n args: [assets],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getAssetsPrices failed: ${e}`);\n });\n\n return (rawPrices as bigint[]).map((priceVal, i) => {\n const priceF64 = baseUnit > 0n ? Number(priceVal) / Number(baseUnit) : 0;\n const priceUsd = baseUnit > 0n ? (priceVal * (10n ** 18n)) / baseUnit : 0n;\n return {\n source: `${this.protocolName} Oracle`,\n source_type: \"oracle\",\n asset: assets[i]!,\n price_usd: priceUsd,\n price_f64: priceF64,\n };\n });\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst CTOKEN_ABI = parseAbi([\n \"function supplyRatePerBlock() external view returns (uint256)\",\n \"function borrowRatePerBlock() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function totalBorrows() external view returns (uint256)\",\n \"function mint(uint256 mintAmount) external returns (uint256)\",\n \"function redeem(uint256 redeemTokens) external returns (uint256)\",\n \"function borrow(uint256 borrowAmount) external returns (uint256)\",\n \"function repayBorrow(uint256 repayAmount) external returns (uint256)\",\n]);\n\n// ~3s blocks on BSC\nconst BSC_BLOCKS_PER_YEAR = 10_512_000;\n\nexport class CompoundV2Adapter implements ILending {\n private readonly protocolName: string;\n private readonly defaultVtoken: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const vtoken =\n contracts[\"vusdt\"] ??\n contracts[\"vusdc\"] ??\n contracts[\"vbnb\"] ??\n contracts[\"comptroller\"];\n if (!vtoken) throw DefiError.contractError(\"Missing vToken or comptroller address\");\n this.defaultVtoken = vtoken;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"mint\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"borrow\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"repayBorrow\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"redeem\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw from Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [supplyRate, borrowRate, totalSupply, totalBorrows] = await Promise.all([\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"supplyRatePerBlock\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyRatePerBlock failed: ${e}`); }),\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"borrowRatePerBlock\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] borrowRatePerBlock failed: ${e}`); }),\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"totalSupply\" }).catch(() => 0n),\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"totalBorrows\" }).catch(() => 0n),\n ]);\n\n const supplyPerBlock = Number(supplyRate) / 1e18;\n const borrowPerBlock = Number(borrowRate) / 1e18;\n const supplyApy = supplyPerBlock * BSC_BLOCKS_PER_YEAR * 100;\n const borrowApy = borrowPerBlock * BSC_BLOCKS_PER_YEAR * 100;\n\n const supplyF = Number(totalSupply);\n const borrowF = Number(totalBorrows);\n const utilization = supplyF > 0 ? (borrowF / supplyF) * 100 : 0;\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization,\n total_supply: totalSupply as bigint,\n total_borrow: totalBorrows as bigint,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] User position requires querying individual vToken balances`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst COMET_ABI = parseAbi([\n \"function getUtilization() external view returns (uint256)\",\n \"function getSupplyRate(uint256 utilization) external view returns (uint64)\",\n \"function getBorrowRate(uint256 utilization) external view returns (uint64)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function totalBorrow() external view returns (uint256)\",\n \"function supply(address asset, uint256 amount) external\",\n \"function withdraw(address asset, uint256 amount) external\",\n]);\n\nconst SECONDS_PER_YEAR = 365.25 * 24 * 3600;\n\nexport class CompoundV3Adapter implements ILending {\n private readonly protocolName: string;\n private readonly comet: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const comet = contracts[\"comet_usdc\"] ?? contracts[\"comet\"] ?? contracts[\"comet_weth\"];\n if (!comet) throw DefiError.contractError(\"Missing 'comet_usdc' or 'comet' address\");\n this.comet = comet;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"supply\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n // In Compound V3, borrow = withdraw base asset\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n // In Compound V3, repay = supply base asset\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"supply\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw from Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const utilization = await client.readContract({\n address: this.comet,\n abi: COMET_ABI,\n functionName: \"getUtilization\",\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] getUtilization failed: ${e}`); });\n\n const [supplyRate, borrowRate, totalSupply, totalBorrow] = await Promise.all([\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"getSupplyRate\", args: [utilization as bigint] }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] getSupplyRate failed: ${e}`); }),\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"getBorrowRate\", args: [utilization as bigint] }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] getBorrowRate failed: ${e}`); }),\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"totalSupply\" }).catch(() => 0n),\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"totalBorrow\" }).catch(() => 0n),\n ]);\n\n // Comet rates are per-second scaled by 1e18\n const supplyPerSec = Number(supplyRate) / 1e18;\n const borrowPerSec = Number(borrowRate) / 1e18;\n const supplyApy = supplyPerSec * SECONDS_PER_YEAR * 100;\n const borrowApy = borrowPerSec * SECONDS_PER_YEAR * 100;\n const utilPct = Number(utilization as bigint) / 1e18 * 100;\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization: utilPct,\n total_supply: totalSupply as bigint,\n total_borrow: totalBorrow as bigint,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] User position requires querying Comet balanceOf + borrowBalanceOf`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst EULER_VAULT_ABI = parseAbi([\n \"function deposit(uint256 amount, address receiver) external returns (uint256)\",\n \"function withdraw(uint256 amount, address receiver, address owner) external returns (uint256)\",\n \"function borrow(uint256 amount, address receiver) external returns (uint256)\",\n \"function repay(uint256 amount, address receiver) external returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function totalBorrows() external view returns (uint256)\",\n \"function interestRate() external view returns (uint256)\",\n]);\n\nconst SECONDS_PER_YEAR = 365.25 * 24 * 3600;\n\nexport class EulerV2Adapter implements ILending {\n private readonly protocolName: string;\n private readonly euler: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const euler = contracts[\"evk_vault\"] ?? contracts[\"euler\"] ?? contracts[\"markets\"];\n if (!euler) throw DefiError.contractError(\"Missing 'evk_vault' or 'euler' contract address\");\n this.euler = euler;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"deposit\",\n args: [params.amount, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Deposit ${params.amount} into Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"borrow\",\n args: [params.amount, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"repay\",\n args: [params.amount, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"withdraw\",\n args: [params.amount, params.to, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [totalSupply, totalBorrows, interestRate] = await Promise.all([\n client.readContract({ address: this.euler, abi: EULER_VAULT_ABI, functionName: \"totalSupply\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalSupply failed: ${e}`); }),\n client.readContract({ address: this.euler, abi: EULER_VAULT_ABI, functionName: \"totalBorrows\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalBorrows failed: ${e}`); }),\n client.readContract({ address: this.euler, abi: EULER_VAULT_ABI, functionName: \"interestRate\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] interestRate failed: ${e}`); }),\n ]);\n\n // Euler V2 interest rates per-second scaled by 1e27\n const rateF64 = Number(interestRate) / 1e27;\n const borrowApy = rateF64 * SECONDS_PER_YEAR * 100;\n\n const supplyF = Number(totalSupply);\n const borrowF = Number(totalBorrows);\n const utilization = supplyF > 0 ? (borrowF / supplyF) * 100 : 0;\n const supplyApy = borrowApy * (borrowF / Math.max(supplyF, 1));\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization,\n total_supply: totalSupply as bigint,\n total_borrow: totalBorrows as bigint,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Euler V2 user positions require querying individual vault balances. Use the vault address directly to check balanceOf(user) for supply positions.`,\n );\n }\n}\n","import { parseAbi, encodeFunctionData, decodeFunctionResult, zeroAddress } from \"viem\";\nimport type { Address, Hex } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n multicallRead,\n decodeU256,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst MORPHO_ABI = parseAbi([\n \"function market(bytes32 id) external view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)\",\n \"function idToMarketParams(bytes32 id) external view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)\",\n \"function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) external returns (uint256 assetsSupplied, uint256 sharesSupplied)\",\n \"function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed)\",\n \"function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) external returns (uint256 assetsRepaid, uint256 sharesRepaid)\",\n \"function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)\",\n]);\n\nconst META_MORPHO_ABI = parseAbi([\n \"function supplyQueueLength() external view returns (uint256)\",\n \"function supplyQueue(uint256 index) external view returns (bytes32)\",\n \"function totalAssets() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nconst IRM_ABI = parseAbi([\n \"function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) external view returns (uint256)\",\n]);\n\nconst SECONDS_PER_YEAR = 365.25 * 24 * 3600;\n\ntype MarketParams = {\n loanToken: Address;\n collateralToken: Address;\n oracle: Address;\n irm: Address;\n lltv: bigint;\n};\n\nfunction defaultMarketParams(loanToken: Address = zeroAddress as Address): MarketParams {\n return {\n loanToken,\n collateralToken: zeroAddress as Address,\n oracle: zeroAddress as Address,\n irm: zeroAddress as Address,\n lltv: 0n,\n };\n}\n\nfunction decodeMarket(data: Hex | null): [bigint, bigint, bigint, bigint, bigint, bigint] | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({\n abi: MORPHO_ABI,\n functionName: \"market\",\n data,\n }) as [bigint, bigint, bigint, bigint, bigint, bigint];\n } catch {\n return null;\n }\n}\n\nfunction decodeMarketParams(data: Hex | null): [Address, Address, Address, Address, bigint] | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({\n abi: MORPHO_ABI,\n functionName: \"idToMarketParams\",\n data,\n }) as [Address, Address, Address, Address, bigint];\n } catch {\n return null;\n }\n}\n\nexport class MorphoBlueAdapter implements ILending {\n private readonly protocolName: string;\n private readonly morpho: Address;\n private readonly defaultVault?: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const morpho = contracts[\"morpho_blue\"];\n if (!morpho) throw DefiError.contractError(\"Missing 'morpho_blue' contract address\");\n this.morpho = morpho;\n this.defaultVault =\n contracts[\"fehype\"] ?? contracts[\"vault\"] ?? contracts[\"feusdc\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"supply\",\n args: [market, params.amount, 0n, params.on_behalf_of, \"0x\"],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"borrow\",\n args: [market, params.amount, 0n, params.on_behalf_of, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"repay\",\n args: [market, params.amount, 0n, params.on_behalf_of, \"0x\"],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"withdraw\",\n args: [market, params.amount, 0n, params.to, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n if (!this.defaultVault) {\n throw DefiError.contractError(`[${this.protocolName}] No MetaMorpho vault configured for rate query`);\n }\n\n // Batch 1: supplyQueueLength (gate check)\n const [queueLenRaw] = await multicallRead(this.rpcUrl, [\n [this.defaultVault, encodeFunctionData({ abi: META_MORPHO_ABI, functionName: \"supplyQueueLength\" })],\n ]).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyQueueLength failed: ${e}`); });\n\n const queueLen = decodeU256(queueLenRaw ?? null);\n\n if (queueLen === 0n) {\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: 0,\n borrow_variable_apy: 0,\n utilization: 0,\n total_supply: 0n,\n total_borrow: 0n,\n };\n }\n\n // supplyQueue(0) — single call, depends on queueLen > 0\n const [marketIdRaw] = await multicallRead(this.rpcUrl, [\n [this.defaultVault, encodeFunctionData({ abi: META_MORPHO_ABI, functionName: \"supplyQueue\", args: [0n] })],\n ]).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyQueue(0) failed: ${e}`); });\n\n if (!marketIdRaw || marketIdRaw.length < 66) {\n throw DefiError.rpcError(`[${this.protocolName}] supplyQueue(0) returned no data`);\n }\n const marketId = marketIdRaw.slice(0, 66) as `0x${string}`;\n\n // Batch 2: market + idToMarketParams (both depend on marketId, independent of each other)\n const [marketRaw, paramsRaw] = await multicallRead(this.rpcUrl, [\n [this.morpho, encodeFunctionData({ abi: MORPHO_ABI, functionName: \"market\", args: [marketId] })],\n [this.morpho, encodeFunctionData({ abi: MORPHO_ABI, functionName: \"idToMarketParams\", args: [marketId] })],\n ]).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] market/idToMarketParams failed: ${e}`); });\n\n const mktDecoded = decodeMarket(marketRaw ?? null);\n if (!mktDecoded) throw DefiError.rpcError(`[${this.protocolName}] market() returned no data`);\n const [totalSupplyAssets, totalSupplyShares, totalBorrowAssets, totalBorrowShares, lastUpdate, fee] = mktDecoded;\n\n const paramsDecoded = decodeMarketParams(paramsRaw ?? null);\n if (!paramsDecoded) throw DefiError.rpcError(`[${this.protocolName}] idToMarketParams returned no data`);\n const [loanToken, collateralToken, oracle, irm, lltv] = paramsDecoded;\n\n const supplyF = Number(totalSupplyAssets);\n const borrowF = Number(totalBorrowAssets);\n const util = supplyF > 0 ? borrowF / supplyF : 0;\n\n const irmMarketParams: MarketParams = { loanToken, collateralToken, oracle, irm, lltv };\n const irmMarket = { totalSupplyAssets, totalSupplyShares, totalBorrowAssets, totalBorrowShares, lastUpdate, fee };\n\n // borrowRateView depends on both market + idToMarketParams results — keep separate\n const borrowRatePerSec = await (async () => {\n const [borrowRateRaw] = await multicallRead(this.rpcUrl!, [\n [irm, encodeFunctionData({ abi: IRM_ABI, functionName: \"borrowRateView\", args: [irmMarketParams, irmMarket] })],\n ]).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] borrowRateView failed: ${e}`); });\n return decodeU256(borrowRateRaw ?? null);\n })();\n\n const ratePerSec = Number(borrowRatePerSec) / 1e18;\n const borrowApy = ratePerSec * SECONDS_PER_YEAR * 100;\n const feePct = Number(fee) / 1e18;\n const supplyApy = borrowApy * util * (1 - feePct);\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization: util * 100,\n total_supply: totalSupplyAssets,\n total_borrow: totalBorrowAssets,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Morpho Blue user positions are per-market — use vault deposit/withdraw instead`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ICdp } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type OpenCdpParams,\n type AdjustCdpParams,\n type CloseCdpParams,\n type CdpInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst BORROWER_OPS_ABI = parseAbi([\n \"function openTrove(address _owner, uint256 _ownerIndex, uint256 _collAmount, uint256 _boldAmount, uint256 _upperHint, uint256 _lowerHint, uint256 _annualInterestRate, uint256 _maxUpfrontFee, address _addManager, address _removeManager, address _receiver) external returns (uint256)\",\n \"function adjustTrove(uint256 _troveId, uint256 _collChange, bool _isCollIncrease, uint256 _debtChange, bool _isDebtIncrease, uint256 _upperHint, uint256 _lowerHint, uint256 _maxUpfrontFee) external\",\n \"function closeTrove(uint256 _troveId) external\",\n]);\n\nconst TROVE_MANAGER_ABI = parseAbi([\n \"function getLatestTroveData(uint256 _troveId) external view returns (uint256 entireDebt, uint256 entireColl, uint256 redistDebtGain, uint256 redistCollGain, uint256 accruedInterest, uint256 recordedDebt, uint256 annualInterestRate, uint256 accruedBatchManagementFee, uint256 weightedRecordedDebt, uint256 lastInterestRateAdjTime)\",\n]);\n\nconst HINT_HELPERS_ABI = parseAbi([\n \"function getApproxHint(uint256 _collIndex, uint256 _interestRate, uint256 _numTrials, uint256 _inputRandomSeed) external view returns (uint256 hintId, uint256 diff, uint256 latestRandomSeed)\",\n]);\n\nconst SORTED_TROVES_ABI = parseAbi([\n \"function findInsertPosition(uint256 _annualInterestRate, uint256 _prevId, uint256 _nextId) external view returns (uint256 prevId, uint256 nextId)\",\n]);\n\nexport class FelixCdpAdapter implements ICdp {\n private readonly protocolName: string;\n private readonly borrowerOperations: Address;\n private readonly troveManager?: Address;\n private readonly hintHelpers?: Address;\n private readonly sortedTroves?: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const bo = contracts[\"borrower_operations\"];\n if (!bo) throw DefiError.contractError(\"Missing 'borrower_operations' contract\");\n this.borrowerOperations = bo;\n this.troveManager = contracts[\"trove_manager\"];\n this.hintHelpers = contracts[\"hint_helpers\"];\n this.sortedTroves = contracts[\"sorted_troves\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n private async getHints(interestRate: bigint): Promise<[bigint, bigint]> {\n if (!this.hintHelpers || !this.sortedTroves || !this.rpcUrl) {\n return [0n, 0n];\n }\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const approxResult = await client.readContract({\n address: this.hintHelpers,\n abi: HINT_HELPERS_ABI,\n functionName: \"getApproxHint\",\n args: [0n, interestRate, 15n, 42n],\n }).catch(() => null);\n\n if (!approxResult) return [0n, 0n];\n const [hintId] = approxResult as [bigint, bigint, bigint];\n\n const insertResult = await client.readContract({\n address: this.sortedTroves,\n abi: SORTED_TROVES_ABI,\n functionName: \"findInsertPosition\",\n args: [interestRate, hintId, hintId],\n }).catch(() => null);\n\n if (!insertResult) return [0n, 0n];\n const [prevId, nextId] = insertResult as [bigint, bigint];\n return [prevId, nextId];\n }\n\n async buildOpen(params: OpenCdpParams): Promise<DeFiTx> {\n const interestRate = 50000000000000000n; // 5% default\n const [upperHint, lowerHint] = await this.getHints(interestRate);\n const hasHints = upperHint !== 0n || lowerHint !== 0n;\n\n const data = encodeFunctionData({\n abi: BORROWER_OPS_ABI,\n functionName: \"openTrove\",\n args: [\n params.recipient,\n 0n,\n params.collateral_amount,\n params.debt_amount,\n upperHint,\n lowerHint,\n interestRate,\n BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"), // U256::MAX\n params.recipient,\n params.recipient,\n params.recipient,\n ],\n });\n\n return {\n description: `[${this.protocolName}] Open trove: collateral=${params.collateral_amount}, debt=${params.debt_amount} (hints=${hasHints ? \"optimized\" : \"none\"})`,\n to: this.borrowerOperations,\n data,\n value: 0n,\n gas_estimate: hasHints ? 500_000 : 5_000_000,\n };\n }\n\n async buildAdjust(params: AdjustCdpParams): Promise<DeFiTx> {\n const collChange = params.collateral_delta ?? 0n;\n const debtChange = params.debt_delta ?? 0n;\n\n const data = encodeFunctionData({\n abi: BORROWER_OPS_ABI,\n functionName: \"adjustTrove\",\n args: [\n params.cdp_id,\n collChange,\n params.add_collateral,\n debtChange,\n params.add_debt,\n 0n,\n 0n,\n BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Adjust trove ${params.cdp_id}`,\n to: this.borrowerOperations,\n data,\n value: 0n,\n gas_estimate: 400_000,\n };\n }\n\n async buildClose(params: CloseCdpParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: BORROWER_OPS_ABI,\n functionName: \"closeTrove\",\n args: [params.cdp_id],\n });\n\n return {\n description: `[${this.protocolName}] Close trove ${params.cdp_id}`,\n to: this.borrowerOperations,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async getCdpInfo(cdpId: bigint): Promise<CdpInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(`[${this.protocolName}] getCdpInfo requires RPC — set HYPEREVM_RPC_URL`);\n if (!this.troveManager) throw DefiError.contractError(`[${this.protocolName}] trove_manager contract not configured`);\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const data = await client.readContract({\n address: this.troveManager,\n abi: TROVE_MANAGER_ABI,\n functionName: \"getLatestTroveData\",\n args: [cdpId],\n }).catch((e: unknown) => {\n throw DefiError.invalidParam(`[${this.protocolName}] Trove ${cdpId} not found: ${e}`);\n });\n\n const [entireDebt, entireColl] = data as [bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint];\n\n if (entireDebt === 0n && entireColl === 0n) {\n throw DefiError.invalidParam(`[${this.protocolName}] Trove ${cdpId} does not exist`);\n }\n\n const collRatio = entireDebt > 0n ? Number(entireColl) / Number(entireDebt) : 0;\n\n return {\n protocol: this.protocolName,\n cdp_id: cdpId,\n collateral: {\n token: zeroAddress as Address,\n symbol: \"WHYPE\",\n amount: entireColl,\n decimals: 18,\n },\n debt: {\n token: zeroAddress as Address,\n symbol: \"feUSD\",\n amount: entireDebt,\n decimals: 18,\n },\n collateral_ratio: collRatio,\n };\n }\n}\n","import { createPublicClient, http, parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IOracle } from \"@hypurrquant/defi-core\";\nimport { DefiError, type ProtocolEntry, type PriceData } from \"@hypurrquant/defi-core\";\n\nconst PRICE_FEED_ABI = parseAbi([\n \"function fetchPrice() external view returns (uint256 price, bool isNewOracleFailureDetected)\",\n \"function lastGoodPrice() external view returns (uint256)\",\n]);\n\nexport class FelixOracleAdapter implements IOracle {\n private readonly protocolName: string;\n private readonly priceFeed: Address;\n private readonly asset: Address;\n private readonly rpcUrl: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n if (!rpcUrl) throw DefiError.rpcError(`[${entry.name}] RPC URL required for oracle`);\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const feed = contracts[\"price_feed\"];\n if (!feed) throw DefiError.contractError(`[${entry.name}] Missing 'price_feed' contract address`);\n this.priceFeed = feed;\n // The asset address is stored under \"asset\" or falls back to zero (WHYPE native)\n this.asset = contracts[\"asset\"] ?? (\"0x0000000000000000000000000000000000000000\" as Address);\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getPrice(asset: Address): Promise<PriceData> {\n if (asset !== this.asset && this.asset !== \"0x0000000000000000000000000000000000000000\") {\n throw DefiError.unsupported(`[${this.protocolName}] Felix PriceFeed only supports asset ${this.asset}`);\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n let priceVal: bigint;\n try {\n const result = await client.readContract({\n address: this.priceFeed,\n abi: PRICE_FEED_ABI,\n functionName: \"fetchPrice\",\n });\n const [price] = result as [bigint, boolean];\n priceVal = price;\n } catch {\n // Fall back to lastGoodPrice\n priceVal = await client.readContract({\n address: this.priceFeed,\n abi: PRICE_FEED_ABI,\n functionName: \"lastGoodPrice\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] lastGoodPrice failed: ${e}`);\n }) as bigint;\n }\n\n // Felix prices are already in 18-decimal USD\n const priceF64 = Number(priceVal) / 1e18;\n\n return {\n source: \"Felix PriceFeed\",\n source_type: \"oracle\",\n asset,\n price_usd: priceVal,\n price_f64: priceF64,\n };\n }\n\n async getPrices(assets: Address[]): Promise<PriceData[]> {\n const results: PriceData[] = [];\n for (const asset of assets) {\n try {\n results.push(await this.getPrice(asset));\n } catch {\n // Skip unsupported assets\n }\n }\n return results;\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IVault } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type VaultInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst ERC4626_ABI = parseAbi([\n \"function asset() external view returns (address)\",\n \"function totalAssets() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function convertToShares(uint256 assets) external view returns (uint256)\",\n \"function convertToAssets(uint256 shares) external view returns (uint256)\",\n \"function deposit(uint256 assets, address receiver) external returns (uint256 shares)\",\n \"function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares)\",\n]);\n\nexport class ERC4626VaultAdapter implements IVault {\n private readonly protocolName: string;\n private readonly vaultAddress: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const vault = entry.contracts?.[\"vault\"];\n if (!vault) throw DefiError.contractError(\"Missing 'vault' contract address\");\n this.vaultAddress = vault;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildDeposit(assets: bigint, receiver: Address): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: ERC4626_ABI,\n functionName: \"deposit\",\n args: [assets, receiver],\n });\n return {\n description: `[${this.protocolName}] Deposit ${assets} assets into vault`,\n to: this.vaultAddress,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildWithdraw(assets: bigint, receiver: Address, owner: Address): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: ERC4626_ABI,\n functionName: \"withdraw\",\n args: [assets, receiver, owner],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${assets} assets from vault`,\n to: this.vaultAddress,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async totalAssets(): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return client.readContract({\n address: this.vaultAddress,\n abi: ERC4626_ABI,\n functionName: \"totalAssets\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] totalAssets failed: ${e}`);\n }) as Promise<bigint>;\n }\n\n async convertToShares(assets: bigint): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return client.readContract({\n address: this.vaultAddress,\n abi: ERC4626_ABI,\n functionName: \"convertToShares\",\n args: [assets],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] convertToShares failed: ${e}`);\n }) as Promise<bigint>;\n }\n\n async convertToAssets(shares: bigint): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return client.readContract({\n address: this.vaultAddress,\n abi: ERC4626_ABI,\n functionName: \"convertToAssets\",\n args: [shares],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] convertToAssets failed: ${e}`);\n }) as Promise<bigint>;\n }\n\n async getVaultInfo(): Promise<VaultInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [totalAssets, totalSupply, asset] = await Promise.all([\n client.readContract({ address: this.vaultAddress, abi: ERC4626_ABI, functionName: \"totalAssets\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalAssets failed: ${e}`); }),\n client.readContract({ address: this.vaultAddress, abi: ERC4626_ABI, functionName: \"totalSupply\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalSupply failed: ${e}`); }),\n client.readContract({ address: this.vaultAddress, abi: ERC4626_ABI, functionName: \"asset\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] asset failed: ${e}`); }),\n ]);\n\n return {\n protocol: this.protocolName,\n vault_address: this.vaultAddress,\n asset: asset as Address,\n total_assets: totalAssets as bigint,\n total_supply: totalSupply as bigint,\n };\n }\n}\n","import { parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type StakeParams,\n type UnstakeParams,\n type StakingInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst GENERIC_LST_ABI = parseAbi([\n \"function stake() external payable returns (uint256)\",\n \"function unstake(uint256 amount) external returns (uint256)\",\n]);\n\nexport class GenericLstAdapter implements ILiquidStaking {\n private readonly protocolName: string;\n private readonly staking: Address;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const staking = entry.contracts?.[\"staking\"];\n if (!staking) throw DefiError.contractError(\"Missing 'staking' contract\");\n this.staking = staking;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildStake(params: StakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({ abi: GENERIC_LST_ABI, functionName: \"stake\" });\n return {\n description: `[${this.protocolName}] Stake ${params.amount} HYPE`,\n to: this.staking,\n data,\n value: params.amount,\n gas_estimate: 200_000,\n };\n }\n\n async buildUnstake(params: UnstakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: GENERIC_LST_ABI,\n functionName: \"unstake\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Unstake ${params.amount}`,\n to: this.staking,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async getInfo(): Promise<StakingInfo> {\n throw DefiError.unsupported(`[${this.protocolName}] getInfo requires RPC`);\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type StakeParams,\n type UnstakeParams,\n type StakingInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst STHYPE_ABI = parseAbi([\n \"function submit(address referral) external payable returns (uint256)\",\n \"function requestWithdrawals(uint256[] amounts, address owner) external returns (uint256[] requestIds)\",\n]);\n\nconst ERC20_ABI = parseAbi([\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nexport class StHypeAdapter implements ILiquidStaking {\n private readonly protocolName: string;\n private readonly staking: Address;\n private readonly sthypeToken?: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const staking = entry.contracts?.[\"staking\"];\n if (!staking) throw DefiError.contractError(\"Missing 'staking' contract\");\n this.staking = staking;\n this.sthypeToken = entry.contracts?.[\"sthype_token\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildStake(params: StakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: STHYPE_ABI,\n functionName: \"submit\",\n args: [zeroAddress as Address],\n });\n return {\n description: `[${this.protocolName}] Stake ${params.amount} HYPE for stHYPE`,\n to: this.staking,\n data,\n value: params.amount,\n gas_estimate: 200_000,\n };\n }\n\n async buildUnstake(params: UnstakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: STHYPE_ABI,\n functionName: \"requestWithdrawals\",\n args: [[params.amount], params.recipient],\n });\n return {\n description: `[${this.protocolName}] Request unstake ${params.amount} stHYPE`,\n to: this.staking,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async getInfo(): Promise<StakingInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const tokenAddr = this.sthypeToken ?? this.staking;\n\n const totalSupply = await client.readContract({\n address: tokenAddr,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] totalSupply failed: ${e}`);\n }) as bigint;\n\n return {\n protocol: this.protocolName,\n staked_token: zeroAddress as Address,\n liquid_token: tokenAddr,\n exchange_rate: 1.0,\n total_staked: totalSupply,\n };\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type StakeParams,\n type UnstakeParams,\n type StakingInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst KINETIQ_ABI = parseAbi([\n \"function stake() external payable returns (uint256)\",\n \"function requestUnstake(uint256 amount) external returns (uint256)\",\n \"function totalStaked() external view returns (uint256)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n]);\n\n// WHYPE address on HyperEVM\nconst WHYPE: Address = \"0x5555555555555555555555555555555555555555\";\n// HyperLend oracle address (Aave V3 compatible)\nconst HYPERLEND_ORACLE: Address = \"0xc9fb4fbe842d57ea1df3e641a281827493a63030\";\n\nexport class KinetiqAdapter implements ILiquidStaking {\n private readonly protocolName: string;\n private readonly staking: Address;\n private readonly liquidToken: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const staking = entry.contracts?.[\"staking\"];\n if (!staking) throw DefiError.contractError(\"Missing 'staking' contract address\");\n this.staking = staking;\n this.liquidToken = entry.contracts?.[\"khype_token\"] ?? staking;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildStake(params: StakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({ abi: KINETIQ_ABI, functionName: \"stake\" });\n return {\n description: `[${this.protocolName}] Stake ${params.amount} HYPE for kHYPE`,\n to: this.staking,\n data,\n value: params.amount,\n gas_estimate: 300_000,\n };\n }\n\n async buildUnstake(params: UnstakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: KINETIQ_ABI,\n functionName: \"requestUnstake\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Request unstake ${params.amount} kHYPE`,\n to: this.staking,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async getInfo(): Promise<StakingInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const totalStaked = await client.readContract({\n address: this.staking,\n abi: KINETIQ_ABI,\n functionName: \"totalStaked\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] totalStaked failed: ${e}`);\n }) as bigint;\n\n const [khypePrice, hypePrice] = await Promise.all([\n client.readContract({ address: HYPERLEND_ORACLE, abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [this.liquidToken] }).catch(() => 0n),\n client.readContract({ address: HYPERLEND_ORACLE, abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [WHYPE] }).catch(() => 0n),\n ]);\n\n const rateF64 =\n (hypePrice as bigint) > 0n && (khypePrice as bigint) > 0n\n ? Number((khypePrice as bigint) * 10n ** 18n / (hypePrice as bigint)) / 1e18\n : 1.0;\n\n return {\n protocol: this.protocolName,\n staked_token: zeroAddress as Address,\n liquid_token: this.liquidToken,\n exchange_rate: rateF64,\n total_staked: totalStaked,\n };\n }\n}\n","import type { Address } from \"viem\";\nimport type { IYieldSource } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type YieldInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class PendleAdapter implements IYieldSource {\n private readonly protocolName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n if (!entry.contracts?.[\"router\"]) {\n throw DefiError.contractError(\"Missing 'router' contract\");\n }\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getYields(): Promise<YieldInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] getYields requires RPC`);\n }\n\n async buildDeposit(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Pendle deposit requires market address and token routing params. Use Pendle-specific CLI.`,\n );\n }\n\n async buildWithdraw(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Pendle withdraw requires market-specific params`,\n );\n }\n}\n","import type { Address } from \"viem\";\nimport type { IYieldSource } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type YieldInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class GenericYieldAdapter implements IYieldSource {\n private readonly protocolName: string;\n private readonly interfaceName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n this.interfaceName = entry.interface;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getYields(): Promise<YieldInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] getYields requires RPC`);\n }\n\n async buildDeposit(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Yield interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'pendle_v2' (Pendle). Protocols like Steer (managed liquidity), ` +\n `Liminal (yield optimization), and Altura (gaming yield) need custom deposit logic.`,\n );\n }\n\n async buildWithdraw(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Yield interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'pendle_v2' (Pendle). Protocols like Steer (managed liquidity), ` +\n `Liminal (yield optimization), and Altura (gaming yield) need custom withdraw logic.`,\n );\n }\n}\n","import { parseAbi, encodeFunctionData } from \"viem\";\nimport type { IDerivatives } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type DerivativesPositionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\n\nconst HLP_ABI = parseAbi([\n \"function deposit(uint256 amount) external returns (uint256)\",\n \"function withdraw(uint256 shares) external returns (uint256)\",\n]);\n\nexport class HlpVaultAdapter implements IDerivatives {\n private readonly protocolName: string;\n private readonly vault: Address;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const vault = entry.contracts?.[\"vault\"];\n if (!vault) throw DefiError.contractError(\"Missing 'vault' contract\");\n this.vault = vault;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildOpenPosition(params: DerivativesPositionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: HLP_ABI,\n functionName: \"deposit\",\n args: [params.collateral],\n });\n return {\n description: `[${this.protocolName}] Deposit ${params.collateral} into HLP vault`,\n to: this.vault,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildClosePosition(params: DerivativesPositionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: HLP_ABI,\n functionName: \"withdraw\",\n args: [params.size],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.size} from HLP vault`,\n to: this.vault,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n}\n","import type { IDerivatives } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type DerivativesPositionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class GenericDerivativesAdapter implements IDerivatives {\n private readonly protocolName: string;\n private readonly interfaceName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n this.interfaceName = entry.interface;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildOpenPosition(_params: DerivativesPositionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Derivatives interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'hlp_vault' (HLP Vault). Protocols like Rumpel need custom position management logic.`,\n );\n }\n\n async buildClosePosition(_params: DerivativesPositionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Derivatives interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'hlp_vault' (HLP Vault). Protocols like Rumpel need custom position management logic.`,\n );\n }\n}\n","import { parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IOptions } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type OptionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst RYSK_ABI = parseAbi([\n \"function openOption(address underlying, uint256 strikePrice, uint256 expiry, bool isCall, uint256 amount) external returns (uint256 premium)\",\n \"function closeOption(address underlying, uint256 strikePrice, uint256 expiry, bool isCall, uint256 amount) external returns (uint256 payout)\",\n]);\n\nexport class RyskAdapter implements IOptions {\n private readonly protocolName: string;\n private readonly controller: Address;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const controller = entry.contracts?.[\"controller\"];\n if (!controller) throw DefiError.contractError(\"Missing 'controller' contract\");\n this.controller = controller;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildBuy(params: OptionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: RYSK_ABI,\n functionName: \"openOption\",\n args: [\n params.underlying,\n params.strike_price,\n BigInt(params.expiry),\n params.is_call,\n params.amount,\n ],\n });\n return {\n description: `[${this.protocolName}] Buy ${params.is_call ? \"call\" : \"put\"} ${params.amount} option, strike=${params.strike_price}, expiry=${params.expiry}`,\n to: this.controller,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildSell(params: OptionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: RYSK_ABI,\n functionName: \"closeOption\",\n args: [\n params.underlying,\n params.strike_price,\n BigInt(params.expiry),\n params.is_call,\n params.amount,\n ],\n });\n return {\n description: `[${this.protocolName}] Sell/close ${params.is_call ? \"call\" : \"put\"} ${params.amount} option`,\n to: this.controller,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n}\n","import type { IOptions } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type OptionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class GenericOptionsAdapter implements IOptions {\n private readonly protocolName: string;\n private readonly interfaceName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n this.interfaceName = entry.interface;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildBuy(_params: OptionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Options interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'rysk' (Rysk Finance). Other options protocols need custom strike/expiry handling.`,\n );\n }\n\n async buildSell(_params: OptionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Options interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'rysk' (Rysk Finance). Other options protocols need custom strike/expiry handling.`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { INft, NftCollectionInfo, NftTokenInfo } from \"@hypurrquant/defi-core\";\nimport { DefiError, type ProtocolEntry } from \"@hypurrquant/defi-core\";\n\nconst ERC721_ABI = parseAbi([\n \"function name() returns (string)\",\n \"function symbol() returns (string)\",\n \"function totalSupply() returns (uint256)\",\n \"function ownerOf(uint256 tokenId) returns (address)\",\n \"function balanceOf(address owner) returns (uint256)\",\n \"function tokenURI(uint256 tokenId) returns (string)\",\n]);\n\nexport class ERC721Adapter implements INft {\n private readonly protocolName: string;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getCollectionInfo(collection: Address): Promise<NftCollectionInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [collectionName, symbol, totalSupply] = await Promise.all([\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"name\" })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] name failed: ${e}`);\n }),\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"symbol\" })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] symbol failed: ${e}`);\n }),\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"totalSupply\" })\n .catch(() => undefined),\n ]);\n\n return {\n address: collection,\n name: collectionName as string,\n symbol: symbol as string,\n total_supply: totalSupply as bigint | undefined,\n };\n }\n\n async getTokenInfo(collection: Address, tokenId: bigint): Promise<NftTokenInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [owner, tokenUri] = await Promise.all([\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"ownerOf\", args: [tokenId] })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] ownerOf failed: ${e}`);\n }),\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"tokenURI\", args: [tokenId] })\n .catch(() => undefined),\n ]);\n\n return {\n collection,\n token_id: tokenId,\n owner: owner as Address,\n token_uri: tokenUri as string | undefined,\n };\n }\n\n async getBalance(owner: Address, collection: Address): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n return client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"balanceOf\", args: [owner] })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] balanceOf failed: ${e}`);\n }) as Promise<bigint>;\n }\n}\n","import type { Address } from \"viem\";\n\nimport type { IDex, PriceData, QuoteParams } from \"@hypurrquant/defi-core\";\n\n/**\n * Utility for deriving spot prices from DEX quoters.\n * Quotes 1 unit of the token against a quote token (e.g. USDC) to derive price.\n */\nexport class DexSpotPrice {\n /**\n * Get the spot price for `token` denominated in `quoteToken` (e.g. USDC).\n *\n * `tokenDecimals` — decimals of the input token (to know how much \"1 unit\" is)\n * `quoteDecimals` — decimals of the quote token (to convert the output to number)\n */\n static async getPrice(\n dex: IDex,\n token: Address,\n tokenDecimals: number,\n quoteToken: Address,\n quoteDecimals: number,\n ): Promise<PriceData> {\n const amountIn = 10n ** BigInt(tokenDecimals); // 1 token\n\n const quoteParams: QuoteParams = {\n protocol: \"\",\n token_in: token,\n token_out: quoteToken,\n amount_in: amountIn,\n };\n\n const quote = await dex.quote(quoteParams);\n\n // Convert to USD price (assuming quoteToken is a USD stablecoin)\n const priceF64 = Number(quote.amount_out) / 10 ** quoteDecimals;\n\n // Normalize to 18-decimal representation\n let priceUsd: bigint;\n if (quoteDecimals < 18) {\n priceUsd = quote.amount_out * 10n ** BigInt(18 - quoteDecimals);\n } else if (quoteDecimals > 18) {\n priceUsd = quote.amount_out / 10n ** BigInt(quoteDecimals - 18);\n } else {\n priceUsd = quote.amount_out;\n }\n\n return {\n source: `dex:${dex.name()}`,\n source_type: \"dex_spot\",\n asset: token,\n price_usd: priceUsd,\n price_f64: priceF64,\n block_number: undefined,\n timestamp: undefined,\n };\n }\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createDex } from \"@hypurrquant/defi-protocols\";\n\nexport function registerDex(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const dex = parent.command(\"dex\").description(\"DEX operations: swap, quote, compare\");\n\n dex.command(\"quote\")\n .description(\"Get a swap quote without executing\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--token-in <token>\", \"Input token symbol or address\")\n .requiredOption(\"--token-out <token>\", \"Output token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount of input token in wei\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createDex(protocol, chain.effectiveRpcUrl());\n const tokenIn = opts.tokenIn.startsWith(\"0x\") ? opts.tokenIn as Address : registry.resolveToken(chainName, opts.tokenIn).address as Address;\n const tokenOut = opts.tokenOut.startsWith(\"0x\") ? opts.tokenOut as Address : registry.resolveToken(chainName, opts.tokenOut).address as Address;\n const result = await adapter.quote({ protocol: protocol.name, token_in: tokenIn, token_out: tokenOut, amount_in: BigInt(opts.amount) });\n printOutput(result, getOpts());\n });\n\n dex.command(\"swap\")\n .description(\"Execute a token swap\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--token-in <token>\", \"Input token\")\n .requiredOption(\"--token-out <token>\", \"Output token\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--slippage <bps>\", \"Slippage tolerance in bps\", \"50\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createDex(protocol, chain.effectiveRpcUrl());\n const tokenIn = opts.tokenIn.startsWith(\"0x\") ? opts.tokenIn as Address : registry.resolveToken(chainName, opts.tokenIn).address as Address;\n const tokenOut = opts.tokenOut.startsWith(\"0x\") ? opts.tokenOut as Address : registry.resolveToken(chainName, opts.tokenOut).address as Address;\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildSwap({\n protocol: protocol.name, token_in: tokenIn, token_out: tokenOut,\n amount_in: BigInt(opts.amount), slippage: { bps: parseInt(opts.slippage) }, recipient,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n dex.command(\"lp-add\")\n .description(\"Add liquidity to a pool\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--token-a <token>\", \"First token symbol or address\")\n .requiredOption(\"--token-b <token>\", \"Second token symbol or address\")\n .requiredOption(\"--amount-a <amount>\", \"Amount of token A in wei\")\n .requiredOption(\"--amount-b <amount>\", \"Amount of token B in wei\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .option(\"--tick-lower <tick>\", \"Lower tick for concentrated LP (default: full range)\")\n .option(\"--tick-upper <tick>\", \"Upper tick for concentrated LP (default: full range)\")\n .option(\"--range <percent>\", \"±N% concentrated range around current price (e.g. --range 2 for ±2%)\")\n .option(\"--pool <name_or_address>\", \"Pool name (e.g. WHYPE/USDC) or address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createDex(protocol, chain.effectiveRpcUrl());\n const tokenA = opts.tokenA.startsWith(\"0x\") ? opts.tokenA as Address : registry.resolveToken(chainName, opts.tokenA).address as Address;\n const tokenB = opts.tokenB.startsWith(\"0x\") ? opts.tokenB as Address : registry.resolveToken(chainName, opts.tokenB).address as Address;\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n\n // Resolve pool: name (WHYPE/USDC) → address from config, or raw address\n let poolAddr: Address | undefined;\n if (opts.pool) {\n if (opts.pool.startsWith(\"0x\")) {\n poolAddr = opts.pool as Address;\n } else {\n const poolInfo = registry.resolvePool(opts.protocol, opts.pool);\n poolAddr = poolInfo.address;\n }\n }\n\n const tx = await adapter.buildAddLiquidity({\n protocol: protocol.name,\n token_a: tokenA,\n token_b: tokenB,\n amount_a: BigInt(opts.amountA),\n amount_b: BigInt(opts.amountB),\n recipient,\n tick_lower: opts.tickLower !== undefined ? parseInt(opts.tickLower) : undefined,\n tick_upper: opts.tickUpper !== undefined ? parseInt(opts.tickUpper) : undefined,\n range_pct: opts.range !== undefined ? parseFloat(opts.range) : undefined,\n pool: poolAddr,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n dex.command(\"lp-remove\")\n .description(\"Remove liquidity from a pool\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--token-a <token>\", \"First token symbol or address\")\n .requiredOption(\"--token-b <token>\", \"Second token symbol or address\")\n .requiredOption(\"--liquidity <amount>\", \"Liquidity amount to remove in wei\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createDex(protocol, chain.effectiveRpcUrl());\n const tokenA = opts.tokenA.startsWith(\"0x\") ? opts.tokenA as Address : registry.resolveToken(chainName, opts.tokenA).address as Address;\n const tokenB = opts.tokenB.startsWith(\"0x\") ? opts.tokenB as Address : registry.resolveToken(chainName, opts.tokenB).address as Address;\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildRemoveLiquidity({\n protocol: protocol.name,\n token_a: tokenA,\n token_b: tokenB,\n liquidity: BigInt(opts.liquidity),\n recipient,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n dex.command(\"compare\")\n .description(\"Compare quotes across DEXes\")\n .requiredOption(\"--token-in <token>\", \"Input token\")\n .requiredOption(\"--token-out <token>\", \"Output token\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const tokenIn = opts.tokenIn.startsWith(\"0x\") ? opts.tokenIn as Address : registry.resolveToken(chainName, opts.tokenIn).address as Address;\n const tokenOut = opts.tokenOut.startsWith(\"0x\") ? opts.tokenOut as Address : registry.resolveToken(chainName, opts.tokenOut).address as Address;\n const dexProtocols = registry.getProtocolsByCategory(\"dex\" as any).filter(p => p.chain === chainName);\n const results: Array<{ protocol: string; amount_out: bigint; error?: string }> = [];\n await Promise.all(dexProtocols.map(async (p) => {\n try {\n const adapter = createDex(p, chain.effectiveRpcUrl());\n const q = await adapter.quote({ protocol: p.name, token_in: tokenIn, token_out: tokenOut, amount_in: BigInt(opts.amount) });\n results.push({ protocol: p.name, amount_out: q.amount_out });\n } catch (e) { results.push({ protocol: p.name, amount_out: 0n, error: e instanceof Error ? e.message : String(e) }); }\n }));\n results.sort((a, b) => (b.amount_out > a.amount_out ? 1 : -1));\n printOutput({ chain: chainName, quotes: results }, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { createGauge } from \"@hypurrquant/defi-protocols\";\n\nfunction resolveAccount(): Address | undefined {\n const walletAddr = process.env[\"DEFI_WALLET_ADDRESS\"];\n if (walletAddr) return walletAddr as Address;\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n if (privateKey) return privateKeyToAccount(privateKey as `0x${string}`).address;\n return undefined;\n}\n\nexport function registerGauge(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const gauge = parent.command(\"gauge\").description(\"Gauge operations: find, deposit, withdraw, claim, earned\");\n\n gauge.command(\"discover\")\n .description(\"Find all pools with emission gauges (scans V2 + CL factories)\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, chain.effectiveRpcUrl());\n if (!adapter.discoverGaugedPools) throw new Error(`${protocol.name} does not support gauge discovery`);\n const pools = await adapter.discoverGaugedPools();\n printOutput(pools, getOpts());\n });\n\n gauge.command(\"find\")\n .description(\"Find gauge address for a pool via voter contract\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pool <address>\", \"Pool address\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, chain.effectiveRpcUrl());\n if (!adapter.resolveGauge) throw new Error(`${protocol.name} does not support gauge lookup`);\n const gaugeAddr = await adapter.resolveGauge(opts.pool as Address);\n printOutput({ pool: opts.pool, gauge: gaugeAddr, protocol: protocol.name }, getOpts());\n });\n\n gauge.command(\"earned\")\n .description(\"Check pending rewards for a gauge\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--gauge <address>\", \"Gauge contract address\")\n .option(\"--token-id <id>\", \"NFT tokenId (for CL gauges like Hybra)\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, chain.effectiveRpcUrl());\n\n if (opts.tokenId) {\n if (!adapter.getPendingRewardsByTokenId) throw new Error(`${protocol.name} does not support NFT rewards`);\n const earned = await adapter.getPendingRewardsByTokenId(opts.gauge as Address, BigInt(opts.tokenId));\n printOutput({ gauge: opts.gauge, token_id: opts.tokenId, earned: earned.toString() }, getOpts());\n } else {\n const account = resolveAccount();\n if (!account) throw new Error(\"DEFI_WALLET_ADDRESS or DEFI_PRIVATE_KEY required\");\n const rewards = await adapter.getPendingRewards(opts.gauge as Address, account);\n printOutput(rewards.map(r => ({ token: r.token, amount: r.amount.toString() })), getOpts());\n }\n });\n\n gauge.command(\"deposit\")\n .description(\"Deposit LP tokens or NFT into a gauge\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--gauge <address>\", \"Gauge contract address\")\n .option(\"--amount <amount>\", \"LP token amount in wei (for V2 gauges)\")\n .option(\"--token-id <id>\", \"NFT tokenId (for CL gauges like Hybra)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, chain.effectiveRpcUrl());\n const amount = opts.amount ? BigInt(opts.amount) : 0n;\n const tokenId = opts.tokenId ? BigInt(opts.tokenId) : undefined;\n const tx = await adapter.buildDeposit(opts.gauge as Address, amount, tokenId);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n gauge.command(\"withdraw\")\n .description(\"Withdraw LP tokens or NFT from a gauge\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--gauge <address>\", \"Gauge contract address\")\n .option(\"--amount <amount>\", \"LP token amount in wei (for V2 gauges)\")\n .option(\"--token-id <id>\", \"NFT tokenId (for CL gauges like Hybra)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, chain.effectiveRpcUrl());\n const amount = opts.amount ? BigInt(opts.amount) : 0n;\n const tokenId = opts.tokenId ? BigInt(opts.tokenId) : undefined;\n const tx = await adapter.buildWithdraw(opts.gauge as Address, amount, tokenId);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n gauge.command(\"claim\")\n .description(\"Claim earned rewards from a gauge\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--gauge <address>\", \"Gauge contract address\")\n .option(\"--token-id <id>\", \"NFT tokenId (for CL gauges like Hybra)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, chain.effectiveRpcUrl());\n\n if (opts.tokenId) {\n if (!adapter.buildClaimRewardsByTokenId) throw new Error(`${protocol.name} does not support NFT claim`);\n const tx = await adapter.buildClaimRewardsByTokenId(opts.gauge as Address, BigInt(opts.tokenId));\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n } else {\n const account = resolveAccount();\n const tx = await adapter.buildClaimRewards(opts.gauge as Address, account);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry, InterestRateMode } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createLending } from \"@hypurrquant/defi-protocols\";\n\nexport function registerLending(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const lending = parent.command(\"lending\").description(\"Lending operations: supply, borrow, repay, withdraw, rates, position\");\n\n lending.command(\"rates\")\n .description(\"Show current lending rates\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n const asset = opts.asset.startsWith(\"0x\") ? opts.asset as Address : registry.resolveToken(chainName, opts.asset).address as Address;\n const rates = await adapter.getRates(asset);\n printOutput(rates, getOpts());\n });\n\n lending.command(\"position\")\n .description(\"Show current lending position\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--address <address>\", \"Wallet address to query\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n const position = await adapter.getUserPosition(opts.address as Address);\n printOutput(position, getOpts());\n });\n\n lending.command(\"supply\")\n .description(\"Supply an asset to a lending protocol\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount to supply in wei\")\n .option(\"--on-behalf-of <address>\", \"On behalf of address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n const asset = opts.asset.startsWith(\"0x\") ? opts.asset as Address : registry.resolveToken(chainName, opts.asset).address as Address;\n const onBehalfOf = (opts.onBehalfOf ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildSupply({ protocol: protocol.name, asset, amount: BigInt(opts.amount), on_behalf_of: onBehalfOf });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n lending.command(\"borrow\")\n .description(\"Borrow an asset\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--rate-mode <mode>\", \"variable or stable\", \"variable\")\n .option(\"--on-behalf-of <address>\", \"On behalf of address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n const asset = opts.asset.startsWith(\"0x\") ? opts.asset as Address : registry.resolveToken(chainName, opts.asset).address as Address;\n const onBehalfOf = (opts.onBehalfOf ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildBorrow({\n protocol: protocol.name, asset, amount: BigInt(opts.amount),\n interest_rate_mode: opts.rateMode === \"stable\" ? InterestRateMode.Stable : InterestRateMode.Variable,\n on_behalf_of: onBehalfOf,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n lending.command(\"repay\")\n .description(\"Repay a borrowed asset\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--rate-mode <mode>\", \"variable or stable\", \"variable\")\n .option(\"--on-behalf-of <address>\", \"On behalf of address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n const asset = opts.asset.startsWith(\"0x\") ? opts.asset as Address : registry.resolveToken(chainName, opts.asset).address as Address;\n const onBehalfOf = (opts.onBehalfOf ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildRepay({\n protocol: protocol.name, asset, amount: BigInt(opts.amount),\n interest_rate_mode: opts.rateMode === \"stable\" ? InterestRateMode.Stable : InterestRateMode.Variable,\n on_behalf_of: onBehalfOf,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n lending.command(\"withdraw\")\n .description(\"Withdraw a supplied asset\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--to <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n const asset = opts.asset.startsWith(\"0x\") ? opts.asset as Address : registry.resolveToken(chainName, opts.asset).address as Address;\n const to = (opts.to ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildWithdraw({ protocol: protocol.name, asset, amount: BigInt(opts.amount), to });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createCdp } from \"@hypurrquant/defi-protocols\";\n\nexport function registerCdp(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const cdp = parent.command(\"cdp\").description(\"CDP operations: open, adjust, close, info\");\n\n cdp.command(\"open\")\n .description(\"Open a new CDP position\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--collateral <token>\", \"Collateral token address\")\n .requiredOption(\"--amount <amount>\", \"Collateral amount in wei\")\n .requiredOption(\"--mint <amount>\", \"Stablecoin to mint in wei\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createCdp(protocol, chain.effectiveRpcUrl());\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildOpen({\n protocol: protocol.name, collateral: opts.collateral as Address,\n collateral_amount: BigInt(opts.amount), debt_amount: BigInt(opts.mint), recipient,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n cdp.command(\"info\")\n .description(\"Show CDP position info, or protocol overview if --position is omitted\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .option(\"--position <id>\", \"CDP/trove ID (omit for protocol overview)\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n if (opts.position === undefined) {\n printOutput({\n name: protocol.name,\n slug: protocol.slug,\n chain: chainName,\n contracts: (protocol as unknown as Record<string, unknown>).contracts ?? {},\n }, getOpts());\n return;\n }\n const adapter = createCdp(protocol, chain.effectiveRpcUrl());\n const info = await adapter.getCdpInfo(BigInt(opts.position));\n printOutput(info, getOpts());\n });\n\n cdp.command(\"adjust\")\n .description(\"Adjust an existing CDP position\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--position <id>\", \"CDP/trove ID\")\n .option(\"--add-collateral <amount>\", \"Add collateral in wei\")\n .option(\"--withdraw-collateral <amount>\", \"Withdraw collateral in wei\")\n .option(\"--mint <amount>\", \"Mint additional stablecoin\")\n .option(\"--repay <amount>\", \"Repay stablecoin\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createCdp(protocol, chain.effectiveRpcUrl());\n const tx = await adapter.buildAdjust({\n protocol: protocol.name, cdp_id: BigInt(opts.position),\n collateral_delta: opts.addCollateral ? BigInt(opts.addCollateral) : opts.withdrawCollateral ? BigInt(opts.withdrawCollateral) : undefined,\n debt_delta: opts.mint ? BigInt(opts.mint) : opts.repay ? BigInt(opts.repay) : undefined,\n add_collateral: !!opts.addCollateral, add_debt: !!opts.mint,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n cdp.command(\"close\")\n .description(\"Close a CDP position\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--position <id>\", \"CDP/trove ID\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createCdp(protocol, chain.effectiveRpcUrl());\n const tx = await adapter.buildClose({ protocol: protocol.name, cdp_id: BigInt(opts.position) });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createLiquidStaking } from \"@hypurrquant/defi-protocols\";\n\nexport function registerStaking(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const staking = parent.command(\"staking\").description(\"Liquid staking: stake, unstake, info\");\n\n staking.command(\"stake\")\n .description(\"Stake tokens via liquid staking\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLiquidStaking(protocol, chain.effectiveRpcUrl());\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildStake({ protocol: protocol.name, amount: BigInt(opts.amount), recipient });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n staking.command(\"unstake\")\n .description(\"Unstake tokens\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLiquidStaking(protocol, chain.effectiveRpcUrl());\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildUnstake({ protocol: protocol.name, amount: BigInt(opts.amount), recipient });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n staking.command(\"info\")\n .description(\"Show staking info and rates\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLiquidStaking(protocol, chain.effectiveRpcUrl());\n const info = await adapter.getInfo();\n printOutput(info, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createVault } from \"@hypurrquant/defi-protocols\";\n\nexport function registerVault(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const vault = parent.command(\"vault\").description(\"Vault operations: deposit, withdraw, info\");\n\n vault.command(\"deposit\")\n .description(\"Deposit assets into a vault\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--receiver <address>\", \"Receiver address for vault shares\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createVault(protocol, chain.effectiveRpcUrl());\n const receiver = (opts.receiver ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildDeposit(BigInt(opts.amount), receiver);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n vault.command(\"withdraw\")\n .description(\"Withdraw assets from a vault\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei (shares)\")\n .option(\"--receiver <address>\", \"Receiver address\")\n .option(\"--owner <address>\", \"Owner address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createVault(protocol, chain.effectiveRpcUrl());\n const receiver = (opts.receiver ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const owner = (opts.owner ?? receiver) as Address;\n const tx = await adapter.buildWithdraw(BigInt(opts.amount), receiver, owner);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n vault.command(\"info\")\n .description(\"Show vault info (TVL, APY, shares)\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createVault(protocol, chain.effectiveRpcUrl());\n const info = await adapter.getVaultInfo();\n printOutput(info, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { Address } from \"viem\";\nimport { Registry, ProtocolCategory } from \"@hypurrquant/defi-core\";\nimport type { LendingRates } from \"@hypurrquant/defi-core\";\nimport { createLending, createVault } from \"@hypurrquant/defi-protocols\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\n\nfunction resolveAsset(registry: Registry, chain: string, asset: string): Address {\n // Try parsing as address first\n if (/^0x[0-9a-fA-F]{40}$/.test(asset)) {\n return asset as Address;\n }\n return registry.resolveToken(chain, asset).address;\n}\n\n/** Collect lending rates for aave_v3 and aave_v3_isolated protocols */\nasync function collectLendingRates(\n registry: Registry,\n chainName: string,\n rpc: string,\n assetAddr: Address,\n): Promise<LendingRates[]> {\n const protos = registry\n .getProtocolsForChain(chainName)\n .filter(\n (p) =>\n p.category === ProtocolCategory.Lending &&\n (p.interface === \"aave_v3\" || p.interface === \"aave_v3_isolated\"),\n );\n\n const results: LendingRates[] = [];\n let first = true;\n\n for (const proto of protos) {\n if (!first) {\n // Small delay between calls to avoid rate limiting\n await new Promise((r) => setTimeout(r, 500));\n }\n first = false;\n\n try {\n const lending = createLending(proto, rpc);\n const rates = await lending.getRates(assetAddr);\n results.push(rates);\n } catch (err) {\n process.stderr.write(`Warning: ${proto.name} rates unavailable: ${err}\\n`);\n }\n }\n\n return results;\n}\n\n/** Collect all yield opportunities: lending + morpho + vaults */\nasync function collectAllYields(\n registry: Registry,\n chainName: string,\n rpc: string,\n asset: string,\n assetAddr: Address,\n): Promise<unknown[]> {\n const opportunities: unknown[] = [];\n\n // 1. Aave V3 lending rates\n const lendingRates = await collectLendingRates(registry, chainName, rpc, assetAddr);\n for (const r of lendingRates) {\n if (r.supply_apy > 0) {\n opportunities.push({\n protocol: r.protocol,\n type: \"lending_supply\",\n asset,\n apy: r.supply_apy,\n utilization: r.utilization,\n });\n }\n }\n\n // 2. Morpho Blue rates\n const chainProtos = registry.getProtocolsForChain(chainName);\n for (const proto of chainProtos) {\n if (proto.category === ProtocolCategory.Lending && proto.interface === \"morpho_blue\") {\n try {\n const lending = createLending(proto, rpc);\n const rates = await lending.getRates(assetAddr);\n if (rates.supply_apy > 0) {\n opportunities.push({\n protocol: rates.protocol,\n type: \"morpho_vault\",\n asset,\n apy: rates.supply_apy,\n utilization: rates.utilization,\n });\n }\n } catch {\n // skip\n }\n }\n }\n\n // 3. ERC-4626 vaults\n for (const proto of chainProtos) {\n if (proto.category === ProtocolCategory.Vault && proto.interface === \"erc4626\") {\n try {\n const vault = createVault(proto, rpc);\n const info = await vault.getVaultInfo();\n opportunities.push({\n protocol: info.protocol,\n type: \"vault\",\n asset,\n apy: info.apy ?? 0,\n total_assets: info.total_assets.toString(),\n });\n } catch {\n // skip\n }\n }\n }\n\n // Sort by APY descending\n opportunities.sort((a, b) => {\n const aa = (a as Record<string, unknown>)[\"apy\"] as number ?? 0;\n const ba = (b as Record<string, unknown>)[\"apy\"] as number ?? 0;\n return ba - aa;\n });\n\n return opportunities;\n}\n\n/** Scan all chains in parallel for best yield on an asset */\nasync function runYieldScan(registry: Registry, asset: string, output: OutputMode): Promise<void> {\n const t0 = Date.now();\n const chainKeys = Array.from(registry.chains.keys());\n\n const tasks = chainKeys.map(async (ck) => {\n try {\n const chain = registry.getChain(ck);\n const chainName = chain.name.toLowerCase();\n\n let assetAddr: Address;\n try {\n assetAddr = registry.resolveToken(chainName, asset).address;\n } catch {\n return [];\n }\n\n const protos = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending && p.interface === \"aave_v3\");\n\n if (protos.length === 0) return [];\n\n const rpc = chain.effectiveRpcUrl();\n const rates: unknown[] = [];\n\n for (const proto of protos) {\n try {\n const lending = createLending(proto, rpc);\n const r = await lending.getRates(assetAddr);\n if (r.supply_apy > 0) {\n rates.push({\n chain: chain.name,\n protocol: r.protocol,\n supply_apy: r.supply_apy,\n borrow_variable_apy: r.borrow_variable_apy,\n });\n }\n } catch {\n // skip\n }\n }\n\n return rates;\n } catch {\n return [];\n }\n });\n\n const nested = await Promise.all(tasks);\n const allRates = nested.flat() as Array<Record<string, unknown>>;\n\n // Sort by supply APY descending\n allRates.sort((a, b) => (b[\"supply_apy\"] as number ?? 0) - (a[\"supply_apy\"] as number ?? 0));\n\n const best =\n allRates.length > 0\n ? `${allRates[0][\"protocol\"]} on ${allRates[0][\"chain\"]}`\n : null;\n\n // Find arb opportunities (supply on A, borrow on B)\n const arbs: unknown[] = [];\n for (const s of allRates) {\n for (const b of allRates) {\n const sp = s[\"supply_apy\"] as number ?? 0;\n const bp = b[\"borrow_variable_apy\"] as number ?? 0;\n if (sp > bp && bp > 0) {\n const sc = s[\"chain\"] as string;\n const bc = b[\"chain\"] as string;\n const sp2 = s[\"protocol\"] as string;\n const bp2 = b[\"protocol\"] as string;\n if (sc !== bc || sp2 !== bp2) {\n arbs.push({\n spread_pct: Math.round((sp - bp) * 100) / 100,\n supply_chain: sc,\n supply_protocol: sp2,\n supply_apy: sp,\n borrow_chain: bc,\n borrow_protocol: bp2,\n borrow_apy: bp,\n strategy: sc === bc ? \"same-chain\" : \"cross-chain\",\n });\n }\n }\n }\n }\n\n arbs.sort((a, b) => {\n const as_ = (a as Record<string, unknown>)[\"spread_pct\"] as number ?? 0;\n const bs_ = (b as Record<string, unknown>)[\"spread_pct\"] as number ?? 0;\n return bs_ - as_;\n });\n arbs.splice(10); // Top 10\n\n printOutput(\n {\n asset,\n scan_duration_ms: Date.now() - t0,\n chains_scanned: chainKeys.length,\n rates: allRates,\n best_supply: best,\n arb_opportunities: arbs,\n },\n output,\n );\n}\n\n/** Scan rate entry with slug for execute subcommand */\ninterface ScanRate {\n chain: string;\n protocol: string;\n slug: string;\n supply_apy: number;\n borrow_variable_apy: number;\n}\n\n/** Run a cross-chain yield scan and return typed rate entries */\nasync function scanRatesForExecute(registry: Registry, asset: string): Promise<ScanRate[]> {\n const chainKeys = Array.from(registry.chains.keys());\n\n const tasks = chainKeys.map(async (ck): Promise<ScanRate[]> => {\n try {\n const chain = registry.getChain(ck);\n const chainName = chain.name.toLowerCase();\n let assetAddr: Address;\n try {\n assetAddr = registry.resolveToken(chainName, asset).address;\n } catch {\n return [];\n }\n const protos = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending && p.interface === \"aave_v3\");\n if (protos.length === 0) return [];\n const rpc = chain.effectiveRpcUrl();\n const rates: ScanRate[] = [];\n for (const proto of protos) {\n try {\n const lending = createLending(proto, rpc);\n const r = await lending.getRates(assetAddr);\n if (r.supply_apy > 0) {\n rates.push({\n chain: chain.name,\n protocol: r.protocol,\n slug: proto.slug,\n supply_apy: r.supply_apy,\n borrow_variable_apy: r.borrow_variable_apy,\n });\n }\n } catch {\n // skip unreachable\n }\n }\n return rates;\n } catch {\n return [];\n }\n });\n\n const nested = await Promise.all(tasks);\n const all = nested.flat();\n all.sort((a, b) => b.supply_apy - a.supply_apy);\n return all;\n}\n\nexport function registerYield(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const yieldCmd = parent\n .command(\"yield\")\n .description(\"Yield operations: compare, scan, optimize, execute\");\n\n // yield compare\n yieldCmd\n .command(\"compare\")\n .description(\"Compare lending rates across protocols for an asset\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n const chainName: string = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n const chain = registry.getChain(chainName);\n const rpc = chain.effectiveRpcUrl();\n const assetAddr = resolveAsset(registry, chainName, opts.asset as string);\n\n const results = await collectLendingRates(registry, chainName, rpc, assetAddr);\n\n if (results.length === 0) {\n printOutput(\n { error: `No lending rate data available for asset '${opts.asset}'` },\n getOpts(),\n );\n process.exit(1);\n return;\n }\n\n results.sort((a, b) => b.supply_apy - a.supply_apy);\n\n const bestSupply = results[0]?.protocol ?? null;\n const bestBorrow =\n results.reduce((best, r) => {\n if (!best || r.borrow_variable_apy < best.borrow_variable_apy) return r;\n return best;\n }, null as LendingRates | null)?.protocol ?? null;\n\n printOutput(\n {\n asset: opts.asset,\n rates: results,\n best_supply: bestSupply,\n best_borrow: bestBorrow,\n },\n getOpts(),\n );\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n process.exit(1);\n }\n });\n\n // yield scan\n yieldCmd\n .command(\"scan\")\n .description(\"Scan all chains for best yield opportunities (parallel)\")\n .requiredOption(\"--asset <token>\", \"Token symbol (e.g. USDC, WETH)\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n await runYieldScan(registry, opts.asset as string, getOpts());\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n process.exit(1);\n }\n });\n\n // yield execute\n yieldCmd\n .command(\"execute\")\n .description(\"Find the best yield opportunity and execute supply (or show cross-chain plan)\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address (e.g. USDC)\")\n .requiredOption(\"--amount <amount>\", \"Human-readable amount to supply (e.g. 1000)\")\n .option(\"--min-spread <percent>\", \"Minimum spread % required to execute cross-chain arb\", \"1.0\")\n .option(\"--target-chain <chain>\", \"Override auto-detected best chain\")\n .option(\"--target-protocol <protocol>\", \"Override auto-detected best protocol slug\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n const asset = opts.asset as string;\n const humanAmount = parseFloat(opts.amount as string);\n if (isNaN(humanAmount) || humanAmount <= 0) {\n printOutput({ error: `Invalid amount: ${opts.amount}` }, getOpts());\n process.exit(1);\n return;\n }\n const minSpread = parseFloat((opts.minSpread as string) ?? \"1.0\");\n\n let targetChainName: string;\n let targetProtocolSlug: string | undefined = opts.targetProtocol as string | undefined;\n\n if (opts.targetChain) {\n // Manual chain override — skip scan\n targetChainName = (opts.targetChain as string).toLowerCase();\n } else {\n // Run cross-chain scan to find best supply opportunity\n process.stderr.write(`Scanning all chains for best ${asset} yield...\\n`);\n const t0 = Date.now();\n const allRates = await scanRatesForExecute(registry, asset);\n process.stderr.write(`Scan done in ${Date.now() - t0}ms — ${allRates.length} rates found\\n`);\n\n if (allRates.length === 0) {\n printOutput({ error: `No yield opportunities found for ${asset}` }, getOpts());\n process.exit(1);\n return;\n }\n\n // Find best cross-chain arb (highest spread)\n let bestArb: {\n spread_pct: number;\n supply_chain: string;\n supply_protocol: string;\n supply_slug: string;\n supply_apy: number;\n borrow_chain: string;\n borrow_protocol: string;\n borrow_apy: number;\n strategy: string;\n } | null = null;\n\n for (const s of allRates) {\n for (const b of allRates) {\n const spread = s.supply_apy - b.borrow_variable_apy;\n if (spread > 0 && b.borrow_variable_apy > 0 && (s.chain !== b.chain || s.slug !== b.slug)) {\n if (!bestArb || spread > bestArb.spread_pct) {\n bestArb = {\n spread_pct: Math.round(spread * 10000) / 10000,\n supply_chain: s.chain,\n supply_protocol: s.protocol,\n supply_slug: s.slug,\n supply_apy: s.supply_apy,\n borrow_chain: b.chain,\n borrow_protocol: b.protocol,\n borrow_apy: b.borrow_variable_apy,\n strategy: s.chain === b.chain ? \"same-chain\" : \"cross-chain\",\n };\n }\n }\n }\n }\n\n // If best arb is cross-chain and meets min-spread: output plan only (no execution)\n if (bestArb && bestArb.strategy === \"cross-chain\" && bestArb.spread_pct >= minSpread) {\n const supplyChainLower = bestArb.supply_chain.toLowerCase();\n let supplyAssetAddr: Address | undefined;\n let supplyDecimals = 18;\n try {\n const tok = registry.resolveToken(supplyChainLower, asset);\n supplyAssetAddr = tok.address;\n supplyDecimals = tok.decimals;\n } catch {\n // leave as undefined\n }\n const amountWei = BigInt(Math.round(humanAmount * 10 ** supplyDecimals));\n\n printOutput(\n {\n mode: \"plan_only\",\n reason: \"cross-chain arb requires manual bridge execution\",\n asset,\n amount_human: humanAmount,\n amount_wei: amountWei.toString(),\n best_arb: bestArb,\n steps: [\n {\n step: 1,\n action: \"bridge\",\n description: `Bridge ${humanAmount} ${asset} from current chain to ${bestArb.supply_chain}`,\n from_chain: \"current\",\n to_chain: bestArb.supply_chain,\n token: asset,\n amount_wei: amountWei.toString(),\n },\n {\n step: 2,\n action: \"supply\",\n description: `Supply ${humanAmount} ${asset} on ${bestArb.supply_protocol}`,\n chain: bestArb.supply_chain,\n protocol: bestArb.supply_protocol,\n protocol_slug: bestArb.supply_slug,\n asset_address: supplyAssetAddr,\n amount_wei: amountWei.toString(),\n expected_apy: bestArb.supply_apy,\n },\n ],\n expected_spread_pct: bestArb.spread_pct,\n supply_apy: bestArb.supply_apy,\n borrow_apy: bestArb.borrow_apy,\n },\n getOpts(),\n );\n return;\n }\n\n // Fall through to same-chain supply on the best rate\n targetChainName = allRates[0].chain.toLowerCase();\n if (!targetProtocolSlug) {\n targetProtocolSlug = allRates[0].slug;\n }\n }\n\n // Same-chain supply execution path\n const chain = registry.getChain(targetChainName);\n const chainName = chain.name.toLowerCase();\n const rpc = chain.effectiveRpcUrl();\n\n // Resolve asset address + decimals on target chain\n let assetAddr: Address;\n let decimals = 18;\n try {\n const tok = registry.resolveToken(chainName, asset);\n assetAddr = tok.address;\n decimals = tok.decimals;\n } catch {\n if (/^0x[0-9a-fA-F]{40}$/.test(asset)) {\n assetAddr = asset as Address;\n } else {\n printOutput({ error: `Cannot resolve ${asset} on chain ${chainName}` }, getOpts());\n process.exit(1);\n return;\n }\n }\n\n const amountWei = BigInt(Math.round(humanAmount * 10 ** decimals));\n\n // Resolve protocol\n let proto: ReturnType<typeof registry.getProtocol>;\n if (targetProtocolSlug) {\n try {\n proto = registry.getProtocol(targetProtocolSlug);\n } catch {\n printOutput({ error: `Protocol not found: ${targetProtocolSlug}` }, getOpts());\n process.exit(1);\n return;\n }\n } else {\n // Pick the aave_v3 protocol on the target chain with highest supply APY\n const candidates = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending && p.interface === \"aave_v3\");\n if (candidates.length === 0) {\n printOutput({ error: `No aave_v3 lending protocol found on ${chainName}` }, getOpts());\n process.exit(1);\n return;\n }\n let bestRate: LendingRates | null = null;\n let bestProto = candidates[0];\n for (const c of candidates) {\n try {\n const lending = createLending(c, rpc);\n const r = await lending.getRates(assetAddr);\n if (!bestRate || r.supply_apy > bestRate.supply_apy) {\n bestRate = r;\n bestProto = c;\n }\n } catch {\n // skip\n }\n }\n proto = bestProto;\n }\n\n const onBehalfOf = (\n process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\"\n ) as Address;\n const adapter = createLending(proto, rpc);\n\n // Fetch current rate for display (non-fatal)\n let currentApy: number | undefined;\n try {\n const r = await adapter.getRates(assetAddr);\n currentApy = r.supply_apy;\n } catch {\n // non-fatal\n }\n\n process.stderr.write(\n `Supplying ${humanAmount} ${asset} (${amountWei} wei) on ${proto.name} (${chain.name})...\\n`,\n );\n\n const executor = makeExecutor();\n const tx = await adapter.buildSupply({\n protocol: proto.name,\n asset: assetAddr,\n amount: amountWei,\n on_behalf_of: onBehalfOf,\n });\n\n const result = await executor.execute(tx);\n\n printOutput(\n {\n action: \"yield_execute\",\n asset,\n amount_human: humanAmount,\n amount_wei: amountWei.toString(),\n chain: chain.name,\n protocol: proto.name,\n protocol_slug: proto.slug,\n supply_apy: currentApy,\n result,\n },\n getOpts(),\n );\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n process.exit(1);\n }\n });\n\n // yield optimize\n yieldCmd\n .command(\"optimize\")\n .description(\"Find the optimal yield strategy for an asset\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .option(\"--strategy <strategy>\", \"Strategy: best-supply, leverage-loop, auto\", \"auto\")\n .option(\"--amount <amount>\", \"Amount to deploy (for allocation breakdown)\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n const chainName: string = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n const chain = registry.getChain(chainName);\n const rpc = chain.effectiveRpcUrl();\n const asset = opts.asset as string;\n const assetAddr = resolveAsset(registry, chainName, asset);\n const strategy = (opts.strategy as string) ?? \"auto\";\n\n if (strategy === \"auto\") {\n const opportunities = await collectAllYields(registry, chainName, rpc, asset, assetAddr);\n\n if (opportunities.length === 0) {\n printOutput({ error: `No yield opportunities found for '${asset}'` }, getOpts());\n process.exit(1);\n return;\n }\n\n const amount = opts.amount ? parseFloat(opts.amount as string) : null;\n const weights = [0.6, 0.3, 0.1];\n const allocations =\n amount !== null\n ? opportunities.slice(0, weights.length).map((opp, i) => ({\n protocol: (opp as Record<string, unknown>)[\"protocol\"],\n type: (opp as Record<string, unknown>)[\"type\"],\n apy: (opp as Record<string, unknown>)[\"apy\"],\n allocation_pct: weights[i] * 100,\n amount: (amount * weights[i]).toFixed(2),\n }))\n : [];\n\n const best = opportunities[0] as Record<string, unknown>;\n const weightedApy =\n allocations.length > 0\n ? opportunities.slice(0, weights.length).reduce((sum: number, o, i) => {\n return sum + ((o as Record<string, unknown>)[\"apy\"] as number ?? 0) * weights[i];\n }, 0)\n : (best[\"apy\"] as number ?? 0);\n\n printOutput(\n {\n strategy: \"auto\",\n asset,\n best_protocol: best[\"protocol\"],\n best_apy: best[\"apy\"],\n weighted_apy: weightedApy,\n opportunities,\n allocation: allocations,\n },\n getOpts(),\n );\n } else if (strategy === \"best-supply\") {\n const results = await collectLendingRates(registry, chainName, rpc, assetAddr);\n\n if (results.length === 0) {\n printOutput({ error: `No lending rate data available for asset '${asset}'` }, getOpts());\n process.exit(1);\n return;\n }\n\n results.sort((a, b) => b.supply_apy - a.supply_apy);\n const best = results[0];\n const recommendations = results.map((r) => ({\n protocol: r.protocol,\n supply_apy: r.supply_apy,\n action: \"supply\",\n }));\n\n printOutput(\n {\n strategy: \"best-supply\",\n asset,\n recommendation: `Supply ${asset} on ${best.protocol} for ${(best.supply_apy * 100).toFixed(2)}% APY`,\n best_protocol: best.protocol,\n best_supply_apy: best.supply_apy,\n all_options: recommendations,\n },\n getOpts(),\n );\n } else if (strategy === \"leverage-loop\") {\n const results = await collectLendingRates(registry, chainName, rpc, assetAddr);\n\n if (results.length === 0) {\n printOutput({ error: `No lending rate data available for asset '${asset}'` }, getOpts());\n process.exit(1);\n return;\n }\n\n const ltv = 0.8;\n const loops = 5;\n const candidates: unknown[] = [];\n\n for (const r of results) {\n const threshold = r.borrow_variable_apy * 0.8;\n if (r.supply_apy > threshold && r.borrow_variable_apy > 0) {\n let effectiveSupplyApy = 0;\n let effectiveBorrowApy = 0;\n let leverage = 1.0;\n for (let l = 0; l < loops; l++) {\n effectiveSupplyApy += r.supply_apy * leverage;\n effectiveBorrowApy += r.borrow_variable_apy * leverage * ltv;\n leverage *= ltv;\n }\n candidates.push({\n protocol: r.protocol,\n supply_apy: r.supply_apy,\n borrow_variable_apy: r.borrow_variable_apy,\n loops,\n ltv,\n effective_supply_apy: effectiveSupplyApy,\n effective_borrow_cost: effectiveBorrowApy,\n net_apy: effectiveSupplyApy - effectiveBorrowApy,\n });\n }\n }\n\n candidates.sort((a, b) => {\n const an = (a as Record<string, unknown>)[\"net_apy\"] as number ?? 0;\n const bn = (b as Record<string, unknown>)[\"net_apy\"] as number ?? 0;\n return bn - an;\n });\n\n const recommendation =\n candidates.length > 0\n ? (() => {\n const b = candidates[0] as Record<string, unknown>;\n return `Leverage loop ${asset} on ${b[\"protocol\"]} — net APY: ${((b[\"net_apy\"] as number) * 100).toFixed(2)}% (${loops} loops at ${ltv * 100}% LTV)`;\n })()\n : `No favorable leverage loop found for ${asset} — supply rate too low relative to borrow rate`;\n\n printOutput(\n {\n strategy: \"leverage-loop\",\n asset,\n recommendation,\n candidates,\n },\n getOpts(),\n );\n } else {\n printOutput(\n { error: `Unknown strategy '${strategy}'. Supported: best-supply, leverage-loop, auto` },\n getOpts(),\n );\n process.exit(1);\n }\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n process.exit(1);\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport { Registry, ProtocolCategory, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { takeSnapshot, saveSnapshot, loadSnapshots, calculatePnL } from \"../portfolio-tracker.js\";\n\nconst ERC20_ABI = parseAbi([\n \"function balanceOf(address owner) external view returns (uint256)\",\n]);\n\nconst POOL_ABI = parseAbi([\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n]);\n\nfunction decodeU256(data: Hex | null, wordOffset = 0): bigint {\n if (!data || data.length < 2 + (wordOffset + 1) * 64) return 0n;\n const hex = data.slice(2 + wordOffset * 64, 2 + wordOffset * 64 + 64);\n return BigInt(\"0x\" + hex);\n}\n\nexport function registerPortfolio(parent: Command, getOpts: () => OutputMode): void {\n const portfolio = parent\n .command(\"portfolio\")\n .description(\"Aggregate positions across all protocols\");\n\n // Show current positions\n portfolio\n .command(\"show\")\n .description(\"Show current portfolio positions\")\n .requiredOption(\"--address <address>\", \"Wallet address to query\")\n .action(async (opts: { address: string }) => {\n\n const mode = getOpts();\n const registry = Registry.loadEmbedded();\n const chainName = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n\n let chain;\n try {\n chain = registry.getChain(chainName);\n } catch (e) {\n printOutput({ error: `Chain not found: ${chainName}` }, mode);\n return;\n }\n\n const user = opts.address as Address;\n if (!/^0x[0-9a-fA-F]{40}$/.test(user)) {\n printOutput({ error: `Invalid address: ${opts.address}` }, mode);\n return;\n }\n\n const rpc = chain.effectiveRpcUrl();\n const calls: Array<[Address, Hex]> = [];\n const callLabels: string[] = [];\n\n // 1. Token balances\n const tokenSymbols: string[] = (registry.tokens.get(chainName) ?? []).map((t) => t.symbol);\n\n for (const symbol of tokenSymbols) {\n let entry;\n try {\n entry = registry.resolveToken(chainName, symbol);\n } catch {\n continue;\n }\n if (entry.address === (\"0x0000000000000000000000000000000000000000\" as Address)) continue;\n calls.push([\n entry.address as Address,\n encodeFunctionData({ abi: ERC20_ABI, functionName: \"balanceOf\", args: [user] }),\n ]);\n callLabels.push(`balance:${symbol}`);\n }\n\n // 2. Lending positions — aave_v3 pools\n const lendingProtocols = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending && p.interface === \"aave_v3\")\n .filter((p) => p.contracts?.[\"pool\"]);\n\n for (const p of lendingProtocols) {\n calls.push([\n p.contracts![\"pool\"] as Address,\n encodeFunctionData({ abi: POOL_ABI, functionName: \"getUserAccountData\", args: [user] }),\n ]);\n callLabels.push(`lending:${p.name}`);\n }\n\n // 3. Native token price from first available oracle\n const oracleEntry = registry\n .getProtocolsForChain(chainName)\n .find((p) => p.interface === \"aave_v3\" && p.contracts?.[\"oracle\"]);\n const oracleAddr = oracleEntry?.contracts?.[\"oracle\"] as Address | undefined;\n const wrappedNative = (chain.wrapped_native ?? \"0x5555555555555555555555555555555555555555\") as Address;\n\n if (oracleAddr) {\n calls.push([\n oracleAddr,\n encodeFunctionData({ abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [wrappedNative] }),\n ]);\n callLabels.push(\"price:native\");\n }\n\n if (calls.length === 0) {\n printOutput(\n {\n address: user,\n chain: chain.name,\n error: \"No protocols or tokens configured for this chain\",\n },\n mode,\n );\n return;\n }\n\n let results: (Hex | null)[];\n try {\n results = await multicallRead(rpc, calls);\n } catch (e) {\n printOutput({ error: `Multicall failed: ${e instanceof Error ? e.message : String(e)}` }, mode);\n return;\n }\n\n // Get native price (last call if oracle present)\n let nativePriceUsd = 0;\n if (oracleAddr) {\n const priceData = results[results.length - 1] ?? null;\n nativePriceUsd = Number(decodeU256(priceData)) / 1e8;\n }\n\n let totalValueUsd = 0;\n let idx = 0;\n const tokenBalances: unknown[] = [];\n\n // Parse token balances\n for (const symbol of tokenSymbols) {\n let entry;\n try {\n entry = registry.resolveToken(chainName, symbol);\n } catch {\n continue;\n }\n if (entry.address === (\"0x0000000000000000000000000000000000000000\" as Address)) continue;\n if (idx >= results.length) break;\n\n const balance = decodeU256(results[idx] ?? null);\n if (balance > 0n) {\n const decimals = entry.decimals;\n const balF64 = Number(balance) / 10 ** decimals;\n const symbolUpper = symbol.toUpperCase();\n const valueUsd =\n symbolUpper.includes(\"USD\") || symbolUpper.includes(\"usd\")\n ? balF64\n : balF64 * nativePriceUsd;\n totalValueUsd += valueUsd;\n tokenBalances.push({\n symbol,\n balance: balF64.toFixed(4),\n value_usd: valueUsd.toFixed(2),\n });\n }\n idx++;\n }\n\n // Parse lending positions\n const lendingPositions: unknown[] = [];\n for (const p of lendingProtocols) {\n if (idx >= results.length) break;\n const data = results[idx] ?? null;\n if (data && data.length >= 2 + 192 * 2) {\n const collateral = Number(decodeU256(data, 0)) / 1e8;\n const debt = Number(decodeU256(data, 1)) / 1e8;\n const hfRaw = decodeU256(data, 5);\n let hf: number | null = null;\n if (hfRaw <= BigInt(\"0xffffffffffffffffffffffffffffffff\")) {\n const v = Number(hfRaw) / 1e18;\n hf = v > 1e10 ? null : v;\n }\n if (collateral > 0 || debt > 0) {\n totalValueUsd += collateral - debt;\n lendingPositions.push({\n protocol: p.name,\n collateral_usd: collateral.toFixed(2),\n debt_usd: debt.toFixed(2),\n health_factor: hf,\n });\n }\n }\n idx++;\n }\n\n printOutput(\n {\n address: user,\n chain: chain.name,\n native_price_usd: nativePriceUsd.toFixed(2),\n total_value_usd: totalValueUsd.toFixed(2),\n token_balances: tokenBalances,\n lending_positions: lendingPositions,\n },\n mode,\n );\n });\n\n // --- Subcommand: snapshot ---\n portfolio\n .command(\"snapshot\")\n .description(\"Take a new portfolio snapshot and save it locally\")\n .requiredOption(\"--address <address>\", \"Wallet address to snapshot\")\n .action(async (opts: { address: string }) => {\n const mode = getOpts();\n const chainName = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n const registry = Registry.loadEmbedded();\n\n if (!/^0x[0-9a-fA-F]{40}$/.test(opts.address)) {\n printOutput({ error: `Invalid address: ${opts.address}` }, mode);\n return;\n }\n\n try {\n const snapshot = await takeSnapshot(chainName, opts.address, registry);\n const filepath = saveSnapshot(snapshot);\n printOutput(\n {\n saved: filepath,\n timestamp: new Date(snapshot.timestamp).toISOString(),\n chain: snapshot.chain,\n wallet: snapshot.wallet,\n total_value_usd: snapshot.total_value_usd.toFixed(2),\n token_count: snapshot.tokens.length,\n defi_position_count: snapshot.defi_positions.length,\n },\n mode,\n );\n } catch (e) {\n printOutput({ error: e instanceof Error ? e.message : String(e) }, mode);\n }\n });\n\n // --- Subcommand: pnl ---\n portfolio\n .command(\"pnl\")\n .description(\"Show PnL since the last snapshot\")\n .requiredOption(\"--address <address>\", \"Wallet address\")\n .option(\"--since <hours>\", \"Compare against snapshot from N hours ago (default: last snapshot)\")\n .action(async (opts: { address: string; since?: string }) => {\n const mode = getOpts();\n const chainName = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n const registry = Registry.loadEmbedded();\n\n if (!/^0x[0-9a-fA-F]{40}$/.test(opts.address)) {\n printOutput({ error: `Invalid address: ${opts.address}` }, mode);\n return;\n }\n\n const snapshots = loadSnapshots(chainName, opts.address, 50);\n if (snapshots.length === 0) {\n printOutput({ error: \"No snapshots found. Run `portfolio snapshot` first.\" }, mode);\n return;\n }\n\n let previous = snapshots[0];\n if (opts.since) {\n const sinceMs = parseFloat(opts.since) * 60 * 60 * 1000;\n const cutoff = Date.now() - sinceMs;\n const match = snapshots.find((s) => s.timestamp <= cutoff);\n if (!match) {\n printOutput({ error: `No snapshot found older than ${opts.since} hours` }, mode);\n return;\n }\n previous = match;\n }\n\n try {\n const current = await takeSnapshot(chainName, opts.address, registry);\n const pnl = calculatePnL(current, previous);\n printOutput(\n {\n chain: chainName,\n wallet: opts.address,\n previous_snapshot: new Date(previous.timestamp).toISOString(),\n current_time: new Date(current.timestamp).toISOString(),\n ...pnl,\n pnl_usd: pnl.pnl_usd.toFixed(2),\n pnl_pct: pnl.pnl_pct.toFixed(4),\n start_value_usd: pnl.start_value_usd.toFixed(2),\n end_value_usd: pnl.end_value_usd.toFixed(2),\n },\n mode,\n );\n } catch (e) {\n printOutput({ error: e instanceof Error ? e.message : String(e) }, mode);\n }\n });\n\n // --- Subcommand: history ---\n portfolio\n .command(\"history\")\n .description(\"List saved portfolio snapshots with values\")\n .requiredOption(\"--address <address>\", \"Wallet address\")\n .option(\"--limit <n>\", \"Number of snapshots to show\", \"10\")\n .action(async (opts: { address: string; limit: string }) => {\n const mode = getOpts();\n const chainName = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n\n if (!/^0x[0-9a-fA-F]{40}$/.test(opts.address)) {\n printOutput({ error: `Invalid address: ${opts.address}` }, mode);\n return;\n }\n\n const limit = parseInt(opts.limit, 10);\n const snapshots = loadSnapshots(chainName, opts.address, limit);\n\n if (snapshots.length === 0) {\n printOutput({ message: \"No snapshots found for this address on this chain.\" }, mode);\n return;\n }\n\n const history = snapshots.map((s) => ({\n timestamp: new Date(s.timestamp).toISOString(),\n chain: s.chain,\n wallet: s.wallet,\n total_value_usd: s.total_value_usd.toFixed(2),\n token_count: s.tokens.length,\n defi_position_count: s.defi_positions.length,\n }));\n\n printOutput({ snapshots: history }, mode);\n });\n}\n","import { mkdirSync, writeFileSync, readdirSync, readFileSync, existsSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { resolve } from \"path\";\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport { Registry, ProtocolCategory, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { PortfolioSnapshot, TokenBalance, DefiPosition, PortfolioPnL, TokenChange } from \"@hypurrquant/defi-core\";\n\nconst ERC20_ABI = parseAbi([\n \"function balanceOf(address owner) external view returns (uint256)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n]);\n\nconst POOL_ABI = parseAbi([\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n]);\n\nfunction decodeU256Word(data: Hex | null, wordOffset = 0): bigint {\n if (!data || data.length < 2 + (wordOffset + 1) * 64) return 0n;\n const hex = data.slice(2 + wordOffset * 64, 2 + wordOffset * 64 + 64);\n return BigInt(\"0x\" + hex);\n}\n\nfunction snapshotDir(): string {\n return resolve(homedir(), \".defi-cli\", \"snapshots\");\n}\n\nexport async function takeSnapshot(\n chainName: string,\n wallet: string,\n registry: Registry,\n): Promise<PortfolioSnapshot> {\n const chain = registry.getChain(chainName);\n const user = wallet as Address;\n const rpc = chain.effectiveRpcUrl();\n\n const calls: Array<[Address, Hex]> = [];\n const callLabels: string[] = [];\n\n // 1. Token balances\n const tokenEntries: Array<{ symbol: string; address: Address; decimals: number }> = [];\n for (const t of registry.tokens.get(chainName) ?? []) {\n let entry;\n try {\n entry = registry.resolveToken(chainName, t.symbol);\n } catch {\n continue;\n }\n if (entry.address === (\"0x0000000000000000000000000000000000000000\" as Address)) continue;\n tokenEntries.push({ symbol: t.symbol, address: entry.address as Address, decimals: entry.decimals });\n calls.push([\n entry.address as Address,\n encodeFunctionData({ abi: ERC20_ABI, functionName: \"balanceOf\", args: [user] }),\n ]);\n callLabels.push(`balance:${t.symbol}`);\n }\n\n // 2. Lending positions (aave_v3)\n const lendingProtocols = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending && p.interface === \"aave_v3\")\n .filter((p) => p.contracts?.[\"pool\"]);\n\n for (const p of lendingProtocols) {\n calls.push([\n p.contracts![\"pool\"] as Address,\n encodeFunctionData({ abi: POOL_ABI, functionName: \"getUserAccountData\", args: [user] }),\n ]);\n callLabels.push(`lending:${p.name}`);\n }\n\n // 3. Native price from oracle\n const oracleEntry = registry\n .getProtocolsForChain(chainName)\n .find((p) => p.interface === \"aave_v3\" && p.contracts?.[\"oracle\"]);\n const oracleAddr = oracleEntry?.contracts?.[\"oracle\"] as Address | undefined;\n const wrappedNative = (chain.wrapped_native ?? \"0x5555555555555555555555555555555555555555\") as Address;\n\n if (oracleAddr) {\n calls.push([\n oracleAddr,\n encodeFunctionData({ abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [wrappedNative] }),\n ]);\n callLabels.push(\"price:native\");\n }\n\n let results: (Hex | null)[] = calls.map(() => null);\n if (calls.length > 0) {\n results = await multicallRead(rpc, calls);\n }\n\n // Native price\n let nativePriceUsd = 0;\n if (oracleAddr) {\n const priceData = results[results.length - 1] ?? null;\n nativePriceUsd = Number(decodeU256Word(priceData)) / 1e8;\n }\n\n let idx = 0;\n const tokens: TokenBalance[] = [];\n let totalValueUsd = 0;\n\n // Parse token balances\n for (const entry of tokenEntries) {\n if (idx >= results.length) break;\n const balance = decodeU256Word(results[idx] ?? null);\n const balF64 = Number(balance) / 10 ** entry.decimals;\n const symbolUpper = entry.symbol.toUpperCase();\n const priceUsd =\n symbolUpper.includes(\"USD\") ? 1 : nativePriceUsd;\n const valueUsd = balF64 * priceUsd;\n totalValueUsd += valueUsd;\n tokens.push({\n token: entry.address,\n symbol: entry.symbol,\n balance,\n value_usd: valueUsd,\n price_usd: priceUsd,\n });\n idx++;\n }\n\n // Parse lending positions\n const defiPositions: DefiPosition[] = [];\n for (const p of lendingProtocols) {\n if (idx >= results.length) break;\n const data = results[idx] ?? null;\n if (data && data.length >= 2 + 192 * 2) {\n const collateral = Number(decodeU256Word(data, 0)) / 1e8;\n const debt = Number(decodeU256Word(data, 1)) / 1e8;\n if (collateral > 0) {\n totalValueUsd += collateral;\n defiPositions.push({\n protocol: p.name,\n type: \"lending_supply\",\n asset: \"collateral\",\n amount: BigInt(Math.round(collateral * 1e8)),\n value_usd: collateral,\n });\n }\n if (debt > 0) {\n totalValueUsd -= debt;\n defiPositions.push({\n protocol: p.name,\n type: \"lending_borrow\",\n asset: \"debt\",\n amount: BigInt(Math.round(debt * 1e8)),\n value_usd: debt,\n });\n }\n }\n idx++;\n }\n\n return {\n timestamp: Date.now(),\n chain: chainName,\n wallet,\n tokens,\n defi_positions: defiPositions,\n total_value_usd: totalValueUsd,\n };\n}\n\nexport function saveSnapshot(snapshot: PortfolioSnapshot): string {\n const dir = snapshotDir();\n mkdirSync(dir, { recursive: true });\n const filename = `${snapshot.chain}_${snapshot.wallet}_${snapshot.timestamp}.json`;\n const filepath = resolve(dir, filename);\n writeFileSync(filepath, JSON.stringify(snapshot, (_k, v) => (typeof v === \"bigint\" ? v.toString() : v), 2));\n return filepath;\n}\n\nexport function loadSnapshots(chain: string, wallet: string, limit = 10): PortfolioSnapshot[] {\n const dir = snapshotDir();\n if (!existsSync(dir)) return [];\n\n const prefix = `${chain}_${wallet}_`;\n const files = readdirSync(dir)\n .filter((f) => f.startsWith(prefix) && f.endsWith(\".json\"))\n .sort()\n .reverse()\n .slice(0, limit);\n\n return files.map((f) => {\n const raw = JSON.parse(readFileSync(resolve(dir, f), \"utf-8\"));\n // Restore bigint fields\n if (Array.isArray(raw.tokens)) {\n for (const t of raw.tokens) {\n if (typeof t.balance === \"string\") t.balance = BigInt(t.balance);\n }\n }\n if (Array.isArray(raw.defi_positions)) {\n for (const p of raw.defi_positions) {\n if (typeof p.amount === \"string\") p.amount = BigInt(p.amount);\n }\n }\n return raw as PortfolioSnapshot;\n });\n}\n\nexport function calculatePnL(current: PortfolioSnapshot, previous: PortfolioSnapshot): PortfolioPnL {\n const startValue = previous.total_value_usd;\n const endValue = current.total_value_usd;\n const pnlUsd = endValue - startValue;\n const pnlPct = startValue !== 0 ? (pnlUsd / startValue) * 100 : 0;\n\n const prevTokenMap = new Map<string, TokenBalance>();\n for (const t of previous.tokens) {\n prevTokenMap.set(t.symbol, t);\n }\n\n const tokenChanges: TokenChange[] = [];\n for (const t of current.tokens) {\n const prev = prevTokenMap.get(t.symbol);\n const prevBalance = prev?.balance ?? 0n;\n const prevValueUsd = prev?.value_usd ?? 0;\n const balanceChange = t.balance - prevBalance;\n const valueChangeUsd = t.value_usd - prevValueUsd;\n if (balanceChange !== 0n || Math.abs(valueChangeUsd) > 0.001) {\n tokenChanges.push({\n symbol: t.symbol,\n balance_change: balanceChange,\n value_change_usd: valueChangeUsd,\n });\n }\n }\n\n const durationMs = current.timestamp - previous.timestamp;\n const durationHours = durationMs / (1000 * 60 * 60);\n const period =\n durationHours < 1\n ? `${Math.round(durationMs / 60000)}m`\n : durationHours < 24\n ? `${durationHours.toFixed(1)}h`\n : `${(durationHours / 24).toFixed(1)}d`;\n\n return {\n period,\n start_value_usd: startValue,\n end_value_usd: endValue,\n pnl_usd: pnlUsd,\n pnl_pct: pnlPct,\n token_changes: tokenChanges,\n };\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry, ProtocolCategory } from \"@hypurrquant/defi-core\";\nimport { createLending } from \"@hypurrquant/defi-protocols\";\nimport type { Address } from \"viem\";\n\ninterface PositionResult {\n chain: string;\n protocol: string;\n health_factor: number;\n total_supply_usd: number;\n total_borrow_usd: number;\n alert: boolean;\n}\n\nasync function checkChainLendingPositions(\n chainKey: string,\n registry: Registry,\n address: Address,\n threshold: number,\n): Promise<PositionResult[]> {\n let chain;\n try {\n chain = registry.getChain(chainKey);\n } catch {\n return [];\n }\n\n const rpc = chain.effectiveRpcUrl();\n const chainName = chain.name;\n const protocols = registry.getProtocolsForChain(chainKey).filter(\n (p) => p.category === ProtocolCategory.Lending,\n );\n\n const results = await Promise.all(\n protocols.map(async (proto): Promise<PositionResult | null> => {\n try {\n const adapter = createLending(proto, rpc);\n const position = await adapter.getUserPosition(address);\n const hf = position.health_factor ?? Infinity;\n\n // Skip positions with no borrows (no liquidation risk)\n const totalBorrow = position.borrows?.reduce(\n (sum, b) => sum + (b.value_usd ?? 0),\n 0,\n ) ?? 0;\n if (totalBorrow === 0) return null;\n\n const totalSupply = position.supplies?.reduce(\n (sum, s) => sum + (s.value_usd ?? 0),\n 0,\n ) ?? 0;\n\n return {\n chain: chainName,\n protocol: proto.name,\n health_factor: hf === Infinity ? 999999 : Math.round(hf * 100) / 100,\n total_supply_usd: Math.round(totalSupply * 100) / 100,\n total_borrow_usd: Math.round(totalBorrow * 100) / 100,\n alert: hf < threshold,\n };\n } catch {\n return null;\n }\n }),\n );\n\n return results.filter((r): r is PositionResult => r !== null);\n}\n\nexport function registerMonitor(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"monitor\")\n .description(\"Monitor health factor with alerts\")\n .option(\"--protocol <protocol>\", \"Protocol slug (required unless --all-chains)\")\n .requiredOption(\"--address <address>\", \"Wallet address to monitor\")\n .option(\"--threshold <hf>\", \"Health factor alert threshold\", \"1.5\")\n .option(\"--interval <secs>\", \"Polling interval in seconds\", \"60\")\n .option(\"--once\", \"Run once instead of continuously\")\n .option(\"--all-chains\", \"Scan all chains for lending positions\")\n .action(async (opts) => {\n const threshold = parseFloat(opts.threshold);\n const address = opts.address as Address;\n\n if (opts.allChains) {\n // Multi-chain mode\n const registry = Registry.loadEmbedded();\n const chainKeys = Array.from(registry.chains.keys());\n\n const poll = async () => {\n const timestamp = new Date().toISOString();\n\n const chainResults = await Promise.all(\n chainKeys.map((ck) =>\n checkChainLendingPositions(ck, registry, address, threshold),\n ),\n );\n\n const positions = chainResults.flat();\n const alertsCount = positions.filter((p) => p.alert).length;\n\n const output = {\n timestamp,\n address,\n threshold,\n positions,\n alerts_count: alertsCount,\n };\n\n // Write alerts to stderr for visibility\n for (const pos of positions) {\n if (pos.alert) {\n process.stderr.write(\n `ALERT: ${pos.chain}/${pos.protocol} HF=${pos.health_factor} < ${threshold}\\n`,\n );\n }\n }\n\n printOutput(output, getOpts());\n };\n\n await poll();\n if (!opts.once) {\n const intervalMs = parseInt(opts.interval) * 1000;\n const timer = setInterval(poll, intervalMs);\n process.on(\"SIGINT\", () => { clearInterval(timer); process.exit(0); });\n }\n } else {\n // Single-protocol mode (backward compat)\n if (!opts.protocol) {\n printOutput({ error: \"Either --protocol or --all-chains is required\" }, getOpts());\n process.exit(1);\n }\n\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n\n const poll = async () => {\n try {\n const position = await adapter.getUserPosition(address);\n const hf = position.health_factor ?? Infinity;\n const alert = hf < threshold;\n printOutput({\n protocol: protocol.name,\n user: opts.address,\n health_factor: hf,\n threshold,\n alert,\n timestamp: new Date().toISOString(),\n supplies: position.supplies,\n borrows: position.borrows,\n }, getOpts());\n } catch (e) {\n printOutput({\n error: e instanceof Error ? e.message : String(e),\n protocol: protocol.name,\n timestamp: new Date().toISOString(),\n }, getOpts());\n }\n };\n\n await poll();\n if (!opts.once) {\n const intervalMs = parseInt(opts.interval) * 1000;\n const timer = setInterval(poll, intervalMs);\n process.on(\"SIGINT\", () => { clearInterval(timer); process.exit(0); });\n }\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport { createDex } from \"@hypurrquant/defi-protocols\";\nimport { createLending } from \"@hypurrquant/defi-protocols\";\n\nexport function registerAlert(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"alert\")\n .description(\"Alert on DEX vs Oracle price deviation\")\n .option(\"--threshold <pct>\", \"Deviation threshold in percent\", \"5.0\")\n .option(\"--once\", \"Run once instead of continuously\")\n .option(\"--interval <secs>\", \"Polling interval in seconds\", \"60\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const rpcUrl = chain.effectiveRpcUrl();\n const threshold = parseFloat(opts.threshold);\n\n const dexProtocols = registry.getProtocolsByCategory(\"dex\" as any).filter(p => p.chain === chainName);\n const lendingProtocols = registry.getProtocolsByCategory(\"lending\" as any).filter(p => p.chain === chainName);\n\n const poll = async () => {\n const alerts: Array<{ protocol: string; type: string; message: string }> = [];\n\n for (const p of dexProtocols) {\n try {\n const dex = createDex(p, rpcUrl);\n alerts.push({\n protocol: p.name,\n type: \"info\",\n message: `DEX ${dex.name()} active on ${chainName}`,\n });\n } catch { /* skip unsupported */ }\n }\n\n printOutput({\n chain: chainName,\n threshold_pct: threshold,\n alerts,\n timestamp: new Date().toISOString(),\n }, getOpts());\n };\n\n await poll();\n if (!opts.once) {\n const intervalMs = parseInt(opts.interval) * 1000;\n const timer = setInterval(poll, intervalMs);\n process.on(\"SIGINT\", () => { clearInterval(timer); process.exit(0); });\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport { Registry, ProtocolCategory, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\n\n// ABI fragments for scan\nconst AAVE_ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n]);\n\nconst UNIV2_ROUTER_ABI = parseAbi([\n \"function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory)\",\n]);\n\nconst VTOKEN_ABI = parseAbi([\n \"function exchangeRateStored() external view returns (uint256)\",\n]);\n\nconst STABLECOINS = new Set([\"USDC\", \"USDT\", \"DAI\", \"USDT0\"]);\n\n// Rounding helpers\nfunction round2(x: number): number { return Math.round(x * 100) / 100; }\nfunction round4(x: number): number { return Math.round(x * 10000) / 10000; }\nfunction round6(x: number): number { return Math.round(x * 1000000) / 1000000; }\n\n/** Parse a uint256 return from multicall (first 32 bytes) */\nfunction parseU256F64(data: Hex | null, decimals: number): number {\n if (!data || data.length < 66) return 0;\n const raw = BigInt(data.slice(0, 66));\n return Number(raw) / 10 ** decimals;\n}\n\n/**\n * Parse the last element of a getAmountsOut return array.\n * ABI encoding: offset(32) + length(32) + elements[N * 32]\n * We want the last element.\n */\nfunction parseAmountsOutLast(data: Hex | null, outDecimals: number): number {\n if (!data) return 0;\n // Strip 0x prefix\n const hex = data.startsWith(\"0x\") ? data.slice(2) : data;\n // Minimum: 128 hex chars = 64 bytes = offset(32) + length(32)\n if (hex.length < 128) return 0;\n // Array length is at bytes 32..64 (hex chars 64..128)\n const num = parseInt(hex.slice(64, 128), 16);\n if (num === 0) return 0;\n // Last element is at offset: 64 bytes header + (num-1)*32 bytes\n const byteOff = 64 + (num - 1) * 32;\n const hexOff = byteOff * 2;\n if (hex.length < hexOff + 64) return 0;\n const val = BigInt(\"0x\" + hex.slice(hexOff, hexOff + 64));\n return Number(val) / 10 ** outDecimals;\n}\n\ntype CallType =\n | { kind: \"oracle\"; oracle: string; token: string; oracleDecimals: number }\n | { kind: \"dex\"; token: string; outDecimals: number }\n | { kind: \"stable\"; from: string; to: string; outDecimals: number }\n | { kind: \"exchangeRate\"; protocol: string; vtoken: string };\n\nexport function registerScan(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"scan\")\n .description(\"Multi-pattern exploit detection scanner\")\n .option(\"--chain <chain>\", \"Chain to scan\", \"hyperevm\")\n .option(\"--patterns <patterns>\", \"Comma-separated patterns: oracle,stable,exchange_rate\", \"oracle,stable,exchange_rate\")\n .option(\"--oracle-threshold <pct>\", \"Oracle divergence threshold (percent)\", \"5.0\")\n .option(\"--stable-threshold <price>\", \"Stablecoin depeg threshold (min price)\", \"0.98\")\n .option(\"--rate-threshold <pct>\", \"Exchange rate change threshold (percent)\", \"5.0\")\n .option(\"--interval <secs>\", \"Polling interval in seconds\", \"30\")\n .option(\"--once\", \"Single check then exit\")\n .option(\"--all-chains\", \"Scan all chains in parallel\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n const oracleThreshold = parseFloat(opts.oracleThreshold ?? \"5.0\");\n const stableThreshold = parseFloat(opts.stableThreshold ?? \"0.98\");\n const rateThreshold = parseFloat(opts.rateThreshold ?? \"5.0\");\n const interval = parseInt(opts.interval ?? \"30\", 10);\n const patterns: string = opts.patterns ?? \"oracle,stable,exchange_rate\";\n const once: boolean = !!opts.once;\n\n if (opts.allChains) {\n const result = await runAllChains(registry, patterns, oracleThreshold, stableThreshold, rateThreshold);\n printOutput(result, getOpts());\n return;\n }\n\n const chainName: string = (opts.chain ?? \"hyperevm\").toLowerCase();\n const chain = registry.getChain(chainName);\n const rpc = chain.effectiveRpcUrl();\n\n const pats = patterns.split(\",\").map((s: string) => s.trim());\n const doOracle = pats.includes(\"oracle\");\n const doStable = pats.includes(\"stable\");\n const doRate = pats.includes(\"exchange_rate\");\n\n // Discover chain resources\n const allTokens = registry.tokens.get(chainName) ?? [];\n const wrappedNative = chain.wrapped_native as Address | undefined;\n\n const quoteStable = (() => {\n for (const sym of [\"USDT\", \"USDC\", \"USDT0\"]) {\n try { return registry.resolveToken(chainName, sym); } catch { /* continue */ }\n }\n return null;\n })();\n\n if (!quoteStable) {\n printOutput({ error: `No stablecoin found on chain ${chainName}` }, getOpts());\n return;\n }\n\n const scanTokens = allTokens.filter(\n (t) => t.address !== \"0x0000000000000000000000000000000000000000\" && !STABLECOINS.has(t.symbol),\n );\n\n // Aave oracles\n const oracles: Array<{ name: string; addr: Address; decimals: number }> = registry\n .getProtocolsForChain(chainName)\n .filter(\n (p) =>\n p.category === ProtocolCategory.Lending &&\n (p.interface === \"aave_v3\" || p.interface === \"aave_v2\" || p.interface === \"aave_v3_isolated\"),\n )\n .flatMap((p) => {\n const oracleAddr = p.contracts?.[\"oracle\"];\n if (!oracleAddr) return [];\n const decimals = p.interface === \"aave_v2\" ? 18 : 8;\n return [{ name: p.name, addr: oracleAddr, decimals }];\n });\n\n // First uniswap_v2 DEX router\n const dexProto = registry\n .getProtocolsForChain(chainName)\n .find((p) => p.category === ProtocolCategory.Dex && p.interface === \"uniswap_v2\");\n const dexRouter = dexProto?.contracts?.[\"router\"] as Address | undefined;\n\n // Compound V2 forks (Venus, Sonne)\n const compoundForks = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending && p.interface === \"compound_v2\")\n .map((p) => ({\n name: p.name,\n vtokens: Object.entries(p.contracts ?? {}).filter(([k]) => k.startsWith(\"v\")).map(([k, a]) => ({ key: k, addr: a as Address })),\n }));\n\n const usdc = (() => { try { return registry.resolveToken(chainName, \"USDC\"); } catch { return null; } })();\n const usdt = (() => { try { return registry.resolveToken(chainName, \"USDT\"); } catch { return null; } })();\n\n // Track prev exchange rates across iterations\n const prevRates = new Map<string, number>();\n\n const runOnce = async () => {\n const timestamp = Math.floor(Date.now() / 1000);\n const t0 = Date.now();\n\n const calls: Array<[Address, Hex]> = [];\n const callTypes: CallType[] = [];\n\n // P1: Oracle + DEX price calls\n if (doOracle) {\n for (const oracle of oracles) {\n for (const token of scanTokens) {\n callTypes.push({ kind: \"oracle\", oracle: oracle.name, token: token.symbol, oracleDecimals: oracle.decimals });\n calls.push([\n oracle.addr,\n encodeFunctionData({ abi: AAVE_ORACLE_ABI, functionName: \"getAssetPrice\", args: [token.address] }),\n ]);\n }\n }\n\n if (dexRouter) {\n for (const token of scanTokens) {\n const amountIn = BigInt(10) ** BigInt(token.decimals);\n const path: Address[] =\n wrappedNative && token.address.toLowerCase() === wrappedNative.toLowerCase()\n ? [token.address, quoteStable.address]\n : wrappedNative\n ? [token.address, wrappedNative, quoteStable.address]\n : [token.address, quoteStable.address];\n callTypes.push({ kind: \"dex\", token: token.symbol, outDecimals: quoteStable.decimals });\n calls.push([\n dexRouter,\n encodeFunctionData({ abi: UNIV2_ROUTER_ABI, functionName: \"getAmountsOut\", args: [amountIn, path] }),\n ]);\n }\n }\n }\n\n // P2: Stablecoin cross-peg calls\n if (doStable && usdc && usdt && dexRouter) {\n callTypes.push({ kind: \"stable\", from: \"USDC\", to: \"USDT\", outDecimals: usdt.decimals });\n calls.push([\n dexRouter,\n encodeFunctionData({\n abi: UNIV2_ROUTER_ABI,\n functionName: \"getAmountsOut\",\n args: [BigInt(10) ** BigInt(usdc.decimals), [usdc.address, usdt.address]],\n }),\n ]);\n callTypes.push({ kind: \"stable\", from: \"USDT\", to: \"USDC\", outDecimals: usdc.decimals });\n calls.push([\n dexRouter,\n encodeFunctionData({\n abi: UNIV2_ROUTER_ABI,\n functionName: \"getAmountsOut\",\n args: [BigInt(10) ** BigInt(usdt.decimals), [usdt.address, usdc.address]],\n }),\n ]);\n }\n\n // P4: Exchange rate calls\n if (doRate) {\n for (const fork of compoundForks) {\n for (const { key, addr } of fork.vtokens) {\n callTypes.push({ kind: \"exchangeRate\", protocol: fork.name, vtoken: key });\n calls.push([addr, encodeFunctionData({ abi: VTOKEN_ABI, functionName: \"exchangeRateStored\", args: [] })]);\n }\n }\n }\n\n if (calls.length === 0) {\n printOutput({ error: `No scannable resources found on ${chainName}` }, getOpts());\n return;\n }\n\n const results = await multicallRead(rpc, calls);\n const scanMs = Date.now() - t0;\n\n const alerts: unknown[] = [];\n const oracleByToken = new Map<string, Array<{ oracle: string; price: number }>>();\n const dexByToken = new Map<string, number>();\n const oracleData: Record<string, number> = {};\n const dexData: Record<string, number> = {};\n const stableData: Record<string, number> = {};\n const stablePrices: Array<{ asset: string; pair: string; price: number }> = [];\n const rateData: Record<string, number> = {};\n\n for (let i = 0; i < callTypes.length; i++) {\n const ct = callTypes[i];\n const raw = results[i] ?? null;\n\n if (ct.kind === \"oracle\") {\n const price = parseU256F64(raw, ct.oracleDecimals);\n if (price > 0) {\n const existing = oracleByToken.get(ct.token) ?? [];\n existing.push({ oracle: ct.oracle, price });\n oracleByToken.set(ct.token, existing);\n oracleData[`${ct.oracle}/${ct.token}`] = round4(price);\n }\n } else if (ct.kind === \"dex\") {\n const price = parseAmountsOutLast(raw, ct.outDecimals);\n if (price > 0) {\n dexByToken.set(ct.token, price);\n dexData[ct.token] = round4(price);\n }\n } else if (ct.kind === \"stable\") {\n const price = parseAmountsOutLast(raw, ct.outDecimals);\n if (price <= 0) continue;\n const pair = `${ct.from}/${ct.to}`;\n stableData[pair] = round4(price);\n stablePrices.push({ asset: ct.from, pair, price });\n } else if (ct.kind === \"exchangeRate\") {\n const rate = parseU256F64(raw, 18);\n const key = `${ct.protocol}/${ct.vtoken}`;\n rateData[key] = round6(rate);\n if (rate > 0) {\n const prev = prevRates.get(key);\n if (prev !== undefined) {\n const change = Math.abs((rate - prev) / prev * 100);\n if (change > rateThreshold) {\n const severity = change > 50 ? \"critical\" : change > 20 ? \"high\" : \"medium\";\n alerts.push({\n pattern: \"exchange_rate_anomaly\",\n severity,\n protocol: ct.protocol,\n vtoken: ct.vtoken,\n prev_rate: round6(prev),\n curr_rate: round6(rate),\n change_pct: round2(change),\n action: `possible donation attack on ${ct.protocol} ${ct.vtoken}`,\n });\n }\n }\n prevRates.set(key, rate);\n }\n }\n }\n\n // Stablecoin depeg alerts\n if (stablePrices.length >= 2) {\n const allBelow = stablePrices.every((s) => s.price < stableThreshold);\n if (!allBelow) {\n for (const { asset, pair, price } of stablePrices) {\n if (price < stableThreshold) {\n const severity = price < 0.95 ? \"critical\" : \"high\";\n alerts.push({\n pattern: \"stablecoin_depeg\",\n severity,\n asset,\n pair,\n price: round4(price),\n threshold: stableThreshold,\n action: `buy ${asset} at $${round4(price)}, wait for repeg`,\n });\n }\n }\n }\n } else {\n for (const { asset, pair, price } of stablePrices) {\n if (price < stableThreshold) {\n const severity = price < 0.95 ? \"critical\" : \"high\";\n alerts.push({\n pattern: \"stablecoin_depeg\",\n severity,\n asset,\n pair,\n price: round4(price),\n threshold: stableThreshold,\n action: `buy ${asset} at $${round4(price)}, wait for repeg`,\n });\n }\n }\n }\n\n // Oracle divergence alerts\n if (doOracle) {\n for (const [token, oracleEntries] of oracleByToken) {\n const dexPrice = dexByToken.get(token);\n if (dexPrice === undefined) continue;\n for (const { oracle, price: oraclePrice } of oracleEntries) {\n // Skip unreliable DEX quotes (no liquidity)\n if (dexPrice < oraclePrice && dexPrice < oraclePrice * 0.1) continue;\n const deviation = Math.abs(dexPrice - oraclePrice) / oraclePrice * 100;\n if (deviation > oracleThreshold) {\n const severity = deviation > 100 ? \"critical\" : deviation > 20 ? \"high\" : \"medium\";\n const action =\n dexPrice > oraclePrice\n ? `borrow ${token} from ${oracle}, sell on DEX`\n : `buy ${token} on DEX, use as collateral on ${oracle}`;\n alerts.push({\n pattern: \"oracle_divergence\",\n severity,\n asset: token,\n oracle,\n oracle_price: round4(oraclePrice),\n dex_price: round4(dexPrice),\n deviation_pct: round2(deviation),\n action,\n });\n }\n }\n }\n }\n\n // Build output data object\n const data: Record<string, unknown> = {};\n if (Object.keys(oracleData).length > 0) data[\"oracle_prices\"] = oracleData;\n if (Object.keys(dexData).length > 0) data[\"dex_prices\"] = dexData;\n if (Object.keys(stableData).length > 0) data[\"stablecoin_pegs\"] = stableData;\n if (Object.keys(rateData).length > 0) data[\"exchange_rates\"] = rateData;\n\n const output = {\n timestamp,\n chain: chain.name,\n scan_duration_ms: scanMs,\n patterns,\n alert_count: alerts.length,\n alerts,\n data,\n };\n\n for (const alert of alerts as Array<Record<string, unknown>>) {\n process.stderr.write(\n `ALERT [${alert[\"severity\"]}]: ${alert[\"pattern\"]} — ${alert[\"action\"]}\\n`,\n );\n }\n\n printOutput(output, getOpts());\n };\n\n await runOnce();\n\n if (!once) {\n const intervalMs = interval * 1000;\n const loop = async () => {\n await new Promise((r) => setTimeout(r, intervalMs));\n await runOnce();\n void loop();\n };\n await loop();\n }\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n process.exit(1);\n }\n });\n}\n\nasync function runAllChains(\n registry: Registry,\n patterns: string,\n oracleThreshold: number,\n stableThreshold: number,\n _rateThreshold: number,\n): Promise<unknown> {\n const t0 = Date.now();\n const chainKeys = Array.from(registry.chains.keys());\n\n const tasks = chainKeys.map(async (ck) => {\n try {\n const chain = registry.getChain(ck);\n const rpc = chain.effectiveRpcUrl();\n const chainName = chain.name.toLowerCase();\n const allTokens = registry.tokens.get(chainName) ?? [];\n const wrappedNative = chain.wrapped_native as Address | undefined;\n\n const quoteStable = (() => {\n for (const sym of [\"USDT\", \"USDC\", \"USDT0\"]) {\n try { return registry.resolveToken(chainName, sym); } catch { /* continue */ }\n }\n return null;\n })();\n if (!quoteStable) return null;\n\n const scanTokens = allTokens.filter(\n (t) => t.address !== \"0x0000000000000000000000000000000000000000\" && !STABLECOINS.has(t.symbol),\n );\n\n const pats = patterns.split(\",\").map((s) => s.trim());\n const doOracle = pats.includes(\"oracle\");\n const doStable = pats.includes(\"stable\");\n\n const oracles: Array<{ name: string; addr: Address; decimals: number }> = registry\n .getProtocolsForChain(chainName)\n .filter(\n (p) =>\n p.category === ProtocolCategory.Lending &&\n (p.interface === \"aave_v3\" || p.interface === \"aave_v2\" || p.interface === \"aave_v3_isolated\"),\n )\n .flatMap((p) => {\n const oracleAddr = p.contracts?.[\"oracle\"];\n if (!oracleAddr) return [];\n return [{ name: p.name, addr: oracleAddr, decimals: p.interface === \"aave_v2\" ? 18 : 8 }];\n });\n\n const dexProto = registry\n .getProtocolsForChain(chainName)\n .find((p) => p.category === ProtocolCategory.Dex && p.interface === \"uniswap_v2\");\n const dexRouter = dexProto?.contracts?.[\"router\"] as Address | undefined;\n\n const usdc = (() => { try { return registry.resolveToken(chainName, \"USDC\"); } catch { return null; } })();\n const usdt = (() => { try { return registry.resolveToken(chainName, \"USDT\"); } catch { return null; } })();\n\n const calls: Array<[Address, Hex]> = [];\n type CT = { kind: \"oracle\"; oracle: string; token: string; dec: number } | { kind: \"dex\"; token: string; dec: number } | { kind: \"stable\"; from: string; to: string; dec: number };\n const cts: CT[] = [];\n\n if (doOracle) {\n for (const oracle of oracles) {\n for (const token of scanTokens) {\n cts.push({ kind: \"oracle\", oracle: oracle.name, token: token.symbol, dec: oracle.decimals });\n calls.push([oracle.addr, encodeFunctionData({ abi: AAVE_ORACLE_ABI, functionName: \"getAssetPrice\", args: [token.address] })]);\n }\n }\n if (dexRouter) {\n for (const token of scanTokens) {\n const path: Address[] =\n wrappedNative && token.address.toLowerCase() === wrappedNative.toLowerCase()\n ? [token.address, quoteStable.address]\n : wrappedNative\n ? [token.address, wrappedNative, quoteStable.address]\n : [token.address, quoteStable.address];\n cts.push({ kind: \"dex\", token: token.symbol, dec: quoteStable.decimals });\n calls.push([dexRouter, encodeFunctionData({ abi: UNIV2_ROUTER_ABI, functionName: \"getAmountsOut\", args: [BigInt(10) ** BigInt(token.decimals), path] })]);\n }\n }\n }\n\n if (doStable && usdc && usdt && dexRouter) {\n cts.push({ kind: \"stable\", from: \"USDC\", to: \"USDT\", dec: usdt.decimals });\n calls.push([dexRouter, encodeFunctionData({ abi: UNIV2_ROUTER_ABI, functionName: \"getAmountsOut\", args: [BigInt(10) ** BigInt(usdc.decimals), [usdc.address, usdt.address]] })]);\n cts.push({ kind: \"stable\", from: \"USDT\", to: \"USDC\", dec: usdc.decimals });\n calls.push([dexRouter, encodeFunctionData({ abi: UNIV2_ROUTER_ABI, functionName: \"getAmountsOut\", args: [BigInt(10) ** BigInt(usdt.decimals), [usdt.address, usdc.address]] })]);\n }\n\n if (calls.length === 0) return null;\n\n const ct0 = Date.now();\n const results = await multicallRead(rpc, calls);\n const scanMs = Date.now() - ct0;\n\n const alerts: unknown[] = [];\n const oracleByToken = new Map<string, Array<{ oracle: string; price: number }>>();\n const dexByToken = new Map<string, number>();\n const stablePrices: Array<{ asset: string; pair: string; price: number }> = [];\n\n for (let i = 0; i < cts.length; i++) {\n const ct = cts[i];\n const raw = results[i] ?? null;\n if (ct.kind === \"oracle\") {\n const price = parseU256F64(raw, ct.dec);\n if (price > 0) {\n const existing = oracleByToken.get(ct.token) ?? [];\n existing.push({ oracle: ct.oracle, price });\n oracleByToken.set(ct.token, existing);\n }\n } else if (ct.kind === \"dex\") {\n const price = parseAmountsOutLast(raw, ct.dec);\n if (price > 0) dexByToken.set(ct.token, price);\n } else if (ct.kind === \"stable\") {\n const price = parseAmountsOutLast(raw, ct.dec);\n if (price > 0) stablePrices.push({ asset: ct.from, pair: `${ct.from}/${ct.to}`, price });\n }\n }\n\n // Stablecoin depeg\n if (stablePrices.length >= 2) {\n const allBelow = stablePrices.every((s) => s.price < stableThreshold);\n if (!allBelow) {\n for (const { asset, pair, price } of stablePrices) {\n if (price < stableThreshold) {\n alerts.push({ pattern: \"stablecoin_depeg\", severity: price < 0.95 ? \"critical\" : \"high\", asset, pair, price: round4(price) });\n }\n }\n }\n }\n\n // Oracle divergence\n for (const [token, oEntries] of oracleByToken) {\n const dp = dexByToken.get(token);\n if (dp === undefined) continue;\n for (const { oracle, price: op } of oEntries) {\n if (dp < op && dp < op * 0.1) continue;\n const dev = Math.abs(dp - op) / op * 100;\n if (dev > oracleThreshold) {\n const sev = dev > 100 ? \"critical\" : dev > 20 ? \"high\" : \"medium\";\n alerts.push({\n pattern: \"oracle_divergence\",\n severity: sev,\n asset: token,\n oracle,\n oracle_price: round4(op),\n dex_price: round4(dp),\n deviation_pct: round2(dev),\n action: dp > op ? `borrow ${token} from ${oracle}, sell on DEX` : `buy ${token} on DEX, collateral on ${oracle}`,\n });\n }\n }\n }\n\n return { chain: chain.name, scan_duration_ms: scanMs, alert_count: alerts.length, alerts };\n } catch {\n return null;\n }\n });\n\n const chainResults = (await Promise.all(tasks)).filter(Boolean);\n chainResults.sort((a, b) => {\n const ac = (a as Record<string, unknown>)[\"alert_count\"] as number ?? 0;\n const bc = (b as Record<string, unknown>)[\"alert_count\"] as number ?? 0;\n return bc - ac;\n });\n\n const totalAlerts = chainResults.reduce((sum, r) => sum + ((r as Record<string, unknown>)[\"alert_count\"] as number ?? 0), 0);\n\n return {\n mode: \"all_chains\",\n chains_scanned: chainKeys.length,\n scan_duration_ms: Date.now() - t0,\n total_alerts: totalAlerts,\n chains: chainResults,\n };\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport { createDex } from \"@hypurrquant/defi-protocols\";\nimport type { Address } from \"viem\";\n\nexport function registerArb(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n parent\n .command(\"arb\")\n .description(\"Detect arbitrage opportunities across DEXes\")\n .option(\"--token-in <token>\", \"Base token (default: WHYPE)\", \"WHYPE\")\n .option(\"--token-out <token>\", \"Quote token (default: USDC)\", \"USDC\")\n .option(\"--amount <amount>\", \"Test amount in wei\", \"1000000000000000000\")\n .option(\"--execute\", \"Execute best arb (default: analysis only)\")\n .option(\"--min-profit <bps>\", \"Min profit in bps to execute\", \"10\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const rpcUrl = chain.effectiveRpcUrl();\n\n const tokenIn = opts.tokenIn.startsWith(\"0x\") ? opts.tokenIn as Address : registry.resolveToken(chainName, opts.tokenIn).address as Address;\n const tokenOut = opts.tokenOut.startsWith(\"0x\") ? opts.tokenOut as Address : registry.resolveToken(chainName, opts.tokenOut).address as Address;\n const amountIn = BigInt(opts.amount);\n\n const dexProtocols = registry.getProtocolsByCategory(\"dex\" as any).filter(p => p.chain === chainName);\n const quotes: Array<{ protocol: string; buy: bigint; sell: bigint; profit_bps: number }> = [];\n\n for (const p of dexProtocols) {\n try {\n const adapter = createDex(p, rpcUrl);\n const buyQuote = await adapter.quote({ protocol: p.name, token_in: tokenIn, token_out: tokenOut, amount_in: amountIn });\n if (buyQuote.amount_out === 0n) continue;\n const sellQuote = await adapter.quote({ protocol: p.name, token_in: tokenOut, token_out: tokenIn, amount_in: buyQuote.amount_out });\n const profitBps = Number((sellQuote.amount_out - amountIn) * 10000n / amountIn);\n quotes.push({ protocol: p.name, buy: buyQuote.amount_out, sell: sellQuote.amount_out, profit_bps: profitBps });\n } catch { /* skip unsupported */ }\n }\n\n // Cross-DEX arb: buy on cheapest, sell on most expensive\n const opportunities: Array<{ buy_on: string; sell_on: string; profit_bps: number }> = [];\n for (let i = 0; i < quotes.length; i++) {\n for (let j = 0; j < quotes.length; j++) {\n if (i === j) continue;\n const buyAmount = quotes[i].buy;\n const sellAmount = quotes[j].sell;\n if (sellAmount > amountIn) {\n const profitBps = Number((sellAmount - amountIn) * 10000n / amountIn);\n opportunities.push({ buy_on: quotes[i].protocol, sell_on: quotes[j].protocol, profit_bps: profitBps });\n }\n }\n }\n opportunities.sort((a, b) => b.profit_bps - a.profit_bps);\n\n printOutput({\n chain: chainName, token_in: tokenIn, token_out: tokenOut,\n amount_in: amountIn, single_dex: quotes, cross_dex_opportunities: opportunities.slice(0, 5),\n }, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport { Registry, ProtocolCategory, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\n\nconst ERC20_ABI = parseAbi([\n \"function balanceOf(address owner) external view returns (uint256)\",\n]);\n\nconst POOL_ABI = parseAbi([\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n]);\n\nfunction round2(x: number): number {\n return Math.round(x * 100) / 100;\n}\n\nfunction round4(x: number): number {\n return Math.round(x * 10000) / 10000;\n}\n\nfunction estimateTokenValue(symbol: string, balance: number, nativePrice: number): number {\n const s = symbol.toUpperCase();\n if (s.includes(\"USD\") || s.includes(\"DAI\")) return balance;\n if (s.includes(\"BTC\") || s.includes(\"FBTC\")) return balance * 75000;\n if ([\"WETH\", \"ETH\", \"METH\", \"CBETH\", \"WSTETH\"].includes(s)) return balance * 2350;\n return balance * nativePrice;\n}\n\nfunction decodeU256(data: Hex | null, offset = 0): bigint {\n if (!data || data.length < 2 + (offset + 32) * 2) return 0n;\n const hex = data.slice(2 + offset * 64, 2 + offset * 64 + 64);\n return BigInt(\"0x\" + hex);\n}\n\ninterface ChainScanResult {\n chain_name: string;\n native_price: number;\n chain_value: number;\n collateral: number;\n debt: number;\n token_balances: unknown[];\n lending_positions: unknown[];\n}\n\nasync function scanSingleChain(\n chainName: string,\n rpc: string,\n user: Address,\n tokens: Array<{ address: Address; symbol: string; decimals: number }>,\n lendingPools: Array<{ name: string; pool: Address; iface: string }>,\n oracleAddr: Address | undefined,\n wrappedNative: Address,\n): Promise<ChainScanResult | null> {\n const calls: Array<[Address, Hex]> = [];\n\n type CallType =\n | { kind: \"token\"; symbol: string; decimals: number }\n | { kind: \"lending\"; protocol: string; iface: string }\n | { kind: \"native_price\" };\n\n const callTypes: CallType[] = [];\n\n for (const token of tokens) {\n if (token.address !== (\"0x0000000000000000000000000000000000000000\" as Address)) {\n callTypes.push({ kind: \"token\", symbol: token.symbol, decimals: token.decimals });\n calls.push([\n token.address,\n encodeFunctionData({ abi: ERC20_ABI, functionName: \"balanceOf\", args: [user] }),\n ]);\n }\n }\n\n for (const { name, pool, iface } of lendingPools) {\n callTypes.push({ kind: \"lending\", protocol: name, iface });\n calls.push([\n pool,\n encodeFunctionData({ abi: POOL_ABI, functionName: \"getUserAccountData\", args: [user] }),\n ]);\n }\n\n if (oracleAddr) {\n callTypes.push({ kind: \"native_price\" });\n calls.push([\n oracleAddr,\n encodeFunctionData({ abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [wrappedNative] }),\n ]);\n }\n\n if (calls.length === 0) return null;\n\n let results: (Hex | null)[];\n try {\n results = await multicallRead(rpc, calls);\n } catch {\n return null;\n }\n\n const nativePrice = oracleAddr\n ? Number(decodeU256(results[results.length - 1]!)) / 1e8\n : 0;\n\n const tokenBalances: unknown[] = [];\n const lendingPositions: unknown[] = [];\n let chainValue = 0;\n let totalColl = 0;\n let totalDebt = 0;\n\n for (let i = 0; i < callTypes.length; i++) {\n const ct = callTypes[i]!;\n const data = results[i] ?? null;\n\n if (ct.kind === \"token\") {\n const balance = decodeU256(data);\n if (balance > 0n) {\n const balF64 = Number(balance) / 10 ** ct.decimals;\n const valueUsd = estimateTokenValue(ct.symbol, balF64, nativePrice);\n if (valueUsd > 0.01) {\n chainValue += valueUsd;\n tokenBalances.push({\n symbol: ct.symbol,\n balance: round4(balF64),\n value_usd: round2(valueUsd),\n });\n }\n }\n } else if (ct.kind === \"lending\") {\n if (data && data.length >= 2 + 192 * 2) {\n const priceDecimals = ct.iface === \"aave_v2\" ? 18 : 8;\n const divisor = 10 ** priceDecimals;\n const collateral = Number(decodeU256(data, 0)) / divisor;\n const debt = Number(decodeU256(data, 1)) / divisor;\n const hfRaw = decodeU256(data, 5);\n let hf: number | null = null;\n if (hfRaw <= BigInt(\"0xffffffffffffffffffffffffffffffff\")) {\n const v = Number(hfRaw) / 1e18;\n hf = v > 1e10 ? null : round2(v);\n }\n\n if (collateral > 0.01 || debt > 0.01) {\n const net = collateral - debt;\n chainValue += net;\n totalColl += collateral;\n totalDebt += debt;\n lendingPositions.push({\n protocol: ct.protocol,\n collateral_usd: round2(collateral),\n debt_usd: round2(debt),\n net_usd: round2(net),\n health_factor: hf,\n });\n }\n }\n }\n // native_price call — already decoded above\n }\n\n if (tokenBalances.length === 0 && lendingPositions.length === 0) return null;\n\n return {\n chain_name: chainName,\n native_price: nativePrice,\n chain_value: chainValue,\n collateral: totalColl,\n debt: totalDebt,\n token_balances: tokenBalances,\n lending_positions: lendingPositions,\n };\n}\n\nexport function registerPositions(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"positions\")\n .description(\"Cross-chain position scanner: find all your positions everywhere\")\n .requiredOption(\"--address <address>\", \"Wallet address to scan\")\n .option(\"--chains <chains>\", \"Comma-separated chain names (omit for all)\")\n .action(async (opts: { address: string; chains?: string }) => {\n const mode = getOpts();\n const registry = Registry.loadEmbedded();\n\n const user = opts.address as Address;\n if (!/^0x[0-9a-fA-F]{40}$/.test(user)) {\n printOutput({ error: `Invalid address: ${opts.address}` }, mode);\n return;\n }\n\n const chainFilter = opts.chains\n ? opts.chains.split(\",\").map((s) => s.trim().toLowerCase())\n : null;\n\n const chainKeys = chainFilter ?? Array.from(registry.chains.keys());\n\n const start = Date.now();\n\n // Build scan params for each chain\n const scanParams: Array<{\n chainName: string;\n rpc: string;\n tokens: Array<{ address: Address; symbol: string; decimals: number }>;\n lendingPools: Array<{ name: string; pool: Address; iface: string }>;\n oracleAddr: Address | undefined;\n wrappedNative: Address;\n }> = [];\n\n for (const chainKey of chainKeys) {\n let chain;\n try {\n chain = registry.getChain(chainKey);\n } catch {\n continue;\n }\n const rpc = chain.effectiveRpcUrl();\n const rawTokens = registry.tokens.get(chainKey) ?? [];\n const tokens = rawTokens.map((t) => ({\n address: t.address as Address,\n symbol: t.symbol,\n decimals: t.decimals,\n }));\n\n const chainProtocols = registry.getProtocolsForChain(chainKey);\n\n const lendingPools = chainProtocols\n .filter(\n (p) =>\n p.category === ProtocolCategory.Lending &&\n (p.interface === \"aave_v3\" || p.interface === \"aave_v2\"),\n )\n .filter((p) => p.contracts?.[\"pool\"])\n .map((p) => ({\n name: p.name,\n pool: p.contracts![\"pool\"] as Address,\n iface: p.interface,\n }));\n\n const oracleEntry = chainProtocols.find(\n (p) => p.interface === \"aave_v3\" && p.contracts?.[\"oracle\"],\n );\n const oracleAddr = oracleEntry?.contracts?.[\"oracle\"] as Address | undefined;\n\n const wrappedNative = (chain.wrapped_native ?? \"0x5555555555555555555555555555555555555555\") as Address;\n\n scanParams.push({ chainName: chain.name, rpc, tokens, lendingPools, oracleAddr, wrappedNative });\n }\n\n // Run all chains in parallel\n const chainResultsRaw = await Promise.all(\n scanParams.map((p) =>\n scanSingleChain(p.chainName, p.rpc, user, p.tokens, p.lendingPools, p.oracleAddr, p.wrappedNative),\n ),\n );\n\n let grandTotalUsd = 0;\n let totalCollateralUsd = 0;\n let totalDebtUsd = 0;\n\n const chainResults = chainResultsRaw\n .filter((r): r is ChainScanResult => r !== null)\n .map((r) => {\n grandTotalUsd += r.chain_value;\n totalCollateralUsd += r.collateral;\n totalDebtUsd += r.debt;\n return {\n chain: r.chain_name,\n native_price_usd: round2(r.native_price),\n chain_total_usd: round2(r.chain_value),\n token_balances: r.token_balances,\n lending_positions: r.lending_positions,\n };\n })\n .sort((a, b) => b.chain_total_usd - a.chain_total_usd);\n\n const scanMs = Date.now() - start;\n\n printOutput(\n {\n address: user,\n scan_duration_ms: scanMs,\n chains_scanned: chainKeys.length,\n chains_with_positions: chainResults.length,\n summary: {\n total_value_usd: round2(grandTotalUsd),\n total_collateral_usd: round2(totalCollateralUsd),\n total_debt_usd: round2(totalDebtUsd),\n net_lending_usd: round2(totalCollateralUsd - totalDebtUsd),\n },\n chains: chainResults,\n },\n mode,\n );\n });\n}\n","import type { Command } from \"commander\";\nimport type { Address } from \"viem\";\nimport { Registry, ProtocolCategory } from \"@hypurrquant/defi-core\";\nimport { createOracleFromLending, createOracleFromCdp, createDex, DexSpotPrice } from \"@hypurrquant/defi-protocols\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\n\ninterface PriceEntry {\n source: string;\n source_type: string;\n price: number;\n}\n\ninterface PriceReport {\n asset: string;\n asset_address: string;\n prices: PriceEntry[];\n max_spread_pct: number;\n oracle_vs_dex_spread_pct: number;\n}\n\nfunction round2(x: number): number {\n return Math.round(x * 100) / 100;\n}\n\nfunction resolveAsset(\n registry: Registry,\n chain: string,\n asset: string,\n): { address: Address; symbol: string; decimals: number } {\n // Try parse as address\n if (/^0x[0-9a-fA-F]{40}$/.test(asset)) {\n return { address: asset as Address, symbol: asset, decimals: 18 };\n }\n const token = registry.resolveToken(chain, asset);\n return { address: token.address, symbol: token.symbol, decimals: token.decimals };\n}\n\nconst WHYPE_ADDRESS = \"0x5555555555555555555555555555555555555555\" as Address;\n\nexport function registerPrice(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"price\")\n .description(\"Query asset prices from oracles and DEXes\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .option(\"--source <source>\", \"Price source: oracle, dex, or all\", \"all\")\n .action(async (opts: { asset: string; source: string }) => {\n const mode = getOpts();\n const registry = Registry.loadEmbedded();\n const chainName = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n\n let chain;\n try {\n chain = registry.getChain(chainName);\n } catch (e) {\n printOutput({ error: `Chain not found: ${chainName}` }, mode);\n return;\n }\n\n const rpcUrl = chain.effectiveRpcUrl();\n\n let assetAddr: Address;\n let assetSymbol: string;\n let assetDecimals: number;\n try {\n const resolved = resolveAsset(registry, chainName, opts.asset);\n assetAddr = resolved.address;\n assetSymbol = resolved.symbol;\n assetDecimals = resolved.decimals;\n } catch (e) {\n printOutput({ error: `Could not resolve asset: ${opts.asset}` }, mode);\n return;\n }\n\n const fetchOracle = opts.source === \"all\" || opts.source === \"oracle\";\n const fetchDex = opts.source === \"all\" || opts.source === \"dex\";\n\n const allPrices: Array<{ source: string; source_type: string; price_f64: number }> = [];\n\n // Oracle prices from lending protocols (Aave V3 forks)\n if (fetchOracle) {\n const lendingProtocols = registry.getProtocolsByCategory(ProtocolCategory.Lending)\n .filter((p) => p.chain.toLowerCase() === chainName);\n\n await Promise.all(\n lendingProtocols.map(async (entry) => {\n try {\n const oracle = createOracleFromLending(entry, rpcUrl);\n const price = await oracle.getPrice(assetAddr);\n allPrices.push({\n source: price.source,\n source_type: price.source_type,\n price_f64: price.price_f64,\n });\n } catch {\n // Interface doesn't support oracle — skip\n }\n }),\n );\n\n // Oracle prices from CDP protocols (Felix) — only for WHYPE\n const isWhype =\n assetAddr.toLowerCase() === WHYPE_ADDRESS.toLowerCase() ||\n assetSymbol.toUpperCase() === \"WHYPE\" ||\n assetSymbol.toUpperCase() === \"HYPE\";\n\n if (isWhype) {\n const cdpProtocols = registry.getProtocolsByCategory(ProtocolCategory.Cdp)\n .filter((p) => p.chain.toLowerCase() === chainName);\n\n await Promise.all(\n cdpProtocols.map(async (entry) => {\n try {\n const oracle = createOracleFromCdp(entry, assetAddr, rpcUrl);\n const price = await oracle.getPrice(assetAddr);\n allPrices.push({\n source: price.source,\n source_type: price.source_type,\n price_f64: price.price_f64,\n });\n } catch {\n // skip\n }\n }),\n );\n }\n }\n\n // DEX spot prices\n if (fetchDex) {\n let usdcToken;\n try {\n usdcToken = registry.resolveToken(chainName, \"USDC\");\n } catch {\n process.stderr.write(\"USDC token not found in registry — skipping DEX prices\\n\");\n }\n\n if (usdcToken) {\n const dexProtocols = registry.getProtocolsByCategory(ProtocolCategory.Dex)\n .filter((p) => p.chain.toLowerCase() === chainName);\n\n await Promise.all(\n dexProtocols.map(async (entry) => {\n try {\n const dex = createDex(entry, rpcUrl);\n const price = await DexSpotPrice.getPrice(\n dex,\n assetAddr,\n assetDecimals,\n usdcToken!.address,\n usdcToken!.decimals,\n );\n allPrices.push({\n source: price.source,\n source_type: price.source_type,\n price_f64: price.price_f64,\n });\n } catch {\n // skip\n }\n }),\n );\n }\n }\n\n if (allPrices.length === 0) {\n printOutput({ error: \"No prices could be fetched from any source\" }, mode);\n return;\n }\n\n const pricesF64 = allPrices.map((p) => p.price_f64);\n const maxPrice = Math.max(...pricesF64);\n const minPrice = Math.min(...pricesF64);\n const maxSpreadPct = minPrice > 0 ? ((maxPrice - minPrice) / minPrice) * 100 : 0;\n\n const oraclePrices = allPrices.filter((p) => p.source_type === \"oracle\").map((p) => p.price_f64);\n const dexPrices = allPrices.filter((p) => p.source_type === \"dex_spot\").map((p) => p.price_f64);\n\n let oracleVsDexSpreadPct = 0;\n if (oraclePrices.length > 0 && dexPrices.length > 0) {\n const avgOracle = oraclePrices.reduce((a, b) => a + b, 0) / oraclePrices.length;\n const avgDex = dexPrices.reduce((a, b) => a + b, 0) / dexPrices.length;\n const minAvg = Math.min(avgOracle, avgDex);\n oracleVsDexSpreadPct = minAvg > 0 ? (Math.abs(avgOracle - avgDex) / minAvg) * 100 : 0;\n }\n\n const report: PriceReport = {\n asset: assetSymbol,\n asset_address: assetAddr,\n prices: allPrices.map((p) => ({\n source: p.source,\n source_type: p.source_type,\n price: round2(p.price_f64),\n })),\n max_spread_pct: round2(maxSpreadPct),\n oracle_vs_dex_spread_pct: round2(oracleVsDexSpreadPct),\n };\n\n printOutput(report, mode);\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport { createPublicClient, http, formatEther } from \"viem\";\n\nexport function registerWallet(parent: Command, getOpts: () => OutputMode): void {\n const wallet = parent.command(\"wallet\").description(\"Wallet management\");\n\n wallet\n .command(\"balance\")\n .description(\"Show native token balance\")\n .requiredOption(\"--address <address>\", \"Wallet address to query\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const client = createPublicClient({ transport: http(chain.effectiveRpcUrl()) });\n\n const balance = await client.getBalance({ address: opts.address as `0x${string}` });\n printOutput({\n chain: chain.name,\n address: opts.address,\n native_token: chain.native_token,\n balance_wei: balance,\n balance_formatted: formatEther(balance),\n }, getOpts());\n });\n\n wallet\n .command(\"address\")\n .description(\"Show configured wallet address\")\n .action(async () => {\n const addr = process.env.DEFI_WALLET_ADDRESS ?? \"(not set)\";\n printOutput({ address: addr }, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry, buildApprove, buildTransfer, erc20Abi } from \"@hypurrquant/defi-core\";\nimport { createPublicClient, http, maxUint256 } from \"viem\";\nimport type { Address } from \"viem\";\n\nexport function registerToken(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const token = parent.command(\"token\").description(\"Token operations: approve, allowance, transfer, balance\");\n\n token\n .command(\"balance\")\n .description(\"Query token balance for an address\")\n .requiredOption(\"--token <token>\", \"Token symbol or address\")\n .requiredOption(\"--owner <address>\", \"Wallet address to query\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const client = createPublicClient({ transport: http(chain.effectiveRpcUrl()) });\n\n const tokenAddr = opts.token.startsWith(\"0x\")\n ? opts.token as Address\n : registry.resolveToken(chainName, opts.token).address as Address;\n\n const [balance, symbol, decimals] = await Promise.all([\n client.readContract({ address: tokenAddr, abi: erc20Abi, functionName: \"balanceOf\", args: [opts.owner as Address] }),\n client.readContract({ address: tokenAddr, abi: erc20Abi, functionName: \"symbol\" }),\n client.readContract({ address: tokenAddr, abi: erc20Abi, functionName: \"decimals\" }),\n ]);\n\n printOutput({\n token: tokenAddr,\n symbol,\n owner: opts.owner,\n balance,\n decimals,\n }, getOpts());\n });\n\n token\n .command(\"approve\")\n .description(\"Approve a spender for a token\")\n .requiredOption(\"--token <token>\", \"Token symbol or address\")\n .requiredOption(\"--spender <address>\", \"Spender address\")\n .option(\"--amount <amount>\", \"Amount to approve (use 'max' for unlimited)\", \"max\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const tokenAddr = opts.token.startsWith(\"0x\")\n ? opts.token as Address\n : registry.resolveToken(chainName, opts.token).address as Address;\n\n const amount = opts.amount === \"max\" ? maxUint256 : BigInt(opts.amount);\n const tx = buildApprove(tokenAddr, opts.spender as Address, amount);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n token\n .command(\"allowance\")\n .description(\"Check token allowance\")\n .requiredOption(\"--token <token>\", \"Token symbol or address\")\n .requiredOption(\"--owner <address>\", \"Owner address\")\n .requiredOption(\"--spender <address>\", \"Spender address\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const client = createPublicClient({ transport: http(chain.effectiveRpcUrl()) });\n\n const tokenAddr = opts.token.startsWith(\"0x\")\n ? opts.token as Address\n : registry.resolveToken(chainName, opts.token).address as Address;\n\n const allowance = await client.readContract({\n address: tokenAddr, abi: erc20Abi, functionName: \"allowance\",\n args: [opts.owner as Address, opts.spender as Address],\n });\n\n printOutput({ token: tokenAddr, owner: opts.owner, spender: opts.spender, allowance }, getOpts());\n });\n\n token\n .command(\"transfer\")\n .description(\"Transfer tokens to an address\")\n .requiredOption(\"--token <token>\", \"Token symbol or address\")\n .requiredOption(\"--to <address>\", \"Recipient address\")\n .requiredOption(\"--amount <amount>\", \"Amount to transfer (in wei)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const tokenAddr = opts.token.startsWith(\"0x\")\n ? opts.token as Address\n : registry.resolveToken(chainName, opts.token).address as Address;\n\n const tx = buildTransfer(tokenAddr, opts.to as Address, BigInt(opts.amount));\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport { Registry, ProtocolCategory, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\n\nconst POOL_ABI = parseAbi([\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n]);\n\nfunction round2(x: number): number {\n return Math.round(x * 100) / 100;\n}\n\nfunction round4(x: number): number {\n return Math.round(x * 10000) / 10000;\n}\n\nfunction decodeU256(data: Hex | null, wordOffset = 0): bigint {\n if (!data || data.length < 2 + (wordOffset + 1) * 64) return 0n;\n const hex = data.slice(2 + wordOffset * 64, 2 + wordOffset * 64 + 64);\n return BigInt(\"0x\" + hex);\n}\n\nfunction getExplorerApi(chainId: number, explorerUrl?: string): { base: string; apiKey?: string } | null {\n // routescan (free, no key)\n const routescanChains = [1, 43114, 10, 5000];\n if (routescanChains.includes(chainId)) {\n return {\n base: `https://api.routescan.io/v2/network/mainnet/evm/${chainId}/etherscan/api`,\n };\n }\n\n // Etherscan V2 unified API\n const apiKey = process.env[\"ETHERSCAN_API_KEY\"];\n if (apiKey) {\n return {\n base: `https://api.etherscan.io/v2/api?chainid=${chainId}`,\n apiKey,\n };\n }\n\n return null;\n}\n\nexport function registerWhales(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"whales\")\n .description(\"Find top token holders (whales) and their positions\")\n .requiredOption(\"--token <token>\", \"Token symbol or address\")\n .option(\"--top <n>\", \"Number of top holders to show\", \"10\")\n .option(\"--positions\", \"Also scan each whale's lending positions\")\n .action(async (opts: { token: string; top: string; positions?: boolean }) => {\n const mode = getOpts();\n const registry = Registry.loadEmbedded();\n const chainName = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n\n let chain;\n try {\n chain = registry.getChain(chainName);\n } catch {\n printOutput({ error: `Chain not found: ${chainName}` }, mode);\n return;\n }\n\n const rpc = chain.effectiveRpcUrl();\n const top = parseInt(opts.top, 10) || 10;\n\n // Resolve token\n let token;\n try {\n token = registry.resolveToken(chainName, opts.token);\n } catch {\n printOutput({ error: `Token not found: ${opts.token}` }, mode);\n return;\n }\n\n // Get explorer API\n const explorerApi = getExplorerApi(chain.chain_id, chain.explorer_url);\n if (!explorerApi) {\n printOutput(\n {\n error: `No explorer API available for ${chain.name} (chain_id: ${chain.chain_id}). Set ETHERSCAN_API_KEY to enable.`,\n },\n mode,\n );\n return;\n }\n\n // Build URL\n const tokenAddr = token.address;\n let url = `${explorerApi.base}?module=token&action=tokenholderlist&contractaddress=${tokenAddr}&page=1&offset=${top}`;\n if (explorerApi.apiKey) {\n url += `&apikey=${explorerApi.apiKey}`;\n }\n\n // Fetch top holders\n let body: { status?: string; result?: unknown };\n try {\n const resp = await fetch(url);\n body = (await resp.json()) as { status?: string; result?: unknown };\n } catch (e) {\n printOutput({ error: `Explorer API request failed: ${e instanceof Error ? e.message : String(e)}` }, mode);\n return;\n }\n\n if (body.status !== \"1\") {\n const msg = typeof body.result === \"string\" ? body.result : \"Unknown error\";\n if (msg.includes(\"API Key\") || msg.includes(\"apikey\")) {\n printOutput(\n { error: \"Explorer API requires API key. Set ETHERSCAN_API_KEY environment variable.\" },\n mode,\n );\n return;\n }\n printOutput({ error: `Explorer API error: ${msg}` }, mode);\n return;\n }\n\n const holders = Array.isArray(body.result) ? body.result : [];\n\n // Parse holders\n const whaleList: Array<{ address: Address; balance: number }> = [];\n for (const h of holders) {\n const addrStr: string = h[\"TokenHolderAddress\"] ?? \"\";\n const qtyStr: string = h[\"TokenHolderQuantity\"] ?? \"0\";\n if (/^0x[0-9a-fA-F]{40}$/.test(addrStr)) {\n const raw = BigInt(qtyStr || \"0\");\n const balance = Number(raw) / 10 ** token.decimals;\n whaleList.push({ address: addrStr as Address, balance });\n }\n }\n\n const whaleData: unknown[] = [];\n\n if (opts.positions && whaleList.length > 0) {\n // Get lending pools\n const lendingPools = registry\n .getProtocolsForChain(chainName)\n .filter(\n (p) =>\n p.category === ProtocolCategory.Lending &&\n (p.interface === \"aave_v3\" || p.interface === \"aave_v2\"),\n )\n .filter((p) => p.contracts?.[\"pool\"])\n .map((p) => ({\n name: p.name,\n pool: p.contracts![\"pool\"] as Address,\n iface: p.interface,\n }));\n\n // Build multicall: each whale × each pool\n const calls: Array<[Address, Hex]> = [];\n for (const whale of whaleList) {\n for (const { pool } of lendingPools) {\n calls.push([\n pool,\n encodeFunctionData({ abi: POOL_ABI, functionName: \"getUserAccountData\", args: [whale.address] }),\n ]);\n }\n }\n\n let results: (Hex | null)[] = [];\n if (calls.length > 0) {\n try {\n results = await multicallRead(rpc, calls);\n } catch {\n results = [];\n }\n }\n\n const poolsPerWhale = lendingPools.length;\n\n for (let wi = 0; wi < whaleList.length; wi++) {\n const whale = whaleList[wi]!;\n const positions: unknown[] = [];\n\n for (let pi = 0; pi < lendingPools.length; pi++) {\n const { name: protoName, iface } = lendingPools[pi]!;\n const idx = wi * poolsPerWhale + pi;\n const data = results[idx] ?? null;\n\n if (data && data.length >= 2 + 192 * 2) {\n const dec = iface === \"aave_v2\" ? 18 : 8;\n const divisor = 10 ** dec;\n const collateral = Number(decodeU256(data, 0)) / divisor;\n const debt = Number(decodeU256(data, 1)) / divisor;\n const hfRaw = decodeU256(data, 5);\n let hf: number | null = null;\n if (hfRaw <= BigInt(\"0xffffffffffffffffffffffffffffffff\")) {\n const v = Number(hfRaw) / 1e18;\n hf = v > 1e10 ? null : round2(v);\n }\n\n if (collateral > 0.01 || debt > 0.01) {\n positions.push({\n protocol: protoName,\n collateral_usd: round2(collateral),\n debt_usd: round2(debt),\n health_factor: hf,\n });\n }\n }\n }\n\n whaleData.push({\n rank: wi + 1,\n address: whale.address,\n balance: round4(whale.balance),\n positions,\n });\n }\n } else {\n for (let wi = 0; wi < whaleList.length; wi++) {\n const whale = whaleList[wi]!;\n whaleData.push({\n rank: wi + 1,\n address: whale.address,\n balance: round4(whale.balance),\n });\n }\n }\n\n printOutput(\n {\n chain: chain.name,\n token: opts.token,\n token_address: tokenAddr,\n decimals: token.decimals,\n top,\n holders: whaleData,\n explorer: chain.explorer_url ?? \"\",\n },\n mode,\n );\n });\n}\n","import { spawnSync } from \"child_process\";\nimport type { Command } from \"commander\";\nimport { Registry, ProtocolCategory } from \"@hypurrquant/defi-core\";\nimport { createLending } from \"@hypurrquant/defi-protocols\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\n\nfunction round2(x: number): number {\n return Math.round(x * 100) / 100;\n}\n\n/** Fetch perp funding rates by calling `perp --json arb scan --rates` */\nasync function fetchPerpRates(): Promise<unknown[]> {\n // Try global `perp` first, then npx fallback\n let result = spawnSync(\"perp\", [\"--json\", \"arb\", \"scan\", \"--rates\"], { encoding: \"utf8\", timeout: 30000 });\n if (result.error || result.status !== 0) {\n result = spawnSync(\"npx\", [\"-y\", \"perp-cli@latest\", \"--json\", \"arb\", \"scan\", \"--rates\"], {\n encoding: \"utf8\",\n timeout: 60000,\n });\n }\n\n if (result.error || result.status !== 0) {\n throw new Error(\"perp-cli not found or failed\");\n }\n\n let data: unknown;\n try {\n data = JSON.parse(result.stdout);\n } catch {\n throw new Error(\"perp JSON parse error\");\n }\n\n const d = data as Record<string, unknown>;\n const symbolsRaw =\n (d[\"data\"] as Record<string, unknown> | undefined)?.[\"symbols\"] ??\n d[\"symbols\"];\n const symbols = Array.isArray(symbolsRaw) ? symbolsRaw : [];\n\n const results: unknown[] = [];\n for (const sym of symbols as Array<Record<string, unknown>>) {\n const symbol = (sym[\"symbol\"] as string) ?? \"?\";\n const maxSpread = (sym[\"maxSpreadAnnual\"] as number) ?? 0;\n const longEx = (sym[\"longExchange\"] as string) ?? \"?\";\n const shortEx = (sym[\"shortExchange\"] as string) ?? \"?\";\n\n if (Math.abs(maxSpread) > 0) {\n results.push({\n type: \"perp_funding\",\n asset: symbol,\n apy: round2(maxSpread),\n detail: `long ${longEx} / short ${shortEx}`,\n risk: Math.abs(maxSpread) > 50 ? \"high\" : Math.abs(maxSpread) > 20 ? \"medium\" : \"low\",\n source: \"perp-cli\",\n });\n }\n\n const rates = Array.isArray(sym[\"rates\"]) ? (sym[\"rates\"] as Array<Record<string, unknown>>) : [];\n for (const rate of rates) {\n const exchange = (rate[\"exchange\"] as string) ?? \"?\";\n const annual = (rate[\"annualizedPct\"] as number) ?? 0;\n if (Math.abs(annual) > 1.0) {\n results.push({\n type: \"perp_rate\",\n asset: symbol,\n apy: round2(annual),\n detail: exchange,\n risk: Math.abs(annual) > 50 ? \"high\" : Math.abs(annual) > 20 ? \"medium\" : \"low\",\n source: \"perp-cli\",\n });\n }\n }\n }\n\n return results;\n}\n\n/** Fetch lending supply rates across all chains for a given asset */\nasync function fetchLendingRates(registry: Registry, asset: string): Promise<unknown[]> {\n const chainKeys = Array.from(registry.chains.keys());\n\n const tasks = chainKeys.map(async (ck) => {\n try {\n const chain = registry.getChain(ck);\n const chainName = chain.name.toLowerCase();\n\n let assetAddr: `0x${string}`;\n try {\n assetAddr = registry.resolveToken(chainName, asset).address;\n } catch {\n return [];\n }\n\n const protos = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending && p.interface === \"aave_v3\");\n\n if (protos.length === 0) return [];\n\n const rpc = chain.effectiveRpcUrl();\n const rates: unknown[] = [];\n\n for (const proto of protos) {\n try {\n const lending = createLending(proto, rpc);\n const r = await lending.getRates(assetAddr);\n if (r.supply_apy > 0) {\n rates.push({\n type: \"lending_supply\",\n asset,\n apy: round2(r.supply_apy * 100),\n detail: `${r.protocol} (${chain.name})`,\n risk: \"low\",\n source: \"defi-cli\",\n });\n }\n } catch {\n // skip unavailable protocols\n }\n }\n\n return rates;\n } catch {\n return [];\n }\n });\n\n const nested = await Promise.all(tasks);\n return nested.flat();\n}\n\nexport function registerCompare(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"compare\")\n .description(\"Compare all yield sources: perp funding vs lending APY vs staking\")\n .option(\"--asset <token>\", \"Token symbol to compare (e.g. USDC, ETH)\", \"USDC\")\n .option(\"--no-perps\", \"Exclude perp funding rates\")\n .option(\"--no-lending\", \"Exclude lending rates\")\n .option(\"--min-apy <pct>\", \"Minimum absolute APY to show\", \"1.0\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n const asset: string = opts.asset ?? \"USDC\";\n const includePerps: boolean = opts.perps !== false;\n const includeLending: boolean = opts.lending !== false;\n const minApy = parseFloat(opts.minApy ?? \"1.0\");\n\n const t0 = Date.now();\n const opportunities: unknown[] = [];\n\n // 1. Perp funding rates\n if (includePerps) {\n try {\n const perpData = await fetchPerpRates();\n for (const opp of perpData) {\n const apy = Math.abs((opp as Record<string, unknown>)[\"apy\"] as number ?? 0);\n if (apy >= minApy) opportunities.push(opp);\n }\n } catch {\n // perp-cli not available — skip silently\n }\n }\n\n // 2. Lending rates across all chains\n if (includeLending) {\n const lendingData = await fetchLendingRates(registry, asset);\n for (const opp of lendingData) {\n const apy = Math.abs((opp as Record<string, unknown>)[\"apy\"] as number ?? 0);\n if (apy >= minApy) opportunities.push(opp);\n }\n }\n\n // Sort by absolute APY descending\n opportunities.sort((a, b) => {\n const aApy = Math.abs((a as Record<string, unknown>)[\"apy\"] as number ?? 0);\n const bApy = Math.abs((b as Record<string, unknown>)[\"apy\"] as number ?? 0);\n return bApy - aApy;\n });\n\n const scanMs = Date.now() - t0;\n\n printOutput(\n {\n asset,\n scan_duration_ms: scanMs,\n total_opportunities: opportunities.length,\n opportunities,\n },\n getOpts(),\n );\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n process.exit(1);\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\n\nconst ODOS_API = \"https://api.odos.xyz\";\n\nexport function registerSwap(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n parent\n .command(\"swap\")\n .description(\"Aggregator swap: best price across all DEXes (ODOS)\")\n .requiredOption(\"--token-in <token>\", \"Input token symbol or address\")\n .requiredOption(\"--token-out <token>\", \"Output token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount of input token in wei\")\n .option(\"--slippage <bps>\", \"Slippage tolerance in basis points\", \"50\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const tokenIn = opts.tokenIn.startsWith(\"0x\") ? opts.tokenIn as Address : registry.resolveToken(chainName, opts.tokenIn).address as Address;\n const tokenOut = opts.tokenOut.startsWith(\"0x\") ? opts.tokenOut as Address : registry.resolveToken(chainName, opts.tokenOut).address as Address;\n const sender = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n\n try {\n const quoteRes = await fetch(`${ODOS_API}/sor/quote/v2`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n chainId: chain.chain_id, inputTokens: [{ tokenAddress: tokenIn, amount: opts.amount }],\n outputTokens: [{ tokenAddress: tokenOut, proportion: 1 }],\n slippageLimitPercent: parseInt(opts.slippage) / 100, userAddr: sender,\n }),\n });\n const quote = await quoteRes.json() as any;\n if (!quote.pathId) { printOutput({ error: \"No ODOS route found\", quote }, getOpts()); return; }\n\n const assembleRes = await fetch(`${ODOS_API}/sor/assemble`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ pathId: quote.pathId, userAddr: sender }),\n });\n const assembled = await assembleRes.json() as Record<string, Record<string, string>>;\n\n if (assembled.transaction) {\n const tx = {\n description: `ODOS swap ${tokenIn} → ${tokenOut}`,\n to: assembled.transaction.to as Address,\n data: assembled.transaction.data as `0x${string}`,\n value: BigInt(assembled.transaction.value ?? 0),\n };\n const result = await executor.execute(tx);\n printOutput({ ...result, odos_quote: quote }, getOpts());\n } else {\n printOutput({ error: \"ODOS assembly failed\", assembled }, getOpts());\n }\n } catch (e) {\n printOutput({ error: `ODOS API error: ${e instanceof Error ? e.message : String(e)}` }, getOpts());\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\n\nconst LIFI_API = \"https://li.quest/v1\";\nconst DLN_API = \"https://dln.debridge.finance/v1.0/dln/order\";\nconst CCTP_FEE_API = \"https://iris-api.circle.com/v2/burn/USDC/fees\";\n\n// ── deBridge DLN ──\n\nconst DLN_CHAIN_IDS: Record<string, number> = {\n ethereum: 1,\n optimism: 10,\n bnb: 56,\n polygon: 137,\n arbitrum: 42161,\n avalanche: 43114,\n base: 8453,\n linea: 59144,\n zksync: 324,\n};\n\nasync function getDebridgeQuote(\n srcChainId: number,\n dstChainId: number,\n srcToken: string,\n dstToken: string,\n amountRaw: string,\n recipient: string,\n): Promise<{ amountOut: string; estimatedTime: number; raw: unknown }> {\n const params = new URLSearchParams({\n srcChainId: String(srcChainId),\n srcChainTokenIn: srcToken,\n srcChainTokenInAmount: amountRaw,\n dstChainId: String(dstChainId),\n dstChainTokenOut: dstToken,\n prependOperatingExpenses: \"true\",\n });\n\n const res = await fetch(`${DLN_API}/quote?${params}`);\n if (!res.ok) throw new Error(`deBridge quote failed: ${res.status} ${await res.text()}`);\n const data = await res.json() as Record<string, unknown>;\n\n const estimation = data.estimation as Record<string, unknown>;\n const dstOut = estimation?.dstChainTokenOut as Record<string, unknown>;\n const amountOut = String(dstOut?.recommendedAmount ?? dstOut?.amount ?? \"0\");\n const fulfillDelay = Number((data.order as Record<string, unknown>)?.approximateFulfillmentDelay ?? 10);\n\n // Get create-tx data for the transaction\n const createParams = new URLSearchParams({\n srcChainId: String(srcChainId),\n srcChainTokenIn: srcToken,\n srcChainTokenInAmount: amountRaw,\n dstChainId: String(dstChainId),\n dstChainTokenOut: dstToken,\n dstChainTokenOutAmount: amountOut,\n dstChainTokenOutRecipient: recipient,\n srcChainOrderAuthorityAddress: recipient,\n dstChainOrderAuthorityAddress: recipient,\n prependOperatingExpenses: \"true\",\n });\n\n const createRes = await fetch(`${DLN_API}/create-tx?${createParams}`);\n if (!createRes.ok) throw new Error(`deBridge create-tx failed: ${createRes.status} ${await createRes.text()}`);\n const createData = await createRes.json() as Record<string, unknown>;\n\n return {\n amountOut,\n estimatedTime: fulfillDelay,\n raw: createData,\n };\n}\n\n// ── Circle CCTP ──\n\n// CCTP domains per chain (V2)\nconst CCTP_DOMAINS: Record<string, number> = {\n ethereum: 0,\n avalanche: 1,\n optimism: 2,\n arbitrum: 3,\n solana: 5,\n base: 6,\n polygon: 7,\n sui: 8,\n aptos: 9,\n};\n\n// TokenMessenger V2 contract address (same on all EVM chains)\nconst CCTP_TOKEN_MESSENGER_V2 = \"0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d\";\n\n// Native USDC addresses per chain\nconst CCTP_USDC_ADDRESSES: Record<string, string> = {\n ethereum: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\",\n avalanche: \"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E\",\n optimism: \"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85\",\n arbitrum: \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\",\n base: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n polygon: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\",\n};\n\nasync function getCctpFeeEstimate(\n srcDomain: number,\n dstDomain: number,\n amountUsdc: number,\n): Promise<{ fee: number; maxFeeSubunits: bigint }> {\n try {\n const res = await fetch(`${CCTP_FEE_API}/${srcDomain}/${dstDomain}`);\n if (res.ok) {\n const schedules = await res.json() as Array<{\n finalityThreshold: number;\n minimumFee: number;\n forwardFee?: { low: number; med: number; high: number };\n }>;\n // Use standard finality (2000) schedule\n const schedule = schedules.find(s => s.finalityThreshold === 2000) ?? schedules[0];\n if (schedule) {\n const amountSubunits = BigInt(Math.round(amountUsdc * 1e6));\n const bpsRounded = BigInt(Math.round(schedule.minimumFee * 100));\n const protocolFee = (amountSubunits * bpsRounded) / 1_000_000n;\n const protocolFeeBuffered = (protocolFee * 120n) / 100n;\n\n if (schedule.forwardFee) {\n const forwardFeeSubunits = BigInt(schedule.forwardFee.high);\n const totalMaxFee = protocolFeeBuffered + forwardFeeSubunits;\n return { fee: Number(totalMaxFee) / 1e6, maxFeeSubunits: totalMaxFee };\n }\n\n const minFee = protocolFeeBuffered > 0n ? protocolFeeBuffered : 10000n;\n return { fee: Number(minFee) / 1e6, maxFeeSubunits: minFee };\n }\n }\n } catch {\n // use fallback\n }\n return { fee: 0.25, maxFeeSubunits: 250000n };\n}\n\nexport function registerBridge(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"bridge\")\n .description(\"Cross-chain bridge: move assets between chains\")\n .requiredOption(\"--token <token>\", \"Token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .requiredOption(\"--to-chain <chain>\", \"Destination chain name\")\n .option(\"--recipient <address>\", \"Recipient address on destination chain\")\n .option(\"--slippage <bps>\", \"Slippage in bps (LI.FI only)\", \"50\")\n .option(\"--provider <name>\", \"Bridge provider: lifi, debridge, cctp\", \"lifi\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const fromChain = registry.getChain(chainName);\n const toChain = registry.getChain(opts.toChain);\n const tokenAddr = opts.token.startsWith(\"0x\") ? opts.token : registry.resolveToken(chainName, opts.token).address;\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const provider = (opts.provider as string).toLowerCase();\n\n if (provider === \"debridge\") {\n try {\n const srcId = DLN_CHAIN_IDS[chainName] ?? fromChain.chain_id;\n const dstId = DLN_CHAIN_IDS[opts.toChain] ?? toChain.chain_id;\n\n const result = await getDebridgeQuote(\n srcId, dstId,\n tokenAddr, tokenAddr,\n opts.amount,\n recipient,\n );\n\n const tx = (result.raw as Record<string, unknown>).tx as Record<string, unknown> | undefined;\n printOutput({\n from_chain: fromChain.name, to_chain: toChain.name,\n token: tokenAddr, amount: opts.amount,\n bridge: \"deBridge DLN\",\n estimated_output: result.amountOut,\n estimated_time_seconds: result.estimatedTime,\n tx: tx ? { to: tx.to, data: tx.data, value: tx.value } : undefined,\n }, getOpts());\n } catch (e) {\n printOutput({ error: `deBridge API error: ${e instanceof Error ? e.message : String(e)}` }, getOpts());\n }\n return;\n }\n\n if (provider === \"cctp\") {\n try {\n const srcDomain = CCTP_DOMAINS[chainName];\n const dstDomain = CCTP_DOMAINS[opts.toChain];\n\n if (srcDomain === undefined) {\n printOutput({ error: `CCTP not supported on source chain: ${chainName}. Supported: ${Object.keys(CCTP_DOMAINS).join(\", \")}` }, getOpts());\n return;\n }\n if (dstDomain === undefined) {\n printOutput({ error: `CCTP not supported on destination chain: ${opts.toChain}. Supported: ${Object.keys(CCTP_DOMAINS).join(\", \")}` }, getOpts());\n return;\n }\n\n const usdcSrc = CCTP_USDC_ADDRESSES[chainName];\n const usdcDst = CCTP_USDC_ADDRESSES[opts.toChain];\n if (!usdcSrc) {\n printOutput({ error: `No native USDC address known for ${chainName}. CCTP requires native USDC.` }, getOpts());\n return;\n }\n\n const amountUsdc = Number(BigInt(opts.amount)) / 1e6;\n const { fee, maxFeeSubunits } = await getCctpFeeEstimate(srcDomain, dstDomain, amountUsdc);\n\n // Build depositForBurn call data\n // TokenMessenger V2: depositForBurn(amount, destinationDomain, mintRecipient, burnToken, maxFee, minFinalityThreshold)\n // mintRecipient must be 32 bytes (left-padded address)\n const recipientPadded = `0x${\"0\".repeat(24)}${recipient.replace(\"0x\", \"\").toLowerCase()}` as `0x${string}`;\n\n const { encodeFunctionData, parseAbi } = await import(\"viem\");\n const tokenMessengerAbi = parseAbi([\n \"function depositForBurn(uint256 amount, uint32 destinationDomain, bytes32 mintRecipient, address burnToken, bytes32 destinationCaller, uint256 maxFee, uint32 minFinalityThreshold) external returns (uint64 nonce)\",\n ]);\n\n const data = encodeFunctionData({\n abi: tokenMessengerAbi,\n functionName: \"depositForBurn\",\n args: [\n BigInt(opts.amount),\n dstDomain,\n recipientPadded as `0x${string}`,\n usdcSrc as Address,\n `0x${\"0\".repeat(64)}` as `0x${string}`, // any caller\n maxFeeSubunits,\n 2000, // standard finality\n ],\n });\n\n printOutput({\n from_chain: fromChain.name, to_chain: toChain.name,\n token: usdcSrc,\n token_dst: usdcDst ?? tokenAddr,\n amount: opts.amount,\n bridge: \"Circle CCTP V2\",\n estimated_fee_usdc: fee,\n estimated_output: String(BigInt(opts.amount) - maxFeeSubunits),\n note: \"After burn, poll https://iris-api.circle.com/v2/messages/{srcDomain} for attestation, then call MessageTransmitter.receiveMessage() on destination\",\n tx: {\n to: CCTP_TOKEN_MESSENGER_V2,\n data,\n value: \"0x0\",\n },\n }, getOpts());\n } catch (e) {\n printOutput({ error: `CCTP error: ${e instanceof Error ? e.message : String(e)}` }, getOpts());\n }\n return;\n }\n\n // Default: LI.FI\n try {\n const params = new URLSearchParams({\n fromChain: String(fromChain.chain_id), toChain: String(toChain.chain_id),\n fromToken: tokenAddr, toToken: tokenAddr,\n fromAmount: opts.amount, fromAddress: recipient,\n slippage: String(parseInt(opts.slippage) / 10000),\n });\n const res = await fetch(`${LIFI_API}/quote?${params}`);\n const quote = await res.json() as any;\n\n if (quote.transactionRequest) {\n printOutput({\n from_chain: fromChain.name, to_chain: toChain.name,\n token: tokenAddr, amount: opts.amount,\n bridge: quote.toolDetails?.name ?? \"LI.FI\",\n estimated_output: quote.estimate?.toAmount,\n tx: { to: quote.transactionRequest.to, data: quote.transactionRequest.data, value: quote.transactionRequest.value },\n }, getOpts());\n } else {\n printOutput({ error: \"No LI.FI route found\", details: quote }, getOpts());\n }\n } catch (e) {\n printOutput({ error: `LI.FI API error: ${e instanceof Error ? e.message : String(e)}` }, getOpts());\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport { createNft } from \"@hypurrquant/defi-protocols\";\nimport type { Address } from \"viem\";\n\nexport function registerNft(parent: Command, getOpts: () => OutputMode): void {\n const nft = parent.command(\"nft\").description(\"NFT operations: collection info, ownership, balance\");\n\n nft.command(\"info\")\n .description(\"Get NFT collection info (name, symbol, total supply)\")\n .requiredOption(\"--collection <address>\", \"NFT collection contract address\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const nftProtocols = registry.getProtocolsByCategory(\"nft\" as any).filter(p => p.chain === chainName);\n const entry = nftProtocols[0] ?? { name: \"ERC721\", slug: \"erc721\", category: \"nft\", interface: \"erc721\", chain: chainName, contracts: { collection: opts.collection } };\n try {\n const adapter = createNft(entry, chain.effectiveRpcUrl());\n const info = await adapter.getCollectionInfo(opts.collection as Address);\n printOutput(info, getOpts());\n } catch (e) {\n printOutput({ error: e instanceof Error ? e.message : String(e) }, getOpts());\n }\n });\n\n nft.command(\"owner\")\n .description(\"Check who owns a specific NFT token ID\")\n .requiredOption(\"--collection <address>\", \"NFT collection contract address\")\n .requiredOption(\"--token-id <id>\", \"Token ID\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const nftProtocols = registry.getProtocolsByCategory(\"nft\" as any).filter(p => p.chain === chainName);\n const entry = nftProtocols[0] ?? { name: \"ERC721\", slug: \"erc721\", category: \"nft\", interface: \"erc721\", chain: chainName, contracts: { collection: opts.collection } };\n try {\n const adapter = createNft(entry, chain.effectiveRpcUrl());\n const info = await adapter.getTokenInfo(opts.collection as Address, BigInt(opts.tokenId));\n printOutput(info, getOpts());\n } catch (e) {\n printOutput({ error: e instanceof Error ? e.message : String(e) }, getOpts());\n }\n });\n\n nft.command(\"balance\")\n .description(\"Check how many NFTs an address holds in a collection\")\n .requiredOption(\"--collection <address>\", \"NFT collection contract address\")\n .requiredOption(\"--owner <address>\", \"Owner address to query\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const nftProtocols = registry.getProtocolsByCategory(\"nft\" as any).filter(p => p.chain === chainName);\n const entry = nftProtocols[0] ?? { name: \"ERC721\", slug: \"erc721\", category: \"nft\", interface: \"erc721\", chain: chainName, contracts: { collection: opts.collection } };\n try {\n const adapter = createNft(entry, chain.effectiveRpcUrl());\n const balance = await adapter.getBalance(opts.owner as Address, opts.collection as Address);\n printOutput({ collection: opts.collection, owner: opts.owner, balance }, getOpts());\n } catch (e) {\n printOutput({ error: e instanceof Error ? e.message : String(e) }, getOpts());\n }\n });\n\n nft.command(\"uri\")\n .description(\"Get token URI for a specific NFT\")\n .requiredOption(\"--collection <address>\", \"NFT collection contract address\")\n .requiredOption(\"--token-id <id>\", \"Token ID\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const nftProtocols = registry.getProtocolsByCategory(\"nft\" as any).filter(p => p.chain === chainName);\n const entry = nftProtocols[0] ?? { name: \"ERC721\", slug: \"erc721\", category: \"nft\", interface: \"erc721\", chain: chainName, contracts: { collection: opts.collection } };\n try {\n const adapter = createNft(entry, chain.effectiveRpcUrl());\n const info = await adapter.getTokenInfo(opts.collection as Address, BigInt(opts.tokenId));\n printOutput({ collection: opts.collection, token_id: opts.tokenId, token_uri: info.token_uri }, getOpts());\n } catch (e) {\n printOutput({ error: e instanceof Error ? e.message : String(e) }, getOpts());\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createMasterChef, MasterChefAdapter } from \"@hypurrquant/defi-protocols\";\n\nexport function registerFarm(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const farm = parent.command(\"farm\").description(\"LP farm operations: deposit, withdraw, claim rewards (MasterChef)\");\n\n farm.command(\"deposit\")\n .description(\"Deposit LP tokens into a MasterChef farm\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pid <pid>\", \"Farm pool ID\")\n .requiredOption(\"--amount <amount>\", \"LP token amount in wei\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMasterChef(protocol, rpcUrl);\n const tx = await adapter.buildDeposit(\n protocol.contracts?.[\"masterchef\"] as Address,\n BigInt(opts.amount),\n BigInt(opts.pid),\n );\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farm.command(\"withdraw\")\n .description(\"Withdraw LP tokens from a MasterChef farm\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pid <pid>\", \"Farm pool ID\")\n .requiredOption(\"--amount <amount>\", \"LP token amount in wei\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMasterChef(protocol, rpcUrl);\n const tx = await (adapter as MasterChefAdapter).buildWithdrawPid(\n BigInt(opts.pid),\n BigInt(opts.amount),\n );\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farm.command(\"claim\")\n .description(\"Claim pending rewards from a MasterChef farm\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pid <pid>\", \"Farm pool ID\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMasterChef(protocol, rpcUrl);\n const tx = await (adapter as MasterChefAdapter).buildClaimRewardsPid(\n BigInt(opts.pid),\n );\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farm.command(\"info\")\n .description(\"Show pending rewards and farm info\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .option(\"--pid <pid>\", \"Farm pool ID (optional)\")\n .option(\"--address <address>\", \"Wallet address to query (defaults to DEFI_WALLET_ADDRESS env)\")\n .action(async (opts) => {\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMasterChef(protocol, rpcUrl);\n const walletAddress = (opts.address ?? process.env[\"DEFI_WALLET_ADDRESS\"]) as Address | undefined;\n if (!walletAddress) {\n throw new Error(\"--address or DEFI_WALLET_ADDRESS required\");\n }\n const masterchef = protocol.contracts?.[\"masterchef\"] as Address;\n const rewards = await adapter.getPendingRewards(masterchef, walletAddress);\n printOutput(rewards, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { createKittenSwapFarming } from \"@hypurrquant/defi-protocols\";\n\nexport function registerFarming(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const farming = parent\n .command(\"farming\")\n .description(\"Algebra eternal farming operations (KittenSwap): enter, exit, collect rewards, claim, discover\");\n\n farming\n .command(\"enter\")\n .description(\"Enter farming: stake an NFT position to start earning rewards\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. kittenswap)\")\n .requiredOption(\"--pool <address>\", \"Pool address\")\n .requiredOption(\"--token-id <id>\", \"NFT position token ID\")\n .option(\"--owner <address>\", \"Owner address to receive claimed rewards (defaults to DEFI_WALLET_ADDRESS or private key address)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createKittenSwapFarming(protocol, rpcUrl);\n const owner = resolveOwner(opts.owner);\n const tx = await adapter.buildEnterFarming(\n BigInt(opts.tokenId),\n opts.pool as Address,\n owner,\n );\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farming\n .command(\"exit\")\n .description(\"Exit farming: unstake an NFT position\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. kittenswap)\")\n .requiredOption(\"--pool <address>\", \"Pool address\")\n .requiredOption(\"--token-id <id>\", \"NFT position token ID\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createKittenSwapFarming(protocol, rpcUrl);\n const tx = await adapter.buildExitFarming(\n BigInt(opts.tokenId),\n opts.pool as Address,\n );\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farming\n .command(\"rewards\")\n .description(\"Collect + claim farming rewards for a staked position (collectRewards + claimReward multicall)\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. kittenswap)\")\n .requiredOption(\"--pool <address>\", \"Pool address\")\n .requiredOption(\"--token-id <id>\", \"NFT position token ID\")\n .option(\"--owner <address>\", \"Owner address to receive claimed rewards (defaults to DEFI_WALLET_ADDRESS or private key address)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createKittenSwapFarming(protocol, rpcUrl);\n const owner = resolveOwner(opts.owner);\n const tx = await adapter.buildCollectRewards(\n BigInt(opts.tokenId),\n opts.pool as Address,\n owner,\n );\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farming\n .command(\"claim\")\n .description(\"Claim accumulated farming rewards (KITTEN + WHYPE) without changing position\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. kittenswap)\")\n .option(\"--owner <address>\", \"Owner address to receive rewards (defaults to DEFI_WALLET_ADDRESS or private key address)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createKittenSwapFarming(protocol, rpcUrl);\n const owner = resolveOwner(opts.owner);\n const tx = await adapter.buildClaimReward(owner);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farming\n .command(\"pending\")\n .description(\"Query pending farming rewards for a position (read-only)\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. kittenswap)\")\n .requiredOption(\"--pool <address>\", \"Pool address\")\n .requiredOption(\"--token-id <id>\", \"NFT position token ID\")\n .action(async (opts) => {\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createKittenSwapFarming(protocol, rpcUrl);\n const rewards = await adapter.getPendingRewards(\n BigInt(opts.tokenId),\n opts.pool as Address,\n );\n printOutput(\n {\n tokenId: opts.tokenId,\n pool: opts.pool,\n reward_kitten: rewards.reward.toString(),\n bonus_reward_whype: rewards.bonusReward.toString(),\n },\n getOpts(),\n );\n });\n\n farming\n .command(\"discover\")\n .description(\"Discover all pools with active KittenSwap farming incentives\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. kittenswap)\")\n .action(async (opts) => {\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createKittenSwapFarming(protocol, rpcUrl);\n const pools = await adapter.discoverFarmingPools();\n const output = pools.map((p) => ({\n pool: p.pool,\n nonce: p.key.nonce.toString(),\n total_reward: p.totalReward.toString(),\n bonus_reward: p.bonusReward.toString(),\n active: p.active,\n }));\n printOutput(output, getOpts());\n });\n}\n\n/** Resolve owner address from CLI option, env vars, or private key */\nfunction resolveOwner(optOwner?: string): Address {\n if (optOwner) return optOwner as Address;\n\n const walletAddr = process.env[\"DEFI_WALLET_ADDRESS\"];\n if (walletAddr) return walletAddr as Address;\n\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n if (privateKey) {\n return privateKeyToAccount(privateKey as `0x${string}`).address;\n }\n\n throw new Error(\n \"--owner, DEFI_WALLET_ADDRESS, or DEFI_PRIVATE_KEY is required to resolve reward recipient\",\n );\n}\n","import type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { createInterface } from \"readline\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { resolve } from \"path\";\n\nconst DEFI_DIR = resolve(process.env.HOME || \"~\", \".defi\");\nconst ENV_FILE = resolve(DEFI_DIR, \".env\");\n\n// ── .env helpers ──────────────────────────────────────────────\n\nfunction ensureDefiDir() {\n if (!existsSync(DEFI_DIR)) mkdirSync(DEFI_DIR, { recursive: true, mode: 0o700 });\n}\n\nfunction loadEnvFile(): Record<string, string> {\n if (!existsSync(ENV_FILE)) return {};\n const lines = readFileSync(ENV_FILE, \"utf-8\").split(\"\\n\");\n const env: Record<string, string> = {};\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eqIdx = trimmed.indexOf(\"=\");\n if (eqIdx > 0) {\n env[trimmed.slice(0, eqIdx)] = trimmed.slice(eqIdx + 1);\n }\n }\n return env;\n}\n\nfunction writeEnvFile(env: Record<string, string>) {\n ensureDefiDir();\n const lines = [\n \"# defi-cli configuration\",\n \"# Generated by 'defi setup' — edit freely\",\n \"\",\n ];\n for (const [key, value] of Object.entries(env)) {\n lines.push(`${key}=${value}`);\n }\n lines.push(\"\");\n writeFileSync(ENV_FILE, lines.join(\"\\n\"), { mode: 0o600 });\n}\n\n// ── Interactive helpers ────────────────────────────────────────\n\nfunction ask(rl: ReturnType<typeof createInterface>, question: string): Promise<string> {\n return new Promise((res) => rl.question(question, (answer) => res(answer.trim())));\n}\n\n// ── Validation helpers ─────────────────────────────────────────\n\nfunction isValidAddress(s: string): boolean {\n return /^0x[0-9a-fA-F]{40}$/.test(s);\n}\n\nfunction isValidPrivateKey(s: string): boolean {\n return /^0x[0-9a-fA-F]{64}$/.test(s);\n}\n\nasync function deriveAddress(privateKey: string): Promise<string | null> {\n try {\n const { privateKeyToAccount } = await import(\"viem/accounts\");\n const account = privateKeyToAccount(privateKey as `0x${string}`);\n return account.address;\n } catch {\n return null;\n }\n}\n\n// ── Command ────────────────────────────────────────────────────\n\nexport function registerSetup(program: Command) {\n program\n .command(\"setup\")\n .alias(\"init\")\n .description(\"Interactive setup wizard — configure wallet & RPC URLs\")\n .action(async () => {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n\n try {\n console.log(pc.cyan(pc.bold(\"\\n defi-cli Setup Wizard\\n\")));\n\n // Show current config if it exists\n const existing = loadEnvFile();\n if (Object.keys(existing).length > 0) {\n console.log(pc.white(\" Current configuration:\"));\n for (const [key, value] of Object.entries(existing)) {\n const masked =\n key.toLowerCase().includes(\"key\")\n ? value.slice(0, 6) + \"...\" + value.slice(-4)\n : value;\n console.log(` ${pc.cyan(key.padEnd(24))} ${pc.gray(masked)}`);\n }\n console.log();\n const overwrite = await ask(rl, \" Overwrite existing config? (y/N): \");\n if (overwrite.toLowerCase() !== \"y\" && overwrite.toLowerCase() !== \"yes\") {\n console.log(pc.gray(\"\\n Keeping existing configuration.\\n\"));\n rl.close();\n return;\n }\n console.log();\n }\n\n const newEnv: Record<string, string> = {};\n\n // ── Wallet address / private key ──\n console.log(pc.cyan(pc.bold(\" Wallet\")));\n\n const privateKey = await ask(rl, \" Private key (optional, for --broadcast, 0x...): \");\n if (privateKey) {\n const normalized = privateKey.startsWith(\"0x\") ? privateKey : `0x${privateKey}`;\n if (!isValidPrivateKey(normalized)) {\n console.log(pc.red(\" Invalid private key (must be 0x + 64 hex chars). Skipped.\"));\n } else {\n newEnv.DEFI_PRIVATE_KEY = normalized;\n const derived = await deriveAddress(normalized);\n if (derived) {\n newEnv.DEFI_WALLET_ADDRESS = derived;\n console.log(` ${pc.green(\"OK\")} derived address: ${pc.gray(derived)}`);\n }\n }\n }\n\n if (!newEnv.DEFI_WALLET_ADDRESS) {\n const address = await ask(rl, \" Wallet address (0x...): \");\n if (address) {\n if (!isValidAddress(address)) {\n console.log(pc.yellow(\" Invalid address format. Skipping.\"));\n } else {\n newEnv.DEFI_WALLET_ADDRESS = address;\n console.log(` ${pc.green(\"OK\")} ${pc.gray(address)}`);\n }\n }\n }\n\n // ── RPC URLs ──\n console.log(pc.cyan(pc.bold(\"\\n RPC URLs\")) + pc.gray(\" (press Enter to use public defaults)\"));\n\n const hyperevmRpc = await ask(rl, \" HyperEVM RPC URL: \");\n if (hyperevmRpc) {\n newEnv.HYPEREVM_RPC_URL = hyperevmRpc;\n console.log(` ${pc.green(\"OK\")} HyperEVM RPC set`);\n }\n\n const mantleRpc = await ask(rl, \" Mantle RPC URL: \");\n if (mantleRpc) {\n newEnv.MANTLE_RPC_URL = mantleRpc;\n console.log(` ${pc.green(\"OK\")} Mantle RPC set`);\n }\n\n // Merge with existing non-overwritten keys (keep old keys not touched above)\n const finalEnv = { ...existing, ...newEnv };\n\n // Write .env\n writeEnvFile(finalEnv);\n\n // Summary\n console.log(pc.cyan(pc.bold(\"\\n Setup Complete!\\n\")));\n console.log(` Config: ${pc.gray(ENV_FILE)}`);\n if (finalEnv.DEFI_WALLET_ADDRESS) {\n console.log(` Wallet: ${pc.gray(finalEnv.DEFI_WALLET_ADDRESS)}`);\n }\n if (finalEnv.DEFI_PRIVATE_KEY) {\n console.log(` Key: ${pc.green(\"configured\")}`);\n }\n if (finalEnv.HYPEREVM_RPC_URL) {\n console.log(` HyperEVM RPC: ${pc.gray(finalEnv.HYPEREVM_RPC_URL)}`);\n }\n if (finalEnv.MANTLE_RPC_URL) {\n console.log(` Mantle RPC: ${pc.gray(finalEnv.MANTLE_RPC_URL)}`);\n }\n\n console.log(pc.bold(pc.white(\"\\n Next steps:\")));\n console.log(` ${pc.green(\"defi portfolio\")} view balances & positions`);\n console.log(` ${pc.green(\"defi scan\")} scan for exploits`);\n console.log(` ${pc.green(\"defi dex quote\")} get a swap quote`);\n console.log(` ${pc.green(\"defi --help\")} browse all commands\\n`);\n\n rl.close();\n } catch (err) {\n rl.close();\n throw err;\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createMerchantMoeLB } from \"@hypurrquant/defi-protocols\";\n\nexport function registerLB(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const lb = parent.command(\"lb\").description(\"Merchant Moe Liquidity Book: add/remove liquidity, rewards, positions\");\n\n lb.command(\"add\")\n .description(\"Add liquidity to a Liquidity Book pair\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. merchantmoe-mantle)\")\n .requiredOption(\"--pool <address>\", \"LB pair address\")\n .requiredOption(\"--token-x <address>\", \"Token X address\")\n .requiredOption(\"--token-y <address>\", \"Token Y address\")\n .requiredOption(\"--bin-step <step>\", \"Bin step of the pair\")\n .option(\"--amount-x <wei>\", \"Amount of token X in wei\", \"0\")\n .option(\"--amount-y <wei>\", \"Amount of token Y in wei\", \"0\")\n .option(\"--bins <N>\", \"Number of bins on each side of active bin\", \"5\")\n .option(\"--active-id <id>\", \"Active bin id (defaults to on-chain query)\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"mantle\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMerchantMoeLB(protocol, rpcUrl);\n const recipient = (opts.recipient ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildAddLiquidity({\n pool: opts.pool as Address,\n tokenX: opts.tokenX as Address,\n tokenY: opts.tokenY as Address,\n binStep: parseInt(opts.binStep),\n amountX: BigInt(opts.amountX),\n amountY: BigInt(opts.amountY),\n numBins: parseInt(opts.bins),\n activeIdDesired: opts.activeId ? parseInt(opts.activeId) : undefined,\n recipient,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n lb.command(\"remove\")\n .description(\"Remove liquidity from Liquidity Book bins\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--token-x <address>\", \"Token X address\")\n .requiredOption(\"--token-y <address>\", \"Token Y address\")\n .requiredOption(\"--bin-step <step>\", \"Bin step of the pair\")\n .requiredOption(\"--bins <binIds>\", \"Comma-separated bin IDs to remove from\")\n .requiredOption(\"--amounts <amounts>\", \"Comma-separated LB token amounts to remove per bin (wei)\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createMerchantMoeLB(protocol);\n const recipient = (opts.recipient ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const binIds = (opts.bins as string).split(\",\").map((s: string) => parseInt(s.trim()));\n const amounts = (opts.amounts as string).split(\",\").map((s: string) => BigInt(s.trim()));\n const tx = await adapter.buildRemoveLiquidity({\n tokenX: opts.tokenX as Address,\n tokenY: opts.tokenY as Address,\n binStep: parseInt(opts.binStep),\n binIds,\n amounts,\n recipient,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n lb.command(\"rewards\")\n .description(\"Show pending MOE rewards for a pool\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pool <address>\", \"LB pair address\")\n .option(\"--bins <binIds>\", \"Comma-separated bin IDs to check (auto-detected from rewarder range if omitted)\")\n .option(\"--address <address>\", \"Wallet address (defaults to DEFI_WALLET_ADDRESS)\")\n .action(async (opts) => {\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"mantle\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMerchantMoeLB(protocol, rpcUrl);\n const user = (opts.address ?? process.env[\"DEFI_WALLET_ADDRESS\"]) as Address | undefined;\n if (!user) throw new Error(\"--address or DEFI_WALLET_ADDRESS required\");\n const binIds = opts.bins ? (opts.bins as string).split(\",\").map((s: string) => parseInt(s.trim())) : undefined;\n const rewards = await adapter.getPendingRewards(user, opts.pool as Address, binIds);\n printOutput(rewards, getOpts());\n });\n\n lb.command(\"claim\")\n .description(\"Claim pending MOE rewards from a pool\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pool <address>\", \"LB pair address\")\n .option(\"--bins <binIds>\", \"Comma-separated bin IDs to claim from (auto-detected from rewarder range if omitted)\")\n .option(\"--address <address>\", \"Wallet address (defaults to DEFI_WALLET_ADDRESS)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"mantle\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMerchantMoeLB(protocol, rpcUrl);\n const user = (opts.address ?? process.env[\"DEFI_WALLET_ADDRESS\"]) as Address | undefined;\n if (!user) throw new Error(\"--address or DEFI_WALLET_ADDRESS required\");\n const binIds = opts.bins ? (opts.bins as string).split(\",\").map((s: string) => parseInt(s.trim())) : undefined;\n const tx = await adapter.buildClaimRewards(user, opts.pool as Address, binIds);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n lb.command(\"discover\")\n .description(\"Find all rewarded LB pools on chain\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .option(\"--active-only\", \"Only show non-stopped pools\")\n .action(async (opts) => {\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"mantle\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMerchantMoeLB(protocol, rpcUrl);\n let pools = await adapter.discoverRewardedPools();\n if (opts.activeOnly) {\n pools = pools.filter((p) => !p.stopped);\n }\n printOutput(pools, getOpts());\n });\n\n lb.command(\"positions\")\n .description(\"Show user positions per bin in a LB pool\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pool <address>\", \"LB pair address\")\n .option(\"--bins <binIds>\", \"Comma-separated bin IDs to query (auto-detected from rewarder range or active ± 50 if omitted)\")\n .option(\"--address <address>\", \"Wallet address (defaults to DEFI_WALLET_ADDRESS)\")\n .action(async (opts) => {\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"mantle\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMerchantMoeLB(protocol, rpcUrl);\n const user = (opts.address ?? process.env[\"DEFI_WALLET_ADDRESS\"]) as Address | undefined;\n if (!user) throw new Error(\"--address or DEFI_WALLET_ADDRESS required\");\n const binIds = opts.bins ? (opts.bins as string).split(\",\").map((s: string) => parseInt(s.trim())) : undefined;\n const positions = await adapter.getUserPositions(user, opts.pool as Address, binIds);\n printOutput(positions, getOpts());\n });\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,SAAS,qBAAqB;;;ACD9B,SAAS,sBAAAA,qBAAoB,oBAAoB,QAAAC,OAAM,YAAAC,WAAU,sBAAAC,2BAA0B;AAE3F,SAAS,2BAA2B;;;AIDpC,SAAS,oBAAoB,gBAAgB;ACD7C,SAAS,oBAAoB,YAA+B;ACC5D,SAAS,sBAAAC,qBAAoB,sBAAsB,YAAAC,iBAAgB;AGDnE,SAAS,cAAc,mBAAmB;AAC1C,SAAS,eAAe;AACxB,SAAS,qBAAqB;;;ACyB9B,SAAS,kBAAkB,QAAQ,KAAK;AACpC,MAAI,QAAQ,OAAO,MAAM,GAAG,GAAG,EAAE,MAAM,aAAa;AACpD,SAAO,CAAC,MAAM,QAAQ,MAAM,IAAI,EAAE,SAAS,CAAC;AAChD;AACA,SAAS,cAAc,QAAQ,MAAM,QAAQ;AACzC,MAAI,QAAQ,OAAO,MAAM,aAAa;AACtC,MAAI,YAAY;AAChB,MAAI,aAAa,KAAK,MAAM,OAAO,CAAC,IAAI,KAAK;AAC7C,WAAS,IAAI,OAAO,GAAG,KAAK,OAAO,GAAG,KAAK;AACvC,QAAI,IAAI,MAAM,IAAI,CAAC;AACnB,QAAI,CAAC;AACD;AACJ,iBAAa,EAAE,SAAS,EAAE,OAAO,WAAW,GAAG;AAC/C,iBAAa;AACb,iBAAa;AACb,iBAAa;AACb,QAAI,MAAM,MAAM;AACZ,mBAAa,IAAI,OAAO,YAAY,SAAS,CAAC;AAC9C,mBAAa;AAAA,IACjB;AAAA,EACJ;AACA,SAAO;AACX;AACO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY,SAAS,SAAS;AAC1B,U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CAAC,KAAK,WAAW,MAAM,gBAAgB,GAAG,MAAM,YAAY;AACnF;AAGA,eAAe,SAAS,aAAa;AACrC,eAAe,SAAS,aAAa;AACrC,YAAY,SAAS,eAAe,YAAY;AAChD,cAAc,SAAS,eAAe,YAAY;AAClD,gBAAgB,SAAS,eAAe,YAAY;AACpD,YAAY,SAAS,eAAe,YAAY;AAChD,gBAAgB,SAAS,eAAe,YAAY;AACpD,cAAc,SAAS,eAAe,YAAY;AAClD,cAAc,SAAS,eAAe,YAAY;AAClD,kBAAkB,SAAS,aAAa;AACxC,gBAAgB,SAAS,aAAa;AACtC,cAAc,SAAS,aAAa;AACpC,aAAa,SAAS,aAAa;AACnC,YAAY,SAAS,eAAe,YAAY;AAChD,kBAAkB,SAAS,aAAa;AACxC,cAAc,SAAS,aAAa;AACpC,eAAe,SAAS,aAAa;AACrC,cAAc,SAAS,eAAe,YAAY;AAClD,eAAe,SAAS,aAAa;AACrC,gBAAgB,SAAS,aAAa;AACtC,aAAa,SAAS,eAAe,YAAY;AACjD,eAAe,SAAS,aAAa;AACrC,YAAY,SAAS,aAAa;AAClC,aAAa,SAAS,eAAe,YAAY;AACjD,gBAAgB,SAAS,eAAe,YAAY;AACpD,WAAW,SAAS,eAAe,YAAY;AAC/C,cAAc,OAAO;AAGrB,QACG,QAAQ,OAAO,EACf,YAAY,2DAA2D,EACvE,OAAO,YAAY;AAElB,QAAM,WAAW,aAAa;AAC9B,UAAQ,OAAO,MAAM,mDAAmD;AAGxE,UAAQ,OAAO,MAAM,oDAAoD;AACzE,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["createPublicClient","http","parseAbi","encodeFunctionData","encodeFunctionData","parseAbi","endPtr","TxStatus","InterestRateMode","parseAbi","encodeFunctionData","ProtocolCategory","parseAbi","encodeFunctionData","createPublicClient","http","jsonVal","createPublicClient","http","encodeFunctionData","parseAbi","createPublicClient","http","encodeFunctionData","parseAbi","createPublicClient","http","decodeFunctionResult","decodeAbiParameters","encodeFunctionData","parseAbi","createPublicClient","http","decodeAbiParameters","encodeFunctionData","parseAbi","zeroAddress","encodeFunctionData","parseAbi","encodeFunctionData","parseAbi","decodeAbiParameters","encodeFunctionData","parseAbi","createPublicClient","http","zeroAddress","createPublicClient","decodeFunctionResult","encodeFunctionData","http","parseAbi","zeroAddress","encodeFunctionData","parseAbi","zeroAddress","createPublicClient","decodeFunctionResult","encodeFunctionData","http","parseAbi","zeroAddress","encodeFunctionData","parseAbi","createPublicClient","http","encodeFunctionData","decodeFunctionResult","parseAbi","createPublicClient","http","decodeAbiParameters","encodeFunctionData","http","createPublicClient","parseAbi","decodeFunctionResult","zeroAddress","createPublicClient","http","parseAbi","encodeFunctionData","decodeFunctionResult","zeroAddress","createPublicClient","http","parseAbi","encodeFunctionData","zeroAddress","createPublicClient","http","parseAbi","createPublicClient","http","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","encodeFunctionData","parseAbi","encodeFunctionData","decodeFunctionResult","zeroAddress","createPublicClient","http","parseAbi","encodeFunctionData","zeroAddress","createPublicClient","http","parseAbi","createPublicClient","http","parseAbi","encodeFunctionData","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","encodeFunctionData","zeroAddress","createPublicClient","http","parseAbi","encodeFunctionData","zeroAddress","parseAbi","encodeFunctionData","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","parseAbi","encodeFunctionData","client","createPublicClient","http","amountOut","best","DefiError","decodeFunctionResult","decodeAbiParameters","abi","result","zeroAddress","poolAbi","multicallRead","veAbi","voterAbi","_addressDecodeAbi","decodeAddress","_symbolDecodeAbi","decodeSymbol","algebraFactoryAbi","data","lbQuoterAbi","erc20Abi","ids","HYPEREVM_TOKENS","positionManagerAbi","ERC20_ABI","SECONDS_PER_YEAR","POOL_ABI","u256ToF64","InterestRateMode","ORACLE_ABI","decodeU256","parseAbi","parseAbi","parseAbi","DefiError","createPublicClient","http","DefiError","makeExecutor","privateKeyToAccount","privateKeyToAccount","makeExecutor","makeExecutor","makeExecutor","makeExecutor","makeExecutor","makeExecutor","amountWei","encodeFunctionData","parseAbi","readdirSync","readFileSync","existsSync","resolve","encodeFunctionData","parseAbi","ERC20_ABI","parseAbi","ORACLE_ABI","POOL_ABI","resolve","encodeFunctionData","existsSync","readdirSync","readFileSync","ERC20_ABI","parseAbi","POOL_ABI","ORACLE_ABI","decodeU256","encodeFunctionData","encodeFunctionData","parseAbi","parseAbi","encodeFunctionData","makeExecutor","encodeFunctionData","parseAbi","ERC20_ABI","parseAbi","POOL_ABI","ORACLE_ABI","round2","round4","decodeU256","encodeFunctionData","round2","resolveAsset","createPublicClient","http","createPublicClient","http","makeExecutor","encodeFunctionData","parseAbi","POOL_ABI","parseAbi","round2","round4","decodeU256","encodeFunctionData","round2","makeExecutor","encodeFunctionData","parseAbi","makeExecutor","privateKeyToAccount","makeExecutor","privateKeyToAccount","pc","existsSync","mkdirSync","readFileSync","writeFileSync","resolve","privateKeyToAccount","program","makeExecutor"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/executor.ts","../../defi-core/src/types.ts","../../defi-core/src/error.ts","../../defi-core/src/json.ts","../../defi-core/src/erc20.ts","../../defi-core/src/provider.ts","../../defi-core/src/multicall.ts","../../defi-core/src/registry/chain.ts","../../defi-core/src/registry/protocol.ts","../../defi-core/src/registry/registry.ts","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/error.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/util.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/date.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/primitive.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/extract.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/struct.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/parse.js","../src/table.ts","../src/output.ts","../src/commands/status.ts","../src/agent.ts","../src/commands/schema.ts","../../defi-protocols/src/factory.ts","../../defi-protocols/src/dex/uniswap_v3.ts","../../defi-protocols/src/dex/uniswap_v2.ts","../../defi-protocols/src/dex/algebra_v3.ts","../../defi-protocols/src/dex/tick_math.ts","../../defi-protocols/src/dex/balancer_v3.ts","../../defi-protocols/src/dex/curve.ts","../../defi-protocols/src/dex/solidly.ts","../../defi-protocols/src/dex/thena_cl.ts","../../defi-protocols/src/dex/hybra_gauge.ts","../../defi-protocols/src/dex/woofi.ts","../../defi-protocols/src/dex/solidly_gauge.ts","../../defi-protocols/src/dex/masterchef.ts","../../defi-protocols/src/dex/merchant_moe_lb.ts","../../defi-protocols/src/dex/kittenswap_farming.ts","../../defi-protocols/src/lending/aave_v3.ts","../../defi-protocols/src/lending/aave_v2.ts","../../defi-protocols/src/lending/aave_oracle.ts","../../defi-protocols/src/lending/compound_v2.ts","../../defi-protocols/src/lending/compound_v3.ts","../../defi-protocols/src/lending/euler_v2.ts","../../defi-protocols/src/lending/morpho.ts","../../defi-protocols/src/cdp/felix.ts","../../defi-protocols/src/cdp/felix_oracle.ts","../../defi-protocols/src/vault/erc4626.ts","../../defi-protocols/src/liquid_staking/generic_lst.ts","../../defi-protocols/src/liquid_staking/sthype.ts","../../defi-protocols/src/liquid_staking/kinetiq.ts","../../defi-protocols/src/yield_source/pendle.ts","../../defi-protocols/src/yield_source/generic_yield.ts","../../defi-protocols/src/derivatives/hlp.ts","../../defi-protocols/src/derivatives/generic_derivatives.ts","../../defi-protocols/src/options/rysk.ts","../../defi-protocols/src/options/generic_options.ts","../../defi-protocols/src/nft/erc721.ts","../../defi-protocols/src/dex/dex_price.ts","../src/commands/dex.ts","../src/commands/gauge.ts","../src/commands/lending.ts","../src/commands/cdp.ts","../src/commands/staking.ts","../src/commands/vault.ts","../src/commands/yield.ts","../src/commands/portfolio.ts","../src/portfolio-tracker.ts","../src/commands/monitor.ts","../src/commands/alert.ts","../src/commands/scan.ts","../src/commands/arb.ts","../src/commands/positions.ts","../src/commands/price.ts","../src/commands/wallet.ts","../src/commands/token.ts","../src/commands/whales.ts","../src/commands/compare.ts","../src/commands/swap.ts","../src/commands/bridge.ts","../src/commands/nft.ts","../src/commands/farm.ts","../src/commands/farming.ts","../src/commands/setup.ts","../src/commands/lb.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { createRequire } from \"node:module\";\nimport { Executor } from \"./executor.js\";\nimport { parseOutputMode } from \"./output.js\";\nimport type { OutputMode } from \"./output.js\";\nimport { runAgent } from \"./agent.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\n\nconst _require = createRequire(import.meta.url);\nconst _pkg = _require(\"../package.json\") as { version: string };\n\nimport { registerStatus } from \"./commands/status.js\";\nimport { registerSchema } from \"./commands/schema.js\";\nimport { registerDex } from \"./commands/dex.js\";\nimport { registerGauge } from \"./commands/gauge.js\";\nimport { registerLending } from \"./commands/lending.js\";\nimport { registerCdp } from \"./commands/cdp.js\";\nimport { registerStaking } from \"./commands/staking.js\";\nimport { registerVault } from \"./commands/vault.js\";\nimport { registerYield } from \"./commands/yield.js\";\nimport { registerPortfolio } from \"./commands/portfolio.js\";\nimport { registerMonitor } from \"./commands/monitor.js\";\nimport { registerAlert } from \"./commands/alert.js\";\nimport { registerScan } from \"./commands/scan.js\";\nimport { registerArb } from \"./commands/arb.js\";\nimport { registerPositions } from \"./commands/positions.js\";\nimport { registerPrice } from \"./commands/price.js\";\nimport { registerWallet } from \"./commands/wallet.js\";\nimport { registerToken } from \"./commands/token.js\";\nimport { registerWhales } from \"./commands/whales.js\";\nimport { registerCompare } from \"./commands/compare.js\";\nimport { registerSwap } from \"./commands/swap.js\";\nimport { registerBridge } from \"./commands/bridge.js\";\nimport { registerNft } from \"./commands/nft.js\";\nimport { registerFarm } from \"./commands/farm.js\";\nimport { registerFarming } from \"./commands/farming.js\";\nimport { registerSetup } from \"./commands/setup.js\";\nimport { registerLB } from \"./commands/lb.js\";\n\nconst BANNER = `\n ██████╗ ███████╗███████╗██╗ ██████╗██╗ ██╗\n ██╔══██╗██╔════╝██╔════╝██║ ██╔════╝██║ ██║\n ██║ ██║█████╗ █████╗ ██║ ██║ ██║ ██║\n ██║ ██║██╔══╝ ██╔══╝ ██║ ██║ ██║ ██║\n ██████╔╝███████╗██║ ██║ ╚██████╗███████╗██║\n ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝╚══════╝╚═╝\n\n 2 chains · 23 protocols · by HypurrQuant\n\n Scan exploits, swap tokens, bridge assets, track whales,\n compare yields — all from your terminal.\n`;\n\nexport const program = new Command()\n .name(\"defi\")\n .description(\"DeFi CLI — Multi-chain DeFi toolkit\")\n .version(_pkg.version)\n .addHelpText(\"before\", BANNER)\n .option(\"--json\", \"Output as JSON\")\n .option(\"--ndjson\", \"Output as newline-delimited JSON\")\n .option(\"--fields <fields>\", \"Select specific output fields (comma-separated)\")\n .option(\"--chain <chain>\", \"Target chain\", \"hyperevm\")\n .option(\"--dry-run\", \"Dry-run mode (default, no broadcast)\", true)\n .option(\"--broadcast\", \"Actually broadcast the transaction\");\n\n// Helper: read global output mode from the root program options\nfunction getOutputMode(): OutputMode {\n const opts = program.opts<{\n json?: boolean;\n ndjson?: boolean;\n fields?: string;\n }>();\n return parseOutputMode(opts);\n}\n\n// Build executor from global options (lazy — must be called inside action handler, not at registration)\nfunction makeExecutor(): Executor {\n const opts = program.opts<{ broadcast?: boolean; chain?: string }>();\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(opts.chain ?? \"hyperevm\");\n return new Executor(!!opts.broadcast, chain.effectiveRpcUrl(), chain.explorer_url);\n}\n\n// Register all commands\nregisterStatus(program, getOutputMode);\nregisterSchema(program, getOutputMode);\nregisterDex(program, getOutputMode, makeExecutor);\nregisterGauge(program, getOutputMode, makeExecutor);\nregisterLending(program, getOutputMode, makeExecutor);\nregisterCdp(program, getOutputMode, makeExecutor);\nregisterStaking(program, getOutputMode, makeExecutor);\nregisterVault(program, getOutputMode, makeExecutor);\nregisterYield(program, getOutputMode, makeExecutor);\nregisterPortfolio(program, getOutputMode);\nregisterMonitor(program, getOutputMode);\nregisterAlert(program, getOutputMode);\nregisterScan(program, getOutputMode);\nregisterArb(program, getOutputMode, makeExecutor);\nregisterPositions(program, getOutputMode);\nregisterPrice(program, getOutputMode);\nregisterWallet(program, getOutputMode);\nregisterToken(program, getOutputMode, makeExecutor);\nregisterWhales(program, getOutputMode);\nregisterCompare(program, getOutputMode);\nregisterSwap(program, getOutputMode, makeExecutor);\nregisterBridge(program, getOutputMode);\nregisterNft(program, getOutputMode);\nregisterFarm(program, getOutputMode, makeExecutor);\nregisterFarming(program, getOutputMode, makeExecutor);\nregisterLB(program, getOutputMode, makeExecutor);\nregisterSetup(program);\n\n// Agent mode command\nprogram\n .command(\"agent\")\n .description(\"Agent mode: read JSON commands from stdin (for AI agents)\")\n .action(async () => {\n // Registry loading is not yet wired — stub for now\n const executor = makeExecutor();\n process.stderr.write(\"Agent mode: reading JSON commands from stdin...\\n\");\n // TODO: wire registry when registry loading is available in TS\n // await runAgent(registry, executor);\n process.stderr.write(\"Agent mode not yet fully implemented in TS port.\\n\");\n process.exit(1);\n });\n","import { createPublicClient, createWalletClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport { TxStatus } from \"@hypurrquant/defi-core\";\nimport type { ActionResult, DeFiTx } from \"@hypurrquant/defi-core\";\n\nconst ERC20_ABI = parseAbi([\n \"function allowance(address owner, address spender) external view returns (uint256)\",\n \"function approve(address spender, uint256 amount) external returns (bool)\",\n]);\n\n/** Gas buffer multiplier: 120% over estimated gas (20% headroom) */\nconst GAS_BUFFER_BPS = 12000n;\n\n/** Default max priority fee (tip) in wei — 20 gwei (safe for Mantle + EVM chains) */\nconst DEFAULT_PRIORITY_FEE_WEI = 20_000_000_000n;\n\n/** Max gas limit cap — Mantle uses high gas units (up to 5B for complex txs) */\nconst MAX_GAS_LIMIT = 5_000_000_000n; // 5B\n\nexport class Executor {\n readonly dryRun: boolean;\n readonly rpcUrl: string | undefined;\n readonly explorerUrl: string | undefined;\n\n constructor(broadcast: boolean, rpcUrl?: string, explorerUrl?: string) {\n this.dryRun = !broadcast;\n this.rpcUrl = rpcUrl;\n this.explorerUrl = explorerUrl;\n }\n\n /** Apply 20% buffer to a gas estimate */\n private static applyGasBuffer(gas: bigint): bigint {\n return (gas * GAS_BUFFER_BPS) / 10000n;\n }\n\n /**\n * Check allowance for a single token/spender pair and send an approve tx if needed.\n * Only called in broadcast mode (not dry-run).\n */\n private async checkAndApprove(\n token: Address,\n spender: Address,\n amount: bigint,\n owner: Address,\n publicClient: ReturnType<typeof createPublicClient>,\n walletClient: ReturnType<typeof createWalletClient>,\n ): Promise<void> {\n const allowance = await publicClient.readContract({\n address: token,\n abi: ERC20_ABI,\n functionName: \"allowance\",\n args: [owner, spender],\n });\n\n if (allowance >= amount) return;\n\n process.stderr.write(\n ` Approving ${amount} of ${token} for ${spender}...\\n`,\n );\n\n const approveData = encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [spender, amount],\n });\n\n const rpcUrl = this.rpcUrl!;\n const gasLimit = await (async () => {\n try {\n const estimated = await publicClient.estimateGas({\n to: token,\n data: approveData,\n account: owner,\n });\n const buffered = Executor.applyGasBuffer(estimated);\n return buffered > MAX_GAS_LIMIT ? MAX_GAS_LIMIT : buffered;\n } catch {\n return 80_000n;\n }\n })();\n\n const [maxFeePerGas, maxPriorityFeePerGas] = await this.fetchEip1559Fees(rpcUrl);\n\n const approveTxHash = await walletClient.sendTransaction({\n chain: null,\n account: walletClient.account!,\n to: token,\n data: approveData,\n gas: gasLimit > 0n ? gasLimit : undefined,\n maxFeePerGas: maxFeePerGas > 0n ? maxFeePerGas : undefined,\n maxPriorityFeePerGas: maxPriorityFeePerGas > 0n ? maxPriorityFeePerGas : undefined,\n });\n\n const approveTxUrl = this.explorerUrl\n ? `${this.explorerUrl}/tx/${approveTxHash}`\n : undefined;\n process.stderr.write(` Approve tx: ${approveTxHash}\\n`);\n if (approveTxUrl) process.stderr.write(` Explorer: ${approveTxUrl}\\n`);\n\n await publicClient.waitForTransactionReceipt({ hash: approveTxHash });\n process.stderr.write(\n ` Approved ${amount} of ${token} for ${spender}\\n`,\n );\n }\n\n /** Fetch EIP-1559 fee params from the network. Returns [maxFeePerGas, maxPriorityFeePerGas]. */\n private async fetchEip1559Fees(rpcUrl: string): Promise<[bigint, bigint]> {\n try {\n const client = createPublicClient({ transport: http(rpcUrl) });\n const gasPrice = await client.getGasPrice();\n let priorityFee = DEFAULT_PRIORITY_FEE_WEI;\n try {\n priorityFee = await client.estimateMaxPriorityFeePerGas();\n } catch {\n // fallback to default\n }\n const maxFee = gasPrice * 2n + priorityFee;\n return [maxFee, priorityFee];\n } catch {\n return [0n, 0n];\n }\n }\n\n /** Estimate gas dynamically with buffer, falling back to a hardcoded estimate */\n private async estimateGasWithBuffer(\n rpcUrl: string,\n tx: DeFiTx,\n from: `0x${string}`,\n ): Promise<bigint> {\n try {\n const client = createPublicClient({ transport: http(rpcUrl) });\n const estimated = await client.estimateGas({\n to: tx.to,\n data: tx.data,\n value: tx.value,\n account: from,\n });\n if (estimated > 0n) {\n const buffered = Executor.applyGasBuffer(estimated);\n return buffered > MAX_GAS_LIMIT ? MAX_GAS_LIMIT : buffered;\n }\n } catch {\n // fallback: apply buffer to the hint too\n if (tx.gas_estimate) {\n return Executor.applyGasBuffer(BigInt(tx.gas_estimate));\n }\n }\n return 0n;\n }\n\n /** Simulate a transaction via eth_call + eth_estimateGas */\n private async simulate(tx: DeFiTx): Promise<ActionResult> {\n const rpcUrl = this.rpcUrl;\n if (!rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL — cannot simulate. Set HYPEREVM_RPC_URL.\");\n }\n\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n const from: `0x${string}` = privateKey\n ? privateKeyToAccount(privateKey as `0x${string}`).address\n : \"0x0000000000000000000000000000000000000001\";\n\n // Check approvals before simulation\n if (tx.approvals && tx.approvals.length > 0) {\n const pendingApprovals: Array<{ token: string; spender: string; needed: string; current: string }> = [];\n for (const approval of tx.approvals) {\n try {\n const allowance = await client.readContract({\n address: approval.token,\n abi: ERC20_ABI,\n functionName: \"allowance\",\n args: [from as `0x${string}`, approval.spender],\n });\n if (allowance < approval.amount) {\n pendingApprovals.push({\n token: approval.token,\n spender: approval.spender,\n needed: approval.amount.toString(),\n current: allowance.toString(),\n });\n }\n } catch { /* skip check on error */ }\n }\n if (pendingApprovals.length > 0) {\n return {\n tx_hash: undefined,\n status: TxStatus.NeedsApproval,\n gas_used: tx.gas_estimate,\n description: tx.description,\n details: {\n to: tx.to,\n from,\n data: tx.data,\n value: tx.value.toString(),\n mode: \"simulated\",\n result: \"needs_approval\",\n pending_approvals: pendingApprovals,\n hint: \"Use --broadcast to auto-approve and execute\",\n },\n };\n }\n }\n\n try {\n await client.call({ to: tx.to, data: tx.data, value: tx.value, account: from });\n\n const gasEstimate = await this.estimateGasWithBuffer(rpcUrl, tx, from);\n const [maxFee, priorityFee] = await this.fetchEip1559Fees(rpcUrl);\n\n return {\n tx_hash: undefined,\n status: \"simulated\" as TxStatus,\n gas_used: gasEstimate > 0n ? Number(gasEstimate) : undefined,\n description: tx.description,\n details: {\n to: tx.to,\n from,\n data: tx.data,\n value: tx.value.toString(),\n gas_estimate: gasEstimate.toString(),\n max_fee_per_gas_gwei: (Number(maxFee) / 1e9).toFixed(4),\n max_priority_fee_gwei: (Number(priorityFee) / 1e9).toFixed(4),\n mode: \"simulated\",\n result: \"success\",\n },\n };\n } catch (e: unknown) {\n const errMsg = String(e);\n const revertReason = extractRevertReason(errMsg);\n\n return {\n tx_hash: undefined,\n status: \"simulation_failed\" as TxStatus,\n gas_used: tx.gas_estimate,\n description: tx.description,\n details: {\n to: tx.to,\n from,\n data: tx.data,\n value: tx.value.toString(),\n mode: \"simulated\",\n result: \"revert\",\n revert_reason: revertReason,\n },\n };\n }\n }\n\n async execute(tx: DeFiTx): Promise<ActionResult> {\n if (this.dryRun) {\n if (this.rpcUrl) {\n return this.simulate(tx);\n }\n\n return {\n tx_hash: undefined,\n status: \"dry_run\" as TxStatus,\n gas_used: tx.gas_estimate,\n description: tx.description,\n details: {\n to: tx.to,\n data: tx.data,\n value: tx.value.toString(),\n mode: \"dry_run\",\n },\n };\n }\n\n // === Broadcast mode ===\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n if (!privateKey) {\n throw DefiError.invalidParam(\n \"DEFI_PRIVATE_KEY environment variable not set. Required for --broadcast.\",\n );\n }\n\n const account = privateKeyToAccount(privateKey as `0x${string}`);\n\n const rpcUrl = this.rpcUrl;\n if (!rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured for broadcasting\");\n }\n\n const publicClient = createPublicClient({ transport: http(rpcUrl) });\n const walletClient = createWalletClient({ account, transport: http(rpcUrl) });\n\n // Execute pre-transactions (e.g. farming approval)\n if (tx.pre_txs && tx.pre_txs.length > 0) {\n for (const preTx of tx.pre_txs) {\n process.stderr.write(` Pre-tx: ${preTx.description}...\\n`);\n const preGas = await this.estimateGasWithBuffer(rpcUrl, preTx, account.address);\n const preTxHash = await walletClient.sendTransaction({\n chain: null,\n to: preTx.to,\n data: preTx.data,\n value: preTx.value,\n gas: preGas > 0n ? preGas : undefined,\n });\n const preTxUrl = this.explorerUrl ? `${this.explorerUrl}/tx/${preTxHash}` : undefined;\n process.stderr.write(` Pre-tx sent: ${preTxHash}\\n`);\n if (preTxUrl) process.stderr.write(` Explorer: ${preTxUrl}\\n`);\n const preReceipt = await publicClient.waitForTransactionReceipt({ hash: preTxHash });\n if (preReceipt.status !== \"success\") {\n throw new DefiError(\"TX_FAILED\", `Pre-transaction failed: ${preTx.description}`);\n }\n process.stderr.write(` Pre-tx confirmed\\n`);\n }\n }\n\n // Auto-approve ERC20 tokens if needed\n if (tx.approvals && tx.approvals.length > 0) {\n for (const approval of tx.approvals) {\n await this.checkAndApprove(\n approval.token,\n approval.spender,\n approval.amount,\n account.address,\n publicClient,\n walletClient,\n );\n }\n }\n\n // Dynamic gas estimation with buffer\n const gasLimit = await this.estimateGasWithBuffer(rpcUrl, tx, account.address);\n\n // EIP-1559 gas pricing\n const [maxFeePerGas, maxPriorityFeePerGas] = await this.fetchEip1559Fees(rpcUrl);\n\n process.stderr.write(`Broadcasting transaction to ${rpcUrl}...\\n`);\n if (gasLimit > 0n) {\n process.stderr.write(` Gas limit: ${gasLimit} (with 20% buffer)\\n`);\n }\n\n const txHash = await walletClient.sendTransaction({\n chain: null,\n to: tx.to,\n data: tx.data,\n value: tx.value,\n gas: gasLimit > 0n ? gasLimit : undefined,\n maxFeePerGas: maxFeePerGas > 0n ? maxFeePerGas : undefined,\n maxPriorityFeePerGas: maxPriorityFeePerGas > 0n ? maxPriorityFeePerGas : undefined,\n });\n\n const txUrl = this.explorerUrl ? `${this.explorerUrl}/tx/${txHash}` : undefined;\n process.stderr.write(`Transaction sent: ${txHash}\\n`);\n if (txUrl) process.stderr.write(`Explorer: ${txUrl}\\n`);\n process.stderr.write(\"Waiting for confirmation...\\n\");\n\n const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });\n\n const status = receipt.status === \"success\" ? \"confirmed\" : \"failed\";\n\n // Extract minted NFT tokenId from Transfer(from=0x0) events\n let mintedTokenId: string | undefined;\n if (receipt.status === \"success\" && receipt.logs) {\n const TRANSFER_TOPIC = \"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\";\n const ZERO_TOPIC = \"0x0000000000000000000000000000000000000000000000000000000000000000\";\n for (const log of receipt.logs) {\n if (\n log.topics.length >= 4 &&\n log.topics[0] === TRANSFER_TOPIC &&\n log.topics[1] === ZERO_TOPIC // from = address(0) → mint\n ) {\n mintedTokenId = BigInt(log.topics[3]!).toString();\n break;\n }\n }\n }\n\n const details: Record<string, string | undefined> = {\n to: tx.to,\n from: account.address,\n block_number: receipt.blockNumber?.toString(),\n gas_limit: gasLimit.toString(),\n gas_used: receipt.gasUsed?.toString(),\n explorer_url: txUrl,\n mode: \"broadcast\",\n };\n if (mintedTokenId) {\n details.minted_token_id = mintedTokenId;\n process.stderr.write(` Minted NFT tokenId: ${mintedTokenId}\\n`);\n }\n\n return {\n tx_hash: txHash,\n status: status as TxStatus,\n gas_used: receipt.gasUsed ? Number(receipt.gasUsed) : undefined,\n description: tx.description,\n details,\n };\n }\n}\n\n/** Extract a human-readable revert reason from an RPC error message */\nfunction extractRevertReason(err: string): string {\n for (const marker of [\"execution reverted:\", \"revert:\", \"Error(\"]) {\n const pos = err.indexOf(marker);\n if (pos !== -1) return err.slice(pos);\n }\n return err.length > 200 ? err.slice(0, 200) + \"...\" : err;\n}\n","import type { Address, Hex } from \"viem\";\n\n// === Transaction Types ===\n\n/** A built DeFi transaction ready for simulation or broadcast */\nexport interface DeFiTx {\n description: string;\n to: Address;\n data: Hex;\n value: bigint;\n gas_estimate?: number;\n /** ERC20 approvals to check and send before broadcasting this tx */\n approvals?: Array<{\n token: Address;\n spender: Address;\n amount: bigint;\n }>;\n /** Pre-transactions to execute before the main tx (e.g. farming approval) */\n pre_txs?: DeFiTx[];\n}\n\n/** Result of executing or simulating a transaction */\nexport interface ActionResult {\n tx_hash?: string;\n status: TxStatus;\n gas_used?: number;\n description: string;\n details: Record<string, unknown>;\n}\n\n/** Transaction status (serde: snake_case) */\nexport enum TxStatus {\n DryRun = \"dry_run\",\n Simulated = \"simulated\",\n SimulationFailed = \"simulation_failed\",\n NeedsApproval = \"needs_approval\",\n Pending = \"pending\",\n Confirmed = \"confirmed\",\n Failed = \"failed\",\n}\n\n// === Token Types ===\n\n/** Token amount with decimals-aware formatting */\nexport interface TokenAmount {\n token: Address;\n symbol: string;\n amount: bigint;\n decimals: number;\n}\n\nexport function formatHuman(t: TokenAmount): string {\n const divisor = 10n ** BigInt(t.decimals);\n const whole = t.amount / divisor;\n const frac = t.amount % divisor;\n return `${whole}.${frac.toString().padStart(t.decimals, \"0\")} ${t.symbol}`;\n}\n\n/** Slippage tolerance in basis points */\nexport interface Slippage {\n bps: number;\n}\n\nexport function newSlippage(bps: number): Slippage {\n return { bps };\n}\n\nexport function defaultSwapSlippage(): Slippage {\n return { bps: 50 };\n}\n\nexport function applyMinSlippage(slippage: Slippage, amount: bigint): bigint {\n return (amount * BigInt(10000 - slippage.bps)) / 10000n;\n}\n\n// === Oracle / Price Types ===\n\nexport interface PriceData {\n source: string;\n source_type: string;\n asset: Address;\n price_usd: bigint;\n price_f64: number;\n block_number?: number;\n timestamp?: number;\n}\n\n// === DEX Types ===\n\nexport interface SwapParams {\n protocol: string;\n token_in: Address;\n token_out: Address;\n amount_in: bigint;\n slippage: Slippage;\n recipient: Address;\n deadline?: number;\n}\n\nexport interface QuoteParams {\n protocol: string;\n token_in: Address;\n token_out: Address;\n amount_in: bigint;\n}\n\nexport interface QuoteResult {\n protocol: string;\n amount_out: bigint;\n price_impact_bps?: number;\n fee_bps?: number;\n route: string[];\n}\n\nexport interface AddLiquidityParams {\n protocol: string;\n token_a: Address;\n token_b: Address;\n amount_a: bigint;\n amount_b: bigint;\n recipient: Address;\n /** Optional lower tick for concentrated LP (defaults to full range) */\n tick_lower?: number;\n /** Optional upper tick for concentrated LP (defaults to full range) */\n tick_upper?: number;\n /** ±N% concentrated range around current price (e.g. 2 for ±2%) */\n range_pct?: number;\n /** Optional pool address for tick detection / single-side LP */\n pool?: Address;\n}\n\nexport interface RemoveLiquidityParams {\n protocol: string;\n token_a: Address;\n token_b: Address;\n liquidity: bigint;\n recipient: Address;\n}\n\n// === Lending Types ===\n\nexport interface SupplyParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n on_behalf_of: Address;\n}\n\nexport interface BorrowParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n interest_rate_mode: InterestRateMode;\n on_behalf_of: Address;\n}\n\n/** Interest rate mode (serde: snake_case) */\nexport enum InterestRateMode {\n Variable = \"variable\",\n Stable = \"stable\",\n}\n\nexport interface RepayParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n interest_rate_mode: InterestRateMode;\n on_behalf_of: Address;\n}\n\nexport interface WithdrawParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n to: Address;\n}\n\nexport interface LendingRates {\n protocol: string;\n asset: Address;\n supply_apy: number;\n borrow_variable_apy: number;\n borrow_stable_apy?: number;\n utilization: number;\n total_supply: bigint;\n total_borrow: bigint;\n /** Reward token addresses for supply-side incentives */\n supply_reward_tokens?: string[];\n /** Reward token addresses for borrow-side incentives */\n borrow_reward_tokens?: string[];\n /** Emissions per second per supply reward token (raw uint256 as string) */\n supply_emissions_per_second?: string[];\n /** Emissions per second per borrow reward token (raw uint256 as string) */\n borrow_emissions_per_second?: string[];\n /** Supply-side incentive APY (%) from reward token emissions */\n supply_incentive_apy?: number;\n /** Borrow-side incentive APY (%) from reward token emissions (negative = subsidized) */\n borrow_incentive_apy?: number;\n}\n\nexport interface UserPosition {\n protocol: string;\n user: Address;\n supplies: PositionAsset[];\n borrows: PositionAsset[];\n health_factor?: number;\n net_apy?: number;\n}\n\nexport interface PositionAsset {\n asset: Address;\n symbol: string;\n amount: bigint;\n value_usd?: number;\n}\n\n// === CDP Types ===\n\nexport interface OpenCdpParams {\n protocol: string;\n collateral: Address;\n collateral_amount: bigint;\n debt_amount: bigint;\n recipient: Address;\n}\n\nexport interface AdjustCdpParams {\n protocol: string;\n cdp_id: bigint;\n collateral_delta?: bigint;\n debt_delta?: bigint;\n add_collateral: boolean;\n add_debt: boolean;\n}\n\nexport interface CloseCdpParams {\n protocol: string;\n cdp_id: bigint;\n}\n\nexport interface CdpInfo {\n protocol: string;\n cdp_id: bigint;\n collateral: TokenAmount;\n debt: TokenAmount;\n collateral_ratio: number;\n liquidation_price?: number;\n}\n\n// === Liquid Staking Types ===\n\nexport interface StakeParams {\n protocol: string;\n amount: bigint;\n recipient: Address;\n}\n\nexport interface UnstakeParams {\n protocol: string;\n amount: bigint;\n recipient: Address;\n}\n\nexport interface StakingInfo {\n protocol: string;\n staked_token: Address;\n liquid_token: Address;\n exchange_rate: number;\n apy?: number;\n total_staked: bigint;\n}\n\n// === Vault Types (ERC-4626) ===\n\nexport interface VaultInfo {\n protocol: string;\n vault_address: Address;\n asset: Address;\n total_assets: bigint;\n total_supply: bigint;\n apy?: number;\n}\n\n// === Derivatives Types ===\n\nexport interface DerivativesPositionParams {\n protocol: string;\n market: string;\n size: bigint;\n collateral: bigint;\n is_long: boolean;\n}\n\n// === Options Types ===\n\nexport interface OptionParams {\n protocol: string;\n underlying: Address;\n strike_price: bigint;\n expiry: number;\n is_call: boolean;\n amount: bigint;\n}\n\n// === ve(3,3) Types ===\n\n/** A pool that has an active emission gauge */\nexport interface GaugedPool {\n pool: Address;\n gauge: Address;\n token0: string; // symbol\n token1: string; // symbol\n type: \"V2\" | \"CL\";\n tickSpacing?: number; // for CL pools\n stable?: boolean; // for V2 pools\n}\n\nexport interface RewardInfo {\n token: Address;\n symbol: string;\n amount: bigint;\n value_usd?: number;\n}\n\nexport interface GaugeInfo {\n gauge: Address;\n pool: Address;\n total_staked: bigint;\n reward_rate: bigint;\n rewards: RewardInfo[];\n}\n\nexport interface VeNftInfo {\n token_id: bigint;\n amount: bigint;\n unlock_time: number;\n voting_power: bigint;\n}\n\n// === Yield Types ===\n\nexport interface YieldInfo {\n protocol: string;\n pool: string;\n apy: number;\n tvl: bigint;\n tokens: Address[];\n}\n\n// === Portfolio Tracker Types ===\nexport interface PortfolioSnapshot {\n timestamp: number;\n chain: string;\n wallet: string;\n tokens: TokenBalance[];\n defi_positions: DefiPosition[];\n total_value_usd: number;\n}\n\nexport interface TokenBalance {\n token: string;\n symbol: string;\n balance: bigint;\n value_usd: number;\n price_usd: number;\n}\n\nexport interface DefiPosition {\n protocol: string;\n type: \"lending_supply\" | \"lending_borrow\" | \"lp\" | \"staking\" | \"vault\";\n asset: string;\n amount: bigint;\n value_usd: number;\n}\n\nexport interface PortfolioPnL {\n period: string;\n start_value_usd: number;\n end_value_usd: number;\n pnl_usd: number;\n pnl_pct: number;\n token_changes: TokenChange[];\n}\n\nexport interface TokenChange {\n symbol: string;\n balance_change: bigint;\n value_change_usd: number;\n}\n","import type { Address } from \"viem\";\n\nexport type DefiErrorCode =\n | \"PROTOCOL_NOT_FOUND\"\n | \"TOKEN_NOT_FOUND\"\n | \"CHAIN_NOT_FOUND\"\n | \"INSUFFICIENT_BALANCE\"\n | \"INSUFFICIENT_ALLOWANCE\"\n | \"SLIPPAGE_EXCEEDED\"\n | \"SIMULATION_FAILED\"\n | \"ABI_ERROR\"\n | \"REGISTRY_ERROR\"\n | \"RPC_ERROR\"\n | \"PROVIDER_ERROR\"\n | \"CONTRACT_ERROR\"\n | \"INVALID_PARAM\"\n | \"UNSUPPORTED\"\n | \"TX_FAILED\"\n | \"INTERNAL\";\n\nexport class DefiError extends Error {\n readonly code: DefiErrorCode;\n\n constructor(code: DefiErrorCode, message: string) {\n super(message);\n this.name = \"DefiError\";\n this.code = code;\n }\n\n static protocolNotFound(name: string): DefiError {\n return new DefiError(\"PROTOCOL_NOT_FOUND\", `Protocol not found: ${name}`);\n }\n\n static tokenNotFound(name: string): DefiError {\n return new DefiError(\"TOKEN_NOT_FOUND\", `Token not found: ${name}`);\n }\n\n static chainNotFound(name: string): DefiError {\n return new DefiError(\"CHAIN_NOT_FOUND\", `Chain not found: ${name}`);\n }\n\n static insufficientBalance(needed: string, available: string): DefiError {\n return new DefiError(\n \"INSUFFICIENT_BALANCE\",\n `Insufficient balance: need ${needed}, have ${available}`,\n );\n }\n\n static insufficientAllowance(spender: Address): DefiError {\n return new DefiError(\n \"INSUFFICIENT_ALLOWANCE\",\n `Insufficient allowance for spender ${spender}`,\n );\n }\n\n static slippageExceeded(expected: string, actual: string): DefiError {\n return new DefiError(\n \"SLIPPAGE_EXCEEDED\",\n `Slippage exceeded: expected ${expected}, got ${actual}`,\n );\n }\n\n static simulationFailed(reason: string): DefiError {\n return new DefiError(\n \"SIMULATION_FAILED\",\n `Transaction simulation failed: ${reason}`,\n );\n }\n\n static abiError(reason: string): DefiError {\n return new DefiError(\"ABI_ERROR\", `ABI encoding error: ${reason}`);\n }\n\n static registryError(reason: string): DefiError {\n return new DefiError(\"REGISTRY_ERROR\", `Registry error: ${reason}`);\n }\n\n static rpcError(reason: string): DefiError {\n return new DefiError(\"RPC_ERROR\", `RPC error: ${reason}`);\n }\n\n static providerError(reason: string): DefiError {\n return new DefiError(\"PROVIDER_ERROR\", `Provider error: ${reason}`);\n }\n\n static contractError(reason: string): DefiError {\n return new DefiError(\"CONTRACT_ERROR\", `Contract error: ${reason}`);\n }\n\n static invalidParam(reason: string): DefiError {\n return new DefiError(\"INVALID_PARAM\", `Invalid parameter: ${reason}`);\n }\n\n static unsupported(operation: string): DefiError {\n return new DefiError(\n \"UNSUPPORTED\",\n `Unsupported operation: ${operation}`,\n );\n }\n\n static internal(reason: string): DefiError {\n return new DefiError(\"INTERNAL\", `Internal error: ${reason}`);\n }\n\n toJSON() {\n return { error: this.message };\n }\n}\n\nexport type Result<T> = T;\n","/**\n * BigInt JSON serialization utilities.\n *\n * Rust's alloy U256 (backed by ruint) serializes to JSON as 0x-prefixed\n * lowercase hex strings (e.g., \"0x75bcd15\"). We must match this exactly\n * for behavioral parity.\n */\n\n/** JSON replacer for Rust parity — bigint becomes 0x-hex string */\nexport function jsonReplacer(_key: string, value: unknown): unknown {\n if (typeof value === \"bigint\") {\n return \"0x\" + value.toString(16);\n }\n return value;\n}\n\n/** JSON replacer for SDK consumers — bigint becomes decimal string */\nexport function jsonReplacerDecimal(_key: string, value: unknown): unknown {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n}\n\n/** Stringify with decimal bigint handling */\nexport function jsonStringify(data: unknown, pretty = true): string {\n return pretty\n ? JSON.stringify(data, jsonReplacerDecimal, 2)\n : JSON.stringify(data, jsonReplacerDecimal);\n}\n\n/** Parse a 0x-hex or decimal string to bigint */\nexport function parseBigInt(value: string): bigint {\n if (value.startsWith(\"0x\") || value.startsWith(\"0X\")) {\n return BigInt(value);\n }\n return BigInt(value);\n}\n","import type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport type { DeFiTx } from \"./types.js\";\n\nconst erc20Abi = parseAbi([\n \"function name() view returns (string)\",\n \"function symbol() view returns (string)\",\n \"function decimals() view returns (uint8)\",\n \"function totalSupply() view returns (uint256)\",\n \"function balanceOf(address account) view returns (uint256)\",\n \"function transfer(address to, uint256 amount) returns (bool)\",\n \"function allowance(address owner, address spender) view returns (uint256)\",\n \"function approve(address spender, uint256 amount) returns (bool)\",\n \"function transferFrom(address from, address to, uint256 amount) returns (bool)\",\n]);\n\nexport { erc20Abi };\n\nexport function buildApprove(\n token: Address,\n spender: Address,\n amount: bigint,\n): DeFiTx {\n const data = encodeFunctionData({\n abi: erc20Abi,\n functionName: \"approve\",\n args: [spender, amount],\n });\n return {\n description: `Approve ${spender} to spend ${amount} of token ${token}`,\n to: token,\n data,\n value: 0n,\n gas_estimate: 60_000,\n };\n}\n\nexport function buildTransfer(\n token: Address,\n to: Address,\n amount: bigint,\n): DeFiTx {\n const data = encodeFunctionData({\n abi: erc20Abi,\n functionName: \"transfer\",\n args: [to, amount],\n });\n return {\n description: `Transfer ${amount} of token ${token} to ${to}`,\n to: token,\n data,\n value: 0n,\n gas_estimate: 65_000,\n };\n}\n","import { createPublicClient, http, type PublicClient } from \"viem\";\n\nconst providerCache = new Map<string, PublicClient>();\n\nexport function getProvider(rpcUrl: string): PublicClient {\n const cached = providerCache.get(rpcUrl);\n if (cached) return cached;\n\n const client = createPublicClient({ transport: http(rpcUrl) });\n providerCache.set(rpcUrl, client);\n return client;\n}\n\nexport function clearProviderCache(): void {\n providerCache.clear();\n}\n","import type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, decodeFunctionResult, parseAbi } from \"viem\";\nimport type { DeFiTx } from \"./types.js\";\nimport { getProvider } from \"./provider.js\";\n\nexport const MULTICALL3_ADDRESS: Address =\n \"0xcA11bde05977b3631167028862bE2a173976CA11\";\n\nconst multicall3Abi = parseAbi([\n \"struct Call3 { address target; bool allowFailure; bytes callData; }\",\n \"struct Result { bool success; bytes returnData; }\",\n \"function aggregate3(Call3[] calls) returns (Result[] returnData)\",\n]);\n\nexport function buildMulticall(calls: Array<[Address, Hex]>): DeFiTx {\n const mcCalls = calls.map(([target, callData]) => ({\n target,\n allowFailure: true,\n callData,\n }));\n\n const data = encodeFunctionData({\n abi: multicall3Abi,\n functionName: \"aggregate3\",\n args: [mcCalls],\n });\n\n return {\n description: `Multicall3 batch (${calls.length} calls)`,\n to: MULTICALL3_ADDRESS,\n data,\n value: 0n,\n };\n}\n\nexport async function multicallRead(\n rpcUrl: string,\n calls: Array<[Address, Hex]>,\n): Promise<(Hex | null)[]> {\n const client = getProvider(rpcUrl);\n\n const mcCalls = calls.map(([target, callData]) => ({\n target,\n allowFailure: true,\n callData,\n }));\n\n const result = await client.call({\n to: MULTICALL3_ADDRESS,\n data: encodeFunctionData({\n abi: multicall3Abi,\n functionName: \"aggregate3\",\n args: [mcCalls],\n }),\n });\n\n if (!result.data) return calls.map(() => null);\n\n const decoded = decodeFunctionResult({\n abi: multicall3Abi,\n functionName: \"aggregate3\",\n data: result.data,\n }) as Array<{ success: boolean; returnData: Hex }>;\n\n return decoded.map((r) => (r.success ? r.returnData : null));\n}\n\nexport function decodeU256(data: Hex | null): bigint {\n if (!data || data.length < 66) return 0n;\n return BigInt(data.slice(0, 66));\n}\n\nexport function decodeU128(data: Hex | null): bigint {\n if (!data || data.length < 66) return 0n;\n const val = BigInt(data.slice(0, 66));\n return val & ((1n << 128n) - 1n);\n}\n","export class ChainConfig {\n name!: string;\n chain_id!: number;\n rpc_url!: string;\n explorer_url?: string;\n native_token!: string;\n wrapped_native?: string;\n multicall3?: string;\n\n effectiveRpcUrl(): string {\n const chainEnv = this.name.toUpperCase().replace(/ /g, \"_\") + \"_RPC_URL\";\n return (\n process.env[chainEnv] ??\n process.env[\"HYPEREVM_RPC_URL\"] ??\n this.rpc_url\n );\n }\n}\n","import type { Address } from \"viem\";\n\nexport enum ProtocolCategory {\n Dex = \"dex\",\n Lending = \"lending\",\n Cdp = \"cdp\",\n Bridge = \"bridge\",\n LiquidStaking = \"liquid_staking\",\n YieldSource = \"yield_source\",\n YieldAggregator = \"yield_aggregator\",\n Vault = \"vault\",\n Derivatives = \"derivatives\",\n Options = \"options\",\n LiquidityManager = \"liquidity_manager\",\n Nft = \"nft\",\n Other = \"other\",\n}\n\nexport function protocolCategoryLabel(category: ProtocolCategory): string {\n switch (category) {\n case ProtocolCategory.Dex:\n return \"DEX\";\n case ProtocolCategory.Lending:\n return \"Lending\";\n case ProtocolCategory.Cdp:\n return \"CDP\";\n case ProtocolCategory.Bridge:\n return \"Bridge\";\n case ProtocolCategory.LiquidStaking:\n return \"Liquid Staking\";\n case ProtocolCategory.YieldSource:\n return \"Yield Source\";\n case ProtocolCategory.YieldAggregator:\n return \"Yield Aggregator\";\n case ProtocolCategory.Vault:\n return \"Vault\";\n case ProtocolCategory.Derivatives:\n return \"Derivatives\";\n case ProtocolCategory.Options:\n return \"Options\";\n case ProtocolCategory.LiquidityManager:\n return \"Liquidity Manager\";\n case ProtocolCategory.Nft:\n return \"NFT\";\n case ProtocolCategory.Other:\n return \"Other\";\n }\n}\n\nexport interface PoolInfo {\n name: string;\n address: Address;\n token0: string;\n token1: string;\n tick_spacing?: number;\n gauge?: Address;\n stable?: boolean;\n}\n\nexport interface ProtocolEntry {\n name: string;\n slug: string;\n category: ProtocolCategory;\n interface: string;\n chain: string;\n native?: boolean;\n contracts?: Record<string, Address>;\n pools?: PoolInfo[];\n description?: string;\n}\n","import { readFileSync, readdirSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { parse } from \"smol-toml\";\nimport { ChainConfig } from \"./chain.js\";\nimport type { TokenEntry } from \"./token.js\";\nimport { type ProtocolEntry, type PoolInfo, ProtocolCategory } from \"./protocol.js\";\n\nimport { existsSync } from \"fs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\n\n// Resolve config dir: works from src/ (vitest), dist/ (built), and npm bundle (npx)\nfunction findConfigDir(): string {\n const candidates = [\n resolve(__dirname, \"../../../config\"), // from dist/registry/ (monorepo build)\n resolve(__dirname, \"../../../../config\"), // from src/registry/ (vitest)\n resolve(__dirname, \"../config\"), // from dist/ (npm bundle — config at package root)\n resolve(__dirname, \"../../config\"), // from dist/subdir (npm bundle variant)\n ];\n for (const dir of candidates) {\n if (existsSync(resolve(dir, \"chains.toml\"))) return dir;\n }\n throw new Error(`Config directory not found. Searched: ${candidates.join(\", \")}`);\n}\n\nconst CONFIG_DIR = findConfigDir();\n\nfunction readToml(relPath: string): string {\n return readFileSync(resolve(CONFIG_DIR, relPath), \"utf-8\");\n}\n\ninterface ChainConfigWrapper {\n chain: Record<string, ChainConfig>;\n}\n\ninterface TokensWrapper {\n token: TokenEntry[];\n}\n\ninterface ProtocolWrapper {\n protocol: ProtocolEntry;\n}\n\nexport class Registry {\n chains: Map<string, ChainConfig>;\n tokens: Map<string, TokenEntry[]>;\n protocols: ProtocolEntry[];\n\n private constructor(\n chains: Map<string, ChainConfig>,\n tokens: Map<string, TokenEntry[]>,\n protocols: ProtocolEntry[],\n ) {\n this.chains = chains;\n this.tokens = tokens;\n this.protocols = protocols;\n }\n\n static loadEmbedded(): Registry {\n const chains = Registry.loadChains();\n const tokens = Registry.loadTokens();\n const protocols = Registry.loadProtocols();\n return new Registry(chains, tokens, protocols);\n }\n\n private static loadChains(): Map<string, ChainConfig> {\n const raw = parse(readToml(\"chains.toml\")) as unknown as ChainConfigWrapper;\n const map = new Map<string, ChainConfig>();\n for (const [key, data] of Object.entries(raw.chain)) {\n const cfg = Object.assign(new ChainConfig(), data);\n map.set(key, cfg);\n }\n return map;\n }\n\n private static loadTokens(): Map<string, TokenEntry[]> {\n // Dynamically discover all token files in config/tokens/\n const map = new Map<string, TokenEntry[]>();\n const tokensDir = resolve(CONFIG_DIR, \"tokens\");\n try {\n const files = readdirSync(tokensDir).filter(f => f.endsWith(\".toml\"));\n for (const file of files) {\n const chain = file.replace(\".toml\", \"\");\n try {\n const raw = parse(readToml(`tokens/${file}`)) as unknown as TokensWrapper;\n map.set(chain, raw.token);\n } catch { /* skip invalid token files */ }\n }\n } catch { /* tokens dir may not exist */ }\n return map;\n }\n\n private static loadProtocols(): ProtocolEntry[] {\n // Dynamically discover all protocol TOML files across all categories\n const protocols: ProtocolEntry[] = [];\n const protocolsDir = resolve(CONFIG_DIR, \"protocols\");\n const categories = [\"dex\", \"lending\", \"cdp\", \"vault\", \"liquid_staking\", \"yield_aggregator\", \"yield_source\", \"derivatives\", \"options\", \"nft\", \"bridge\"];\n\n for (const category of categories) {\n const catDir = resolve(protocolsDir, category);\n try {\n if (!existsSync(catDir)) continue;\n const files = readdirSync(catDir).filter(f => f.endsWith(\".toml\"));\n for (const file of files) {\n try {\n const raw = parse(readToml(`protocols/${category}/${file}`)) as unknown as ProtocolWrapper;\n protocols.push(raw.protocol);\n } catch { /* skip invalid protocol files */ }\n }\n } catch { /* category dir may not exist */ }\n }\n return protocols;\n }\n\n getChain(name: string): ChainConfig {\n const chain = this.chains.get(name);\n if (!chain) throw new Error(`Chain not found: ${name}`);\n return chain;\n }\n\n getProtocol(name: string): ProtocolEntry {\n const protocol = this.protocols.find(\n (p) =>\n p.name.toLowerCase() === name.toLowerCase() ||\n p.slug.toLowerCase() === name.toLowerCase(),\n );\n if (!protocol) throw new Error(`Protocol not found: ${name}`);\n return protocol;\n }\n\n getProtocolsByCategory(category: ProtocolCategory): ProtocolEntry[] {\n return this.protocols.filter((p) => p.category === category);\n }\n\n getProtocolsForChain(chain: string): ProtocolEntry[] {\n return this.protocols.filter(\n (p) => p.chain.toLowerCase() === chain.toLowerCase(),\n );\n }\n\n resolveToken(chain: string, symbol: string): TokenEntry {\n const tokens = this.tokens.get(chain);\n if (!tokens) throw new Error(`Chain not found: ${chain}`);\n const token = tokens.find(\n (t) => t.symbol.toLowerCase() === symbol.toLowerCase(),\n );\n if (!token) throw new Error(`Token not found: ${symbol}`);\n return token;\n }\n\n /**\n * Resolve a pool by name (e.g. \"WHYPE/USDC\") from a protocol's pool list.\n * Returns the pool info or throws if not found.\n */\n resolvePool(protocolSlug: string, poolName: string): PoolInfo {\n const protocol = this.getProtocol(protocolSlug);\n if (!protocol.pools || protocol.pools.length === 0) {\n throw new Error(`Protocol ${protocol.name} has no pools configured`);\n }\n const pool = protocol.pools.find(\n (p) => p.name.toLowerCase() === poolName.toLowerCase(),\n );\n if (!pool) {\n const available = protocol.pools.map(p => p.name).join(\", \");\n throw new Error(`Pool '${poolName}' not found in ${protocol.name}. Available: ${available}`);\n }\n return pool;\n }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nfunction getLineColFromPtr(string, ptr) {\n let lines = string.slice(0, ptr).split(/\\r\\n|\\n|\\r/g);\n return [lines.length, lines.pop().length + 1];\n}\nfunction makeCodeBlock(string, line, column) {\n let lines = string.split(/\\r\\n|\\n|\\r/g);\n let codeblock = '';\n let numberLen = (Math.log10(line + 1) | 0) + 1;\n for (let i = line - 1; i <= line + 1; i++) {\n let l = lines[i - 1];\n if (!l)\n continue;\n codeblock += i.toString().padEnd(numberLen, ' ');\n codeblock += ': ';\n codeblock += l;\n codeblock += '\\n';\n if (i === line) {\n codeblock += ' '.repeat(numberLen + column + 2);\n codeblock += '^\\n';\n }\n }\n return codeblock;\n}\nexport class TomlError extends Error {\n line;\n column;\n codeblock;\n constructor(message, options) {\n const [line, column] = getLineColFromPtr(options.toml, options.ptr);\n const codeblock = makeCodeBlock(options.toml, line, column);\n super(`Invalid TOML document: ${message}\\n\\n${codeblock}`, options);\n this.line = line;\n this.column = column;\n this.codeblock = codeblock;\n }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { TomlError } from './error.js';\nfunction isEscaped(str, ptr) {\n let i = 0;\n while (str[ptr - ++i] === '\\\\')\n ;\n return --i && (i % 2);\n}\nexport function indexOfNewline(str, start = 0, end = str.length) {\n let idx = str.indexOf('\\n', start);\n if (str[idx - 1] === '\\r')\n idx--;\n return idx <= end ? idx : -1;\n}\nexport function skipComment(str, ptr) {\n for (let i = ptr; i < str.length; i++) {\n let c = str[i];\n if (c === '\\n')\n return i;\n if (c === '\\r' && str[i + 1] === '\\n')\n return i + 1;\n if ((c < '\\x20' && c !== '\\t') || c === '\\x7f') {\n throw new TomlError('control characters are not allowed in comments', {\n toml: str,\n ptr: ptr,\n });\n }\n }\n return str.length;\n}\nexport function skipVoid(str, ptr, banNewLines, banComments) {\n let c;\n while ((c = str[ptr]) === ' ' || c === '\\t' || (!banNewLines && (c === '\\n' || c === '\\r' && str[ptr + 1] === '\\n')))\n ptr++;\n return banComments || c !== '#'\n ? ptr\n : skipVoid(str, skipComment(str, ptr), banNewLines);\n}\nexport function skipUntil(str, ptr, sep, end, banNewLines = false) {\n if (!end) {\n ptr = indexOfNewline(str, ptr);\n return ptr < 0 ? str.length : ptr;\n }\n for (let i = ptr; i < str.length; i++) {\n let c = str[i];\n if (c === '#') {\n i = indexOfNewline(str, i);\n }\n else if (c === sep) {\n return i + 1;\n }\n else if (c === end || (banNewLines && (c === '\\n' || (c === '\\r' && str[i + 1] === '\\n')))) {\n return i;\n }\n }\n throw new TomlError('cannot find end of structure', {\n toml: str,\n ptr: ptr\n });\n}\nexport function getStringEnd(str, seek) {\n let first = str[seek];\n let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2]\n ? str.slice(seek, seek + 3)\n : first;\n seek += target.length - 1;\n do\n seek = str.indexOf(target, ++seek);\n while (seek > -1 && first !== \"'\" && isEscaped(str, seek));\n if (seek > -1) {\n seek += target.length;\n if (target.length > 1) {\n if (str[seek] === first)\n seek++;\n if (str[seek] === first)\n seek++;\n }\n }\n return seek;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nlet DATE_TIME_RE = /^(\\d{4}-\\d{2}-\\d{2})?[T ]?(?:(\\d{2}):\\d{2}(?::\\d{2}(?:\\.\\d+)?)?)?(Z|[-+]\\d{2}:\\d{2})?$/i;\nexport class TomlDate extends Date {\n #hasDate = false;\n #hasTime = false;\n #offset = null;\n constructor(date) {\n let hasDate = true;\n let hasTime = true;\n let offset = 'Z';\n if (typeof date === 'string') {\n let match = date.match(DATE_TIME_RE);\n if (match) {\n if (!match[1]) {\n hasDate = false;\n date = `0000-01-01T${date}`;\n }\n hasTime = !!match[2];\n // Make sure to use T instead of a space. Breaks in case of extreme values otherwise.\n hasTime && date[10] === ' ' && (date = date.replace(' ', 'T'));\n // Do not allow rollover hours.\n if (match[2] && +match[2] > 23) {\n date = '';\n }\n else {\n offset = match[3] || null;\n date = date.toUpperCase();\n if (!offset && hasTime)\n date += 'Z';\n }\n }\n else {\n date = '';\n }\n }\n super(date);\n if (!isNaN(this.getTime())) {\n this.#hasDate = hasDate;\n this.#hasTime = hasTime;\n this.#offset = offset;\n }\n }\n isDateTime() {\n return this.#hasDate && this.#hasTime;\n }\n isLocal() {\n return !this.#hasDate || !this.#hasTime || !this.#offset;\n }\n isDate() {\n return this.#hasDate && !this.#hasTime;\n }\n isTime() {\n return this.#hasTime && !this.#hasDate;\n }\n isValid() {\n return this.#hasDate || this.#hasTime;\n }\n toISOString() {\n let iso = super.toISOString();\n // Local Date\n if (this.isDate())\n return iso.slice(0, 10);\n // Local Time\n if (this.isTime())\n return iso.slice(11, 23);\n // Local DateTime\n if (this.#offset === null)\n return iso.slice(0, -1);\n // Offset DateTime\n if (this.#offset === 'Z')\n return iso;\n // This part is quite annoying: JS strips the original timezone from the ISO string representation\n // Instead of using a \"modified\" date and \"Z\", we restore the representation \"as authored\"\n let offset = (+(this.#offset.slice(1, 3)) * 60) + +(this.#offset.slice(4, 6));\n offset = this.#offset[0] === '-' ? offset : -offset;\n let offsetDate = new Date(this.getTime() - (offset * 60e3));\n return offsetDate.toISOString().slice(0, -1) + this.#offset;\n }\n static wrapAsOffsetDateTime(jsDate, offset = 'Z') {\n let date = new TomlDate(jsDate);\n date.#offset = offset;\n return date;\n }\n static wrapAsLocalDateTime(jsDate) {\n let date = new TomlDate(jsDate);\n date.#offset = null;\n return date;\n }\n static wrapAsLocalDate(jsDate) {\n let date = new TomlDate(jsDate);\n date.#hasTime = false;\n date.#offset = null;\n return date;\n }\n static wrapAsLocalTime(jsDate) {\n let date = new TomlDate(jsDate);\n date.#hasDate = false;\n date.#offset = null;\n return date;\n }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { skipVoid } from './util.js';\nimport { TomlDate } from './date.js';\nimport { TomlError } from './error.js';\nlet INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\\d(_?\\d)*))$/;\nlet FLOAT_REGEX = /^[+-]?\\d(_?\\d)*(\\.\\d(_?\\d)*)?([eE][+-]?\\d(_?\\d)*)?$/;\nlet LEADING_ZERO = /^[+-]?0[0-9_]/;\nlet ESCAPE_REGEX = /^[0-9a-f]{2,8}$/i;\nlet ESC_MAP = {\n b: '\\b',\n t: '\\t',\n n: '\\n',\n f: '\\f',\n r: '\\r',\n e: '\\x1b',\n '\"': '\"',\n '\\\\': '\\\\',\n};\nexport function parseString(str, ptr = 0, endPtr = str.length) {\n let isLiteral = str[ptr] === '\\'';\n let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];\n if (isMultiline) {\n endPtr -= 2;\n if (str[ptr += 2] === '\\r')\n ptr++;\n if (str[ptr] === '\\n')\n ptr++;\n }\n let tmp = 0;\n let isEscape;\n let parsed = '';\n let sliceStart = ptr;\n while (ptr < endPtr - 1) {\n let c = str[ptr++];\n if (c === '\\n' || (c === '\\r' && str[ptr] === '\\n')) {\n if (!isMultiline) {\n throw new TomlError('newlines are not allowed in strings', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n }\n else if ((c < '\\x20' && c !== '\\t') || c === '\\x7f') {\n throw new TomlError('control characters are not allowed in strings', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n if (isEscape) {\n isEscape = false;\n if (c === 'x' || c === 'u' || c === 'U') {\n // Unicode escape\n let code = str.slice(ptr, (ptr += (c === 'x' ? 2 : c === 'u' ? 4 : 8)));\n if (!ESCAPE_REGEX.test(code)) {\n throw new TomlError('invalid unicode escape', {\n toml: str,\n ptr: tmp,\n });\n }\n try {\n parsed += String.fromCodePoint(parseInt(code, 16));\n }\n catch {\n throw new TomlError('invalid unicode escape', {\n toml: str,\n ptr: tmp,\n });\n }\n }\n else if (isMultiline && (c === '\\n' || c === ' ' || c === '\\t' || c === '\\r')) {\n // Multiline escape\n ptr = skipVoid(str, ptr - 1, true);\n if (str[ptr] !== '\\n' && str[ptr] !== '\\r') {\n throw new TomlError('invalid escape: only line-ending whitespace may be escaped', {\n toml: str,\n ptr: tmp,\n });\n }\n ptr = skipVoid(str, ptr);\n }\n else if (c in ESC_MAP) {\n // Classic escape\n parsed += ESC_MAP[c];\n }\n else {\n throw new TomlError('unrecognized escape sequence', {\n toml: str,\n ptr: tmp,\n });\n }\n sliceStart = ptr;\n }\n else if (!isLiteral && c === '\\\\') {\n tmp = ptr - 1;\n isEscape = true;\n parsed += str.slice(sliceStart, tmp);\n }\n }\n return parsed + str.slice(sliceStart, endPtr - 1);\n}\nexport function parseValue(value, toml, ptr, integersAsBigInt) {\n // Constant values\n if (value === 'true')\n return true;\n if (value === 'false')\n return false;\n if (value === '-inf')\n return -Infinity;\n if (value === 'inf' || value === '+inf')\n return Infinity;\n if (value === 'nan' || value === '+nan' || value === '-nan')\n return NaN;\n // Avoid FP representation of -0\n if (value === '-0')\n return integersAsBigInt ? 0n : 0;\n // Numbers\n let isInt = INT_REGEX.test(value);\n if (isInt || FLOAT_REGEX.test(value)) {\n if (LEADING_ZERO.test(value)) {\n throw new TomlError('leading zeroes are not allowed', {\n toml: toml,\n ptr: ptr,\n });\n }\n value = value.replace(/_/g, '');\n let numeric = +value;\n if (isNaN(numeric)) {\n throw new TomlError('invalid number', {\n toml: toml,\n ptr: ptr,\n });\n }\n if (isInt) {\n if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) {\n throw new TomlError('integer value cannot be represented losslessly', {\n toml: toml,\n ptr: ptr,\n });\n }\n if (isInt || integersAsBigInt === true)\n numeric = BigInt(value);\n }\n return numeric;\n }\n const date = new TomlDate(value);\n if (!date.isValid()) {\n throw new TomlError('invalid value', {\n toml: toml,\n ptr: ptr,\n });\n }\n return date;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseString, parseValue } from './primitive.js';\nimport { parseArray, parseInlineTable } from './struct.js';\nimport { skipVoid, skipUntil, skipComment, getStringEnd } from './util.js';\nimport { TomlError } from './error.js';\nfunction sliceAndTrimEndOf(str, startPtr, endPtr) {\n let value = str.slice(startPtr, endPtr);\n let commentIdx = value.indexOf('#');\n if (commentIdx > -1) {\n // The call to skipComment allows to \"validate\" the comment\n // (absence of control characters)\n skipComment(str, commentIdx);\n value = value.slice(0, commentIdx);\n }\n return [value.trimEnd(), commentIdx];\n}\nexport function extractValue(str, ptr, end, depth, integersAsBigInt) {\n if (depth === 0) {\n throw new TomlError('document contains excessively nested structures. aborting.', {\n toml: str,\n ptr: ptr\n });\n }\n let c = str[ptr];\n if (c === '[' || c === '{') {\n let [value, endPtr] = c === '['\n ? parseArray(str, ptr, depth, integersAsBigInt)\n : parseInlineTable(str, ptr, depth, integersAsBigInt);\n if (end) {\n endPtr = skipVoid(str, endPtr);\n if (str[endPtr] === ',')\n endPtr++;\n else if (str[endPtr] !== end) {\n throw new TomlError('expected comma or end of structure', {\n toml: str,\n ptr: endPtr,\n });\n }\n }\n return [value, endPtr];\n }\n let endPtr;\n if (c === '\"' || c === \"'\") {\n endPtr = getStringEnd(str, ptr);\n let parsed = parseString(str, ptr, endPtr);\n if (end) {\n endPtr = skipVoid(str, endPtr);\n if (str[endPtr] && str[endPtr] !== ',' && str[endPtr] !== end && str[endPtr] !== '\\n' && str[endPtr] !== '\\r') {\n throw new TomlError('unexpected character encountered', {\n toml: str,\n ptr: endPtr,\n });\n }\n endPtr += (+(str[endPtr] === ','));\n }\n return [parsed, endPtr];\n }\n endPtr = skipUntil(str, ptr, ',', end);\n let slice = sliceAndTrimEndOf(str, ptr, endPtr - (+(str[endPtr - 1] === ',')));\n if (!slice[0]) {\n throw new TomlError('incomplete key-value declaration: no value specified', {\n toml: str,\n ptr: ptr\n });\n }\n if (end && slice[1] > -1) {\n endPtr = skipVoid(str, ptr + slice[1]);\n endPtr += +(str[endPtr] === ',');\n }\n return [\n parseValue(slice[0], str, ptr, integersAsBigInt),\n endPtr,\n ];\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseString } from './primitive.js';\nimport { extractValue } from './extract.js';\nimport { getStringEnd, indexOfNewline, skipComment, skipVoid } from './util.js';\nimport { TomlError } from './error.js';\nlet KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \\t]*$/;\nexport function parseKey(str, ptr, end = '=') {\n let dot = ptr - 1;\n let parsed = [];\n let endPtr = str.indexOf(end, ptr);\n if (endPtr < 0) {\n throw new TomlError('incomplete key-value: cannot find end of key', {\n toml: str,\n ptr: ptr,\n });\n }\n do {\n let c = str[ptr = ++dot];\n // If it's whitespace, ignore\n if (c !== ' ' && c !== '\\t') {\n // If it's a string\n if (c === '\"' || c === '\\'') {\n if (c === str[ptr + 1] && c === str[ptr + 2]) {\n throw new TomlError('multiline strings are not allowed in keys', {\n toml: str,\n ptr: ptr,\n });\n }\n let eos = getStringEnd(str, ptr);\n if (eos < 0) {\n throw new TomlError('unfinished string encountered', {\n toml: str,\n ptr: ptr,\n });\n }\n dot = str.indexOf('.', eos);\n let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);\n let newLine = indexOfNewline(strEnd);\n if (newLine > -1) {\n throw new TomlError('newlines are not allowed in keys', {\n toml: str,\n ptr: ptr + dot + newLine,\n });\n }\n if (strEnd.trimStart()) {\n throw new TomlError('found extra tokens after the string part', {\n toml: str,\n ptr: eos,\n });\n }\n if (endPtr < eos) {\n endPtr = str.indexOf(end, eos);\n if (endPtr < 0) {\n throw new TomlError('incomplete key-value: cannot find end of key', {\n toml: str,\n ptr: ptr,\n });\n }\n }\n parsed.push(parseString(str, ptr, eos));\n }\n else {\n // Normal raw key part consumption and validation\n dot = str.indexOf('.', ptr);\n let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);\n if (!KEY_PART_RE.test(part)) {\n throw new TomlError('only letter, numbers, dashes and underscores are allowed in keys', {\n toml: str,\n ptr: ptr,\n });\n }\n parsed.push(part.trimEnd());\n }\n }\n // Until there's no more dot\n } while (dot + 1 && dot < endPtr);\n return [parsed, skipVoid(str, endPtr + 1, true, true)];\n}\nexport function parseInlineTable(str, ptr, depth, integersAsBigInt) {\n let res = {};\n let seen = new Set();\n let c;\n ptr++;\n while ((c = str[ptr++]) !== '}' && c) {\n if (c === ',') {\n throw new TomlError('expected value, found comma', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n else if (c === '#')\n ptr = skipComment(str, ptr);\n else if (c !== ' ' && c !== '\\t' && c !== '\\n' && c !== '\\r') {\n let k;\n let t = res;\n let hasOwn = false;\n let [key, keyEndPtr] = parseKey(str, ptr - 1);\n for (let i = 0; i < key.length; i++) {\n if (i)\n t = hasOwn ? t[k] : (t[k] = {});\n k = key[i];\n if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== 'object' || seen.has(t[k]))) {\n throw new TomlError('trying to redefine an already defined value', {\n toml: str,\n ptr: ptr,\n });\n }\n if (!hasOwn && k === '__proto__') {\n Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });\n }\n }\n if (hasOwn) {\n throw new TomlError('trying to redefine an already defined value', {\n toml: str,\n ptr: ptr,\n });\n }\n let [value, valueEndPtr] = extractValue(str, keyEndPtr, '}', depth - 1, integersAsBigInt);\n seen.add(value);\n t[k] = value;\n ptr = valueEndPtr;\n }\n }\n if (!c) {\n throw new TomlError('unfinished table encountered', {\n toml: str,\n ptr: ptr,\n });\n }\n return [res, ptr];\n}\nexport function parseArray(str, ptr, depth, integersAsBigInt) {\n let res = [];\n let c;\n ptr++;\n while ((c = str[ptr++]) !== ']' && c) {\n if (c === ',') {\n throw new TomlError('expected value, found comma', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n else if (c === '#')\n ptr = skipComment(str, ptr);\n else if (c !== ' ' && c !== '\\t' && c !== '\\n' && c !== '\\r') {\n let e = extractValue(str, ptr - 1, ']', depth - 1, integersAsBigInt);\n res.push(e[0]);\n ptr = e[1];\n }\n }\n if (!c) {\n throw new TomlError('unfinished array encountered', {\n toml: str,\n ptr: ptr,\n });\n }\n return [res, ptr];\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseKey } from './struct.js';\nimport { extractValue } from './extract.js';\nimport { skipVoid } from './util.js';\nimport { TomlError } from './error.js';\nfunction peekTable(key, table, meta, type) {\n let t = table;\n let m = meta;\n let k;\n let hasOwn = false;\n let state;\n for (let i = 0; i < key.length; i++) {\n if (i) {\n t = hasOwn ? t[k] : (t[k] = {});\n m = (state = m[k]).c;\n if (type === 0 /* Type.DOTTED */ && (state.t === 1 /* Type.EXPLICIT */ || state.t === 2 /* Type.ARRAY */)) {\n return null;\n }\n if (state.t === 2 /* Type.ARRAY */) {\n let l = t.length - 1;\n t = t[l];\n m = m[l].c;\n }\n }\n k = key[i];\n if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 /* Type.DOTTED */ && m[k]?.d) {\n return null;\n }\n if (!hasOwn) {\n if (k === '__proto__') {\n Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });\n Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });\n }\n m[k] = {\n t: i < key.length - 1 && type === 2 /* Type.ARRAY */\n ? 3 /* Type.ARRAY_DOTTED */\n : type,\n d: false,\n i: 0,\n c: {},\n };\n }\n }\n state = m[k];\n if (state.t !== type && !(type === 1 /* Type.EXPLICIT */ && state.t === 3 /* Type.ARRAY_DOTTED */)) {\n // Bad key type!\n return null;\n }\n if (type === 2 /* Type.ARRAY */) {\n if (!state.d) {\n state.d = true;\n t[k] = [];\n }\n t[k].push(t = {});\n state.c[state.i++] = (state = { t: 1 /* Type.EXPLICIT */, d: false, i: 0, c: {} });\n }\n if (state.d) {\n // Redefining a table!\n return null;\n }\n state.d = true;\n if (type === 1 /* Type.EXPLICIT */) {\n t = hasOwn ? t[k] : (t[k] = {});\n }\n else if (type === 0 /* Type.DOTTED */ && hasOwn) {\n return null;\n }\n return [k, t, state.c];\n}\nexport function parse(toml, { maxDepth = 1000, integersAsBigInt } = {}) {\n let res = {};\n let meta = {};\n let tbl = res;\n let m = meta;\n for (let ptr = skipVoid(toml, 0); ptr < toml.length;) {\n if (toml[ptr] === '[') {\n let isTableArray = toml[++ptr] === '[';\n let k = parseKey(toml, ptr += +isTableArray, ']');\n if (isTableArray) {\n if (toml[k[1] - 1] !== ']') {\n throw new TomlError('expected end of table declaration', {\n toml: toml,\n ptr: k[1] - 1,\n });\n }\n k[1]++;\n }\n let p = peekTable(k[0], res, meta, isTableArray ? 2 /* Type.ARRAY */ : 1 /* Type.EXPLICIT */);\n if (!p) {\n throw new TomlError('trying to redefine an already defined table or value', {\n toml: toml,\n ptr: ptr,\n });\n }\n m = p[2];\n tbl = p[1];\n ptr = k[1];\n }\n else {\n let k = parseKey(toml, ptr);\n let p = peekTable(k[0], tbl, m, 0 /* Type.DOTTED */);\n if (!p) {\n throw new TomlError('trying to redefine an already defined table or value', {\n toml: toml,\n ptr: ptr,\n });\n }\n let v = extractValue(toml, k[1], void 0, maxDepth, integersAsBigInt);\n p[1][p[0]] = v[0];\n ptr = v[1];\n }\n ptr = skipVoid(toml, ptr, true);\n if (toml[ptr] && toml[ptr] !== '\\n' && toml[ptr] !== '\\r') {\n throw new TomlError('each key-value declaration must be followed by an end-of-line', {\n toml: toml,\n ptr: ptr\n });\n }\n ptr = skipVoid(toml, ptr);\n }\n return res;\n}\n","import pc from \"picocolors\";\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\n\n/** Try to render a JSON value as a human-readable table. Returns null if shape isn't recognized. */\nexport function renderTable(value: JsonValue): string | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n\n const v = value as Record<string, JsonValue>;\n\n if (\"alerts\" in v && \"scan_duration_ms\" in v) return renderScan(v);\n if (\"holders\" in v) return renderWhales(v);\n if (\"opportunities\" in v && \"total_opportunities\" in v) return renderCompare(v);\n if (\"arb_opportunities\" in v && \"rates\" in v) return renderYieldScan(v);\n if (\"rates\" in v && \"asset\" in v) return renderYield(v);\n if (\"chains\" in v && \"total_alerts\" in v) return renderScanAll(v);\n if (\"chains\" in v && \"chains_scanned\" in v) return renderPositions(v);\n if (\"bridge\" in v && \"amount_out\" in v) return renderBridge(v);\n if (\"aggregator\" in v && \"amount_out\" in v) return renderSwap(v);\n if (\"protocols\" in v && \"summary\" in v) return renderStatus(v);\n if (\"token_balances\" in v && \"lending_positions\" in v) return renderPortfolio(v);\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Simple table helpers (no external dep)\n// ---------------------------------------------------------------------------\n\nfunction makeTable(headers: string[], rows: string[][]): string {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").replace(/\\x1b\\[[0-9;]*m/g, \"\").length))\n );\n\n const sep = \"┼\" + colWidths.map((w) => \"─\".repeat(w + 2)).join(\"┼\") + \"┼\";\n const topBorder = \"┌\" + colWidths.map((w) => \"─\".repeat(w + 2)).join(\"┬\") + \"┐\";\n const midBorder = \"├\" + colWidths.map((w) => \"─\".repeat(w + 2)).join(\"┼\") + \"┤\";\n const botBorder = \"└\" + colWidths.map((w) => \"─\".repeat(w + 2)).join(\"┴\") + \"┘\";\n\n function padCell(text: string, width: number): string {\n const visLen = text.replace(/\\x1b\\[[0-9;]*m/g, \"\").length;\n return text + \" \".repeat(Math.max(0, width - visLen));\n }\n\n const headerRow = \"│ \" + headers.map((h, i) => padCell(pc.bold(h), colWidths[i])).join(\" │ \") + \" │\";\n const dataRows = rows.map(\n (row) => \"│ \" + row.map((cell, i) => padCell(cell ?? \"\", colWidths[i])).join(\" │ \") + \" │\"\n );\n\n return [topBorder, headerRow, midBorder, ...dataRows, botBorder].join(\"\\n\");\n}\n\nfunction asStr(v: JsonValue | undefined): string {\n if (v === undefined || v === null) return \"?\";\n return String(v);\n}\n\nfunction asF64(v: JsonValue | undefined): number {\n if (typeof v === \"number\") return v;\n if (typeof v === \"string\") return parseFloat(v) || 0;\n return 0;\n}\n\nfunction asU64(v: JsonValue | undefined): number {\n if (typeof v === \"number\") return Math.floor(v);\n if (typeof v === \"string\") return parseInt(v, 10) || 0;\n return 0;\n}\n\nfunction asArr(v: JsonValue | undefined): JsonValue[] {\n if (Array.isArray(v)) return v;\n return [];\n}\n\nfunction asObj(v: JsonValue | undefined): Record<string, JsonValue> {\n if (v && typeof v === \"object\" && !Array.isArray(v)) return v as Record<string, JsonValue>;\n return {};\n}\n\nfunction formatPrice(v: JsonValue | undefined): string {\n const p = asF64(v);\n if (p === 0) return \"?\";\n return p > 1000 ? `$${p.toFixed(0)}` : `$${p.toFixed(4)}`;\n}\n\n// ---------------------------------------------------------------------------\n// Renderers\n// ---------------------------------------------------------------------------\n\nfunction renderScan(v: Record<string, JsonValue>): string {\n const chain = asStr(v[\"chain\"]);\n const ms = asU64(v[\"scan_duration_ms\"]);\n const count = asU64(v[\"alert_count\"]);\n let out = ` Scan: ${chain} (${ms} ms)\\n`;\n\n if (count > 0) {\n const rows = asArr(v[\"alerts\"]).map((a) => {\n const ao = asObj(a as JsonValue);\n const sev = asStr(ao[\"severity\"]);\n const color = sev === \"critical\" ? pc.red : sev === \"high\" ? pc.yellow : pc.cyan;\n return [\n color(sev.toUpperCase()),\n asStr(ao[\"pattern\"]),\n asStr(ao[\"asset\"]),\n formatPrice(ao[\"oracle_price\"]),\n formatPrice(ao[\"dex_price\"]),\n `${asF64(ao[\"deviation_pct\"]).toFixed(1)}%`,\n ];\n });\n out += makeTable([\"Severity\", \"Pattern\", \"Asset\", \"Oracle\", \"DEX\", \"Gap\"], rows);\n } else {\n out += ` ${count} alerts\\n`;\n }\n\n const data = asObj(v[\"data\"]);\n const o = Object.keys(asObj(data[\"oracle_prices\"])).length;\n const d = Object.keys(asObj(data[\"dex_prices\"])).length;\n const s = Object.keys(asObj(data[\"stablecoin_pegs\"])).length;\n out += `\\n Data: ${o} oracle, ${d} dex, ${s} stablecoin prices`;\n return out;\n}\n\nfunction renderScanAll(v: Record<string, JsonValue>): string {\n const total = asU64(v[\"total_alerts\"]);\n const scanned = asU64(v[\"chains_scanned\"]);\n const ms = asU64(v[\"scan_duration_ms\"]);\n\n const rows = asArr(v[\"chains\"]).map((c) => {\n const co = asObj(c as JsonValue);\n const alerts = asU64(co[\"alert_count\"]);\n const cms = asU64(co[\"scan_duration_ms\"]);\n const details = asArr(co[\"alerts\"])\n .map((a) => asStr(asObj(a as JsonValue)[\"asset\"]))\n .join(\", \") || \"clean\";\n const alertStr = alerts > 0 ? pc.yellow(String(alerts)) : pc.green(String(alerts));\n return [asStr(co[\"chain\"]), alertStr, `${cms}ms`, details];\n });\n\n return ` All-chain scan: ${scanned} chains, ${total} alerts, ${ms}ms\\n\\n` +\n makeTable([\"Chain\", \"Alerts\", \"Time\", \"Details\"], rows);\n}\n\nfunction renderWhales(v: Record<string, JsonValue>): string {\n const chain = asStr(v[\"chain\"]);\n const token = asStr(v[\"token\"]);\n\n const rows = asArr(v[\"holders\"]).map((h) => {\n const ho = asObj(h as JsonValue);\n const addr = asStr(ho[\"address\"]);\n const short = addr.length > 18 ? `${addr.slice(0, 10)}...${addr.slice(-6)}` : addr;\n return [String(asU64(ho[\"rank\"])), short, asF64(ho[\"balance\"]).toFixed(2)];\n });\n\n return ` ${chain} ${token} Top Holders\\n\\n` + makeTable([\"#\", \"Address\", `${token} Balance`], rows);\n}\n\nfunction renderYield(v: Record<string, JsonValue>): string {\n const chain = asStr(v[\"chain\"]);\n const asset = asStr(v[\"asset\"]);\n\n const rows = asArr(v[\"rates\"]).map((r) => {\n const ro = asObj(r as JsonValue);\n const supply = asF64(ro[\"supply_apy\"]);\n const borrow = asF64(ro[\"borrow_variable_apy\"]);\n const color = supply > 3 ? pc.green : supply > 1 ? pc.cyan : (s: string) => s;\n return [asStr(ro[\"protocol\"]), color(`${supply.toFixed(2)}%`), `${borrow.toFixed(2)}%`];\n });\n\n const best = asStr(v[\"best_supply\"]);\n return ` ${chain} ${asset} Yield Comparison (best: ${best})\\n\\n` +\n makeTable([\"Protocol\", \"Supply APY\", \"Borrow APY\"], rows);\n}\n\nfunction renderPositions(v: Record<string, JsonValue>): string {\n const addr = asStr(v[\"address\"]);\n const summary = asObj(v[\"summary\"]);\n const total = asF64(v[\"total_value_usd\"] ?? summary[\"total_value_usd\"]);\n const ms = asU64(v[\"scan_duration_ms\"]);\n const scanned = asU64(v[\"chains_scanned\"]);\n\n let out = ` Positions for ${addr.slice(0, 8)}...${addr.slice(-4)} (${ms}ms, ${scanned} chains)\\n Total: $${total.toFixed(2)}\\n\\n`;\n\n for (const c of asArr(v[\"chains\"])) {\n const co = asObj(c as JsonValue);\n const chain = asStr(co[\"chain\"]);\n const ctotal = asF64(co[\"chain_total_usd\"]);\n out += ` ${chain} ($${ctotal.toFixed(2)})\\n`;\n\n const rows: string[][] = [];\n for (const b of asArr(co[\"token_balances\"])) {\n const bo = asObj(b as JsonValue);\n rows.push([\"wallet\", asStr(bo[\"symbol\"]), pc.green(`$${asF64(bo[\"value_usd\"]).toFixed(2)}`)]);\n }\n for (const l of asArr(co[\"lending_positions\"])) {\n const lo = asObj(l as JsonValue);\n const coll = asF64(lo[\"collateral_usd\"]);\n const debt = asF64(lo[\"debt_usd\"]);\n rows.push([\"lending\", asStr(lo[\"protocol\"]), pc.cyan(`coll $${coll.toFixed(0)} debt $${debt.toFixed(0)}`)]);\n }\n out += makeTable([\"Type\", \"Asset/Protocol\", \"Value\"], rows) + \"\\n\";\n }\n return out;\n}\n\nfunction renderSwap(v: Record<string, JsonValue>): string {\n const from = asStr(v[\"from\"]);\n const to = asStr(v[\"to\"]);\n const amtIn = asF64(v[\"amount_in\"]);\n const amtOut = asF64(v[\"amount_out\"]);\n const impact = typeof v[\"price_impact_pct\"] === \"number\"\n ? `${asF64(v[\"price_impact_pct\"]).toFixed(4)}%`\n : \"n/a\";\n const agg = asStr(v[\"aggregator\"]);\n const chain = asStr(v[\"chain\"]);\n return ` Swap on ${chain} via ${agg}\\n\\n ${amtIn} ${from} -> ${amtOut.toFixed(6)} ${to}\\n Price impact: ${impact}\\n`;\n}\n\nfunction renderBridge(v: Record<string, JsonValue>): string {\n const from = asStr(v[\"from_chain\"]);\n const to = asStr(v[\"to_chain\"]);\n const token = asStr(v[\"token\"]);\n const amtIn = asF64(v[\"amount_in\"]);\n const amtOut = asF64(v[\"amount_out\"]);\n const cost = asF64(v[\"total_cost_usd\"]);\n const time = asU64(v[\"estimated_time_sec\"]);\n const bridge = asStr(v[\"bridge\"]);\n return ` Bridge ${from} -> ${to} via ${bridge}\\n\\n ${amtIn} ${token} -> ${amtOut.toFixed(6)} ${token}\\n Cost: $${cost.toFixed(2)} | Time: ${time}s\\n`;\n}\n\nfunction renderStatus(v: Record<string, JsonValue>): string {\n const chain = asStr(v[\"chain\"]);\n const summary = asObj(v[\"summary\"]);\n const totalP = asU64(summary[\"total_protocols\"]);\n const totalT = asU64(summary[\"total_tokens\"]);\n\n const rows = asArr(v[\"protocols\"]).map((p) => {\n const po = asObj(p as JsonValue);\n return [asStr(po[\"name\"]), asStr(po[\"category\"]), asStr(po[\"interface\"])];\n });\n\n const tokens = asArr(v[\"tokens\"]).map((t) => String(t)).filter(Boolean);\n let out = ` ${chain} — ${totalP} protocols`;\n if (tokens.length > 0) {\n out += `, ${totalT} tokens\\n Tokens: ${tokens.join(\", \")}`;\n }\n return `${out}\\n\\n` + makeTable([\"Protocol\", \"Category\", \"Interface\"], rows);\n}\n\nfunction renderCompare(v: Record<string, JsonValue>): string {\n const asset = asStr(v[\"asset\"]);\n const ms = asU64(v[\"scan_duration_ms\"]);\n const total = asU64(v[\"total_opportunities\"]);\n\n const rows = asArr(v[\"opportunities\"]).map((opp) => {\n const oo = asObj(opp as JsonValue);\n const typ = asStr(oo[\"type\"]);\n const apy = asF64(oo[\"apy\"]);\n const detail = asStr(oo[\"detail\"]);\n const risk = asStr(oo[\"risk\"]);\n const oppAsset = asStr(oo[\"asset\"]);\n\n const typeLabel = typ === \"perp_funding\" ? \"Perp Arb\"\n : typ === \"perp_rate\" ? \"Perp Rate\"\n : typ === \"lending_supply\" ? \"Lending\"\n : typ;\n\n const apyColor = Math.abs(apy) > 20 ? pc.green : Math.abs(apy) > 5 ? pc.cyan : (s: string) => s;\n const riskColor = risk === \"high\" ? pc.red : risk === \"medium\" ? pc.yellow : pc.green;\n\n return [typeLabel, oppAsset, apyColor(`${apy.toFixed(1)}%`), detail, riskColor(risk)];\n });\n\n return ` Yield Compare: ${asset} (${total} opportunities, ${ms}ms)\\n\\n` +\n makeTable([\"Type\", \"Asset\", \"APY\", \"Where\", \"Risk\"], rows);\n}\n\nfunction renderYieldScan(v: Record<string, JsonValue>): string {\n const asset = asStr(v[\"asset\"]);\n const ms = asU64(v[\"scan_duration_ms\"]);\n const best = asStr(v[\"best_supply\"]);\n\n const rows = asArr(v[\"rates\"]).map((r) => {\n const ro = asObj(r as JsonValue);\n const supply = asF64(ro[\"supply_apy\"]);\n const borrow = asF64(ro[\"borrow_variable_apy\"]);\n const color = supply > 3 ? pc.green : supply > 1 ? pc.cyan : (s: string) => s;\n return [asStr(ro[\"chain\"]), asStr(ro[\"protocol\"]), color(`${supply.toFixed(2)}%`), `${borrow.toFixed(2)}%`];\n });\n\n let out = ` ${asset} Yield Scan (${ms}ms) — Best: ${best}\\n\\n` +\n makeTable([\"Chain\", \"Protocol\", \"Supply APY\", \"Borrow APY\"], rows);\n\n const arbs = asArr(v[\"arb_opportunities\"]);\n if (arbs.length > 0) {\n const arbRows = arbs.map((a) => {\n const ao = asObj(a as JsonValue);\n const spread = asF64(ao[\"spread_pct\"]);\n const color = spread > 1 ? pc.green : pc.cyan;\n return [\n color(`+${spread.toFixed(2)}%`),\n `${asStr(ao[\"supply_protocol\"])} (${asStr(ao[\"supply_chain\"])})`,\n `${asStr(ao[\"borrow_protocol\"])} (${asStr(ao[\"borrow_chain\"])})`,\n asStr(ao[\"strategy\"]),\n ];\n });\n out += \"\\n Arb Opportunities\\n\\n\" + makeTable([\"Spread\", \"Supply @\", \"Borrow @\", \"Type\"], arbRows);\n }\n\n return out;\n}\n\nfunction renderPortfolio(v: Record<string, JsonValue>): string {\n return renderPositions(v);\n}\n","import { jsonStringify, jsonReplacerDecimal } from \"@hypurrquant/defi-core\";\nimport { renderTable } from \"./table.js\";\n\nexport interface OutputMode {\n json: boolean;\n ndjson: boolean;\n fields?: string[];\n}\n\nexport function parseOutputMode(opts: {\n json?: boolean;\n ndjson?: boolean;\n fields?: string;\n}): OutputMode {\n return {\n json: !!(opts.json || opts.ndjson),\n ndjson: !!opts.ndjson,\n fields: opts.fields\n ? opts.fields.split(\",\").map((f) => f.trim())\n : undefined,\n };\n}\n\nexport function formatOutput(value: unknown, mode: OutputMode): string {\n if (mode.ndjson) {\n return JSON.stringify(value, jsonReplacerDecimal);\n }\n\n if (mode.json) {\n let jsonVal = JSON.parse(jsonStringify(value));\n\n if (mode.fields && typeof jsonVal === \"object\" && jsonVal !== null && !Array.isArray(jsonVal)) {\n const filtered: Record<string, unknown> = {};\n for (const key of mode.fields) {\n if (key in jsonVal) filtered[key] = jsonVal[key];\n }\n jsonVal = filtered;\n }\n\n return JSON.stringify(jsonVal, null, 2);\n }\n\n // Human-readable: try table format, fallback to pretty JSON\n const jsonVal = JSON.parse(jsonStringify(value));\n const table = renderTable(jsonVal);\n if (table !== null) return table;\n return JSON.stringify(jsonVal, null, 2);\n}\n\nexport function printOutput(value: unknown, mode: OutputMode): void {\n console.log(formatOutput(value, mode));\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createPublicClient, http } from \"viem\";\n\ninterface ContractStatus {\n name: string;\n address: string;\n has_code?: boolean;\n status?: string;\n}\n\ninterface ProtocolStatus {\n slug: string;\n name: string;\n category: string;\n interface: string;\n contracts: ContractStatus[];\n}\n\ninterface StatusSummary {\n total_protocols: number;\n verified_contracts?: number;\n invalid_contracts?: number;\n placeholder_contracts?: number;\n}\n\ninterface StatusOutput {\n chain: string;\n chain_id: number;\n rpc_url: string;\n block_number?: number;\n protocols: ProtocolStatus[];\n summary: StatusSummary;\n}\n\nfunction isPlaceholder(addr: string): boolean {\n if (!addr.startsWith(\"0x\") || addr.length !== 42) return false;\n const hex = addr.slice(2).toLowerCase();\n return hex.slice(0, 36).split(\"\").every((c) => c === \"0\") && parseInt(hex.slice(36), 16) <= 0x10;\n}\n\nexport function registerStatus(\n parent: Command,\n getOpts: () => OutputMode,\n): void {\n parent\n .command(\"status\")\n .description(\"Show chain and protocol status\")\n .option(\"--verify\", \"Verify contract addresses on-chain\")\n .action(async (opts) => {\n const globalOpts = parent.opts<{ chain?: string }>();\n const chainName = globalOpts.chain ?? \"hyperevm\";\n\n const registry = Registry.loadEmbedded();\n const chainConfig = registry.getChain(chainName);\n const chainProtocols = registry.getProtocolsForChain(chainName);\n\n let blockNumber: number | undefined;\n let codeMap: Map<string, boolean> | undefined;\n let placeholderCount = 0;\n\n // Count placeholders\n for (const p of chainProtocols) {\n for (const addr of Object.values(p.contracts ?? {}) as string[]) {\n if (isPlaceholder(addr)) placeholderCount++;\n }\n }\n\n if (opts.verify) {\n const rpcUrl = chainConfig.effectiveRpcUrl();\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n try {\n const bn = await client.getBlockNumber();\n blockNumber = Number(bn);\n process.stderr.write(\n `Connected to ${rpcUrl} (block #${blockNumber}). Verifying contracts...\\n`,\n );\n } catch (e) {\n process.stderr.write(`Warning: could not get block number\\n`);\n }\n\n codeMap = new Map();\n const allAddrs: Array<{ key: string; addr: Address }> = [];\n\n for (const p of chainProtocols) {\n for (const [name, addr] of Object.entries(p.contracts ?? {}) as [string, string][]) {\n if (!isPlaceholder(addr)) {\n allAddrs.push({ key: `${p.name}:${name}`, addr: addr as Address });\n }\n }\n }\n\n // Batch verify in chunks of 20\n for (let i = 0; i < allAddrs.length; i += 20) {\n const chunk = allAddrs.slice(i, i + 20);\n const results = await Promise.all(\n chunk.map(async ({ key, addr }) => {\n try {\n const code = await client.getCode({ address: addr as `0x${string}` });\n return { key, hasCode: !!code && code !== \"0x\" };\n } catch {\n return { key, hasCode: false };\n }\n }),\n );\n for (const r of results) {\n codeMap.set(r.key, r.hasCode);\n }\n }\n }\n\n // Build output\n let verifiedCount = 0;\n let invalidCount = 0;\n\n const protocols: ProtocolStatus[] = chainProtocols.map((p) => {\n const contracts: ContractStatus[] = (Object.entries(p.contracts ?? {}) as [string, string][]).map(\n ([name, addr]) => {\n if (isPlaceholder(addr)) {\n return { name, address: addr, status: \"placeholder\" };\n }\n if (codeMap) {\n const hasCode = codeMap.get(`${p.name}:${name}`) ?? false;\n if (hasCode) verifiedCount++;\n else invalidCount++;\n return {\n name,\n address: addr,\n has_code: hasCode,\n status: hasCode ? \"verified\" : \"NO_CODE\",\n };\n }\n return { name, address: addr };\n },\n );\n\n return {\n slug: p.slug,\n name: p.name,\n category: p.category,\n interface: p.interface,\n contracts,\n };\n });\n\n const output: StatusOutput = {\n chain: chainConfig.name,\n chain_id: chainConfig.chain_id,\n rpc_url: chainConfig.effectiveRpcUrl(),\n ...(blockNumber !== undefined ? { block_number: blockNumber } : {}),\n protocols,\n summary: {\n total_protocols: protocols.length,\n ...(opts.verify\n ? {\n verified_contracts: verifiedCount,\n invalid_contracts: invalidCount,\n placeholder_contracts: placeholderCount,\n }\n : {}),\n },\n };\n\n printOutput(output, getOpts());\n });\n}\n","import * as readline from \"readline\";\nimport type { Executor } from \"./executor.js\";\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type { Registry } from \"@hypurrquant/defi-core\";\n\nexport interface AgentCommand {\n action: string;\n params: unknown;\n}\n\nexport interface AgentResponse {\n action: string;\n success: boolean;\n result?: unknown;\n error?: string;\n}\n\nexport async function runAgent(registry: Registry, executor: Executor): Promise<void> {\n const rl = readline.createInterface({ input: process.stdin, terminal: false });\n\n for await (const line of rl) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n let cmd: AgentCommand;\n try {\n cmd = JSON.parse(trimmed) as AgentCommand;\n } catch (e: unknown) {\n const resp: AgentResponse = {\n action: \"unknown\",\n success: false,\n error: `Invalid JSON: ${e instanceof Error ? e.message : String(e)}`,\n };\n console.log(JSON.stringify(resp));\n continue;\n }\n\n const resp = await dispatchCommand(cmd, registry, executor);\n console.log(JSON.stringify(resp));\n }\n}\n\nasync function dispatchCommand(\n cmd: AgentCommand,\n registry: Registry,\n executor: Executor,\n): Promise<AgentResponse> {\n try {\n const result = await handleAction(cmd.action, cmd.params, registry, executor);\n return { action: cmd.action, success: true, result };\n } catch (e: unknown) {\n return {\n action: cmd.action,\n success: false,\n error: e instanceof Error ? e.message : String(e),\n };\n }\n}\n\nasync function handleAction(\n action: string,\n params: unknown,\n registry: Registry,\n executor: Executor,\n): Promise<unknown> {\n const p = (params ?? {}) as Record<string, unknown>;\n\n switch (action) {\n case \"status\":\n return handleStatus(registry);\n\n case \"list_protocols\":\n return handleListProtocols(registry, p);\n\n case \"schema\":\n return handleSchema(p);\n\n case \"dex.swap\":\n case \"dex.quote\":\n case \"lending.supply\":\n case \"lending.borrow\":\n case \"lending.repay\":\n case \"lending.withdraw\":\n case \"staking.stake\":\n case \"staking.unstake\":\n case \"vault.deposit\":\n case \"vault.withdraw\":\n case \"cdp.open\":\n throw DefiError.unsupported(`Agent action '${action}' not yet implemented in TS port`);\n\n default:\n throw DefiError.unsupported(`Unknown action: ${action}`);\n }\n}\n\nfunction handleStatus(registry: Registry): unknown {\n const chain = registry.getChain(\"hyperevm\");\n const protocols = registry.protocols.map((p) => ({\n name: p.name,\n slug: p.slug,\n category: p.category,\n interface: p.interface,\n native: p.native,\n }));\n\n return {\n chain: chain.name,\n chain_id: chain.chain_id,\n protocol_count: protocols.length,\n protocols,\n };\n}\n\nfunction handleListProtocols(registry: Registry, params: Record<string, unknown>): unknown {\n const categoryFilter = typeof params[\"category\"] === \"string\" ? params[\"category\"] : undefined;\n\n const protocols = registry.protocols\n .filter((p) => !categoryFilter || p.category.toLowerCase() === categoryFilter.toLowerCase())\n .map((p) => ({\n name: p.name,\n slug: p.slug,\n category: p.category,\n interface: p.interface,\n }));\n\n return { protocols };\n}\n\nexport function handleSchema(params: Record<string, unknown>): unknown {\n const action = typeof params[\"action\"] === \"string\" ? params[\"action\"] : \"all\";\n\n switch (action) {\n case \"dex.swap\":\n return {\n action: \"dex.swap\",\n params: {\n protocol: { type: \"string\", required: true, description: \"Protocol slug (e.g. hyperswap-v3)\" },\n token_in: { type: \"string\", required: true, description: \"Input token symbol or address\" },\n token_out: { type: \"string\", required: true, description: \"Output token symbol or address\" },\n amount: { type: \"string\", required: true, description: \"Amount (human-readable, e.g. '1.5')\" },\n slippage_bps: { type: \"number\", required: false, default: 50, description: \"Slippage in basis points\" },\n recipient: { type: \"string\", required: false, description: \"Recipient address\" },\n },\n };\n\n case \"dex.quote\":\n return {\n action: \"dex.quote\",\n params: {\n protocol: { type: \"string\", required: true, description: \"Protocol slug\" },\n token_in: { type: \"string\", required: true, description: \"Input token symbol or address\" },\n token_out: { type: \"string\", required: true, description: \"Output token symbol or address\" },\n amount: { type: \"string\", required: true, description: \"Amount (human-readable)\" },\n },\n };\n\n case \"lending.supply\":\n case \"lending.borrow\":\n case \"lending.repay\":\n case \"lending.withdraw\":\n return {\n action,\n params: {\n protocol: { type: \"string\", required: true, description: \"Protocol slug\" },\n asset: { type: \"string\", required: true, description: \"Token symbol or address\" },\n amount: { type: \"string\", required: true, description: \"Amount (human-readable)\" },\n },\n };\n\n case \"staking.stake\":\n case \"staking.unstake\":\n return {\n action,\n params: {\n protocol: { type: \"string\", required: true, description: \"Protocol slug\" },\n amount: { type: \"string\", required: true, description: \"Amount (human-readable)\" },\n },\n };\n\n case \"vault.deposit\":\n case \"vault.withdraw\":\n return {\n action,\n params: {\n protocol: { type: \"string\", required: true, description: \"Protocol slug\" },\n amount: { type: \"string\", required: true, description: \"Amount (human-readable)\" },\n },\n };\n\n case \"cdp.open\":\n return {\n action: \"cdp.open\",\n params: {\n protocol: { type: \"string\", required: true, description: \"Protocol slug\" },\n collateral: { type: \"string\", required: true, description: \"Collateral token symbol or address\" },\n collateral_amount: { type: \"string\", required: true, description: \"Collateral amount (human-readable)\" },\n debt_amount: { type: \"string\", required: true, description: \"Debt amount (human-readable)\" },\n },\n };\n\n case \"status\":\n return { action: \"status\", params: {} };\n\n case \"list_protocols\":\n return {\n action: \"list_protocols\",\n params: {\n category: { type: \"string\", required: false, description: \"Filter by category (e.g. dex, lending, vault)\" },\n },\n };\n\n default:\n return {\n actions: [\n \"status\", \"list_protocols\", \"schema\",\n \"dex.swap\", \"dex.quote\",\n \"lending.supply\", \"lending.borrow\", \"lending.repay\", \"lending.withdraw\",\n \"staking.stake\", \"staking.unstake\",\n \"vault.deposit\", \"vault.withdraw\",\n \"cdp.open\",\n ],\n };\n }\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { handleSchema } from \"../agent.js\";\n\nexport function registerSchema(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"schema [command]\")\n .description(\"Output JSON schema for a command (agent-friendly)\")\n .option(\"--all\", \"Show all schemas\")\n .action(async (command: string | undefined, opts: { all?: boolean }) => {\n const mode = getOpts();\n const action = opts.all ? \"all\" : (command ?? \"all\");\n const params: Record<string, unknown> = { action };\n const schema = handleSchema(params);\n printOutput(schema, mode);\n });\n}\n","import { DefiError } from \"@hypurrquant/defi-core\";\nimport type { ProtocolEntry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\n\n// DEX adapters\nimport { UniswapV3Adapter } from \"./dex/uniswap_v3.js\";\nimport { UniswapV2Adapter } from \"./dex/uniswap_v2.js\";\nimport { AlgebraV3Adapter } from \"./dex/algebra_v3.js\";\nimport { BalancerV3Adapter } from \"./dex/balancer_v3.js\";\nimport { CurveStableSwapAdapter } from \"./dex/curve.js\";\nimport { SolidlyAdapter } from \"./dex/solidly.js\";\nimport { ThenaCLAdapter } from \"./dex/thena_cl.js\";\nimport { HybraGaugeAdapter } from \"./dex/hybra_gauge.js\";\nimport { WooFiAdapter } from \"./dex/woofi.js\";\nimport { SolidlyGaugeAdapter } from \"./dex/solidly_gauge.js\";\nimport { MasterChefAdapter } from \"./dex/masterchef.js\";\nimport { MerchantMoeLBAdapter } from \"./dex/merchant_moe_lb.js\";\nimport { KittenSwapFarmingAdapter } from \"./dex/kittenswap_farming.js\";\n\n// Trait interfaces\nimport type { IDex } from \"@hypurrquant/defi-core\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport type { ICdp } from \"@hypurrquant/defi-core\";\nimport type { IVault } from \"@hypurrquant/defi-core\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport type { IGaugeSystem } from \"@hypurrquant/defi-core\";\nimport type { IGauge } from \"@hypurrquant/defi-core\";\nimport type { IYieldSource } from \"@hypurrquant/defi-core\";\nimport type { IDerivatives } from \"@hypurrquant/defi-core\";\nimport type { IOptions } from \"@hypurrquant/defi-core\";\nimport type { IOracle } from \"@hypurrquant/defi-core\";\nimport type { INft } from \"@hypurrquant/defi-core\";\n\n// Lending adapters\nimport { AaveV3Adapter } from \"./lending/aave_v3.js\";\nimport { AaveV2Adapter } from \"./lending/aave_v2.js\";\nimport { AaveOracleAdapter } from \"./lending/aave_oracle.js\";\nimport { CompoundV2Adapter } from \"./lending/compound_v2.js\";\nimport { CompoundV3Adapter } from \"./lending/compound_v3.js\";\nimport { EulerV2Adapter } from \"./lending/euler_v2.js\";\nimport { MorphoBlueAdapter } from \"./lending/morpho.js\";\n\n// CDP adapters\nimport { FelixCdpAdapter } from \"./cdp/felix.js\";\nimport { FelixOracleAdapter } from \"./cdp/felix_oracle.js\";\n\n// Vault adapters\nimport { ERC4626VaultAdapter } from \"./vault/erc4626.js\";\n\n// Liquid staking adapters\nimport { GenericLstAdapter } from \"./liquid_staking/generic_lst.js\";\nimport { StHypeAdapter } from \"./liquid_staking/sthype.js\";\nimport { KinetiqAdapter } from \"./liquid_staking/kinetiq.js\";\n\n// Yield source adapters\nimport { PendleAdapter } from \"./yield_source/pendle.js\";\nimport { GenericYieldAdapter } from \"./yield_source/generic_yield.js\";\n\n// Derivatives adapters\nimport { HlpVaultAdapter } from \"./derivatives/hlp.js\";\nimport { GenericDerivativesAdapter } from \"./derivatives/generic_derivatives.js\";\n\n// Options adapters\nimport { RyskAdapter } from \"./options/rysk.js\";\nimport { GenericOptionsAdapter } from \"./options/generic_options.js\";\n\n// NFT adapters\nimport { ERC721Adapter } from \"./nft/erc721.js\";\n\n// ============================================================\n// DEX\n// ============================================================\n\n/** Create a Dex implementation from a protocol registry entry */\nexport function createDex(entry: ProtocolEntry, rpcUrl?: string): IDex {\n switch (entry.interface) {\n case \"uniswap_v3\":\n return new UniswapV3Adapter(entry, rpcUrl);\n case \"uniswap_v4\":\n throw DefiError.unsupported(\n `[${entry.name}] Uniswap V4 (singleton PoolManager) is not yet supported — use HyperSwap V3 or another V3-compatible DEX for quotes`,\n );\n case \"algebra_v3\":\n return new AlgebraV3Adapter(entry, rpcUrl);\n case \"uniswap_v2\":\n return new UniswapV2Adapter(entry, rpcUrl);\n case \"solidly_v2\":\n case \"solidly_cl\":\n return new SolidlyAdapter(entry, rpcUrl);\n case \"hybra\":\n return new ThenaCLAdapter(entry, rpcUrl);\n case \"curve_stableswap\":\n return new CurveStableSwapAdapter(entry);\n case \"balancer_v3\":\n return new BalancerV3Adapter(entry);\n case \"woofi\":\n return new WooFiAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`DEX interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// Lending\n// ============================================================\n\n/** Create a Lending implementation from a protocol registry entry */\nexport function createLending(entry: ProtocolEntry, rpcUrl?: string): ILending {\n switch (entry.interface) {\n case \"aave_v3\":\n case \"aave_v3_isolated\":\n return new AaveV3Adapter(entry, rpcUrl);\n case \"aave_v2\":\n return new AaveV2Adapter(entry, rpcUrl);\n case \"morpho_blue\":\n return new MorphoBlueAdapter(entry, rpcUrl);\n case \"euler_v2\":\n return new EulerV2Adapter(entry, rpcUrl);\n case \"compound_v2\":\n return new CompoundV2Adapter(entry, rpcUrl);\n case \"compound_v3\":\n return new CompoundV3Adapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Lending interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// CDP\n// ============================================================\n\n/** Create a CDP implementation from a protocol registry entry */\nexport function createCdp(entry: ProtocolEntry, rpcUrl?: string): ICdp {\n switch (entry.interface) {\n case \"liquity_v2\":\n return new FelixCdpAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`CDP interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// Vault\n// ============================================================\n\n/** Create a Vault implementation from a protocol registry entry */\nexport function createVault(entry: ProtocolEntry, rpcUrl?: string): IVault {\n switch (entry.interface) {\n case \"erc4626\":\n case \"beefy_vault\":\n return new ERC4626VaultAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Vault interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// Liquid Staking\n// ============================================================\n\n/** Create a LiquidStaking implementation from a protocol registry entry */\nexport function createLiquidStaking(entry: ProtocolEntry, rpcUrl?: string): ILiquidStaking {\n switch (entry.interface) {\n case \"kinetiq_staking\":\n return new KinetiqAdapter(entry, rpcUrl);\n case \"sthype_staking\":\n return new StHypeAdapter(entry, rpcUrl);\n case \"hyperbeat_lst\":\n case \"kintsu\":\n return new GenericLstAdapter(entry, rpcUrl);\n default:\n return new GenericLstAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// Gauge\n// ============================================================\n\n/** Create a GaugeSystem implementation from a protocol registry entry */\nexport function createGauge(entry: ProtocolEntry, rpcUrl?: string): IGaugeSystem {\n // Hybra has its own GaugeManager system\n if (entry.interface === \"hybra\" || entry.contracts?.[\"gauge_manager\"]) {\n return new HybraGaugeAdapter(entry, rpcUrl);\n }\n switch (entry.interface) {\n case \"solidly_v2\":\n case \"solidly_cl\":\n case \"algebra_v3\":\n return new SolidlyGaugeAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Gauge interface '${entry.interface}' not supported`);\n }\n}\n\n/** Create a MasterChef IGauge implementation from a protocol registry entry */\nexport function createMasterChef(entry: ProtocolEntry, rpcUrl?: string): IGauge {\n return new MasterChefAdapter(entry, rpcUrl);\n}\n\n// ============================================================\n// Yield Source (fallback to GenericYield)\n// ============================================================\n\n/** Create a YieldSource implementation — falls back to GenericYield for unknown interfaces */\nexport function createYieldSource(entry: ProtocolEntry, rpcUrl?: string): IYieldSource {\n switch (entry.interface) {\n case \"pendle_v2\":\n return new PendleAdapter(entry, rpcUrl);\n default:\n return new GenericYieldAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// Derivatives (fallback to GenericDerivatives)\n// ============================================================\n\n/** Create a Derivatives implementation — falls back to GenericDerivatives for unknown interfaces */\nexport function createDerivatives(entry: ProtocolEntry, rpcUrl?: string): IDerivatives {\n switch (entry.interface) {\n case \"hlp_vault\":\n return new HlpVaultAdapter(entry, rpcUrl);\n default:\n return new GenericDerivativesAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// Options (fallback to GenericOptions)\n// ============================================================\n\n/** Create an Options implementation — falls back to GenericOptions for unknown interfaces */\nexport function createOptions(entry: ProtocolEntry, rpcUrl?: string): IOptions {\n switch (entry.interface) {\n case \"rysk\":\n return new RyskAdapter(entry, rpcUrl);\n default:\n return new GenericOptionsAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// NFT\n// ============================================================\n\n/** Create an NFT implementation from a protocol registry entry */\nexport function createNft(entry: ProtocolEntry, rpcUrl?: string): INft {\n switch (entry.interface) {\n case \"erc721\":\n return new ERC721Adapter(entry, rpcUrl);\n case \"marketplace\":\n throw DefiError.unsupported(`NFT marketplace '${entry.name}' is not queryable as ERC-721. Use a specific collection address.`);\n default:\n throw DefiError.unsupported(`NFT interface '${entry.interface}' not supported`);\n }\n}\n\n// ============================================================\n// Oracle from Lending\n// ============================================================\n\n/** Create an Oracle from a lending protocol entry (Aave V3 forks have an oracle contract) */\nexport function createOracleFromLending(entry: ProtocolEntry, rpcUrl: string): IOracle {\n switch (entry.interface) {\n case \"aave_v3\":\n case \"aave_v3_isolated\":\n return new AaveOracleAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Oracle not available for lending interface '${entry.interface}'`);\n }\n}\n\n// ============================================================\n// Oracle from CDP\n// ============================================================\n\n/** Create an Oracle from a CDP protocol entry (Felix has its own PriceFeed contract) */\nexport function createOracleFromCdp(entry: ProtocolEntry, _asset: Address, rpcUrl: string): IOracle {\n switch (entry.interface) {\n case \"liquity_v2\":\n return new FelixOracleAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Oracle not available for CDP interface '${entry.interface}'`);\n }\n}\n\n// ============================================================\n// Merchant Moe LB\n// ============================================================\n\n/** Create a MerchantMoeLBAdapter for Liquidity Book operations */\nexport function createMerchantMoeLB(entry: ProtocolEntry, rpcUrl?: string): MerchantMoeLBAdapter {\n return new MerchantMoeLBAdapter(entry, rpcUrl);\n}\n\n// ============================================================\n// KittenSwap Algebra Farming\n// ============================================================\n\n/** Create a KittenSwapFarmingAdapter for Algebra eternal farming operations */\nexport function createKittenSwapFarming(entry: ProtocolEntry, rpcUrl: string): KittenSwapFarmingAdapter {\n const farmingCenter = entry.contracts?.[\"farming_center\"];\n if (!farmingCenter) {\n throw new DefiError(\"CONTRACT_ERROR\", `[${entry.name}] Missing 'farming_center' contract address`);\n }\n const eternalFarming = entry.contracts?.[\"eternal_farming\"];\n if (!eternalFarming) {\n throw new DefiError(\"CONTRACT_ERROR\", `[${entry.name}] Missing 'eternal_farming' contract address`);\n }\n const positionManager = entry.contracts?.[\"position_manager\"];\n if (!positionManager) {\n throw new DefiError(\"CONTRACT_ERROR\", `[${entry.name}] Missing 'position_manager' contract address`);\n }\n const factory = entry.contracts?.[\"factory\"] as Address | undefined;\n return new KittenSwapFarmingAdapter(entry.name, farmingCenter, eternalFarming, positionManager, rpcUrl, factory);\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst DEFAULT_FEE = 3000;\n\nconst swapRouterAbi = parseAbi([\n \"struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; }\",\n \"function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut)\",\n]);\n\nconst quoterAbi = parseAbi([\n \"struct QuoteExactInputSingleParams { address tokenIn; address tokenOut; uint256 amountIn; uint24 fee; uint160 sqrtPriceLimitX96; }\",\n \"function quoteExactInputSingle(QuoteExactInputSingleParams memory params) external returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\",\n]);\n\n// Ramses CL uses tickSpacing instead of fee in the quoter struct\nconst ramsesQuoterAbi = parseAbi([\n \"struct QuoteExactInputSingleParams { address tokenIn; address tokenOut; uint256 amountIn; int24 tickSpacing; uint160 sqrtPriceLimitX96; }\",\n \"function quoteExactInputSingle(QuoteExactInputSingleParams memory params) external returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\",\n]);\n\nconst positionManagerAbi = parseAbi([\n \"struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; }\",\n \"function mint(MintParams calldata params) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)\",\n]);\n\nexport class UniswapV3Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly quoter: Address | undefined;\n private readonly positionManager: Address | undefined;\n private readonly factory: Address | undefined;\n private readonly fee: number;\n private readonly rpcUrl: string | undefined;\n private readonly useTickSpacingQuoter: boolean;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.quoter = entry.contracts?.[\"quoter\"];\n this.positionManager = entry.contracts?.[\"position_manager\"];\n this.factory = entry.contracts?.[\"factory\"];\n this.fee = DEFAULT_FEE;\n this.rpcUrl = rpcUrl;\n // Ramses CL and similar forks use tickSpacing-based pool identification\n this.useTickSpacingQuoter = entry.contracts?.[\"pool_deployer\"] !== undefined\n || entry.contracts?.[\"gauge_factory\"] !== undefined;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n const amountOutMinimum = 0n;\n\n const data = encodeFunctionData({\n abi: swapRouterAbi,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n fee: this.fee,\n recipient: params.recipient,\n deadline,\n amountIn: params.amount_in,\n amountOutMinimum,\n sqrtPriceLimitX96: 0n,\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokenIn for tokenOut`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 200_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured\");\n }\n\n if (this.quoter) {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // Try tickSpacing-based quoter first for Ramses CL and similar forks\n if (this.useTickSpacingQuoter) {\n const tickSpacings = [1, 10, 50, 100, 200];\n const tsResults = await Promise.allSettled(\n tickSpacings.map(async (ts) => {\n const result = await client.call({\n to: this.quoter!,\n data: encodeFunctionData({\n abi: ramsesQuoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n amountIn: params.amount_in,\n tickSpacing: ts,\n sqrtPriceLimitX96: 0n,\n },\n ],\n }),\n });\n if (!result.data) return { amountOut: 0n, tickSpacing: ts };\n const [amountOut] = decodeAbiParameters(\n [{ name: \"amountOut\", type: \"uint256\" }],\n result.data,\n );\n return { amountOut, tickSpacing: ts };\n }),\n );\n\n let best = { amountOut: 0n, tickSpacing: 50 };\n for (const r of tsResults) {\n if (r.status === \"fulfilled\" && r.value.amountOut > best.amountOut) {\n best = r.value;\n }\n }\n\n if (best.amountOut > 0n) {\n return {\n protocol: this.protocolName,\n amount_out: best.amountOut,\n price_impact_bps: undefined,\n fee_bps: undefined,\n route: [`${params.token_in} -> ${params.token_out} (tickSpacing: ${best.tickSpacing})`],\n };\n }\n\n // tickSpacing-based protocol (Ramses CL): quoter returned no result.\n // Pool exists but has no liquidity in this fork snapshot.\n throw DefiError.rpcError(\n `[${this.protocolName}] No quote available — pool exists but has zero liquidity for this pair`,\n );\n }\n\n // Standard Uniswap V3 fee-based quoter\n const feeTiers = [500, 3000, 10000, 100];\n const results = await Promise.allSettled(\n feeTiers.map(async (fee) => {\n const result = await client.call({\n to: this.quoter!,\n data: encodeFunctionData({\n abi: quoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n amountIn: params.amount_in,\n fee,\n sqrtPriceLimitX96: 0n,\n },\n ],\n }),\n });\n if (!result.data) return { amountOut: 0n, fee };\n const [amountOut] = decodeAbiParameters(\n [{ name: \"amountOut\", type: \"uint256\" }],\n result.data,\n );\n return { amountOut, fee };\n }),\n );\n\n let best = { amountOut: 0n, fee: 3000 };\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value.amountOut > best.amountOut) {\n best = r.value;\n }\n }\n\n if (best.amountOut > 0n) {\n return {\n protocol: this.protocolName,\n amount_out: best.amountOut,\n price_impact_bps: undefined,\n fee_bps: Math.floor(best.fee / 10),\n route: [`${params.token_in} -> ${params.token_out} (fee: ${best.fee})`],\n };\n }\n }\n\n // Fallback: simulate swap via eth_call on the router\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const callData = encodeFunctionData({\n abi: swapRouterAbi,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n fee: this.fee,\n recipient: \"0x0000000000000000000000000000000000000001\",\n deadline: BigInt(\"18446744073709551615\"),\n amountIn: params.amount_in,\n amountOutMinimum: 0n,\n sqrtPriceLimitX96: 0n,\n },\n ],\n });\n\n let output: `0x${string}` | undefined;\n try {\n const result = await client.call({ to: this.router, data: callData });\n output = result.data;\n } catch (e: unknown) {\n const errMsg = String(e);\n if (errMsg.includes(\"STF\") || errMsg.includes(\"insufficient\")) {\n throw DefiError.unsupported(\n `[${this.protocolName}] quote unavailable — no quoter contract configured. Swap simulation requires token balance. Add a quoter address to the protocol config.`,\n );\n }\n throw DefiError.rpcError(`[${this.protocolName}] swap simulation for quote failed: ${errMsg}`);\n }\n\n const amountOut =\n output && output.length >= 66\n ? BigInt(output.slice(0, 66))\n : 0n;\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut,\n price_impact_bps: undefined,\n fee_bps: Math.floor(this.fee / 10),\n route: [`${params.token_in} -> ${params.token_out} (simulated)`],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const pm = this.positionManager;\n if (!pm) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Position manager address not configured\");\n }\n\n // Sort tokens (Uniswap V3 requires token0 < token1)\n const [token0, token1, rawAmount0, rawAmount1] =\n params.token_a.toLowerCase() < params.token_b.toLowerCase()\n ? [params.token_a, params.token_b, params.amount_a, params.amount_b]\n : [params.token_b, params.token_a, params.amount_b, params.amount_a];\n\n // V3 NPM mint: getLiquidityForAmounts uses min(L0, L1), so if either is 0\n // then liquidity=0 → revert. Use 1 wei minimum for single-side LP.\n const amount0 = rawAmount0 === 0n && rawAmount1 > 0n ? 1n : rawAmount0;\n const amount1 = rawAmount1 === 0n && rawAmount0 > 0n ? 1n : rawAmount1;\n\n const data = encodeFunctionData({\n abi: positionManagerAbi,\n functionName: \"mint\",\n args: [\n {\n token0,\n token1,\n fee: this.fee,\n tickLower: -887220,\n tickUpper: 887220,\n amount0Desired: amount0,\n amount1Desired: amount1,\n amount0Min: 0n,\n amount1Min: 0n,\n recipient: params.recipient,\n deadline: BigInt(\"18446744073709551615\"),\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity`,\n to: pm,\n data,\n value: 0n,\n gas_estimate: 500_000,\n approvals: [\n { token: token0, spender: pm, amount: amount0 },\n { token: token1, spender: pm, amount: amount1 },\n ],\n };\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] remove_liquidity requires tokenId — use NFT position manager directly`,\n );\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeFunctionResult, decodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts)\",\n \"function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB, uint256 liquidity)\",\n \"function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB)\",\n \"function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts)\",\n]);\n\nconst lbQuoterAbi = parseAbi([\n \"function findBestPathFromAmountIn(address[] calldata route, uint128 amountIn) external view returns ((address[] route, address[] pairs, uint256[] binSteps, uint256[] versions, uint128[] amounts, uint128[] virtualAmountsWithoutSlippage, uint128[] fees))\",\n]);\n\nexport class UniswapV2Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly rpcUrl: string | undefined;\n private readonly lbQuoter: Address | undefined;\n private readonly lbIntermediaries: Address[];\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.lbQuoter = entry.contracts?.[\"lb_quoter\"];\n this.rpcUrl = rpcUrl;\n\n // Collect LB intermediary tokens from contracts with \"lb_mid_\" prefix\n this.lbIntermediaries = [];\n if (entry.contracts) {\n for (const [key, addr] of Object.entries(entry.contracts)) {\n if (key.startsWith(\"lb_mid_\")) {\n this.lbIntermediaries.push(addr);\n }\n }\n }\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const amountOutMin = 0n;\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n const path: Address[] = [params.token_in, params.token_out];\n\n const data = encodeFunctionData({\n abi,\n functionName: \"swapExactTokensForTokens\",\n args: [params.amount_in, amountOutMin, path, params.recipient, deadline],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokens via V2`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 150_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured\");\n }\n\n // Try LB (Liquidity Book) quote first if lb_quoter is configured\n if (this.lbQuoter) {\n try {\n return await this.lbQuote(params);\n } catch {\n // Fall through to V2 quote\n }\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const path: Address[] = [params.token_in, params.token_out];\n\n const result = await client.call({\n to: this.router,\n data: encodeFunctionData({\n abi,\n functionName: \"getAmountsOut\",\n args: [params.amount_in, path],\n }),\n });\n\n if (!result.data) {\n throw DefiError.rpcError(`[${this.protocolName}] getAmountsOut returned no data`);\n }\n\n const decoded = decodeFunctionResult({\n abi,\n functionName: \"getAmountsOut\",\n data: result.data,\n }) as unknown as bigint[];\n\n const amountOut = decoded[decoded.length - 1];\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut,\n price_impact_bps: undefined,\n fee_bps: 30,\n route: [`${params.token_in} -> ${params.token_out}`],\n };\n }\n\n private async lbQuote(params: QuoteParams): Promise<QuoteResult> {\n const client = createPublicClient({ transport: http(this.rpcUrl!) });\n\n // Build candidate routes: direct + multi-hop through each intermediary\n const routes: Address[][] = [[params.token_in, params.token_out]];\n const tokenInLower = params.token_in.toLowerCase();\n const tokenOutLower = params.token_out.toLowerCase();\n for (const mid of this.lbIntermediaries) {\n if (mid.toLowerCase() !== tokenInLower && mid.toLowerCase() !== tokenOutLower) {\n routes.push([params.token_in, mid, params.token_out]);\n }\n }\n\n const lbResultParams = [\n {\n type: \"tuple\" as const,\n components: [\n { name: \"route\", type: \"address[]\" as const },\n { name: \"pairs\", type: \"address[]\" as const },\n { name: \"binSteps\", type: \"uint256[]\" as const },\n { name: \"versions\", type: \"uint256[]\" as const },\n { name: \"amounts\", type: \"uint128[]\" as const },\n { name: \"virtualAmountsWithoutSlippage\", type: \"uint128[]\" as const },\n { name: \"fees\", type: \"uint128[]\" as const },\n ],\n },\n ] as const;\n\n let bestOut = 0n;\n let bestRoute: Address[] = [];\n\n const results = await Promise.allSettled(\n routes.map(async (route) => {\n const result = await client.call({\n to: this.lbQuoter!,\n data: encodeFunctionData({\n abi: lbQuoterAbi,\n functionName: \"findBestPathFromAmountIn\",\n args: [route, params.amount_in],\n }),\n });\n if (!result.data) return { amountOut: 0n, route };\n const [quote] = decodeAbiParameters(lbResultParams, result.data);\n const amounts = quote.amounts;\n return { amountOut: amounts[amounts.length - 1], route };\n }),\n );\n\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value.amountOut > bestOut) {\n bestOut = r.value.amountOut;\n bestRoute = r.value.route;\n }\n }\n\n if (bestOut === 0n) {\n throw DefiError.rpcError(`[${this.protocolName}] LB quote returned zero for all routes`);\n }\n\n return {\n protocol: this.protocolName,\n amount_out: bestOut,\n price_impact_bps: undefined,\n fee_bps: undefined,\n route: [bestRoute.map((a) => a.slice(0, 10)).join(\" -> \") + \" (LB)\"],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"addLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n params.amount_a,\n params.amount_b,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity V2`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [\n { token: params.token_a, spender: this.router, amount: params.amount_a },\n { token: params.token_b, spender: this.router, amount: params.amount_b },\n ],\n };\n }\n\n async buildRemoveLiquidity(params: RemoveLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"removeLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n params.liquidity,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Remove liquidity V2`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeAbiParameters, concatHex, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport { rangeToTicks, alignTickUp, alignTickDown } from \"./tick_math.js\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"struct ExactInputSingleParams { address tokenIn; address tokenOut; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 limitSqrtPrice; }\",\n \"function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut)\",\n]);\n\n// Algebra Integral quoter: path = tokenIn(20) + deployer(20) + tokenOut(20) per hop\n// Returns arrays for multi-hop results\nconst algebraQuoterAbi = parseAbi([\n \"function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256[] memory amountOutList, uint256[] memory amountInList, uint160[] memory sqrtPriceX96AfterList, uint32[] memory initializedTicksCrossedList, uint256 gasEstimate, uint16[] memory feeList)\",\n]);\n\n// Algebra V2 / NEST-style quoter: single-hop struct\n// selector: 0x5e5e6e0f quoteExactInputSingle((address,address,uint256,uint160))\n// returns: (uint256 amountOut, uint256 amountIn, uint160 sqrtPriceX96After)\nconst algebraSingleQuoterAbi = parseAbi([\n \"function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint160 limitSqrtPrice) params) external returns (uint256 amountOut, uint256 amountIn, uint160 sqrtPriceX96After)\",\n]);\n\n// Algebra Integral NonfungiblePositionManager (includes deployer field for pool identification)\nconst algebraIntegralPmAbi = parseAbi([\n \"struct MintParams { address token0; address token1; address deployer; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; }\",\n \"function mint(MintParams calldata params) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)\",\n]);\n\n// Algebra V2 / NEST-style NonfungiblePositionManager (no deployer field)\nconst algebraV2PmAbi = parseAbi([\n \"struct MintParams { address token0; address token1; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; }\",\n \"function mint(MintParams calldata params) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)\",\n]);\n\nexport class AlgebraV3Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly quoter: Address | undefined;\n private readonly positionManager: Address | undefined;\n private readonly rpcUrl: string | undefined;\n // NEST and similar forks expose quoteExactInputSingle((address,address,uint256,uint160))\n // instead of path-based quoteExactInput. Detected by presence of pool_deployer in config.\n private readonly useSingleQuoter: boolean;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.quoter = entry.contracts?.[\"quoter\"];\n this.positionManager = entry.contracts?.[\"position_manager\"];\n this.rpcUrl = rpcUrl;\n // pool_deployer present → NEST-style single-hop struct quoter\n this.useSingleQuoter = entry.contracts?.[\"pool_deployer\"] !== undefined;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n const amountOutMinimum = 0n;\n\n const data = encodeFunctionData({\n abi,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n recipient: params.recipient,\n deadline,\n amountIn: params.amount_in,\n amountOutMinimum,\n limitSqrtPrice: 0n,\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokenIn for tokenOut`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 250_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured\");\n }\n if (!this.quoter) {\n throw DefiError.unsupported(\n `[${this.protocolName}] No quoter contract configured`,\n );\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // NEST and similar forks: use single-hop struct quoter\n if (this.useSingleQuoter) {\n const result = await client.call({\n to: this.quoter,\n data: encodeFunctionData({\n abi: algebraSingleQuoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n amountIn: params.amount_in,\n limitSqrtPrice: 0n,\n },\n ],\n }),\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] quoteExactInputSingle failed: ${e}`);\n });\n\n if (!result.data || result.data.length < 66) {\n throw DefiError.rpcError(`[${this.protocolName}] quoter returned empty data`);\n }\n\n const [amountOut] = decodeAbiParameters(\n [\n { name: \"amountOut\", type: \"uint256\" },\n { name: \"amountIn\", type: \"uint256\" },\n { name: \"sqrtPriceX96After\", type: \"uint160\" },\n ],\n result.data,\n );\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut as bigint,\n price_impact_bps: undefined,\n fee_bps: undefined,\n route: [`${params.token_in} -> ${params.token_out}`],\n };\n }\n\n // KittenSwap and standard Algebra Integral path: tokenIn(20) + deployer(20) + tokenOut(20) = 60 bytes\n // Standard pools use deployer=address(0) in path (CREATE2 salt without deployer prefix)\n const path = concatHex([params.token_in, zeroAddress as Address, params.token_out]);\n\n const result = await client.call({\n to: this.quoter,\n data: encodeFunctionData({\n abi: algebraQuoterAbi,\n functionName: \"quoteExactInput\",\n args: [path, params.amount_in],\n }),\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] quoteExactInput failed: ${e}`);\n });\n\n if (!result.data || result.data.length < 66) {\n throw DefiError.rpcError(`[${this.protocolName}] quoter returned empty data`);\n }\n\n // Decode first element: amountOutList is an array, take the last element\n const decoded = decodeAbiParameters(\n [\n { name: \"amountOutList\", type: \"uint256[]\" },\n { name: \"amountInList\", type: \"uint256[]\" },\n { name: \"sqrtPriceX96AfterList\", type: \"uint160[]\" },\n { name: \"initializedTicksCrossedList\", type: \"uint32[]\" },\n { name: \"gasEstimate\", type: \"uint256\" },\n { name: \"feeList\", type: \"uint16[]\" },\n ],\n result.data,\n );\n\n const amountOutList = decoded[0] as readonly bigint[];\n const feeList = decoded[5] as readonly number[];\n const amountOut = amountOutList[amountOutList.length - 1];\n const fee = feeList.length > 0 ? feeList[0] : undefined;\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut,\n price_impact_bps: undefined,\n fee_bps: fee !== undefined ? Math.floor(fee / 10) : undefined,\n route: [`${params.token_in} -> ${params.token_out}`],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const pm = this.positionManager;\n if (!pm) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Position manager address not configured\");\n }\n\n // Sort tokens (Algebra requires token0 < token1)\n const [token0, token1, rawAmount0, rawAmount1] =\n params.token_a.toLowerCase() < params.token_b.toLowerCase()\n ? [params.token_a, params.token_b, params.amount_a, params.amount_b]\n : [params.token_b, params.token_a, params.amount_b, params.amount_a];\n\n let tickLower = params.tick_lower ?? -887220;\n let tickUpper = params.tick_upper ?? 887220;\n\n // Auto tick detection: --range N% or single-side\n const isSingleSide = rawAmount0 === 0n || rawAmount1 === 0n;\n const needsAutoTick = (params.range_pct !== undefined) || (isSingleSide && !params.tick_lower && !params.tick_upper);\n\n if (needsAutoTick) {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required for auto tick detection\");\n const poolAddr = params.pool as Address | undefined;\n if (!poolAddr) throw new DefiError(\"CONTRACT_ERROR\", \"Pool address required (use --pool)\");\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const algebraPoolAbi = parseAbi([\n \"function globalState() view returns (uint160 price, int24 tick, uint16 lastFee, uint8 pluginConfig, uint16 communityFee, bool unlocked)\",\n \"function tickSpacing() view returns (int24)\",\n ]);\n const [globalState, spacing] = await Promise.all([\n client.readContract({ address: poolAddr, abi: algebraPoolAbi, functionName: \"globalState\" }),\n client.readContract({ address: poolAddr, abi: algebraPoolAbi, functionName: \"tickSpacing\" }),\n ]);\n const currentTick = Number(globalState[1]);\n const tickSpace = Number(spacing);\n\n if (params.range_pct !== undefined) {\n // ±N% concentrated range\n const range = rangeToTicks(currentTick, params.range_pct, tickSpace);\n tickLower = range.tickLower;\n tickUpper = range.tickUpper;\n } else if (rawAmount0 > 0n && rawAmount1 === 0n) {\n tickLower = alignTickUp(currentTick + tickSpace, tickSpace);\n tickUpper = 887220;\n } else {\n tickLower = -887220;\n tickUpper = alignTickDown(currentTick - tickSpace, tickSpace);\n }\n }\n\n const amount0 = rawAmount0;\n const amount1 = rawAmount1;\n\n // Algebra V2 (NEST-style, has pool_deployer) uses no deployer field in MintParams\n // Algebra Integral (KittenSwap) includes deployer field\n const data = this.useSingleQuoter\n ? encodeFunctionData({\n abi: algebraV2PmAbi,\n functionName: \"mint\",\n args: [{ token0, token1, tickLower, tickUpper, amount0Desired: amount0, amount1Desired: amount1, amount0Min: 0n, amount1Min: 0n, recipient: params.recipient, deadline: BigInt(\"18446744073709551615\") }],\n })\n : encodeFunctionData({\n abi: algebraIntegralPmAbi,\n functionName: \"mint\",\n args: [{ token0, token1, deployer: zeroAddress as Address, tickLower, tickUpper, amount0Desired: amount0, amount1Desired: amount1, amount0Min: 0n, amount1Min: 0n, recipient: params.recipient, deadline: BigInt(\"18446744073709551615\") }],\n });\n\n // Only add approvals for non-zero amounts\n const approvals: { token: Address; spender: Address; amount: bigint }[] = [];\n if (amount0 > 0n) approvals.push({ token: token0, spender: pm, amount: amount0 });\n if (amount1 > 0n) approvals.push({ token: token1, spender: pm, amount: amount1 });\n\n return {\n description: `[${this.protocolName}] Add liquidity [${tickLower}, ${tickUpper}]`,\n to: pm,\n data,\n value: 0n,\n gas_estimate: 500_000,\n approvals,\n };\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] remove_liquidity requires tokenId — use NFT position manager directly`,\n );\n }\n}\n","/**\n * Convert a ±percentage to tick delta.\n * tickDelta = ln(1 + pct/100) / ln(1.0001)\n */\nexport function pctToTickDelta(pct: number): number {\n return Math.round(Math.log(1 + pct / 100) / Math.log(1.0001));\n}\n\n/**\n * Align a tick down to the nearest multiple of tickSpacing.\n */\nexport function alignTickDown(tick: number, tickSpacing: number): number {\n return Math.floor(tick / tickSpacing) * tickSpacing;\n}\n\n/**\n * Align a tick up to the nearest multiple of tickSpacing.\n */\nexport function alignTickUp(tick: number, tickSpacing: number): number {\n return Math.ceil(tick / tickSpacing) * tickSpacing;\n}\n\n/**\n * Calculate ±pct% tick range centered on currentTick, aligned to tickSpacing.\n */\nexport function rangeToTicks(\n currentTick: number,\n rangePct: number,\n tickSpacing: number,\n): { tickLower: number; tickUpper: number } {\n const delta = pctToTickDelta(rangePct);\n return {\n tickLower: alignTickDown(currentTick - delta, tickSpacing),\n tickUpper: alignTickUp(currentTick + delta, tickSpacing),\n };\n}\n","import { encodeFunctionData, parseAbi, zeroAddress } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"function swapSingleTokenExactIn(address pool, address tokenIn, address tokenOut, uint256 exactAmountIn, uint256 minAmountOut, uint256 deadline, bool wethIsEth, bytes calldata userData) external returns (uint256 amountOut)\",\n]);\n\nexport class BalancerV3Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract\");\n }\n this.router = router;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const minAmountOut = 0n;\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n\n // Balancer V3 requires a pool address. For now use a simplified single-pool swap.\n // In production, the pool would be resolved from the registry or an on-chain query.\n const data = encodeFunctionData({\n abi,\n functionName: \"swapSingleTokenExactIn\",\n args: [\n zeroAddress, // TODO: resolve pool from registry\n params.token_in,\n params.token_out,\n params.amount_in,\n minAmountOut,\n deadline,\n false,\n \"0x\",\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} via Balancer V3`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote requires RPC`);\n }\n\n async buildAddLiquidity(_params: AddLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] add_liquidity requires pool-specific params`);\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] remove_liquidity requires pool-specific params`);\n }\n}\n","import { encodeFunctionData, parseAbi } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst poolAbi = parseAbi([\n \"function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256)\",\n \"function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256)\",\n \"function add_liquidity(uint256[2] amounts, uint256 min_mint_amount) external returns (uint256)\",\n \"function remove_liquidity(uint256 amount, uint256[2] min_amounts) external returns (uint256[2])\",\n]);\n\nexport class CurveStableSwapAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n // Direct pool exchange: swap token at index 0 for token at index 1.\n // The `router` address is treated as the pool address for direct swaps.\n // Callers should set the pool address as the \"router\" contract in the registry\n // when targeting a specific Curve pool.\n // Without prior quote, set min output to 0. Use quote() first for slippage protection.\n const minDy = 0n;\n\n const data = encodeFunctionData({\n abi: poolAbi,\n functionName: \"exchange\",\n args: [0n, 1n, params.amount_in, minDy],\n });\n\n return {\n description: `[${this.protocolName}] Curve pool exchange ${params.amount_in} tokens (index 0 -> 1)`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote requires RPC connection`);\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n // Add liquidity to a 2-token Curve pool\n const data = encodeFunctionData({\n abi: poolAbi,\n functionName: \"add_liquidity\",\n args: [[params.amount_a, params.amount_b], 0n],\n });\n\n return {\n description: `[${this.protocolName}] Curve add liquidity`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 400_000,\n };\n }\n\n async buildRemoveLiquidity(params: RemoveLiquidityParams): Promise<DeFiTx> {\n // Remove liquidity from a 2-token Curve pool\n const data = encodeFunctionData({\n abi: poolAbi,\n functionName: \"remove_liquidity\",\n args: [params.liquidity, [0n, 0n]],\n });\n\n return {\n description: `[${this.protocolName}] Curve remove liquidity`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, decodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError, multicallRead } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"struct Route { address from; address to; bool stable; }\",\n \"function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, (address from, address to, bool stable)[] calldata routes, address to, uint256 deadline) external returns (uint256[] memory amounts)\",\n \"function getAmountsOut(uint256 amountIn, (address from, address to, bool stable)[] calldata routes) external view returns (uint256[] memory amounts)\",\n \"function addLiquidity(address tokenA, address tokenB, bool stable, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB, uint256 liquidity)\",\n \"function removeLiquidity(address tokenA, address tokenB, bool stable, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB)\",\n]);\n\n// Velodrome V2 / Aerodrome style: Route includes factory address\nconst abiV2 = parseAbi([\n \"function getAmountsOut(uint256 amountIn, (address from, address to, bool stable, address factory)[] calldata routes) external view returns (uint256[] memory amounts)\",\n]);\n\nexport class SolidlyAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n /** Default to volatile (false). True for stablecoin pairs. */\n private readonly defaultStable: boolean;\n private readonly rpcUrl: string | undefined;\n /** Factory address — present on Velodrome V2 / Aerodrome forks */\n private readonly factory: Address | undefined;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.defaultStable = false;\n this.rpcUrl = rpcUrl;\n this.factory = entry.contracts?.[\"factory\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const amountOutMin = 0n;\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n\n const routes = [\n { from: params.token_in, to: params.token_out, stable: this.defaultStable },\n ];\n\n const data = encodeFunctionData({\n abi,\n functionName: \"swapExactTokensForTokens\",\n args: [params.amount_in, amountOutMin, routes, params.recipient, deadline],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokens via Solidly`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 200_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n private encodeV1(params: QuoteParams, stable: boolean): `0x${string}` {\n return encodeFunctionData({\n abi,\n functionName: \"getAmountsOut\",\n args: [params.amount_in, [{ from: params.token_in, to: params.token_out, stable }]],\n });\n }\n\n private encodeV2(params: QuoteParams, stable: boolean): `0x${string}` {\n return encodeFunctionData({\n abi: abiV2,\n functionName: \"getAmountsOut\",\n args: [params.amount_in, [{ from: params.token_in, to: params.token_out, stable, factory: this.factory! }]],\n });\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n\n // Build all route variant candidates in one multicall batch.\n // Order: V2 variants first (if factory present), then V1 volatile + stable.\n const candidates: Array<{ callData: `0x${string}`; stable: boolean }> = [\n { callData: this.encodeV1(params, false), stable: false },\n { callData: this.encodeV1(params, true), stable: true },\n ];\n if (this.factory) {\n candidates.unshift(\n { callData: this.encodeV2(params, false), stable: false },\n { callData: this.encodeV2(params, true), stable: true },\n );\n }\n\n const rawResults = await multicallRead(\n this.rpcUrl,\n candidates.map((c) => [this.router, c.callData]),\n );\n\n let bestOut = 0n;\n let bestStable = false;\n for (let i = 0; i < rawResults.length; i++) {\n const raw = rawResults[i];\n if (!raw) continue;\n try {\n const [amounts] = decodeAbiParameters(\n [{ name: \"amounts\", type: \"uint256[]\" }],\n raw,\n );\n const out = amounts.length >= 2 ? amounts[amounts.length - 1] : 0n;\n if (out > bestOut) {\n bestOut = out;\n bestStable = candidates[i].stable;\n }\n } catch {\n // Route failed — skip\n }\n }\n\n if (bestOut === 0n) {\n throw DefiError.rpcError(`[${this.protocolName}] getAmountsOut returned zero for all routes`);\n }\n\n return {\n protocol: this.protocolName,\n amount_out: bestOut,\n price_impact_bps: undefined,\n fee_bps: bestStable ? 4 : 20,\n route: [`${params.token_in} -> ${params.token_out} (stable: ${bestStable})`],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"addLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n this.defaultStable,\n params.amount_a,\n params.amount_b,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity (Solidly)`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 350_000,\n approvals: [\n { token: params.token_a, spender: this.router, amount: params.amount_a },\n { token: params.token_b, spender: this.router, amount: params.amount_b },\n ],\n };\n }\n\n async buildRemoveLiquidity(params: RemoveLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"removeLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n this.defaultStable,\n params.liquidity,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Remove liquidity (Solidly)`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport { rangeToTicks, alignTickUp, alignTickDown } from \"./tick_math.js\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\n// Thena V3 CL NonfungiblePositionManager (includes tickSpacing + sqrtPriceX96 in MintParams)\nconst thenaPmAbi = parseAbi([\n \"struct MintParams { address token0; address token1; int24 tickSpacing; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; uint160 sqrtPriceX96; }\",\n \"function mint(MintParams calldata params) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)\",\n]);\n\nconst thenaRouterAbi = parseAbi([\n \"struct ExactInputSingleParams { address tokenIn; address tokenOut; int24 tickSpacing; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; }\",\n \"function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut)\",\n]);\n\nconst thenaPoolAbi = parseAbi([\n \"function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, bool unlocked)\",\n \"function tickSpacing() view returns (int24)\",\n \"function token0() view returns (address)\",\n \"function token1() view returns (address)\",\n]);\n\nconst thenaFactoryAbi = parseAbi([\n \"function getPool(address tokenA, address tokenB, int24 tickSpacing) view returns (address)\",\n]);\n\nexport class ThenaCLAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly positionManager: Address | undefined;\n private readonly factory: Address | undefined;\n private readonly rpcUrl: string | undefined;\n private readonly defaultTickSpacing: number;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n this.router = router;\n this.positionManager = entry.contracts?.[\"position_manager\"];\n this.factory = entry.contracts?.[\"pool_factory\"];\n this.rpcUrl = rpcUrl;\n this.defaultTickSpacing = 50;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: thenaRouterAbi,\n functionName: \"exactInputSingle\",\n args: [{\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n tickSpacing: this.defaultTickSpacing,\n recipient: params.recipient,\n deadline: BigInt(params.deadline ?? 18446744073709551615n),\n amountIn: params.amount_in,\n amountOutMinimum: 0n,\n sqrtPriceLimitX96: 0n,\n }],\n });\n return {\n description: `[${this.protocolName}] Swap`,\n to: this.router, data, value: 0n, gas_estimate: 300_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote not yet implemented — use swap router`);\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const pm = this.positionManager;\n if (!pm) throw new DefiError(\"CONTRACT_ERROR\", \"Position manager not configured\");\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required\");\n\n // Sort tokens\n const [token0, token1, rawAmount0, rawAmount1] =\n params.token_a.toLowerCase() < params.token_b.toLowerCase()\n ? [params.token_a, params.token_b, params.amount_a, params.amount_b]\n : [params.token_b, params.token_a, params.amount_b, params.amount_a];\n\n // Resolve pool and tick range\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const poolAddr = params.pool as Address | undefined;\n let tickSpacing = this.defaultTickSpacing;\n let tickLower = params.tick_lower ?? 0;\n let tickUpper = params.tick_upper ?? 0;\n\n // If pool provided or we need to auto-detect ticks\n if (poolAddr || !params.tick_lower || !params.tick_upper) {\n let pool = poolAddr;\n if (!pool && this.factory) {\n pool = await client.readContract({\n address: this.factory, abi: thenaFactoryAbi, functionName: \"getPool\",\n args: [token0, token1, tickSpacing],\n }) as Address;\n if (pool === zeroAddress) throw new DefiError(\"CONTRACT_ERROR\", \"Pool not found\");\n }\n if (pool) {\n const [slot0, ts] = await Promise.all([\n client.readContract({ address: pool, abi: thenaPoolAbi, functionName: \"slot0\" }),\n client.readContract({ address: pool, abi: thenaPoolAbi, functionName: \"tickSpacing\" }),\n ]);\n const currentTick = Number((slot0 as readonly [bigint, number, ...unknown[]])[1]);\n tickSpacing = Number(ts);\n\n if (params.range_pct !== undefined) {\n // ±N% concentrated range\n const range = rangeToTicks(currentTick, params.range_pct, tickSpacing);\n tickLower = range.tickLower;\n tickUpper = range.tickUpper;\n } else if (!params.tick_lower && !params.tick_upper) {\n const isSingleSide = rawAmount0 === 0n || rawAmount1 === 0n;\n if (isSingleSide) {\n if (rawAmount0 > 0n) {\n tickLower = alignTickUp(currentTick + tickSpacing, tickSpacing);\n tickUpper = Math.floor(887272 / tickSpacing) * tickSpacing;\n } else {\n tickLower = Math.ceil(-887272 / tickSpacing) * tickSpacing;\n tickUpper = alignTickDown(currentTick - tickSpacing, tickSpacing);\n }\n } else {\n tickLower = Math.ceil(-887272 / tickSpacing) * tickSpacing;\n tickUpper = Math.floor(887272 / tickSpacing) * tickSpacing;\n }\n }\n }\n }\n\n // Apply explicit tick params (override auto-detected)\n if (params.tick_lower !== undefined) tickLower = params.tick_lower;\n if (params.tick_upper !== undefined) tickUpper = params.tick_upper;\n\n const data = encodeFunctionData({\n abi: thenaPmAbi,\n functionName: \"mint\",\n args: [{\n token0, token1,\n tickSpacing,\n tickLower, tickUpper,\n amount0Desired: rawAmount0,\n amount1Desired: rawAmount1,\n amount0Min: 0n, amount1Min: 0n,\n recipient: params.recipient,\n deadline: BigInt(\"18446744073709551615\"),\n sqrtPriceX96: 0n,\n }],\n });\n\n const approvals: { token: Address; spender: Address; amount: bigint }[] = [];\n if (rawAmount0 > 0n) approvals.push({ token: token0, spender: pm, amount: rawAmount0 });\n if (rawAmount1 > 0n) approvals.push({ token: token1, spender: pm, amount: rawAmount1 });\n\n return {\n description: `[${this.protocolName}] Add liquidity [${tickLower}, ${tickUpper}]`,\n to: pm, data, value: 0n, gas_estimate: 700_000, approvals,\n };\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] remove_liquidity requires tokenId`);\n }\n}\n","import { createPublicClient, decodeFunctionResult, encodeFunctionData, http, parseAbi, zeroAddress } from \"viem\";\nimport type { Address, Hex } from \"viem\";\n\nimport { DefiError, multicallRead } from \"@hypurrquant/defi-core\";\nimport type {\n IGaugeSystem,\n GaugedPool,\n ProtocolEntry,\n RewardInfo,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\n// Multicall decode helpers\nconst _addressDecodeAbi = parseAbi([\"function f() external view returns (address)\"]);\nfunction decodeAddress(data: Hex | null): Address | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _addressDecodeAbi, functionName: \"f\", data }) as Address;\n } catch {\n return null;\n }\n}\n\nconst _symbolDecodeAbi = parseAbi([\"function symbol() external view returns (string)\"]);\nfunction decodeSymbol(data: Hex | null): string {\n if (!data) return \"?\";\n try {\n return decodeFunctionResult({ abi: _symbolDecodeAbi, functionName: \"symbol\", data }) as string;\n } catch {\n return \"?\";\n }\n}\n\nconst gaugeManagerAbi = parseAbi([\n \"function gauges(address pool) view returns (address gauge)\",\n \"function isGauge(address gauge) view returns (bool)\",\n \"function isAlive(address gauge) view returns (bool)\",\n \"function claimRewards(address gauge, uint256[] tokenIds, uint8 redeemType) external\",\n]);\n\nconst gaugeCLAbi = parseAbi([\n \"function deposit(uint256 tokenId) external\",\n \"function withdraw(uint256 tokenId, uint8 redeemType) external\",\n \"function earned(uint256 tokenId) view returns (uint256)\",\n \"function balanceOf(uint256 tokenId) view returns (uint256)\",\n \"function rewardToken() view returns (address)\",\n]);\n\nconst nfpmAbi = parseAbi([\n \"function approve(address to, uint256 tokenId) external\",\n \"function getApproved(uint256 tokenId) view returns (address)\",\n]);\n\nconst veAbi = parseAbi([\n \"function create_lock(uint256 value, uint256 lock_duration) external returns (uint256)\",\n \"function increase_amount(uint256 tokenId, uint256 value) external\",\n \"function increase_unlock_time(uint256 tokenId, uint256 lock_duration) external\",\n \"function withdraw(uint256 tokenId) external\",\n]);\n\nconst voterAbi = parseAbi([\n \"function vote(uint256 tokenId, address[] pools, uint256[] weights) external\",\n \"function claimBribes(address[] bribes, address[][] tokens, uint256 tokenId) external\",\n \"function claimFees(address[] fees, address[][] tokens, uint256 tokenId) external\",\n]);\n\n/**\n * Hybra ve(3,3) Gauge adapter using GaugeManager pattern.\n * CL gauges require NFT deposit and claim goes through GaugeManager (not directly to gauge).\n */\nexport class HybraGaugeAdapter implements IGaugeSystem {\n private readonly protocolName: string;\n private readonly gaugeManager: Address;\n private readonly veToken: Address;\n private readonly voter: Address;\n private readonly positionManager: Address;\n private readonly poolFactory: Address | undefined;\n private readonly rpcUrl: string | undefined;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const gm = entry.contracts?.[\"gauge_manager\"];\n if (!gm) throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'gauge_manager' contract\");\n this.gaugeManager = gm;\n const ve = entry.contracts?.[\"ve_token\"];\n if (!ve) throw new DefiError(\"CONTRACT_ERROR\", \"Missing 've_token' contract\");\n this.veToken = ve;\n this.voter = entry.contracts?.[\"voter\"] ?? zeroAddress as Address;\n this.positionManager = entry.contracts?.[\"position_manager\"] ?? zeroAddress as Address;\n this.poolFactory = entry.contracts?.[\"pool_factory\"];\n this.rpcUrl = rpcUrl;\n }\n\n name(): string { return this.protocolName; }\n\n // ─── Gauge Discovery ──────────────────────────────────────\n\n async discoverGaugedPools(): Promise<GaugedPool[]> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required for gauge discovery\");\n if (!this.poolFactory) throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'pool_factory' contract\");\n\n const factoryAbi = parseAbi([\n \"function allPoolsLength() external view returns (uint256)\",\n \"function allPools(uint256) external view returns (address)\",\n ]);\n const poolAbi = parseAbi([\n \"function token0() external view returns (address)\",\n \"function token1() external view returns (address)\",\n ]);\n const erc20SymbolAbi = parseAbi([\"function symbol() external view returns (string)\"]);\n const gaugesAbi = parseAbi([\"function gauges(address pool) view returns (address gauge)\"]);\n\n // Step 1: get total pool count\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n let poolCount: bigint;\n try {\n poolCount = await client.readContract({\n address: this.poolFactory,\n abi: factoryAbi,\n functionName: \"allPoolsLength\",\n }) as bigint;\n } catch {\n return [];\n }\n\n const count = Number(poolCount);\n if (count === 0) return [];\n\n // Step 2: batch-fetch all pool addresses\n const poolAddressCalls: Array<[Address, Hex]> = [];\n for (let i = 0; i < count; i++) {\n poolAddressCalls.push([\n this.poolFactory,\n encodeFunctionData({ abi: factoryAbi, functionName: \"allPools\", args: [BigInt(i)] }),\n ]);\n }\n const poolAddressResults = await multicallRead(this.rpcUrl, poolAddressCalls);\n const pools: Address[] = poolAddressResults\n .map((r) => decodeAddress(r))\n .filter((a): a is Address => a !== null && a !== zeroAddress);\n\n if (pools.length === 0) return [];\n\n // Step 3: batch GaugeManager.gauges(pool) for all pools\n const gaugeCalls: Array<[Address, Hex]> = pools.map((pool) => [\n this.gaugeManager,\n encodeFunctionData({ abi: gaugesAbi, functionName: \"gauges\", args: [pool] }),\n ]);\n const gaugeResults = await multicallRead(this.rpcUrl, gaugeCalls);\n\n // Filter pools that have an active gauge\n const gaugedPools: Array<{ pool: Address; gauge: Address }> = [];\n for (let i = 0; i < pools.length; i++) {\n const gauge = decodeAddress(gaugeResults[i] ?? null);\n if (gauge && gauge !== zeroAddress) {\n gaugedPools.push({ pool: pools[i]!, gauge });\n }\n }\n\n if (gaugedPools.length === 0) return [];\n\n // Step 4: batch token0() and token1() for gauged pools\n const tokenCalls: Array<[Address, Hex]> = [];\n for (const { pool } of gaugedPools) {\n tokenCalls.push([pool, encodeFunctionData({ abi: poolAbi, functionName: \"token0\" })]);\n tokenCalls.push([pool, encodeFunctionData({ abi: poolAbi, functionName: \"token1\" })]);\n }\n const tokenResults = await multicallRead(this.rpcUrl, tokenCalls);\n\n // Step 5: collect unique token addresses and fetch symbols\n const tokenAddrs = new Set<Address>();\n for (let i = 0; i < gaugedPools.length; i++) {\n const t0 = decodeAddress(tokenResults[i * 2] ?? null);\n const t1 = decodeAddress(tokenResults[i * 2 + 1] ?? null);\n if (t0 && t0 !== zeroAddress) tokenAddrs.add(t0);\n if (t1 && t1 !== zeroAddress) tokenAddrs.add(t1);\n }\n\n const uniqueTokens = Array.from(tokenAddrs);\n const symbolCalls: Array<[Address, Hex]> = uniqueTokens.map((t) => [\n t,\n encodeFunctionData({ abi: erc20SymbolAbi, functionName: \"symbol\" }),\n ]);\n const symbolResults = await multicallRead(this.rpcUrl, symbolCalls);\n const symbolMap = new Map<Address, string>();\n for (let i = 0; i < uniqueTokens.length; i++) {\n symbolMap.set(uniqueTokens[i]!, decodeSymbol(symbolResults[i] ?? null));\n }\n\n // Step 6: assemble results\n const out: GaugedPool[] = [];\n for (let i = 0; i < gaugedPools.length; i++) {\n const { pool, gauge } = gaugedPools[i]!;\n const t0 = decodeAddress(tokenResults[i * 2] ?? null);\n const t1 = decodeAddress(tokenResults[i * 2 + 1] ?? null);\n out.push({\n pool,\n gauge,\n token0: t0 ? (symbolMap.get(t0) ?? t0.slice(0, 10)) : \"?\",\n token1: t1 ? (symbolMap.get(t1) ?? t1.slice(0, 10)) : \"?\",\n type: \"CL\",\n });\n }\n\n return out;\n }\n\n // ─── Gauge Lookup ──────────────────────────────────────────\n\n async resolveGauge(pool: Address): Promise<Address> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC required\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const gauge = await client.readContract({\n address: this.gaugeManager, abi: gaugeManagerAbi,\n functionName: \"gauges\", args: [pool],\n }) as Address;\n if (gauge === zeroAddress) throw new DefiError(\"CONTRACT_ERROR\", `No gauge for pool ${pool}`);\n return gauge;\n }\n\n // ─── CL Gauge: NFT Deposit/Withdraw ──────────────────────────\n\n async buildDeposit(gauge: Address, _amount: bigint, tokenId?: bigint): Promise<DeFiTx> {\n if (tokenId === undefined) throw new DefiError(\"CONTRACT_ERROR\", \"tokenId required for CL gauge deposit\");\n\n // Pre-tx: approve NFT to gauge\n const approveTx: DeFiTx = {\n description: `[${this.protocolName}] Approve NFT #${tokenId} to gauge`,\n to: this.positionManager,\n data: encodeFunctionData({ abi: nfpmAbi, functionName: \"approve\", args: [gauge, tokenId] }),\n value: 0n, gas_estimate: 80_000,\n };\n\n return {\n description: `[${this.protocolName}] Deposit NFT #${tokenId} to gauge`,\n to: gauge,\n data: encodeFunctionData({ abi: gaugeCLAbi, functionName: \"deposit\", args: [tokenId] }),\n value: 0n, gas_estimate: 500_000,\n pre_txs: [approveTx],\n };\n }\n\n async buildWithdraw(gauge: Address, _amount: bigint, tokenId?: bigint): Promise<DeFiTx> {\n if (tokenId === undefined) throw new DefiError(\"CONTRACT_ERROR\", \"tokenId required for CL gauge withdraw\");\n return {\n description: `[${this.protocolName}] Withdraw NFT #${tokenId} from gauge`,\n to: gauge,\n data: encodeFunctionData({ abi: gaugeCLAbi, functionName: \"withdraw\", args: [tokenId, 1] }),\n value: 0n, gas_estimate: 1_000_000,\n };\n }\n\n // ─── Claim: via GaugeManager ──────────────────────────────────\n\n async buildClaimRewards(gauge: Address, _account?: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] Use buildClaimRewardsByTokenId for CL gauges`);\n }\n\n async buildClaimRewardsByTokenId(gauge: Address, tokenId: bigint): Promise<DeFiTx> {\n return {\n description: `[${this.protocolName}] Claim rewards for NFT #${tokenId}`,\n to: this.gaugeManager,\n data: encodeFunctionData({\n abi: gaugeManagerAbi, functionName: \"claimRewards\",\n args: [gauge, [tokenId], 1], // redeemType=1\n }),\n value: 0n, gas_estimate: 1_000_000,\n };\n }\n\n // ─── Pending Rewards ──────────────────────────────────────────\n\n async getPendingRewards(gauge: Address, _user: Address): Promise<RewardInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] Use getPendingRewardsByTokenId for CL gauges`);\n }\n\n async getPendingRewardsByTokenId(gauge: Address, tokenId: bigint): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC required\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return await client.readContract({\n address: gauge, abi: gaugeCLAbi,\n functionName: \"earned\", args: [tokenId],\n }) as bigint;\n }\n\n // ─── VoteEscrow ──────────────────────────────────────────────\n\n async buildCreateLock(amount: bigint, lockDuration: number): Promise<DeFiTx> {\n return {\n description: `[${this.protocolName}] Create veNFT lock`,\n to: this.veToken,\n data: encodeFunctionData({ abi: veAbi, functionName: \"create_lock\", args: [amount, BigInt(lockDuration)] }),\n value: 0n, gas_estimate: 300_000,\n };\n }\n\n async buildIncreaseAmount(tokenId: bigint, amount: bigint): Promise<DeFiTx> {\n return {\n description: `[${this.protocolName}] Increase veNFT #${tokenId}`,\n to: this.veToken,\n data: encodeFunctionData({ abi: veAbi, functionName: \"increase_amount\", args: [tokenId, amount] }),\n value: 0n, gas_estimate: 200_000,\n };\n }\n\n async buildIncreaseUnlockTime(tokenId: bigint, lockDuration: number): Promise<DeFiTx> {\n return {\n description: `[${this.protocolName}] Extend veNFT #${tokenId} lock`,\n to: this.veToken,\n data: encodeFunctionData({ abi: veAbi, functionName: \"increase_unlock_time\", args: [tokenId, BigInt(lockDuration)] }),\n value: 0n, gas_estimate: 200_000,\n };\n }\n\n async buildWithdrawExpired(tokenId: bigint): Promise<DeFiTx> {\n return {\n description: `[${this.protocolName}] Withdraw expired veNFT #${tokenId}`,\n to: this.veToken,\n data: encodeFunctionData({ abi: veAbi, functionName: \"withdraw\", args: [tokenId] }),\n value: 0n, gas_estimate: 200_000,\n };\n }\n\n // ─── Voter ──────────────────────────────────────────────────\n\n async buildVote(tokenId: bigint, pools: Address[], weights: bigint[]): Promise<DeFiTx> {\n return {\n description: `[${this.protocolName}] Vote with veNFT #${tokenId}`,\n to: this.voter,\n data: encodeFunctionData({ abi: voterAbi, functionName: \"vote\", args: [tokenId, pools, weights] }),\n value: 0n, gas_estimate: 500_000,\n };\n }\n\n async buildClaimBribes(bribes: Address[], tokenId: bigint): Promise<DeFiTx> {\n const tokensPerBribe: Address[][] = bribes.map(() => []);\n return {\n description: `[${this.protocolName}] Claim bribes for veNFT #${tokenId}`,\n to: this.voter,\n data: encodeFunctionData({ abi: voterAbi, functionName: \"claimBribes\", args: [bribes, tokensPerBribe, tokenId] }),\n value: 0n, gas_estimate: 300_000,\n };\n }\n\n async buildClaimFees(fees: Address[], tokenId: bigint): Promise<DeFiTx> {\n const tokensPerFee: Address[][] = fees.map(() => []);\n return {\n description: `[${this.protocolName}] Claim fees for veNFT #${tokenId}`,\n to: this.voter,\n data: encodeFunctionData({ abi: voterAbi, functionName: \"claimFees\", args: [fees, tokensPerFee, tokenId] }),\n value: 0n, gas_estimate: 300_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, zeroAddress } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"function swap(address fromToken, address toToken, uint256 fromAmount, uint256 minToAmount, address to, address rebateTo) external payable returns (uint256 realToAmount)\",\n]);\n\nexport class WooFiAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract\");\n }\n this.router = router;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const minToAmount = 0n;\n\n const data = encodeFunctionData({\n abi,\n functionName: \"swap\",\n args: [\n params.token_in,\n params.token_out,\n params.amount_in,\n minToAmount,\n params.recipient,\n zeroAddress,\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} via WOOFi`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote requires RPC`);\n }\n\n async buildAddLiquidity(_params: AddLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] WOOFi does not support LP positions via router`);\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] WOOFi does not support LP positions via router`);\n }\n}\n","import { createPublicClient, decodeFunctionResult, encodeFunctionData, http, parseAbi, zeroAddress } from \"viem\";\nimport type { Address, Hex } from \"viem\";\n\nimport { DefiError, multicallRead } from \"@hypurrquant/defi-core\";\nimport type {\n IGaugeSystem,\n GaugedPool,\n ProtocolEntry,\n RewardInfo,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst gaugeAbi = parseAbi([\n \"function deposit(uint256 amount) external\",\n \"function depositFor(uint256 amount, uint256 tokenId) external\",\n \"function withdraw(uint256 amount) external\",\n \"function getReward() external\",\n \"function getReward(address account) external\",\n \"function getReward(address account, address[] tokens) external\",\n \"function getReward(uint256 tokenId) external\",\n \"function earned(address account) external view returns (uint256)\",\n \"function earned(address token, address account) external view returns (uint256)\",\n \"function earned(uint256 tokenId) external view returns (uint256)\",\n \"function rewardRate() external view returns (uint256)\",\n \"function rewardToken() external view returns (address)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function rewardsListLength() external view returns (uint256)\",\n \"function rewardData(address token) external view returns (uint256 periodFinish, uint256 rewardRate, uint256 lastUpdateTime, uint256 rewardPerTokenStored)\",\n \"function nonfungiblePositionManager() external view returns (address)\",\n]);\n\nconst veAbi = parseAbi([\n \"function create_lock(uint256 value, uint256 lock_duration) external returns (uint256)\",\n \"function increase_amount(uint256 tokenId, uint256 value) external\",\n \"function increase_unlock_time(uint256 tokenId, uint256 lock_duration) external\",\n \"function withdraw(uint256 tokenId) external\",\n \"function balanceOfNFT(uint256 tokenId) external view returns (uint256)\",\n \"function locked(uint256 tokenId) external view returns (uint256 amount, uint256 end)\",\n]);\n\nconst voterAbi = parseAbi([\n \"function vote(uint256 tokenId, address[] calldata pools, uint256[] calldata weights) external\",\n \"function claimBribes(address[] calldata bribes, address[][] calldata tokens, uint256 tokenId) external\",\n \"function claimFees(address[] calldata fees, address[][] calldata tokens, uint256 tokenId) external\",\n \"function gauges(address pool) external view returns (address)\",\n \"function gaugeForPool(address pool) external view returns (address)\",\n \"function poolToGauge(address pool) external view returns (address)\",\n]);\n\n// Multicall decode helpers\nconst _addressDecodeAbi = parseAbi([\"function f() external view returns (address)\"]);\nfunction decodeAddress(data: Hex | null): Address | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _addressDecodeAbi, functionName: \"f\", data }) as Address;\n } catch {\n return null;\n }\n}\n\nconst _symbolDecodeAbi = parseAbi([\"function symbol() external view returns (string)\"]);\nfunction decodeSymbol(data: Hex | null): string {\n if (!data) return \"?\";\n try {\n return decodeFunctionResult({ abi: _symbolDecodeAbi, functionName: \"symbol\", data }) as string;\n } catch {\n return \"?\";\n }\n}\n\nconst _boolDecodeAbi = parseAbi([\"function f() external view returns (bool)\"]);\nfunction decodeBoolean(data: Hex): boolean {\n try {\n return decodeFunctionResult({ abi: _boolDecodeAbi, functionName: \"f\", data }) as boolean;\n } catch {\n return false;\n }\n}\n\n// HyperEVM well-known token addresses for CL pool discovery\nconst HYPEREVM_TOKENS: Record<string, Address> = {\n WHYPE: \"0x5555555555555555555555555555555555555555\",\n USDC: \"0xb88339CB7199b77E23DB6E890353E22632Ba630f\",\n USDT0: \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\",\n UETH: \"0xBe6727B535545C67d5cAa73dEa54865B92CF7907\",\n UBTC: \"0x9FDBdA0A5e284c32744D2f17Ee5c74B284993463\",\n USDH: \"0x111111a1a0667d36bD57c0A9f569b98057111111\",\n USDe: \"0x5d3a1Ff2b6BAb83b63cd9AD0787074081a52ef34\",\n sUSDe: \"0x211Cc4DD073734dA055fbF44a2b4667d5E5fE5d2\",\n XAUt0: \"0xf4D9235269a96aaDaFc9aDAe454a0618eBE37949\",\n kHYPE: \"0xfD739d4e423301CE9385c1fb8850539D657C296D\",\n RAM: \"0x555570a286F15EbDFE42B66eDE2f724Aa1AB5555\",\n hyperRAM: \"0xAAAE8378809bb8815c08D3C59Eb0c7D1529aD769\",\n};\n\nconst CL_TICK_SPACINGS = [1, 5, 10, 50, 100, 200];\n\nexport class SolidlyGaugeAdapter implements IGaugeSystem {\n private readonly protocolName: string;\n private readonly voter: Address;\n private readonly veToken: Address;\n private readonly rpcUrl: string | undefined;\n private readonly clFactory: Address | undefined;\n private readonly v2Factory: Address | undefined;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const voter = entry.contracts?.[\"voter\"];\n if (!voter) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'voter' contract\");\n }\n const veToken = entry.contracts?.[\"ve_token\"];\n if (!veToken) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 've_token' contract\");\n }\n this.voter = voter;\n this.veToken = veToken;\n this.rpcUrl = rpcUrl;\n this.clFactory = entry.contracts?.[\"cl_factory\"] ?? entry.contracts?.[\"factory\"];\n this.v2Factory = entry.contracts?.[\"pair_factory\"] ?? entry.contracts?.[\"factory\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n /** Scan V2 and CL factories for pools that have active emission gauges. */\n async discoverGaugedPools(): Promise<GaugedPool[]> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required for gauge discovery\");\n\n const results: GaugedPool[] = [];\n\n await Promise.all([\n this._discoverV2GaugedPools(results),\n this._discoverCLGaugedPools(results),\n ]);\n\n return results;\n }\n\n private async _discoverV2GaugedPools(out: GaugedPool[]): Promise<void> {\n if (!this.rpcUrl || !this.v2Factory) return;\n\n const v2FactoryAbi = parseAbi([\n \"function allPairsLength() external view returns (uint256)\",\n \"function allPairs(uint256) external view returns (address)\",\n ]);\n const pairAbi = parseAbi([\n \"function token0() external view returns (address)\",\n \"function token1() external view returns (address)\",\n \"function stable() external view returns (bool)\",\n ]);\n const erc20SymbolAbi = parseAbi([\"function symbol() external view returns (string)\"]);\n\n // Step 1: get total pairs count\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n let pairCount: bigint;\n try {\n pairCount = await client.readContract({\n address: this.v2Factory,\n abi: v2FactoryAbi,\n functionName: \"allPairsLength\",\n }) as bigint;\n } catch {\n return;\n }\n\n const count = Number(pairCount);\n if (count === 0) return;\n\n // Step 2: batch-fetch all pair addresses\n const pairAddressCalls: Array<[Address, Hex]> = [];\n for (let i = 0; i < count; i++) {\n pairAddressCalls.push([\n this.v2Factory,\n encodeFunctionData({ abi: v2FactoryAbi, functionName: \"allPairs\", args: [BigInt(i)] }),\n ]);\n }\n const pairAddressResults = await multicallRead(this.rpcUrl, pairAddressCalls);\n const pairs: Address[] = pairAddressResults.map((r) => decodeAddress(r)).filter((a): a is Address => a !== null && a !== zeroAddress);\n\n if (pairs.length === 0) return;\n\n // Step 3: for each pair, call gaugeForPool on voter (fallback to poolToGauge)\n const gaugeForPoolAbi = parseAbi([\"function gaugeForPool(address) external view returns (address)\"]);\n const poolToGaugeAbi = parseAbi([\"function poolToGauge(address) external view returns (address)\"]);\n const gaugeCalls: Array<[Address, Hex]> = pairs.map((pair) => [\n this.voter,\n encodeFunctionData({ abi: gaugeForPoolAbi, functionName: \"gaugeForPool\", args: [pair] }),\n ]);\n let gaugeResults = await multicallRead(this.rpcUrl, gaugeCalls);\n\n // If all results are null (gaugeForPool not supported), try poolToGauge\n const allNullV2 = gaugeResults.every(r => !r || decodeAddress(r) === zeroAddress || decodeAddress(r) === null);\n if (allNullV2) {\n const fallbackCalls: Array<[Address, Hex]> = pairs.map((pair) => [\n this.voter,\n encodeFunctionData({ abi: poolToGaugeAbi, functionName: \"poolToGauge\", args: [pair] }),\n ]);\n gaugeResults = await multicallRead(this.rpcUrl, fallbackCalls);\n }\n\n // Filter only pairs that have a gauge\n const gaugedPairs: Array<{ pair: Address; gauge: Address }> = [];\n for (let i = 0; i < pairs.length; i++) {\n const gauge = decodeAddress(gaugeResults[i] ?? null);\n if (gauge && gauge !== zeroAddress) {\n gaugedPairs.push({ pair: pairs[i]!, gauge });\n }\n }\n\n if (gaugedPairs.length === 0) return;\n\n // Step 4: fetch token0, token1, stable for each gauged pair\n const metaCalls: Array<[Address, Hex]> = [];\n for (const { pair } of gaugedPairs) {\n metaCalls.push([pair, encodeFunctionData({ abi: pairAbi, functionName: \"token0\" })]);\n metaCalls.push([pair, encodeFunctionData({ abi: pairAbi, functionName: \"token1\" })]);\n metaCalls.push([pair, encodeFunctionData({ abi: pairAbi, functionName: \"stable\" })]);\n }\n const metaResults = await multicallRead(this.rpcUrl, metaCalls);\n\n // Step 5: collect unique token addresses and fetch symbols\n const tokenAddrs = new Set<Address>();\n for (let i = 0; i < gaugedPairs.length; i++) {\n const t0 = decodeAddress(metaResults[i * 3] ?? null);\n const t1 = decodeAddress(metaResults[i * 3 + 1] ?? null);\n if (t0 && t0 !== zeroAddress) tokenAddrs.add(t0);\n if (t1 && t1 !== zeroAddress) tokenAddrs.add(t1);\n }\n\n const uniqueTokens = Array.from(tokenAddrs);\n const symbolCalls: Array<[Address, Hex]> = uniqueTokens.map((t) => [\n t,\n encodeFunctionData({ abi: erc20SymbolAbi, functionName: \"symbol\" }),\n ]);\n const symbolResults = await multicallRead(this.rpcUrl, symbolCalls);\n const symbolMap = new Map<Address, string>();\n for (let i = 0; i < uniqueTokens.length; i++) {\n symbolMap.set(uniqueTokens[i]!, decodeSymbol(symbolResults[i] ?? null));\n }\n\n // Step 6: assemble results\n for (let i = 0; i < gaugedPairs.length; i++) {\n const { pair, gauge } = gaugedPairs[i]!;\n const t0 = decodeAddress(metaResults[i * 3] ?? null);\n const t1 = decodeAddress(metaResults[i * 3 + 1] ?? null);\n const stableRaw = metaResults[i * 3 + 2];\n const stable = stableRaw ? decodeBoolean(stableRaw) : false;\n out.push({\n pool: pair,\n gauge,\n token0: t0 ? (symbolMap.get(t0) ?? t0.slice(0, 10)) : \"?\",\n token1: t1 ? (symbolMap.get(t1) ?? t1.slice(0, 10)) : \"?\",\n type: \"V2\",\n stable,\n });\n }\n }\n\n private async _discoverCLGaugedPools(out: GaugedPool[]): Promise<void> {\n if (!this.rpcUrl || !this.clFactory) return;\n\n const clFactoryAbi = parseAbi([\n \"function getPool(address tokenA, address tokenB, int24 tickSpacing) external view returns (address pool)\",\n ]);\n const algebraFactoryAbi = parseAbi([\n \"function poolByPair(address tokenA, address tokenB) external view returns (address pool)\",\n ]);\n const poolAbi = parseAbi([\n \"function token0() external view returns (address)\",\n \"function token1() external view returns (address)\",\n ]);\n const erc20SymbolAbi = parseAbi([\"function symbol() external view returns (string)\"]);\n const gaugeForPoolAbi = parseAbi([\"function gaugeForPool(address) external view returns (address)\"]);\n const poolToGaugeAbi = parseAbi([\"function poolToGauge(address) external view returns (address)\"]);\n\n const tokenEntries = Object.entries(HYPEREVM_TOKENS);\n const tokenAddresses = tokenEntries.map(([, addr]) => addr);\n\n // Generate all unique token pairs\n const pairs: Array<[Address, Address]> = [];\n for (let i = 0; i < tokenAddresses.length; i++) {\n for (let j = i + 1; j < tokenAddresses.length; j++) {\n pairs.push([tokenAddresses[i]!, tokenAddresses[j]!]);\n }\n }\n\n // Detect factory type: try poolByPair (Algebra) — if it returns non-null, it's Algebra\n const isAlgebra = await (async () => {\n try {\n const [result] = await multicallRead(this.rpcUrl!, [[\n this.clFactory!,\n encodeFunctionData({ abi: algebraFactoryAbi, functionName: \"poolByPair\", args: [tokenAddresses[0]!, tokenAddresses[1]!] }),\n ]]);\n // If poolByPair returns any data (even zero address), it's Algebra\n return result !== null && result.length >= 66;\n } catch {\n return false;\n }\n })();\n\n // Build pool lookup calls\n const getPoolCalls: Array<[Address, Hex]> = [];\n const callMeta: Array<{ pairIdx: number; tickSpacing: number }> = [];\n\n if (isAlgebra) {\n // Algebra: one pool per pair (no tickSpacing)\n for (let p = 0; p < pairs.length; p++) {\n const [tokenA, tokenB] = pairs[p]!;\n getPoolCalls.push([\n this.clFactory!,\n encodeFunctionData({ abi: algebraFactoryAbi, functionName: \"poolByPair\", args: [tokenA!, tokenB!] }),\n ]);\n callMeta.push({ pairIdx: p, tickSpacing: 0 });\n }\n } else {\n // Uniswap-style: multiple tick spacings per pair\n for (let p = 0; p < pairs.length; p++) {\n const [tokenA, tokenB] = pairs[p]!;\n for (const ts of CL_TICK_SPACINGS) {\n getPoolCalls.push([\n this.clFactory!,\n encodeFunctionData({ abi: clFactoryAbi, functionName: \"getPool\", args: [tokenA!, tokenB!, ts] }),\n ]);\n callMeta.push({ pairIdx: p, tickSpacing: ts });\n }\n }\n }\n\n const getPoolResults = await multicallRead(this.rpcUrl, getPoolCalls);\n\n // Collect non-zero pool addresses\n const candidatePools: Array<{ pool: Address; tokenA: Address; tokenB: Address; tickSpacing: number }> = [];\n for (let i = 0; i < getPoolCalls.length; i++) {\n const pool = decodeAddress(getPoolResults[i] ?? null);\n if (pool && pool !== zeroAddress) {\n const { pairIdx, tickSpacing } = callMeta[i]!;\n const [tokenA, tokenB] = pairs[pairIdx]!;\n candidatePools.push({ pool, tokenA: tokenA!, tokenB: tokenB!, tickSpacing });\n }\n }\n\n if (candidatePools.length === 0) return;\n\n // Batch gauge lookup — try gaugeForPool first, fallback to poolToGauge\n const gaugeCalls: Array<[Address, Hex]> = candidatePools.map(({ pool }) => [\n this.voter,\n encodeFunctionData({ abi: gaugeForPoolAbi, functionName: \"gaugeForPool\", args: [pool] }),\n ]);\n let gaugeResults = await multicallRead(this.rpcUrl, gaugeCalls);\n\n // If all results are null (gaugeForPool not supported), try poolToGauge\n const allNull = gaugeResults.every(r => !r || decodeAddress(r) === zeroAddress || decodeAddress(r) === null);\n if (allNull) {\n const fallbackCalls: Array<[Address, Hex]> = candidatePools.map(({ pool }) => [\n this.voter,\n encodeFunctionData({ abi: poolToGaugeAbi, functionName: \"poolToGauge\", args: [pool] }),\n ]);\n gaugeResults = await multicallRead(this.rpcUrl, fallbackCalls);\n }\n\n // Filter to pools that have a gauge\n const gaugedCL: Array<{ pool: Address; gauge: Address; tokenA: Address; tokenB: Address; tickSpacing: number }> = [];\n for (let i = 0; i < candidatePools.length; i++) {\n const gauge = decodeAddress(gaugeResults[i] ?? null);\n if (gauge && gauge !== zeroAddress) {\n gaugedCL.push({ ...candidatePools[i]!, gauge });\n }\n }\n\n if (gaugedCL.length === 0) return;\n\n // Fetch token0/token1 from pool to get correct ordering, then symbols\n const tokenAddrsInPools = new Set<Address>();\n for (const { tokenA, tokenB } of gaugedCL) {\n tokenAddrsInPools.add(tokenA);\n tokenAddrsInPools.add(tokenB);\n }\n const uniqueTokens = Array.from(tokenAddrsInPools);\n const symbolCalls: Array<[Address, Hex]> = uniqueTokens.map((t) => [\n t,\n encodeFunctionData({ abi: erc20SymbolAbi, functionName: \"symbol\" }),\n ]);\n const symbolResults = await multicallRead(this.rpcUrl, symbolCalls);\n const symbolMap = new Map<Address, string>();\n for (let i = 0; i < uniqueTokens.length; i++) {\n symbolMap.set(uniqueTokens[i]!, decodeSymbol(symbolResults[i] ?? null));\n }\n\n // Also try to read actual token0/token1 ordering from the pool contract\n const poolTokenCalls: Array<[Address, Hex]> = [];\n for (const { pool } of gaugedCL) {\n poolTokenCalls.push([pool, encodeFunctionData({ abi: poolAbi, functionName: \"token0\" })]);\n poolTokenCalls.push([pool, encodeFunctionData({ abi: poolAbi, functionName: \"token1\" })]);\n }\n const poolTokenResults = await multicallRead(this.rpcUrl, poolTokenCalls);\n\n for (let i = 0; i < gaugedCL.length; i++) {\n const { pool, gauge, tokenA, tokenB, tickSpacing } = gaugedCL[i]!;\n const rawT0 = decodeAddress(poolTokenResults[i * 2] ?? null);\n const rawT1 = decodeAddress(poolTokenResults[i * 2 + 1] ?? null);\n const t0 = rawT0 && rawT0 !== zeroAddress ? rawT0 : tokenA;\n const t1 = rawT1 && rawT1 !== zeroAddress ? rawT1 : tokenB;\n out.push({\n pool,\n gauge,\n token0: symbolMap.get(t0) ?? t0.slice(0, 10),\n token1: symbolMap.get(t1) ?? t1.slice(0, 10),\n type: \"CL\",\n tickSpacing,\n });\n }\n }\n\n // IGauge\n\n async buildDeposit(gauge: Address, amount: bigint, tokenId?: bigint, lpToken?: Address): Promise<DeFiTx> {\n if (tokenId !== undefined) {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"depositFor\",\n args: [amount, tokenId],\n });\n return {\n description: `[${this.protocolName}] Deposit ${amount} LP to gauge (boost veNFT #${tokenId})`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n approvals: lpToken ? [{ token: lpToken, spender: gauge, amount }] : undefined,\n };\n }\n\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"deposit\",\n args: [amount],\n });\n return {\n description: `[${this.protocolName}] Deposit ${amount} LP to gauge`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n approvals: lpToken ? [{ token: lpToken, spender: gauge, amount }] : undefined,\n };\n }\n\n async buildWithdraw(gauge: Address, amount: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"withdraw\",\n args: [amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${amount} LP from gauge`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /**\n * Resolve gauge address from a pool address via voter contract.\n * Tries gaugeForPool (Ramses), poolToGauge (NEST), gauges (classic Solidly).\n */\n async resolveGauge(pool: Address): Promise<Address> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required for gauge lookup\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n for (const fn of [\"gaugeForPool\", \"poolToGauge\", \"gauges\"] as const) {\n try {\n const gauge = await client.readContract({\n address: this.voter,\n abi: voterAbi,\n functionName: fn,\n args: [pool],\n }) as Address;\n if (gauge !== zeroAddress) return gauge;\n } catch {\n // try next\n }\n }\n throw new DefiError(\"CONTRACT_ERROR\", `[${this.protocolName}] No gauge found for pool ${pool}`);\n }\n\n /**\n * Discover reward tokens for a gauge.\n * Returns { tokens, multiToken } where multiToken indicates getReward(account, tokens[]) support.\n */\n private async discoverRewardTokens(gauge: Address): Promise<{ tokens: Address[]; multiToken: boolean }> {\n if (!this.rpcUrl) return { tokens: [], multiToken: false };\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // 1. Try rewardsListLength — multi-token gauges (Ramses style)\n try {\n const len = await client.readContract({\n address: gauge,\n abi: gaugeAbi,\n functionName: \"rewardsListLength\",\n }) as bigint;\n\n if (Number(len) > 0) {\n // Discover via rewardData for known HyperEVM tokens\n const candidates: Address[] = [\n \"0x5555555555555555555555555555555555555555\", // WHYPE\n \"0x555570a286F15EbDFE42B66eDE2f724Aa1AB5555\", // xRAM\n \"0x067b0C72aa4C6Bd3BFEFfF443c536DCd6a25a9C8\", // HYBR\n \"0x07c57E32a3C29D5659bda1d3EFC2E7BF004E3035\", // NEST token\n ];\n const found: Address[] = [];\n for (const token of candidates) {\n try {\n const rd = await client.readContract({\n address: gauge,\n abi: gaugeAbi,\n functionName: \"rewardData\",\n args: [token],\n }) as readonly [bigint, bigint, bigint, bigint];\n if (rd[0] > 0n || rd[1] > 0n) found.push(token);\n } catch { /* not a reward */ }\n }\n if (found.length > 0) return { tokens: found, multiToken: true };\n return { tokens: [], multiToken: true }; // has rewards but couldn't enumerate\n }\n } catch {\n // no rewardsListLength\n }\n\n // 2. Fallback: rewardToken() — single-reward gauges (NEST / Hybra style)\n try {\n const rt = await client.readContract({\n address: gauge,\n abi: gaugeAbi,\n functionName: \"rewardToken\",\n }) as Address;\n if (rt !== zeroAddress) return { tokens: [rt], multiToken: false };\n } catch { /* no rewardToken */ }\n\n return { tokens: [], multiToken: false };\n }\n\n async buildClaimRewards(gauge: Address, account?: Address): Promise<DeFiTx> {\n if (!this.rpcUrl || !account) {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [account ?? zeroAddress],\n });\n return { description: `[${this.protocolName}] Claim gauge rewards`, to: gauge, data, value: 0n, gas_estimate: 200_000 };\n }\n\n const { tokens, multiToken } = await this.discoverRewardTokens(gauge);\n\n // Multi-token gauge (Ramses): getReward(account, tokens[])\n if (multiToken && tokens.length > 0) {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [account, tokens],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards (${tokens.length} tokens)`,\n to: gauge, data, value: 0n, gas_estimate: 300_000,\n };\n }\n\n // Single-token gauge (NEST / standard): getReward() with no args\n // Some gauges use getReward(account), but NEST-style uses getReward()\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards`,\n to: gauge, data, value: 0n, gas_estimate: 200_000,\n };\n }\n\n /**\n * Claim rewards for a CL gauge by NFT tokenId (Hybra V4 style).\n */\n async buildClaimRewardsByTokenId(gauge: Address, tokenId: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [tokenId],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards for NFT #${tokenId}`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async getPendingRewards(gauge: Address, user: Address): Promise<RewardInfo[]> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const results: RewardInfo[] = [];\n\n const { tokens, multiToken } = await this.discoverRewardTokens(gauge);\n\n if (multiToken && tokens.length > 0) {\n for (const token of tokens) {\n try {\n const earned = await client.readContract({\n address: gauge, abi: gaugeAbi, functionName: \"earned\", args: [token, user],\n }) as bigint;\n results.push({ token, symbol: token.slice(0, 10), amount: earned });\n } catch { /* skip */ }\n }\n } else if (tokens.length > 0) {\n // Single-token gauge: earned(account)\n try {\n const earned = await client.readContract({\n address: gauge, abi: gaugeAbi, functionName: \"earned\", args: [user],\n }) as bigint;\n results.push({ token: tokens[0]!, symbol: tokens[0]!.slice(0, 10), amount: earned });\n } catch { /* skip */ }\n } else {\n try {\n const earned = await client.readContract({\n address: gauge, abi: gaugeAbi, functionName: \"earned\", args: [user],\n }) as bigint;\n results.push({ token: zeroAddress as Address, symbol: \"unknown\", amount: earned });\n } catch { /* skip */ }\n }\n\n return results;\n }\n\n /**\n * Get pending rewards for a CL gauge NFT position (Hybra V4 style).\n */\n async getPendingRewardsByTokenId(gauge: Address, tokenId: bigint): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"RPC URL required\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return await client.readContract({\n address: gauge,\n abi: gaugeAbi,\n functionName: \"earned\",\n args: [tokenId],\n }) as bigint;\n }\n\n // IVoteEscrow\n\n async buildCreateLock(amount: bigint, lockDuration: number): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"create_lock\",\n args: [amount, BigInt(lockDuration)],\n });\n return {\n description: `[${this.protocolName}] Create veNFT lock: ${amount} tokens for ${lockDuration}s`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildIncreaseAmount(tokenId: bigint, amount: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"increase_amount\",\n args: [tokenId, amount],\n });\n return {\n description: `[${this.protocolName}] Increase veNFT #${tokenId} by ${amount}`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildIncreaseUnlockTime(tokenId: bigint, lockDuration: number): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"increase_unlock_time\",\n args: [tokenId, BigInt(lockDuration)],\n });\n return {\n description: `[${this.protocolName}] Extend veNFT #${tokenId} lock by ${lockDuration}s`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildWithdrawExpired(tokenId: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"withdraw\",\n args: [tokenId],\n });\n return {\n description: `[${this.protocolName}] Withdraw expired veNFT #${tokenId}`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n // IVoter\n\n async buildVote(tokenId: bigint, pools: Address[], weights: bigint[]): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: voterAbi,\n functionName: \"vote\",\n args: [tokenId, pools, weights],\n });\n return {\n description: `[${this.protocolName}] Vote with veNFT #${tokenId}`,\n to: this.voter,\n data,\n value: 0n,\n gas_estimate: 500_000,\n };\n }\n\n async buildClaimBribes(bribes: Address[], tokenId: bigint): Promise<DeFiTx> {\n // claimBribes needs token arrays per bribe contract — simplified version\n const tokensPerBribe: Address[][] = bribes.map(() => []);\n const data = encodeFunctionData({\n abi: voterAbi,\n functionName: \"claimBribes\",\n args: [bribes, tokensPerBribe, tokenId],\n });\n return {\n description: `[${this.protocolName}] Claim bribes for veNFT #${tokenId}`,\n to: this.voter,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildClaimFees(fees: Address[], tokenId: bigint): Promise<DeFiTx> {\n const tokensPerFee: Address[][] = fees.map(() => []);\n const data = encodeFunctionData({\n abi: voterAbi,\n functionName: \"claimFees\",\n args: [fees, tokensPerFee, tokenId],\n });\n return {\n description: `[${this.protocolName}] Claim trading fees for veNFT #${tokenId}`,\n to: this.voter,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IGauge,\n ProtocolEntry,\n RewardInfo,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst masterchefAbi = parseAbi([\n \"function deposit(uint256 pid, uint256 amount) external\",\n \"function withdraw(uint256 pid, uint256 amount) external\",\n \"function claim(uint256[] calldata pids) external\",\n \"function pendingRewards(address account, uint256[] calldata pids) view returns (uint256[] memory moeRewards)\",\n \"function getNumberOfFarms() view returns (uint256)\",\n \"function getPidByPool(address pool) view returns (uint256)\",\n]);\n\nexport class MasterChefAdapter implements IGauge {\n private readonly protocolName: string;\n private readonly masterchef: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const masterchef = entry.contracts?.[\"masterchef\"];\n if (!masterchef) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'masterchef' contract\");\n }\n this.masterchef = masterchef;\n this.rpcUrl = rpcUrl;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n /**\n * Deposit LP tokens into a MasterChef farm.\n * `gauge` is the pool address (unused for calldata — MasterChef is the target).\n * `tokenId` carries the farm pid.\n */\n async buildDeposit(gauge: Address, amount: bigint, tokenId?: bigint): Promise<DeFiTx> {\n const pid = tokenId ?? 0n;\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"deposit\",\n args: [pid, amount],\n });\n return {\n description: `[${this.protocolName}] Deposit ${amount} LP to farm pid=${pid} (pool ${gauge})`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /**\n * Withdraw LP tokens from a MasterChef farm.\n * `gauge` is used to look up the pid description only; call site should pass pid via tokenId\n * on the deposit flow. Here pid defaults to 0 — callers should encode the pid in the gauge\n * address slot or wrap this adapter with a pid-aware helper.\n */\n async buildWithdraw(gauge: Address, amount: bigint): Promise<DeFiTx> {\n // IGauge interface does not carry tokenId on withdraw; default pid=0.\n // Callers that need a specific pid should call buildWithdrawPid directly.\n const pid = 0n;\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"withdraw\",\n args: [pid, amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${amount} LP from farm pid=${pid} (pool ${gauge})`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Withdraw LP tokens specifying a pid explicitly (MasterChef extension beyond IGauge). */\n async buildWithdrawPid(pid: bigint, amount: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"withdraw\",\n args: [pid, amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${amount} LP from farm pid=${pid}`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Claim pending MOE rewards. IGauge interface provides no pid — defaults to pid=0. */\n async buildClaimRewards(gauge: Address): Promise<DeFiTx> {\n const pid = 0n;\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"claim\",\n args: [[pid]],\n });\n return {\n description: `[${this.protocolName}] Claim MOE rewards for farm pid=${pid} (pool ${gauge})`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Claim pending MOE rewards for a specific pid (MasterChef extension beyond IGauge). */\n async buildClaimRewardsPid(pid: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"claim\",\n args: [[pid]],\n });\n return {\n description: `[${this.protocolName}] Claim MOE rewards for farm pid=${pid}`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Get pending MOE rewards for a user. Requires rpcUrl. */\n async getPendingRewards(_gauge: Address, user: Address): Promise<RewardInfo[]> {\n if (!this.rpcUrl) {\n throw DefiError.unsupported(`[${this.protocolName}] getPendingRewards requires RPC`);\n }\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const rewards = await client.readContract({\n address: this.masterchef,\n abi: masterchefAbi,\n functionName: \"pendingRewards\",\n args: [user, [0n]],\n });\n return (rewards as bigint[]).map((amount) => ({\n token: this.masterchef,\n symbol: \"MOE\",\n amount,\n }));\n }\n}\n","import {\n encodeFunctionData,\n decodeFunctionResult,\n parseAbi,\n createPublicClient,\n http,\n} from \"viem\";\nimport type { Address, Hex } from \"viem\";\n\nimport { DefiError, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { ProtocolEntry, DeFiTx, RewardInfo } from \"@hypurrquant/defi-core\";\n\n// ============================================================\n// ABIs\n// ============================================================\n\nconst lbRouterAbi = parseAbi([\n \"struct LiquidityParameters { address tokenX; address tokenY; uint256 binStep; uint256 amountX; uint256 amountY; uint256 amountXMin; uint256 amountYMin; uint256 activeIdDesired; uint256 idSlippage; int256[] deltaIds; uint256[] distributionX; uint256[] distributionY; address to; address refundTo; uint256 deadline; }\",\n \"function addLiquidity(LiquidityParameters calldata liquidityParameters) external returns (uint256 amountXAdded, uint256 amountYAdded, uint256 amountXLeft, uint256 amountYLeft, uint256[] memory depositIds, uint256[] memory liquidityMinted)\",\n \"function removeLiquidity(address tokenX, address tokenY, uint16 binStep, uint256 amountXMin, uint256 amountYMin, uint256[] memory ids, uint256[] memory amounts, address to, uint256 deadline) external returns (uint256 amountX, uint256 amountY)\",\n]);\n\nconst lbFactoryAbi = parseAbi([\n \"function getNumberOfLBPairs() external view returns (uint256)\",\n \"function getLBPairAtIndex(uint256 index) external view returns (address)\",\n]);\n\nconst lbPairAbi = parseAbi([\n \"function getLBHooksParameters() external view returns (bytes32)\",\n \"function getActiveId() external view returns (uint24)\",\n \"function getBinStep() external view returns (uint16)\",\n \"function getTokenX() external view returns (address)\",\n \"function getTokenY() external view returns (address)\",\n \"function balanceOf(address account, uint256 id) external view returns (uint256)\",\n \"function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory)\",\n]);\n\nconst lbRewarderAbi = parseAbi([\n \"function getRewardToken() external view returns (address)\",\n \"function getRewardedRange() external view returns (uint256 minBinId, uint256 maxBinId)\",\n \"function getPendingRewards(address user, uint256[] calldata ids) external view returns (uint256 pendingRewards)\",\n \"function claim(address user, uint256[] calldata ids) external\",\n \"function getPid() external view returns (uint256)\",\n \"function isStopped() external view returns (bool)\",\n \"function getLBPair() external view returns (address)\",\n \"function getMasterChef() external view returns (address)\",\n]);\n\nconst masterChefAbi = parseAbi([\n \"function getMoePerSecond() external view returns (uint256)\",\n \"function getTreasuryShare() external view returns (uint256)\",\n \"function getStaticShare() external view returns (uint256)\",\n \"function getVeMoe() external view returns (address)\",\n]);\n\nconst veMoeAbi = parseAbi([\n \"function getWeight(uint256 pid) external view returns (uint256)\",\n \"function getTotalWeight() external view returns (uint256)\",\n \"function getTopPoolIds() external view returns (uint256[] memory)\",\n]);\n\nconst lbPairBinAbi = parseAbi([\n \"function getBin(uint24 id) external view returns (uint128 reserveX, uint128 reserveY)\",\n \"function getActiveId() external view returns (uint24)\",\n]);\n\nconst lbQuoterAbi = parseAbi([\n \"function findBestPathFromAmountIn(address[] calldata route, uint128 amountIn) external view returns ((address[] route, address[] pairs, uint256[] binSteps, uint256[] versions, uint128[] amounts, uint128[] virtualAmountsWithoutSlippage, uint128[] fees))\",\n]);\n\nconst erc20Abi = parseAbi([\n \"function symbol() external view returns (string)\",\n]);\n\n// ============================================================\n// Types\n// ============================================================\n\nexport interface LBAddLiquidityParams {\n pool: Address;\n tokenX: Address;\n tokenY: Address;\n binStep: number;\n amountX: bigint;\n amountY: bigint;\n /** Number of bins on each side of active bin to distribute across (default: 5) */\n numBins?: number;\n /** Active bin id desired (defaults to on-chain query if rpcUrl provided) */\n activeIdDesired?: number;\n recipient: Address;\n deadline?: bigint;\n}\n\nexport interface LBRemoveLiquidityParams {\n tokenX: Address;\n tokenY: Address;\n binStep: number;\n binIds: number[];\n /** Amount of LB tokens to remove per bin (in order matching binIds) */\n amounts: bigint[];\n amountXMin?: bigint;\n amountYMin?: bigint;\n recipient: Address;\n deadline?: bigint;\n}\n\nexport interface LBPosition {\n binId: number;\n balance: bigint;\n}\n\nexport interface RewardedPool {\n pool: Address;\n rewarder: Address;\n rewardToken: Address;\n minBinId: number;\n maxBinId: number;\n pid: number;\n stopped: boolean;\n tokenX: Address;\n tokenY: Address;\n symbolX: string;\n symbolY: string;\n isTopPool: boolean;\n moePerDay: number;\n rangeTvlUsd: number;\n aprPercent: number;\n rewardedBins: number;\n}\n\n// ============================================================\n// Helpers\n// ============================================================\n\n/** Decode address using a generic address ABI */\nconst _addressAbi = parseAbi([\"function f() external view returns (address)\"]);\nfunction decodeAddressResult(data: Hex | null): Address | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _addressAbi, functionName: \"f\", data }) as Address;\n } catch {\n return null;\n }\n}\n\n/** Decode uint256 from multicall returnData */\nconst _uint256Abi = parseAbi([\"function f() external view returns (uint256)\"]);\nfunction decodeUint256Result(data: Hex | null): bigint | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _uint256Abi, functionName: \"f\", data }) as bigint;\n } catch {\n return null;\n }\n}\n\n/** Decode bool from multicall returnData */\nconst _boolAbi = parseAbi([\"function f() external view returns (bool)\"]);\nfunction decodeBoolResult(data: Hex | null): boolean | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _boolAbi, functionName: \"f\", data }) as boolean;\n } catch {\n return null;\n }\n}\n\n/** Decode string from multicall returnData */\nfunction decodeStringResult(data: Hex | null): string {\n if (!data) return \"?\";\n try {\n return decodeFunctionResult({ abi: erc20Abi, functionName: \"symbol\", data }) as string;\n } catch {\n return \"?\";\n }\n}\n\n/** Decode getRewardedRange (returns (uint256, uint256)) */\nconst _rangeAbi = parseAbi([\"function f() external view returns (uint256 minBinId, uint256 maxBinId)\"]);\nfunction decodeRangeResult(data: Hex | null): [bigint, bigint] | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _rangeAbi, functionName: \"f\", data }) as [bigint, bigint];\n } catch {\n return null;\n }\n}\n\n/** Decode getBin result (uint128, uint128) */\nconst _binAbi = parseAbi([\"function f() external view returns (uint128 reserveX, uint128 reserveY)\"]);\nfunction decodeBinResult(data: Hex | null): [bigint, bigint] | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _binAbi, functionName: \"f\", data }) as [bigint, bigint];\n } catch {\n return null;\n }\n}\n\n/** Decode uint256[] (e.g. getTopPoolIds) */\nconst _uint256ArrayAbi = parseAbi([\"function f() external view returns (uint256[] memory)\"]);\nfunction decodeUint256ArrayResult(data: Hex | null): bigint[] | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _uint256ArrayAbi, functionName: \"f\", data }) as bigint[];\n } catch {\n return null;\n }\n}\n\n/** Extract rewarder address from LB hooks params (lower 20 bytes of bytes32) */\nfunction extractRewarderAddress(hooksParams: Hex): Address | null {\n // hooksParams is a 32-byte hex string (0x + 64 hex chars)\n if (!hooksParams || hooksParams === \"0x0000000000000000000000000000000000000000000000000000000000000000\") {\n return null;\n }\n // Lower 20 bytes = last 40 hex characters of the 64-char data portion\n const hex = hooksParams.slice(2); // strip 0x\n if (hex.length < 64) return null;\n const addrHex = hex.slice(24, 64); // bytes 12..31 = lower 20 bytes\n if (addrHex === \"0000000000000000000000000000000000000000\") return null;\n return `0x${addrHex}` as Address;\n}\n\n/** Build uniform distribution arrays for LB add liquidity.\n *\n * Distribution rules:\n * - Bins strictly below active: only tokenY (distributionX[i]=0, distributionY[i]=share)\n * - Bin at active: tokenX and tokenY split 50/50\n * - Bins strictly above active: only tokenX (distributionX[i]=share, distributionY[i]=0)\n *\n * distributionX / distributionY sum to 1e18 respectively.\n */\nfunction buildUniformDistribution(\n deltaIds: number[],\n): { distributionX: bigint[]; distributionY: bigint[] } {\n const PRECISION = 10n ** 18n;\n const n = deltaIds.length;\n\n // Count how many bins receive X and Y\n const xBins = deltaIds.filter((d) => d >= 0).length; // active + above\n const yBins = deltaIds.filter((d) => d <= 0).length; // active + below\n\n const distributionX: bigint[] = [];\n const distributionY: bigint[] = [];\n\n for (const delta of deltaIds) {\n // X share: bins at or above active\n const xShare = delta >= 0 && xBins > 0 ? PRECISION / BigInt(xBins) : 0n;\n // Y share: bins at or below active\n const yShare = delta <= 0 && yBins > 0 ? PRECISION / BigInt(yBins) : 0n;\n distributionX.push(xShare);\n distributionY.push(yShare);\n }\n\n // Correct rounding on the active bin (index where delta === 0)\n // The sum must be exactly PRECISION; adjust the first qualifying element\n const xSum = distributionX.reduce((a, b) => a + b, 0n);\n const ySum = distributionY.reduce((a, b) => a + b, 0n);\n if (xSum > 0n && xSum !== PRECISION) {\n const firstX = distributionX.findIndex((v) => v > 0n);\n if (firstX !== -1) distributionX[firstX] += PRECISION - xSum;\n }\n if (ySum > 0n && ySum !== PRECISION) {\n const firstY = distributionY.findIndex((v) => v > 0n);\n if (firstY !== -1) distributionY[firstY] += PRECISION - ySum;\n }\n\n return { distributionX, distributionY };\n}\n\n// ============================================================\n// Adapter\n// ============================================================\n\nexport class MerchantMoeLBAdapter {\n private readonly protocolName: string;\n private readonly lbRouter: Address;\n private readonly lbFactory: Address;\n private readonly lbQuoter?: Address;\n private readonly rpcUrl?: string;\n /** WMNT address (lb_mid_wmnt in config) used for MOE price routing */\n private readonly wmnt?: Address;\n /** USDT address (lb_mid_usdt in config) used for MNT/USD price routing */\n private readonly usdt?: Address;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const lbRouter = entry.contracts?.[\"lb_router\"];\n if (!lbRouter) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'lb_router' contract address\");\n }\n const lbFactory = entry.contracts?.[\"lb_factory\"];\n if (!lbFactory) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'lb_factory' contract address\");\n }\n this.lbRouter = lbRouter;\n this.lbFactory = lbFactory;\n this.lbQuoter = entry.contracts?.[\"lb_quoter\"];\n this.wmnt = entry.contracts?.[\"lb_mid_wmnt\"];\n this.usdt = entry.contracts?.[\"lb_mid_usdt\"];\n this.rpcUrl = rpcUrl;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n private requireRpc(): string {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(`[${this.protocolName}] RPC URL required`);\n }\n return this.rpcUrl;\n }\n\n /**\n * Build an addLiquidity transaction for a Liquidity Book pair.\n * Distributes tokenX/tokenY uniformly across active bin ± numBins.\n */\n async buildAddLiquidity(params: LBAddLiquidityParams): Promise<DeFiTx> {\n const numBins = params.numBins ?? 5;\n const deadline = params.deadline ?? BigInt(\"18446744073709551615\");\n\n // Resolve active bin id\n let activeIdDesired = params.activeIdDesired;\n if (activeIdDesired === undefined) {\n const rpcUrl = this.requireRpc();\n const client = createPublicClient({ transport: http(rpcUrl) });\n const activeId = await client.readContract({\n address: params.pool,\n abi: lbPairAbi,\n functionName: \"getActiveId\",\n });\n activeIdDesired = activeId as number;\n }\n\n // Build delta IDs: [-numBins, ..., -1, 0, 1, ..., numBins]\n const deltaIds: number[] = [];\n for (let d = -numBins; d <= numBins; d++) {\n deltaIds.push(d);\n }\n\n const { distributionX, distributionY } = buildUniformDistribution(deltaIds);\n\n const data = encodeFunctionData({\n abi: lbRouterAbi,\n functionName: \"addLiquidity\",\n args: [\n {\n tokenX: params.tokenX,\n tokenY: params.tokenY,\n binStep: BigInt(params.binStep),\n amountX: params.amountX,\n amountY: params.amountY,\n amountXMin: 0n,\n amountYMin: 0n,\n activeIdDesired: BigInt(activeIdDesired),\n idSlippage: BigInt(numBins + 2),\n deltaIds: deltaIds.map(BigInt),\n distributionX,\n distributionY,\n to: params.recipient,\n refundTo: params.recipient,\n deadline,\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] LB addLiquidity ${params.amountX} tokenX + ${params.amountY} tokenY across ${deltaIds.length} bins`,\n to: this.lbRouter,\n data,\n value: 0n,\n gas_estimate: 800_000,\n approvals: [\n { token: params.tokenX, spender: this.lbRouter, amount: params.amountX },\n { token: params.tokenY, spender: this.lbRouter, amount: params.amountY },\n ],\n };\n }\n\n /**\n * Build a removeLiquidity transaction for specific LB bins.\n */\n async buildRemoveLiquidity(params: LBRemoveLiquidityParams): Promise<DeFiTx> {\n const deadline = params.deadline ?? BigInt(\"18446744073709551615\");\n\n const data = encodeFunctionData({\n abi: lbRouterAbi,\n functionName: \"removeLiquidity\",\n args: [\n params.tokenX,\n params.tokenY,\n params.binStep,\n params.amountXMin ?? 0n,\n params.amountYMin ?? 0n,\n params.binIds.map(BigInt),\n params.amounts,\n params.recipient,\n deadline,\n ],\n });\n\n return {\n description: `[${this.protocolName}] LB removeLiquidity from ${params.binIds.length} bins`,\n to: this.lbRouter,\n data,\n value: 0n,\n gas_estimate: 600_000,\n };\n }\n\n /**\n * Auto-detect bin IDs for a pool from the rewarder's rewarded range.\n * Falls back to active bin ± 50 scan if no rewarder exists.\n */\n private async autoDetectBins(pool: Address): Promise<number[]> {\n const rpcUrl = this.requireRpc();\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n const hooksParams = await client.readContract({\n address: pool,\n abi: lbPairAbi,\n functionName: \"getLBHooksParameters\",\n }) as Hex;\n\n const rewarder = extractRewarderAddress(hooksParams);\n if (rewarder) {\n const range = await client.readContract({\n address: rewarder,\n abi: lbRewarderAbi,\n functionName: \"getRewardedRange\",\n }) as [bigint, bigint];\n const min = Number(range[0]);\n const max = Number(range[1]);\n const ids: number[] = [];\n for (let b = min; b <= max; b++) ids.push(b);\n return ids;\n }\n\n // No rewarder: scan active bin ± 50\n const activeId = await client.readContract({\n address: pool,\n abi: lbPairAbi,\n functionName: \"getActiveId\",\n }) as number;\n const ids: number[] = [];\n for (let b = activeId - 50; b <= activeId + 50; b++) ids.push(b);\n return ids;\n }\n\n /**\n * Get pending MOE rewards for a user across specified bin IDs.\n * If binIds is omitted, auto-detects from the rewarder's rewarded range.\n * Reads the rewarder address from the pool's hooks parameters.\n */\n async getPendingRewards(user: Address, pool: Address, binIds?: number[]): Promise<RewardInfo[]> {\n const rpcUrl = this.requireRpc();\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n const hooksParams = await client.readContract({\n address: pool,\n abi: lbPairAbi,\n functionName: \"getLBHooksParameters\",\n }) as Hex;\n\n const rewarder = extractRewarderAddress(hooksParams);\n if (!rewarder) {\n return [];\n }\n\n // Auto-detect bins from rewarder range if not provided\n let resolvedBinIds = binIds;\n if (!resolvedBinIds || resolvedBinIds.length === 0) {\n const range = await client.readContract({\n address: rewarder,\n abi: lbRewarderAbi,\n functionName: \"getRewardedRange\",\n }) as [bigint, bigint];\n const min = Number(range[0]);\n const max = Number(range[1]);\n resolvedBinIds = [];\n for (let b = min; b <= max; b++) resolvedBinIds.push(b);\n }\n\n const [pending, rewardToken] = await Promise.all([\n client.readContract({\n address: rewarder,\n abi: lbRewarderAbi,\n functionName: \"getPendingRewards\",\n args: [user, resolvedBinIds.map(BigInt)],\n }),\n client.readContract({\n address: rewarder,\n abi: lbRewarderAbi,\n functionName: \"getRewardToken\",\n }),\n ]);\n\n return [\n {\n token: rewardToken as Address,\n symbol: \"MOE\",\n amount: pending as bigint,\n },\n ];\n }\n\n /**\n * Build a claim rewards transaction for specific LB bins.\n * If binIds is omitted, auto-detects from the rewarder's rewarded range.\n */\n async buildClaimRewards(user: Address, pool: Address, binIds?: number[]): Promise<DeFiTx> {\n const rpcUrl = this.requireRpc();\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n const hooksParams = await client.readContract({\n address: pool,\n abi: lbPairAbi,\n functionName: \"getLBHooksParameters\",\n }) as Hex;\n\n const rewarder = extractRewarderAddress(hooksParams);\n if (!rewarder) {\n throw new DefiError(\"CONTRACT_ERROR\", `[${this.protocolName}] Pool ${pool} has no active rewarder`);\n }\n\n // Auto-detect bins from rewarder range if not provided\n let resolvedBinIds = binIds;\n if (!resolvedBinIds || resolvedBinIds.length === 0) {\n const range = await client.readContract({\n address: rewarder,\n abi: lbRewarderAbi,\n functionName: \"getRewardedRange\",\n }) as [bigint, bigint];\n const min = Number(range[0]);\n const max = Number(range[1]);\n resolvedBinIds = [];\n for (let b = min; b <= max; b++) resolvedBinIds.push(b);\n }\n\n const data = encodeFunctionData({\n abi: lbRewarderAbi,\n functionName: \"claim\",\n args: [user, resolvedBinIds.map(BigInt)],\n });\n\n return {\n description: `[${this.protocolName}] LB claim rewards for ${resolvedBinIds.length} bins`,\n to: rewarder,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n /**\n * Discover all active rewarded LB pools by iterating the factory.\n * Uses 7 multicall batches to minimise RPC round-trips and avoid 429s.\n *\n * Batch 1: getNumberOfLBPairs(), then getLBPairAtIndex(i) for all i\n * Batch 2: getLBHooksParameters() for all pairs → extract rewarder addresses\n * Batch 3: isStopped/getRewardedRange/getRewardToken/getPid/getMasterChef for each rewarder\n * Batch 4: getTokenX/getTokenY for each rewarded pair, then symbol() for unique tokens\n * Batch 5: Bootstrap MasterChef→VeMoe, then getMoePerSecond/getTreasuryShare/getStaticShare/getTotalWeight/getTopPoolIds\n * Batch 6: VeMoe.getWeight(pid) for each rewarded pool\n * Batch 7: Pool.getBin(binId) for all bins in rewarded range of each pool\n * Price: LB Quoter findBestPathFromAmountIn for MOE/WMNT and WMNT/USDT prices\n */\n async discoverRewardedPools(): Promise<RewardedPool[]> {\n const rpcUrl = this.requireRpc();\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n // --- Batch 1a: get pair count ---\n const pairCount = await client.readContract({\n address: this.lbFactory,\n abi: lbFactoryAbi,\n functionName: \"getNumberOfLBPairs\",\n }) as bigint;\n\n const count = Number(pairCount);\n if (count === 0) return [];\n\n // --- Batch 1b: getLBPairAtIndex for all indices ---\n const batch1Calls: Array<[Address, Hex]> = Array.from({ length: count }, (_, i) => [\n this.lbFactory,\n encodeFunctionData({ abi: lbFactoryAbi, functionName: \"getLBPairAtIndex\", args: [BigInt(i)] }),\n ]);\n const batch1Results = await multicallRead(rpcUrl, batch1Calls);\n\n const pairAddresses: Address[] = batch1Results\n .map((r) => decodeAddressResult(r))\n .filter((a): a is Address => a !== null);\n\n if (pairAddresses.length === 0) return [];\n\n // --- Batch 2: getLBHooksParameters for all pairs ---\n const batch2Calls: Array<[Address, Hex]> = pairAddresses.map((pair) => [\n pair,\n encodeFunctionData({ abi: lbPairAbi, functionName: \"getLBHooksParameters\" }),\n ]);\n const batch2Results = await multicallRead(rpcUrl, batch2Calls);\n\n // Filter pairs with a rewarder\n const rewardedPairs: Array<{ pool: Address; rewarder: Address }> = [];\n for (let i = 0; i < pairAddresses.length; i++) {\n const raw = batch2Results[i];\n if (!raw) continue;\n // getLBHooksParameters returns bytes32 — decode as raw bytes32 value\n let hooksBytes: Hex;\n try {\n const _bytes32Abi = parseAbi([\"function f() external view returns (bytes32)\"]);\n hooksBytes = decodeFunctionResult({ abi: _bytes32Abi, functionName: \"f\", data: raw }) as Hex;\n } catch {\n continue;\n }\n const rewarder = extractRewarderAddress(hooksBytes);\n if (rewarder) {\n rewardedPairs.push({ pool: pairAddresses[i]!, rewarder });\n }\n }\n\n if (rewardedPairs.length === 0) return [];\n\n // --- Batch 3: rewarder details (5 calls per rewarder, interleaved) ---\n const batch3Calls: Array<[Address, Hex]> = [];\n for (const { rewarder } of rewardedPairs) {\n batch3Calls.push([rewarder, encodeFunctionData({ abi: lbRewarderAbi, functionName: \"isStopped\" })]);\n batch3Calls.push([rewarder, encodeFunctionData({ abi: lbRewarderAbi, functionName: \"getRewardedRange\" })]);\n batch3Calls.push([rewarder, encodeFunctionData({ abi: lbRewarderAbi, functionName: \"getRewardToken\" })]);\n batch3Calls.push([rewarder, encodeFunctionData({ abi: lbRewarderAbi, functionName: \"getPid\" })]);\n batch3Calls.push([rewarder, encodeFunctionData({ abi: lbRewarderAbi, functionName: \"getMasterChef\" })]);\n }\n const batch3Results = await multicallRead(rpcUrl, batch3Calls);\n\n // --- Batch 4a: getTokenX / getTokenY for rewarded pairs ---\n const batch4aCalls: Array<[Address, Hex]> = [];\n for (const { pool } of rewardedPairs) {\n batch4aCalls.push([pool, encodeFunctionData({ abi: lbPairAbi, functionName: \"getTokenX\" })]);\n batch4aCalls.push([pool, encodeFunctionData({ abi: lbPairAbi, functionName: \"getTokenY\" })]);\n }\n const batch4aResults = await multicallRead(rpcUrl, batch4aCalls);\n\n // Collect unique token addresses for symbol lookup\n const tokenXAddresses: Array<Address | null> = [];\n const tokenYAddresses: Array<Address | null> = [];\n for (let i = 0; i < rewardedPairs.length; i++) {\n tokenXAddresses.push(decodeAddressResult(batch4aResults[i * 2] ?? null));\n tokenYAddresses.push(decodeAddressResult(batch4aResults[i * 2 + 1] ?? null));\n }\n\n const uniqueTokens = Array.from(\n new Set([...tokenXAddresses, ...tokenYAddresses].filter((a): a is Address => a !== null)),\n );\n\n // --- Batch 4b: symbol() for each unique token ---\n const batch4bCalls: Array<[Address, Hex]> = uniqueTokens.map((token) => [\n token,\n encodeFunctionData({ abi: erc20Abi, functionName: \"symbol\" }),\n ]);\n const batch4bResults = await multicallRead(rpcUrl, batch4bCalls);\n const symbolMap = new Map<Address, string>();\n for (let i = 0; i < uniqueTokens.length; i++) {\n symbolMap.set(uniqueTokens[i]!, decodeStringResult(batch4bResults[i] ?? null));\n }\n\n // Extract per-pool data from batch 3 (5 calls per rewarder)\n const STRIDE3 = 5;\n const poolData: Array<{\n stopped: boolean;\n range: [bigint, bigint] | null;\n rewardToken: Address | null;\n pid: number;\n masterChef: Address | null;\n }> = [];\n for (let i = 0; i < rewardedPairs.length; i++) {\n const base = i * STRIDE3;\n poolData.push({\n stopped: decodeBoolResult(batch3Results[base] ?? null) ?? false,\n range: decodeRangeResult(batch3Results[base + 1] ?? null),\n rewardToken: decodeAddressResult(batch3Results[base + 2] ?? null),\n pid: Number(decodeUint256Result(batch3Results[base + 3] ?? null) ?? 0n),\n masterChef: decodeAddressResult(batch3Results[base + 4] ?? null),\n });\n }\n\n // --- Batch 5: Bootstrap MasterChef/VeMoe, then fetch global emission params ---\n // Find the first valid MasterChef address from the rewarders\n const masterChefAddr = poolData.map((d) => d.masterChef).find((a): a is Address => a !== null) ?? null;\n\n let moePerDay = 0;\n let topPoolIds = new Set<number>();\n let totalWeightRaw = 0n;\n let veMoeAddr: Address | null = null;\n\n if (masterChefAddr) {\n // First get VeMoe address from MasterChef\n veMoeAddr = await client.readContract({\n address: masterChefAddr,\n abi: masterChefAbi,\n functionName: \"getVeMoe\",\n }) as Address;\n\n // Batch 5: MasterChef global data + VeMoe global data\n const batch5Calls: Array<[Address, Hex]> = [\n [masterChefAddr, encodeFunctionData({ abi: masterChefAbi, functionName: \"getMoePerSecond\" })],\n [masterChefAddr, encodeFunctionData({ abi: masterChefAbi, functionName: \"getTreasuryShare\" })],\n [masterChefAddr, encodeFunctionData({ abi: masterChefAbi, functionName: \"getStaticShare\" })],\n [veMoeAddr, encodeFunctionData({ abi: veMoeAbi, functionName: \"getTotalWeight\" })],\n [veMoeAddr, encodeFunctionData({ abi: veMoeAbi, functionName: \"getTopPoolIds\" })],\n ];\n const batch5Results = await multicallRead(rpcUrl, batch5Calls);\n\n const moePerSecRaw = decodeUint256Result(batch5Results[0] ?? null) ?? 0n;\n const treasuryShareRaw = decodeUint256Result(batch5Results[1] ?? null) ?? 0n;\n const staticShareRaw = decodeUint256Result(batch5Results[2] ?? null) ?? 0n;\n totalWeightRaw = decodeUint256Result(batch5Results[3] ?? null) ?? 0n;\n const topPoolIdsRaw = decodeUint256ArrayResult(batch5Results[4] ?? null) ?? [];\n\n topPoolIds = new Set(topPoolIdsRaw.map(Number));\n\n // Shares are fixed-point 1e18 fractions\n const PRECISION = 10n ** 18n;\n // net_moe_per_sec = total × (1 - treasury) × (1 - static)\n // expressed in bigint arithmetic to avoid float truncation\n const netPerSec =\n (moePerSecRaw * (PRECISION - treasuryShareRaw) / PRECISION) *\n (PRECISION - staticShareRaw) / PRECISION;\n\n // Convert to human-readable MOE/day (MOE has 18 decimals)\n // This is the total net MOE/day that flows to dynamic (VeMoe) pools\n moePerDay = Number(netPerSec * 86400n) / 1e18;\n }\n\n // --- Batch 6: VeMoe.getWeight(pid) for each rewarded pool ---\n const weightByPid = new Map<number, bigint>();\n if (veMoeAddr && rewardedPairs.length > 0) {\n const batch6Calls: Array<[Address, Hex]> = poolData.map((d) => [\n veMoeAddr!,\n encodeFunctionData({ abi: veMoeAbi, functionName: \"getWeight\", args: [BigInt(d.pid)] }),\n ]);\n const batch6Results = await multicallRead(rpcUrl, batch6Calls);\n for (let i = 0; i < poolData.length; i++) {\n weightByPid.set(poolData[i]!.pid, decodeUint256Result(batch6Results[i] ?? null) ?? 0n);\n }\n }\n\n // --- Price: MOE and WMNT prices in USD via LB Quoter ---\n // Route: MOE → WMNT → USDT (MOE has 18 decimals, WMNT has 18, USDT has 6)\n let moePriceUsd = 0;\n let wmntPriceUsd = 0;\n const MOE_ADDR = \"0x4515A45337F461A11Ff0FE8aBF3c606AE5dC00c9\" as Address;\n if (this.lbQuoter && this.wmnt && this.usdt) {\n try {\n const [moeWmntQuote, wmntUsdtQuote] = await Promise.all([\n client.readContract({\n address: this.lbQuoter,\n abi: lbQuoterAbi,\n functionName: \"findBestPathFromAmountIn\",\n args: [[MOE_ADDR, this.wmnt], 10n ** 18n],\n }),\n client.readContract({\n address: this.lbQuoter,\n abi: lbQuoterAbi,\n functionName: \"findBestPathFromAmountIn\",\n args: [[this.wmnt, this.usdt], 10n ** 18n],\n }),\n ]);\n // amounts[last] is the output amount (USDT has 6 decimals, WMNT has 18)\n const moeInWmnt = Number((moeWmntQuote as unknown as { amounts: bigint[] }).amounts.at(-1) ?? 0n) / 1e18;\n wmntPriceUsd = Number((wmntUsdtQuote as unknown as { amounts: bigint[] }).amounts.at(-1) ?? 0n) / 1e6;\n moePriceUsd = moeInWmnt * wmntPriceUsd;\n } catch {\n // Price fetch failed — APR will be 0\n }\n }\n\n // --- Batch 7: Pool.getBin(binId) for all bins in rewarded range ---\n // Build flat list of (poolIndex, binId) for all rewarded bins\n type BinRequest = { poolIdx: number; binId: number };\n const binRequests: BinRequest[] = [];\n for (let i = 0; i < rewardedPairs.length; i++) {\n const range = poolData[i]!.range;\n if (!range) continue;\n const minBin = Number(range[0]);\n const maxBin = Number(range[1]);\n for (let b = minBin; b <= maxBin; b++) {\n binRequests.push({ poolIdx: i, binId: b });\n }\n }\n\n // Bin reserves keyed by pool index\n // reserveX[poolIdx][binId] and reserveY[poolIdx][binId]\n const binReservesX = new Map<number, Map<number, bigint>>();\n const binReservesY = new Map<number, Map<number, bigint>>();\n\n if (binRequests.length > 0) {\n const batch7Calls: Array<[Address, Hex]> = binRequests.map(({ poolIdx, binId }) => [\n rewardedPairs[poolIdx]!.pool,\n encodeFunctionData({ abi: lbPairBinAbi, functionName: \"getBin\", args: [binId] }),\n ]);\n const batch7Results = await multicallRead(rpcUrl, batch7Calls);\n\n for (let j = 0; j < binRequests.length; j++) {\n const { poolIdx, binId } = binRequests[j]!;\n const decoded = decodeBinResult(batch7Results[j] ?? null);\n if (!decoded) continue;\n if (!binReservesX.has(poolIdx)) {\n binReservesX.set(poolIdx, new Map());\n binReservesY.set(poolIdx, new Map());\n }\n binReservesX.get(poolIdx)!.set(binId, decoded[0]);\n binReservesY.get(poolIdx)!.set(binId, decoded[1]);\n }\n }\n\n // --- Assemble results ---\n // Token price classification by symbol (USD)\n // Stablecoins → $1; WMNT/MNT → wmntPriceUsd; MOE → moePriceUsd; unknown → 0\n const stableSymbols = new Set([\"USDT\", \"USDC\", \"MUSD\", \"AUSD\", \"USDY\", \"FDUSD\"]);\n const mntSymbols = new Set([\"WMNT\", \"MNT\"]);\n const moeSymbols = new Set([\"MOE\"]);\n // USDT/USDC on Mantle have 6 decimals; other stable tokens have 18\n const sixDecimalStables = new Set([\"USDT\", \"USDC\", \"FDUSD\"]);\n\n const getTokenPriceUsd = (sym: string): number => {\n if (stableSymbols.has(sym)) return 1;\n if (mntSymbols.has(sym)) return wmntPriceUsd;\n if (moeSymbols.has(sym)) return moePriceUsd;\n return 0;\n };\n\n const getTokenDecimals = (sym: string): number => {\n return sixDecimalStables.has(sym) ? 6 : 18;\n };\n\n const results: RewardedPool[] = [];\n for (let i = 0; i < rewardedPairs.length; i++) {\n const { pool, rewarder } = rewardedPairs[i]!;\n const data = poolData[i]!;\n\n const tokenX = tokenXAddresses[i] ?? (\"0x0000000000000000000000000000000000000000\" as Address);\n const tokenY = tokenYAddresses[i] ?? (\"0x0000000000000000000000000000000000000000\" as Address);\n const symX = symbolMap.get(tokenX) ?? \"?\";\n const symY = symbolMap.get(tokenY) ?? \"?\";\n\n const isTopPool = topPoolIds.has(data.pid);\n const weight = weightByPid.get(data.pid) ?? 0n;\n\n // Pool's MOE/day = total_net_moe_per_day × weight / total_weight\n // Only top pools (in VeMoe top list) receive dynamic emissions\n let poolMoePerDay = 0;\n if (isTopPool && totalWeightRaw > 0n && weight > 0n) {\n poolMoePerDay = moePerDay * (Number(weight) / Number(totalWeightRaw));\n }\n\n // Range TVL: sum bin reserves × token prices\n const rxMap = binReservesX.get(i);\n const ryMap = binReservesY.get(i);\n const range = data.range;\n let rangeTvlUsd = 0;\n let rewardedBins = 0;\n\n if (range) {\n const minBin = Number(range[0]);\n const maxBin = Number(range[1]);\n rewardedBins = maxBin - minBin + 1;\n if (rxMap && ryMap) {\n const priceX = getTokenPriceUsd(symX);\n const priceY = getTokenPriceUsd(symY);\n const decX = getTokenDecimals(symX);\n const decY = getTokenDecimals(symY);\n for (let b = minBin; b <= maxBin; b++) {\n const rx = rxMap.get(b) ?? 0n;\n const ry = ryMap.get(b) ?? 0n;\n rangeTvlUsd += (Number(rx) / 10 ** decX) * priceX;\n rangeTvlUsd += (Number(ry) / 10 ** decY) * priceY;\n }\n }\n }\n\n // APR = (poolMoePerDay * moePriceUsd * 365) / rangeTvlUsd * 100\n const aprPercent =\n rangeTvlUsd > 0 && moePriceUsd > 0\n ? (poolMoePerDay * moePriceUsd * 365 / rangeTvlUsd) * 100\n : 0;\n\n results.push({\n pool,\n rewarder,\n rewardToken: data.rewardToken ?? (\"0x0000000000000000000000000000000000000000\" as Address),\n minBinId: range ? Number(range[0]) : 0,\n maxBinId: range ? Number(range[1]) : 0,\n pid: data.pid,\n stopped: data.stopped,\n tokenX,\n tokenY,\n symbolX: symX,\n symbolY: symY,\n isTopPool,\n moePerDay: poolMoePerDay,\n rangeTvlUsd,\n aprPercent,\n rewardedBins,\n });\n }\n\n return results;\n }\n\n /**\n * Get a user's LB positions (bin balances) across a range of bin IDs.\n * If binIds is omitted, auto-detects from the rewarder's rewarded range (or active ± 50).\n */\n async getUserPositions(user: Address, pool: Address, binIds?: number[]): Promise<LBPosition[]> {\n const rpcUrl = this.requireRpc();\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n const resolvedBinIds = (binIds && binIds.length > 0) ? binIds : await this.autoDetectBins(pool);\n\n const accounts = resolvedBinIds.map(() => user);\n const ids = resolvedBinIds.map(BigInt);\n\n const balances = await client.readContract({\n address: pool,\n abi: lbPairAbi,\n functionName: \"balanceOfBatch\",\n args: [accounts, ids],\n }) as bigint[];\n\n return resolvedBinIds\n .map((binId, i) => ({ binId, balance: balances[i] ?? 0n }))\n .filter((p) => p.balance > 0n);\n }\n}\n","import {\n decodeAbiParameters,\n encodeFunctionData,\n encodeAbiParameters,\n http,\n createPublicClient,\n keccak256,\n parseAbi,\n decodeFunctionResult,\n zeroAddress,\n} from \"viem\";\nimport type { Address, Hex } from \"viem\";\n\nimport { DefiError, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { DeFiTx } from \"@hypurrquant/defi-core\";\n\n// ─── Constants ────────────────────────────────────────────────────────────────\n\n/** KITTEN reward token on Hyper EVM */\nconst KITTEN_TOKEN: Address = \"0x618275f8efe54c2afa87bfb9f210a52f0ff89364\";\n\n/** WHYPE bonus reward token */\nconst WHYPE_TOKEN: Address = \"0x5555555555555555555555555555555555555555\";\n\n/** Max nonce to scan when discovering incentive keys */\nconst MAX_NONCE_SCAN = 60;\n\n/** HyperEVM well-known token addresses for pool discovery (matches solidly_gauge.ts) */\nconst HYPEREVM_TOKENS: Address[] = [\n \"0x5555555555555555555555555555555555555555\", // WHYPE\n \"0xb88339CB7199b77E23DB6E890353E22632Ba630f\", // USDC\n \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\", // USDT0\n \"0xBe6727B535545C67d5cAa73dEa54865B92CF7907\", // UETH\n \"0x9FDBdA0A5e284c32744D2f17Ee5c74B284993463\", // UBTC\n \"0x111111a1a0667d36bD57c0A9f569b98057111111\", // USDH\n \"0x5d3a1Ff2b6BAb83b63cd9AD0787074081a52ef34\", // USDe\n \"0x211Cc4DD073734dA055fbF44a2b4667d5E5fE5d2\", // sUSDe\n \"0xf4D9235269a96aaDaFc9aDAe454a0618eBE37949\", // XAUt0\n \"0xfD739d4e423301CE9385c1fb8850539D657C296D\", // kHYPE\n KITTEN_TOKEN, // KITTEN\n];\n\n// ─── ABIs ─────────────────────────────────────────────────────────────────────\n\nconst farmingCenterAbi = parseAbi([\n \"function multicall(bytes[] calldata data) external payable returns (bytes[] memory results)\",\n \"function enterFarming((address rewardToken, address bonusRewardToken, address pool, uint256 nonce) key, uint256 tokenId) external\",\n \"function exitFarming((address rewardToken, address bonusRewardToken, address pool, uint256 nonce) key, uint256 tokenId) external\",\n \"function collectRewards((address rewardToken, address bonusRewardToken, address pool, uint256 nonce) key, uint256 tokenId) external\",\n \"function claimReward(address rewardToken, address to, uint128 amountRequested) external returns (uint256 reward)\",\n]);\n\nconst positionManagerAbi = parseAbi([\n \"function approveForFarming(uint256 tokenId, bool approve, address farmingAddress) external\",\n \"function farmingApprovals(uint256 tokenId) external view returns (address)\",\n]);\n\nconst eternalFarmingAbi = parseAbi([\n \"function incentives(bytes32 incentiveId) external view returns (uint256 totalReward, uint256 bonusReward, address virtualPoolAddress, uint24 minimalPositionWidth, bool deactivated, address pluginAddress)\",\n \"function getRewardInfo((address rewardToken, address bonusRewardToken, address pool, uint256 nonce) key, uint256 tokenId) external view returns (uint256 reward, uint256 bonusReward)\",\n]);\n\nconst algebraFactoryAbi = parseAbi([\n \"function poolByPair(address tokenA, address tokenB) external view returns (address pool)\",\n]);\n\n// Decode helpers\nconst _addressDecodeAbi = parseAbi([\"function f() external view returns (address)\"]);\nfunction decodeAddress(data: Hex | null): Address | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({ abi: _addressDecodeAbi, functionName: \"f\", data }) as Address;\n } catch {\n return null;\n }\n}\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface IncentiveKey {\n rewardToken: Address;\n bonusRewardToken: Address;\n pool: Address;\n nonce: bigint;\n}\n\nexport interface FarmingPool {\n pool: Address;\n key: IncentiveKey;\n totalReward: bigint;\n bonusReward: bigint;\n active: boolean;\n}\n\n// ─── Helper ───────────────────────────────────────────────────────────────────\n\n/** Compute the incentiveId hash for an IncentiveKey (keccak256(abi.encode(key))) */\nfunction incentiveId(key: IncentiveKey): Hex {\n return keccak256(\n encodeAbiParameters(\n [\n { name: \"rewardToken\", type: \"address\" },\n { name: \"bonusRewardToken\", type: \"address\" },\n { name: \"pool\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n ],\n [key.rewardToken, key.bonusRewardToken, key.pool, key.nonce],\n ),\n );\n}\n\n/** Build the enterFarming calldata (without selector overhead — for use inside multicall) */\nfunction encodeEnterFarming(key: IncentiveKey, tokenId: bigint): Hex {\n return encodeFunctionData({\n abi: farmingCenterAbi,\n functionName: \"enterFarming\",\n args: [key, tokenId],\n });\n}\n\n/** Build the exitFarming calldata */\nfunction encodeExitFarming(key: IncentiveKey, tokenId: bigint): Hex {\n return encodeFunctionData({\n abi: farmingCenterAbi,\n functionName: \"exitFarming\",\n args: [key, tokenId],\n });\n}\n\n/** Build the collectRewards calldata */\nfunction encodeCollectRewards(key: IncentiveKey, tokenId: bigint): Hex {\n return encodeFunctionData({\n abi: farmingCenterAbi,\n functionName: \"collectRewards\",\n args: [key, tokenId],\n });\n}\n\n/** Build the claimReward calldata */\nfunction encodeClaimReward(rewardToken: Address, to: Address): Hex {\n return encodeFunctionData({\n abi: farmingCenterAbi,\n functionName: \"claimReward\",\n args: [rewardToken, to, 2n ** 128n - 1n], // max uint128\n });\n}\n\n/** Encode the top-level multicall wrapping an array of calldatas */\nfunction encodeMulticall(calls: Hex[]): Hex {\n return encodeFunctionData({\n abi: farmingCenterAbi,\n functionName: \"multicall\",\n args: [calls],\n });\n}\n\n// ─── Runtime cache ───────────────────────────────────────────────────────────\n\n/** Runtime cache: pool (lowercased) → discovered nonce. Avoids repeated scans within a session. */\nconst nonceCache = new Map<string, bigint>();\n\n// ─── Adapter ──────────────────────────────────────────────────────────────────\n\nexport class KittenSwapFarmingAdapter {\n private readonly protocolName: string;\n private readonly farmingCenter: Address;\n private readonly eternalFarming: Address;\n private readonly positionManager: Address;\n private readonly rpcUrl: string;\n private readonly factory: Address | undefined;\n\n constructor(\n protocolName: string,\n farmingCenter: Address,\n eternalFarming: Address,\n positionManager: Address,\n rpcUrl: string,\n factory?: Address,\n ) {\n this.protocolName = protocolName;\n this.farmingCenter = farmingCenter;\n this.eternalFarming = eternalFarming;\n this.positionManager = positionManager;\n this.rpcUrl = rpcUrl;\n this.factory = factory;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n /**\n * Discover the active IncentiveKey for a given pool.\n * 1. Check runtime cache\n * 2. Batch-query nonces 0-60 via single multicall (61 calls)\n * 3. Return first non-zero incentive (totalReward > 0 and not deactivated)\n */\n async discoverIncentiveKey(pool: Address): Promise<IncentiveKey | null> {\n const poolLc = pool.toLowerCase();\n\n // Fast path: runtime cache\n if (nonceCache.has(poolLc)) {\n return {\n rewardToken: KITTEN_TOKEN,\n bonusRewardToken: WHYPE_TOKEN,\n pool,\n nonce: nonceCache.get(poolLc)!,\n };\n }\n\n // Build 61 multicall calls for nonces 0-60\n const calls: Array<[Address, Hex]> = [];\n const nonces: bigint[] = [];\n for (let n = 0; n <= MAX_NONCE_SCAN; n++) {\n const nonce = BigInt(n);\n nonces.push(nonce);\n const key: IncentiveKey = {\n rewardToken: KITTEN_TOKEN,\n bonusRewardToken: WHYPE_TOKEN,\n pool,\n nonce,\n };\n calls.push([\n this.eternalFarming,\n encodeFunctionData({\n abi: eternalFarmingAbi,\n functionName: \"incentives\",\n args: [incentiveId(key)],\n }),\n ]);\n }\n\n const results = await multicallRead(this.rpcUrl, calls);\n\n for (let i = 0; i < results.length; i++) {\n const data = results[i];\n if (!data || data.length < 66) continue;\n\n try {\n const decoded = decodeAbiParameters(\n [\n { name: \"totalReward\", type: \"uint256\" },\n { name: \"bonusReward\", type: \"uint256\" },\n { name: \"virtualPoolAddress\", type: \"address\" },\n { name: \"minimalPositionWidth\", type: \"uint24\" },\n { name: \"deactivated\", type: \"bool\" },\n { name: \"pluginAddress\", type: \"address\" },\n ],\n data,\n );\n\n const totalReward = decoded[0] as bigint;\n const deactivated = decoded[4] as boolean;\n\n if (totalReward > 0n && !deactivated) {\n const nonce = nonces[i]!;\n nonceCache.set(poolLc, nonce);\n return {\n rewardToken: KITTEN_TOKEN,\n bonusRewardToken: WHYPE_TOKEN,\n pool,\n nonce,\n };\n }\n } catch {\n // skip decode errors\n }\n }\n\n return null;\n }\n\n /**\n * Build approveForFarming tx on the PositionManager.\n * Required before enterFarming if not already approved.\n */\n async buildApproveForFarming(tokenId: bigint): Promise<DeFiTx | null> {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const currentApproval = await client.readContract({\n address: this.positionManager,\n abi: positionManagerAbi,\n functionName: \"farmingApprovals\",\n args: [tokenId],\n }) as Address;\n\n if (currentApproval.toLowerCase() === this.farmingCenter.toLowerCase()) {\n return null; // Already approved\n }\n\n return {\n description: `[${this.protocolName}] Approve NFT #${tokenId} for farming`,\n to: this.positionManager,\n data: encodeFunctionData({\n abi: positionManagerAbi,\n functionName: \"approveForFarming\",\n args: [tokenId, true, this.farmingCenter],\n }),\n value: 0n,\n gas_estimate: 60_000,\n };\n }\n\n /**\n * Build enterFarming tx for a position NFT.\n * Checks farming approval first and returns pre_txs if needed.\n */\n async buildEnterFarming(\n tokenId: bigint,\n pool: Address,\n _owner: Address,\n ): Promise<DeFiTx> {\n const key = await this.discoverIncentiveKey(pool);\n if (!key) {\n throw new DefiError(\n \"CONTRACT_ERROR\",\n `[${this.protocolName}] No active incentive found for pool ${pool}`,\n );\n }\n\n const approveTx = await this.buildApproveForFarming(tokenId);\n\n return {\n description: `[${this.protocolName}] Enter farming for NFT #${tokenId} in pool ${pool}`,\n to: this.farmingCenter,\n data: encodeEnterFarming(key, tokenId),\n value: 0n,\n gas_estimate: 400_000,\n pre_txs: approveTx ? [approveTx] : undefined,\n };\n }\n\n /**\n * Build a tx that exits farming for a position NFT (unstakes).\n */\n async buildExitFarming(tokenId: bigint, pool: Address): Promise<DeFiTx> {\n const key = await this.discoverIncentiveKey(pool);\n if (!key) {\n throw new DefiError(\n \"CONTRACT_ERROR\",\n `[${this.protocolName}] No active incentive found for pool ${pool}`,\n );\n }\n\n return {\n description: `[${this.protocolName}] Exit farming for NFT #${tokenId} in pool ${pool}`,\n to: this.farmingCenter,\n data: encodeExitFarming(key, tokenId),\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n /**\n * Build a multicall tx that collects rewards for a staked position and claims them.\n * Pattern: multicall([collectRewards(key, tokenId), claimReward(KITTEN, owner, max), claimReward(WHYPE, owner, max)])\n */\n async buildCollectRewards(\n tokenId: bigint,\n pool: Address,\n owner: Address,\n ): Promise<DeFiTx> {\n const key = await this.discoverIncentiveKey(pool);\n if (!key) {\n throw new DefiError(\n \"CONTRACT_ERROR\",\n `[${this.protocolName}] No active incentive found for pool ${pool}`,\n );\n }\n\n const calls: Hex[] = [\n encodeCollectRewards(key, tokenId),\n encodeClaimReward(KITTEN_TOKEN, owner),\n encodeClaimReward(WHYPE_TOKEN, owner),\n ];\n\n return {\n description: `[${this.protocolName}] Collect + claim rewards for NFT #${tokenId} in pool ${pool}`,\n to: this.farmingCenter,\n data: encodeMulticall(calls),\n value: 0n,\n gas_estimate: 400_000,\n };\n }\n\n /**\n * Build a tx that only claims already-accumulated rewards (no position change needed).\n */\n async buildClaimReward(owner: Address): Promise<DeFiTx> {\n const calls: Hex[] = [\n encodeClaimReward(KITTEN_TOKEN, owner),\n encodeClaimReward(WHYPE_TOKEN, owner),\n ];\n\n return {\n description: `[${this.protocolName}] Claim KITTEN + WHYPE farming rewards to ${owner}`,\n to: this.farmingCenter,\n data: encodeMulticall(calls),\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /**\n * Query pending rewards for a staked position NFT.\n */\n async getPendingRewards(\n tokenId: bigint,\n pool: Address,\n ): Promise<{ reward: bigint; bonusReward: bigint }> {\n const key = await this.discoverIncentiveKey(pool);\n if (!key) {\n return { reward: 0n, bonusReward: 0n };\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const result = await client.readContract({\n address: this.eternalFarming,\n abi: eternalFarmingAbi,\n functionName: \"getRewardInfo\",\n args: [key, tokenId],\n }) as readonly [bigint, bigint];\n\n return { reward: result[0], bonusReward: result[1] };\n }\n\n /**\n * Discover all KittenSwap pools with active farming incentives.\n *\n * Steps:\n * 1. Generate all unique token pair combos from HYPEREVM_TOKENS (includes KITTEN)\n * 2. Batch poolByPair calls via multicall against the Algebra factory\n * 3. For each found pool, batch-scan nonces 0-60 via multicall\n * 4. Return enriched FarmingPool[] for pools with active incentives\n */\n async discoverFarmingPools(): Promise<FarmingPool[]> {\n if (!this.factory) {\n return [];\n }\n\n // Step 1: generate all unique token pairs\n const pairs: Array<[Address, Address]> = [];\n for (let i = 0; i < HYPEREVM_TOKENS.length; i++) {\n for (let j = i + 1; j < HYPEREVM_TOKENS.length; j++) {\n pairs.push([HYPEREVM_TOKENS[i]!, HYPEREVM_TOKENS[j]!]);\n }\n }\n\n // Step 2: batch poolByPair calls\n const poolByPairCalls: Array<[Address, Hex]> = pairs.map(([tokenA, tokenB]) => [\n this.factory!,\n encodeFunctionData({\n abi: algebraFactoryAbi,\n functionName: \"poolByPair\",\n args: [tokenA, tokenB],\n }),\n ]);\n\n const poolResults = await multicallRead(this.rpcUrl, poolByPairCalls);\n\n // Collect unique non-zero pool addresses\n const poolSet = new Set<string>();\n for (const data of poolResults) {\n const addr = decodeAddress(data);\n if (addr && addr !== zeroAddress) {\n poolSet.add(addr.toLowerCase());\n }\n }\n\n if (poolSet.size === 0) return [];\n\n const pools = Array.from(poolSet) as Address[];\n\n // Step 3: for each pool, batch-scan nonces 0-60 via a single multicall per pool.\n // We build all nonce calls for all pools in one big multicall to minimize RPC round-trips.\n const NONCE_COUNT = MAX_NONCE_SCAN + 1; // 61\n const allNonceCalls: Array<[Address, Hex]> = [];\n for (const pool of pools) {\n for (let n = 0; n <= MAX_NONCE_SCAN; n++) {\n const key: IncentiveKey = {\n rewardToken: KITTEN_TOKEN,\n bonusRewardToken: WHYPE_TOKEN,\n pool: pool as Address,\n nonce: BigInt(n),\n };\n allNonceCalls.push([\n this.eternalFarming,\n encodeFunctionData({\n abi: eternalFarmingAbi,\n functionName: \"incentives\",\n args: [incentiveId(key)],\n }),\n ]);\n }\n }\n\n const allNonceResults = await multicallRead(this.rpcUrl, allNonceCalls);\n\n // Step 4: find best active incentive per pool and build result\n const results: FarmingPool[] = [];\n\n for (let pi = 0; pi < pools.length; pi++) {\n const pool = pools[pi]! as Address;\n const poolLc = pool.toLowerCase();\n const base = pi * NONCE_COUNT;\n\n let bestKey: IncentiveKey | null = null;\n let bestTotalReward = 0n;\n let bestBonusReward = 0n;\n let bestActive = false;\n\n for (let n = 0; n <= MAX_NONCE_SCAN; n++) {\n const data = allNonceResults[base + n];\n if (!data || data.length < 66) continue;\n\n try {\n const decoded = decodeAbiParameters(\n [\n { name: \"totalReward\", type: \"uint256\" },\n { name: \"bonusReward\", type: \"uint256\" },\n { name: \"virtualPoolAddress\", type: \"address\" },\n { name: \"minimalPositionWidth\", type: \"uint24\" },\n { name: \"deactivated\", type: \"bool\" },\n { name: \"pluginAddress\", type: \"address\" },\n ],\n data,\n );\n\n const totalReward = decoded[0] as bigint;\n const bonusReward = decoded[1] as bigint;\n const deactivated = decoded[4] as boolean;\n\n if (totalReward > 0n) {\n const nonce = BigInt(n);\n const isActive = !deactivated;\n\n // Prefer active incentives; among active ones, prefer higher nonce (newer)\n if (!bestKey || (isActive && !bestActive) || (isActive === bestActive && nonce > bestKey.nonce)) {\n bestKey = {\n rewardToken: KITTEN_TOKEN,\n bonusRewardToken: WHYPE_TOKEN,\n pool,\n nonce,\n };\n bestTotalReward = totalReward;\n bestBonusReward = bonusReward;\n bestActive = isActive;\n }\n }\n } catch {\n // skip decode errors\n }\n }\n\n if (bestKey) {\n // Cache the discovered nonce\n nonceCache.set(poolLc, bestKey.nonce);\n results.push({\n pool,\n key: bestKey,\n totalReward: bestTotalReward,\n bonusReward: bestBonusReward,\n active: bestActive,\n });\n }\n }\n\n return results;\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, decodeFunctionResult, zeroAddress } from \"viem\";\nimport type { Address, Hex } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n multicallRead,\n decodeU256,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n InterestRateMode,\n} from \"@hypurrquant/defi-core\";\n\nconst POOL_ABI = parseAbi([\n \"function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external\",\n \"function borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf) external\",\n \"function repay(address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf) external returns (uint256)\",\n \"function withdraw(address asset, uint256 amount, address to) external returns (uint256)\",\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n \"function getReserveData(address asset) external view returns (uint256 configuration, uint128 liquidityIndex, uint128 currentLiquidityRate, uint128 variableBorrowIndex, uint128 currentVariableBorrowRate, uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, uint16 id, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress, uint128 accruedToTreasury, uint128 unbacked, uint128 isolationModeTotalDebt)\",\n]);\n\nconst ERC20_ABI = parseAbi([\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nconst INCENTIVES_ABI = parseAbi([\n \"function getIncentivesController() external view returns (address)\",\n]);\n\nconst REWARDS_CONTROLLER_ABI = parseAbi([\n \"function getRewardsByAsset(address asset) external view returns (address[])\",\n \"function getRewardsData(address asset, address reward) external view returns (uint256 index, uint256 emissionsPerSecond, uint256 lastUpdateTimestamp, uint256 distributionEnd)\",\n]);\n\nconst POOL_PROVIDER_ABI = parseAbi([\n \"function ADDRESSES_PROVIDER() external view returns (address)\",\n]);\n\nconst ADDRESSES_PROVIDER_ABI = parseAbi([\n \"function getPriceOracle() external view returns (address)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n \"function BASE_CURRENCY_UNIT() external view returns (uint256)\",\n]);\n\nconst ERC20_DECIMALS_ABI = parseAbi([\n \"function decimals() external view returns (uint8)\",\n]);\n\nfunction u256ToF64(v: bigint): number {\n const MAX_U128 = (1n << 128n) - 1n;\n if (v > MAX_U128) return Infinity;\n return Number(v);\n}\n\nfunction decodeAddress(data: Hex | null): Address | null {\n if (!data || data.length < 66) return null;\n // ABI-encoded address: 12 bytes padding + 20 bytes address (total 32 bytes = 64 hex chars + 0x)\n return `0x${data.slice(26, 66)}` as Address;\n}\n\nfunction decodeAddressArray(data: Hex | null): Address[] {\n if (!data) return [];\n try {\n return decodeFunctionResult({\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsByAsset\",\n data,\n }) as Address[];\n } catch {\n return [];\n }\n}\n\nfunction decodeReserveData(data: Hex | null): ReturnType<typeof decodeFunctionResult> | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({\n abi: POOL_ABI,\n functionName: \"getReserveData\",\n data,\n });\n } catch {\n return null;\n }\n}\n\nfunction decodeRewardsData(data: Hex | null): [bigint, bigint, bigint, bigint] | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsData\",\n data,\n }) as [bigint, bigint, bigint, bigint];\n } catch {\n return null;\n }\n}\n\nexport class AaveV3Adapter implements ILending {\n private readonly protocolName: string;\n private readonly pool: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const pool = entry.contracts?.[\"pool\"];\n if (!pool) throw DefiError.contractError(`[${entry.name}] Missing 'pool' contract address`);\n this.pool = pool;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"supply\",\n args: [params.asset, params.amount, params.on_behalf_of, 0],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [{ token: params.asset, spender: this.pool, amount: params.amount }],\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"borrow\",\n args: [params.asset, params.amount, rateMode, 0, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"repay\",\n args: [params.asset, params.amount, rateMode, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [{ token: params.asset, spender: this.pool, amount: params.amount }],\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n\n // Batch 1: getReserveData\n const reserveCallData = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"getReserveData\",\n args: [asset],\n });\n const [reserveRaw] = await multicallRead(this.rpcUrl, [\n [this.pool, reserveCallData],\n ]).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getReserveData failed: ${e}`);\n });\n\n const reserveDecoded = decodeReserveData(reserveRaw ?? null);\n if (!reserveDecoded) {\n throw DefiError.rpcError(`[${this.protocolName}] getReserveData returned no data`);\n }\n const result = reserveDecoded as [bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint, Address, Address, Address, Address, bigint, bigint, bigint];\n\n const RAY = 1e27;\n const SECONDS_PER_YEAR = 31536000;\n\n // Convert ray rate to APY: ((1 + rate/SECONDS_PER_YEAR)^SECONDS_PER_YEAR - 1) * 100\n const toApy = (rayRate: bigint): number => {\n const rate = Number(rayRate) / RAY;\n return (Math.pow(1 + rate / SECONDS_PER_YEAR, SECONDS_PER_YEAR) - 1) * 100;\n };\n\n const supplyRate = toApy(result[2]);\n const variableRate = toApy(result[4]);\n const stableRate = toApy(result[5]);\n\n const aTokenAddress = result[8] as Address;\n const variableDebtTokenAddress = result[10] as Address;\n\n // Batch 2: totalSupply for aToken + variableDebtToken\n const [supplyRaw, borrowRaw] = await multicallRead(this.rpcUrl, [\n [aTokenAddress, encodeFunctionData({ abi: ERC20_ABI, functionName: \"totalSupply\" })],\n [variableDebtTokenAddress, encodeFunctionData({ abi: ERC20_ABI, functionName: \"totalSupply\" })],\n ]);\n const totalSupply = decodeU256(supplyRaw ?? null);\n const totalBorrow = decodeU256(borrowRaw ?? null);\n\n const utilization = totalSupply > 0n\n ? Number((totalBorrow * 10000n) / totalSupply) / 100\n : 0;\n\n // Fetch incentive/reward data (best-effort, never breaks base rates)\n const supplyRewardTokens: string[] = [];\n const borrowRewardTokens: string[] = [];\n const supplyEmissions: string[] = [];\n const borrowEmissions: string[] = [];\n\n try {\n // Batch 3: getIncentivesController (single call)\n const [controllerRaw] = await multicallRead(this.rpcUrl, [\n [aTokenAddress, encodeFunctionData({ abi: INCENTIVES_ABI, functionName: \"getIncentivesController\" })],\n ]);\n const controllerAddr = decodeAddress(controllerRaw ?? null);\n\n if (controllerAddr && controllerAddr !== zeroAddress) {\n // Batch 4: getRewardsByAsset for aToken + variableDebtToken\n const [supplyRewardsRaw, borrowRewardsRaw] = await multicallRead(this.rpcUrl, [\n [controllerAddr, encodeFunctionData({ abi: REWARDS_CONTROLLER_ABI, functionName: \"getRewardsByAsset\", args: [aTokenAddress] })],\n [controllerAddr, encodeFunctionData({ abi: REWARDS_CONTROLLER_ABI, functionName: \"getRewardsByAsset\", args: [variableDebtTokenAddress] })],\n ]);\n const supplyRewards = decodeAddressArray(supplyRewardsRaw ?? null);\n const borrowRewards = decodeAddressArray(borrowRewardsRaw ?? null);\n\n // Batch 5: all getRewardsData calls for supply + borrow combined\n const rewardsDataCalls: Array<[Address, Hex]> = [\n ...supplyRewards.map((reward): [Address, Hex] => [\n controllerAddr,\n encodeFunctionData({ abi: REWARDS_CONTROLLER_ABI, functionName: \"getRewardsData\", args: [aTokenAddress, reward] }),\n ]),\n ...borrowRewards.map((reward): [Address, Hex] => [\n controllerAddr,\n encodeFunctionData({ abi: REWARDS_CONTROLLER_ABI, functionName: \"getRewardsData\", args: [variableDebtTokenAddress, reward] }),\n ]),\n ];\n\n if (rewardsDataCalls.length > 0) {\n const rewardsDataResults = await multicallRead(this.rpcUrl, rewardsDataCalls);\n\n const supplyDataResults = rewardsDataResults.slice(0, supplyRewards.length);\n const borrowDataResults = rewardsDataResults.slice(supplyRewards.length);\n\n for (let i = 0; i < supplyRewards.length; i++) {\n const data = decodeRewardsData(supplyDataResults[i] ?? null);\n if (data && data[1] > 0n) {\n supplyRewardTokens.push(supplyRewards[i]);\n supplyEmissions.push(data[1].toString());\n }\n }\n for (let i = 0; i < borrowRewards.length; i++) {\n const data = decodeRewardsData(borrowDataResults[i] ?? null);\n if (data && data[1] > 0n) {\n borrowRewardTokens.push(borrowRewards[i]);\n borrowEmissions.push(data[1].toString());\n }\n }\n }\n }\n } catch {\n // Incentives not supported by this deployment — silently ignore\n }\n\n // Calculate incentive APY from emissions using oracle prices\n let supplyIncentiveApy: number | undefined;\n let borrowIncentiveApy: number | undefined;\n\n const hasSupplyRewards = supplyRewardTokens.length > 0;\n const hasBorrowRewards = borrowRewardTokens.length > 0;\n\n if ((hasSupplyRewards || hasBorrowRewards) && totalSupply > 0n) {\n try {\n // Pool → AddressesProvider → Oracle (sequential, each depends on previous)\n const [providerRaw] = await multicallRead(this.rpcUrl, [\n [this.pool, encodeFunctionData({ abi: POOL_PROVIDER_ABI, functionName: \"ADDRESSES_PROVIDER\" })],\n ]);\n const providerAddr = decodeAddress(providerRaw ?? null);\n if (!providerAddr) throw new Error(\"No provider address\");\n\n const [oracleRaw] = await multicallRead(this.rpcUrl, [\n [providerAddr, encodeFunctionData({ abi: ADDRESSES_PROVIDER_ABI, functionName: \"getPriceOracle\" })],\n ]);\n const oracleAddr = decodeAddress(oracleRaw ?? null);\n if (!oracleAddr) throw new Error(\"No oracle address\");\n\n // Batch 6: assetPrice + BASE_CURRENCY_UNIT + asset decimals\n const [assetPriceRaw, baseCurrencyUnitRaw, assetDecimalsRaw] = await multicallRead(this.rpcUrl, [\n [oracleAddr, encodeFunctionData({ abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [asset] })],\n [oracleAddr, encodeFunctionData({ abi: ORACLE_ABI, functionName: \"BASE_CURRENCY_UNIT\" })],\n [asset, encodeFunctionData({ abi: ERC20_DECIMALS_ABI, functionName: \"decimals\" })],\n ]);\n\n const assetPrice = decodeU256(assetPriceRaw ?? null);\n const baseCurrencyUnit = decodeU256(baseCurrencyUnitRaw ?? null);\n // decimals() returns uint8, fits in lower bits of U256 slot\n const assetDecimals = assetDecimalsRaw ? Number(decodeU256(assetDecimalsRaw)) : 18;\n\n const priceUnit = Number(baseCurrencyUnit) || 1e8;\n const assetPriceF = Number(assetPrice) / priceUnit;\n const assetDecimalsDivisor = 10 ** assetDecimals;\n\n // Collect all unique reward tokens across supply + borrow\n const allRewardTokens = Array.from(new Set([...supplyRewardTokens, ...borrowRewardTokens])) as Address[];\n\n // Batch 7: price + decimals for all reward tokens combined\n const rewardPriceCalls: Array<[Address, Hex]> = allRewardTokens.flatMap((token): Array<[Address, Hex]> => [\n [oracleAddr, encodeFunctionData({ abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [token] })],\n [token, encodeFunctionData({ abi: ERC20_DECIMALS_ABI, functionName: \"decimals\" })],\n ]);\n\n const rewardPriceResults = rewardPriceCalls.length > 0\n ? await multicallRead(this.rpcUrl, rewardPriceCalls)\n : [];\n\n const rewardPriceMap = new Map<string, { price: bigint; decimals: number }>();\n for (let i = 0; i < allRewardTokens.length; i++) {\n const priceRaw = rewardPriceResults[i * 2] ?? null;\n const decimalsRaw = rewardPriceResults[i * 2 + 1] ?? null;\n const price = decodeU256(priceRaw);\n const decimals = decimalsRaw ? Number(decodeU256(decimalsRaw)) : 18;\n rewardPriceMap.set(allRewardTokens[i].toLowerCase(), { price, decimals });\n }\n\n // Supply-side incentive APY\n if (hasSupplyRewards) {\n let totalSupplyIncentiveUsdPerYear = 0;\n const totalSupplyUsd = (Number(totalSupply) / assetDecimalsDivisor) * assetPriceF;\n\n for (let i = 0; i < supplyRewardTokens.length; i++) {\n const emissionPerSec = BigInt(supplyEmissions[i]);\n const entry = rewardPriceMap.get(supplyRewardTokens[i].toLowerCase());\n const rewardPrice = entry?.price ?? 0n;\n const rewardDecimals = entry?.decimals ?? 18;\n if (rewardPrice > 0n) {\n const rewardPriceF = Number(rewardPrice) / priceUnit;\n const emissionPerYear = (Number(emissionPerSec) / (10 ** rewardDecimals)) * SECONDS_PER_YEAR;\n totalSupplyIncentiveUsdPerYear += emissionPerYear * rewardPriceF;\n }\n }\n if (totalSupplyUsd > 0) {\n supplyIncentiveApy = (totalSupplyIncentiveUsdPerYear / totalSupplyUsd) * 100;\n }\n }\n\n // Borrow-side incentive APY\n if (hasBorrowRewards && totalBorrow > 0n) {\n let totalBorrowIncentiveUsdPerYear = 0;\n const totalBorrowUsd = (Number(totalBorrow) / assetDecimalsDivisor) * assetPriceF;\n\n for (let i = 0; i < borrowRewardTokens.length; i++) {\n const emissionPerSec = BigInt(borrowEmissions[i]);\n const entry = rewardPriceMap.get(borrowRewardTokens[i].toLowerCase());\n const rewardPrice = entry?.price ?? 0n;\n const rewardDecimals = entry?.decimals ?? 18;\n if (rewardPrice > 0n) {\n const rewardPriceF = Number(rewardPrice) / priceUnit;\n const emissionPerYear = (Number(emissionPerSec) / (10 ** rewardDecimals)) * SECONDS_PER_YEAR;\n totalBorrowIncentiveUsdPerYear += emissionPerYear * rewardPriceF;\n }\n }\n if (totalBorrowUsd > 0) {\n borrowIncentiveApy = (totalBorrowIncentiveUsdPerYear / totalBorrowUsd) * 100;\n }\n }\n } catch {\n // Oracle not available — skip incentive APY calculation\n }\n }\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyRate,\n borrow_variable_apy: variableRate,\n borrow_stable_apy: stableRate,\n utilization,\n total_supply: totalSupply,\n total_borrow: totalBorrow,\n ...(hasSupplyRewards && {\n supply_reward_tokens: supplyRewardTokens,\n supply_emissions_per_second: supplyEmissions,\n }),\n ...(hasBorrowRewards && {\n borrow_reward_tokens: borrowRewardTokens,\n borrow_emissions_per_second: borrowEmissions,\n }),\n ...(supplyIncentiveApy !== undefined && { supply_incentive_apy: supplyIncentiveApy }),\n ...(borrowIncentiveApy !== undefined && { borrow_incentive_apy: borrowIncentiveApy }),\n };\n }\n\n async getUserPosition(user: Address): Promise<UserPosition> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getUserAccountData\",\n args: [user],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getUserAccountData failed: ${e}`);\n });\n\n const [totalCollateralBase, totalDebtBase, , , ltv, healthFactor] = result;\n const MAX_UINT256 = 2n ** 256n - 1n;\n const hf = healthFactor >= MAX_UINT256 ? Infinity : Number(healthFactor) / 1e18;\n const collateralUsd = u256ToF64(totalCollateralBase) / 1e8;\n const debtUsd = u256ToF64(totalDebtBase) / 1e8;\n const ltvBps = u256ToF64(ltv);\n\n const supplies = collateralUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Collateral\", amount: totalCollateralBase, value_usd: collateralUsd }]\n : [];\n const borrows = debtUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Debt\", amount: totalDebtBase, value_usd: debtUsd }]\n : [];\n\n return {\n protocol: this.protocolName,\n user,\n supplies,\n borrows,\n health_factor: hf,\n net_apy: ltvBps / 100,\n };\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n InterestRateMode,\n} from \"@hypurrquant/defi-core\";\n\n// V2 uses deposit/borrow/repay/withdraw (same as V3 for borrow/repay/withdraw)\nconst POOL_ABI = parseAbi([\n \"function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external\",\n \"function borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf) external\",\n \"function repay(address asset, uint256 amount, uint256 rateMode, address onBehalfOf) external returns (uint256)\",\n \"function withdraw(address asset, uint256 amount, address to) external returns (uint256)\",\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n // V2 getReserveData: 12 fields (no accruedToTreasury/unbacked/isolationModeTotalDebt)\n // positions: [0]=configuration, [1]=liquidityIndex, [2]=variableBorrowIndex,\n // [3]=currentLiquidityRate, [4]=currentVariableBorrowRate, [5]=currentStableBorrowRate,\n // [6]=lastUpdateTimestamp, [7]=aTokenAddress, [8]=stableDebtTokenAddress,\n // [9]=variableDebtTokenAddress, [10]=interestRateStrategyAddress, [11]=id\n \"function getReserveData(address asset) external view returns (uint256 configuration, uint128 liquidityIndex, uint128 variableBorrowIndex, uint128 currentLiquidityRate, uint128 currentVariableBorrowRate, uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress, uint8 id)\",\n]);\n\nconst ERC20_ABI = parseAbi([\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nfunction u256ToF64(v: bigint): number {\n const MAX_U128 = (1n << 128n) - 1n;\n if (v > MAX_U128) return Infinity;\n return Number(v);\n}\n\nexport class AaveV2Adapter implements ILending {\n private readonly protocolName: string;\n private readonly pool: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const pool = entry.contracts?.[\"pool\"];\n if (!pool) throw DefiError.contractError(`[${entry.name}] Missing 'pool' contract address`);\n this.pool = pool;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"deposit\",\n args: [params.asset, params.amount, params.on_behalf_of, 0],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [{ token: params.asset, spender: this.pool, amount: params.amount }],\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"borrow\",\n args: [params.asset, params.amount, rateMode, 0, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"repay\",\n args: [params.asset, params.amount, rateMode, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [{ token: params.asset, spender: this.pool, amount: params.amount }],\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getReserveData\",\n args: [asset],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getReserveData failed: ${e}`);\n });\n\n const RAY = 1e27;\n const SECONDS_PER_YEAR = 31536000;\n\n // Convert ray rate to APY: ((1 + rate/SECONDS_PER_YEAR)^SECONDS_PER_YEAR - 1) * 100\n const toApy = (rayRate: bigint): number => {\n const rate = Number(rayRate) / RAY;\n return (Math.pow(1 + rate / SECONDS_PER_YEAR, SECONDS_PER_YEAR) - 1) * 100;\n };\n\n // V2 field positions:\n // [3] = currentLiquidityRate, [4] = currentVariableBorrowRate, [5] = currentStableBorrowRate\n // [7] = aTokenAddress, [9] = variableDebtTokenAddress\n const supplyRate = toApy(result[3]);\n const variableRate = toApy(result[4]);\n const stableRate = toApy(result[5]);\n\n const aTokenAddress = result[7] as Address;\n const variableDebtTokenAddress = result[9] as Address;\n\n const [totalSupply, totalBorrow] = await Promise.all([\n client.readContract({\n address: aTokenAddress,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch(() => 0n),\n client.readContract({\n address: variableDebtTokenAddress,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch(() => 0n),\n ]);\n\n const utilization = totalSupply > 0n\n ? Number((totalBorrow * 10000n) / totalSupply) / 100\n : 0;\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyRate,\n borrow_variable_apy: variableRate,\n borrow_stable_apy: stableRate,\n utilization,\n total_supply: totalSupply,\n total_borrow: totalBorrow,\n };\n }\n\n async getUserPosition(user: Address): Promise<UserPosition> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getUserAccountData\",\n args: [user],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getUserAccountData failed: ${e}`);\n });\n\n const [totalCollateralBase, totalDebtBase, , , ltv, healthFactor] = result;\n const MAX_UINT256 = 2n ** 256n - 1n;\n const hf = healthFactor >= MAX_UINT256 ? Infinity : Number(healthFactor) / 1e18;\n // V2 returns values in ETH (18 decimals) vs V3's base currency (8 decimals)\n const collateralUsd = u256ToF64(totalCollateralBase) / 1e18;\n const debtUsd = u256ToF64(totalDebtBase) / 1e18;\n const ltvBps = u256ToF64(ltv);\n\n const supplies = collateralUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Collateral\", amount: totalCollateralBase, value_usd: collateralUsd }]\n : [];\n const borrows = debtUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Debt\", amount: totalDebtBase, value_usd: debtUsd }]\n : [];\n\n return {\n protocol: this.protocolName,\n user,\n supplies,\n borrows,\n health_factor: hf,\n net_apy: ltvBps / 100,\n };\n }\n}\n","import { createPublicClient, http, parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IOracle } from \"@hypurrquant/defi-core\";\nimport { DefiError, type ProtocolEntry, type PriceData } from \"@hypurrquant/defi-core\";\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n \"function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory)\",\n \"function BASE_CURRENCY_UNIT() external view returns (uint256)\",\n]);\n\nexport class AaveOracleAdapter implements IOracle {\n private readonly protocolName: string;\n private readonly oracle: Address;\n private readonly rpcUrl: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n if (!rpcUrl) throw DefiError.rpcError(`[${entry.name}] RPC URL required for oracle`);\n this.rpcUrl = rpcUrl;\n const oracle = entry.contracts?.[\"oracle\"];\n if (!oracle) throw DefiError.contractError(`[${entry.name}] Missing 'oracle' contract address`);\n this.oracle = oracle;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getPrice(asset: Address): Promise<PriceData> {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const baseUnit = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"BASE_CURRENCY_UNIT\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] BASE_CURRENCY_UNIT failed: ${e}`);\n });\n\n const priceVal = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [asset],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getAssetPrice failed: ${e}`);\n });\n\n const priceF64 = baseUnit > 0n ? Number(priceVal) / Number(baseUnit) : 0;\n const priceUsd = baseUnit > 0n\n ? (priceVal * (10n ** 18n)) / baseUnit\n : 0n;\n\n return {\n source: `${this.protocolName} Oracle`,\n source_type: \"oracle\",\n asset,\n price_usd: priceUsd,\n price_f64: priceF64,\n };\n }\n\n async getPrices(assets: Address[]): Promise<PriceData[]> {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const baseUnit = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"BASE_CURRENCY_UNIT\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] BASE_CURRENCY_UNIT failed: ${e}`);\n });\n\n const rawPrices = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"getAssetsPrices\",\n args: [assets],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getAssetsPrices failed: ${e}`);\n });\n\n return (rawPrices as bigint[]).map((priceVal, i) => {\n const priceF64 = baseUnit > 0n ? Number(priceVal) / Number(baseUnit) : 0;\n const priceUsd = baseUnit > 0n ? (priceVal * (10n ** 18n)) / baseUnit : 0n;\n return {\n source: `${this.protocolName} Oracle`,\n source_type: \"oracle\",\n asset: assets[i]!,\n price_usd: priceUsd,\n price_f64: priceF64,\n };\n });\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst CTOKEN_ABI = parseAbi([\n \"function supplyRatePerBlock() external view returns (uint256)\",\n \"function borrowRatePerBlock() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function totalBorrows() external view returns (uint256)\",\n \"function mint(uint256 mintAmount) external returns (uint256)\",\n \"function redeem(uint256 redeemTokens) external returns (uint256)\",\n \"function borrow(uint256 borrowAmount) external returns (uint256)\",\n \"function repayBorrow(uint256 repayAmount) external returns (uint256)\",\n]);\n\n// ~3s blocks on BSC\nconst BSC_BLOCKS_PER_YEAR = 10_512_000;\n\nexport class CompoundV2Adapter implements ILending {\n private readonly protocolName: string;\n private readonly defaultVtoken: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const vtoken =\n contracts[\"vusdt\"] ??\n contracts[\"vusdc\"] ??\n contracts[\"vbnb\"] ??\n contracts[\"comptroller\"];\n if (!vtoken) throw DefiError.contractError(\"Missing vToken or comptroller address\");\n this.defaultVtoken = vtoken;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"mint\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"borrow\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"repayBorrow\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"redeem\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw from Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [supplyRate, borrowRate, totalSupply, totalBorrows] = await Promise.all([\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"supplyRatePerBlock\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyRatePerBlock failed: ${e}`); }),\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"borrowRatePerBlock\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] borrowRatePerBlock failed: ${e}`); }),\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"totalSupply\" }).catch(() => 0n),\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"totalBorrows\" }).catch(() => 0n),\n ]);\n\n const supplyPerBlock = Number(supplyRate) / 1e18;\n const borrowPerBlock = Number(borrowRate) / 1e18;\n const supplyApy = supplyPerBlock * BSC_BLOCKS_PER_YEAR * 100;\n const borrowApy = borrowPerBlock * BSC_BLOCKS_PER_YEAR * 100;\n\n const supplyF = Number(totalSupply);\n const borrowF = Number(totalBorrows);\n const utilization = supplyF > 0 ? (borrowF / supplyF) * 100 : 0;\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization,\n total_supply: totalSupply as bigint,\n total_borrow: totalBorrows as bigint,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] User position requires querying individual vToken balances`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst COMET_ABI = parseAbi([\n \"function getUtilization() external view returns (uint256)\",\n \"function getSupplyRate(uint256 utilization) external view returns (uint64)\",\n \"function getBorrowRate(uint256 utilization) external view returns (uint64)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function totalBorrow() external view returns (uint256)\",\n \"function supply(address asset, uint256 amount) external\",\n \"function withdraw(address asset, uint256 amount) external\",\n]);\n\nconst SECONDS_PER_YEAR = 365.25 * 24 * 3600;\n\nexport class CompoundV3Adapter implements ILending {\n private readonly protocolName: string;\n private readonly comet: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const comet = contracts[\"comet_usdc\"] ?? contracts[\"comet\"] ?? contracts[\"comet_weth\"];\n if (!comet) throw DefiError.contractError(\"Missing 'comet_usdc' or 'comet' address\");\n this.comet = comet;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"supply\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n // In Compound V3, borrow = withdraw base asset\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n // In Compound V3, repay = supply base asset\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"supply\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw from Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const utilization = await client.readContract({\n address: this.comet,\n abi: COMET_ABI,\n functionName: \"getUtilization\",\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] getUtilization failed: ${e}`); });\n\n const [supplyRate, borrowRate, totalSupply, totalBorrow] = await Promise.all([\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"getSupplyRate\", args: [utilization as bigint] }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] getSupplyRate failed: ${e}`); }),\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"getBorrowRate\", args: [utilization as bigint] }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] getBorrowRate failed: ${e}`); }),\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"totalSupply\" }).catch(() => 0n),\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"totalBorrow\" }).catch(() => 0n),\n ]);\n\n // Comet rates are per-second scaled by 1e18\n const supplyPerSec = Number(supplyRate) / 1e18;\n const borrowPerSec = Number(borrowRate) / 1e18;\n const supplyApy = supplyPerSec * SECONDS_PER_YEAR * 100;\n const borrowApy = borrowPerSec * SECONDS_PER_YEAR * 100;\n const utilPct = Number(utilization as bigint) / 1e18 * 100;\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization: utilPct,\n total_supply: totalSupply as bigint,\n total_borrow: totalBorrow as bigint,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] User position requires querying Comet balanceOf + borrowBalanceOf`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst EULER_VAULT_ABI = parseAbi([\n \"function deposit(uint256 amount, address receiver) external returns (uint256)\",\n \"function withdraw(uint256 amount, address receiver, address owner) external returns (uint256)\",\n \"function borrow(uint256 amount, address receiver) external returns (uint256)\",\n \"function repay(uint256 amount, address receiver) external returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function totalBorrows() external view returns (uint256)\",\n \"function interestRate() external view returns (uint256)\",\n]);\n\nconst SECONDS_PER_YEAR = 365.25 * 24 * 3600;\n\nexport class EulerV2Adapter implements ILending {\n private readonly protocolName: string;\n private readonly euler: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const euler = contracts[\"evk_vault\"] ?? contracts[\"euler\"] ?? contracts[\"markets\"];\n if (!euler) throw DefiError.contractError(\"Missing 'evk_vault' or 'euler' contract address\");\n this.euler = euler;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"deposit\",\n args: [params.amount, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Deposit ${params.amount} into Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"borrow\",\n args: [params.amount, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"repay\",\n args: [params.amount, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"withdraw\",\n args: [params.amount, params.to, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [totalSupply, totalBorrows, interestRate] = await Promise.all([\n client.readContract({ address: this.euler, abi: EULER_VAULT_ABI, functionName: \"totalSupply\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalSupply failed: ${e}`); }),\n client.readContract({ address: this.euler, abi: EULER_VAULT_ABI, functionName: \"totalBorrows\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalBorrows failed: ${e}`); }),\n client.readContract({ address: this.euler, abi: EULER_VAULT_ABI, functionName: \"interestRate\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] interestRate failed: ${e}`); }),\n ]);\n\n // Euler V2 interest rates per-second scaled by 1e27\n const rateF64 = Number(interestRate) / 1e27;\n const borrowApy = rateF64 * SECONDS_PER_YEAR * 100;\n\n const supplyF = Number(totalSupply);\n const borrowF = Number(totalBorrows);\n const utilization = supplyF > 0 ? (borrowF / supplyF) * 100 : 0;\n const supplyApy = borrowApy * (borrowF / Math.max(supplyF, 1));\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization,\n total_supply: totalSupply as bigint,\n total_borrow: totalBorrows as bigint,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Euler V2 user positions require querying individual vault balances. Use the vault address directly to check balanceOf(user) for supply positions.`,\n );\n }\n}\n","import { parseAbi, encodeFunctionData, decodeFunctionResult, zeroAddress } from \"viem\";\nimport type { Address, Hex } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n multicallRead,\n decodeU256,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst MORPHO_ABI = parseAbi([\n \"function market(bytes32 id) external view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)\",\n \"function idToMarketParams(bytes32 id) external view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)\",\n \"function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) external returns (uint256 assetsSupplied, uint256 sharesSupplied)\",\n \"function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed)\",\n \"function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) external returns (uint256 assetsRepaid, uint256 sharesRepaid)\",\n \"function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)\",\n]);\n\nconst META_MORPHO_ABI = parseAbi([\n \"function supplyQueueLength() external view returns (uint256)\",\n \"function supplyQueue(uint256 index) external view returns (bytes32)\",\n \"function totalAssets() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nconst IRM_ABI = parseAbi([\n \"function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) external view returns (uint256)\",\n]);\n\nconst SECONDS_PER_YEAR = 365.25 * 24 * 3600;\n\ntype MarketParams = {\n loanToken: Address;\n collateralToken: Address;\n oracle: Address;\n irm: Address;\n lltv: bigint;\n};\n\nfunction defaultMarketParams(loanToken: Address = zeroAddress as Address): MarketParams {\n return {\n loanToken,\n collateralToken: zeroAddress as Address,\n oracle: zeroAddress as Address,\n irm: zeroAddress as Address,\n lltv: 0n,\n };\n}\n\nfunction decodeMarket(data: Hex | null): [bigint, bigint, bigint, bigint, bigint, bigint] | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({\n abi: MORPHO_ABI,\n functionName: \"market\",\n data,\n }) as [bigint, bigint, bigint, bigint, bigint, bigint];\n } catch {\n return null;\n }\n}\n\nfunction decodeMarketParams(data: Hex | null): [Address, Address, Address, Address, bigint] | null {\n if (!data) return null;\n try {\n return decodeFunctionResult({\n abi: MORPHO_ABI,\n functionName: \"idToMarketParams\",\n data,\n }) as [Address, Address, Address, Address, bigint];\n } catch {\n return null;\n }\n}\n\nexport class MorphoBlueAdapter implements ILending {\n private readonly protocolName: string;\n private readonly morpho: Address;\n private readonly defaultVault?: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const morpho = contracts[\"morpho_blue\"];\n if (!morpho) throw DefiError.contractError(\"Missing 'morpho_blue' contract address\");\n this.morpho = morpho;\n this.defaultVault =\n contracts[\"fehype\"] ?? contracts[\"vault\"] ?? contracts[\"feusdc\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"supply\",\n args: [market, params.amount, 0n, params.on_behalf_of, \"0x\"],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"borrow\",\n args: [market, params.amount, 0n, params.on_behalf_of, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"repay\",\n args: [market, params.amount, 0n, params.on_behalf_of, \"0x\"],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"withdraw\",\n args: [market, params.amount, 0n, params.to, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n if (!this.defaultVault) {\n throw DefiError.contractError(`[${this.protocolName}] No MetaMorpho vault configured for rate query`);\n }\n\n // Batch 1: supplyQueueLength (gate check)\n const [queueLenRaw] = await multicallRead(this.rpcUrl, [\n [this.defaultVault, encodeFunctionData({ abi: META_MORPHO_ABI, functionName: \"supplyQueueLength\" })],\n ]).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyQueueLength failed: ${e}`); });\n\n const queueLen = decodeU256(queueLenRaw ?? null);\n\n if (queueLen === 0n) {\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: 0,\n borrow_variable_apy: 0,\n utilization: 0,\n total_supply: 0n,\n total_borrow: 0n,\n };\n }\n\n // supplyQueue(0) — single call, depends on queueLen > 0\n const [marketIdRaw] = await multicallRead(this.rpcUrl, [\n [this.defaultVault, encodeFunctionData({ abi: META_MORPHO_ABI, functionName: \"supplyQueue\", args: [0n] })],\n ]).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyQueue(0) failed: ${e}`); });\n\n if (!marketIdRaw || marketIdRaw.length < 66) {\n throw DefiError.rpcError(`[${this.protocolName}] supplyQueue(0) returned no data`);\n }\n const marketId = marketIdRaw.slice(0, 66) as `0x${string}`;\n\n // Batch 2: market + idToMarketParams (both depend on marketId, independent of each other)\n const [marketRaw, paramsRaw] = await multicallRead(this.rpcUrl, [\n [this.morpho, encodeFunctionData({ abi: MORPHO_ABI, functionName: \"market\", args: [marketId] })],\n [this.morpho, encodeFunctionData({ abi: MORPHO_ABI, functionName: \"idToMarketParams\", args: [marketId] })],\n ]).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] market/idToMarketParams failed: ${e}`); });\n\n const mktDecoded = decodeMarket(marketRaw ?? null);\n if (!mktDecoded) throw DefiError.rpcError(`[${this.protocolName}] market() returned no data`);\n const [totalSupplyAssets, totalSupplyShares, totalBorrowAssets, totalBorrowShares, lastUpdate, fee] = mktDecoded;\n\n const paramsDecoded = decodeMarketParams(paramsRaw ?? null);\n if (!paramsDecoded) throw DefiError.rpcError(`[${this.protocolName}] idToMarketParams returned no data`);\n const [loanToken, collateralToken, oracle, irm, lltv] = paramsDecoded;\n\n const supplyF = Number(totalSupplyAssets);\n const borrowF = Number(totalBorrowAssets);\n const util = supplyF > 0 ? borrowF / supplyF : 0;\n\n const irmMarketParams: MarketParams = { loanToken, collateralToken, oracle, irm, lltv };\n const irmMarket = { totalSupplyAssets, totalSupplyShares, totalBorrowAssets, totalBorrowShares, lastUpdate, fee };\n\n // borrowRateView depends on both market + idToMarketParams results — keep separate\n const borrowRatePerSec = await (async () => {\n const [borrowRateRaw] = await multicallRead(this.rpcUrl!, [\n [irm, encodeFunctionData({ abi: IRM_ABI, functionName: \"borrowRateView\", args: [irmMarketParams, irmMarket] })],\n ]).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] borrowRateView failed: ${e}`); });\n return decodeU256(borrowRateRaw ?? null);\n })();\n\n const ratePerSec = Number(borrowRatePerSec) / 1e18;\n const borrowApy = ratePerSec * SECONDS_PER_YEAR * 100;\n const feePct = Number(fee) / 1e18;\n const supplyApy = borrowApy * util * (1 - feePct);\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization: util * 100,\n total_supply: totalSupplyAssets,\n total_borrow: totalBorrowAssets,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Morpho Blue user positions are per-market — use vault deposit/withdraw instead`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ICdp } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type OpenCdpParams,\n type AdjustCdpParams,\n type CloseCdpParams,\n type CdpInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst BORROWER_OPS_ABI = parseAbi([\n \"function openTrove(address _owner, uint256 _ownerIndex, uint256 _collAmount, uint256 _boldAmount, uint256 _upperHint, uint256 _lowerHint, uint256 _annualInterestRate, uint256 _maxUpfrontFee, address _addManager, address _removeManager, address _receiver) external returns (uint256)\",\n \"function adjustTrove(uint256 _troveId, uint256 _collChange, bool _isCollIncrease, uint256 _debtChange, bool _isDebtIncrease, uint256 _upperHint, uint256 _lowerHint, uint256 _maxUpfrontFee) external\",\n \"function closeTrove(uint256 _troveId) external\",\n]);\n\nconst TROVE_MANAGER_ABI = parseAbi([\n \"function getLatestTroveData(uint256 _troveId) external view returns (uint256 entireDebt, uint256 entireColl, uint256 redistDebtGain, uint256 redistCollGain, uint256 accruedInterest, uint256 recordedDebt, uint256 annualInterestRate, uint256 accruedBatchManagementFee, uint256 weightedRecordedDebt, uint256 lastInterestRateAdjTime)\",\n]);\n\nconst HINT_HELPERS_ABI = parseAbi([\n \"function getApproxHint(uint256 _collIndex, uint256 _interestRate, uint256 _numTrials, uint256 _inputRandomSeed) external view returns (uint256 hintId, uint256 diff, uint256 latestRandomSeed)\",\n]);\n\nconst SORTED_TROVES_ABI = parseAbi([\n \"function findInsertPosition(uint256 _annualInterestRate, uint256 _prevId, uint256 _nextId) external view returns (uint256 prevId, uint256 nextId)\",\n]);\n\nexport class FelixCdpAdapter implements ICdp {\n private readonly protocolName: string;\n private readonly borrowerOperations: Address;\n private readonly troveManager?: Address;\n private readonly hintHelpers?: Address;\n private readonly sortedTroves?: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const bo = contracts[\"borrower_operations\"];\n if (!bo) throw DefiError.contractError(\"Missing 'borrower_operations' contract\");\n this.borrowerOperations = bo;\n this.troveManager = contracts[\"trove_manager\"];\n this.hintHelpers = contracts[\"hint_helpers\"];\n this.sortedTroves = contracts[\"sorted_troves\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n private async getHints(interestRate: bigint): Promise<[bigint, bigint]> {\n if (!this.hintHelpers || !this.sortedTroves || !this.rpcUrl) {\n return [0n, 0n];\n }\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const approxResult = await client.readContract({\n address: this.hintHelpers,\n abi: HINT_HELPERS_ABI,\n functionName: \"getApproxHint\",\n args: [0n, interestRate, 15n, 42n],\n }).catch(() => null);\n\n if (!approxResult) return [0n, 0n];\n const [hintId] = approxResult as [bigint, bigint, bigint];\n\n const insertResult = await client.readContract({\n address: this.sortedTroves,\n abi: SORTED_TROVES_ABI,\n functionName: \"findInsertPosition\",\n args: [interestRate, hintId, hintId],\n }).catch(() => null);\n\n if (!insertResult) return [0n, 0n];\n const [prevId, nextId] = insertResult as [bigint, bigint];\n return [prevId, nextId];\n }\n\n async buildOpen(params: OpenCdpParams): Promise<DeFiTx> {\n const interestRate = 50000000000000000n; // 5% default\n const [upperHint, lowerHint] = await this.getHints(interestRate);\n const hasHints = upperHint !== 0n || lowerHint !== 0n;\n\n const data = encodeFunctionData({\n abi: BORROWER_OPS_ABI,\n functionName: \"openTrove\",\n args: [\n params.recipient,\n 0n,\n params.collateral_amount,\n params.debt_amount,\n upperHint,\n lowerHint,\n interestRate,\n BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"), // U256::MAX\n params.recipient,\n params.recipient,\n params.recipient,\n ],\n });\n\n return {\n description: `[${this.protocolName}] Open trove: collateral=${params.collateral_amount}, debt=${params.debt_amount} (hints=${hasHints ? \"optimized\" : \"none\"})`,\n to: this.borrowerOperations,\n data,\n value: 0n,\n gas_estimate: hasHints ? 500_000 : 5_000_000,\n };\n }\n\n async buildAdjust(params: AdjustCdpParams): Promise<DeFiTx> {\n const collChange = params.collateral_delta ?? 0n;\n const debtChange = params.debt_delta ?? 0n;\n\n const data = encodeFunctionData({\n abi: BORROWER_OPS_ABI,\n functionName: \"adjustTrove\",\n args: [\n params.cdp_id,\n collChange,\n params.add_collateral,\n debtChange,\n params.add_debt,\n 0n,\n 0n,\n BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Adjust trove ${params.cdp_id}`,\n to: this.borrowerOperations,\n data,\n value: 0n,\n gas_estimate: 400_000,\n };\n }\n\n async buildClose(params: CloseCdpParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: BORROWER_OPS_ABI,\n functionName: \"closeTrove\",\n args: [params.cdp_id],\n });\n\n return {\n description: `[${this.protocolName}] Close trove ${params.cdp_id}`,\n to: this.borrowerOperations,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async getCdpInfo(cdpId: bigint): Promise<CdpInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(`[${this.protocolName}] getCdpInfo requires RPC — set HYPEREVM_RPC_URL`);\n if (!this.troveManager) throw DefiError.contractError(`[${this.protocolName}] trove_manager contract not configured`);\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const data = await client.readContract({\n address: this.troveManager,\n abi: TROVE_MANAGER_ABI,\n functionName: \"getLatestTroveData\",\n args: [cdpId],\n }).catch((e: unknown) => {\n throw DefiError.invalidParam(`[${this.protocolName}] Trove ${cdpId} not found: ${e}`);\n });\n\n const [entireDebt, entireColl] = data as [bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint];\n\n if (entireDebt === 0n && entireColl === 0n) {\n throw DefiError.invalidParam(`[${this.protocolName}] Trove ${cdpId} does not exist`);\n }\n\n const collRatio = entireDebt > 0n ? Number(entireColl) / Number(entireDebt) : 0;\n\n return {\n protocol: this.protocolName,\n cdp_id: cdpId,\n collateral: {\n token: zeroAddress as Address,\n symbol: \"WHYPE\",\n amount: entireColl,\n decimals: 18,\n },\n debt: {\n token: zeroAddress as Address,\n symbol: \"feUSD\",\n amount: entireDebt,\n decimals: 18,\n },\n collateral_ratio: collRatio,\n };\n }\n}\n","import { createPublicClient, http, parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IOracle } from \"@hypurrquant/defi-core\";\nimport { DefiError, type ProtocolEntry, type PriceData } from \"@hypurrquant/defi-core\";\n\nconst PRICE_FEED_ABI = parseAbi([\n \"function fetchPrice() external view returns (uint256 price, bool isNewOracleFailureDetected)\",\n \"function lastGoodPrice() external view returns (uint256)\",\n]);\n\nexport class FelixOracleAdapter implements IOracle {\n private readonly protocolName: string;\n private readonly priceFeed: Address;\n private readonly asset: Address;\n private readonly rpcUrl: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n if (!rpcUrl) throw DefiError.rpcError(`[${entry.name}] RPC URL required for oracle`);\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const feed = contracts[\"price_feed\"];\n if (!feed) throw DefiError.contractError(`[${entry.name}] Missing 'price_feed' contract address`);\n this.priceFeed = feed;\n // The asset address is stored under \"asset\" or falls back to zero (WHYPE native)\n this.asset = contracts[\"asset\"] ?? (\"0x0000000000000000000000000000000000000000\" as Address);\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getPrice(asset: Address): Promise<PriceData> {\n if (asset !== this.asset && this.asset !== \"0x0000000000000000000000000000000000000000\") {\n throw DefiError.unsupported(`[${this.protocolName}] Felix PriceFeed only supports asset ${this.asset}`);\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n let priceVal: bigint;\n try {\n const result = await client.readContract({\n address: this.priceFeed,\n abi: PRICE_FEED_ABI,\n functionName: \"fetchPrice\",\n });\n const [price] = result as [bigint, boolean];\n priceVal = price;\n } catch {\n // Fall back to lastGoodPrice\n priceVal = await client.readContract({\n address: this.priceFeed,\n abi: PRICE_FEED_ABI,\n functionName: \"lastGoodPrice\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] lastGoodPrice failed: ${e}`);\n }) as bigint;\n }\n\n // Felix prices are already in 18-decimal USD\n const priceF64 = Number(priceVal) / 1e18;\n\n return {\n source: \"Felix PriceFeed\",\n source_type: \"oracle\",\n asset,\n price_usd: priceVal,\n price_f64: priceF64,\n };\n }\n\n async getPrices(assets: Address[]): Promise<PriceData[]> {\n const results: PriceData[] = [];\n for (const asset of assets) {\n try {\n results.push(await this.getPrice(asset));\n } catch {\n // Skip unsupported assets\n }\n }\n return results;\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IVault } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type VaultInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst ERC4626_ABI = parseAbi([\n \"function asset() external view returns (address)\",\n \"function totalAssets() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function convertToShares(uint256 assets) external view returns (uint256)\",\n \"function convertToAssets(uint256 shares) external view returns (uint256)\",\n \"function deposit(uint256 assets, address receiver) external returns (uint256 shares)\",\n \"function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares)\",\n]);\n\nexport class ERC4626VaultAdapter implements IVault {\n private readonly protocolName: string;\n private readonly vaultAddress: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const vault = entry.contracts?.[\"vault\"];\n if (!vault) throw DefiError.contractError(\"Missing 'vault' contract address\");\n this.vaultAddress = vault;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildDeposit(assets: bigint, receiver: Address): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: ERC4626_ABI,\n functionName: \"deposit\",\n args: [assets, receiver],\n });\n return {\n description: `[${this.protocolName}] Deposit ${assets} assets into vault`,\n to: this.vaultAddress,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildWithdraw(assets: bigint, receiver: Address, owner: Address): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: ERC4626_ABI,\n functionName: \"withdraw\",\n args: [assets, receiver, owner],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${assets} assets from vault`,\n to: this.vaultAddress,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async totalAssets(): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return client.readContract({\n address: this.vaultAddress,\n abi: ERC4626_ABI,\n functionName: \"totalAssets\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] totalAssets failed: ${e}`);\n }) as Promise<bigint>;\n }\n\n async convertToShares(assets: bigint): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return client.readContract({\n address: this.vaultAddress,\n abi: ERC4626_ABI,\n functionName: \"convertToShares\",\n args: [assets],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] convertToShares failed: ${e}`);\n }) as Promise<bigint>;\n }\n\n async convertToAssets(shares: bigint): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return client.readContract({\n address: this.vaultAddress,\n abi: ERC4626_ABI,\n functionName: \"convertToAssets\",\n args: [shares],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] convertToAssets failed: ${e}`);\n }) as Promise<bigint>;\n }\n\n async getVaultInfo(): Promise<VaultInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [totalAssets, totalSupply, asset] = await Promise.all([\n client.readContract({ address: this.vaultAddress, abi: ERC4626_ABI, functionName: \"totalAssets\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalAssets failed: ${e}`); }),\n client.readContract({ address: this.vaultAddress, abi: ERC4626_ABI, functionName: \"totalSupply\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalSupply failed: ${e}`); }),\n client.readContract({ address: this.vaultAddress, abi: ERC4626_ABI, functionName: \"asset\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] asset failed: ${e}`); }),\n ]);\n\n return {\n protocol: this.protocolName,\n vault_address: this.vaultAddress,\n asset: asset as Address,\n total_assets: totalAssets as bigint,\n total_supply: totalSupply as bigint,\n };\n }\n}\n","import { parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type StakeParams,\n type UnstakeParams,\n type StakingInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst GENERIC_LST_ABI = parseAbi([\n \"function stake() external payable returns (uint256)\",\n \"function unstake(uint256 amount) external returns (uint256)\",\n]);\n\nexport class GenericLstAdapter implements ILiquidStaking {\n private readonly protocolName: string;\n private readonly staking: Address;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const staking = entry.contracts?.[\"staking\"];\n if (!staking) throw DefiError.contractError(\"Missing 'staking' contract\");\n this.staking = staking;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildStake(params: StakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({ abi: GENERIC_LST_ABI, functionName: \"stake\" });\n return {\n description: `[${this.protocolName}] Stake ${params.amount} HYPE`,\n to: this.staking,\n data,\n value: params.amount,\n gas_estimate: 200_000,\n };\n }\n\n async buildUnstake(params: UnstakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: GENERIC_LST_ABI,\n functionName: \"unstake\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Unstake ${params.amount}`,\n to: this.staking,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async getInfo(): Promise<StakingInfo> {\n throw DefiError.unsupported(`[${this.protocolName}] getInfo requires RPC`);\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type StakeParams,\n type UnstakeParams,\n type StakingInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst STHYPE_ABI = parseAbi([\n \"function submit(address referral) external payable returns (uint256)\",\n \"function requestWithdrawals(uint256[] amounts, address owner) external returns (uint256[] requestIds)\",\n]);\n\nconst ERC20_ABI = parseAbi([\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nexport class StHypeAdapter implements ILiquidStaking {\n private readonly protocolName: string;\n private readonly staking: Address;\n private readonly sthypeToken?: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const staking = entry.contracts?.[\"staking\"];\n if (!staking) throw DefiError.contractError(\"Missing 'staking' contract\");\n this.staking = staking;\n this.sthypeToken = entry.contracts?.[\"sthype_token\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildStake(params: StakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: STHYPE_ABI,\n functionName: \"submit\",\n args: [zeroAddress as Address],\n });\n return {\n description: `[${this.protocolName}] Stake ${params.amount} HYPE for stHYPE`,\n to: this.staking,\n data,\n value: params.amount,\n gas_estimate: 200_000,\n };\n }\n\n async buildUnstake(params: UnstakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: STHYPE_ABI,\n functionName: \"requestWithdrawals\",\n args: [[params.amount], params.recipient],\n });\n return {\n description: `[${this.protocolName}] Request unstake ${params.amount} stHYPE`,\n to: this.staking,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async getInfo(): Promise<StakingInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const tokenAddr = this.sthypeToken ?? this.staking;\n\n const totalSupply = await client.readContract({\n address: tokenAddr,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] totalSupply failed: ${e}`);\n }) as bigint;\n\n return {\n protocol: this.protocolName,\n staked_token: zeroAddress as Address,\n liquid_token: tokenAddr,\n exchange_rate: 1.0,\n total_staked: totalSupply,\n };\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type StakeParams,\n type UnstakeParams,\n type StakingInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst KINETIQ_ABI = parseAbi([\n \"function stake() external payable returns (uint256)\",\n \"function requestUnstake(uint256 amount) external returns (uint256)\",\n \"function totalStaked() external view returns (uint256)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n]);\n\n// WHYPE address on HyperEVM\nconst WHYPE: Address = \"0x5555555555555555555555555555555555555555\";\n// HyperLend oracle address (Aave V3 compatible)\nconst HYPERLEND_ORACLE: Address = \"0xc9fb4fbe842d57ea1df3e641a281827493a63030\";\n\nexport class KinetiqAdapter implements ILiquidStaking {\n private readonly protocolName: string;\n private readonly staking: Address;\n private readonly liquidToken: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const staking = entry.contracts?.[\"staking\"];\n if (!staking) throw DefiError.contractError(\"Missing 'staking' contract address\");\n this.staking = staking;\n this.liquidToken = entry.contracts?.[\"khype_token\"] ?? staking;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildStake(params: StakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({ abi: KINETIQ_ABI, functionName: \"stake\" });\n return {\n description: `[${this.protocolName}] Stake ${params.amount} HYPE for kHYPE`,\n to: this.staking,\n data,\n value: params.amount,\n gas_estimate: 300_000,\n };\n }\n\n async buildUnstake(params: UnstakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: KINETIQ_ABI,\n functionName: \"requestUnstake\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Request unstake ${params.amount} kHYPE`,\n to: this.staking,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async getInfo(): Promise<StakingInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const totalStaked = await client.readContract({\n address: this.staking,\n abi: KINETIQ_ABI,\n functionName: \"totalStaked\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] totalStaked failed: ${e}`);\n }) as bigint;\n\n const [khypePrice, hypePrice] = await Promise.all([\n client.readContract({ address: HYPERLEND_ORACLE, abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [this.liquidToken] }).catch(() => 0n),\n client.readContract({ address: HYPERLEND_ORACLE, abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [WHYPE] }).catch(() => 0n),\n ]);\n\n const rateF64 =\n (hypePrice as bigint) > 0n && (khypePrice as bigint) > 0n\n ? Number((khypePrice as bigint) * 10n ** 18n / (hypePrice as bigint)) / 1e18\n : 1.0;\n\n return {\n protocol: this.protocolName,\n staked_token: zeroAddress as Address,\n liquid_token: this.liquidToken,\n exchange_rate: rateF64,\n total_staked: totalStaked,\n };\n }\n}\n","import type { Address } from \"viem\";\nimport type { IYieldSource } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type YieldInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class PendleAdapter implements IYieldSource {\n private readonly protocolName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n if (!entry.contracts?.[\"router\"]) {\n throw DefiError.contractError(\"Missing 'router' contract\");\n }\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getYields(): Promise<YieldInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] getYields requires RPC`);\n }\n\n async buildDeposit(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Pendle deposit requires market address and token routing params. Use Pendle-specific CLI.`,\n );\n }\n\n async buildWithdraw(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Pendle withdraw requires market-specific params`,\n );\n }\n}\n","import type { Address } from \"viem\";\nimport type { IYieldSource } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type YieldInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class GenericYieldAdapter implements IYieldSource {\n private readonly protocolName: string;\n private readonly interfaceName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n this.interfaceName = entry.interface;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getYields(): Promise<YieldInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] getYields requires RPC`);\n }\n\n async buildDeposit(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Yield interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'pendle_v2' (Pendle). Protocols like Steer (managed liquidity), ` +\n `Liminal (yield optimization), and Altura (gaming yield) need custom deposit logic.`,\n );\n }\n\n async buildWithdraw(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Yield interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'pendle_v2' (Pendle). Protocols like Steer (managed liquidity), ` +\n `Liminal (yield optimization), and Altura (gaming yield) need custom withdraw logic.`,\n );\n }\n}\n","import { parseAbi, encodeFunctionData } from \"viem\";\nimport type { IDerivatives } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type DerivativesPositionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\n\nconst HLP_ABI = parseAbi([\n \"function deposit(uint256 amount) external returns (uint256)\",\n \"function withdraw(uint256 shares) external returns (uint256)\",\n]);\n\nexport class HlpVaultAdapter implements IDerivatives {\n private readonly protocolName: string;\n private readonly vault: Address;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const vault = entry.contracts?.[\"vault\"];\n if (!vault) throw DefiError.contractError(\"Missing 'vault' contract\");\n this.vault = vault;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildOpenPosition(params: DerivativesPositionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: HLP_ABI,\n functionName: \"deposit\",\n args: [params.collateral],\n });\n return {\n description: `[${this.protocolName}] Deposit ${params.collateral} into HLP vault`,\n to: this.vault,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildClosePosition(params: DerivativesPositionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: HLP_ABI,\n functionName: \"withdraw\",\n args: [params.size],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.size} from HLP vault`,\n to: this.vault,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n}\n","import type { IDerivatives } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type DerivativesPositionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class GenericDerivativesAdapter implements IDerivatives {\n private readonly protocolName: string;\n private readonly interfaceName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n this.interfaceName = entry.interface;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildOpenPosition(_params: DerivativesPositionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Derivatives interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'hlp_vault' (HLP Vault). Protocols like Rumpel need custom position management logic.`,\n );\n }\n\n async buildClosePosition(_params: DerivativesPositionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Derivatives interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'hlp_vault' (HLP Vault). Protocols like Rumpel need custom position management logic.`,\n );\n }\n}\n","import { parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IOptions } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type OptionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst RYSK_ABI = parseAbi([\n \"function openOption(address underlying, uint256 strikePrice, uint256 expiry, bool isCall, uint256 amount) external returns (uint256 premium)\",\n \"function closeOption(address underlying, uint256 strikePrice, uint256 expiry, bool isCall, uint256 amount) external returns (uint256 payout)\",\n]);\n\nexport class RyskAdapter implements IOptions {\n private readonly protocolName: string;\n private readonly controller: Address;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const controller = entry.contracts?.[\"controller\"];\n if (!controller) throw DefiError.contractError(\"Missing 'controller' contract\");\n this.controller = controller;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildBuy(params: OptionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: RYSK_ABI,\n functionName: \"openOption\",\n args: [\n params.underlying,\n params.strike_price,\n BigInt(params.expiry),\n params.is_call,\n params.amount,\n ],\n });\n return {\n description: `[${this.protocolName}] Buy ${params.is_call ? \"call\" : \"put\"} ${params.amount} option, strike=${params.strike_price}, expiry=${params.expiry}`,\n to: this.controller,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildSell(params: OptionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: RYSK_ABI,\n functionName: \"closeOption\",\n args: [\n params.underlying,\n params.strike_price,\n BigInt(params.expiry),\n params.is_call,\n params.amount,\n ],\n });\n return {\n description: `[${this.protocolName}] Sell/close ${params.is_call ? \"call\" : \"put\"} ${params.amount} option`,\n to: this.controller,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n}\n","import type { IOptions } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type OptionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class GenericOptionsAdapter implements IOptions {\n private readonly protocolName: string;\n private readonly interfaceName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n this.interfaceName = entry.interface;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildBuy(_params: OptionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Options interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'rysk' (Rysk Finance). Other options protocols need custom strike/expiry handling.`,\n );\n }\n\n async buildSell(_params: OptionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Options interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'rysk' (Rysk Finance). Other options protocols need custom strike/expiry handling.`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { INft, NftCollectionInfo, NftTokenInfo } from \"@hypurrquant/defi-core\";\nimport { DefiError, type ProtocolEntry } from \"@hypurrquant/defi-core\";\n\nconst ERC721_ABI = parseAbi([\n \"function name() returns (string)\",\n \"function symbol() returns (string)\",\n \"function totalSupply() returns (uint256)\",\n \"function ownerOf(uint256 tokenId) returns (address)\",\n \"function balanceOf(address owner) returns (uint256)\",\n \"function tokenURI(uint256 tokenId) returns (string)\",\n]);\n\nexport class ERC721Adapter implements INft {\n private readonly protocolName: string;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getCollectionInfo(collection: Address): Promise<NftCollectionInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [collectionName, symbol, totalSupply] = await Promise.all([\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"name\" })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] name failed: ${e}`);\n }),\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"symbol\" })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] symbol failed: ${e}`);\n }),\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"totalSupply\" })\n .catch(() => undefined),\n ]);\n\n return {\n address: collection,\n name: collectionName as string,\n symbol: symbol as string,\n total_supply: totalSupply as bigint | undefined,\n };\n }\n\n async getTokenInfo(collection: Address, tokenId: bigint): Promise<NftTokenInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [owner, tokenUri] = await Promise.all([\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"ownerOf\", args: [tokenId] })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] ownerOf failed: ${e}`);\n }),\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"tokenURI\", args: [tokenId] })\n .catch(() => undefined),\n ]);\n\n return {\n collection,\n token_id: tokenId,\n owner: owner as Address,\n token_uri: tokenUri as string | undefined,\n };\n }\n\n async getBalance(owner: Address, collection: Address): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n return client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"balanceOf\", args: [owner] })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] balanceOf failed: ${e}`);\n }) as Promise<bigint>;\n }\n}\n","import type { Address } from \"viem\";\n\nimport type { IDex, PriceData, QuoteParams } from \"@hypurrquant/defi-core\";\n\n/**\n * Utility for deriving spot prices from DEX quoters.\n * Quotes 1 unit of the token against a quote token (e.g. USDC) to derive price.\n */\nexport class DexSpotPrice {\n /**\n * Get the spot price for `token` denominated in `quoteToken` (e.g. USDC).\n *\n * `tokenDecimals` — decimals of the input token (to know how much \"1 unit\" is)\n * `quoteDecimals` — decimals of the quote token (to convert the output to number)\n */\n static async getPrice(\n dex: IDex,\n token: Address,\n tokenDecimals: number,\n quoteToken: Address,\n quoteDecimals: number,\n ): Promise<PriceData> {\n const amountIn = 10n ** BigInt(tokenDecimals); // 1 token\n\n const quoteParams: QuoteParams = {\n protocol: \"\",\n token_in: token,\n token_out: quoteToken,\n amount_in: amountIn,\n };\n\n const quote = await dex.quote(quoteParams);\n\n // Convert to USD price (assuming quoteToken is a USD stablecoin)\n const priceF64 = Number(quote.amount_out) / 10 ** quoteDecimals;\n\n // Normalize to 18-decimal representation\n let priceUsd: bigint;\n if (quoteDecimals < 18) {\n priceUsd = quote.amount_out * 10n ** BigInt(18 - quoteDecimals);\n } else if (quoteDecimals > 18) {\n priceUsd = quote.amount_out / 10n ** BigInt(quoteDecimals - 18);\n } else {\n priceUsd = quote.amount_out;\n }\n\n return {\n source: `dex:${dex.name()}`,\n source_type: \"dex_spot\",\n asset: token,\n price_usd: priceUsd,\n price_f64: priceF64,\n block_number: undefined,\n timestamp: undefined,\n };\n }\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createDex } from \"@hypurrquant/defi-protocols\";\n\nexport function registerDex(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const dex = parent.command(\"dex\").description(\"DEX operations: swap, quote, compare\");\n\n dex.command(\"quote\")\n .description(\"Get a swap quote without executing\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--token-in <token>\", \"Input token symbol or address\")\n .requiredOption(\"--token-out <token>\", \"Output token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount of input token in wei\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createDex(protocol, chain.effectiveRpcUrl());\n const tokenIn = opts.tokenIn.startsWith(\"0x\") ? opts.tokenIn as Address : registry.resolveToken(chainName, opts.tokenIn).address as Address;\n const tokenOut = opts.tokenOut.startsWith(\"0x\") ? opts.tokenOut as Address : registry.resolveToken(chainName, opts.tokenOut).address as Address;\n const result = await adapter.quote({ protocol: protocol.name, token_in: tokenIn, token_out: tokenOut, amount_in: BigInt(opts.amount) });\n printOutput(result, getOpts());\n });\n\n dex.command(\"swap\")\n .description(\"Execute a token swap\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--token-in <token>\", \"Input token\")\n .requiredOption(\"--token-out <token>\", \"Output token\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--slippage <bps>\", \"Slippage tolerance in bps\", \"50\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createDex(protocol, chain.effectiveRpcUrl());\n const tokenIn = opts.tokenIn.startsWith(\"0x\") ? opts.tokenIn as Address : registry.resolveToken(chainName, opts.tokenIn).address as Address;\n const tokenOut = opts.tokenOut.startsWith(\"0x\") ? opts.tokenOut as Address : registry.resolveToken(chainName, opts.tokenOut).address as Address;\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildSwap({\n protocol: protocol.name, token_in: tokenIn, token_out: tokenOut,\n amount_in: BigInt(opts.amount), slippage: { bps: parseInt(opts.slippage) }, recipient,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n dex.command(\"lp-add\")\n .description(\"Add liquidity to a pool\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--token-a <token>\", \"First token symbol or address\")\n .requiredOption(\"--token-b <token>\", \"Second token symbol or address\")\n .requiredOption(\"--amount-a <amount>\", \"Amount of token A in wei\")\n .requiredOption(\"--amount-b <amount>\", \"Amount of token B in wei\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .option(\"--tick-lower <tick>\", \"Lower tick for concentrated LP (default: full range)\")\n .option(\"--tick-upper <tick>\", \"Upper tick for concentrated LP (default: full range)\")\n .option(\"--range <percent>\", \"±N% concentrated range around current price (e.g. --range 2 for ±2%)\")\n .option(\"--pool <name_or_address>\", \"Pool name (e.g. WHYPE/USDC) or address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createDex(protocol, chain.effectiveRpcUrl());\n const tokenA = opts.tokenA.startsWith(\"0x\") ? opts.tokenA as Address : registry.resolveToken(chainName, opts.tokenA).address as Address;\n const tokenB = opts.tokenB.startsWith(\"0x\") ? opts.tokenB as Address : registry.resolveToken(chainName, opts.tokenB).address as Address;\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n\n // Resolve pool: name (WHYPE/USDC) → address from config, or raw address\n let poolAddr: Address | undefined;\n if (opts.pool) {\n if (opts.pool.startsWith(\"0x\")) {\n poolAddr = opts.pool as Address;\n } else {\n const poolInfo = registry.resolvePool(opts.protocol, opts.pool);\n poolAddr = poolInfo.address;\n }\n }\n\n const tx = await adapter.buildAddLiquidity({\n protocol: protocol.name,\n token_a: tokenA,\n token_b: tokenB,\n amount_a: BigInt(opts.amountA),\n amount_b: BigInt(opts.amountB),\n recipient,\n tick_lower: opts.tickLower !== undefined ? parseInt(opts.tickLower) : undefined,\n tick_upper: opts.tickUpper !== undefined ? parseInt(opts.tickUpper) : undefined,\n range_pct: opts.range !== undefined ? parseFloat(opts.range) : undefined,\n pool: poolAddr,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n dex.command(\"lp-remove\")\n .description(\"Remove liquidity from a pool\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--token-a <token>\", \"First token symbol or address\")\n .requiredOption(\"--token-b <token>\", \"Second token symbol or address\")\n .requiredOption(\"--liquidity <amount>\", \"Liquidity amount to remove in wei\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createDex(protocol, chain.effectiveRpcUrl());\n const tokenA = opts.tokenA.startsWith(\"0x\") ? opts.tokenA as Address : registry.resolveToken(chainName, opts.tokenA).address as Address;\n const tokenB = opts.tokenB.startsWith(\"0x\") ? opts.tokenB as Address : registry.resolveToken(chainName, opts.tokenB).address as Address;\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildRemoveLiquidity({\n protocol: protocol.name,\n token_a: tokenA,\n token_b: tokenB,\n liquidity: BigInt(opts.liquidity),\n recipient,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n dex.command(\"compare\")\n .description(\"Compare quotes across DEXes\")\n .requiredOption(\"--token-in <token>\", \"Input token\")\n .requiredOption(\"--token-out <token>\", \"Output token\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const tokenIn = opts.tokenIn.startsWith(\"0x\") ? opts.tokenIn as Address : registry.resolveToken(chainName, opts.tokenIn).address as Address;\n const tokenOut = opts.tokenOut.startsWith(\"0x\") ? opts.tokenOut as Address : registry.resolveToken(chainName, opts.tokenOut).address as Address;\n const dexProtocols = registry.getProtocolsByCategory(\"dex\" as any).filter(p => p.chain === chainName);\n const results: Array<{ protocol: string; amount_out: bigint; error?: string }> = [];\n await Promise.all(dexProtocols.map(async (p) => {\n try {\n const adapter = createDex(p, chain.effectiveRpcUrl());\n const q = await adapter.quote({ protocol: p.name, token_in: tokenIn, token_out: tokenOut, amount_in: BigInt(opts.amount) });\n results.push({ protocol: p.name, amount_out: q.amount_out });\n } catch (e) { results.push({ protocol: p.name, amount_out: 0n, error: e instanceof Error ? e.message : String(e) }); }\n }));\n results.sort((a, b) => (b.amount_out > a.amount_out ? 1 : -1));\n printOutput({ chain: chainName, quotes: results }, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { createGauge } from \"@hypurrquant/defi-protocols\";\n\nfunction resolveAccount(): Address | undefined {\n const walletAddr = process.env[\"DEFI_WALLET_ADDRESS\"];\n if (walletAddr) return walletAddr as Address;\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n if (privateKey) return privateKeyToAccount(privateKey as `0x${string}`).address;\n return undefined;\n}\n\nexport function registerGauge(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const gauge = parent.command(\"gauge\").description(\"Gauge operations: find, deposit, withdraw, claim, earned\");\n\n gauge.command(\"discover\")\n .description(\"Find all pools with emission gauges (scans V2 + CL factories)\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, chain.effectiveRpcUrl());\n if (!adapter.discoverGaugedPools) throw new Error(`${protocol.name} does not support gauge discovery`);\n const pools = await adapter.discoverGaugedPools();\n printOutput(pools, getOpts());\n });\n\n gauge.command(\"find\")\n .description(\"Find gauge address for a pool via voter contract\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pool <address>\", \"Pool address\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, chain.effectiveRpcUrl());\n if (!adapter.resolveGauge) throw new Error(`${protocol.name} does not support gauge lookup`);\n const gaugeAddr = await adapter.resolveGauge(opts.pool as Address);\n printOutput({ pool: opts.pool, gauge: gaugeAddr, protocol: protocol.name }, getOpts());\n });\n\n gauge.command(\"earned\")\n .description(\"Check pending rewards for a gauge\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--gauge <address>\", \"Gauge contract address\")\n .option(\"--token-id <id>\", \"NFT tokenId (for CL gauges like Hybra)\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, chain.effectiveRpcUrl());\n\n if (opts.tokenId) {\n if (!adapter.getPendingRewardsByTokenId) throw new Error(`${protocol.name} does not support NFT rewards`);\n const earned = await adapter.getPendingRewardsByTokenId(opts.gauge as Address, BigInt(opts.tokenId));\n printOutput({ gauge: opts.gauge, token_id: opts.tokenId, earned: earned.toString() }, getOpts());\n } else {\n const account = resolveAccount();\n if (!account) throw new Error(\"DEFI_WALLET_ADDRESS or DEFI_PRIVATE_KEY required\");\n const rewards = await adapter.getPendingRewards(opts.gauge as Address, account);\n printOutput(rewards.map(r => ({ token: r.token, amount: r.amount.toString() })), getOpts());\n }\n });\n\n gauge.command(\"deposit\")\n .description(\"Deposit LP tokens or NFT into a gauge\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--gauge <address>\", \"Gauge contract address\")\n .option(\"--amount <amount>\", \"LP token amount in wei (for V2 gauges)\")\n .option(\"--token-id <id>\", \"NFT tokenId (for CL gauges like Hybra)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, chain.effectiveRpcUrl());\n const amount = opts.amount ? BigInt(opts.amount) : 0n;\n const tokenId = opts.tokenId ? BigInt(opts.tokenId) : undefined;\n const tx = await adapter.buildDeposit(opts.gauge as Address, amount, tokenId);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n gauge.command(\"withdraw\")\n .description(\"Withdraw LP tokens or NFT from a gauge\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--gauge <address>\", \"Gauge contract address\")\n .option(\"--amount <amount>\", \"LP token amount in wei (for V2 gauges)\")\n .option(\"--token-id <id>\", \"NFT tokenId (for CL gauges like Hybra)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, chain.effectiveRpcUrl());\n const amount = opts.amount ? BigInt(opts.amount) : 0n;\n const tokenId = opts.tokenId ? BigInt(opts.tokenId) : undefined;\n const tx = await adapter.buildWithdraw(opts.gauge as Address, amount, tokenId);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n gauge.command(\"claim\")\n .description(\"Claim earned rewards from a gauge\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--gauge <address>\", \"Gauge contract address\")\n .option(\"--token-id <id>\", \"NFT tokenId (for CL gauges like Hybra)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, chain.effectiveRpcUrl());\n\n if (opts.tokenId) {\n if (!adapter.buildClaimRewardsByTokenId) throw new Error(`${protocol.name} does not support NFT claim`);\n const tx = await adapter.buildClaimRewardsByTokenId(opts.gauge as Address, BigInt(opts.tokenId));\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n } else {\n const account = resolveAccount();\n const tx = await adapter.buildClaimRewards(opts.gauge as Address, account);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry, InterestRateMode } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createLending } from \"@hypurrquant/defi-protocols\";\n\nexport function registerLending(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const lending = parent.command(\"lending\").description(\"Lending operations: supply, borrow, repay, withdraw, rates, position\");\n\n lending.command(\"rates\")\n .description(\"Show current lending rates\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n const asset = opts.asset.startsWith(\"0x\") ? opts.asset as Address : registry.resolveToken(chainName, opts.asset).address as Address;\n const rates = await adapter.getRates(asset);\n printOutput(rates, getOpts());\n });\n\n lending.command(\"position\")\n .description(\"Show current lending position\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--address <address>\", \"Wallet address to query\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n const position = await adapter.getUserPosition(opts.address as Address);\n printOutput(position, getOpts());\n });\n\n lending.command(\"supply\")\n .description(\"Supply an asset to a lending protocol\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount to supply in wei\")\n .option(\"--on-behalf-of <address>\", \"On behalf of address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n const asset = opts.asset.startsWith(\"0x\") ? opts.asset as Address : registry.resolveToken(chainName, opts.asset).address as Address;\n const onBehalfOf = (opts.onBehalfOf ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildSupply({ protocol: protocol.name, asset, amount: BigInt(opts.amount), on_behalf_of: onBehalfOf });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n lending.command(\"borrow\")\n .description(\"Borrow an asset\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--rate-mode <mode>\", \"variable or stable\", \"variable\")\n .option(\"--on-behalf-of <address>\", \"On behalf of address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n const asset = opts.asset.startsWith(\"0x\") ? opts.asset as Address : registry.resolveToken(chainName, opts.asset).address as Address;\n const onBehalfOf = (opts.onBehalfOf ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildBorrow({\n protocol: protocol.name, asset, amount: BigInt(opts.amount),\n interest_rate_mode: opts.rateMode === \"stable\" ? InterestRateMode.Stable : InterestRateMode.Variable,\n on_behalf_of: onBehalfOf,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n lending.command(\"repay\")\n .description(\"Repay a borrowed asset\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--rate-mode <mode>\", \"variable or stable\", \"variable\")\n .option(\"--on-behalf-of <address>\", \"On behalf of address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n const asset = opts.asset.startsWith(\"0x\") ? opts.asset as Address : registry.resolveToken(chainName, opts.asset).address as Address;\n const onBehalfOf = (opts.onBehalfOf ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildRepay({\n protocol: protocol.name, asset, amount: BigInt(opts.amount),\n interest_rate_mode: opts.rateMode === \"stable\" ? InterestRateMode.Stable : InterestRateMode.Variable,\n on_behalf_of: onBehalfOf,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n lending.command(\"withdraw\")\n .description(\"Withdraw a supplied asset\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--to <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n const asset = opts.asset.startsWith(\"0x\") ? opts.asset as Address : registry.resolveToken(chainName, opts.asset).address as Address;\n const to = (opts.to ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildWithdraw({ protocol: protocol.name, asset, amount: BigInt(opts.amount), to });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createCdp } from \"@hypurrquant/defi-protocols\";\n\nexport function registerCdp(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const cdp = parent.command(\"cdp\").description(\"CDP operations: open, adjust, close, info\");\n\n cdp.command(\"open\")\n .description(\"Open a new CDP position\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--collateral <token>\", \"Collateral token address\")\n .requiredOption(\"--amount <amount>\", \"Collateral amount in wei\")\n .requiredOption(\"--mint <amount>\", \"Stablecoin to mint in wei\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createCdp(protocol, chain.effectiveRpcUrl());\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildOpen({\n protocol: protocol.name, collateral: opts.collateral as Address,\n collateral_amount: BigInt(opts.amount), debt_amount: BigInt(opts.mint), recipient,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n cdp.command(\"info\")\n .description(\"Show CDP position info, or protocol overview if --position is omitted\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .option(\"--position <id>\", \"CDP/trove ID (omit for protocol overview)\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n if (opts.position === undefined) {\n printOutput({\n name: protocol.name,\n slug: protocol.slug,\n chain: chainName,\n contracts: (protocol as unknown as Record<string, unknown>).contracts ?? {},\n }, getOpts());\n return;\n }\n const adapter = createCdp(protocol, chain.effectiveRpcUrl());\n const info = await adapter.getCdpInfo(BigInt(opts.position));\n printOutput(info, getOpts());\n });\n\n cdp.command(\"adjust\")\n .description(\"Adjust an existing CDP position\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--position <id>\", \"CDP/trove ID\")\n .option(\"--add-collateral <amount>\", \"Add collateral in wei\")\n .option(\"--withdraw-collateral <amount>\", \"Withdraw collateral in wei\")\n .option(\"--mint <amount>\", \"Mint additional stablecoin\")\n .option(\"--repay <amount>\", \"Repay stablecoin\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createCdp(protocol, chain.effectiveRpcUrl());\n const tx = await adapter.buildAdjust({\n protocol: protocol.name, cdp_id: BigInt(opts.position),\n collateral_delta: opts.addCollateral ? BigInt(opts.addCollateral) : opts.withdrawCollateral ? BigInt(opts.withdrawCollateral) : undefined,\n debt_delta: opts.mint ? BigInt(opts.mint) : opts.repay ? BigInt(opts.repay) : undefined,\n add_collateral: !!opts.addCollateral, add_debt: !!opts.mint,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n cdp.command(\"close\")\n .description(\"Close a CDP position\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--position <id>\", \"CDP/trove ID\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createCdp(protocol, chain.effectiveRpcUrl());\n const tx = await adapter.buildClose({ protocol: protocol.name, cdp_id: BigInt(opts.position) });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createLiquidStaking } from \"@hypurrquant/defi-protocols\";\n\nexport function registerStaking(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const staking = parent.command(\"staking\").description(\"Liquid staking: stake, unstake, info\");\n\n staking.command(\"stake\")\n .description(\"Stake tokens via liquid staking\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLiquidStaking(protocol, chain.effectiveRpcUrl());\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildStake({ protocol: protocol.name, amount: BigInt(opts.amount), recipient });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n staking.command(\"unstake\")\n .description(\"Unstake tokens\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLiquidStaking(protocol, chain.effectiveRpcUrl());\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildUnstake({ protocol: protocol.name, amount: BigInt(opts.amount), recipient });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n staking.command(\"info\")\n .description(\"Show staking info and rates\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLiquidStaking(protocol, chain.effectiveRpcUrl());\n const info = await adapter.getInfo();\n printOutput(info, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createVault } from \"@hypurrquant/defi-protocols\";\n\nexport function registerVault(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const vault = parent.command(\"vault\").description(\"Vault operations: deposit, withdraw, info\");\n\n vault.command(\"deposit\")\n .description(\"Deposit assets into a vault\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .option(\"--receiver <address>\", \"Receiver address for vault shares\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createVault(protocol, chain.effectiveRpcUrl());\n const receiver = (opts.receiver ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildDeposit(BigInt(opts.amount), receiver);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n vault.command(\"withdraw\")\n .description(\"Withdraw assets from a vault\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei (shares)\")\n .option(\"--receiver <address>\", \"Receiver address\")\n .option(\"--owner <address>\", \"Owner address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createVault(protocol, chain.effectiveRpcUrl());\n const receiver = (opts.receiver ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const owner = (opts.owner ?? receiver) as Address;\n const tx = await adapter.buildWithdraw(BigInt(opts.amount), receiver, owner);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n vault.command(\"info\")\n .description(\"Show vault info (TVL, APY, shares)\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createVault(protocol, chain.effectiveRpcUrl());\n const info = await adapter.getVaultInfo();\n printOutput(info, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { Address } from \"viem\";\nimport { Registry, ProtocolCategory } from \"@hypurrquant/defi-core\";\nimport type { LendingRates } from \"@hypurrquant/defi-core\";\nimport { createLending, createVault } from \"@hypurrquant/defi-protocols\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\n\nfunction resolveAsset(registry: Registry, chain: string, asset: string): Address {\n // Try parsing as address first\n if (/^0x[0-9a-fA-F]{40}$/.test(asset)) {\n return asset as Address;\n }\n return registry.resolveToken(chain, asset).address;\n}\n\n/** Collect lending rates for all lending protocols */\nasync function collectLendingRates(\n registry: Registry,\n chainName: string,\n rpc: string,\n assetAddr: Address,\n): Promise<LendingRates[]> {\n const protos = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending);\n\n const results: LendingRates[] = [];\n let first = true;\n\n for (const proto of protos) {\n if (!first) {\n // Small delay between calls to avoid rate limiting\n await new Promise((r) => setTimeout(r, 500));\n }\n first = false;\n\n try {\n const lending = createLending(proto, rpc);\n const rates = await lending.getRates(assetAddr);\n results.push(rates);\n } catch (err) {\n process.stderr.write(`Warning: ${proto.name} rates unavailable: ${err}\\n`);\n }\n }\n\n return results;\n}\n\n/** Collect all yield opportunities: lending + morpho + vaults */\nasync function collectAllYields(\n registry: Registry,\n chainName: string,\n rpc: string,\n asset: string,\n assetAddr: Address,\n): Promise<unknown[]> {\n const opportunities: unknown[] = [];\n\n // 1. Aave V3 lending rates\n const lendingRates = await collectLendingRates(registry, chainName, rpc, assetAddr);\n for (const r of lendingRates) {\n if (r.supply_apy > 0) {\n opportunities.push({\n protocol: r.protocol,\n type: \"lending_supply\",\n asset,\n apy: r.supply_apy,\n utilization: r.utilization,\n });\n }\n }\n\n // 2. Morpho Blue rates\n const chainProtos = registry.getProtocolsForChain(chainName);\n for (const proto of chainProtos) {\n if (proto.category === ProtocolCategory.Lending && proto.interface === \"morpho_blue\") {\n try {\n const lending = createLending(proto, rpc);\n const rates = await lending.getRates(assetAddr);\n if (rates.supply_apy > 0) {\n opportunities.push({\n protocol: rates.protocol,\n type: \"morpho_vault\",\n asset,\n apy: rates.supply_apy,\n utilization: rates.utilization,\n });\n }\n } catch {\n // skip\n }\n }\n }\n\n // 3. ERC-4626 vaults\n for (const proto of chainProtos) {\n if (proto.category === ProtocolCategory.Vault && proto.interface === \"erc4626\") {\n try {\n const vault = createVault(proto, rpc);\n const info = await vault.getVaultInfo();\n opportunities.push({\n protocol: info.protocol,\n type: \"vault\",\n asset,\n apy: info.apy ?? 0,\n total_assets: info.total_assets.toString(),\n });\n } catch {\n // skip\n }\n }\n }\n\n // Sort by APY descending\n opportunities.sort((a, b) => {\n const aa = (a as Record<string, unknown>)[\"apy\"] as number ?? 0;\n const ba = (b as Record<string, unknown>)[\"apy\"] as number ?? 0;\n return ba - aa;\n });\n\n return opportunities;\n}\n\n/** Scan all chains in parallel for best yield on an asset */\nasync function runYieldScan(registry: Registry, asset: string, output: OutputMode): Promise<void> {\n const t0 = Date.now();\n const chainKeys = Array.from(registry.chains.keys());\n\n const tasks = chainKeys.map(async (ck) => {\n try {\n const chain = registry.getChain(ck);\n const chainName = chain.name.toLowerCase();\n\n let assetAddr: Address;\n try {\n assetAddr = registry.resolveToken(chainName, asset).address;\n } catch {\n return [];\n }\n\n const protos = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending);\n\n if (protos.length === 0) return [];\n\n const rpc = chain.effectiveRpcUrl();\n const rates: unknown[] = [];\n\n for (const proto of protos) {\n try {\n const lending = createLending(proto, rpc);\n const r = await lending.getRates(assetAddr);\n if (r.supply_apy > 0) {\n rates.push({\n chain: chain.name,\n protocol: r.protocol,\n supply_apy: r.supply_apy,\n borrow_variable_apy: r.borrow_variable_apy,\n });\n }\n } catch {\n // skip\n }\n }\n\n return rates;\n } catch {\n return [];\n }\n });\n\n const nested = await Promise.all(tasks);\n const allRates = nested.flat() as Array<Record<string, unknown>>;\n\n // Sort by supply APY descending\n allRates.sort((a, b) => (b[\"supply_apy\"] as number ?? 0) - (a[\"supply_apy\"] as number ?? 0));\n\n const best =\n allRates.length > 0\n ? `${allRates[0][\"protocol\"]} on ${allRates[0][\"chain\"]}`\n : null;\n\n // Find arb opportunities (supply on A, borrow on B)\n const arbs: unknown[] = [];\n for (const s of allRates) {\n for (const b of allRates) {\n const sp = s[\"supply_apy\"] as number ?? 0;\n const bp = b[\"borrow_variable_apy\"] as number ?? 0;\n if (sp > bp && bp > 0) {\n const sc = s[\"chain\"] as string;\n const bc = b[\"chain\"] as string;\n const sp2 = s[\"protocol\"] as string;\n const bp2 = b[\"protocol\"] as string;\n if (sc !== bc || sp2 !== bp2) {\n arbs.push({\n spread_pct: Math.round((sp - bp) * 100) / 100,\n supply_chain: sc,\n supply_protocol: sp2,\n supply_apy: sp,\n borrow_chain: bc,\n borrow_protocol: bp2,\n borrow_apy: bp,\n strategy: sc === bc ? \"same-chain\" : \"cross-chain\",\n });\n }\n }\n }\n }\n\n arbs.sort((a, b) => {\n const as_ = (a as Record<string, unknown>)[\"spread_pct\"] as number ?? 0;\n const bs_ = (b as Record<string, unknown>)[\"spread_pct\"] as number ?? 0;\n return bs_ - as_;\n });\n arbs.splice(10); // Top 10\n\n printOutput(\n {\n asset,\n scan_duration_ms: Date.now() - t0,\n chains_scanned: chainKeys.length,\n rates: allRates,\n best_supply: best,\n arb_opportunities: arbs,\n },\n output,\n );\n}\n\n/** Scan rate entry with slug for execute subcommand */\ninterface ScanRate {\n chain: string;\n protocol: string;\n slug: string;\n supply_apy: number;\n borrow_variable_apy: number;\n}\n\n/** Run a cross-chain yield scan and return typed rate entries */\nasync function scanRatesForExecute(registry: Registry, asset: string): Promise<ScanRate[]> {\n const chainKeys = Array.from(registry.chains.keys());\n\n const tasks = chainKeys.map(async (ck): Promise<ScanRate[]> => {\n try {\n const chain = registry.getChain(ck);\n const chainName = chain.name.toLowerCase();\n let assetAddr: Address;\n try {\n assetAddr = registry.resolveToken(chainName, asset).address;\n } catch {\n return [];\n }\n const protos = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending);\n if (protos.length === 0) return [];\n const rpc = chain.effectiveRpcUrl();\n const rates: ScanRate[] = [];\n for (const proto of protos) {\n try {\n const lending = createLending(proto, rpc);\n const r = await lending.getRates(assetAddr);\n if (r.supply_apy > 0) {\n rates.push({\n chain: chain.name,\n protocol: r.protocol,\n slug: proto.slug,\n supply_apy: r.supply_apy,\n borrow_variable_apy: r.borrow_variable_apy,\n });\n }\n } catch {\n // skip unreachable\n }\n }\n return rates;\n } catch {\n return [];\n }\n });\n\n const nested = await Promise.all(tasks);\n const all = nested.flat();\n all.sort((a, b) => b.supply_apy - a.supply_apy);\n return all;\n}\n\nexport function registerYield(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const yieldCmd = parent\n .command(\"yield\")\n .description(\"Yield operations: compare, scan, optimize, execute\");\n\n // yield (no subcommand) = compare with default USDC\n yieldCmd\n .option(\"--asset <token>\", \"Token symbol or address\", \"USDC\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n const chainName: string = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n const chain = registry.getChain(chainName);\n const rpc = chain.effectiveRpcUrl();\n const assetAddr = resolveAsset(registry, chainName, opts.asset as string);\n const results = await collectLendingRates(registry, chainName, rpc, assetAddr);\n results.sort((a, b) => b.supply_apy - a.supply_apy);\n const bestSupply = results[0]?.protocol ?? null;\n const bestBorrow = results.reduce((best, r) => {\n if (!best || r.borrow_variable_apy < best.borrow_variable_apy) return r;\n return best;\n }, null as LendingRates | null)?.protocol ?? null;\n printOutput({ asset: opts.asset, chain: chainName, rates: results, best_supply: bestSupply, best_borrow: bestBorrow }, getOpts());\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n }\n });\n\n // yield compare\n yieldCmd\n .command(\"compare\")\n .description(\"Compare lending rates across protocols for an asset\")\n .option(\"--asset <token>\", \"Token symbol or address\", \"USDC\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n const chainName: string = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n const chain = registry.getChain(chainName);\n const rpc = chain.effectiveRpcUrl();\n const assetAddr = resolveAsset(registry, chainName, opts.asset as string);\n\n const results = await collectLendingRates(registry, chainName, rpc, assetAddr);\n\n if (results.length === 0) {\n printOutput(\n { error: `No lending rate data available for asset '${opts.asset}'` },\n getOpts(),\n );\n process.exit(1);\n return;\n }\n\n results.sort((a, b) => b.supply_apy - a.supply_apy);\n\n const bestSupply = results[0]?.protocol ?? null;\n const bestBorrow =\n results.reduce((best, r) => {\n if (!best || r.borrow_variable_apy < best.borrow_variable_apy) return r;\n return best;\n }, null as LendingRates | null)?.protocol ?? null;\n\n printOutput(\n {\n asset: opts.asset,\n rates: results,\n best_supply: bestSupply,\n best_borrow: bestBorrow,\n },\n getOpts(),\n );\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n process.exit(1);\n }\n });\n\n // yield scan\n yieldCmd\n .command(\"scan\")\n .description(\"Scan all chains for best yield opportunities (parallel)\")\n .requiredOption(\"--asset <token>\", \"Token symbol (e.g. USDC, WETH)\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n await runYieldScan(registry, opts.asset as string, getOpts());\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n process.exit(1);\n }\n });\n\n // yield execute\n yieldCmd\n .command(\"execute\")\n .description(\"Find the best yield opportunity and execute supply (or show cross-chain plan)\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address (e.g. USDC)\")\n .requiredOption(\"--amount <amount>\", \"Human-readable amount to supply (e.g. 1000)\")\n .option(\"--min-spread <percent>\", \"Minimum spread % required to execute cross-chain arb\", \"1.0\")\n .option(\"--target-chain <chain>\", \"Override auto-detected best chain\")\n .option(\"--target-protocol <protocol>\", \"Override auto-detected best protocol slug\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n const asset = opts.asset as string;\n const humanAmount = parseFloat(opts.amount as string);\n if (isNaN(humanAmount) || humanAmount <= 0) {\n printOutput({ error: `Invalid amount: ${opts.amount}` }, getOpts());\n process.exit(1);\n return;\n }\n const minSpread = parseFloat((opts.minSpread as string) ?? \"1.0\");\n\n let targetChainName: string;\n let targetProtocolSlug: string | undefined = opts.targetProtocol as string | undefined;\n\n if (opts.targetChain) {\n // Manual chain override — skip scan\n targetChainName = (opts.targetChain as string).toLowerCase();\n } else {\n // Run cross-chain scan to find best supply opportunity\n process.stderr.write(`Scanning all chains for best ${asset} yield...\\n`);\n const t0 = Date.now();\n const allRates = await scanRatesForExecute(registry, asset);\n process.stderr.write(`Scan done in ${Date.now() - t0}ms — ${allRates.length} rates found\\n`);\n\n if (allRates.length === 0) {\n printOutput({ error: `No yield opportunities found for ${asset}` }, getOpts());\n process.exit(1);\n return;\n }\n\n // Find best cross-chain arb (highest spread)\n let bestArb: {\n spread_pct: number;\n supply_chain: string;\n supply_protocol: string;\n supply_slug: string;\n supply_apy: number;\n borrow_chain: string;\n borrow_protocol: string;\n borrow_apy: number;\n strategy: string;\n } | null = null;\n\n for (const s of allRates) {\n for (const b of allRates) {\n const spread = s.supply_apy - b.borrow_variable_apy;\n if (spread > 0 && b.borrow_variable_apy > 0 && (s.chain !== b.chain || s.slug !== b.slug)) {\n if (!bestArb || spread > bestArb.spread_pct) {\n bestArb = {\n spread_pct: Math.round(spread * 10000) / 10000,\n supply_chain: s.chain,\n supply_protocol: s.protocol,\n supply_slug: s.slug,\n supply_apy: s.supply_apy,\n borrow_chain: b.chain,\n borrow_protocol: b.protocol,\n borrow_apy: b.borrow_variable_apy,\n strategy: s.chain === b.chain ? \"same-chain\" : \"cross-chain\",\n };\n }\n }\n }\n }\n\n // If best arb is cross-chain and meets min-spread: output plan only (no execution)\n if (bestArb && bestArb.strategy === \"cross-chain\" && bestArb.spread_pct >= minSpread) {\n const supplyChainLower = bestArb.supply_chain.toLowerCase();\n let supplyAssetAddr: Address | undefined;\n let supplyDecimals = 18;\n try {\n const tok = registry.resolveToken(supplyChainLower, asset);\n supplyAssetAddr = tok.address;\n supplyDecimals = tok.decimals;\n } catch {\n // leave as undefined\n }\n const amountWei = BigInt(Math.round(humanAmount * 10 ** supplyDecimals));\n\n printOutput(\n {\n mode: \"plan_only\",\n reason: \"cross-chain arb requires manual bridge execution\",\n asset,\n amount_human: humanAmount,\n amount_wei: amountWei.toString(),\n best_arb: bestArb,\n steps: [\n {\n step: 1,\n action: \"bridge\",\n description: `Bridge ${humanAmount} ${asset} from current chain to ${bestArb.supply_chain}`,\n from_chain: \"current\",\n to_chain: bestArb.supply_chain,\n token: asset,\n amount_wei: amountWei.toString(),\n },\n {\n step: 2,\n action: \"supply\",\n description: `Supply ${humanAmount} ${asset} on ${bestArb.supply_protocol}`,\n chain: bestArb.supply_chain,\n protocol: bestArb.supply_protocol,\n protocol_slug: bestArb.supply_slug,\n asset_address: supplyAssetAddr,\n amount_wei: amountWei.toString(),\n expected_apy: bestArb.supply_apy,\n },\n ],\n expected_spread_pct: bestArb.spread_pct,\n supply_apy: bestArb.supply_apy,\n borrow_apy: bestArb.borrow_apy,\n },\n getOpts(),\n );\n return;\n }\n\n // Fall through to same-chain supply on the best rate\n targetChainName = allRates[0].chain.toLowerCase();\n if (!targetProtocolSlug) {\n targetProtocolSlug = allRates[0].slug;\n }\n }\n\n // Same-chain supply execution path\n const chain = registry.getChain(targetChainName);\n const chainName = chain.name.toLowerCase();\n const rpc = chain.effectiveRpcUrl();\n\n // Resolve asset address + decimals on target chain\n let assetAddr: Address;\n let decimals = 18;\n try {\n const tok = registry.resolveToken(chainName, asset);\n assetAddr = tok.address;\n decimals = tok.decimals;\n } catch {\n if (/^0x[0-9a-fA-F]{40}$/.test(asset)) {\n assetAddr = asset as Address;\n } else {\n printOutput({ error: `Cannot resolve ${asset} on chain ${chainName}` }, getOpts());\n process.exit(1);\n return;\n }\n }\n\n const amountWei = BigInt(Math.round(humanAmount * 10 ** decimals));\n\n // Resolve protocol\n let proto: ReturnType<typeof registry.getProtocol>;\n if (targetProtocolSlug) {\n try {\n proto = registry.getProtocol(targetProtocolSlug);\n } catch {\n printOutput({ error: `Protocol not found: ${targetProtocolSlug}` }, getOpts());\n process.exit(1);\n return;\n }\n } else {\n // Pick the aave_v3 protocol on the target chain with highest supply APY\n const candidates = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending);\n if (candidates.length === 0) {\n printOutput({ error: `No aave_v3 lending protocol found on ${chainName}` }, getOpts());\n process.exit(1);\n return;\n }\n let bestRate: LendingRates | null = null;\n let bestProto = candidates[0];\n for (const c of candidates) {\n try {\n const lending = createLending(c, rpc);\n const r = await lending.getRates(assetAddr);\n if (!bestRate || r.supply_apy > bestRate.supply_apy) {\n bestRate = r;\n bestProto = c;\n }\n } catch {\n // skip\n }\n }\n proto = bestProto;\n }\n\n const onBehalfOf = (\n process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\"\n ) as Address;\n const adapter = createLending(proto, rpc);\n\n // Fetch current rate for display (non-fatal)\n let currentApy: number | undefined;\n try {\n const r = await adapter.getRates(assetAddr);\n currentApy = r.supply_apy;\n } catch {\n // non-fatal\n }\n\n process.stderr.write(\n `Supplying ${humanAmount} ${asset} (${amountWei} wei) on ${proto.name} (${chain.name})...\\n`,\n );\n\n const executor = makeExecutor();\n const tx = await adapter.buildSupply({\n protocol: proto.name,\n asset: assetAddr,\n amount: amountWei,\n on_behalf_of: onBehalfOf,\n });\n\n const result = await executor.execute(tx);\n\n printOutput(\n {\n action: \"yield_execute\",\n asset,\n amount_human: humanAmount,\n amount_wei: amountWei.toString(),\n chain: chain.name,\n protocol: proto.name,\n protocol_slug: proto.slug,\n supply_apy: currentApy,\n result,\n },\n getOpts(),\n );\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n process.exit(1);\n }\n });\n\n // yield optimize\n yieldCmd\n .command(\"optimize\")\n .description(\"Find the optimal yield strategy for an asset\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .option(\"--strategy <strategy>\", \"Strategy: best-supply, leverage-loop, auto\", \"auto\")\n .option(\"--amount <amount>\", \"Amount to deploy (for allocation breakdown)\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n const chainName: string = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n const chain = registry.getChain(chainName);\n const rpc = chain.effectiveRpcUrl();\n const asset = opts.asset as string;\n const assetAddr = resolveAsset(registry, chainName, asset);\n const strategy = (opts.strategy as string) ?? \"auto\";\n\n if (strategy === \"auto\") {\n const opportunities = await collectAllYields(registry, chainName, rpc, asset, assetAddr);\n\n if (opportunities.length === 0) {\n printOutput({ error: `No yield opportunities found for '${asset}'` }, getOpts());\n process.exit(1);\n return;\n }\n\n const amount = opts.amount ? parseFloat(opts.amount as string) : null;\n const weights = [0.6, 0.3, 0.1];\n const allocations =\n amount !== null\n ? opportunities.slice(0, weights.length).map((opp, i) => ({\n protocol: (opp as Record<string, unknown>)[\"protocol\"],\n type: (opp as Record<string, unknown>)[\"type\"],\n apy: (opp as Record<string, unknown>)[\"apy\"],\n allocation_pct: weights[i] * 100,\n amount: (amount * weights[i]).toFixed(2),\n }))\n : [];\n\n const best = opportunities[0] as Record<string, unknown>;\n const weightedApy =\n allocations.length > 0\n ? opportunities.slice(0, weights.length).reduce((sum: number, o, i) => {\n return sum + ((o as Record<string, unknown>)[\"apy\"] as number ?? 0) * weights[i];\n }, 0)\n : (best[\"apy\"] as number ?? 0);\n\n printOutput(\n {\n strategy: \"auto\",\n asset,\n best_protocol: best[\"protocol\"],\n best_apy: best[\"apy\"],\n weighted_apy: weightedApy,\n opportunities,\n allocation: allocations,\n },\n getOpts(),\n );\n } else if (strategy === \"best-supply\") {\n const results = await collectLendingRates(registry, chainName, rpc, assetAddr);\n\n if (results.length === 0) {\n printOutput({ error: `No lending rate data available for asset '${asset}'` }, getOpts());\n process.exit(1);\n return;\n }\n\n results.sort((a, b) => b.supply_apy - a.supply_apy);\n const best = results[0];\n const recommendations = results.map((r) => ({\n protocol: r.protocol,\n supply_apy: r.supply_apy,\n action: \"supply\",\n }));\n\n printOutput(\n {\n strategy: \"best-supply\",\n asset,\n recommendation: `Supply ${asset} on ${best.protocol} for ${(best.supply_apy * 100).toFixed(2)}% APY`,\n best_protocol: best.protocol,\n best_supply_apy: best.supply_apy,\n all_options: recommendations,\n },\n getOpts(),\n );\n } else if (strategy === \"leverage-loop\") {\n const results = await collectLendingRates(registry, chainName, rpc, assetAddr);\n\n if (results.length === 0) {\n printOutput({ error: `No lending rate data available for asset '${asset}'` }, getOpts());\n process.exit(1);\n return;\n }\n\n const ltv = 0.8;\n const loops = 5;\n const candidates: unknown[] = [];\n\n for (const r of results) {\n const threshold = r.borrow_variable_apy * 0.8;\n if (r.supply_apy > threshold && r.borrow_variable_apy > 0) {\n let effectiveSupplyApy = 0;\n let effectiveBorrowApy = 0;\n let leverage = 1.0;\n for (let l = 0; l < loops; l++) {\n effectiveSupplyApy += r.supply_apy * leverage;\n effectiveBorrowApy += r.borrow_variable_apy * leverage * ltv;\n leverage *= ltv;\n }\n candidates.push({\n protocol: r.protocol,\n supply_apy: r.supply_apy,\n borrow_variable_apy: r.borrow_variable_apy,\n loops,\n ltv,\n effective_supply_apy: effectiveSupplyApy,\n effective_borrow_cost: effectiveBorrowApy,\n net_apy: effectiveSupplyApy - effectiveBorrowApy,\n });\n }\n }\n\n candidates.sort((a, b) => {\n const an = (a as Record<string, unknown>)[\"net_apy\"] as number ?? 0;\n const bn = (b as Record<string, unknown>)[\"net_apy\"] as number ?? 0;\n return bn - an;\n });\n\n const recommendation =\n candidates.length > 0\n ? (() => {\n const b = candidates[0] as Record<string, unknown>;\n return `Leverage loop ${asset} on ${b[\"protocol\"]} — net APY: ${((b[\"net_apy\"] as number) * 100).toFixed(2)}% (${loops} loops at ${ltv * 100}% LTV)`;\n })()\n : `No favorable leverage loop found for ${asset} — supply rate too low relative to borrow rate`;\n\n printOutput(\n {\n strategy: \"leverage-loop\",\n asset,\n recommendation,\n candidates,\n },\n getOpts(),\n );\n } else {\n printOutput(\n { error: `Unknown strategy '${strategy}'. Supported: best-supply, leverage-loop, auto` },\n getOpts(),\n );\n process.exit(1);\n }\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n process.exit(1);\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport { Registry, ProtocolCategory, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { takeSnapshot, saveSnapshot, loadSnapshots, calculatePnL } from \"../portfolio-tracker.js\";\n\nconst ERC20_ABI = parseAbi([\n \"function balanceOf(address owner) external view returns (uint256)\",\n]);\n\nconst POOL_ABI = parseAbi([\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n]);\n\nfunction decodeU256(data: Hex | null, wordOffset = 0): bigint {\n if (!data || data.length < 2 + (wordOffset + 1) * 64) return 0n;\n const hex = data.slice(2 + wordOffset * 64, 2 + wordOffset * 64 + 64);\n return BigInt(\"0x\" + hex);\n}\n\nexport function registerPortfolio(parent: Command, getOpts: () => OutputMode): void {\n const portfolio = parent\n .command(\"portfolio\")\n .description(\"Aggregate positions across all protocols\");\n\n // Show current positions\n portfolio\n .command(\"show\")\n .description(\"Show current portfolio positions\")\n .requiredOption(\"--address <address>\", \"Wallet address to query\")\n .action(async (opts: { address: string }) => {\n\n const mode = getOpts();\n const registry = Registry.loadEmbedded();\n const chainName = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n\n let chain;\n try {\n chain = registry.getChain(chainName);\n } catch (e) {\n printOutput({ error: `Chain not found: ${chainName}` }, mode);\n return;\n }\n\n const user = opts.address as Address;\n if (!/^0x[0-9a-fA-F]{40}$/.test(user)) {\n printOutput({ error: `Invalid address: ${opts.address}` }, mode);\n return;\n }\n\n const rpc = chain.effectiveRpcUrl();\n const calls: Array<[Address, Hex]> = [];\n const callLabels: string[] = [];\n\n // 1. Token balances\n const tokenSymbols: string[] = (registry.tokens.get(chainName) ?? []).map((t) => t.symbol);\n\n for (const symbol of tokenSymbols) {\n let entry;\n try {\n entry = registry.resolveToken(chainName, symbol);\n } catch {\n continue;\n }\n if (entry.address === (\"0x0000000000000000000000000000000000000000\" as Address)) continue;\n calls.push([\n entry.address as Address,\n encodeFunctionData({ abi: ERC20_ABI, functionName: \"balanceOf\", args: [user] }),\n ]);\n callLabels.push(`balance:${symbol}`);\n }\n\n // 2. Lending positions — aave_v3 pools\n const lendingProtocols = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending && p.interface === \"aave_v3\")\n .filter((p) => p.contracts?.[\"pool\"]);\n\n for (const p of lendingProtocols) {\n calls.push([\n p.contracts![\"pool\"] as Address,\n encodeFunctionData({ abi: POOL_ABI, functionName: \"getUserAccountData\", args: [user] }),\n ]);\n callLabels.push(`lending:${p.name}`);\n }\n\n // 3. Native token price from first available oracle\n const oracleEntry = registry\n .getProtocolsForChain(chainName)\n .find((p) => p.interface === \"aave_v3\" && p.contracts?.[\"oracle\"]);\n const oracleAddr = oracleEntry?.contracts?.[\"oracle\"] as Address | undefined;\n const wrappedNative = (chain.wrapped_native ?? \"0x5555555555555555555555555555555555555555\") as Address;\n\n if (oracleAddr) {\n calls.push([\n oracleAddr,\n encodeFunctionData({ abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [wrappedNative] }),\n ]);\n callLabels.push(\"price:native\");\n }\n\n if (calls.length === 0) {\n printOutput(\n {\n address: user,\n chain: chain.name,\n error: \"No protocols or tokens configured for this chain\",\n },\n mode,\n );\n return;\n }\n\n let results: (Hex | null)[];\n try {\n results = await multicallRead(rpc, calls);\n } catch (e) {\n printOutput({ error: `Multicall failed: ${e instanceof Error ? e.message : String(e)}` }, mode);\n return;\n }\n\n // Get native price (last call if oracle present)\n let nativePriceUsd = 0;\n if (oracleAddr) {\n const priceData = results[results.length - 1] ?? null;\n nativePriceUsd = Number(decodeU256(priceData)) / 1e8;\n }\n\n let totalValueUsd = 0;\n let idx = 0;\n const tokenBalances: unknown[] = [];\n\n // Parse token balances\n for (const symbol of tokenSymbols) {\n let entry;\n try {\n entry = registry.resolveToken(chainName, symbol);\n } catch {\n continue;\n }\n if (entry.address === (\"0x0000000000000000000000000000000000000000\" as Address)) continue;\n if (idx >= results.length) break;\n\n const balance = decodeU256(results[idx] ?? null);\n if (balance > 0n) {\n const decimals = entry.decimals;\n const balF64 = Number(balance) / 10 ** decimals;\n const symbolUpper = symbol.toUpperCase();\n const valueUsd =\n symbolUpper.includes(\"USD\") || symbolUpper.includes(\"usd\")\n ? balF64\n : balF64 * nativePriceUsd;\n totalValueUsd += valueUsd;\n tokenBalances.push({\n symbol,\n balance: balF64.toFixed(4),\n value_usd: valueUsd.toFixed(2),\n });\n }\n idx++;\n }\n\n // Parse lending positions\n const lendingPositions: unknown[] = [];\n for (const p of lendingProtocols) {\n if (idx >= results.length) break;\n const data = results[idx] ?? null;\n if (data && data.length >= 2 + 192 * 2) {\n const collateral = Number(decodeU256(data, 0)) / 1e8;\n const debt = Number(decodeU256(data, 1)) / 1e8;\n const hfRaw = decodeU256(data, 5);\n let hf: number | null = null;\n if (hfRaw <= BigInt(\"0xffffffffffffffffffffffffffffffff\")) {\n const v = Number(hfRaw) / 1e18;\n hf = v > 1e10 ? null : v;\n }\n if (collateral > 0 || debt > 0) {\n totalValueUsd += collateral - debt;\n lendingPositions.push({\n protocol: p.name,\n collateral_usd: collateral.toFixed(2),\n debt_usd: debt.toFixed(2),\n health_factor: hf,\n });\n }\n }\n idx++;\n }\n\n printOutput(\n {\n address: user,\n chain: chain.name,\n native_price_usd: nativePriceUsd.toFixed(2),\n total_value_usd: totalValueUsd.toFixed(2),\n token_balances: tokenBalances,\n lending_positions: lendingPositions,\n },\n mode,\n );\n });\n\n // --- Subcommand: snapshot ---\n portfolio\n .command(\"snapshot\")\n .description(\"Take a new portfolio snapshot and save it locally\")\n .requiredOption(\"--address <address>\", \"Wallet address to snapshot\")\n .action(async (opts: { address: string }) => {\n const mode = getOpts();\n const chainName = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n const registry = Registry.loadEmbedded();\n\n if (!/^0x[0-9a-fA-F]{40}$/.test(opts.address)) {\n printOutput({ error: `Invalid address: ${opts.address}` }, mode);\n return;\n }\n\n try {\n const snapshot = await takeSnapshot(chainName, opts.address, registry);\n const filepath = saveSnapshot(snapshot);\n printOutput(\n {\n saved: filepath,\n timestamp: new Date(snapshot.timestamp).toISOString(),\n chain: snapshot.chain,\n wallet: snapshot.wallet,\n total_value_usd: snapshot.total_value_usd.toFixed(2),\n token_count: snapshot.tokens.length,\n defi_position_count: snapshot.defi_positions.length,\n },\n mode,\n );\n } catch (e) {\n printOutput({ error: e instanceof Error ? e.message : String(e) }, mode);\n }\n });\n\n // --- Subcommand: pnl ---\n portfolio\n .command(\"pnl\")\n .description(\"Show PnL since the last snapshot\")\n .requiredOption(\"--address <address>\", \"Wallet address\")\n .option(\"--since <hours>\", \"Compare against snapshot from N hours ago (default: last snapshot)\")\n .action(async (opts: { address: string; since?: string }) => {\n const mode = getOpts();\n const chainName = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n const registry = Registry.loadEmbedded();\n\n if (!/^0x[0-9a-fA-F]{40}$/.test(opts.address)) {\n printOutput({ error: `Invalid address: ${opts.address}` }, mode);\n return;\n }\n\n const snapshots = loadSnapshots(chainName, opts.address, 50);\n if (snapshots.length === 0) {\n printOutput({ error: \"No snapshots found. Run `portfolio snapshot` first.\" }, mode);\n return;\n }\n\n let previous = snapshots[0];\n if (opts.since) {\n const sinceMs = parseFloat(opts.since) * 60 * 60 * 1000;\n const cutoff = Date.now() - sinceMs;\n const match = snapshots.find((s) => s.timestamp <= cutoff);\n if (!match) {\n printOutput({ error: `No snapshot found older than ${opts.since} hours` }, mode);\n return;\n }\n previous = match;\n }\n\n try {\n const current = await takeSnapshot(chainName, opts.address, registry);\n const pnl = calculatePnL(current, previous);\n printOutput(\n {\n chain: chainName,\n wallet: opts.address,\n previous_snapshot: new Date(previous.timestamp).toISOString(),\n current_time: new Date(current.timestamp).toISOString(),\n ...pnl,\n pnl_usd: pnl.pnl_usd.toFixed(2),\n pnl_pct: pnl.pnl_pct.toFixed(4),\n start_value_usd: pnl.start_value_usd.toFixed(2),\n end_value_usd: pnl.end_value_usd.toFixed(2),\n },\n mode,\n );\n } catch (e) {\n printOutput({ error: e instanceof Error ? e.message : String(e) }, mode);\n }\n });\n\n // --- Subcommand: history ---\n portfolio\n .command(\"history\")\n .description(\"List saved portfolio snapshots with values\")\n .requiredOption(\"--address <address>\", \"Wallet address\")\n .option(\"--limit <n>\", \"Number of snapshots to show\", \"10\")\n .action(async (opts: { address: string; limit: string }) => {\n const mode = getOpts();\n const chainName = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n\n if (!/^0x[0-9a-fA-F]{40}$/.test(opts.address)) {\n printOutput({ error: `Invalid address: ${opts.address}` }, mode);\n return;\n }\n\n const limit = parseInt(opts.limit, 10);\n const snapshots = loadSnapshots(chainName, opts.address, limit);\n\n if (snapshots.length === 0) {\n printOutput({ message: \"No snapshots found for this address on this chain.\" }, mode);\n return;\n }\n\n const history = snapshots.map((s) => ({\n timestamp: new Date(s.timestamp).toISOString(),\n chain: s.chain,\n wallet: s.wallet,\n total_value_usd: s.total_value_usd.toFixed(2),\n token_count: s.tokens.length,\n defi_position_count: s.defi_positions.length,\n }));\n\n printOutput({ snapshots: history }, mode);\n });\n}\n","import { mkdirSync, writeFileSync, readdirSync, readFileSync, existsSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { resolve } from \"path\";\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport { Registry, ProtocolCategory, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { PortfolioSnapshot, TokenBalance, DefiPosition, PortfolioPnL, TokenChange } from \"@hypurrquant/defi-core\";\n\nconst ERC20_ABI = parseAbi([\n \"function balanceOf(address owner) external view returns (uint256)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n]);\n\nconst POOL_ABI = parseAbi([\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n]);\n\nfunction decodeU256Word(data: Hex | null, wordOffset = 0): bigint {\n if (!data || data.length < 2 + (wordOffset + 1) * 64) return 0n;\n const hex = data.slice(2 + wordOffset * 64, 2 + wordOffset * 64 + 64);\n return BigInt(\"0x\" + hex);\n}\n\nfunction snapshotDir(): string {\n return resolve(homedir(), \".defi-cli\", \"snapshots\");\n}\n\nexport async function takeSnapshot(\n chainName: string,\n wallet: string,\n registry: Registry,\n): Promise<PortfolioSnapshot> {\n const chain = registry.getChain(chainName);\n const user = wallet as Address;\n const rpc = chain.effectiveRpcUrl();\n\n const calls: Array<[Address, Hex]> = [];\n const callLabels: string[] = [];\n\n // 1. Token balances\n const tokenEntries: Array<{ symbol: string; address: Address; decimals: number }> = [];\n for (const t of registry.tokens.get(chainName) ?? []) {\n let entry;\n try {\n entry = registry.resolveToken(chainName, t.symbol);\n } catch {\n continue;\n }\n if (entry.address === (\"0x0000000000000000000000000000000000000000\" as Address)) continue;\n tokenEntries.push({ symbol: t.symbol, address: entry.address as Address, decimals: entry.decimals });\n calls.push([\n entry.address as Address,\n encodeFunctionData({ abi: ERC20_ABI, functionName: \"balanceOf\", args: [user] }),\n ]);\n callLabels.push(`balance:${t.symbol}`);\n }\n\n // 2. Lending positions (aave_v3)\n const lendingProtocols = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending && p.interface === \"aave_v3\")\n .filter((p) => p.contracts?.[\"pool\"]);\n\n for (const p of lendingProtocols) {\n calls.push([\n p.contracts![\"pool\"] as Address,\n encodeFunctionData({ abi: POOL_ABI, functionName: \"getUserAccountData\", args: [user] }),\n ]);\n callLabels.push(`lending:${p.name}`);\n }\n\n // 3. Native price from oracle\n const oracleEntry = registry\n .getProtocolsForChain(chainName)\n .find((p) => p.interface === \"aave_v3\" && p.contracts?.[\"oracle\"]);\n const oracleAddr = oracleEntry?.contracts?.[\"oracle\"] as Address | undefined;\n const wrappedNative = (chain.wrapped_native ?? \"0x5555555555555555555555555555555555555555\") as Address;\n\n if (oracleAddr) {\n calls.push([\n oracleAddr,\n encodeFunctionData({ abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [wrappedNative] }),\n ]);\n callLabels.push(\"price:native\");\n }\n\n let results: (Hex | null)[] = calls.map(() => null);\n if (calls.length > 0) {\n results = await multicallRead(rpc, calls);\n }\n\n // Native price\n let nativePriceUsd = 0;\n if (oracleAddr) {\n const priceData = results[results.length - 1] ?? null;\n nativePriceUsd = Number(decodeU256Word(priceData)) / 1e8;\n }\n\n let idx = 0;\n const tokens: TokenBalance[] = [];\n let totalValueUsd = 0;\n\n // Parse token balances\n for (const entry of tokenEntries) {\n if (idx >= results.length) break;\n const balance = decodeU256Word(results[idx] ?? null);\n const balF64 = Number(balance) / 10 ** entry.decimals;\n const symbolUpper = entry.symbol.toUpperCase();\n const priceUsd =\n symbolUpper.includes(\"USD\") ? 1 : nativePriceUsd;\n const valueUsd = balF64 * priceUsd;\n totalValueUsd += valueUsd;\n tokens.push({\n token: entry.address,\n symbol: entry.symbol,\n balance,\n value_usd: valueUsd,\n price_usd: priceUsd,\n });\n idx++;\n }\n\n // Parse lending positions\n const defiPositions: DefiPosition[] = [];\n for (const p of lendingProtocols) {\n if (idx >= results.length) break;\n const data = results[idx] ?? null;\n if (data && data.length >= 2 + 192 * 2) {\n const collateral = Number(decodeU256Word(data, 0)) / 1e8;\n const debt = Number(decodeU256Word(data, 1)) / 1e8;\n if (collateral > 0) {\n totalValueUsd += collateral;\n defiPositions.push({\n protocol: p.name,\n type: \"lending_supply\",\n asset: \"collateral\",\n amount: BigInt(Math.round(collateral * 1e8)),\n value_usd: collateral,\n });\n }\n if (debt > 0) {\n totalValueUsd -= debt;\n defiPositions.push({\n protocol: p.name,\n type: \"lending_borrow\",\n asset: \"debt\",\n amount: BigInt(Math.round(debt * 1e8)),\n value_usd: debt,\n });\n }\n }\n idx++;\n }\n\n return {\n timestamp: Date.now(),\n chain: chainName,\n wallet,\n tokens,\n defi_positions: defiPositions,\n total_value_usd: totalValueUsd,\n };\n}\n\nexport function saveSnapshot(snapshot: PortfolioSnapshot): string {\n const dir = snapshotDir();\n mkdirSync(dir, { recursive: true });\n const filename = `${snapshot.chain}_${snapshot.wallet}_${snapshot.timestamp}.json`;\n const filepath = resolve(dir, filename);\n writeFileSync(filepath, JSON.stringify(snapshot, (_k, v) => (typeof v === \"bigint\" ? v.toString() : v), 2));\n return filepath;\n}\n\nexport function loadSnapshots(chain: string, wallet: string, limit = 10): PortfolioSnapshot[] {\n const dir = snapshotDir();\n if (!existsSync(dir)) return [];\n\n const prefix = `${chain}_${wallet}_`;\n const files = readdirSync(dir)\n .filter((f) => f.startsWith(prefix) && f.endsWith(\".json\"))\n .sort()\n .reverse()\n .slice(0, limit);\n\n return files.map((f) => {\n const raw = JSON.parse(readFileSync(resolve(dir, f), \"utf-8\"));\n // Restore bigint fields\n if (Array.isArray(raw.tokens)) {\n for (const t of raw.tokens) {\n if (typeof t.balance === \"string\") t.balance = BigInt(t.balance);\n }\n }\n if (Array.isArray(raw.defi_positions)) {\n for (const p of raw.defi_positions) {\n if (typeof p.amount === \"string\") p.amount = BigInt(p.amount);\n }\n }\n return raw as PortfolioSnapshot;\n });\n}\n\nexport function calculatePnL(current: PortfolioSnapshot, previous: PortfolioSnapshot): PortfolioPnL {\n const startValue = previous.total_value_usd;\n const endValue = current.total_value_usd;\n const pnlUsd = endValue - startValue;\n const pnlPct = startValue !== 0 ? (pnlUsd / startValue) * 100 : 0;\n\n const prevTokenMap = new Map<string, TokenBalance>();\n for (const t of previous.tokens) {\n prevTokenMap.set(t.symbol, t);\n }\n\n const tokenChanges: TokenChange[] = [];\n for (const t of current.tokens) {\n const prev = prevTokenMap.get(t.symbol);\n const prevBalance = prev?.balance ?? 0n;\n const prevValueUsd = prev?.value_usd ?? 0;\n const balanceChange = t.balance - prevBalance;\n const valueChangeUsd = t.value_usd - prevValueUsd;\n if (balanceChange !== 0n || Math.abs(valueChangeUsd) > 0.001) {\n tokenChanges.push({\n symbol: t.symbol,\n balance_change: balanceChange,\n value_change_usd: valueChangeUsd,\n });\n }\n }\n\n const durationMs = current.timestamp - previous.timestamp;\n const durationHours = durationMs / (1000 * 60 * 60);\n const period =\n durationHours < 1\n ? `${Math.round(durationMs / 60000)}m`\n : durationHours < 24\n ? `${durationHours.toFixed(1)}h`\n : `${(durationHours / 24).toFixed(1)}d`;\n\n return {\n period,\n start_value_usd: startValue,\n end_value_usd: endValue,\n pnl_usd: pnlUsd,\n pnl_pct: pnlPct,\n token_changes: tokenChanges,\n };\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry, ProtocolCategory } from \"@hypurrquant/defi-core\";\nimport { createLending } from \"@hypurrquant/defi-protocols\";\nimport type { Address } from \"viem\";\n\ninterface PositionResult {\n chain: string;\n protocol: string;\n health_factor: number;\n total_supply_usd: number;\n total_borrow_usd: number;\n alert: boolean;\n}\n\nasync function checkChainLendingPositions(\n chainKey: string,\n registry: Registry,\n address: Address,\n threshold: number,\n): Promise<PositionResult[]> {\n let chain;\n try {\n chain = registry.getChain(chainKey);\n } catch {\n return [];\n }\n\n const rpc = chain.effectiveRpcUrl();\n const chainName = chain.name;\n const protocols = registry.getProtocolsForChain(chainKey).filter(\n (p) => p.category === ProtocolCategory.Lending,\n );\n\n const results = await Promise.all(\n protocols.map(async (proto): Promise<PositionResult | null> => {\n try {\n const adapter = createLending(proto, rpc);\n const position = await adapter.getUserPosition(address);\n const hf = position.health_factor ?? Infinity;\n\n // Skip positions with no borrows (no liquidation risk)\n const totalBorrow = position.borrows?.reduce(\n (sum, b) => sum + (b.value_usd ?? 0),\n 0,\n ) ?? 0;\n if (totalBorrow === 0) return null;\n\n const totalSupply = position.supplies?.reduce(\n (sum, s) => sum + (s.value_usd ?? 0),\n 0,\n ) ?? 0;\n\n return {\n chain: chainName,\n protocol: proto.name,\n health_factor: hf === Infinity ? 999999 : Math.round(hf * 100) / 100,\n total_supply_usd: Math.round(totalSupply * 100) / 100,\n total_borrow_usd: Math.round(totalBorrow * 100) / 100,\n alert: hf < threshold,\n };\n } catch {\n return null;\n }\n }),\n );\n\n return results.filter((r): r is PositionResult => r !== null);\n}\n\nexport function registerMonitor(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"monitor\")\n .description(\"Monitor health factor with alerts\")\n .option(\"--protocol <protocol>\", \"Protocol slug (required unless --all-chains)\")\n .requiredOption(\"--address <address>\", \"Wallet address to monitor\")\n .option(\"--threshold <hf>\", \"Health factor alert threshold\", \"1.5\")\n .option(\"--interval <secs>\", \"Polling interval in seconds\", \"60\")\n .option(\"--once\", \"Run once instead of continuously\")\n .option(\"--all-chains\", \"Scan all chains for lending positions\")\n .action(async (opts) => {\n const threshold = parseFloat(opts.threshold);\n const address = opts.address as Address;\n\n if (opts.allChains) {\n // Multi-chain mode\n const registry = Registry.loadEmbedded();\n const chainKeys = Array.from(registry.chains.keys());\n\n const poll = async () => {\n const timestamp = new Date().toISOString();\n\n const chainResults = await Promise.all(\n chainKeys.map((ck) =>\n checkChainLendingPositions(ck, registry, address, threshold),\n ),\n );\n\n const positions = chainResults.flat();\n const alertsCount = positions.filter((p) => p.alert).length;\n\n const output = {\n timestamp,\n address,\n threshold,\n positions,\n alerts_count: alertsCount,\n };\n\n // Write alerts to stderr for visibility\n for (const pos of positions) {\n if (pos.alert) {\n process.stderr.write(\n `ALERT: ${pos.chain}/${pos.protocol} HF=${pos.health_factor} < ${threshold}\\n`,\n );\n }\n }\n\n printOutput(output, getOpts());\n };\n\n await poll();\n if (!opts.once) {\n const intervalMs = parseInt(opts.interval) * 1000;\n const timer = setInterval(poll, intervalMs);\n process.on(\"SIGINT\", () => { clearInterval(timer); process.exit(0); });\n }\n } else {\n // Single-protocol mode (backward compat)\n if (!opts.protocol) {\n printOutput({ error: \"Either --protocol or --all-chains is required\" }, getOpts());\n process.exit(1);\n }\n\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createLending(protocol, chain.effectiveRpcUrl());\n\n const poll = async () => {\n try {\n const position = await adapter.getUserPosition(address);\n const hf = position.health_factor ?? Infinity;\n const alert = hf < threshold;\n printOutput({\n protocol: protocol.name,\n user: opts.address,\n health_factor: hf,\n threshold,\n alert,\n timestamp: new Date().toISOString(),\n supplies: position.supplies,\n borrows: position.borrows,\n }, getOpts());\n } catch (e) {\n printOutput({\n error: e instanceof Error ? e.message : String(e),\n protocol: protocol.name,\n timestamp: new Date().toISOString(),\n }, getOpts());\n }\n };\n\n await poll();\n if (!opts.once) {\n const intervalMs = parseInt(opts.interval) * 1000;\n const timer = setInterval(poll, intervalMs);\n process.on(\"SIGINT\", () => { clearInterval(timer); process.exit(0); });\n }\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport { createDex } from \"@hypurrquant/defi-protocols\";\nimport { createLending } from \"@hypurrquant/defi-protocols\";\n\nexport function registerAlert(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"alert\")\n .description(\"Alert on DEX vs Oracle price deviation\")\n .option(\"--threshold <pct>\", \"Deviation threshold in percent\", \"5.0\")\n .option(\"--once\", \"Run once instead of continuously\")\n .option(\"--interval <secs>\", \"Polling interval in seconds\", \"60\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const rpcUrl = chain.effectiveRpcUrl();\n const threshold = parseFloat(opts.threshold);\n\n const dexProtocols = registry.getProtocolsByCategory(\"dex\" as any).filter(p => p.chain === chainName);\n const lendingProtocols = registry.getProtocolsByCategory(\"lending\" as any).filter(p => p.chain === chainName);\n\n const poll = async () => {\n const alerts: Array<{ protocol: string; type: string; message: string }> = [];\n\n for (const p of dexProtocols) {\n try {\n const dex = createDex(p, rpcUrl);\n alerts.push({\n protocol: p.name,\n type: \"info\",\n message: `DEX ${dex.name()} active on ${chainName}`,\n });\n } catch { /* skip unsupported */ }\n }\n\n printOutput({\n chain: chainName,\n threshold_pct: threshold,\n alerts,\n timestamp: new Date().toISOString(),\n }, getOpts());\n };\n\n await poll();\n if (!opts.once) {\n const intervalMs = parseInt(opts.interval) * 1000;\n const timer = setInterval(poll, intervalMs);\n process.on(\"SIGINT\", () => { clearInterval(timer); process.exit(0); });\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport { Registry, ProtocolCategory, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\n\n// ABI fragments for scan\nconst AAVE_ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n]);\n\nconst UNIV2_ROUTER_ABI = parseAbi([\n \"function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory)\",\n]);\n\nconst VTOKEN_ABI = parseAbi([\n \"function exchangeRateStored() external view returns (uint256)\",\n]);\n\nconst STABLECOINS = new Set([\"USDC\", \"USDT\", \"DAI\", \"USDT0\"]);\n\n// Rounding helpers\nfunction round2(x: number): number { return Math.round(x * 100) / 100; }\nfunction round4(x: number): number { return Math.round(x * 10000) / 10000; }\nfunction round6(x: number): number { return Math.round(x * 1000000) / 1000000; }\n\n/** Parse a uint256 return from multicall (first 32 bytes) */\nfunction parseU256F64(data: Hex | null, decimals: number): number {\n if (!data || data.length < 66) return 0;\n const raw = BigInt(data.slice(0, 66));\n return Number(raw) / 10 ** decimals;\n}\n\n/**\n * Parse the last element of a getAmountsOut return array.\n * ABI encoding: offset(32) + length(32) + elements[N * 32]\n * We want the last element.\n */\nfunction parseAmountsOutLast(data: Hex | null, outDecimals: number): number {\n if (!data) return 0;\n // Strip 0x prefix\n const hex = data.startsWith(\"0x\") ? data.slice(2) : data;\n // Minimum: 128 hex chars = 64 bytes = offset(32) + length(32)\n if (hex.length < 128) return 0;\n // Array length is at bytes 32..64 (hex chars 64..128)\n const num = parseInt(hex.slice(64, 128), 16);\n if (num === 0) return 0;\n // Last element is at offset: 64 bytes header + (num-1)*32 bytes\n const byteOff = 64 + (num - 1) * 32;\n const hexOff = byteOff * 2;\n if (hex.length < hexOff + 64) return 0;\n const val = BigInt(\"0x\" + hex.slice(hexOff, hexOff + 64));\n return Number(val) / 10 ** outDecimals;\n}\n\ntype CallType =\n | { kind: \"oracle\"; oracle: string; token: string; oracleDecimals: number }\n | { kind: \"dex\"; token: string; outDecimals: number }\n | { kind: \"stable\"; from: string; to: string; outDecimals: number }\n | { kind: \"exchangeRate\"; protocol: string; vtoken: string };\n\nexport function registerScan(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"scan\")\n .description(\"Multi-pattern exploit detection scanner\")\n .option(\"--chain <chain>\", \"Chain to scan\", \"hyperevm\")\n .option(\"--patterns <patterns>\", \"Comma-separated patterns: oracle,stable,exchange_rate\", \"oracle,stable,exchange_rate\")\n .option(\"--oracle-threshold <pct>\", \"Oracle divergence threshold (percent)\", \"5.0\")\n .option(\"--stable-threshold <price>\", \"Stablecoin depeg threshold (min price)\", \"0.98\")\n .option(\"--rate-threshold <pct>\", \"Exchange rate change threshold (percent)\", \"5.0\")\n .option(\"--interval <secs>\", \"Polling interval in seconds\", \"30\")\n .option(\"--once\", \"Single check then exit\")\n .option(\"--all-chains\", \"Scan all chains in parallel\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n const oracleThreshold = parseFloat(opts.oracleThreshold ?? \"5.0\");\n const stableThreshold = parseFloat(opts.stableThreshold ?? \"0.98\");\n const rateThreshold = parseFloat(opts.rateThreshold ?? \"5.0\");\n const interval = parseInt(opts.interval ?? \"30\", 10);\n const patterns: string = opts.patterns ?? \"oracle,stable,exchange_rate\";\n const once: boolean = !!opts.once;\n\n if (opts.allChains) {\n const result = await runAllChains(registry, patterns, oracleThreshold, stableThreshold, rateThreshold);\n printOutput(result, getOpts());\n return;\n }\n\n const chainName: string = (opts.chain ?? \"hyperevm\").toLowerCase();\n const chain = registry.getChain(chainName);\n const rpc = chain.effectiveRpcUrl();\n\n const pats = patterns.split(\",\").map((s: string) => s.trim());\n const doOracle = pats.includes(\"oracle\");\n const doStable = pats.includes(\"stable\");\n const doRate = pats.includes(\"exchange_rate\");\n\n // Discover chain resources\n const allTokens = registry.tokens.get(chainName) ?? [];\n const wrappedNative = chain.wrapped_native as Address | undefined;\n\n const quoteStable = (() => {\n for (const sym of [\"USDT\", \"USDC\", \"USDT0\"]) {\n try { return registry.resolveToken(chainName, sym); } catch { /* continue */ }\n }\n return null;\n })();\n\n if (!quoteStable) {\n printOutput({ error: `No stablecoin found on chain ${chainName}` }, getOpts());\n return;\n }\n\n const scanTokens = allTokens.filter(\n (t) => t.address !== \"0x0000000000000000000000000000000000000000\" && !STABLECOINS.has(t.symbol),\n );\n\n // Aave oracles\n const oracles: Array<{ name: string; addr: Address; decimals: number }> = registry\n .getProtocolsForChain(chainName)\n .filter(\n (p) =>\n p.category === ProtocolCategory.Lending &&\n (p.interface === \"aave_v3\" || p.interface === \"aave_v2\" || p.interface === \"aave_v3_isolated\"),\n )\n .flatMap((p) => {\n const oracleAddr = p.contracts?.[\"oracle\"];\n if (!oracleAddr) return [];\n const decimals = p.interface === \"aave_v2\" ? 18 : 8;\n return [{ name: p.name, addr: oracleAddr, decimals }];\n });\n\n // First uniswap_v2 DEX router\n const dexProto = registry\n .getProtocolsForChain(chainName)\n .find((p) => p.category === ProtocolCategory.Dex && p.interface === \"uniswap_v2\");\n const dexRouter = dexProto?.contracts?.[\"router\"] as Address | undefined;\n\n // Compound V2 forks (Venus, Sonne)\n const compoundForks = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending && p.interface === \"compound_v2\")\n .map((p) => ({\n name: p.name,\n vtokens: Object.entries(p.contracts ?? {}).filter(([k]) => k.startsWith(\"v\")).map(([k, a]) => ({ key: k, addr: a as Address })),\n }));\n\n const usdc = (() => { try { return registry.resolveToken(chainName, \"USDC\"); } catch { return null; } })();\n const usdt = (() => { try { return registry.resolveToken(chainName, \"USDT\"); } catch { return null; } })();\n\n // Track prev exchange rates across iterations\n const prevRates = new Map<string, number>();\n\n const runOnce = async () => {\n const timestamp = Math.floor(Date.now() / 1000);\n const t0 = Date.now();\n\n const calls: Array<[Address, Hex]> = [];\n const callTypes: CallType[] = [];\n\n // P1: Oracle + DEX price calls\n if (doOracle) {\n for (const oracle of oracles) {\n for (const token of scanTokens) {\n callTypes.push({ kind: \"oracle\", oracle: oracle.name, token: token.symbol, oracleDecimals: oracle.decimals });\n calls.push([\n oracle.addr,\n encodeFunctionData({ abi: AAVE_ORACLE_ABI, functionName: \"getAssetPrice\", args: [token.address] }),\n ]);\n }\n }\n\n if (dexRouter) {\n for (const token of scanTokens) {\n const amountIn = BigInt(10) ** BigInt(token.decimals);\n const path: Address[] =\n wrappedNative && token.address.toLowerCase() === wrappedNative.toLowerCase()\n ? [token.address, quoteStable.address]\n : wrappedNative\n ? [token.address, wrappedNative, quoteStable.address]\n : [token.address, quoteStable.address];\n callTypes.push({ kind: \"dex\", token: token.symbol, outDecimals: quoteStable.decimals });\n calls.push([\n dexRouter,\n encodeFunctionData({ abi: UNIV2_ROUTER_ABI, functionName: \"getAmountsOut\", args: [amountIn, path] }),\n ]);\n }\n }\n }\n\n // P2: Stablecoin cross-peg calls\n if (doStable && usdc && usdt && dexRouter) {\n callTypes.push({ kind: \"stable\", from: \"USDC\", to: \"USDT\", outDecimals: usdt.decimals });\n calls.push([\n dexRouter,\n encodeFunctionData({\n abi: UNIV2_ROUTER_ABI,\n functionName: \"getAmountsOut\",\n args: [BigInt(10) ** BigInt(usdc.decimals), [usdc.address, usdt.address]],\n }),\n ]);\n callTypes.push({ kind: \"stable\", from: \"USDT\", to: \"USDC\", outDecimals: usdc.decimals });\n calls.push([\n dexRouter,\n encodeFunctionData({\n abi: UNIV2_ROUTER_ABI,\n functionName: \"getAmountsOut\",\n args: [BigInt(10) ** BigInt(usdt.decimals), [usdt.address, usdc.address]],\n }),\n ]);\n }\n\n // P4: Exchange rate calls\n if (doRate) {\n for (const fork of compoundForks) {\n for (const { key, addr } of fork.vtokens) {\n callTypes.push({ kind: \"exchangeRate\", protocol: fork.name, vtoken: key });\n calls.push([addr, encodeFunctionData({ abi: VTOKEN_ABI, functionName: \"exchangeRateStored\", args: [] })]);\n }\n }\n }\n\n if (calls.length === 0) {\n printOutput({ error: `No scannable resources found on ${chainName}` }, getOpts());\n return;\n }\n\n const results = await multicallRead(rpc, calls);\n const scanMs = Date.now() - t0;\n\n const alerts: unknown[] = [];\n const oracleByToken = new Map<string, Array<{ oracle: string; price: number }>>();\n const dexByToken = new Map<string, number>();\n const oracleData: Record<string, number> = {};\n const dexData: Record<string, number> = {};\n const stableData: Record<string, number> = {};\n const stablePrices: Array<{ asset: string; pair: string; price: number }> = [];\n const rateData: Record<string, number> = {};\n\n for (let i = 0; i < callTypes.length; i++) {\n const ct = callTypes[i];\n const raw = results[i] ?? null;\n\n if (ct.kind === \"oracle\") {\n const price = parseU256F64(raw, ct.oracleDecimals);\n if (price > 0) {\n const existing = oracleByToken.get(ct.token) ?? [];\n existing.push({ oracle: ct.oracle, price });\n oracleByToken.set(ct.token, existing);\n oracleData[`${ct.oracle}/${ct.token}`] = round4(price);\n }\n } else if (ct.kind === \"dex\") {\n const price = parseAmountsOutLast(raw, ct.outDecimals);\n if (price > 0) {\n dexByToken.set(ct.token, price);\n dexData[ct.token] = round4(price);\n }\n } else if (ct.kind === \"stable\") {\n const price = parseAmountsOutLast(raw, ct.outDecimals);\n if (price <= 0) continue;\n const pair = `${ct.from}/${ct.to}`;\n stableData[pair] = round4(price);\n stablePrices.push({ asset: ct.from, pair, price });\n } else if (ct.kind === \"exchangeRate\") {\n const rate = parseU256F64(raw, 18);\n const key = `${ct.protocol}/${ct.vtoken}`;\n rateData[key] = round6(rate);\n if (rate > 0) {\n const prev = prevRates.get(key);\n if (prev !== undefined) {\n const change = Math.abs((rate - prev) / prev * 100);\n if (change > rateThreshold) {\n const severity = change > 50 ? \"critical\" : change > 20 ? \"high\" : \"medium\";\n alerts.push({\n pattern: \"exchange_rate_anomaly\",\n severity,\n protocol: ct.protocol,\n vtoken: ct.vtoken,\n prev_rate: round6(prev),\n curr_rate: round6(rate),\n change_pct: round2(change),\n action: `possible donation attack on ${ct.protocol} ${ct.vtoken}`,\n });\n }\n }\n prevRates.set(key, rate);\n }\n }\n }\n\n // Stablecoin depeg alerts\n if (stablePrices.length >= 2) {\n const allBelow = stablePrices.every((s) => s.price < stableThreshold);\n if (!allBelow) {\n for (const { asset, pair, price } of stablePrices) {\n if (price < stableThreshold) {\n const severity = price < 0.95 ? \"critical\" : \"high\";\n alerts.push({\n pattern: \"stablecoin_depeg\",\n severity,\n asset,\n pair,\n price: round4(price),\n threshold: stableThreshold,\n action: `buy ${asset} at $${round4(price)}, wait for repeg`,\n });\n }\n }\n }\n } else {\n for (const { asset, pair, price } of stablePrices) {\n if (price < stableThreshold) {\n const severity = price < 0.95 ? \"critical\" : \"high\";\n alerts.push({\n pattern: \"stablecoin_depeg\",\n severity,\n asset,\n pair,\n price: round4(price),\n threshold: stableThreshold,\n action: `buy ${asset} at $${round4(price)}, wait for repeg`,\n });\n }\n }\n }\n\n // Oracle divergence alerts\n if (doOracle) {\n for (const [token, oracleEntries] of oracleByToken) {\n const dexPrice = dexByToken.get(token);\n if (dexPrice === undefined) continue;\n for (const { oracle, price: oraclePrice } of oracleEntries) {\n // Skip unreliable DEX quotes (no liquidity)\n if (dexPrice < oraclePrice && dexPrice < oraclePrice * 0.1) continue;\n const deviation = Math.abs(dexPrice - oraclePrice) / oraclePrice * 100;\n if (deviation > oracleThreshold) {\n const severity = deviation > 100 ? \"critical\" : deviation > 20 ? \"high\" : \"medium\";\n const action =\n dexPrice > oraclePrice\n ? `borrow ${token} from ${oracle}, sell on DEX`\n : `buy ${token} on DEX, use as collateral on ${oracle}`;\n alerts.push({\n pattern: \"oracle_divergence\",\n severity,\n asset: token,\n oracle,\n oracle_price: round4(oraclePrice),\n dex_price: round4(dexPrice),\n deviation_pct: round2(deviation),\n action,\n });\n }\n }\n }\n }\n\n // Build output data object\n const data: Record<string, unknown> = {};\n if (Object.keys(oracleData).length > 0) data[\"oracle_prices\"] = oracleData;\n if (Object.keys(dexData).length > 0) data[\"dex_prices\"] = dexData;\n if (Object.keys(stableData).length > 0) data[\"stablecoin_pegs\"] = stableData;\n if (Object.keys(rateData).length > 0) data[\"exchange_rates\"] = rateData;\n\n const output = {\n timestamp,\n chain: chain.name,\n scan_duration_ms: scanMs,\n patterns,\n alert_count: alerts.length,\n alerts,\n data,\n };\n\n for (const alert of alerts as Array<Record<string, unknown>>) {\n process.stderr.write(\n `ALERT [${alert[\"severity\"]}]: ${alert[\"pattern\"]} — ${alert[\"action\"]}\\n`,\n );\n }\n\n printOutput(output, getOpts());\n };\n\n await runOnce();\n\n if (!once) {\n const intervalMs = interval * 1000;\n const loop = async () => {\n await new Promise((r) => setTimeout(r, intervalMs));\n await runOnce();\n void loop();\n };\n await loop();\n }\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n process.exit(1);\n }\n });\n}\n\nasync function runAllChains(\n registry: Registry,\n patterns: string,\n oracleThreshold: number,\n stableThreshold: number,\n _rateThreshold: number,\n): Promise<unknown> {\n const t0 = Date.now();\n const chainKeys = Array.from(registry.chains.keys());\n\n const tasks = chainKeys.map(async (ck) => {\n try {\n const chain = registry.getChain(ck);\n const rpc = chain.effectiveRpcUrl();\n const chainName = chain.name.toLowerCase();\n const allTokens = registry.tokens.get(chainName) ?? [];\n const wrappedNative = chain.wrapped_native as Address | undefined;\n\n const quoteStable = (() => {\n for (const sym of [\"USDT\", \"USDC\", \"USDT0\"]) {\n try { return registry.resolveToken(chainName, sym); } catch { /* continue */ }\n }\n return null;\n })();\n if (!quoteStable) return null;\n\n const scanTokens = allTokens.filter(\n (t) => t.address !== \"0x0000000000000000000000000000000000000000\" && !STABLECOINS.has(t.symbol),\n );\n\n const pats = patterns.split(\",\").map((s) => s.trim());\n const doOracle = pats.includes(\"oracle\");\n const doStable = pats.includes(\"stable\");\n\n const oracles: Array<{ name: string; addr: Address; decimals: number }> = registry\n .getProtocolsForChain(chainName)\n .filter(\n (p) =>\n p.category === ProtocolCategory.Lending &&\n (p.interface === \"aave_v3\" || p.interface === \"aave_v2\" || p.interface === \"aave_v3_isolated\"),\n )\n .flatMap((p) => {\n const oracleAddr = p.contracts?.[\"oracle\"];\n if (!oracleAddr) return [];\n return [{ name: p.name, addr: oracleAddr, decimals: p.interface === \"aave_v2\" ? 18 : 8 }];\n });\n\n const dexProto = registry\n .getProtocolsForChain(chainName)\n .find((p) => p.category === ProtocolCategory.Dex && p.interface === \"uniswap_v2\");\n const dexRouter = dexProto?.contracts?.[\"router\"] as Address | undefined;\n\n const usdc = (() => { try { return registry.resolveToken(chainName, \"USDC\"); } catch { return null; } })();\n const usdt = (() => { try { return registry.resolveToken(chainName, \"USDT\"); } catch { return null; } })();\n\n const calls: Array<[Address, Hex]> = [];\n type CT = { kind: \"oracle\"; oracle: string; token: string; dec: number } | { kind: \"dex\"; token: string; dec: number } | { kind: \"stable\"; from: string; to: string; dec: number };\n const cts: CT[] = [];\n\n if (doOracle) {\n for (const oracle of oracles) {\n for (const token of scanTokens) {\n cts.push({ kind: \"oracle\", oracle: oracle.name, token: token.symbol, dec: oracle.decimals });\n calls.push([oracle.addr, encodeFunctionData({ abi: AAVE_ORACLE_ABI, functionName: \"getAssetPrice\", args: [token.address] })]);\n }\n }\n if (dexRouter) {\n for (const token of scanTokens) {\n const path: Address[] =\n wrappedNative && token.address.toLowerCase() === wrappedNative.toLowerCase()\n ? [token.address, quoteStable.address]\n : wrappedNative\n ? [token.address, wrappedNative, quoteStable.address]\n : [token.address, quoteStable.address];\n cts.push({ kind: \"dex\", token: token.symbol, dec: quoteStable.decimals });\n calls.push([dexRouter, encodeFunctionData({ abi: UNIV2_ROUTER_ABI, functionName: \"getAmountsOut\", args: [BigInt(10) ** BigInt(token.decimals), path] })]);\n }\n }\n }\n\n if (doStable && usdc && usdt && dexRouter) {\n cts.push({ kind: \"stable\", from: \"USDC\", to: \"USDT\", dec: usdt.decimals });\n calls.push([dexRouter, encodeFunctionData({ abi: UNIV2_ROUTER_ABI, functionName: \"getAmountsOut\", args: [BigInt(10) ** BigInt(usdc.decimals), [usdc.address, usdt.address]] })]);\n cts.push({ kind: \"stable\", from: \"USDT\", to: \"USDC\", dec: usdc.decimals });\n calls.push([dexRouter, encodeFunctionData({ abi: UNIV2_ROUTER_ABI, functionName: \"getAmountsOut\", args: [BigInt(10) ** BigInt(usdt.decimals), [usdt.address, usdc.address]] })]);\n }\n\n if (calls.length === 0) return null;\n\n const ct0 = Date.now();\n const results = await multicallRead(rpc, calls);\n const scanMs = Date.now() - ct0;\n\n const alerts: unknown[] = [];\n const oracleByToken = new Map<string, Array<{ oracle: string; price: number }>>();\n const dexByToken = new Map<string, number>();\n const stablePrices: Array<{ asset: string; pair: string; price: number }> = [];\n\n for (let i = 0; i < cts.length; i++) {\n const ct = cts[i];\n const raw = results[i] ?? null;\n if (ct.kind === \"oracle\") {\n const price = parseU256F64(raw, ct.dec);\n if (price > 0) {\n const existing = oracleByToken.get(ct.token) ?? [];\n existing.push({ oracle: ct.oracle, price });\n oracleByToken.set(ct.token, existing);\n }\n } else if (ct.kind === \"dex\") {\n const price = parseAmountsOutLast(raw, ct.dec);\n if (price > 0) dexByToken.set(ct.token, price);\n } else if (ct.kind === \"stable\") {\n const price = parseAmountsOutLast(raw, ct.dec);\n if (price > 0) stablePrices.push({ asset: ct.from, pair: `${ct.from}/${ct.to}`, price });\n }\n }\n\n // Stablecoin depeg\n if (stablePrices.length >= 2) {\n const allBelow = stablePrices.every((s) => s.price < stableThreshold);\n if (!allBelow) {\n for (const { asset, pair, price } of stablePrices) {\n if (price < stableThreshold) {\n alerts.push({ pattern: \"stablecoin_depeg\", severity: price < 0.95 ? \"critical\" : \"high\", asset, pair, price: round4(price) });\n }\n }\n }\n }\n\n // Oracle divergence\n for (const [token, oEntries] of oracleByToken) {\n const dp = dexByToken.get(token);\n if (dp === undefined) continue;\n for (const { oracle, price: op } of oEntries) {\n if (dp < op && dp < op * 0.1) continue;\n const dev = Math.abs(dp - op) / op * 100;\n if (dev > oracleThreshold) {\n const sev = dev > 100 ? \"critical\" : dev > 20 ? \"high\" : \"medium\";\n alerts.push({\n pattern: \"oracle_divergence\",\n severity: sev,\n asset: token,\n oracle,\n oracle_price: round4(op),\n dex_price: round4(dp),\n deviation_pct: round2(dev),\n action: dp > op ? `borrow ${token} from ${oracle}, sell on DEX` : `buy ${token} on DEX, collateral on ${oracle}`,\n });\n }\n }\n }\n\n return { chain: chain.name, scan_duration_ms: scanMs, alert_count: alerts.length, alerts };\n } catch {\n return null;\n }\n });\n\n const chainResults = (await Promise.all(tasks)).filter(Boolean);\n chainResults.sort((a, b) => {\n const ac = (a as Record<string, unknown>)[\"alert_count\"] as number ?? 0;\n const bc = (b as Record<string, unknown>)[\"alert_count\"] as number ?? 0;\n return bc - ac;\n });\n\n const totalAlerts = chainResults.reduce((sum, r) => sum + ((r as Record<string, unknown>)[\"alert_count\"] as number ?? 0), 0);\n\n return {\n mode: \"all_chains\",\n chains_scanned: chainKeys.length,\n scan_duration_ms: Date.now() - t0,\n total_alerts: totalAlerts,\n chains: chainResults,\n };\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport { createDex } from \"@hypurrquant/defi-protocols\";\nimport type { Address } from \"viem\";\n\nexport function registerArb(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n parent\n .command(\"arb\")\n .description(\"Detect arbitrage opportunities across DEXes\")\n .option(\"--token-in <token>\", \"Base token (default: WHYPE)\", \"WHYPE\")\n .option(\"--token-out <token>\", \"Quote token (default: USDC)\", \"USDC\")\n .option(\"--amount <amount>\", \"Test amount in wei\", \"1000000000000000000\")\n .option(\"--execute\", \"Execute best arb (default: analysis only)\")\n .option(\"--min-profit <bps>\", \"Min profit in bps to execute\", \"10\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const rpcUrl = chain.effectiveRpcUrl();\n\n const tokenIn = opts.tokenIn.startsWith(\"0x\") ? opts.tokenIn as Address : registry.resolveToken(chainName, opts.tokenIn).address as Address;\n const tokenOut = opts.tokenOut.startsWith(\"0x\") ? opts.tokenOut as Address : registry.resolveToken(chainName, opts.tokenOut).address as Address;\n const amountIn = BigInt(opts.amount);\n\n const dexProtocols = registry.getProtocolsByCategory(\"dex\" as any).filter(p => p.chain === chainName);\n const quotes: Array<{ protocol: string; buy: bigint; sell: bigint; profit_bps: number }> = [];\n\n for (const p of dexProtocols) {\n try {\n const adapter = createDex(p, rpcUrl);\n const buyQuote = await adapter.quote({ protocol: p.name, token_in: tokenIn, token_out: tokenOut, amount_in: amountIn });\n if (buyQuote.amount_out === 0n) continue;\n const sellQuote = await adapter.quote({ protocol: p.name, token_in: tokenOut, token_out: tokenIn, amount_in: buyQuote.amount_out });\n const profitBps = Number((sellQuote.amount_out - amountIn) * 10000n / amountIn);\n quotes.push({ protocol: p.name, buy: buyQuote.amount_out, sell: sellQuote.amount_out, profit_bps: profitBps });\n } catch { /* skip unsupported */ }\n }\n\n // Cross-DEX arb: buy on cheapest, sell on most expensive\n const opportunities: Array<{ buy_on: string; sell_on: string; profit_bps: number }> = [];\n for (let i = 0; i < quotes.length; i++) {\n for (let j = 0; j < quotes.length; j++) {\n if (i === j) continue;\n const buyAmount = quotes[i].buy;\n const sellAmount = quotes[j].sell;\n if (sellAmount > amountIn) {\n const profitBps = Number((sellAmount - amountIn) * 10000n / amountIn);\n opportunities.push({ buy_on: quotes[i].protocol, sell_on: quotes[j].protocol, profit_bps: profitBps });\n }\n }\n }\n opportunities.sort((a, b) => b.profit_bps - a.profit_bps);\n\n printOutput({\n chain: chainName, token_in: tokenIn, token_out: tokenOut,\n amount_in: amountIn, single_dex: quotes, cross_dex_opportunities: opportunities.slice(0, 5),\n }, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport { Registry, ProtocolCategory, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\n\nconst ERC20_ABI = parseAbi([\n \"function balanceOf(address owner) external view returns (uint256)\",\n]);\n\nconst POOL_ABI = parseAbi([\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n]);\n\nfunction round2(x: number): number {\n return Math.round(x * 100) / 100;\n}\n\nfunction round4(x: number): number {\n return Math.round(x * 10000) / 10000;\n}\n\nfunction estimateTokenValue(symbol: string, balance: number, nativePrice: number): number {\n const s = symbol.toUpperCase();\n if (s.includes(\"USD\") || s.includes(\"DAI\")) return balance;\n if (s.includes(\"BTC\") || s.includes(\"FBTC\")) return balance * 75000;\n if ([\"WETH\", \"ETH\", \"METH\", \"CBETH\", \"WSTETH\"].includes(s)) return balance * 2350;\n return balance * nativePrice;\n}\n\nfunction decodeU256(data: Hex | null, offset = 0): bigint {\n if (!data || data.length < 2 + (offset + 32) * 2) return 0n;\n const hex = data.slice(2 + offset * 64, 2 + offset * 64 + 64);\n return BigInt(\"0x\" + hex);\n}\n\ninterface ChainScanResult {\n chain_name: string;\n native_price: number;\n chain_value: number;\n collateral: number;\n debt: number;\n token_balances: unknown[];\n lending_positions: unknown[];\n}\n\nasync function scanSingleChain(\n chainName: string,\n rpc: string,\n user: Address,\n tokens: Array<{ address: Address; symbol: string; decimals: number }>,\n lendingPools: Array<{ name: string; pool: Address; iface: string }>,\n oracleAddr: Address | undefined,\n wrappedNative: Address,\n): Promise<ChainScanResult | null> {\n const calls: Array<[Address, Hex]> = [];\n\n type CallType =\n | { kind: \"token\"; symbol: string; decimals: number }\n | { kind: \"lending\"; protocol: string; iface: string }\n | { kind: \"native_price\" };\n\n const callTypes: CallType[] = [];\n\n for (const token of tokens) {\n if (token.address !== (\"0x0000000000000000000000000000000000000000\" as Address)) {\n callTypes.push({ kind: \"token\", symbol: token.symbol, decimals: token.decimals });\n calls.push([\n token.address,\n encodeFunctionData({ abi: ERC20_ABI, functionName: \"balanceOf\", args: [user] }),\n ]);\n }\n }\n\n for (const { name, pool, iface } of lendingPools) {\n callTypes.push({ kind: \"lending\", protocol: name, iface });\n calls.push([\n pool,\n encodeFunctionData({ abi: POOL_ABI, functionName: \"getUserAccountData\", args: [user] }),\n ]);\n }\n\n if (oracleAddr) {\n callTypes.push({ kind: \"native_price\" });\n calls.push([\n oracleAddr,\n encodeFunctionData({ abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [wrappedNative] }),\n ]);\n }\n\n if (calls.length === 0) return null;\n\n let results: (Hex | null)[];\n try {\n results = await multicallRead(rpc, calls);\n } catch {\n return null;\n }\n\n const nativePrice = oracleAddr\n ? Number(decodeU256(results[results.length - 1]!)) / 1e8\n : 0;\n\n const tokenBalances: unknown[] = [];\n const lendingPositions: unknown[] = [];\n let chainValue = 0;\n let totalColl = 0;\n let totalDebt = 0;\n\n for (let i = 0; i < callTypes.length; i++) {\n const ct = callTypes[i]!;\n const data = results[i] ?? null;\n\n if (ct.kind === \"token\") {\n const balance = decodeU256(data);\n if (balance > 0n) {\n const balF64 = Number(balance) / 10 ** ct.decimals;\n const valueUsd = estimateTokenValue(ct.symbol, balF64, nativePrice);\n if (valueUsd > 0.01) {\n chainValue += valueUsd;\n tokenBalances.push({\n symbol: ct.symbol,\n balance: round4(balF64),\n value_usd: round2(valueUsd),\n });\n }\n }\n } else if (ct.kind === \"lending\") {\n if (data && data.length >= 2 + 192 * 2) {\n const priceDecimals = ct.iface === \"aave_v2\" ? 18 : 8;\n const divisor = 10 ** priceDecimals;\n const collateral = Number(decodeU256(data, 0)) / divisor;\n const debt = Number(decodeU256(data, 1)) / divisor;\n const hfRaw = decodeU256(data, 5);\n let hf: number | null = null;\n if (hfRaw <= BigInt(\"0xffffffffffffffffffffffffffffffff\")) {\n const v = Number(hfRaw) / 1e18;\n hf = v > 1e10 ? null : round2(v);\n }\n\n if (collateral > 0.01 || debt > 0.01) {\n const net = collateral - debt;\n chainValue += net;\n totalColl += collateral;\n totalDebt += debt;\n lendingPositions.push({\n protocol: ct.protocol,\n collateral_usd: round2(collateral),\n debt_usd: round2(debt),\n net_usd: round2(net),\n health_factor: hf,\n });\n }\n }\n }\n // native_price call — already decoded above\n }\n\n if (tokenBalances.length === 0 && lendingPositions.length === 0) return null;\n\n return {\n chain_name: chainName,\n native_price: nativePrice,\n chain_value: chainValue,\n collateral: totalColl,\n debt: totalDebt,\n token_balances: tokenBalances,\n lending_positions: lendingPositions,\n };\n}\n\nexport function registerPositions(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"positions\")\n .description(\"Cross-chain position scanner: find all your positions everywhere\")\n .requiredOption(\"--address <address>\", \"Wallet address to scan\")\n .option(\"--chains <chains>\", \"Comma-separated chain names (omit for all)\")\n .action(async (opts: { address: string; chains?: string }) => {\n const mode = getOpts();\n const registry = Registry.loadEmbedded();\n\n const user = opts.address as Address;\n if (!/^0x[0-9a-fA-F]{40}$/.test(user)) {\n printOutput({ error: `Invalid address: ${opts.address}` }, mode);\n return;\n }\n\n const chainFilter = opts.chains\n ? opts.chains.split(\",\").map((s) => s.trim().toLowerCase())\n : null;\n\n const chainKeys = chainFilter ?? Array.from(registry.chains.keys());\n\n const start = Date.now();\n\n // Build scan params for each chain\n const scanParams: Array<{\n chainName: string;\n rpc: string;\n tokens: Array<{ address: Address; symbol: string; decimals: number }>;\n lendingPools: Array<{ name: string; pool: Address; iface: string }>;\n oracleAddr: Address | undefined;\n wrappedNative: Address;\n }> = [];\n\n for (const chainKey of chainKeys) {\n let chain;\n try {\n chain = registry.getChain(chainKey);\n } catch {\n continue;\n }\n const rpc = chain.effectiveRpcUrl();\n const rawTokens = registry.tokens.get(chainKey) ?? [];\n const tokens = rawTokens.map((t) => ({\n address: t.address as Address,\n symbol: t.symbol,\n decimals: t.decimals,\n }));\n\n const chainProtocols = registry.getProtocolsForChain(chainKey);\n\n const lendingPools = chainProtocols\n .filter(\n (p) =>\n p.category === ProtocolCategory.Lending &&\n (p.interface === \"aave_v3\" || p.interface === \"aave_v2\"),\n )\n .filter((p) => p.contracts?.[\"pool\"])\n .map((p) => ({\n name: p.name,\n pool: p.contracts![\"pool\"] as Address,\n iface: p.interface,\n }));\n\n const oracleEntry = chainProtocols.find(\n (p) => p.interface === \"aave_v3\" && p.contracts?.[\"oracle\"],\n );\n const oracleAddr = oracleEntry?.contracts?.[\"oracle\"] as Address | undefined;\n\n const wrappedNative = (chain.wrapped_native ?? \"0x5555555555555555555555555555555555555555\") as Address;\n\n scanParams.push({ chainName: chain.name, rpc, tokens, lendingPools, oracleAddr, wrappedNative });\n }\n\n // Run all chains in parallel\n const chainResultsRaw = await Promise.all(\n scanParams.map((p) =>\n scanSingleChain(p.chainName, p.rpc, user, p.tokens, p.lendingPools, p.oracleAddr, p.wrappedNative),\n ),\n );\n\n let grandTotalUsd = 0;\n let totalCollateralUsd = 0;\n let totalDebtUsd = 0;\n\n const chainResults = chainResultsRaw\n .filter((r): r is ChainScanResult => r !== null)\n .map((r) => {\n grandTotalUsd += r.chain_value;\n totalCollateralUsd += r.collateral;\n totalDebtUsd += r.debt;\n return {\n chain: r.chain_name,\n native_price_usd: round2(r.native_price),\n chain_total_usd: round2(r.chain_value),\n token_balances: r.token_balances,\n lending_positions: r.lending_positions,\n };\n })\n .sort((a, b) => b.chain_total_usd - a.chain_total_usd);\n\n const scanMs = Date.now() - start;\n\n printOutput(\n {\n address: user,\n scan_duration_ms: scanMs,\n chains_scanned: chainKeys.length,\n chains_with_positions: chainResults.length,\n summary: {\n total_value_usd: round2(grandTotalUsd),\n total_collateral_usd: round2(totalCollateralUsd),\n total_debt_usd: round2(totalDebtUsd),\n net_lending_usd: round2(totalCollateralUsd - totalDebtUsd),\n },\n chains: chainResults,\n },\n mode,\n );\n });\n}\n","import type { Command } from \"commander\";\nimport type { Address } from \"viem\";\nimport { Registry, ProtocolCategory } from \"@hypurrquant/defi-core\";\nimport { createOracleFromLending, createOracleFromCdp, createDex, DexSpotPrice } from \"@hypurrquant/defi-protocols\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\n\ninterface PriceEntry {\n source: string;\n source_type: string;\n price: number;\n}\n\ninterface PriceReport {\n asset: string;\n asset_address: string;\n prices: PriceEntry[];\n max_spread_pct: number;\n oracle_vs_dex_spread_pct: number;\n}\n\nfunction round2(x: number): number {\n return Math.round(x * 100) / 100;\n}\n\nfunction resolveAsset(\n registry: Registry,\n chain: string,\n asset: string,\n): { address: Address; symbol: string; decimals: number } {\n // Try parse as address\n if (/^0x[0-9a-fA-F]{40}$/.test(asset)) {\n return { address: asset as Address, symbol: asset, decimals: 18 };\n }\n const token = registry.resolveToken(chain, asset);\n return { address: token.address, symbol: token.symbol, decimals: token.decimals };\n}\n\nconst WHYPE_ADDRESS = \"0x5555555555555555555555555555555555555555\" as Address;\n\nexport function registerPrice(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"price\")\n .description(\"Query asset prices from oracles and DEXes\")\n .requiredOption(\"--asset <token>\", \"Token symbol or address\")\n .option(\"--source <source>\", \"Price source: oracle, dex, or all\", \"all\")\n .action(async (opts: { asset: string; source: string }) => {\n const mode = getOpts();\n const registry = Registry.loadEmbedded();\n const chainName = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n\n let chain;\n try {\n chain = registry.getChain(chainName);\n } catch (e) {\n printOutput({ error: `Chain not found: ${chainName}` }, mode);\n return;\n }\n\n const rpcUrl = chain.effectiveRpcUrl();\n\n let assetAddr: Address;\n let assetSymbol: string;\n let assetDecimals: number;\n try {\n const resolved = resolveAsset(registry, chainName, opts.asset);\n assetAddr = resolved.address;\n assetSymbol = resolved.symbol;\n assetDecimals = resolved.decimals;\n } catch (e) {\n printOutput({ error: `Could not resolve asset: ${opts.asset}` }, mode);\n return;\n }\n\n const fetchOracle = opts.source === \"all\" || opts.source === \"oracle\";\n const fetchDex = opts.source === \"all\" || opts.source === \"dex\";\n\n const allPrices: Array<{ source: string; source_type: string; price_f64: number }> = [];\n\n // Oracle prices from lending protocols (Aave V3 forks)\n if (fetchOracle) {\n const lendingProtocols = registry.getProtocolsByCategory(ProtocolCategory.Lending)\n .filter((p) => p.chain.toLowerCase() === chainName);\n\n await Promise.all(\n lendingProtocols.map(async (entry) => {\n try {\n const oracle = createOracleFromLending(entry, rpcUrl);\n const price = await oracle.getPrice(assetAddr);\n allPrices.push({\n source: price.source,\n source_type: price.source_type,\n price_f64: price.price_f64,\n });\n } catch {\n // Interface doesn't support oracle — skip\n }\n }),\n );\n\n // Oracle prices from CDP protocols (Felix) — only for WHYPE\n const isWhype =\n assetAddr.toLowerCase() === WHYPE_ADDRESS.toLowerCase() ||\n assetSymbol.toUpperCase() === \"WHYPE\" ||\n assetSymbol.toUpperCase() === \"HYPE\";\n\n if (isWhype) {\n const cdpProtocols = registry.getProtocolsByCategory(ProtocolCategory.Cdp)\n .filter((p) => p.chain.toLowerCase() === chainName);\n\n await Promise.all(\n cdpProtocols.map(async (entry) => {\n try {\n const oracle = createOracleFromCdp(entry, assetAddr, rpcUrl);\n const price = await oracle.getPrice(assetAddr);\n allPrices.push({\n source: price.source,\n source_type: price.source_type,\n price_f64: price.price_f64,\n });\n } catch {\n // skip\n }\n }),\n );\n }\n }\n\n // DEX spot prices\n if (fetchDex) {\n let usdcToken;\n try {\n usdcToken = registry.resolveToken(chainName, \"USDC\");\n } catch {\n process.stderr.write(\"USDC token not found in registry — skipping DEX prices\\n\");\n }\n\n if (usdcToken) {\n const dexProtocols = registry.getProtocolsByCategory(ProtocolCategory.Dex)\n .filter((p) => p.chain.toLowerCase() === chainName);\n\n await Promise.all(\n dexProtocols.map(async (entry) => {\n try {\n const dex = createDex(entry, rpcUrl);\n const price = await DexSpotPrice.getPrice(\n dex,\n assetAddr,\n assetDecimals,\n usdcToken!.address,\n usdcToken!.decimals,\n );\n allPrices.push({\n source: price.source,\n source_type: price.source_type,\n price_f64: price.price_f64,\n });\n } catch {\n // skip\n }\n }),\n );\n }\n }\n\n if (allPrices.length === 0) {\n printOutput({ error: \"No prices could be fetched from any source\" }, mode);\n return;\n }\n\n const pricesF64 = allPrices.map((p) => p.price_f64);\n const maxPrice = Math.max(...pricesF64);\n const minPrice = Math.min(...pricesF64);\n const maxSpreadPct = minPrice > 0 ? ((maxPrice - minPrice) / minPrice) * 100 : 0;\n\n const oraclePrices = allPrices.filter((p) => p.source_type === \"oracle\").map((p) => p.price_f64);\n const dexPrices = allPrices.filter((p) => p.source_type === \"dex_spot\").map((p) => p.price_f64);\n\n let oracleVsDexSpreadPct = 0;\n if (oraclePrices.length > 0 && dexPrices.length > 0) {\n const avgOracle = oraclePrices.reduce((a, b) => a + b, 0) / oraclePrices.length;\n const avgDex = dexPrices.reduce((a, b) => a + b, 0) / dexPrices.length;\n const minAvg = Math.min(avgOracle, avgDex);\n oracleVsDexSpreadPct = minAvg > 0 ? (Math.abs(avgOracle - avgDex) / minAvg) * 100 : 0;\n }\n\n const report: PriceReport = {\n asset: assetSymbol,\n asset_address: assetAddr,\n prices: allPrices.map((p) => ({\n source: p.source,\n source_type: p.source_type,\n price: round2(p.price_f64),\n })),\n max_spread_pct: round2(maxSpreadPct),\n oracle_vs_dex_spread_pct: round2(oracleVsDexSpreadPct),\n };\n\n printOutput(report, mode);\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport { createPublicClient, http, formatEther } from \"viem\";\n\nexport function registerWallet(parent: Command, getOpts: () => OutputMode): void {\n const wallet = parent.command(\"wallet\").description(\"Wallet management\");\n\n wallet\n .command(\"balance\")\n .description(\"Show native token balance\")\n .requiredOption(\"--address <address>\", \"Wallet address to query\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const client = createPublicClient({ transport: http(chain.effectiveRpcUrl()) });\n\n const balance = await client.getBalance({ address: opts.address as `0x${string}` });\n printOutput({\n chain: chain.name,\n address: opts.address,\n native_token: chain.native_token,\n balance_wei: balance,\n balance_formatted: formatEther(balance),\n }, getOpts());\n });\n\n wallet\n .command(\"address\")\n .description(\"Show configured wallet address\")\n .action(async () => {\n const addr = process.env.DEFI_WALLET_ADDRESS ?? \"(not set)\";\n printOutput({ address: addr }, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry, buildApprove, buildTransfer, erc20Abi } from \"@hypurrquant/defi-core\";\nimport { createPublicClient, http, maxUint256 } from \"viem\";\nimport type { Address } from \"viem\";\n\nexport function registerToken(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const token = parent.command(\"token\").description(\"Token operations: approve, allowance, transfer, balance\");\n\n token\n .command(\"balance\")\n .description(\"Query token balance for an address\")\n .requiredOption(\"--token <token>\", \"Token symbol or address\")\n .requiredOption(\"--owner <address>\", \"Wallet address to query\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const client = createPublicClient({ transport: http(chain.effectiveRpcUrl()) });\n\n const tokenAddr = opts.token.startsWith(\"0x\")\n ? opts.token as Address\n : registry.resolveToken(chainName, opts.token).address as Address;\n\n const [balance, symbol, decimals] = await Promise.all([\n client.readContract({ address: tokenAddr, abi: erc20Abi, functionName: \"balanceOf\", args: [opts.owner as Address] }),\n client.readContract({ address: tokenAddr, abi: erc20Abi, functionName: \"symbol\" }),\n client.readContract({ address: tokenAddr, abi: erc20Abi, functionName: \"decimals\" }),\n ]);\n\n printOutput({\n token: tokenAddr,\n symbol,\n owner: opts.owner,\n balance,\n decimals,\n }, getOpts());\n });\n\n token\n .command(\"approve\")\n .description(\"Approve a spender for a token\")\n .requiredOption(\"--token <token>\", \"Token symbol or address\")\n .requiredOption(\"--spender <address>\", \"Spender address\")\n .option(\"--amount <amount>\", \"Amount to approve (use 'max' for unlimited)\", \"max\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const tokenAddr = opts.token.startsWith(\"0x\")\n ? opts.token as Address\n : registry.resolveToken(chainName, opts.token).address as Address;\n\n const amount = opts.amount === \"max\" ? maxUint256 : BigInt(opts.amount);\n const tx = buildApprove(tokenAddr, opts.spender as Address, amount);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n token\n .command(\"allowance\")\n .description(\"Check token allowance\")\n .requiredOption(\"--token <token>\", \"Token symbol or address\")\n .requiredOption(\"--owner <address>\", \"Owner address\")\n .requiredOption(\"--spender <address>\", \"Spender address\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const client = createPublicClient({ transport: http(chain.effectiveRpcUrl()) });\n\n const tokenAddr = opts.token.startsWith(\"0x\")\n ? opts.token as Address\n : registry.resolveToken(chainName, opts.token).address as Address;\n\n const allowance = await client.readContract({\n address: tokenAddr, abi: erc20Abi, functionName: \"allowance\",\n args: [opts.owner as Address, opts.spender as Address],\n });\n\n printOutput({ token: tokenAddr, owner: opts.owner, spender: opts.spender, allowance }, getOpts());\n });\n\n token\n .command(\"transfer\")\n .description(\"Transfer tokens to an address\")\n .requiredOption(\"--token <token>\", \"Token symbol or address\")\n .requiredOption(\"--to <address>\", \"Recipient address\")\n .requiredOption(\"--amount <amount>\", \"Amount to transfer (in wei)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const tokenAddr = opts.token.startsWith(\"0x\")\n ? opts.token as Address\n : registry.resolveToken(chainName, opts.token).address as Address;\n\n const tx = buildTransfer(tokenAddr, opts.to as Address, BigInt(opts.amount));\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport { Registry, ProtocolCategory, multicallRead } from \"@hypurrquant/defi-core\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\n\nconst POOL_ABI = parseAbi([\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n]);\n\nfunction round2(x: number): number {\n return Math.round(x * 100) / 100;\n}\n\nfunction round4(x: number): number {\n return Math.round(x * 10000) / 10000;\n}\n\nfunction decodeU256(data: Hex | null, wordOffset = 0): bigint {\n if (!data || data.length < 2 + (wordOffset + 1) * 64) return 0n;\n const hex = data.slice(2 + wordOffset * 64, 2 + wordOffset * 64 + 64);\n return BigInt(\"0x\" + hex);\n}\n\nfunction getExplorerApi(chainId: number, explorerUrl?: string): { base: string; apiKey?: string } | null {\n // routescan (free, no key)\n const routescanChains = [1, 43114, 10, 5000];\n if (routescanChains.includes(chainId)) {\n return {\n base: `https://api.routescan.io/v2/network/mainnet/evm/${chainId}/etherscan/api`,\n };\n }\n\n // Etherscan V2 unified API\n const apiKey = process.env[\"ETHERSCAN_API_KEY\"];\n if (apiKey) {\n return {\n base: `https://api.etherscan.io/v2/api?chainid=${chainId}`,\n apiKey,\n };\n }\n\n return null;\n}\n\nexport function registerWhales(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"whales\")\n .description(\"Find top token holders (whales) and their positions\")\n .requiredOption(\"--token <token>\", \"Token symbol or address\")\n .option(\"--top <n>\", \"Number of top holders to show\", \"10\")\n .option(\"--positions\", \"Also scan each whale's lending positions\")\n .action(async (opts: { token: string; top: string; positions?: boolean }) => {\n const mode = getOpts();\n const registry = Registry.loadEmbedded();\n const chainName = (parent.opts<{ chain?: string }>().chain ?? \"hyperevm\").toLowerCase();\n\n let chain;\n try {\n chain = registry.getChain(chainName);\n } catch {\n printOutput({ error: `Chain not found: ${chainName}` }, mode);\n return;\n }\n\n const rpc = chain.effectiveRpcUrl();\n const top = parseInt(opts.top, 10) || 10;\n\n // Resolve token\n let token;\n try {\n token = registry.resolveToken(chainName, opts.token);\n } catch {\n printOutput({ error: `Token not found: ${opts.token}` }, mode);\n return;\n }\n\n // Get explorer API\n const explorerApi = getExplorerApi(chain.chain_id, chain.explorer_url);\n if (!explorerApi) {\n printOutput(\n {\n error: `No explorer API available for ${chain.name} (chain_id: ${chain.chain_id}). Set ETHERSCAN_API_KEY to enable.`,\n },\n mode,\n );\n return;\n }\n\n // Build URL\n const tokenAddr = token.address;\n let url = `${explorerApi.base}?module=token&action=tokenholderlist&contractaddress=${tokenAddr}&page=1&offset=${top}`;\n if (explorerApi.apiKey) {\n url += `&apikey=${explorerApi.apiKey}`;\n }\n\n // Fetch top holders\n let body: { status?: string; result?: unknown };\n try {\n const resp = await fetch(url);\n body = (await resp.json()) as { status?: string; result?: unknown };\n } catch (e) {\n printOutput({ error: `Explorer API request failed: ${e instanceof Error ? e.message : String(e)}` }, mode);\n return;\n }\n\n if (body.status !== \"1\") {\n const msg = typeof body.result === \"string\" ? body.result : \"Unknown error\";\n if (msg.includes(\"API Key\") || msg.includes(\"apikey\")) {\n printOutput(\n { error: \"Explorer API requires API key. Set ETHERSCAN_API_KEY environment variable.\" },\n mode,\n );\n return;\n }\n printOutput({ error: `Explorer API error: ${msg}` }, mode);\n return;\n }\n\n const holders = Array.isArray(body.result) ? body.result : [];\n\n // Parse holders\n const whaleList: Array<{ address: Address; balance: number }> = [];\n for (const h of holders) {\n const addrStr: string = h[\"TokenHolderAddress\"] ?? \"\";\n const qtyStr: string = h[\"TokenHolderQuantity\"] ?? \"0\";\n if (/^0x[0-9a-fA-F]{40}$/.test(addrStr)) {\n const raw = BigInt(qtyStr || \"0\");\n const balance = Number(raw) / 10 ** token.decimals;\n whaleList.push({ address: addrStr as Address, balance });\n }\n }\n\n const whaleData: unknown[] = [];\n\n if (opts.positions && whaleList.length > 0) {\n // Get lending pools\n const lendingPools = registry\n .getProtocolsForChain(chainName)\n .filter(\n (p) =>\n p.category === ProtocolCategory.Lending &&\n (p.interface === \"aave_v3\" || p.interface === \"aave_v2\"),\n )\n .filter((p) => p.contracts?.[\"pool\"])\n .map((p) => ({\n name: p.name,\n pool: p.contracts![\"pool\"] as Address,\n iface: p.interface,\n }));\n\n // Build multicall: each whale × each pool\n const calls: Array<[Address, Hex]> = [];\n for (const whale of whaleList) {\n for (const { pool } of lendingPools) {\n calls.push([\n pool,\n encodeFunctionData({ abi: POOL_ABI, functionName: \"getUserAccountData\", args: [whale.address] }),\n ]);\n }\n }\n\n let results: (Hex | null)[] = [];\n if (calls.length > 0) {\n try {\n results = await multicallRead(rpc, calls);\n } catch {\n results = [];\n }\n }\n\n const poolsPerWhale = lendingPools.length;\n\n for (let wi = 0; wi < whaleList.length; wi++) {\n const whale = whaleList[wi]!;\n const positions: unknown[] = [];\n\n for (let pi = 0; pi < lendingPools.length; pi++) {\n const { name: protoName, iface } = lendingPools[pi]!;\n const idx = wi * poolsPerWhale + pi;\n const data = results[idx] ?? null;\n\n if (data && data.length >= 2 + 192 * 2) {\n const dec = iface === \"aave_v2\" ? 18 : 8;\n const divisor = 10 ** dec;\n const collateral = Number(decodeU256(data, 0)) / divisor;\n const debt = Number(decodeU256(data, 1)) / divisor;\n const hfRaw = decodeU256(data, 5);\n let hf: number | null = null;\n if (hfRaw <= BigInt(\"0xffffffffffffffffffffffffffffffff\")) {\n const v = Number(hfRaw) / 1e18;\n hf = v > 1e10 ? null : round2(v);\n }\n\n if (collateral > 0.01 || debt > 0.01) {\n positions.push({\n protocol: protoName,\n collateral_usd: round2(collateral),\n debt_usd: round2(debt),\n health_factor: hf,\n });\n }\n }\n }\n\n whaleData.push({\n rank: wi + 1,\n address: whale.address,\n balance: round4(whale.balance),\n positions,\n });\n }\n } else {\n for (let wi = 0; wi < whaleList.length; wi++) {\n const whale = whaleList[wi]!;\n whaleData.push({\n rank: wi + 1,\n address: whale.address,\n balance: round4(whale.balance),\n });\n }\n }\n\n printOutput(\n {\n chain: chain.name,\n token: opts.token,\n token_address: tokenAddr,\n decimals: token.decimals,\n top,\n holders: whaleData,\n explorer: chain.explorer_url ?? \"\",\n },\n mode,\n );\n });\n}\n","import { spawnSync } from \"child_process\";\nimport type { Command } from \"commander\";\nimport { Registry, ProtocolCategory } from \"@hypurrquant/defi-core\";\nimport { createLending } from \"@hypurrquant/defi-protocols\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\n\nfunction round2(x: number): number {\n return Math.round(x * 100) / 100;\n}\n\n/** Fetch perp funding rates by calling `perp --json arb scan --rates` */\nasync function fetchPerpRates(): Promise<unknown[]> {\n // Try global `perp` first, then npx fallback\n let result = spawnSync(\"perp\", [\"--json\", \"arb\", \"scan\", \"--rates\"], { encoding: \"utf8\", timeout: 30000 });\n if (result.error || result.status !== 0) {\n result = spawnSync(\"npx\", [\"-y\", \"perp-cli@latest\", \"--json\", \"arb\", \"scan\", \"--rates\"], {\n encoding: \"utf8\",\n timeout: 60000,\n });\n }\n\n if (result.error || result.status !== 0) {\n throw new Error(\"perp-cli not found or failed\");\n }\n\n let data: unknown;\n try {\n data = JSON.parse(result.stdout);\n } catch {\n throw new Error(\"perp JSON parse error\");\n }\n\n const d = data as Record<string, unknown>;\n const symbolsRaw =\n (d[\"data\"] as Record<string, unknown> | undefined)?.[\"symbols\"] ??\n d[\"symbols\"];\n const symbols = Array.isArray(symbolsRaw) ? symbolsRaw : [];\n\n const results: unknown[] = [];\n for (const sym of symbols as Array<Record<string, unknown>>) {\n const symbol = (sym[\"symbol\"] as string) ?? \"?\";\n const maxSpread = (sym[\"maxSpreadAnnual\"] as number) ?? 0;\n const longEx = (sym[\"longExchange\"] as string) ?? \"?\";\n const shortEx = (sym[\"shortExchange\"] as string) ?? \"?\";\n\n if (Math.abs(maxSpread) > 0) {\n results.push({\n type: \"perp_funding\",\n asset: symbol,\n apy: round2(maxSpread),\n detail: `long ${longEx} / short ${shortEx}`,\n risk: Math.abs(maxSpread) > 50 ? \"high\" : Math.abs(maxSpread) > 20 ? \"medium\" : \"low\",\n source: \"perp-cli\",\n });\n }\n\n const rates = Array.isArray(sym[\"rates\"]) ? (sym[\"rates\"] as Array<Record<string, unknown>>) : [];\n for (const rate of rates) {\n const exchange = (rate[\"exchange\"] as string) ?? \"?\";\n const annual = (rate[\"annualizedPct\"] as number) ?? 0;\n if (Math.abs(annual) > 1.0) {\n results.push({\n type: \"perp_rate\",\n asset: symbol,\n apy: round2(annual),\n detail: exchange,\n risk: Math.abs(annual) > 50 ? \"high\" : Math.abs(annual) > 20 ? \"medium\" : \"low\",\n source: \"perp-cli\",\n });\n }\n }\n }\n\n return results;\n}\n\n/** Fetch lending supply rates across all chains for a given asset */\nasync function fetchLendingRates(registry: Registry, asset: string): Promise<unknown[]> {\n const chainKeys = Array.from(registry.chains.keys());\n\n const tasks = chainKeys.map(async (ck) => {\n try {\n const chain = registry.getChain(ck);\n const chainName = chain.name.toLowerCase();\n\n let assetAddr: `0x${string}`;\n try {\n assetAddr = registry.resolveToken(chainName, asset).address;\n } catch {\n return [];\n }\n\n const protos = registry\n .getProtocolsForChain(chainName)\n .filter((p) => p.category === ProtocolCategory.Lending && p.interface === \"aave_v3\");\n\n if (protos.length === 0) return [];\n\n const rpc = chain.effectiveRpcUrl();\n const rates: unknown[] = [];\n\n for (const proto of protos) {\n try {\n const lending = createLending(proto, rpc);\n const r = await lending.getRates(assetAddr);\n if (r.supply_apy > 0) {\n rates.push({\n type: \"lending_supply\",\n asset,\n apy: round2(r.supply_apy * 100),\n detail: `${r.protocol} (${chain.name})`,\n risk: \"low\",\n source: \"defi-cli\",\n });\n }\n } catch {\n // skip unavailable protocols\n }\n }\n\n return rates;\n } catch {\n return [];\n }\n });\n\n const nested = await Promise.all(tasks);\n return nested.flat();\n}\n\nexport function registerCompare(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"compare\")\n .description(\"Compare all yield sources: perp funding vs lending APY vs staking\")\n .option(\"--asset <token>\", \"Token symbol to compare (e.g. USDC, ETH)\", \"USDC\")\n .option(\"--no-perps\", \"Exclude perp funding rates\")\n .option(\"--no-lending\", \"Exclude lending rates\")\n .option(\"--min-apy <pct>\", \"Minimum absolute APY to show\", \"1.0\")\n .action(async (opts) => {\n try {\n const registry = Registry.loadEmbedded();\n const asset: string = opts.asset ?? \"USDC\";\n const includePerps: boolean = opts.perps !== false;\n const includeLending: boolean = opts.lending !== false;\n const minApy = parseFloat(opts.minApy ?? \"1.0\");\n\n const t0 = Date.now();\n const opportunities: unknown[] = [];\n\n // 1. Perp funding rates\n if (includePerps) {\n try {\n const perpData = await fetchPerpRates();\n for (const opp of perpData) {\n const apy = Math.abs((opp as Record<string, unknown>)[\"apy\"] as number ?? 0);\n if (apy >= minApy) opportunities.push(opp);\n }\n } catch {\n // perp-cli not available — skip silently\n }\n }\n\n // 2. Lending rates across all chains\n if (includeLending) {\n const lendingData = await fetchLendingRates(registry, asset);\n for (const opp of lendingData) {\n const apy = Math.abs((opp as Record<string, unknown>)[\"apy\"] as number ?? 0);\n if (apy >= minApy) opportunities.push(opp);\n }\n }\n\n // Sort by absolute APY descending\n opportunities.sort((a, b) => {\n const aApy = Math.abs((a as Record<string, unknown>)[\"apy\"] as number ?? 0);\n const bApy = Math.abs((b as Record<string, unknown>)[\"apy\"] as number ?? 0);\n return bApy - aApy;\n });\n\n const scanMs = Date.now() - t0;\n\n printOutput(\n {\n asset,\n scan_duration_ms: scanMs,\n total_opportunities: opportunities.length,\n opportunities,\n },\n getOpts(),\n );\n } catch (err) {\n printOutput({ error: String(err) }, getOpts());\n process.exit(1);\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\n\nconst ODOS_API = \"https://api.odos.xyz\";\n\nexport function registerSwap(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n parent\n .command(\"swap\")\n .description(\"Aggregator swap: best price across all DEXes (ODOS)\")\n .requiredOption(\"--token-in <token>\", \"Input token symbol or address\")\n .requiredOption(\"--token-out <token>\", \"Output token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount of input token in wei\")\n .option(\"--slippage <bps>\", \"Slippage tolerance in basis points\", \"50\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const tokenIn = opts.tokenIn.startsWith(\"0x\") ? opts.tokenIn as Address : registry.resolveToken(chainName, opts.tokenIn).address as Address;\n const tokenOut = opts.tokenOut.startsWith(\"0x\") ? opts.tokenOut as Address : registry.resolveToken(chainName, opts.tokenOut).address as Address;\n const sender = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n\n try {\n const quoteRes = await fetch(`${ODOS_API}/sor/quote/v2`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n chainId: chain.chain_id, inputTokens: [{ tokenAddress: tokenIn, amount: opts.amount }],\n outputTokens: [{ tokenAddress: tokenOut, proportion: 1 }],\n slippageLimitPercent: parseInt(opts.slippage) / 100, userAddr: sender,\n }),\n });\n const quote = await quoteRes.json() as any;\n if (!quote.pathId) { printOutput({ error: \"No ODOS route found\", quote }, getOpts()); return; }\n\n const assembleRes = await fetch(`${ODOS_API}/sor/assemble`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ pathId: quote.pathId, userAddr: sender }),\n });\n const assembled = await assembleRes.json() as Record<string, Record<string, string>>;\n\n if (assembled.transaction) {\n const tx = {\n description: `ODOS swap ${tokenIn} → ${tokenOut}`,\n to: assembled.transaction.to as Address,\n data: assembled.transaction.data as `0x${string}`,\n value: BigInt(assembled.transaction.value ?? 0),\n };\n const result = await executor.execute(tx);\n printOutput({ ...result, odos_quote: quote }, getOpts());\n } else {\n printOutput({ error: \"ODOS assembly failed\", assembled }, getOpts());\n }\n } catch (e) {\n printOutput({ error: `ODOS API error: ${e instanceof Error ? e.message : String(e)}` }, getOpts());\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\n\nconst LIFI_API = \"https://li.quest/v1\";\nconst DLN_API = \"https://dln.debridge.finance/v1.0/dln/order\";\nconst CCTP_FEE_API = \"https://iris-api.circle.com/v2/burn/USDC/fees\";\n\n// ── deBridge DLN ──\n\nconst DLN_CHAIN_IDS: Record<string, number> = {\n ethereum: 1,\n optimism: 10,\n bnb: 56,\n polygon: 137,\n arbitrum: 42161,\n avalanche: 43114,\n base: 8453,\n linea: 59144,\n zksync: 324,\n};\n\nasync function getDebridgeQuote(\n srcChainId: number,\n dstChainId: number,\n srcToken: string,\n dstToken: string,\n amountRaw: string,\n recipient: string,\n): Promise<{ amountOut: string; estimatedTime: number; raw: unknown }> {\n const params = new URLSearchParams({\n srcChainId: String(srcChainId),\n srcChainTokenIn: srcToken,\n srcChainTokenInAmount: amountRaw,\n dstChainId: String(dstChainId),\n dstChainTokenOut: dstToken,\n prependOperatingExpenses: \"true\",\n });\n\n const res = await fetch(`${DLN_API}/quote?${params}`);\n if (!res.ok) throw new Error(`deBridge quote failed: ${res.status} ${await res.text()}`);\n const data = await res.json() as Record<string, unknown>;\n\n const estimation = data.estimation as Record<string, unknown>;\n const dstOut = estimation?.dstChainTokenOut as Record<string, unknown>;\n const amountOut = String(dstOut?.recommendedAmount ?? dstOut?.amount ?? \"0\");\n const fulfillDelay = Number((data.order as Record<string, unknown>)?.approximateFulfillmentDelay ?? 10);\n\n // Get create-tx data for the transaction\n const createParams = new URLSearchParams({\n srcChainId: String(srcChainId),\n srcChainTokenIn: srcToken,\n srcChainTokenInAmount: amountRaw,\n dstChainId: String(dstChainId),\n dstChainTokenOut: dstToken,\n dstChainTokenOutAmount: amountOut,\n dstChainTokenOutRecipient: recipient,\n srcChainOrderAuthorityAddress: recipient,\n dstChainOrderAuthorityAddress: recipient,\n prependOperatingExpenses: \"true\",\n });\n\n const createRes = await fetch(`${DLN_API}/create-tx?${createParams}`);\n if (!createRes.ok) throw new Error(`deBridge create-tx failed: ${createRes.status} ${await createRes.text()}`);\n const createData = await createRes.json() as Record<string, unknown>;\n\n return {\n amountOut,\n estimatedTime: fulfillDelay,\n raw: createData,\n };\n}\n\n// ── Circle CCTP ──\n\n// CCTP domains per chain (V2)\nconst CCTP_DOMAINS: Record<string, number> = {\n ethereum: 0,\n avalanche: 1,\n optimism: 2,\n arbitrum: 3,\n solana: 5,\n base: 6,\n polygon: 7,\n sui: 8,\n aptos: 9,\n};\n\n// TokenMessenger V2 contract address (same on all EVM chains)\nconst CCTP_TOKEN_MESSENGER_V2 = \"0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d\";\n\n// Native USDC addresses per chain\nconst CCTP_USDC_ADDRESSES: Record<string, string> = {\n ethereum: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\",\n avalanche: \"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E\",\n optimism: \"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85\",\n arbitrum: \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\",\n base: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n polygon: \"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359\",\n};\n\nasync function getCctpFeeEstimate(\n srcDomain: number,\n dstDomain: number,\n amountUsdc: number,\n): Promise<{ fee: number; maxFeeSubunits: bigint }> {\n try {\n const res = await fetch(`${CCTP_FEE_API}/${srcDomain}/${dstDomain}`);\n if (res.ok) {\n const schedules = await res.json() as Array<{\n finalityThreshold: number;\n minimumFee: number;\n forwardFee?: { low: number; med: number; high: number };\n }>;\n // Use standard finality (2000) schedule\n const schedule = schedules.find(s => s.finalityThreshold === 2000) ?? schedules[0];\n if (schedule) {\n const amountSubunits = BigInt(Math.round(amountUsdc * 1e6));\n const bpsRounded = BigInt(Math.round(schedule.minimumFee * 100));\n const protocolFee = (amountSubunits * bpsRounded) / 1_000_000n;\n const protocolFeeBuffered = (protocolFee * 120n) / 100n;\n\n if (schedule.forwardFee) {\n const forwardFeeSubunits = BigInt(schedule.forwardFee.high);\n const totalMaxFee = protocolFeeBuffered + forwardFeeSubunits;\n return { fee: Number(totalMaxFee) / 1e6, maxFeeSubunits: totalMaxFee };\n }\n\n const minFee = protocolFeeBuffered > 0n ? protocolFeeBuffered : 10000n;\n return { fee: Number(minFee) / 1e6, maxFeeSubunits: minFee };\n }\n }\n } catch {\n // use fallback\n }\n return { fee: 0.25, maxFeeSubunits: 250000n };\n}\n\nexport function registerBridge(parent: Command, getOpts: () => OutputMode): void {\n parent\n .command(\"bridge\")\n .description(\"Cross-chain bridge: move assets between chains\")\n .requiredOption(\"--token <token>\", \"Token symbol or address\")\n .requiredOption(\"--amount <amount>\", \"Amount in wei\")\n .requiredOption(\"--to-chain <chain>\", \"Destination chain name\")\n .option(\"--recipient <address>\", \"Recipient address on destination chain\")\n .option(\"--slippage <bps>\", \"Slippage in bps (LI.FI only)\", \"50\")\n .option(\"--provider <name>\", \"Bridge provider: lifi, debridge, cctp\", \"lifi\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const fromChain = registry.getChain(chainName);\n const toChain = registry.getChain(opts.toChain);\n const tokenAddr = opts.token.startsWith(\"0x\") ? opts.token : registry.resolveToken(chainName, opts.token).address;\n const recipient = (opts.recipient ?? process.env.DEFI_WALLET_ADDRESS ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const provider = (opts.provider as string).toLowerCase();\n\n if (provider === \"debridge\") {\n try {\n const srcId = DLN_CHAIN_IDS[chainName] ?? fromChain.chain_id;\n const dstId = DLN_CHAIN_IDS[opts.toChain] ?? toChain.chain_id;\n\n const result = await getDebridgeQuote(\n srcId, dstId,\n tokenAddr, tokenAddr,\n opts.amount,\n recipient,\n );\n\n const tx = (result.raw as Record<string, unknown>).tx as Record<string, unknown> | undefined;\n printOutput({\n from_chain: fromChain.name, to_chain: toChain.name,\n token: tokenAddr, amount: opts.amount,\n bridge: \"deBridge DLN\",\n estimated_output: result.amountOut,\n estimated_time_seconds: result.estimatedTime,\n tx: tx ? { to: tx.to, data: tx.data, value: tx.value } : undefined,\n }, getOpts());\n } catch (e) {\n printOutput({ error: `deBridge API error: ${e instanceof Error ? e.message : String(e)}` }, getOpts());\n }\n return;\n }\n\n if (provider === \"cctp\") {\n try {\n const srcDomain = CCTP_DOMAINS[chainName];\n const dstDomain = CCTP_DOMAINS[opts.toChain];\n\n if (srcDomain === undefined) {\n printOutput({ error: `CCTP not supported on source chain: ${chainName}. Supported: ${Object.keys(CCTP_DOMAINS).join(\", \")}` }, getOpts());\n return;\n }\n if (dstDomain === undefined) {\n printOutput({ error: `CCTP not supported on destination chain: ${opts.toChain}. Supported: ${Object.keys(CCTP_DOMAINS).join(\", \")}` }, getOpts());\n return;\n }\n\n const usdcSrc = CCTP_USDC_ADDRESSES[chainName];\n const usdcDst = CCTP_USDC_ADDRESSES[opts.toChain];\n if (!usdcSrc) {\n printOutput({ error: `No native USDC address known for ${chainName}. CCTP requires native USDC.` }, getOpts());\n return;\n }\n\n const amountUsdc = Number(BigInt(opts.amount)) / 1e6;\n const { fee, maxFeeSubunits } = await getCctpFeeEstimate(srcDomain, dstDomain, amountUsdc);\n\n // Build depositForBurn call data\n // TokenMessenger V2: depositForBurn(amount, destinationDomain, mintRecipient, burnToken, maxFee, minFinalityThreshold)\n // mintRecipient must be 32 bytes (left-padded address)\n const recipientPadded = `0x${\"0\".repeat(24)}${recipient.replace(\"0x\", \"\").toLowerCase()}` as `0x${string}`;\n\n const { encodeFunctionData, parseAbi } = await import(\"viem\");\n const tokenMessengerAbi = parseAbi([\n \"function depositForBurn(uint256 amount, uint32 destinationDomain, bytes32 mintRecipient, address burnToken, bytes32 destinationCaller, uint256 maxFee, uint32 minFinalityThreshold) external returns (uint64 nonce)\",\n ]);\n\n const data = encodeFunctionData({\n abi: tokenMessengerAbi,\n functionName: \"depositForBurn\",\n args: [\n BigInt(opts.amount),\n dstDomain,\n recipientPadded as `0x${string}`,\n usdcSrc as Address,\n `0x${\"0\".repeat(64)}` as `0x${string}`, // any caller\n maxFeeSubunits,\n 2000, // standard finality\n ],\n });\n\n printOutput({\n from_chain: fromChain.name, to_chain: toChain.name,\n token: usdcSrc,\n token_dst: usdcDst ?? tokenAddr,\n amount: opts.amount,\n bridge: \"Circle CCTP V2\",\n estimated_fee_usdc: fee,\n estimated_output: String(BigInt(opts.amount) - maxFeeSubunits),\n note: \"After burn, poll https://iris-api.circle.com/v2/messages/{srcDomain} for attestation, then call MessageTransmitter.receiveMessage() on destination\",\n tx: {\n to: CCTP_TOKEN_MESSENGER_V2,\n data,\n value: \"0x0\",\n },\n }, getOpts());\n } catch (e) {\n printOutput({ error: `CCTP error: ${e instanceof Error ? e.message : String(e)}` }, getOpts());\n }\n return;\n }\n\n // Default: LI.FI\n try {\n const params = new URLSearchParams({\n fromChain: String(fromChain.chain_id), toChain: String(toChain.chain_id),\n fromToken: tokenAddr, toToken: tokenAddr,\n fromAmount: opts.amount, fromAddress: recipient,\n slippage: String(parseInt(opts.slippage) / 10000),\n });\n const res = await fetch(`${LIFI_API}/quote?${params}`);\n const quote = await res.json() as any;\n\n if (quote.transactionRequest) {\n printOutput({\n from_chain: fromChain.name, to_chain: toChain.name,\n token: tokenAddr, amount: opts.amount,\n bridge: quote.toolDetails?.name ?? \"LI.FI\",\n estimated_output: quote.estimate?.toAmount,\n tx: { to: quote.transactionRequest.to, data: quote.transactionRequest.data, value: quote.transactionRequest.value },\n }, getOpts());\n } else {\n printOutput({ error: \"No LI.FI route found\", details: quote }, getOpts());\n }\n } catch (e) {\n printOutput({ error: `LI.FI API error: ${e instanceof Error ? e.message : String(e)}` }, getOpts());\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport { createNft } from \"@hypurrquant/defi-protocols\";\nimport type { Address } from \"viem\";\n\nexport function registerNft(parent: Command, getOpts: () => OutputMode): void {\n const nft = parent.command(\"nft\").description(\"NFT operations: collection info, ownership, balance\");\n\n nft.command(\"info\")\n .description(\"Get NFT collection info (name, symbol, total supply)\")\n .requiredOption(\"--collection <address>\", \"NFT collection contract address\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const nftProtocols = registry.getProtocolsByCategory(\"nft\" as any).filter(p => p.chain === chainName);\n const entry = nftProtocols[0] ?? { name: \"ERC721\", slug: \"erc721\", category: \"nft\", interface: \"erc721\", chain: chainName, contracts: { collection: opts.collection } };\n try {\n const adapter = createNft(entry, chain.effectiveRpcUrl());\n const info = await adapter.getCollectionInfo(opts.collection as Address);\n printOutput(info, getOpts());\n } catch (e) {\n printOutput({ error: e instanceof Error ? e.message : String(e) }, getOpts());\n }\n });\n\n nft.command(\"owner\")\n .description(\"Check who owns a specific NFT token ID\")\n .requiredOption(\"--collection <address>\", \"NFT collection contract address\")\n .requiredOption(\"--token-id <id>\", \"Token ID\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const nftProtocols = registry.getProtocolsByCategory(\"nft\" as any).filter(p => p.chain === chainName);\n const entry = nftProtocols[0] ?? { name: \"ERC721\", slug: \"erc721\", category: \"nft\", interface: \"erc721\", chain: chainName, contracts: { collection: opts.collection } };\n try {\n const adapter = createNft(entry, chain.effectiveRpcUrl());\n const info = await adapter.getTokenInfo(opts.collection as Address, BigInt(opts.tokenId));\n printOutput(info, getOpts());\n } catch (e) {\n printOutput({ error: e instanceof Error ? e.message : String(e) }, getOpts());\n }\n });\n\n nft.command(\"balance\")\n .description(\"Check how many NFTs an address holds in a collection\")\n .requiredOption(\"--collection <address>\", \"NFT collection contract address\")\n .requiredOption(\"--owner <address>\", \"Owner address to query\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const nftProtocols = registry.getProtocolsByCategory(\"nft\" as any).filter(p => p.chain === chainName);\n const entry = nftProtocols[0] ?? { name: \"ERC721\", slug: \"erc721\", category: \"nft\", interface: \"erc721\", chain: chainName, contracts: { collection: opts.collection } };\n try {\n const adapter = createNft(entry, chain.effectiveRpcUrl());\n const balance = await adapter.getBalance(opts.owner as Address, opts.collection as Address);\n printOutput({ collection: opts.collection, owner: opts.owner, balance }, getOpts());\n } catch (e) {\n printOutput({ error: e instanceof Error ? e.message : String(e) }, getOpts());\n }\n });\n\n nft.command(\"uri\")\n .description(\"Get token URI for a specific NFT\")\n .requiredOption(\"--collection <address>\", \"NFT collection contract address\")\n .requiredOption(\"--token-id <id>\", \"Token ID\")\n .action(async (opts) => {\n const chainName = parent.opts<{ chain?: string }>().chain ?? \"hyperevm\";\n const registry = Registry.loadEmbedded();\n const chain = registry.getChain(chainName);\n const nftProtocols = registry.getProtocolsByCategory(\"nft\" as any).filter(p => p.chain === chainName);\n const entry = nftProtocols[0] ?? { name: \"ERC721\", slug: \"erc721\", category: \"nft\", interface: \"erc721\", chain: chainName, contracts: { collection: opts.collection } };\n try {\n const adapter = createNft(entry, chain.effectiveRpcUrl());\n const info = await adapter.getTokenInfo(opts.collection as Address, BigInt(opts.tokenId));\n printOutput({ collection: opts.collection, token_id: opts.tokenId, token_uri: info.token_uri }, getOpts());\n } catch (e) {\n printOutput({ error: e instanceof Error ? e.message : String(e) }, getOpts());\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createMasterChef, MasterChefAdapter } from \"@hypurrquant/defi-protocols\";\n\nexport function registerFarm(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const farm = parent.command(\"farm\").description(\"LP farm operations: deposit, withdraw, claim rewards (MasterChef)\");\n\n farm.command(\"deposit\")\n .description(\"Deposit LP tokens into a MasterChef farm\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pid <pid>\", \"Farm pool ID\")\n .requiredOption(\"--amount <amount>\", \"LP token amount in wei\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMasterChef(protocol, rpcUrl);\n const tx = await adapter.buildDeposit(\n protocol.contracts?.[\"masterchef\"] as Address,\n BigInt(opts.amount),\n BigInt(opts.pid),\n );\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farm.command(\"withdraw\")\n .description(\"Withdraw LP tokens from a MasterChef farm\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pid <pid>\", \"Farm pool ID\")\n .requiredOption(\"--amount <amount>\", \"LP token amount in wei\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMasterChef(protocol, rpcUrl);\n const tx = await (adapter as MasterChefAdapter).buildWithdrawPid(\n BigInt(opts.pid),\n BigInt(opts.amount),\n );\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farm.command(\"claim\")\n .description(\"Claim pending rewards from a MasterChef farm\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pid <pid>\", \"Farm pool ID\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMasterChef(protocol, rpcUrl);\n const tx = await (adapter as MasterChefAdapter).buildClaimRewardsPid(\n BigInt(opts.pid),\n );\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farm.command(\"info\")\n .description(\"Show pending rewards and farm info\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .option(\"--pid <pid>\", \"Farm pool ID (optional)\")\n .option(\"--address <address>\", \"Wallet address to query (defaults to DEFI_WALLET_ADDRESS env)\")\n .action(async (opts) => {\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMasterChef(protocol, rpcUrl);\n const walletAddress = (opts.address ?? process.env[\"DEFI_WALLET_ADDRESS\"]) as Address | undefined;\n if (!walletAddress) {\n throw new Error(\"--address or DEFI_WALLET_ADDRESS required\");\n }\n const masterchef = protocol.contracts?.[\"masterchef\"] as Address;\n const rewards = await adapter.getPendingRewards(masterchef, walletAddress);\n printOutput(rewards, getOpts());\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { createKittenSwapFarming } from \"@hypurrquant/defi-protocols\";\n\nexport function registerFarming(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const farming = parent\n .command(\"farming\")\n .description(\"Algebra eternal farming operations (KittenSwap): enter, exit, collect rewards, claim, discover\");\n\n farming\n .command(\"enter\")\n .description(\"Enter farming: stake an NFT position to start earning rewards\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. kittenswap)\")\n .requiredOption(\"--pool <address>\", \"Pool address\")\n .requiredOption(\"--token-id <id>\", \"NFT position token ID\")\n .option(\"--owner <address>\", \"Owner address to receive claimed rewards (defaults to DEFI_WALLET_ADDRESS or private key address)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createKittenSwapFarming(protocol, rpcUrl);\n const owner = resolveOwner(opts.owner);\n const tx = await adapter.buildEnterFarming(\n BigInt(opts.tokenId),\n opts.pool as Address,\n owner,\n );\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farming\n .command(\"exit\")\n .description(\"Exit farming: unstake an NFT position\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. kittenswap)\")\n .requiredOption(\"--pool <address>\", \"Pool address\")\n .requiredOption(\"--token-id <id>\", \"NFT position token ID\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createKittenSwapFarming(protocol, rpcUrl);\n const tx = await adapter.buildExitFarming(\n BigInt(opts.tokenId),\n opts.pool as Address,\n );\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farming\n .command(\"rewards\")\n .description(\"Collect + claim farming rewards for a staked position (collectRewards + claimReward multicall)\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. kittenswap)\")\n .requiredOption(\"--pool <address>\", \"Pool address\")\n .requiredOption(\"--token-id <id>\", \"NFT position token ID\")\n .option(\"--owner <address>\", \"Owner address to receive claimed rewards (defaults to DEFI_WALLET_ADDRESS or private key address)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createKittenSwapFarming(protocol, rpcUrl);\n const owner = resolveOwner(opts.owner);\n const tx = await adapter.buildCollectRewards(\n BigInt(opts.tokenId),\n opts.pool as Address,\n owner,\n );\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farming\n .command(\"claim\")\n .description(\"Claim accumulated farming rewards (KITTEN + WHYPE) without changing position\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. kittenswap)\")\n .option(\"--owner <address>\", \"Owner address to receive rewards (defaults to DEFI_WALLET_ADDRESS or private key address)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createKittenSwapFarming(protocol, rpcUrl);\n const owner = resolveOwner(opts.owner);\n const tx = await adapter.buildClaimReward(owner);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n farming\n .command(\"pending\")\n .description(\"Query pending farming rewards for a position (read-only)\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. kittenswap)\")\n .requiredOption(\"--pool <address>\", \"Pool address\")\n .requiredOption(\"--token-id <id>\", \"NFT position token ID\")\n .action(async (opts) => {\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createKittenSwapFarming(protocol, rpcUrl);\n const rewards = await adapter.getPendingRewards(\n BigInt(opts.tokenId),\n opts.pool as Address,\n );\n printOutput(\n {\n tokenId: opts.tokenId,\n pool: opts.pool,\n reward_kitten: rewards.reward.toString(),\n bonus_reward_whype: rewards.bonusReward.toString(),\n },\n getOpts(),\n );\n });\n\n farming\n .command(\"discover\")\n .description(\"Discover all pools with active KittenSwap farming incentives\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. kittenswap)\")\n .action(async (opts) => {\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"hyperevm\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createKittenSwapFarming(protocol, rpcUrl);\n const pools = await adapter.discoverFarmingPools();\n const output = pools.map((p) => ({\n pool: p.pool,\n nonce: p.key.nonce.toString(),\n total_reward: p.totalReward.toString(),\n bonus_reward: p.bonusReward.toString(),\n active: p.active,\n }));\n printOutput(output, getOpts());\n });\n}\n\n/** Resolve owner address from CLI option, env vars, or private key */\nfunction resolveOwner(optOwner?: string): Address {\n if (optOwner) return optOwner as Address;\n\n const walletAddr = process.env[\"DEFI_WALLET_ADDRESS\"];\n if (walletAddr) return walletAddr as Address;\n\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n if (privateKey) {\n return privateKeyToAccount(privateKey as `0x${string}`).address;\n }\n\n throw new Error(\n \"--owner, DEFI_WALLET_ADDRESS, or DEFI_PRIVATE_KEY is required to resolve reward recipient\",\n );\n}\n","import type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { createInterface } from \"readline\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { resolve } from \"path\";\n\nconst DEFI_DIR = resolve(process.env.HOME || \"~\", \".defi\");\nconst ENV_FILE = resolve(DEFI_DIR, \".env\");\n\n// ── .env helpers ──────────────────────────────────────────────\n\nfunction ensureDefiDir() {\n if (!existsSync(DEFI_DIR)) mkdirSync(DEFI_DIR, { recursive: true, mode: 0o700 });\n}\n\nfunction loadEnvFile(): Record<string, string> {\n if (!existsSync(ENV_FILE)) return {};\n const lines = readFileSync(ENV_FILE, \"utf-8\").split(\"\\n\");\n const env: Record<string, string> = {};\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eqIdx = trimmed.indexOf(\"=\");\n if (eqIdx > 0) {\n env[trimmed.slice(0, eqIdx)] = trimmed.slice(eqIdx + 1);\n }\n }\n return env;\n}\n\nfunction writeEnvFile(env: Record<string, string>) {\n ensureDefiDir();\n const lines = [\n \"# defi-cli configuration\",\n \"# Generated by 'defi setup' — edit freely\",\n \"\",\n ];\n for (const [key, value] of Object.entries(env)) {\n lines.push(`${key}=${value}`);\n }\n lines.push(\"\");\n writeFileSync(ENV_FILE, lines.join(\"\\n\"), { mode: 0o600 });\n}\n\n// ── Interactive helpers ────────────────────────────────────────\n\nfunction ask(rl: ReturnType<typeof createInterface>, question: string): Promise<string> {\n return new Promise((res) => rl.question(question, (answer) => res(answer.trim())));\n}\n\n// ── Validation helpers ─────────────────────────────────────────\n\nfunction isValidAddress(s: string): boolean {\n return /^0x[0-9a-fA-F]{40}$/.test(s);\n}\n\nfunction isValidPrivateKey(s: string): boolean {\n return /^0x[0-9a-fA-F]{64}$/.test(s);\n}\n\nasync function deriveAddress(privateKey: string): Promise<string | null> {\n try {\n const { privateKeyToAccount } = await import(\"viem/accounts\");\n const account = privateKeyToAccount(privateKey as `0x${string}`);\n return account.address;\n } catch {\n return null;\n }\n}\n\n// ── Command ────────────────────────────────────────────────────\n\nexport function registerSetup(program: Command) {\n program\n .command(\"setup\")\n .alias(\"init\")\n .description(\"Interactive setup wizard — configure wallet & RPC URLs\")\n .action(async () => {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n\n try {\n console.log(pc.cyan(pc.bold(\"\\n defi-cli Setup Wizard\\n\")));\n\n // Show current config if it exists\n const existing = loadEnvFile();\n if (Object.keys(existing).length > 0) {\n console.log(pc.white(\" Current configuration:\"));\n for (const [key, value] of Object.entries(existing)) {\n const masked =\n key.toLowerCase().includes(\"key\")\n ? value.slice(0, 6) + \"...\" + value.slice(-4)\n : value;\n console.log(` ${pc.cyan(key.padEnd(24))} ${pc.gray(masked)}`);\n }\n console.log();\n const overwrite = await ask(rl, \" Overwrite existing config? (y/N): \");\n if (overwrite.toLowerCase() !== \"y\" && overwrite.toLowerCase() !== \"yes\") {\n console.log(pc.gray(\"\\n Keeping existing configuration.\\n\"));\n rl.close();\n return;\n }\n console.log();\n }\n\n const newEnv: Record<string, string> = {};\n\n // ── Wallet address / private key ──\n console.log(pc.cyan(pc.bold(\" Wallet\")));\n\n const privateKey = await ask(rl, \" Private key (optional, for --broadcast, 0x...): \");\n if (privateKey) {\n const normalized = privateKey.startsWith(\"0x\") ? privateKey : `0x${privateKey}`;\n if (!isValidPrivateKey(normalized)) {\n console.log(pc.red(\" Invalid private key (must be 0x + 64 hex chars). Skipped.\"));\n } else {\n newEnv.DEFI_PRIVATE_KEY = normalized;\n const derived = await deriveAddress(normalized);\n if (derived) {\n newEnv.DEFI_WALLET_ADDRESS = derived;\n console.log(` ${pc.green(\"OK\")} derived address: ${pc.gray(derived)}`);\n }\n }\n }\n\n if (!newEnv.DEFI_WALLET_ADDRESS) {\n const address = await ask(rl, \" Wallet address (0x...): \");\n if (address) {\n if (!isValidAddress(address)) {\n console.log(pc.yellow(\" Invalid address format. Skipping.\"));\n } else {\n newEnv.DEFI_WALLET_ADDRESS = address;\n console.log(` ${pc.green(\"OK\")} ${pc.gray(address)}`);\n }\n }\n }\n\n // ── RPC URLs ──\n console.log(pc.cyan(pc.bold(\"\\n RPC URLs\")) + pc.gray(\" (press Enter to use public defaults)\"));\n\n const hyperevmRpc = await ask(rl, \" HyperEVM RPC URL: \");\n if (hyperevmRpc) {\n newEnv.HYPEREVM_RPC_URL = hyperevmRpc;\n console.log(` ${pc.green(\"OK\")} HyperEVM RPC set`);\n }\n\n const mantleRpc = await ask(rl, \" Mantle RPC URL: \");\n if (mantleRpc) {\n newEnv.MANTLE_RPC_URL = mantleRpc;\n console.log(` ${pc.green(\"OK\")} Mantle RPC set`);\n }\n\n // Merge with existing non-overwritten keys (keep old keys not touched above)\n const finalEnv = { ...existing, ...newEnv };\n\n // Write .env\n writeEnvFile(finalEnv);\n\n // Summary\n console.log(pc.cyan(pc.bold(\"\\n Setup Complete!\\n\")));\n console.log(` Config: ${pc.gray(ENV_FILE)}`);\n if (finalEnv.DEFI_WALLET_ADDRESS) {\n console.log(` Wallet: ${pc.gray(finalEnv.DEFI_WALLET_ADDRESS)}`);\n }\n if (finalEnv.DEFI_PRIVATE_KEY) {\n console.log(` Key: ${pc.green(\"configured\")}`);\n }\n if (finalEnv.HYPEREVM_RPC_URL) {\n console.log(` HyperEVM RPC: ${pc.gray(finalEnv.HYPEREVM_RPC_URL)}`);\n }\n if (finalEnv.MANTLE_RPC_URL) {\n console.log(` Mantle RPC: ${pc.gray(finalEnv.MANTLE_RPC_URL)}`);\n }\n\n console.log(pc.bold(pc.white(\"\\n Next steps:\")));\n console.log(` ${pc.green(\"defi portfolio\")} view balances & positions`);\n console.log(` ${pc.green(\"defi scan\")} scan for exploits`);\n console.log(` ${pc.green(\"defi dex quote\")} get a swap quote`);\n console.log(` ${pc.green(\"defi --help\")} browse all commands\\n`);\n\n rl.close();\n } catch (err) {\n rl.close();\n throw err;\n }\n });\n}\n","import type { Command } from \"commander\";\nimport type { OutputMode } from \"../output.js\";\nimport type { Executor } from \"../executor.js\";\nimport { printOutput } from \"../output.js\";\nimport { Registry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\nimport { createMerchantMoeLB } from \"@hypurrquant/defi-protocols\";\n\nexport function registerLB(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const lb = parent.command(\"lb\").description(\"Merchant Moe Liquidity Book: add/remove liquidity, rewards, positions\");\n\n lb.command(\"add\")\n .description(\"Add liquidity to a Liquidity Book pair\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug (e.g. merchantmoe-mantle)\")\n .requiredOption(\"--pool <address>\", \"LB pair address\")\n .requiredOption(\"--token-x <address>\", \"Token X address\")\n .requiredOption(\"--token-y <address>\", \"Token Y address\")\n .requiredOption(\"--bin-step <step>\", \"Bin step of the pair\")\n .option(\"--amount-x <wei>\", \"Amount of token X in wei\", \"0\")\n .option(\"--amount-y <wei>\", \"Amount of token Y in wei\", \"0\")\n .option(\"--bins <N>\", \"Number of bins on each side of active bin\", \"5\")\n .option(\"--active-id <id>\", \"Active bin id (defaults to on-chain query)\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"mantle\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMerchantMoeLB(protocol, rpcUrl);\n const recipient = (opts.recipient ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildAddLiquidity({\n pool: opts.pool as Address,\n tokenX: opts.tokenX as Address,\n tokenY: opts.tokenY as Address,\n binStep: parseInt(opts.binStep),\n amountX: BigInt(opts.amountX),\n amountY: BigInt(opts.amountY),\n numBins: parseInt(opts.bins),\n activeIdDesired: opts.activeId ? parseInt(opts.activeId) : undefined,\n recipient,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n lb.command(\"remove\")\n .description(\"Remove liquidity from Liquidity Book bins\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--token-x <address>\", \"Token X address\")\n .requiredOption(\"--token-y <address>\", \"Token Y address\")\n .requiredOption(\"--bin-step <step>\", \"Bin step of the pair\")\n .requiredOption(\"--bins <binIds>\", \"Comma-separated bin IDs to remove from\")\n .requiredOption(\"--amounts <amounts>\", \"Comma-separated LB token amounts to remove per bin (wei)\")\n .option(\"--recipient <address>\", \"Recipient address\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createMerchantMoeLB(protocol);\n const recipient = (opts.recipient ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const binIds = (opts.bins as string).split(\",\").map((s: string) => parseInt(s.trim()));\n const amounts = (opts.amounts as string).split(\",\").map((s: string) => BigInt(s.trim()));\n const tx = await adapter.buildRemoveLiquidity({\n tokenX: opts.tokenX as Address,\n tokenY: opts.tokenY as Address,\n binStep: parseInt(opts.binStep),\n binIds,\n amounts,\n recipient,\n });\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n lb.command(\"rewards\")\n .description(\"Show pending MOE rewards for a pool\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pool <address>\", \"LB pair address\")\n .option(\"--bins <binIds>\", \"Comma-separated bin IDs to check (auto-detected from rewarder range if omitted)\")\n .option(\"--address <address>\", \"Wallet address (defaults to DEFI_WALLET_ADDRESS)\")\n .action(async (opts) => {\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"mantle\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMerchantMoeLB(protocol, rpcUrl);\n const user = (opts.address ?? process.env[\"DEFI_WALLET_ADDRESS\"]) as Address | undefined;\n if (!user) throw new Error(\"--address or DEFI_WALLET_ADDRESS required\");\n const binIds = opts.bins ? (opts.bins as string).split(\",\").map((s: string) => parseInt(s.trim())) : undefined;\n const rewards = await adapter.getPendingRewards(user, opts.pool as Address, binIds);\n printOutput(rewards, getOpts());\n });\n\n lb.command(\"claim\")\n .description(\"Claim pending MOE rewards from a pool\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pool <address>\", \"LB pair address\")\n .option(\"--bins <binIds>\", \"Comma-separated bin IDs to claim from (auto-detected from rewarder range if omitted)\")\n .option(\"--address <address>\", \"Wallet address (defaults to DEFI_WALLET_ADDRESS)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"mantle\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMerchantMoeLB(protocol, rpcUrl);\n const user = (opts.address ?? process.env[\"DEFI_WALLET_ADDRESS\"]) as Address | undefined;\n if (!user) throw new Error(\"--address or DEFI_WALLET_ADDRESS required\");\n const binIds = opts.bins ? (opts.bins as string).split(\",\").map((s: string) => parseInt(s.trim())) : undefined;\n const tx = await adapter.buildClaimRewards(user, opts.pool as Address, binIds);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n lb.command(\"discover\")\n .description(\"Find all rewarded LB pools on chain\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .option(\"--active-only\", \"Only show non-stopped pools\")\n .action(async (opts) => {\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"mantle\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMerchantMoeLB(protocol, rpcUrl);\n let pools = await adapter.discoverRewardedPools();\n if (opts.activeOnly) {\n pools = pools.filter((p) => !p.stopped);\n }\n printOutput(pools, getOpts());\n });\n\n lb.command(\"positions\")\n .description(\"Show user positions per bin in a LB pool\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--pool <address>\", \"LB pair address\")\n .option(\"--bins <binIds>\", \"Comma-separated bin IDs to query (auto-detected from rewarder range or active ± 50 if omitted)\")\n .option(\"--address <address>\", \"Wallet address (defaults to DEFI_WALLET_ADDRESS)\")\n .action(async (opts) => {\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const chainName = parent.opts<{ chain?: string }>().chain;\n const chain = registry.getChain(chainName ?? \"mantle\");\n const rpcUrl = chain.effectiveRpcUrl();\n const adapter = createMerchantMoeLB(protocol, rpcUrl);\n const user = (opts.address ?? process.env[\"DEFI_WALLET_ADDRESS\"]) as Address | undefined;\n if (!user) throw new Error(\"--address or DEFI_WALLET_ADDRESS required\");\n const binIds = opts.bins ? (opts.bins as string).split(\",\").map((s: string) => parseInt(s.trim())) : undefined;\n const positions = await adapter.getUserPositions(user, opts.pool as Address, binIds);\n printOutput(positions, getOpts());\n });\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,SAAS,qBAAqB;;;ACD9B,SAAS,sBAAAA,qBAAoB,oBAAoB,QAAAC,OAAM,YAAAC,WAAU,sBAAAC,2BAA0B;AAE3F,SAAS,2BA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,QAAQ,OAAO,EACf,YAAY,2DAA2D,EACvE,OAAO,YAAY;AAElB,QAAM,WAAW,aAAa;AAC9B,UAAQ,OAAO,MAAM,mDAAmD;AAGxE,UAAQ,OAAO,MAAM,oDAAoD;AACzE,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["createPublicClient","http","parseAbi","encodeFunctionData","encodeFunctionData","parseAbi","endPtr","TxStatus","InterestRateMode","parseAbi","encodeFunctionData","ProtocolCategory","parseAbi","encodeFunctionData","createPublicClient","http","jsonVal","createPublicClient","http","encodeFunctionData","parseAbi","createPublicClient","http","encodeFunctionData","parseAbi","createPublicClient","http","decodeFunctionResult","decodeAbiParameters","encodeFunctionData","parseAbi","createPublicClient","http","decodeAbiParameters","encodeFunctionData","parseAbi","zeroAddress","encodeFunctionData","parseAbi","encodeFunctionData","parseAbi","decodeAbiParameters","encodeFunctionData","parseAbi","createPublicClient","http","zeroAddress","createPublicClient","decodeFunctionResult","encodeFunctionData","http","parseAbi","zeroAddress","encodeFunctionData","parseAbi","zeroAddress","createPublicClient","decodeFunctionResult","encodeFunctionData","http","parseAbi","zeroAddress","encodeFunctionData","parseAbi","createPublicClient","http","encodeFunctionData","decodeFunctionResult","parseAbi","createPublicClient","http","decodeAbiParameters","encodeFunctionData","http","createPublicClient","parseAbi","decodeFunctionResult","zeroAddress","createPublicClient","http","parseAbi","encodeFunctionData","decodeFunctionResult","zeroAddress","createPublicClient","http","parseAbi","encodeFunctionData","zeroAddress","createPublicClient","http","parseAbi","createPublicClient","http","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","encodeFunctionData","parseAbi","encodeFunctionData","decodeFunctionResult","zeroAddress","createPublicClient","http","parseAbi","encodeFunctionData","zeroAddress","createPublicClient","http","parseAbi","createPublicClient","http","parseAbi","encodeFunctionData","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","encodeFunctionData","zeroAddress","createPublicClient","http","parseAbi","encodeFunctionData","zeroAddress","parseAbi","encodeFunctionData","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","parseAbi","encodeFunctionData","client","createPublicClient","http","amountOut","best","DefiError","decodeFunctionResult","decodeAbiParameters","abi","result","zeroAddress","poolAbi","multicallRead","veAbi","voterAbi","_addressDecodeAbi","decodeAddress","_symbolDecodeAbi","decodeSymbol","algebraFactoryAbi","data","lbQuoterAbi","erc20Abi","ids","HYPEREVM_TOKENS","positionManagerAbi","ERC20_ABI","SECONDS_PER_YEAR","POOL_ABI","u256ToF64","InterestRateMode","ORACLE_ABI","decodeU256","parseAbi","parseAbi","parseAbi","DefiError","createPublicClient","http","DefiError","makeExecutor","privateKeyToAccount","privateKeyToAccount","makeExecutor","makeExecutor","makeExecutor","makeExecutor","makeExecutor","makeExecutor","amountWei","encodeFunctionData","parseAbi","readdirSync","readFileSync","existsSync","resolve","encodeFunctionData","parseAbi","ERC20_ABI","parseAbi","ORACLE_ABI","POOL_ABI","resolve","encodeFunctionData","existsSync","readdirSync","readFileSync","ERC20_ABI","parseAbi","POOL_ABI","ORACLE_ABI","decodeU256","encodeFunctionData","encodeFunctionData","parseAbi","parseAbi","encodeFunctionData","makeExecutor","encodeFunctionData","parseAbi","ERC20_ABI","parseAbi","POOL_ABI","ORACLE_ABI","round2","round4","decodeU256","encodeFunctionData","round2","resolveAsset","createPublicClient","http","createPublicClient","http","makeExecutor","encodeFunctionData","parseAbi","POOL_ABI","parseAbi","round2","round4","decodeU256","encodeFunctionData","round2","makeExecutor","encodeFunctionData","parseAbi","makeExecutor","privateKeyToAccount","makeExecutor","privateKeyToAccount","pc","existsSync","mkdirSync","readFileSync","writeFileSync","resolve","privateKeyToAccount","program","makeExecutor"]}