@hypurrquant/defi-cli 0.2.3 → 0.2.4
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 +145 -0
- package/dist/index.js.map +1 -1
- package/dist/main.js +179 -26
- package/dist/main.js.map +1 -1
- package/package.json +1 -1
package/dist/main.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/balancer_v3.ts","../../defi-protocols/src/dex/curve.ts","../../defi-protocols/src/dex/solidly.ts","../../defi-protocols/src/dex/woofi.ts","../../defi-protocols/src/dex/solidly_gauge.ts","../../defi-protocols/src/dex/masterchef.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/landing.ts","../src/main.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\";\n\nconst BANNER = `\n ██████╗ ███████╗███████╗██╗ ██████╗██╗ ██╗\n ██╔══██╗██╔════╝██╔════╝██║ ██╔════╝██║ ██║\n ██║ ██║█████╗ █████╗ ██║ ██║ ██║ ██║\n ██║ ██║██╔══╝ ██╔══╝ ██║ ██║ ██║ ██║\n ██████╔╝███████╗██║ ██║ ╚██████╗███████╗██║\n ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝╚══════╝╚═╝\n\n 2 chains · 32 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);\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 } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type { ActionResult, DeFiTx, TxStatus } from \"@hypurrquant/defi-core\";\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 — 0.1 gwei */\nconst DEFAULT_PRIORITY_FEE_WEI = 100_000_000n;\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 /** 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) return Executor.applyGasBuffer(estimated);\n } catch {\n // fallback\n }\n return tx.gas_estimate ? BigInt(tx.gas_estimate) : 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 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 // 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 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 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 };\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}\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 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}\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\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 | \"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 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 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, 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 * 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 { WooFiAdapter } from \"./dex/woofi.js\";\nimport { SolidlyGaugeAdapter } from \"./dex/solidly_gauge.js\";\nimport { MasterChefAdapter } from \"./dex/masterchef.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 \"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 switch (entry.interface) {\n case \"solidly_v2\":\n case \"solidly_cl\":\n case \"algebra_v3\":\n case \"hybra\":\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","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 };\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 };\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 };\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 };\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\";\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 NonfungiblePositionManager (no fee field, uses plugin instead)\nconst algebraPositionManagerAbi = 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 };\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 // Prevent liquidity=0 revert for single-side LP (same as V3)\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: algebraPositionManagerAbi,\n functionName: \"mint\",\n args: [\n {\n token0,\n token1,\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 };\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, 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, createPublicClient, http, decodeAbiParameters } from \"viem\";\nimport type { Address, PublicClient } 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 \"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 };\n }\n\n private async callGetAmountsOut(\n client: PublicClient,\n callData: `0x${string}`,\n ): Promise<bigint> {\n const result = await client.call({ to: this.router, data: callData });\n if (!result.data) return 0n;\n const [amounts] = decodeAbiParameters(\n [{ name: \"amounts\", type: \"uint256[]\" }],\n result.data,\n );\n return amounts.length >= 2 ? amounts[amounts.length - 1] : 0n;\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 const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // Try all combinations: [volatile, stable] x [V1 ABI, V2 ABI (if factory present)]\n // Pick the best (highest amountOut)\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 results = await Promise.allSettled(\n candidates.map((c) => this.callGetAmountsOut(client, c.callData)),\n );\n\n let bestOut = 0n;\n let bestStable = false;\n for (let i = 0; i < results.length; i++) {\n const r = results[i];\n if (r.status === \"fulfilled\" && r.value > bestOut) {\n bestOut = r.value;\n bestStable = candidates[i].stable;\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 };\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, 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, encodeFunctionData, http, parseAbi, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IGaugeSystem,\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(address account) external\",\n \"function getReward(address account, address[] tokens) external\",\n \"function earned(address account) external view returns (uint256)\",\n \"function earned(address token, address account) external view returns (uint256)\",\n \"function rewardRate() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function rewardsListLength() external view returns (uint256)\",\n \"function isReward(address token) external view returns (bool)\",\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]);\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\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 }\n\n name(): string {\n return this.protocolName;\n }\n\n // IGauge\n\n async buildDeposit(gauge: Address, amount: bigint, tokenId?: bigint): 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 };\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 };\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 async buildClaimRewards(gauge: Address, account?: Address): Promise<DeFiTx> {\n // Ramses V2 gauges use getReward(address account, address[] tokens)\n // where account must equal msg.sender. Try to discover reward tokens via RPC.\n if (account && this.rpcUrl) {\n try {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const listLen = await client.readContract({\n address: gauge,\n abi: gaugeAbi,\n functionName: \"rewardsListLength\",\n }) as bigint;\n if (listLen > 0n) {\n // Discover reward tokens by checking isReward against known tokens\n // For Ramses V2, use the voter to find reward tokens\n // Alternatively, scan storage: the gauge exposes earned(token, account)\n // We'll pass empty tokens array and let the gauge figure it out,\n // or pass a placeholder. Since we know RAM is the reward token\n // from the gauge context, we need to enumerate them.\n // Fallback: use getReward(account, []) — some implementations accept empty array\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [account, [] as Address[]],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n } catch {\n // fall through to default\n }\n }\n\n // Standard Solidly V2 gauge: getReward(address account)\n // account param will be overridden by msg.sender in most gauge implementations\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [account ?? zeroAddress],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async getPendingRewards(_gauge: Address, _user: Address): Promise<RewardInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] get_pending_rewards requires RPC`);\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 { 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\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\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 };\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 };\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 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 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 // 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 const controllerAddr = await client.readContract({\n address: aTokenAddress,\n abi: INCENTIVES_ABI,\n functionName: \"getIncentivesController\",\n });\n\n if (controllerAddr && controllerAddr !== zeroAddress) {\n const [supplyRewards, borrowRewards] = await Promise.all([\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsByAsset\",\n args: [aTokenAddress],\n }).catch(() => [] as Address[]),\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsByAsset\",\n args: [variableDebtTokenAddress],\n }).catch(() => [] as Address[]),\n ]);\n\n // Fetch emissions data for supply rewards\n const supplyDataPromises = supplyRewards.map((reward) =>\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsData\",\n args: [aTokenAddress, reward],\n }).catch(() => null),\n );\n const supplyData = await Promise.all(supplyDataPromises);\n for (let i = 0; i < supplyRewards.length; i++) {\n const data = supplyData[i];\n if (data && data[1] > 0n) {\n supplyRewardTokens.push(supplyRewards[i]);\n supplyEmissions.push(data[1].toString());\n }\n }\n\n // Fetch emissions data for borrow rewards\n const borrowDataPromises = borrowRewards.map((reward) =>\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsData\",\n args: [variableDebtTokenAddress, reward],\n }).catch(() => null),\n );\n const borrowData = await Promise.all(borrowDataPromises);\n for (let i = 0; i < borrowRewards.length; i++) {\n const data = borrowData[i];\n if (data && data[1] > 0n) {\n borrowRewardTokens.push(borrowRewards[i]);\n borrowEmissions.push(data[1].toString());\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\n const providerAddr = await client.readContract({\n address: this.pool,\n abi: POOL_PROVIDER_ABI,\n functionName: \"ADDRESSES_PROVIDER\",\n });\n const oracleAddr = await client.readContract({\n address: providerAddr,\n abi: ADDRESSES_PROVIDER_ABI,\n functionName: \"getPriceOracle\",\n });\n const [assetPrice, baseCurrencyUnit, assetDecimals] = await Promise.all([\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [asset],\n }),\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"BASE_CURRENCY_UNIT\",\n }),\n client.readContract({\n address: asset,\n abi: ERC20_DECIMALS_ABI,\n functionName: \"decimals\",\n }).catch(() => 18),\n ]);\n\n const priceUnit = Number(baseCurrencyUnit);\n const assetPriceF = Number(assetPrice) / priceUnit;\n const assetDecimalsDivisor = 10 ** assetDecimals;\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 [rewardPrice, rewardDecimals] = await Promise.all([\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [supplyRewardTokens[i] as Address],\n }).catch(() => 0n),\n client.readContract({\n address: supplyRewardTokens[i] as Address,\n abi: ERC20_DECIMALS_ABI,\n functionName: \"decimals\",\n }).catch(() => 18),\n ]);\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 [rewardPrice, rewardDecimals] = await Promise.all([\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [borrowRewardTokens[i] as Address],\n }).catch(() => 0n),\n client.readContract({\n address: borrowRewardTokens[i] as Address,\n abi: ERC20_DECIMALS_ABI,\n functionName: \"decimals\",\n }).catch(() => 18),\n ]);\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 };\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 };\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 { 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} 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\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 const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const queueLen = await client.readContract({\n address: this.defaultVault,\n abi: META_MORPHO_ABI,\n functionName: \"supplyQueueLength\",\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyQueueLength failed: ${e}`); });\n\n if ((queueLen as bigint) === 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 const marketId = await client.readContract({\n address: this.defaultVault,\n abi: META_MORPHO_ABI,\n functionName: \"supplyQueue\",\n args: [0n],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyQueue(0) failed: ${e}`); }) as `0x${string}`;\n\n const mkt = await client.readContract({\n address: this.morpho,\n abi: MORPHO_ABI,\n functionName: \"market\",\n args: [marketId],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] market() failed: ${e}`); });\n\n const [totalSupplyAssets, totalSupplyShares, totalBorrowAssets, totalBorrowShares, lastUpdate, fee] = mkt as [bigint, bigint, bigint, bigint, bigint, bigint];\n\n const supplyF = Number(totalSupplyAssets);\n const borrowF = Number(totalBorrowAssets);\n const util = supplyF > 0 ? borrowF / supplyF : 0;\n\n const params2 = await client.readContract({\n address: this.morpho,\n abi: MORPHO_ABI,\n functionName: \"idToMarketParams\",\n args: [marketId],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] idToMarketParams failed: ${e}`); });\n\n const [loanToken, collateralToken, oracle, irm, lltv] = params2 as [Address, Address, Address, Address, bigint];\n\n const irmMarketParams: MarketParams = { loanToken, collateralToken, oracle, irm, lltv };\n const irmMarket = { totalSupplyAssets, totalSupplyShares, totalBorrowAssets, totalBorrowShares, lastUpdate, fee };\n\n const borrowRatePerSec = await client.readContract({\n address: irm,\n abi: IRM_ABI,\n functionName: \"borrowRateView\",\n args: [irmMarketParams, irmMarket],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] borrowRateView failed: ${e}`); }) as bigint;\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 .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.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 });\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\nexport function registerGauge(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const gauge = parent.command(\"gauge\").description(\"Gauge operations: deposit, withdraw, claim, lock, vote (ve(3,3))\");\n\n gauge.command(\"deposit\")\n .description(\"Deposit LP tokens into a gauge\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--gauge <address>\", \"Gauge contract address\")\n .requiredOption(\"--amount <amount>\", \"LP token amount in wei\")\n .option(\"--ve-nft <tokenId>\", \"veNFT token ID for boosted rewards\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol);\n const tokenId = opts.veNft ? BigInt(opts.veNft) : undefined;\n const tx = await adapter.buildDeposit(opts.gauge as Address, BigInt(opts.amount), tokenId);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n gauge.command(\"withdraw\")\n .description(\"Withdraw LP tokens from a gauge\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--gauge <address>\", \"Gauge contract address\")\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 adapter = createGauge(protocol);\n const tx = await adapter.buildWithdraw(opts.gauge as Address, BigInt(opts.amount));\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 .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, executor.rpcUrl);\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n const account = privateKey\n ? privateKeyToAccount(privateKey as `0x${string}`).address\n : undefined;\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 gauge.command(\"lock\")\n .description(\"Create a veNFT lock\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--amount <amount>\", \"Amount to lock in wei\")\n .option(\"--days <days>\", \"Lock duration in days\", \"365\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol);\n const tx = await adapter.buildCreateLock(BigInt(opts.amount), parseInt(opts.days) * 86400);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n gauge.command(\"vote\")\n .description(\"Vote on gauge emissions with veNFT\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--ve-nft <tokenId>\", \"veNFT token ID\")\n .requiredOption(\"--pools <pools>\", \"Pool addresses (comma-separated)\")\n .requiredOption(\"--weights <weights>\", \"Vote weights (comma-separated)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol);\n const pools = opts.pools.split(\",\") as Address[];\n const weights = opts.weights.split(\",\").map((w: string) => BigInt(w));\n const tx = await adapter.buildVote(BigInt(opts.veNft), pools, weights);\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, 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 pc from \"picocolors\";\nimport { encodeFunctionData, parseAbi, formatUnits, createPublicClient, http } from \"viem\";\nimport type { Address, Hex } from \"viem\";\nimport { Registry, multicallRead, decodeU256, MULTICALL3_ADDRESS } from \"@hypurrquant/defi-core\";\nimport type { TokenEntry } from \"@hypurrquant/defi-core\";\n\n// Tokens to show on the landing page (ordered by importance)\nconst HYPEREVM_DISPLAY = [\"HYPE\", \"WHYPE\", \"USDC\", \"USDT0\", \"USDe\", \"kHYPE\", \"wstHYPE\"];\nconst MANTLE_DISPLAY = [\"MNT\", \"WMNT\", \"USDC\", \"USDT\", \"WETH\", \"mETH\"];\n\nconst balanceOfAbi = parseAbi([\n \"function balanceOf(address account) view returns (uint256)\",\n]);\n\n// multicall3 getEthBalance ABI\nconst getEthBalanceAbi = parseAbi([\n \"function getEthBalance(address addr) view returns (uint256)\",\n]);\n\ninterface TokenBalance {\n symbol: string;\n balance: string; // formatted, or \"?\" on error\n decimals: number;\n}\n\nasync function fetchBalances(\n rpcUrl: string,\n wallet: Address,\n tokens: TokenEntry[],\n): Promise<TokenBalance[]> {\n const calls: Array<[Address, Hex]> = tokens.map((t) => {\n const isNative = t.tags?.includes(\"native\") || t.address === \"0x0000000000000000000000000000000000000000\";\n if (isNative) {\n return [\n MULTICALL3_ADDRESS,\n encodeFunctionData({\n abi: getEthBalanceAbi,\n functionName: \"getEthBalance\",\n args: [wallet],\n }),\n ];\n }\n return [\n t.address,\n encodeFunctionData({\n abi: balanceOfAbi,\n functionName: \"balanceOf\",\n args: [wallet],\n }),\n ];\n });\n\n let results: (Hex | null)[];\n try {\n results = await multicallRead(rpcUrl, calls);\n } catch {\n results = tokens.map(() => null);\n }\n\n return tokens.map((t, i) => {\n const raw = decodeU256(results[i]);\n const formatted = formatUnits(raw, t.decimals);\n // Trim trailing zeros but keep 2 decimal places minimum\n const num = parseFloat(formatted);\n const display = num === 0 ? \"0.00\" : num >= 1000\n ? num.toLocaleString(\"en-US\", { minimumFractionDigits: 2, maximumFractionDigits: 2 })\n : num.toLocaleString(\"en-US\", { minimumFractionDigits: 2, maximumFractionDigits: 6 });\n return { symbol: t.symbol, balance: display, decimals: t.decimals };\n });\n}\n\nfunction shortenAddress(addr: string): string {\n if (addr.length < 12) return addr;\n return `${addr.slice(0, 6)}...${addr.slice(-4)}`;\n}\n\nfunction padRight(s: string, len: number): string {\n return s.length >= len ? s : s + \" \".repeat(len - s.length);\n}\n\nfunction padLeft(s: string, len: number): string {\n return s.length >= len ? s : \" \".repeat(len - s.length) + s;\n}\n\nfunction formatBalanceLine(sym: string, bal: string): string {\n const symPad = padRight(sym, 10);\n const balPad = padLeft(bal, 12);\n return ` ${symPad}${balPad}`;\n}\n\nexport async function showLandingPage(isJson: boolean): Promise<void> {\n const registry = Registry.loadEmbedded();\n const wallet = process.env.DEFI_WALLET_ADDRESS as Address | undefined;\n\n if (isJson) {\n if (!wallet) {\n console.log(JSON.stringify({ error: \"DEFI_WALLET_ADDRESS not set\" }, null, 2));\n return;\n }\n const heChain = registry.getChain(\"hyperevm\");\n const mantleChain = registry.getChain(\"mantle\");\n const heTokens = (registry.tokens.get(\"hyperevm\") ?? []).filter(t => HYPEREVM_DISPLAY.includes(t.symbol));\n const mantleTokens = (registry.tokens.get(\"mantle\") ?? []).filter(t => MANTLE_DISPLAY.includes(t.symbol));\n\n // Sort to match display order\n const heSorted = HYPEREVM_DISPLAY.map(s => heTokens.find(t => t.symbol === s)).filter(Boolean) as TokenEntry[];\n const mantleSorted = MANTLE_DISPLAY.map(s => mantleTokens.find(t => t.symbol === s)).filter(Boolean) as TokenEntry[];\n\n const [heBalances, mantleBalances] = await Promise.all([\n fetchBalances(heChain.effectiveRpcUrl(), wallet, heSorted),\n fetchBalances(mantleChain.effectiveRpcUrl(), wallet, mantleSorted),\n ]);\n\n console.log(JSON.stringify({\n wallet,\n chains: {\n hyperevm: { name: heChain.name, balances: heBalances },\n mantle: { name: mantleChain.name, balances: mantleBalances },\n },\n }, null, 2));\n return;\n }\n\n // Human-readable mode\n const { createRequire } = await import(\"node:module\");\n const _require = createRequire(import.meta.url);\n const pkg = _require(\"../package.json\") as { version: string };\n const version = pkg.version;\n\n if (!wallet) {\n console.log(\"\");\n console.log(pc.bold(pc.cyan(\" DeFi CLI v\" + version)));\n console.log(\"\");\n console.log(pc.yellow(\" Wallet not configured.\"));\n console.log(\" Set DEFI_WALLET_ADDRESS to see your balances:\");\n console.log(\"\");\n console.log(pc.dim(\" export DEFI_WALLET_ADDRESS=0x...\"));\n console.log(\"\");\n console.log(\" Commands:\");\n console.log(pc.dim(\" defi status Protocol overview\"));\n console.log(pc.dim(\" defi lending rates Compare lending APYs\"));\n console.log(pc.dim(\" defi dex quote Get swap quotes\"));\n console.log(pc.dim(\" defi portfolio View all positions\"));\n console.log(pc.dim(\" defi scan Exploit detection\"));\n console.log(pc.dim(\" defi --help Full command list\"));\n console.log(\"\");\n return;\n }\n\n const heChain = registry.getChain(\"hyperevm\");\n const mantleChain = registry.getChain(\"mantle\");\n\n const heTokens = (registry.tokens.get(\"hyperevm\") ?? []).filter(t => HYPEREVM_DISPLAY.includes(t.symbol));\n const mantleTokens = (registry.tokens.get(\"mantle\") ?? []).filter(t => MANTLE_DISPLAY.includes(t.symbol));\n\n const heSorted = HYPEREVM_DISPLAY.map(s => heTokens.find(t => t.symbol === s)).filter(Boolean) as TokenEntry[];\n const mantleSorted = MANTLE_DISPLAY.map(s => mantleTokens.find(t => t.symbol === s)).filter(Boolean) as TokenEntry[];\n\n // Fetch both chains in parallel\n const [heBalances, mantleBalances] = await Promise.all([\n fetchBalances(heChain.effectiveRpcUrl(), wallet, heSorted).catch(() =>\n heSorted.map(t => ({ symbol: t.symbol, balance: \"?\", decimals: t.decimals }))\n ),\n fetchBalances(mantleChain.effectiveRpcUrl(), wallet, mantleSorted).catch(() =>\n mantleSorted.map(t => ({ symbol: t.symbol, balance: \"?\", decimals: t.decimals }))\n ),\n ]);\n\n const colWidth = 38;\n const divider = \"─\".repeat(colWidth - 2);\n\n console.log(\"\");\n console.log(\n pc.bold(pc.cyan(\" DeFi CLI v\" + version)) +\n pc.dim(\" — \") +\n pc.bold(heChain.name) +\n pc.dim(\" · \") +\n pc.bold(mantleChain.name)\n );\n console.log(\"\");\n console.log(\" Wallet: \" + pc.yellow(shortenAddress(wallet)));\n console.log(\"\");\n\n // Chain headers\n const heHeader = padRight(\" \" + pc.bold(heChain.name), colWidth + 10 /* account for ANSI */);\n const mantleHeader = pc.bold(mantleChain.name);\n console.log(heHeader + \" \" + mantleHeader);\n\n const heDivider = padRight(\" \" + pc.dim(divider), colWidth + 10);\n const mantleDivider = pc.dim(divider);\n console.log(heDivider + \" \" + mantleDivider);\n\n const maxRows = Math.max(heBalances.length, mantleBalances.length);\n for (let i = 0; i < maxRows; i++) {\n const heEntry = heBalances[i];\n const mantleEntry = mantleBalances[i];\n\n const heText = heEntry ? formatBalanceLine(heEntry.symbol, heEntry.balance) : \"\";\n const mantleText = mantleEntry ? formatBalanceLine(mantleEntry.symbol, mantleEntry.balance) : \"\";\n\n // Color zero balances dimly, non-zero normally\n const heColored = heEntry\n ? (heEntry.balance === \"0.00\" || heEntry.balance === \"?\"\n ? pc.dim(heText)\n : heText)\n : \"\";\n const mantleColored = mantleEntry\n ? (mantleEntry.balance === \"0.00\" || mantleEntry.balance === \"?\"\n ? pc.dim(mantleText)\n : mantleText)\n : \"\";\n\n // Pad the left column (strip ANSI for length calculation)\n const visibleLen = heText.length;\n const padNeeded = colWidth - visibleLen;\n const paddedHe = heColored + (padNeeded > 0 ? \" \".repeat(padNeeded) : \"\");\n\n console.log(paddedHe + \" \" + mantleColored);\n }\n\n console.log(\"\");\n console.log(\" \" + pc.bold(\"Commands:\"));\n console.log(\" \" + pc.cyan(\"defi status\") + \" Protocol overview\");\n console.log(\" \" + pc.cyan(\"defi lending rates\") + \" Compare lending APYs\");\n console.log(\" \" + pc.cyan(\"defi dex quote\") + \" Get swap quotes\");\n console.log(\" \" + pc.cyan(\"defi portfolio\") + \" View all positions\");\n console.log(\" \" + pc.cyan(\"defi scan\") + \" Exploit detection\");\n console.log(\" \" + pc.cyan(\"defi --help\") + \" Full command list\");\n console.log(\"\");\n}\n","import { program } from \"./cli.js\";\nimport { showLandingPage } from \"./landing.js\";\n\nasync function main() {\n try {\n const rawArgs = process.argv.slice(2);\n // Known subcommands registered in cli.ts — everything that isn't a flag\n const knownSubcommands = new Set([\n \"status\", \"schema\", \"dex\", \"gauge\", \"lending\", \"cdp\", \"staking\", \"vault\",\n \"yield\", \"portfolio\", \"monitor\", \"alert\", \"scan\", \"arb\", \"positions\",\n \"price\", \"wallet\", \"token\", \"whales\", \"compare\", \"swap\", \"bridge\", \"nft\",\n \"farm\", \"agent\",\n ]);\n const hasSubcommand = rawArgs.some(a => !a.startsWith(\"-\") && knownSubcommands.has(a));\n const isJson = rawArgs.includes(\"--json\") || rawArgs.includes(\"--ndjson\");\n const isHelp = rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\");\n const isVersion = rawArgs.includes(\"--version\") || rawArgs.includes(\"-V\");\n\n if (!isHelp && !isVersion && (rawArgs.length === 0 || !hasSubcommand)) {\n await showLandingPage(isJson);\n return;\n }\n\n await program.parseAsync(process.argv);\n } catch (error) {\n const isJsonMode =\n process.argv.includes(\"--json\") || process.argv.includes(\"--ndjson\");\n\n if (isJsonMode) {\n const errorObj = {\n error: error instanceof Error ? error.message : String(error),\n };\n process.stderr.write(JSON.stringify(errorObj, null, 2) + \"\\n\");\n } else {\n process.stderr.write(\n `Error: ${error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E;AAAA,IACF;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;AAEA,KAAK;","names":["createPublicClient","http","encodeFunctionData","parseAbi","endPtr","InterestRateMode","parseAbi","encodeFunctionData","ProtocolCategory","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","createPublicClient","http","decodeAbiParameters","encodeFunctionData","parseAbi","zeroAddress","createPublicClient","encodeFunctionData","http","parseAbi","zeroAddress","encodeFunctionData","parseAbi","createPublicClient","http","createPublicClient","http","parseAbi","encodeFunctionData","zeroAddress","createPublicClient","http","parseAbi","encodeFunctionData","zeroAddress","createPublicClient","http","parseAbi","createPublicClient","http","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","encodeFunctionData","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","data","SECONDS_PER_YEAR","POOL_ABI","ERC20_ABI","u256ToF64","InterestRateMode","ORACLE_ABI","parseAbi","parseAbi","parseAbi","DefiError","createPublicClient","http","DefiError","makeExecutor","privateKeyToAccount","makeExecutor","privateKeyToAccount","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","pc","encodeFunctionData","parseAbi","parseAbi","encodeFunctionData","heChain","mantleChain","heTokens","mantleTokens","heSorted","mantleSorted","heBalances","mantleBalances","createRequire","_require","pc"]}
|
|
1
|
+
{"version":3,"sources":["../src/main.ts","../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/balancer_v3.ts","../../defi-protocols/src/dex/curve.ts","../../defi-protocols/src/dex/solidly.ts","../../defi-protocols/src/dex/woofi.ts","../../defi-protocols/src/dex/solidly_gauge.ts","../../defi-protocols/src/dex/masterchef.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/setup.ts","../src/landing.ts"],"sourcesContent":["import { config } from \"dotenv\";\nimport { resolve } from \"path\";\n// Load global ~/.defi/.env first, then CWD .env overrides it\nconfig({ path: resolve(process.env.HOME || \"~\", \".defi\", \".env\"), quiet: true });\nconfig({ quiet: true });\n\nimport { program } from \"./cli.js\";\nimport { showLandingPage } from \"./landing.js\";\n\nasync function main() {\n try {\n const rawArgs = process.argv.slice(2);\n // Known subcommands registered in cli.ts — everything that isn't a flag\n const knownSubcommands = new Set([\n \"status\", \"schema\", \"dex\", \"gauge\", \"lending\", \"cdp\", \"staking\", \"vault\",\n \"yield\", \"portfolio\", \"monitor\", \"alert\", \"scan\", \"arb\", \"positions\",\n \"price\", \"wallet\", \"token\", \"whales\", \"compare\", \"swap\", \"bridge\", \"nft\",\n \"farm\", \"agent\", \"setup\", \"init\",\n ]);\n const hasSubcommand = rawArgs.some(a => !a.startsWith(\"-\") && knownSubcommands.has(a));\n const isJson = rawArgs.includes(\"--json\") || rawArgs.includes(\"--ndjson\");\n const isHelp = rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\");\n const isVersion = rawArgs.includes(\"--version\") || rawArgs.includes(\"-V\");\n\n if (!isHelp && !isVersion && (rawArgs.length === 0 || !hasSubcommand)) {\n await showLandingPage(isJson);\n return;\n }\n\n await program.parseAsync(process.argv);\n } catch (error) {\n const isJsonMode =\n process.argv.includes(\"--json\") || process.argv.includes(\"--ndjson\");\n\n if (isJsonMode) {\n const errorObj = {\n error: error instanceof Error ? error.message : String(error),\n };\n process.stderr.write(JSON.stringify(errorObj, null, 2) + \"\\n\");\n } else {\n process.stderr.write(\n `Error: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n }\n process.exit(1);\n }\n}\n\nmain();\n","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 { registerSetup } from \"./commands/setup.js\";\n\nconst BANNER = `\n ██████╗ ███████╗███████╗██╗ ██████╗██╗ ██╗\n ██╔══██╗██╔════╝██╔════╝██║ ██╔════╝██║ ██║\n ██║ ██║█████╗ █████╗ ██║ ██║ ██║ ██║\n ██║ ██║██╔══╝ ██╔══╝ ██║ ██║ ██║ ██║\n ██████╔╝███████╗██║ ██║ ╚██████╗███████╗██║\n ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝╚══════╝╚═╝\n\n 2 chains · 32 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);\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 } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type { ActionResult, DeFiTx, TxStatus } from \"@hypurrquant/defi-core\";\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 — 0.1 gwei */\nconst DEFAULT_PRIORITY_FEE_WEI = 100_000_000n;\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 /** 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) return Executor.applyGasBuffer(estimated);\n } catch {\n // fallback\n }\n return tx.gas_estimate ? BigInt(tx.gas_estimate) : 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 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 // 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 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 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 };\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}\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 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}\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\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 | \"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 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 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, 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 * 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 { WooFiAdapter } from \"./dex/woofi.js\";\nimport { SolidlyGaugeAdapter } from \"./dex/solidly_gauge.js\";\nimport { MasterChefAdapter } from \"./dex/masterchef.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 \"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 switch (entry.interface) {\n case \"solidly_v2\":\n case \"solidly_cl\":\n case \"algebra_v3\":\n case \"hybra\":\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","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 };\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 };\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 };\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 };\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\";\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 NonfungiblePositionManager (no fee field, uses plugin instead)\nconst algebraPositionManagerAbi = 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 };\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 // Prevent liquidity=0 revert for single-side LP (same as V3)\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: algebraPositionManagerAbi,\n functionName: \"mint\",\n args: [\n {\n token0,\n token1,\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 };\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, 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, createPublicClient, http, decodeAbiParameters } from \"viem\";\nimport type { Address, PublicClient } 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 \"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 };\n }\n\n private async callGetAmountsOut(\n client: PublicClient,\n callData: `0x${string}`,\n ): Promise<bigint> {\n const result = await client.call({ to: this.router, data: callData });\n if (!result.data) return 0n;\n const [amounts] = decodeAbiParameters(\n [{ name: \"amounts\", type: \"uint256[]\" }],\n result.data,\n );\n return amounts.length >= 2 ? amounts[amounts.length - 1] : 0n;\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 const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // Try all combinations: [volatile, stable] x [V1 ABI, V2 ABI (if factory present)]\n // Pick the best (highest amountOut)\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 results = await Promise.allSettled(\n candidates.map((c) => this.callGetAmountsOut(client, c.callData)),\n );\n\n let bestOut = 0n;\n let bestStable = false;\n for (let i = 0; i < results.length; i++) {\n const r = results[i];\n if (r.status === \"fulfilled\" && r.value > bestOut) {\n bestOut = r.value;\n bestStable = candidates[i].stable;\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 };\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, 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, encodeFunctionData, http, parseAbi, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IGaugeSystem,\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(address account) external\",\n \"function getReward(address account, address[] tokens) external\",\n \"function earned(address account) external view returns (uint256)\",\n \"function earned(address token, address account) external view returns (uint256)\",\n \"function rewardRate() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function rewardsListLength() external view returns (uint256)\",\n \"function isReward(address token) external view returns (bool)\",\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]);\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\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 }\n\n name(): string {\n return this.protocolName;\n }\n\n // IGauge\n\n async buildDeposit(gauge: Address, amount: bigint, tokenId?: bigint): 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 };\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 };\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 async buildClaimRewards(gauge: Address, account?: Address): Promise<DeFiTx> {\n // Ramses V2 gauges use getReward(address account, address[] tokens)\n // where account must equal msg.sender. Try to discover reward tokens via RPC.\n if (account && this.rpcUrl) {\n try {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const listLen = await client.readContract({\n address: gauge,\n abi: gaugeAbi,\n functionName: \"rewardsListLength\",\n }) as bigint;\n if (listLen > 0n) {\n // Discover reward tokens by checking isReward against known tokens\n // For Ramses V2, use the voter to find reward tokens\n // Alternatively, scan storage: the gauge exposes earned(token, account)\n // We'll pass empty tokens array and let the gauge figure it out,\n // or pass a placeholder. Since we know RAM is the reward token\n // from the gauge context, we need to enumerate them.\n // Fallback: use getReward(account, []) — some implementations accept empty array\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [account, [] as Address[]],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n } catch {\n // fall through to default\n }\n }\n\n // Standard Solidly V2 gauge: getReward(address account)\n // account param will be overridden by msg.sender in most gauge implementations\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [account ?? zeroAddress],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async getPendingRewards(_gauge: Address, _user: Address): Promise<RewardInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] get_pending_rewards requires RPC`);\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 { 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\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\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 };\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 };\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 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 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 // 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 const controllerAddr = await client.readContract({\n address: aTokenAddress,\n abi: INCENTIVES_ABI,\n functionName: \"getIncentivesController\",\n });\n\n if (controllerAddr && controllerAddr !== zeroAddress) {\n const [supplyRewards, borrowRewards] = await Promise.all([\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsByAsset\",\n args: [aTokenAddress],\n }).catch(() => [] as Address[]),\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsByAsset\",\n args: [variableDebtTokenAddress],\n }).catch(() => [] as Address[]),\n ]);\n\n // Fetch emissions data for supply rewards\n const supplyDataPromises = supplyRewards.map((reward) =>\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsData\",\n args: [aTokenAddress, reward],\n }).catch(() => null),\n );\n const supplyData = await Promise.all(supplyDataPromises);\n for (let i = 0; i < supplyRewards.length; i++) {\n const data = supplyData[i];\n if (data && data[1] > 0n) {\n supplyRewardTokens.push(supplyRewards[i]);\n supplyEmissions.push(data[1].toString());\n }\n }\n\n // Fetch emissions data for borrow rewards\n const borrowDataPromises = borrowRewards.map((reward) =>\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsData\",\n args: [variableDebtTokenAddress, reward],\n }).catch(() => null),\n );\n const borrowData = await Promise.all(borrowDataPromises);\n for (let i = 0; i < borrowRewards.length; i++) {\n const data = borrowData[i];\n if (data && data[1] > 0n) {\n borrowRewardTokens.push(borrowRewards[i]);\n borrowEmissions.push(data[1].toString());\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\n const providerAddr = await client.readContract({\n address: this.pool,\n abi: POOL_PROVIDER_ABI,\n functionName: \"ADDRESSES_PROVIDER\",\n });\n const oracleAddr = await client.readContract({\n address: providerAddr,\n abi: ADDRESSES_PROVIDER_ABI,\n functionName: \"getPriceOracle\",\n });\n const [assetPrice, baseCurrencyUnit, assetDecimals] = await Promise.all([\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [asset],\n }),\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"BASE_CURRENCY_UNIT\",\n }),\n client.readContract({\n address: asset,\n abi: ERC20_DECIMALS_ABI,\n functionName: \"decimals\",\n }).catch(() => 18),\n ]);\n\n const priceUnit = Number(baseCurrencyUnit);\n const assetPriceF = Number(assetPrice) / priceUnit;\n const assetDecimalsDivisor = 10 ** assetDecimals;\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 [rewardPrice, rewardDecimals] = await Promise.all([\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [supplyRewardTokens[i] as Address],\n }).catch(() => 0n),\n client.readContract({\n address: supplyRewardTokens[i] as Address,\n abi: ERC20_DECIMALS_ABI,\n functionName: \"decimals\",\n }).catch(() => 18),\n ]);\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 [rewardPrice, rewardDecimals] = await Promise.all([\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [borrowRewardTokens[i] as Address],\n }).catch(() => 0n),\n client.readContract({\n address: borrowRewardTokens[i] as Address,\n abi: ERC20_DECIMALS_ABI,\n functionName: \"decimals\",\n }).catch(() => 18),\n ]);\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 };\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 };\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 { 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} 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\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 const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const queueLen = await client.readContract({\n address: this.defaultVault,\n abi: META_MORPHO_ABI,\n functionName: \"supplyQueueLength\",\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyQueueLength failed: ${e}`); });\n\n if ((queueLen as bigint) === 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 const marketId = await client.readContract({\n address: this.defaultVault,\n abi: META_MORPHO_ABI,\n functionName: \"supplyQueue\",\n args: [0n],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyQueue(0) failed: ${e}`); }) as `0x${string}`;\n\n const mkt = await client.readContract({\n address: this.morpho,\n abi: MORPHO_ABI,\n functionName: \"market\",\n args: [marketId],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] market() failed: ${e}`); });\n\n const [totalSupplyAssets, totalSupplyShares, totalBorrowAssets, totalBorrowShares, lastUpdate, fee] = mkt as [bigint, bigint, bigint, bigint, bigint, bigint];\n\n const supplyF = Number(totalSupplyAssets);\n const borrowF = Number(totalBorrowAssets);\n const util = supplyF > 0 ? borrowF / supplyF : 0;\n\n const params2 = await client.readContract({\n address: this.morpho,\n abi: MORPHO_ABI,\n functionName: \"idToMarketParams\",\n args: [marketId],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] idToMarketParams failed: ${e}`); });\n\n const [loanToken, collateralToken, oracle, irm, lltv] = params2 as [Address, Address, Address, Address, bigint];\n\n const irmMarketParams: MarketParams = { loanToken, collateralToken, oracle, irm, lltv };\n const irmMarket = { totalSupplyAssets, totalSupplyShares, totalBorrowAssets, totalBorrowShares, lastUpdate, fee };\n\n const borrowRatePerSec = await client.readContract({\n address: irm,\n abi: IRM_ABI,\n functionName: \"borrowRateView\",\n args: [irmMarketParams, irmMarket],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] borrowRateView failed: ${e}`); }) as bigint;\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 .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.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 });\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\nexport function registerGauge(parent: Command, getOpts: () => OutputMode, makeExecutor: () => Executor): void {\n const gauge = parent.command(\"gauge\").description(\"Gauge operations: deposit, withdraw, claim, lock, vote (ve(3,3))\");\n\n gauge.command(\"deposit\")\n .description(\"Deposit LP tokens into a gauge\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--gauge <address>\", \"Gauge contract address\")\n .requiredOption(\"--amount <amount>\", \"LP token amount in wei\")\n .option(\"--ve-nft <tokenId>\", \"veNFT token ID for boosted rewards\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol);\n const tokenId = opts.veNft ? BigInt(opts.veNft) : undefined;\n const tx = await adapter.buildDeposit(opts.gauge as Address, BigInt(opts.amount), tokenId);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n gauge.command(\"withdraw\")\n .description(\"Withdraw LP tokens from a gauge\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--gauge <address>\", \"Gauge contract address\")\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 adapter = createGauge(protocol);\n const tx = await adapter.buildWithdraw(opts.gauge as Address, BigInt(opts.amount));\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 .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol, executor.rpcUrl);\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n const account = privateKey\n ? privateKeyToAccount(privateKey as `0x${string}`).address\n : undefined;\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 gauge.command(\"lock\")\n .description(\"Create a veNFT lock\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--amount <amount>\", \"Amount to lock in wei\")\n .option(\"--days <days>\", \"Lock duration in days\", \"365\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol);\n const tx = await adapter.buildCreateLock(BigInt(opts.amount), parseInt(opts.days) * 86400);\n const result = await executor.execute(tx);\n printOutput(result, getOpts());\n });\n\n gauge.command(\"vote\")\n .description(\"Vote on gauge emissions with veNFT\")\n .requiredOption(\"--protocol <protocol>\", \"Protocol slug\")\n .requiredOption(\"--ve-nft <tokenId>\", \"veNFT token ID\")\n .requiredOption(\"--pools <pools>\", \"Pool addresses (comma-separated)\")\n .requiredOption(\"--weights <weights>\", \"Vote weights (comma-separated)\")\n .action(async (opts) => {\n const executor = makeExecutor();\n const registry = Registry.loadEmbedded();\n const protocol = registry.getProtocol(opts.protocol);\n const adapter = createGauge(protocol);\n const pools = opts.pools.split(\",\") as Address[];\n const weights = opts.weights.split(\",\").map((w: string) => BigInt(w));\n const tx = await adapter.buildVote(BigInt(opts.veNft), pools, weights);\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, 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 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 pc from \"picocolors\";\nimport { encodeFunctionData, parseAbi, formatUnits, createPublicClient, http } from \"viem\";\nimport type { Address, Hex } from \"viem\";\nimport { Registry, multicallRead, decodeU256, MULTICALL3_ADDRESS } from \"@hypurrquant/defi-core\";\nimport type { TokenEntry } from \"@hypurrquant/defi-core\";\n\n// Tokens to show on the landing page (ordered by importance)\nconst HYPEREVM_DISPLAY = [\"HYPE\", \"WHYPE\", \"USDC\", \"USDT0\", \"USDe\", \"kHYPE\", \"wstHYPE\"];\nconst MANTLE_DISPLAY = [\"MNT\", \"WMNT\", \"USDC\", \"USDT\", \"WETH\", \"mETH\"];\n\nconst balanceOfAbi = parseAbi([\n \"function balanceOf(address account) view returns (uint256)\",\n]);\n\n// multicall3 getEthBalance ABI\nconst getEthBalanceAbi = parseAbi([\n \"function getEthBalance(address addr) view returns (uint256)\",\n]);\n\ninterface TokenBalance {\n symbol: string;\n balance: string; // formatted, or \"?\" on error\n decimals: number;\n}\n\nasync function fetchBalances(\n rpcUrl: string,\n wallet: Address,\n tokens: TokenEntry[],\n): Promise<TokenBalance[]> {\n const calls: Array<[Address, Hex]> = tokens.map((t) => {\n const isNative = t.tags?.includes(\"native\") || t.address === \"0x0000000000000000000000000000000000000000\";\n if (isNative) {\n return [\n MULTICALL3_ADDRESS,\n encodeFunctionData({\n abi: getEthBalanceAbi,\n functionName: \"getEthBalance\",\n args: [wallet],\n }),\n ];\n }\n return [\n t.address,\n encodeFunctionData({\n abi: balanceOfAbi,\n functionName: \"balanceOf\",\n args: [wallet],\n }),\n ];\n });\n\n let results: (Hex | null)[];\n try {\n results = await multicallRead(rpcUrl, calls);\n } catch {\n results = tokens.map(() => null);\n }\n\n return tokens.map((t, i) => {\n const raw = decodeU256(results[i]);\n const formatted = formatUnits(raw, t.decimals);\n // Trim trailing zeros but keep 2 decimal places minimum\n const num = parseFloat(formatted);\n const display = num === 0 ? \"0.00\" : num >= 1000\n ? num.toLocaleString(\"en-US\", { minimumFractionDigits: 2, maximumFractionDigits: 2 })\n : num.toLocaleString(\"en-US\", { minimumFractionDigits: 2, maximumFractionDigits: 6 });\n return { symbol: t.symbol, balance: display, decimals: t.decimals };\n });\n}\n\nfunction shortenAddress(addr: string): string {\n if (addr.length < 12) return addr;\n return `${addr.slice(0, 6)}...${addr.slice(-4)}`;\n}\n\nfunction padRight(s: string, len: number): string {\n return s.length >= len ? s : s + \" \".repeat(len - s.length);\n}\n\nfunction padLeft(s: string, len: number): string {\n return s.length >= len ? s : \" \".repeat(len - s.length) + s;\n}\n\nfunction formatBalanceLine(sym: string, bal: string): string {\n const symPad = padRight(sym, 10);\n const balPad = padLeft(bal, 12);\n return ` ${symPad}${balPad}`;\n}\n\nexport async function showLandingPage(isJson: boolean): Promise<void> {\n const registry = Registry.loadEmbedded();\n const wallet = process.env.DEFI_WALLET_ADDRESS as Address | undefined;\n\n if (isJson) {\n if (!wallet) {\n console.log(JSON.stringify({ error: \"DEFI_WALLET_ADDRESS not set\" }, null, 2));\n return;\n }\n const heChain = registry.getChain(\"hyperevm\");\n const mantleChain = registry.getChain(\"mantle\");\n const heTokens = (registry.tokens.get(\"hyperevm\") ?? []).filter(t => HYPEREVM_DISPLAY.includes(t.symbol));\n const mantleTokens = (registry.tokens.get(\"mantle\") ?? []).filter(t => MANTLE_DISPLAY.includes(t.symbol));\n\n // Sort to match display order\n const heSorted = HYPEREVM_DISPLAY.map(s => heTokens.find(t => t.symbol === s)).filter(Boolean) as TokenEntry[];\n const mantleSorted = MANTLE_DISPLAY.map(s => mantleTokens.find(t => t.symbol === s)).filter(Boolean) as TokenEntry[];\n\n const [heBalances, mantleBalances] = await Promise.all([\n fetchBalances(heChain.effectiveRpcUrl(), wallet, heSorted),\n fetchBalances(mantleChain.effectiveRpcUrl(), wallet, mantleSorted),\n ]);\n\n console.log(JSON.stringify({\n wallet,\n chains: {\n hyperevm: { name: heChain.name, balances: heBalances },\n mantle: { name: mantleChain.name, balances: mantleBalances },\n },\n }, null, 2));\n return;\n }\n\n // Human-readable mode\n const { createRequire } = await import(\"node:module\");\n const _require = createRequire(import.meta.url);\n const pkg = _require(\"../package.json\") as { version: string };\n const version = pkg.version;\n\n if (!wallet) {\n console.log(\"\");\n console.log(pc.bold(pc.cyan(\" DeFi CLI v\" + version)));\n console.log(\"\");\n console.log(pc.yellow(\" Wallet not configured.\"));\n console.log(\" Set DEFI_WALLET_ADDRESS to see your balances:\");\n console.log(\"\");\n console.log(pc.dim(\" export DEFI_WALLET_ADDRESS=0x...\"));\n console.log(\"\");\n console.log(\" Commands:\");\n console.log(pc.dim(\" defi status Protocol overview\"));\n console.log(pc.dim(\" defi lending rates Compare lending APYs\"));\n console.log(pc.dim(\" defi dex quote Get swap quotes\"));\n console.log(pc.dim(\" defi portfolio View all positions\"));\n console.log(pc.dim(\" defi scan Exploit detection\"));\n console.log(pc.dim(\" defi --help Full command list\"));\n console.log(\"\");\n return;\n }\n\n const heChain = registry.getChain(\"hyperevm\");\n const mantleChain = registry.getChain(\"mantle\");\n\n const heTokens = (registry.tokens.get(\"hyperevm\") ?? []).filter(t => HYPEREVM_DISPLAY.includes(t.symbol));\n const mantleTokens = (registry.tokens.get(\"mantle\") ?? []).filter(t => MANTLE_DISPLAY.includes(t.symbol));\n\n const heSorted = HYPEREVM_DISPLAY.map(s => heTokens.find(t => t.symbol === s)).filter(Boolean) as TokenEntry[];\n const mantleSorted = MANTLE_DISPLAY.map(s => mantleTokens.find(t => t.symbol === s)).filter(Boolean) as TokenEntry[];\n\n // Fetch both chains in parallel\n const [heBalances, mantleBalances] = await Promise.all([\n fetchBalances(heChain.effectiveRpcUrl(), wallet, heSorted).catch(() =>\n heSorted.map(t => ({ symbol: t.symbol, balance: \"?\", decimals: t.decimals }))\n ),\n fetchBalances(mantleChain.effectiveRpcUrl(), wallet, mantleSorted).catch(() =>\n mantleSorted.map(t => ({ symbol: t.symbol, balance: \"?\", decimals: t.decimals }))\n ),\n ]);\n\n const colWidth = 38;\n const divider = \"─\".repeat(colWidth - 2);\n\n console.log(\"\");\n console.log(\n pc.bold(pc.cyan(\" DeFi CLI v\" + version)) +\n pc.dim(\" — \") +\n pc.bold(heChain.name) +\n pc.dim(\" · \") +\n pc.bold(mantleChain.name)\n );\n console.log(\"\");\n console.log(\" Wallet: \" + pc.yellow(shortenAddress(wallet)));\n console.log(\"\");\n\n // Chain headers\n const heHeader = padRight(\" \" + pc.bold(heChain.name), colWidth + 10 /* account for ANSI */);\n const mantleHeader = pc.bold(mantleChain.name);\n console.log(heHeader + \" \" + mantleHeader);\n\n const heDivider = padRight(\" \" + pc.dim(divider), colWidth + 10);\n const mantleDivider = pc.dim(divider);\n console.log(heDivider + \" \" + mantleDivider);\n\n const maxRows = Math.max(heBalances.length, mantleBalances.length);\n for (let i = 0; i < maxRows; i++) {\n const heEntry = heBalances[i];\n const mantleEntry = mantleBalances[i];\n\n const heText = heEntry ? formatBalanceLine(heEntry.symbol, heEntry.balance) : \"\";\n const mantleText = mantleEntry ? formatBalanceLine(mantleEntry.symbol, mantleEntry.balance) : \"\";\n\n // Color zero balances dimly, non-zero normally\n const heColored = heEntry\n ? (heEntry.balance === \"0.00\" || heEntry.balance === \"?\"\n ? pc.dim(heText)\n : heText)\n : \"\";\n const mantleColored = mantleEntry\n ? (mantleEntry.balance === \"0.00\" || mantleEntry.balance === \"?\"\n ? pc.dim(mantleText)\n : mantleText)\n : \"\";\n\n // Pad the left column (strip ANSI for length calculation)\n const visibleLen = heText.length;\n const padNeeded = colWidth - visibleLen;\n const paddedHe = heColored + (padNeeded > 0 ? \" \".repeat(padNeeded) : \"\");\n\n console.log(paddedHe + \" \" + mantleColored);\n }\n\n console.log(\"\");\n console.log(\" \" + pc.bold(\"Commands:\"));\n console.log(\" \" + pc.cyan(\"defi status\") + \" Protocol overview\");\n console.log(\" \" + pc.cyan(\"defi lending rates\") + \" Compare lending APYs\");\n console.log(\" \" + pc.cyan(\"defi dex quote\") + \" Get swap quotes\");\n console.log(\" \" + pc.cyan(\"defi portfolio\") + \" View all positions\");\n console.log(\" \" + pc.cyan(\"defi scan\") + \" Exploit detection\");\n console.log(\" \" + pc.cyan(\"defi --help\") + \" Full command list\");\n console.log(\"\");\n}\n"],"mappings":";;;AAAA,SAAS,cAAc;AACvB,SAAS,WAAAA,gBAAe;;;ACDxB,SAAS,eAAe;AACxB,SAAS,qBAAqB;;;ACD9B,SAAS,sBAAAC,qBAAoB,oBAAoB,QAAAC,aAAY;AAC7D,SAAS,2BAA2B;;;AIApC,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,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E,UAAM,YAAY,QAAQ,SAAS,WAAW,KAAK,QAAQ,SAAS,IAAI;AAExE,QAAI,CAAC,UAAU,CAAC,cAAc,QAAQ,WAAW,KAAK,CAAC,gBAAgB;AACrE,YAAM,gBAAgB,MAAM;AAC5B;AAAA,IACF;AAEA,UAAM,QAAQ,WAAW,QAAQ,IAAI;AAAA,EACvC,SAAS,OAAO;AACd,UAAM,aACJ,QAAQ,KAAK,SAAS,QAAQ,KAAK,QAAQ,KAAK,SAAS,UAAU;AAErE,QAAI,YAAY;AACd,YAAM,WAAW;AAAA,QACf,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,MAC9D;AACA,cAAQ,OAAO,MAAM,KAAK,UAAU,UAAU,MAAM,CAAC,IAAI,IAAI;AAAA,IAC/D,OAAO;AACL,cAAQ,OAAO;AAAA,QACb,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA;AAAA,MAClE;AAAA,IACF;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;AAEA,KAAK;","names":["resolve","createPublicClient","http","encodeFunctionData","parseAbi","endPtr","InterestRateMode","parseAbi","encodeFunctionData","ProtocolCategory","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","createPublicClient","http","decodeAbiParameters","encodeFunctionData","parseAbi","zeroAddress","createPublicClient","encodeFunctionData","http","parseAbi","zeroAddress","encodeFunctionData","parseAbi","createPublicClient","http","createPublicClient","http","parseAbi","encodeFunctionData","zeroAddress","createPublicClient","http","parseAbi","encodeFunctionData","zeroAddress","createPublicClient","http","parseAbi","createPublicClient","http","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","encodeFunctionData","createPublicClient","http","parseAbi","encodeFunctionData","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","data","SECONDS_PER_YEAR","POOL_ABI","ERC20_ABI","u256ToF64","InterestRateMode","ORACLE_ABI","parseAbi","parseAbi","parseAbi","DefiError","createPublicClient","http","DefiError","makeExecutor","privateKeyToAccount","makeExecutor","privateKeyToAccount","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","pc","existsSync","mkdirSync","readFileSync","writeFileSync","resolve","privateKeyToAccount","program","pc","encodeFunctionData","parseAbi","parseAbi","encodeFunctionData","heChain","mantleChain","heTokens","mantleTokens","heSorted","mantleSorted","heBalances","mantleBalances","createRequire","_require","pc","resolve"]}
|