FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
news tab update
tilakpatel227106dab0c23f
diff --git a/.github/workflows/build-cpp.yml b/.github/workflows/build-cpp.ymlindex 1cfcad498..f568b3490 100644--- a/.github/workflows/build-cpp.yml+++ b/.github/workflows/build-cpp.yml@@ -93,6 +93,7 @@ jobs:sudo apt-get install -y \cmake ninja-build gcc-12 g++-12 \libssl-dev \+ libsecret-1-dev \qt6-base-dev qt6-base-private-dev \qt6-tools-dev qt6-tools-dev-tools \libqt6charts6-dev libqt6websockets6-dev \diff --git a/docs/CRYPTO_WALLET_CONNECT.md b/docs/CRYPTO_WALLET_CONNECT.mdnew file mode 100644index 000000000..440e621a5--- /dev/null+++ b/docs/CRYPTO_WALLET_CONNECT.md@@ -0,0 +1,113 @@+# Connect your wallet — Crypto Center++The **Crypto Center** is where Fincept Terminal reads your $FNCPT identity. It shows your public address, SOL balance, $FNCPT balance, and live USD value. **Your private keys never touch the terminal.**++## Supported wallets++The terminal works with any Solana wallet that exposes the Wallet Standard provider in the browser:++| Wallet | Status |+|---|---|+| Phantom | ✅ |+| Solflare | ✅ |+| Backpack | ✅ |+| Glow | ✅ |+| Coinbase Wallet (Solana mode) | ✅ via `window.solana` |+| Any other extension exposing `window.solana` | ✅ |++Hardware wallets (Ledger, Trezor) work transparently — connect them through Phantom or Solflare and the terminal sees the resulting public key with no extra setup.++## How connect works (high level)++1. You click **Connect Wallet** in the Crypto Center.+2. The terminal opens **a single-use page in your default browser** at `http://127.0.0.1:<random-port>`.+3. The page asks your wallet extension to share its public key and to **sign a one-time challenge message** generated by the terminal.+4. The terminal verifies that signature locally, stores the public key (only) in your OS credential store, and closes the browser tab.+5. Balances start streaming from Solana RPC.++The browser tab self-destructs after the handshake. The local server only listens on `127.0.0.1`, only on a random port, only for the duration of the handshake (max 2 minutes), and only accepts requests carrying a fresh single-use token.++## Step by step (Phantom)++1. Install the [Phantom extension](https://phantom.app/) in Chrome, Brave, Edge, or Firefox.+2. In Fincept Terminal: **Navigate → Crypto → Crypto Center**.+3. Click **Connect Wallet**.+4. A new browser tab opens. Click the row labelled **Phantom**.+5. Phantom prompts you to authorise the connection — review the message, click **Connect**.+6. Phantom shows a second prompt: a *signed message* request. Verify it begins with `Fincept Terminal wallet-connect challenge.` then click **Sign**.+7. Tab closes. Terminal shows your public key and balances.++The Solflare flow is identical — pick the Solflare row instead.++## Step by step (other extensions)++If you don't see your wallet in the list, click **Other Solana wallet (window.solana)**. Most non-listed wallets inject themselves under that hook.++## Step by step (hardware wallet)++The terminal does **not** talk to Ledger or Trezor directly. Instead:++1. Pair your hardware wallet with **Phantom** or **Solflare** (one-time setup inside that wallet's UI).+2. Use the regular Phantom/Solflare connect flow above.+3. When Phantom asks you to sign the challenge, your hardware device will display the message — confirm on the device.++## Disconnecting++In Crypto Center → click **Disconnect**. The terminal:++- Wipes the saved public key from secure storage.+- Stops fetching balances.+- Resets the screen to the empty state.++The browser/wallet itself keeps its own session — to fully revoke access, also use Phantom's **Settings → Trusted Apps → Revoke**.++## What we store++Only on your local machine, in your OS credential store (Windows Credential Manager / macOS Keychain / Linux Secret Service):++- Your wallet's **public address** (base58).+- A short label (`phantom`, `solflare`, …) so the UI can display the right name.+- The timestamp you connected.++We never store, transmit, or even temporarily hold:++- Private keys.+- Seed phrases.+- Signed transaction blobs.+- Authentication tokens from the wallet provider.++## What we never do++- We never auto-sign anything. Every signing request goes through the wallet's own approval UI.+- We never hold custody of $FNCPT or SOL — your wallet is the only signer.+- We never expose the local connect server beyond `127.0.0.1`. Other devices on your LAN cannot reach it.+- We never use a remote CDN to load wallet-connect code. The connect page is bundled with the terminal and served from your local disk.++## Troubleshooting++**The browser tab opens but no wallet rows show "detected"**+Your extension may be installed but disabled for `127.0.0.1`. Open `chrome://extensions`, find your wallet, click **Details**, and ensure **Allow on localhost / all sites** is enabled.++**"Signature verification failed"**+The challenge message in your wallet didn't match what the terminal expected. This usually means the wallet returned a signature for a different message than was requested. Try again with a fresh connect.++**"Timed out waiting for browser callback"**+You took longer than 2 minutes to approve, or the browser couldn't reach `127.0.0.1`. Click **Reopen browser** in the dialog — the existing handshake session is still valid for a moment.++**Balances stuck at "—"**+The terminal falls back to the public Solana RPC, which is rate-limited. Add a free Helius API key for reliable balance fetching:+1. Sign up at [helius.dev](https://www.helius.dev/) (free tier is enough).+2. In Settings → Secrets, add the key under `solana.helius_api_key`.+3. Click the **Refresh** button on the Balance card.++**$FNCPT shows zero but I have tokens**+Your tokens might be at a different mint than the one the terminal is configured for. The current mint is hard-coded as the pump.fun deployment — `9LUqJ5aQTjQiUCL93gi33LZcscUoSBJNhVCYpPzEpump`. If your tokens were minted elsewhere, file an issue.++## Privacy++The terminal makes outbound requests to:++- The Solana RPC endpoint (Helius if you set a key, otherwise the public mainnet endpoint) — for `getBalance` and `getTokenAccountsByOwner`. The endpoint sees your public key.+- `lite-api.jup.ag` — for the $FNCPT spot price. The endpoint sees only the mint address (not your wallet).++Both requests are made by the terminal directly. Your wallet provider (Phantom/Solflare) is not contacted by the terminal at any point — it only runs in your browser, owned by you.diff --git a/fincept-qt/.claude/scheduled_tasks.lock b/fincept-qt/.claude/scheduled_tasks.lockdeleted file mode 100644index 4f37331f9..000000000--- a/fincept-qt/.claude/scheduled_tasks.lock+++ /dev/null@@ -1 +0,0 @@-{"sessionId":"70b3bc8e-3d5a-4a4c-a308-a40235226d57","pid":16144,"acquiredAt":1777033746170}\ No newline at end of filediff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txtindex 469602358..61c4f4865 100644--- a/fincept-qt/CMakeLists.txt+++ b/fincept-qt/CMakeLists.txt@@ -23,7 +23,7 @@ if(WIN32 AND CMAKE_HOST_WIN32)endif()endif()-project(FinceptTerminal VERSION 4.0.2 LANGUAGES CXX)+project(FinceptTerminal VERSION 4.0.2 LANGUAGES C CXX)# Strip C/C++ flags out of RC invocations — rc.exe only understands /D, /I, /fo.if(WIN32)@@ -65,11 +65,66 @@ endif()# ── Compiler cache (ccache / sccache) ────────────────────────────────────────# Detected at configure time. If present, routes every C/C++ compilation# through the cache. Cuts clean rebuilds by 5-20x when source hasn't changed.+#+# PCH SUPPORT — without this, ccache rejects 99% of calls with+# "Could not use precompiled header" because MSVC-style PCH files include+# a serialised path that defeats the cache key. The sloppiness flags ++# CCACHE_PCH_EXTSUM tell ccache to hash the PCH's contents instead of its+# path. This must be set both at configure time (when CMake records the+# launcher script) and at build time (when the launcher actually runs),+# so we wrap ccache in a CMake-generated script that exports the env vars+# unconditionally.find_program(FINCEPT_CCACHE_PROGRAM NAMES ccache sccache)if(FINCEPT_CCACHE_PROGRAM)- set(CMAKE_CXX_COMPILER_LAUNCHER "${FINCEPT_CCACHE_PROGRAM}")- set(CMAKE_C_COMPILER_LAUNCHER "${FINCEPT_CCACHE_PROGRAM}")- message(STATUS "Compiler cache enabled: ${FINCEPT_CCACHE_PROGRAM}")+ # Expose the same env vars to interactive `ccache -s` runs by writing a+ # ccache.conf in the cache dir. This is idempotent — ccache reads it on+ # every invocation, so changes here propagate without a clean rebuild.+ if(WIN32)+ set(_fincept_ccache_dir "$ENV{LOCALAPPDATA}/ccache")+ elseif(APPLE)+ set(_fincept_ccache_dir "$ENV{HOME}/Library/Caches/ccache")+ else()+ set(_fincept_ccache_dir "$ENV{HOME}/.ccache")+ endif()+ if(_fincept_ccache_dir AND IS_DIRECTORY "${_fincept_ccache_dir}")+ # ccache.conf format: KEY = VALUE per line. We write only the keys we+ # need; ccache merges with defaults for everything else.+ file(WRITE "${_fincept_ccache_dir}/ccache.conf"+ "sloppiness = pch_defines,time_macros,include_file_mtime,include_file_ctime,locale\n"+ "pch_external_checksum = true\n"+ "depend_mode = true\n"+ "compiler_check = content\n"+ "max_size = 5G\n")+ message(STATUS "Wrote ccache config to ${_fincept_ccache_dir}/ccache.conf")+ endif()++ # Wrap ccache in a launcher script that exports the env vars unconditionally+ # — belt-and-braces in case ccache.conf isn't picked up (e.g. when the user+ # has CCACHE_DIR set to a non-default location).+ if(WIN32)+ set(_fincept_ccache_launcher "${CMAKE_BINARY_DIR}/ccache_launcher.cmd")+ file(WRITE "${_fincept_ccache_launcher}"+ "@echo off\r\n"+ "set CCACHE_SLOPPINESS=pch_defines,time_macros,include_file_mtime,include_file_ctime,locale\r\n"+ "set CCACHE_PCH_EXTSUM=true\r\n"+ "set CCACHE_DEPEND=1\r\n"+ "set CCACHE_COMPILERCHECK=content\r\n"+ "\"${FINCEPT_CCACHE_PROGRAM}\" %*\r\n")+ else()+ set(_fincept_ccache_launcher "${CMAKE_BINARY_DIR}/ccache_launcher.sh")+ file(WRITE "${_fincept_ccache_launcher}"+ "#!/bin/sh\n"+ "export CCACHE_SLOPPINESS=pch_defines,time_macros,include_file_mtime,include_file_ctime,locale\n"+ "export CCACHE_PCH_EXTSUM=true\n"+ "export CCACHE_DEPEND=1\n"+ "export CCACHE_COMPILERCHECK=content\n"+ "exec \"${FINCEPT_CCACHE_PROGRAM}\" \"$@\"\n")+ execute_process(COMMAND chmod +x "${_fincept_ccache_launcher}")+ endif()++ set(CMAKE_CXX_COMPILER_LAUNCHER "${_fincept_ccache_launcher}")+ set(CMAKE_C_COMPILER_LAUNCHER "${_fincept_ccache_launcher}")+ message(STATUS "Compiler cache enabled: ${FINCEPT_CCACHE_PROGRAM} (PCH-aware launcher)")endif()# ── macOS rpath configuration ────────────────────────────────────────────────@@ -110,19 +165,34 @@ set(CMAKE_UNITY_BUILD_BATCH_SIZE 14)# https://cmake.org/cmake/help/latest/module/FetchContent.html#variable:FETCHCONTENT_UPDATES_DISCONNECTEDset(FETCHCONTENT_UPDATES_DISCONNECTED ON CACHE BOOL "Skip FetchContent update step after initial download")+# ── LTO (whole-program optimisation) ─────────────────────────────────────────+# /GL + /LTCG produce the smallest, fastest binary but make every incremental+# link a full whole-program rebuild over 400+ object files — easily 30-90s per+# link on a developer machine. Default OFF so daily iteration is fast; CI and+# explicit release builds opt in.+option(FINCEPT_ENABLE_LTO+ "Enable MSVC /GL + /LTCG and equivalent on GCC/Clang (slow link, smaller/faster binary)"+ OFF)+if(DEFINED ENV{CI})+ set(FINCEPT_ENABLE_LTO ON CACHE BOOL "" FORCE)+endif()+# MSVC compiler flags for maximum build throughput:-# /MP — multi-processor compilation (uses all logical cores within one project)-# /Z7 — embed debug info in .obj instead of shared PDB → no PDB write contention-# that serialises /MP builds (major speedup on 16+ core machines)+# /Z7 — embed debug info in .obj instead of shared PDB → no PDB write+# contention (major speedup with parallel compilation)# /Oi — enable intrinsics (faster codegen, no extra passes)# /bigobj — allow >65535 sections (needed by large unity TUs and MOC output)-# /d2FuncCache7 — MSVC internal: increase function-level cache for template-heavy code+#+# /MP is intentionally NOT set: Ninja already parallelises at the cl.exe level+# (one cl.exe per TU, capped at host CPU count). Adding /MP makes each cl.exe+# fork N more workers, oversubscribing the box and *slowing* builds. /MP is+# only useful under MSBuild, which parallelises by project not by TU.if(MSVC)# /permissive- : enforces ISO C++ conformance — catches MS-specific non-portable# code that would break on GCC/Clang (two-phase lookup, etc.)# /W4 : level-4 warnings (highest practical without /Wall noise)# /WX only in CI so local iteration isn't blocked by new warnings- add_compile_options(/MP /Z7 /Oi /bigobj /permissive- /W4)+ add_compile_options(/Z7 /Oi /bigobj /permissive- /W4)if(DEFINED ENV{CI})add_compile_options(/WX)endif()@@ -133,13 +203,31 @@ if(MSVC)string(REPLACE "/Zi" "/Z7" ${flag_var} "${${flag_var}}")string(REPLACE "/ZI" "/Z7" ${flag_var} "${${flag_var}}")endforeach()- # Release: enable whole-program optimisation + link-time code generation.- # /GL compiles to IL; /LTCG merges at link time for cross-TU inlining & DCE.- # Only for Release — Debug/RelWithDebInfo stay fast for iteration.- if(CMAKE_BUILD_TYPE STREQUAL "Release" OR- (DEFINED CMAKE_CONFIGURATION_TYPES AND "Release" IN_LIST CMAKE_CONFIGURATION_TYPES))++ # Whole-program optimisation. /GL marks each .obj as IL; /LTCG merges at+ # link time. Both required together — using one without the other warns+ # and silently disables. Gated behind FINCEPT_ENABLE_LTO so incremental+ # dev links stay fast (incremental linking is incompatible with /LTCG).+ if(FINCEPT_ENABLE_LTO)add_compile_options($<$<CONFIG:Release>:/GL>)add_link_options($<$<CONFIG:Release>:/LTCG:incremental>)+ else()+ # /INCREMENTAL with debug info needs /DEBUG to emit a usable PDB even+ # though we use /Z7 (objects carry debug). Keep linker incremental for+ # fast Release-mode iteration. CMake's default Release link flags set+ # /INCREMENTAL:NO; override here.+ add_link_options($<$<CONFIG:Release>:/INCREMENTAL>)+ add_link_options($<$<CONFIG:RelWithDebInfo>:/INCREMENTAL>)+ # Replace any /INCREMENTAL:NO that CMake's defaults inserted.+ foreach(flag_var+ CMAKE_EXE_LINKER_FLAGS_RELEASE+ CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO+ CMAKE_SHARED_LINKER_FLAGS_RELEASE+ CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO+ CMAKE_MODULE_LINKER_FLAGS_RELEASE+ CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO)+ string(REPLACE "/INCREMENTAL:NO" "/INCREMENTAL" ${flag_var} "${${flag_var}}")+ endforeach()endif()endif()@@ -460,6 +548,34 @@ else()target_compile_options(qtadvanceddocking-qt6 PRIVATE -w -Wno-error)endif()+# ── ed25519 (orlp/ed25519) ───────────────────────────────────────────────────+# Public-domain Ed25519 reference implementation. We only use ed25519_verify+# in WalletService (signed-message challenge for Solana wallet connect).+# Upstream has no CMakeLists, so we build the .c files into a small static lib.+set(CMAKE_SKIP_INSTALL_RULES TRUE CACHE BOOL "" FORCE)+FetchContent_Declare(+ ed25519+ GIT_REPOSITORY https://github.com/orlp/ed25519.git+ GIT_TAG b1f19fab4aebe607805620d25a5e42566ce46a0e # master @ 2026-04-27+ GIT_SHALLOW TRUE+ UPDATE_DISCONNECTED TRUE+)+FetchContent_MakeAvailable(ed25519)+file(GLOB FINCEPT_ED25519_SRC "${ed25519_SOURCE_DIR}/src/*.c")+add_library(fincept_ed25519 STATIC ${FINCEPT_ED25519_SRC})+target_include_directories(fincept_ed25519 PUBLIC "${ed25519_SOURCE_DIR}/src")+set_target_properties(fincept_ed25519 PROPERTIES+ UNITY_BUILD OFF+ POSITION_INDEPENDENT_CODE ON+ C_STANDARD 99+)+if(MSVC)+ target_compile_options(fincept_ed25519 PRIVATE /W0 /WX-)+else()+ target_compile_options(fincept_ed25519 PRIVATE -w -Wno-error)+endif()+set(CMAKE_SKIP_INSTALL_RULES FALSE CACHE BOOL "" FORCE)+# ── Source files by module ────────────────────────────────────────────────────# Core@@ -475,6 +591,7 @@ set(CORE_SOURCESsrc/core/keys/WindowCycler.cppsrc/core/net/NetSpeedMeter.cppsrc/core/symbol/SymbolContext.cpp+ src/core/symbol/SymbolGroupRegistry.cppsrc/core/symbol/SymbolMime.cppsrc/core/symbol/SymbolDragSource.cppsrc/core/components/ComponentCatalog.cpp@@ -585,6 +702,7 @@ set(STORAGE_SOURCESsrc/storage/sqlite/migrations/v018_widget_config.cppsrc/storage/sqlite/migrations/v019_sector_cache.cppsrc/storage/sqlite/migrations/v020_security_audit_log.cpp+ src/storage/sqlite/migrations/v021_max_tokens_default.cpp)# Python runner@@ -597,6 +715,7 @@ set(PYTHON_SOURCES# AI Chatset(AI_CHAT_SOURCESsrc/ai_chat/LlmService.cpp+ src/ai_chat/ModelCatalog.cppsrc/ai_chat/AiChatScreen.cppsrc/ai_chat/AiChatBubble.cpp)@@ -631,6 +750,7 @@ set(MCP_SOURCESsrc/mcp/tools/PythonTools.cppsrc/mcp/tools/SystemTools.cppsrc/mcp/tools/DataHubTools.cpp+ src/mcp/tools/ReportBuilderTools.cpp)# Trading@@ -711,6 +831,26 @@ set(SERVICE_SOURCESsrc/services/economics/EconomicsService.cppsrc/services/agents/AgentService.cppsrc/services/file_manager/FileManagerService.cpp++ # Wallet (Phase 1 — Solana wallet identity + balance display)+ src/services/wallet/Ed25519Verifier.cpp+ src/services/wallet/SolanaRpcClient.cpp+ src/services/wallet/LocalWalletBridge.cpp+ src/services/wallet/ConnectWalletDialog.cpp+ src/services/wallet/WalletService.cpp+ src/services/wallet/WalletTypes.cpp+ src/services/wallet/WalletBalanceProducer.cpp+ src/services/wallet/TokenPriceProducer.cpp+ # Wallet (Phase 2 — transaction-signing bridge + PumpPortal swap)+ src/services/wallet/WalletTxBridge.cpp+ src/services/wallet/SignTransactionDialog.cpp+ src/services/wallet/PumpFunSwapService.cpp+ # Wallet (Phase 2 Stage 2A.5 — multi-token holdings)+ src/services/wallet/TokenMetadataService.cpp+ # Wallet (Phase 2 Stage 2B — activity feed)+ src/services/wallet/WalletActivityProducer.cpp+ # Billing (Phase 2 Stage 2C — fee discount eligibility)+ src/services/billing/FeeDiscountService.cppsrc/services/sectors/SectorResolver.cppsrc/services/workflow/NodeRegistry.cppsrc/services/workflow/WorkflowService.cpp@@ -853,6 +993,8 @@ set(SCREEN_SOURCESsrc/screens/relationship_map/RelationshipMapScreen.cppsrc/screens/relationship_map/RelationshipGraphScene.cppsrc/services/relationship_map/RelationshipMapService.cpp+ src/services/report_builder/ReportBuilderService.cpp+ src/services/report_builder/ReportBuilderTemplates.cppsrc/screens/markets/MarketsScreen.cppsrc/screens/markets/MarketPanel.cppsrc/screens/markets/MarketPanelStore.cpp@@ -954,8 +1096,9 @@ set(SCREEN_SOURCESsrc/screens/surface_analytics/SurfaceCsvImporter.cppsrc/screens/surface_analytics/Surface3DWidget.cppsrc/screens/surface_analytics/SurfaceTableWidget.cpp- src/screens/surface_analytics/SurfaceMetricsPanel.cpp- src/screens/surface_analytics/SurfaceDatabentoPanel.cpp+ src/screens/surface_analytics/SurfaceLineWidget.cpp+ src/screens/surface_analytics/SurfaceControlPanel.cpp+ src/screens/surface_analytics/SurfaceDataInspector.cppsrc/screens/surface_analytics/SurfaceAnalyticsScreen.cppsrc/screens/dbnomics/DBnomicsDataTable.cppsrc/screens/dbnomics/DBnomicsChartWidget.cpp@@ -1142,6 +1285,19 @@ set(SCREEN_SOURCESsrc/screens/node_editor/properties/ExecutionResultsPanel.cppsrc/screens/node_editor/toolbar/NodeEditorToolbar.cppsrc/screens/node_editor/toolbar/DeployDialog.cpp++ # Crypto Center+ src/screens/crypto_center/CryptoCenterScreen.cpp+ src/screens/crypto_center/HoldingsBar.cpp+ src/screens/crypto_center/WalletActionConfirmDialog.cpp+ src/screens/crypto_center/tabs/ComingSoonTab.cpp+ src/screens/crypto_center/tabs/HomeTab.cpp+ src/screens/crypto_center/tabs/SettingsTab.cpp+ src/screens/crypto_center/tabs/TradeTab.cpp+ src/screens/crypto_center/tabs/ActivityTab.cpp+ src/screens/crypto_center/panels/SwapPanel.cpp+ src/screens/crypto_center/panels/HoldingsTable.cpp+ src/screens/crypto_center/panels/FeeDiscountPanel.cpp)# App@@ -1259,6 +1415,17 @@ set_source_files_properties(src/screens/dashboard/widgets/WatchlistWidget.cppsrc/screens/dashboard/widgets/WebScraperWidget.cppsrc/screens/data_mapping/DataMappingScreen.cpp+ src/screens/crypto_center/CryptoCenterScreen.cpp+ src/screens/crypto_center/HoldingsBar.cpp+ src/screens/crypto_center/WalletActionConfirmDialog.cpp+ src/screens/crypto_center/tabs/ComingSoonTab.cpp+ src/screens/crypto_center/tabs/HomeTab.cpp+ src/screens/crypto_center/tabs/SettingsTab.cpp+ src/screens/crypto_center/tabs/TradeTab.cpp+ src/screens/crypto_center/tabs/ActivityTab.cpp+ src/screens/crypto_center/panels/SwapPanel.cpp+ src/screens/crypto_center/panels/HoldingsTable.cpp+ src/screens/crypto_center/panels/FeeDiscountPanel.cppsrc/screens/dbnomics/DBnomicsChartWidget.cppsrc/screens/dbnomics/DBnomicsDataTable.cppsrc/screens/dbnomics/DBnomicsScreen.cpp@@ -1373,10 +1540,11 @@ set_source_files_properties(src/screens/support/SupportScreen.cppsrc/screens/surface_analytics/Surface3DWidget.cppsrc/screens/surface_analytics/SurfaceAnalyticsScreen.cpp+ src/screens/surface_analytics/SurfaceControlPanel.cppsrc/screens/surface_analytics/SurfaceCsvImporter.cpp- src/screens/surface_analytics/SurfaceDatabentoPanel.cpp+ src/screens/surface_analytics/SurfaceDataInspector.cppsrc/screens/surface_analytics/SurfaceDemoData.cpp- src/screens/surface_analytics/SurfaceMetricsPanel.cpp+ src/screens/surface_analytics/SurfaceLineWidget.cppsrc/screens/surface_analytics/SurfaceTableWidget.cppsrc/screens/trade_viz/TradeVizScreen.cppsrc/screens/watchlist/WatchlistScreen.cpp@@ -1841,11 +2009,35 @@ target_link_libraries(FinceptTerminal PRIVATEqtadvanceddocking-qt6OpenSSL::SSLOpenSSL::Crypto+ fincept_ed25519)-# macOS: also link Security.framework for Keychain in SecureStorage+# macOS: link Security.framework + CoreFoundation for SecItem API in SecureStorageif(APPLE)- target_link_libraries(FinceptTerminal PRIVATE "-framework Security")+ target_link_libraries(FinceptTerminal PRIVATE "-framework Security" "-framework CoreFoundation")+endif()++# Linux: optionally link libsecret for cryptographically-secure credential+# storage (Secret Service / GNOME Keyring / KWallet via the freedesktop+# compatibility layer). Without libsecret, SecureStorage falls back to+# XOR-obfuscated QSettings which is NOT secure. Install libsecret-1-dev+# (Debian/Ubuntu), libsecret-devel (Fedora), or libsecret (Arch) and+# reconfigure to enable.+if(UNIX AND NOT APPLE)+ find_package(PkgConfig QUIET)+ if(PkgConfig_FOUND)+ pkg_check_modules(LIBSECRET IMPORTED_TARGET libsecret-1)+ if(LIBSECRET_FOUND)+ target_link_libraries(FinceptTerminal PRIVATE PkgConfig::LIBSECRET)+ target_compile_definitions(FinceptTerminal PRIVATE FINCEPT_HAVE_LIBSECRET)+ message(STATUS "libsecret found — Linux SecureStorage will use Secret Service backend")+ else()+ message(WARNING+ "libsecret-1 not found — Linux credential storage falls back to "+ "XOR-obfuscated QSettings (NOT cryptographically secure). "+ "Install libsecret-1-dev and rebuild for production deployments.")+ endif()+ endif()endif()# Windows: link dbghelp for the crash-handler minidump writer (see@@ -2007,6 +2199,19 @@ add_custom_command(TARGET FinceptTerminal POST_BUILDCOMMAND ${CMAKE_COMMAND} -E copy_if_different"${CMAKE_CURRENT_SOURCE_DIR}/resources/component_catalog.json""$<TARGET_FILE_DIR:FinceptTerminal>/resources/component_catalog.json"+ COMMAND ${CMAKE_COMMAND} -E make_directory+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/wallet"+ COMMAND ${CMAKE_COMMAND} -E copy_if_different+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/wallet/connect.html"+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/wallet/connect.html"+ COMMAND ${CMAKE_COMMAND} -E copy_if_different+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/wallet/swap.html"+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/wallet/swap.html"+ COMMAND ${CMAKE_COMMAND} -E make_directory+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/wallet/vendor"+ COMMAND ${CMAKE_COMMAND} -E copy_directory+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/wallet/vendor"+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/wallet/vendor"COMMENT "Copying requirements files to build output...")diff --git a/fincept-qt/CMakePresets.json b/fincept-qt/CMakePresets.jsonindex 2d2d1cc19..48f2fd37e 100644--- a/fincept-qt/CMakePresets.json+++ b/fincept-qt/CMakePresets.json@@ -16,7 +16,7 @@{"name": "win-release","displayName": "Windows Release (MSVC 2022, Qt 6.8.3)",- "description": "Pinned Release build for Windows x64",+ "description": "Pinned Release build for Windows x64. Defaults to fast incremental link; opt into LTO with -DFINCEPT_ENABLE_LTO=ON for ship builds.","inherits": "base","condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Windows" },"architecture": { "value": "x64", "strategy": "external" },@@ -31,6 +31,25 @@"inherits": "win-release","cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" }},+ {+ "name": "win-fast",+ "displayName": "Windows Fast Iteration (MSVC 2022, RelWithDebInfo, Qt 6.8.3)",+ "description": "Optimised build tuned for fast incremental link — no LTO, incremental linker, /O2 with /Ob1. Use for daily development; switch to win-release for shipping.",+ "inherits": "win-release",+ "cacheVariables": {+ "CMAKE_BUILD_TYPE": "RelWithDebInfo",+ "FINCEPT_ENABLE_LTO": "OFF"+ }+ },+ {+ "name": "win-release-lto",+ "displayName": "Windows Release + LTO (MSVC 2022, Qt 6.8.3)",+ "description": "Ship build: full /GL + /LTCG whole-program optimisation. Slow to link (30-90s); use win-release or win-fast for iteration.",+ "inherits": "win-release",+ "cacheVariables": {+ "FINCEPT_ENABLE_LTO": "ON"+ }+ },{"name": "linux-release",@@ -71,8 +90,10 @@],"buildPresets": [- { "name": "win-release", "configurePreset": "win-release" },- { "name": "win-debug", "configurePreset": "win-debug" },+ { "name": "win-release", "configurePreset": "win-release" },+ { "name": "win-debug", "configurePreset": "win-debug" },+ { "name": "win-fast", "configurePreset": "win-fast" },+ { "name": "win-release-lto", "configurePreset": "win-release-lto" },{ "name": "linux-release", "configurePreset": "linux-release" },{ "name": "linux-debug", "configurePreset": "linux-debug" },{ "name": "macos-release", "configurePreset": "macos-release" },diff --git a/fincept-qt/docs/DATAHUB_TOPICS.md b/fincept-qt/docs/DATAHUB_TOPICS.mdindex 6095296bb..e6d06c09c 100644--- a/fincept-qt/docs/DATAHUB_TOPICS.md+++ b/fincept-qt/docs/DATAHUB_TOPICS.md@@ -128,6 +128,39 @@ The MCP module `DataHubTools` exposes four generic introspection tools to any LL- `datahub_request` — ask the hub to refresh a topic (subject to policy + `force` flag)- `datahub_subscribe_briefly` — collect all values published on a topic for a bounded duration (100-30000 ms)+## Crypto / on-chain (Phase 10)++The Crypto Center owns a small set of topics for the user's connected Solana wallet. Read-only data flows through the hub. Transaction-signing paths (Phase 2 swap) **do not** go through the hub — they're one-shot user actions handled by `WalletService` + `WalletTxBridge` directly.++### Wallet balances++| Pattern | Producer | TTL | Min interval | Notes |+|---|---|---|---|---|+| `wallet:balance:<pubkey>` | `WalletBalanceProducer` | 30 s (poll) / push-only (stream) | 10 s (poll) / — (stream) | Two refresh modes, switched at runtime via SecureStorage `wallet.balance_mode` (`poll` / `stream`). **Phase 2 §2A.5 carries every SPL token the wallet holds**, not just $FNCPT. Polling uses Solana RPC `getBalance` + `getTokenAccountsByOwner` (programId-filtered, no mint filter) + `TokenMetadataService::lookup` for symbol/name/icon. Streaming opens a per-pubkey WebSocket to the RPC `wss://` endpoint and `accountSubscribe`s on the wallet pubkey for SOL changes; non-SOL tokens are bootstrapped via REST and re-seeded on a 30 s heartbeat. Stream policy: `push_only=true`, `coalesce_within_ms=250`. Shape: `WalletBalance{pubkey_b58, sol_lamports, tokens: QVector<TokenHolding{mint, symbol, name, amount_raw, decimals, verified, icon_url}>, ts_ms}`. Legacy back-compat accessors `fncpt_holding()` / `fncpt_ui()` / `fncpt_decimals()` are exposed on `WalletBalance` for callers that still want FNCPT specifically. Endpoint priority: `solana.rpc_url` SecureStorage override → Helius (`solana.helius_api_key`) → public mainnet RPC (`https`/`wss` derived). |++### Token price++| Pattern | Producer | TTL | Min interval | Notes |+|---|---|---|---|---|+| `market:price:token:<mint>` | `TokenPriceProducer` | 60 s | 30 s | Jupiter Lite Price API (`lite-api.jup.ag/price/v3`). One batched call per refresh covers every mint that has at least one subscriber: `?ids=<m1>,<m2>,…`. Coalesce 250 ms across rapid subscribe events (panel re-subscribes on every balance update). `<mint>` accepts wrapped-SOL (`So111…1112`) for native SOL pricing. Shape: `TokenPrice{mint, usd, sol, ts_ms, valid}`. The `sol` field is FNCPT-priced-in-SOL when the SOL mint is part of the same batch; 0 otherwise. |+| `market:price:fncpt` | `TokenPriceProducer` | 60 s | 30 s | **Deprecated alias** for `market:price:token:9LUqJ5aQTjQiUCL93gi33LZcscUoSBJNhVCYpPzEpump`. Kept for one phase so existing subscribers (Phase 1's HoldingsBar, BalancePanel, SwapPanel) keep working without churn. Removed in Phase 3 cleanup; new subscribers should use `market:price:token:<mint>` directly. Shape: `TokenPrice` (legacy `FncptPrice` is a typedef alias). |++### Wallet activity (Phase 2)++| Pattern | Producer | TTL | Min interval | Notes |+|---|---|---|---|---|+| `wallet:activity:<pubkey>` | `WalletActivityProducer` | 30 s | 10 s | Last 50 parsed wallet operations. Helius parsed-transactions endpoint (`api.helius.xyz/v0/addresses/<pk>/transactions?limit=50`) when the user has a Helius key in `solana.helius_api_key`; falls back to raw `getSignaturesForAddress` (signatures only) when no key is configured. Shape: `vector<ParsedActivity{ts, kind, asset, amount, signature, status}>` where `kind` ∈ `{SWAP, RECEIVE, SEND, OTHER}`. |++### Fee discount eligibility (Phase 2)++| Pattern | Producer | TTL | Min interval | Notes |+|---|---|---|---|---|+| `billing:fncpt_discount:<pubkey>` | `FeeDiscountService` | derived from `wallet:balance:<pubkey>` (no separate fetch) | — | The service subscribes to the user's balance topic internally and republishes eligibility. Shape: `FncptDiscount{eligible, threshold_raw, threshold_decimals, applied_skus}`. Threshold + applied SKUs come from `services/billing/FeeDiscountConfig.h`; defaults to **1,000 $FNCPT → 30 % off** for AI reports, deep backtests, premium screens. |++> **Phase 2 swap path is not a hub topic.** `PumpFunSwapService::build_swap()` is a one-shot, user-initiated HTTP POST to `pumpportal.fun/api/trade-local` that returns an unsigned versioned-tx body. There's no debounce-coalesce or cache-coherence value to pushing it through DataHub; the result is fed directly into `WalletService::sign_and_send()`. See `plans/crypto-center-phase-2.md` D1.++> **Burn deferred to Phase 5.** Phase 2 ships BUY and SELL only. Real burns (with on-chain receipt) move into Phase 5 alongside the buyback-worker design. No `wallet:burn_receipt:*` topic in Phase 2.+## Force refresh`DataHub::request(topic, force=true)` bypasses `min_interval_ms` (so user-driven refresh buttons work inside the interval gate). Per-producer `max_requests_per_sec()` is still honoured — rage-clicking cannot hammer upstream.diff --git a/fincept-qt/plans/crypto-center-future-phases.md b/fincept-qt/plans/crypto-center-future-phases.mdnew file mode 100644index 000000000..00005273b--- /dev/null+++ b/fincept-qt/plans/crypto-center-future-phases.md@@ -0,0 +1,583 @@+# Crypto Center — Future Phases (2–5)++**Status**: design draft+**Owner**: tilakpatel22+**Last updated**: 2026-04-27+**Predecessor**: `plans/crypto-center-wallet-connect.md` (Phase 1, shipped); Phase 1.5 hardening shipped 2026-04-27 — see §1.5 below.+**Scope**: everything that lands inside `screens/crypto_center/CryptoCenterScreen` after the wallet-connect MVP — all subsequent capability that uses the same screen as its home.++---++## 0. North star++The Crypto Center is the **single home for everything $FNCPT** inside Fincept Terminal. By the end of Phase 5 it should answer four questions at a glance, in this order of priority:++1. **What do I hold?** — SOL + $FNCPT balance, USD value, recent activity. (Phase 1 done; Phase 2 deepens.)+2. **What can I do with it?** — buy/swap/burn, fee discounts, tier perks. (Phase 2.)+3. **What am I locked into?** — staked $FNCPT, lock duration remaining, projected yield. (Phase 3.)+4. **What can I bet on?** — internal prediction markets entry point. (Phase 4.)+5. **Why is this token worth something?** — buyback&burn dashboard with revenue → token flow. (Phase 5.)++Every later phase **adds rows / panels / tabs** to the existing screen — never a new top-level route. The screen grows; the navigation stays simple.++---++## 1. Layout strategy across phases++The screen evolves from a 2-panel grid to a **tabbed full-screen workspace** with a persistent identity bar across the top.++```+┌─ FINCEPT / CRYPTO CENTER ─────────── ● CONNECTED ── 7eV4z…aoowY ──┐+│ │+│ HOLDINGS BAR (always visible) │+│ SOL 2.41 ─ $FNCPT 12,304 ─ USD $341.22 ─ 24h Δ +3.4% │+│ │+├──────┬────────┬───────┬─────────┬──────────┬──────────┬───────────┤+│ HOME │ TRADE │ STAKE │ MARKETS │ ACTIVITY │ ROADMAP │ SETTINGS │+├──────┴────────┴───────┴─────────┴──────────┴──────────┴───────────┤+│ │+│ ACTIVE TAB CONTENT (fills remaining space) │+│ │+└───────────────────────────────────────────────────────────────────┘+```++Tabs follow the same `b45309` orange pattern as the main app tab bar (`DESIGN_SYSTEM.md` §6). The HOLDINGS BAR is identity-level — visible on every tab. The Phase 1 layout becomes the **HOME** tab content.++### Phase mapping to tabs++| Tab | Lands in | Notes |+|---|---|---|+| HOME | Phase 1 (shipped) | Identity, balances, $FNCPT roadmap |+| TRADE | Phase 2 | Buy / swap / burn, fee discount |+| STAKE | Phase 3 | veFNCPT lock, real-yield dashboard |+| MARKETS | Phase 4 | Internal prediction markets |+| ACTIVITY | Phase 2 | On-chain transaction history (added with TRADE) |+| ROADMAP | Phase 5 (replaces Phase 1 panel) | Buyback & burn dashboard, treasury |+| SETTINGS | Phase 1+ | Mode toggle, RPC, API keys, hardware wallet preferences |++ACTIVITY ships with Phase 2 because the moment we let users sign transactions, they need to see them.++---++## 1.5 Phase 1.5 — Hardening (shipped 2026-04-27)++**Status**: shipped+**Scope**: Phase 1 stayed as-is in capability; this pass closed five correctness bugs and seven UX gaps that surfaced in production use of the HOME tab. Documented here so future-phase work inherits the patterns instead of re-discovering them.++### 1.5.1 Bugs closed++| ID | Bug | Fix |+|---|---|---|+| B1 | POLL/STREAM toggle could leave both buttons unchecked when the active button was clicked | Wrapped the two `QPushButton`s in an exclusive `QButtonGroup`. Click handlers react only to `toggled(true)` events; clicking the active button is a true no-op. |+| B2 | Stream mode never refreshed FNCPT — only SOL got `accountSubscribe` updates, FNCPT stayed at the seed value | Added a per-stream-session 30s `QTimer` heartbeat that re-runs `seed_stream_state` to refresh FNCPT. Until we surface the FNCPT token-account address and `accountSubscribe` to it directly (a Phase 2 concern), this heartbeat is the source of truth for FNCPT in Stream mode. |+| B3 | STREAM appeared to work on the public RPC but `accountSubscribe` was rate-limited to silence | `WalletBalanceProducer::endpoint_supports_streaming()` checks the resolved endpoint against `api.mainnet-beta.solana.com` and falls back to Poll for that session, publishing a `topic_error` so the screen can show the reason. |+| B4 | REFRESH button in Stream mode only republished cached values | New `WalletService::force_balance_refresh()` → `WalletBalanceProducer::force_refresh(pubkey)` which re-runs `seed_stream_state` in Stream and `refresh_one_poll` in Poll. The screen calls this in addition to a `hub.request(price_topic, force=true)`. |+| B5 | Balance panel header status was a hard-coded `"MAINNET"` label | Replaced with a `FeedStatus` enum (`Idle/Connecting/Live/Stale/Error`) driven by mode-changes, balance publishes, topic errors, and a 5s staleness tick. Object-name swap + `style()->polish` so the colour follows the global stylesheet. |++### 1.5.2 UX gaps closed++| ID | Gap | Fix |+|---|---|---|+| U1 | `apply_theme()` called `setStyleSheet(styleSheet() + …)` 9 times — every call triggered a full QSS reparse on every descendant (P7 violation) | Single composed stylesheet, assigned once. All widget styling keyed by `objectName`. |+| U2 | Topic errors were either swallowed (price) or hijacked the "Updated …" label (balance) | New `cryptoCenterErrorStrip` row inside the balance panel. Visible only while an error is live; auto-clears on the next valid publish. |+| U3 | Stat boxes showed bare em-dashes during the loading window with no microcopy | "waiting for first publish…" is shown in the meta row; REFRESH button is disabled until the first publish lands. |+| U4 | On short windows the static $FNCPT ROADMAP panel pushed balances off-screen | `connected_page_` wrapped in a `QScrollArea` (`widgetResizable=true`, no horizontal scroll). |+| U5 | RPC provider was invisible — users couldn't tell why STREAM was misbehaving | `cryptoCenterRpcChip` next to the feed status pill. Reads `PUBLIC` / `HELIUS` / `CUSTOM` from `SecureStorage` keys (`solana.rpc_url`, `solana.helius_api_key`). Tooltip on `PUBLIC` tells the user to add a Helius key for reliable streaming. |+| U6 | Dead `make_panel()` helper declared and defined but never called | Removed. |+| U7 | No staleness detection — a feed that silently stopped publishing kept showing "Updated 5s ago" forever | 5s `QTimer` re-evaluates `Updated …` text and flips `feed_status_` to `Stale` after 90s of silence. Started in `showEvent`, stopped in `hideEvent` (P3). |++### 1.5.3 New patterns introduced (carry into Phase 2+)++These are now the conventions for any new tab/panel added to Crypto Center:++1. **One stylesheet per screen.** Compose the full CSS string once in `apply_theme()` and assign it once. Widget styling lives in `objectName` selectors; never use inline `setStyleSheet` on individual labels for theming.+2. **`FeedStatus` enum drives the live-status pill.** Each tab in Phase 2+ should reuse the same five-state pattern (`Idle / Connecting / Live / Stale / Error`) and render via an object-name swap so the global stylesheet handles colour. Concrete enum lives in `CryptoCenterScreen.h` for now; promote to a shared `ui::widgets::FeedStatusPill` widget when Phase 2 lands a second consumer.+3. **Force-refresh goes through a service method, not directly through the hub.** `hub.request(topic, force=true)` is fine for read-only re-publish, but any path that actually re-fetches data (REST round-trip, WS re-seed) goes through the owning service so the producer can interpret "force" correctly per its mode. Phase 3's `StakingService` and Phase 4's market services should follow the same `force_*` pattern that `WalletService::force_balance_refresh` established.+4. **Per-session heartbeats are owned by the producer, not the screen.** `WalletBalanceProducer::StreamSession::fncpt_heartbeat` is owned by the producer; lifetime ties to the WS session. Screens never spawn timers for data refresh — that's a P3 + D3 violation.+5. **Endpoint-capability checks before opening streams.** Producers that have both Poll and Stream paths must expose an `endpoint_supports_streaming()` predicate and fall back gracefully with a `publish_error` for visibility. Hard-coded blocks: today the public Solana RPC; Phase 2 may add the public Jupiter rate-limited endpoint.+6. **Staleness is a timer-driven concept on the screen, not a producer responsibility.** Producers publish with a `ts_ms`; the screen decides when "old" becomes "STALE" based on its own threshold (90s for balances, will be tighter for swap quotes).+7. **Error strip pattern.** Every Phase 2+ panel that fetches data must have a hidden-by-default error row that surfaces `topic_error` messages and clears on next valid publish. Use the same `cryptoCenterErrorStrip` styling.+8. **RPC-indicator chip.** Any panel that does Solana RPC work surfaces the resolved provider as a `cryptoCenterRpcChip`-styled label so users understand the latency/reliability profile they're getting.++### 1.5.4 Carry-overs to Phase 2++When Phase 2 lifts the layout to the HOLDINGS BAR + tabbed workspace described in §1:++- The `FeedStatus` pill, RPC indicator, and error strip are **identity-level** — they belong on the HOLDINGS BAR, not duplicated per tab.+- The static `$FNCPT ROADMAP` panel still in the HOME tab is the placeholder slated to be replaced by the Phase 5 buyback & burn dashboard (§5.2). Don't invest further in it.+- The POLL/STREAM toggle moves to the SETTINGS tab (§6) but keeps the same `QButtonGroup`-exclusive widget pattern.+- `WalletService::force_balance_refresh()` becomes one of several `force_*` service methods. Standardise the naming.+- `staleness_timer_` (5s tick) is the prototype for the per-tab refresh timers Phase 2 panels will own. Each tab gets exactly one such timer started in `showEvent` and stopped in `hideEvent`.++### 1.5.5 Files touched in Phase 1.5++- `src/screens/crypto_center/CryptoCenterScreen.{h,cpp}` — full rewrite of `apply_theme`, new `FeedStatus` machinery, scroll wrap, RPC chip, error strip, exclusive button group, REFRESH wiring.+- `src/services/wallet/WalletService.{h,cpp}` — added `force_balance_refresh()`.+- `src/services/wallet/WalletBalanceProducer.{h,cpp}` — added `force_refresh()`, `endpoint_supports_streaming()`, FNCPT heartbeat lifecycle on `StreamSession`.++No new hub topics were introduced; no `DATAHUB_TOPICS.md` update required.++---++## 2. Phase 2 — TRADE tab++> **Detailed plan:** see `plans/crypto-center-phase-2.md` (rev 2). This section is the high-level user-story map; the rev-2 doc is the source of truth for build order, file deltas, and acceptance criteria.++**Goal**: every user can swap SOL ↔ $FNCPT inside the terminal in under 30 seconds, see their last 50 wallet operations, and qualify for a 30 % fee discount when holding ≥ 1,000 $FNCPT.++### 2.1 Capabilities++1. **Buy $FNCPT with SOL** — PumpPortal `trade-local` returns a fully-built unsigned tx; the user signs in their wallet.+2. **Sell $FNCPT for SOL** — symmetric; same endpoint, `action=sell`.+3. **Fee discount** — every paid feature in the terminal (deep backtest, AI report, premium screen) accepts $FNCPT at a 30 % discount. HoldingsBar lights up the chip; TRADE tab shows projected savings given current balance.+4. **Activity feed (ACTIVITY tab)** — last 50 on-chain operations involving the wallet, parsed for human-readable events (sent, received, swapped) via Helius parsed-tx.++**Burn deferred to Phase 5.** Real burns require either ~150 lines of client-side Solana primitives in C++ or a custom Rust on-chain program, both disproportionate for a single user-action. Phase 5's buyback worker burns from the Fincept treasury account using off-chain tooling — that's the right place for the supply mechanism. See `plans/crypto-center-phase-2.md` D6 for the full rationale.++### 2.2 New panels++```+┌─ SWAP ──────────── via PumpPortal · pool=auto ─┐ ┌─ FEE DISCOUNT ─ active ─┐+│ DIRECTION [BUY $FNCPT (SOL → $FNCPT) ▾] │ │ HOLD 1,000 $FNCPT │+│ YOU PAY [ 0.50 ] SOL Bal: 1.20 SOL │ │ ELIGIBLE ✓ 30% off │+│ YOU GET ~12,304 $FNCPT │ │ APPLIED TO │+│ ──────────────────────────────────────────────│ │ AI reports │+│ ROUTE PumpSwap (auto) │ │ Deep backtests │+│ MAX SLIP 1.00% │ │ Premium screens │+│ [SWAP] │ │ │+└────────────────────────────────────────────────┘ └────────────────────────┘+```++There is **no separate quote panel**. PumpPortal has no quote endpoint; estimated output is computed locally from the live `market:price:token:<mint>` family (Stage 2A.5 generalised the legacy `market:price:fncpt` topic into a per-mint family — the FNCPT topic remains as a deprecated alias for one phase) multiplied by the slippage budget.++### 2.3 ACTIVITY tab++```+┌─ ACTIVITY ─ last 50 operations ──────────────── refreshing every 30 s ─┐+│ TIMESTAMP EVENT ASSET AMOUNT STATUS │+│ 2026-04-28 09:14:02 SWAP SOL→FNCPT 0.5 → 12,304 confirmed │+│ 2026-04-27 14:02:11 RECEIVE SOL 0.10 confirmed │+│ ... │+└────────────────────────────────────────────────────────────────────────┘+```++Click a row → opens Solscan in default browser. Helius parsed-tx covers SWAP / RECEIVE / SEND directly; everything else is OTHER with the signature link.++### 2.4 New services++| Service | Path | Producer | Topics |+|---|---|---|---|+| `PumpFunSwapService` | `src/services/wallet/PumpFunSwapService.{h,cpp}` | **no** (one-shot, user-driven) | — `build_swap()` HTTP-POSTs to `pumpportal.fun/api/trade-local` and returns `tx_base64` directly to the caller |+| `WalletActivityProducer` | `src/services/wallet/WalletActivityProducer.{h,cpp}` | yes | `wallet:activity:<pubkey>` (paged JSON of parsed transfers) |+| `FeeDiscountService` | `src/services/billing/FeeDiscountService.{h,cpp}` | yes | `billing:fncpt_discount:<pubkey>` (eligibility, applied SKUs) |++The one-shot pattern for `PumpFunSwapService` mirrors `WalletService::sign_and_send` (Stage 2.0) — user-initiated actions that don't benefit from caching/coalescing don't need to be Producers. See the Phase 2 plan §3 for the full reasoning.++### 2.5 New hub topics (Phase 2)++| Pattern | Producer | TTL | Min | Notes |+|---|---|---|---|---|+| `wallet:activity:<pubkey>` | `WalletActivityProducer` | 30 s (poll) | 10 s | Parsed last-50 wallet operations via Helius. Falls back to raw signatures if no Helius key. |+| `billing:fncpt_discount:<pubkey>` | `FeeDiscountService` | derived from `wallet:balance:<pubkey>` | — | Republishes whenever balance changes. |+| `market:price:token:<mint>` | `TokenPriceProducer` | 60 s | 30 s | Generalised per-mint USD price, batched into one Jupiter Lite call per refresh. Supersedes the Phase 1 `market:price:fncpt` topic, which remains as a deprecated alias for one phase. See `plans/crypto-center-phase-2.md` §2A.5 for the full upgrade rationale. |++The earlier rev specced `wallet:quote:*` and `wallet:burn_receipt:*` — both retired. PumpPortal has no quote endpoint (output is estimated locally from spot price), and burn is deferred. The `wallet:balance:<pubkey>` topic is still owned by `WalletBalanceProducer`, but the payload shape was upgraded in Stage 2A.5 to carry `QVector<TokenHolding>` instead of FNCPT-only fields — see `docs/DATAHUB_TOPICS.md` for the new shape.++### 2.6 Solana program work++**None this phase.** The earlier rev specced a custom `fincept_burn` Anchor program for on-chain burn receipts. Burn is deferred to Phase 5; that's the correct place for any custodial burn primitive too. Phase 2 ships zero on-chain code.++### 2.7 Security++Phase 1 was read-only. Phase 2 introduces transaction signing, so the threat model expands:++- Every swap re-prompts the wallet UI. We **never** pre-sign or cache.+- The terminal shows the **decoded transaction summary** before sign — never trust the wallet to do this alone, since some users approve blindly.+- Slippage cap default 1 %; user adjustable up to 5 %. SettingsTab clamps the slider.+- PumpPortal MITM mitigation: simulate the unsigned tx against the user's RPC before forwarding, refuse if any non-FNCPT/non-SOL/non-wSOL token balance changes. Optional TLS leaf-cert pinning is a Phase 2.5 polish.+- Replay: refuse to sign if `currentBlockHeight > tx.lastValidBlockHeight - 50`.+- The shared `WalletActionConfirmDialog` enforces a 1.5 s arm-time on the SWAP button.++A separate `crypto-center-trade-security.md` review doc lands with the Phase 2 PR.++### 2.8 Acceptance criteria++- [ ] User can BUY 0.001 SOL of $FNCPT on mainnet and see balance update via DataHub within 5 s of `confirmed`.+- [ ] User can SELL 50 % of resulting $FNCPT and receive SOL back within 30 s.+- [ ] Holding 1,000+ $FNCPT shows "30 % off" badge on HoldingsBar and FeeDiscountPanel.+- [ ] ACTIVITY tab populates with last 50 parsed events.+- [ ] All five Phase 1 P-rules and four Phase 1 D-rules hold (no PythonRunner spawn, hub-first, etc.).+- [ ] No Rust source anywhere in the tree.++---++## 3. Phase 3 — STAKE tab++**Goal**: users can lock $FNCPT for 1–4 years and earn a real-yield share (USDC) of terminal revenue, plus governance weight. Curve `veCRV` model, but sized down for our scale.++### 3.1 Capabilities++1. **veFNCPT lock** — choose amount + duration (3 mo / 6 mo / 1 yr / 2 yr / 4 yr).+2. **Boost preview** — show projected weekly yield in USDC for the chosen lock.+3. **Existing positions** — table of locks, time remaining, current weight.+4. **Extend / increase** — add tokens or extend duration of an existing lock.+5. **Withdraw on expiry** — auto-prompt when a lock unlocks.+6. **Governance preview** — open proposals (read-only this phase; voting in Phase 4).+7. **Tier badge** — bronze / silver / gold based on `veFNCPT` weight, surfaced on HOME tab and across the terminal (gates premium features).++### 3.2 New panels++```+┌─ STAKE / LOCK ──────────────────────────────────────────────────────────────┐+│ AMOUNT [ 1,000 ] $FNCPT AVAILABLE 12,304 │+│ DURATION ◯ 3 MO ◯ 6 MO ● 1 YR ◯ 2 YR ◯ 4 YR │+│ WEIGHT 1,000 veFNCPT × 0.25 (1 yr) = 250 veFNCPT │+│ EST. YIELD $42 / week (USDC) — 2.18% weekly real yield at $341 stake │+│ TIER Silver → Gold (after lock) │+│ [PREVIEW LOCK] [LOCK] │+└──────────────────────────────────────────────────────────────────────────────┘++┌─ ACTIVE LOCKS ─ 3 positions ─ Σ 4,500 veFNCPT ─────────────────────────────┐+│ LOCKED DURATION UNLOCKS WEIGHT YIELD (LIFETIME) │+│ 2,000 4 yr 2030-04-27 2,000 $1,240 USDC │+│ 1,000 1 yr 2027-04-01 250 $42 USDC │+│ 500 6 mo 2026-10-27 62.5 $14 USDC │+│ ────────────────────────────────────────────────────────────────────── │+│ TOTAL — — 2,312.5 $1,296 USDC │+└─────────────────────────────────────────────────────────────────────────────┘++┌─ TIER ──────────────────────────────────── current GOLD ────────────────────┐+│ BRONZE 100+ veFNCPT basic API quota [achieved] │+│ SILVER 1k+ veFNCPT premium screens [achieved] │+│ GOLD 10k+ veFNCPT all agents + arena [achieved] │+└─────────────────────────────────────────────────────────────────────────────┘+```++### 3.3 New services++| Service | Path | Topics |+|---|---|---|+| `StakingService` | `src/services/wallet/StakingService.{h,cpp}` | `wallet:locks:<pubkey>`, `wallet:vefncpt:<pubkey>` |+| `RealYieldService` | `src/services/wallet/RealYieldService.{h,cpp}` | `wallet:yield:<pubkey>`, `treasury:revenue` (terminal-wide stat) |+| `TierService` | `src/services/billing/TierService.{h,cpp}` | `billing:tier:<pubkey>` |++### 3.4 Hub topics (Phase 3)++| Pattern | Producer | TTL | Min | Notes |+|---|---|---|---|---|+| `wallet:locks:<pubkey>` | `StakingService` | 60 s (poll) / push | 30 s | Vector of `LockPosition{amount_raw, decimals, unlock_ts, weight}`. |+| `wallet:vefncpt:<pubkey>` | `StakingService` | 60 s | 30 s | Aggregated weight + projected next-period yield. |+| `wallet:yield:<pubkey>` | `RealYieldService` | 5 min | 60 s | Lifetime + last-period USDC yield earned. |+| `treasury:revenue` | `RealYieldService` | 1 h | 5 min | Terminal-wide aggregate (weekly bucket) — used in Phase 5 dashboard. |+| `billing:tier:<pubkey>` | `TierService` | 60 s | 30 s | `{tier, weight, next_threshold}`. Drives badges across the terminal. |++### 3.5 Solana program work++The lock program is the heart of Phase 3. Either:++- **(a) Reuse Curve-style ve-token contracts** — community ports exist for Solana (Realms, Squads), but each has different governance assumptions.+- **(b) Build minimal `fincept_lock` Anchor program**:+ - `lock(amount, duration_secs)` → mints non-transferable position NFT, escrows tokens.+ - `extend(position, new_duration)`.+ - `withdraw(position)` — only after unlock.+ - `emit_distribution(epoch, total_usdc)` — admin instruction (Fincept Corp signer) to settle the per-epoch real-yield split.++Decision: **(b)**. Curve-style contracts come with governance baggage (proposal queues, vote escrow boost calculations) we won't use until Phase 4. A small purpose-built program is auditable in a week.++Repo: `solana/programs/fincept_lock/`.++### 3.6 Tier integration with the rest of the terminal++The `TierService` publishes `billing:tier:<pubkey>` and emits a Qt signal `tier_changed`. Existing screens consume:++- **AI Quant Lab**: locked behind Silver+. The screen factory checks tier on `showEvent`; if insufficient, renders a "UPGRADE" pill that deep-links back to the STAKE tab.+- **Alpha Arena**: locked behind Gold.+- **All paid screens**: hidden in nav for Free; revealed for Silver+.+- **API quota**: handled centrally in `services/billing/ApiQuotaService` (already exists for plan-based gating); takes a tier override.++This is the **first cross-screen feature** $FNCPT enables. The HOME tab gets a "TIER STATUS" panel showing what's unlocked.++### 3.7 Acceptance criteria++- [ ] User can lock 1,000 $FNCPT for 1 year and see veFNCPT weight = 250.+- [ ] After a simulated revenue distribution event, the user receives USDC pro-rata to weight.+- [ ] Tier badge appears on HOME and gates AI Quant Lab.+- [ ] User cannot withdraw a non-expired lock (program rejects, UI explains).+- [ ] Locks survive terminal restart (state lives on-chain, not in SecureStorage).++---++## 4. Phase 4 — MARKETS tab (internal prediction markets)++**Goal**: $FNCPT becomes the only collateral on a small, curated prediction-market venue inside the terminal. Synergy with the existing `PredictionExchangeAdapter` (Polymarket, Kalshi).++### 4.1 Capabilities++1. **Market list** — curated prediction markets that settle in $FNCPT only: Fed rate moves, CPI prints, S&P close, weather (maybe), crypto milestones.+2. **YES / NO order entry** — limit + market orders. Off-chain order book, on-chain settlement.+3. **Open positions** — current YES/NO holdings, mark-to-market in $FNCPT.+4. **Settled history** — past markets, P&L, redeem-on-resolve flow.+5. **Create market** (Gold tier only) — propose a market with oracle source and end date; community votes via veFNCPT to list.+6. **Earn from order flow** — veFNCPT lockers receive a share of trading fees (real yield on top of Phase 3).++### 4.2 New panels++```+┌─ MARKETS ─ live ─ 12 open ─ Σ volume 12.3M $FNCPT ──────────────────────────┐+│ MARKET YES NO 24h VOL EXPIRES │+│ Fed cuts in May 2026 0.62 0.38 1.2M 2026-05-07 │+│ NYC max 80F+ on May 1 0.71 0.29 83k 2026-05-01 │+│ $FNCPT > $0.0001 by month end 0.45 0.55 421k 2026-05-31 │+│ ... │+└─────────────────────────────────────────────────────────────────────────────┘++┌─ ORDER ENTRY ──────────────────────┐ ┌─ YOUR POSITIONS ──────────────────┐+│ MARKET Fed cuts in May 2026 │ │ MARKET YES P&L │+│ SIDE ● YES ◯ NO │ │ NYC max 80F+ 500 +124 │+│ TYPE ● LIMIT ◯ MARKET │ │ Fed cuts 1,000 -42 │+│ PRICE [ 0.62 ] $FNCPT/share │ │ ... │+│ AMOUNT [ 1000 ] shares │ └────────────────────────────────────┘+│ COST 620 $FNCPT (escrowed) │+│ [PLACE] │+└────────────────────────────────────┘+```++### 4.3 Architecture++The existing `PredictionExchangeAdapter` already abstracts Polymarket and Kalshi. Add a third adapter:++```+PredictionExchangeRegistry+ ├─ PolymarketAdapter (existing)+ ├─ KalshiAdapter (existing)+ └─ FinceptInternalAdapter (NEW — Phase 4)+```++`FinceptInternalAdapter` speaks to a **terminal-side Fincept matching engine** (HTTP + WebSocket on `markets.fincept.in`), but settlement is on-chain via a `fincept_market` Anchor program.++### 4.4 New services++| Service | Path | Topics |+|---|---|---|+| `FinceptInternalAdapter` | `src/services/prediction/internal/FinceptInternalAdapter.{h,cpp}` | `prediction:fincept:*` (markets, books, trades) |+| `MarketCreationService` | `src/services/prediction/internal/MarketCreationService.{h,cpp}` | `prediction:fincept:proposals` |+| `OracleResolverService` | `src/services/prediction/internal/OracleResolverService.{h,cpp}` | `prediction:fincept:resolutions:<id>` |++Hub topics follow the unified `prediction:*` pattern already documented in `DATAHUB_TOPICS.md` — drop in `prediction:fincept:*` as a sibling family.++### 4.5 Solana program work++`fincept_market` program:+- `create_market(end_ts, resolver_pubkey, fee_bps)`+- `deposit_collateral(market, side, amount)` (called per matched fill)+- `resolve(market, outcome)` — only callable by `resolver_pubkey` (the oracle, multi-sig'd to a 3-of-5 set chosen by veFNCPT vote).+- `redeem(market, position)` — winner withdraws; fees split to staking pool.++Repo: `solana/programs/fincept_market/`.++### 4.6 Oracle layer++Pre-built sources:+- **Pyth Network** — Fed rates, S&P close, BTC price.+- **Switchboard** — custom OOB queries (HTTP fetch from NOAA, IMF).+- **Manual review board** — multi-sig of 3 trusted Fincept staff for ambiguous markets, slashable via veFNCPT vote if they misresolve.++Oracle source is part of the market metadata; UI shows the source pill.++### 4.7 Compliance / scope++Real-money prediction markets are regulated as derivatives in US/EU. We mitigate by:+- $FNCPT is a token, not USD — marketed as a play-money internal mechanic, not a regulated derivative.+- Geo-block US/UK during sign-up if legal counsel insists.+- All markets have a legal disclaimer line in the terminal.++This is a **policy decision** outside the scope of this doc — the engineering plan ships the same either way.++### 4.8 Acceptance criteria++- [ ] User can place a YES order on a market and see it in the order book within 1 s (WS feed).+- [ ] On market resolution, redeem flow auto-prompts in the MARKETS tab.+- [ ] Trading fees flow into the Phase 3 staking pool — `wallet:yield:<pubkey>` reflects new yield within one epoch.+- [ ] Gold-tier user can propose a market; community vote (veFNCPT) lists it.+- [ ] Market data uses `prediction:fincept:*` topics, never bypasses the hub.++---++## 5. Phase 5 — Buyback & Burn dashboard (ROADMAP tab)++**Goal**: make the value loop visible. Every user can see exactly how much terminal revenue has been spent buying $FNCPT off the market and burning it. This is the **demand engine** that justifies the token long-term.++### 5.1 Capabilities++1. **Live buyback ticker** — current epoch's $FNCPT bought from Jupiter using terminal revenue.+2. **Cumulative burn counter** — total $FNCPT burned all-time.+3. **Supply chart** — circulating + total + burned over time.+4. **Revenue breakdown** — terminal subscriptions, fee discount, prediction market fees, what fraction goes to buyback.+5. **Treasury panel** — current treasury size, USDC reserves, runway.++### 5.2 ROADMAP tab replaces Phase 1's static panel++```+┌─ BUYBACK & BURN ─ epoch 47 ─ 2026-04-21 → 2026-04-27 ───────────────────────┐+│ │+│ THIS EPOCH │+│ ───────────── │+│ Revenue $42,310 USD (subs $32k · pred-mkt fees $8k · misc $2k) │+│ Buyback $21,155 (50% of revenue) │+│ $FNCPT bought 82.4M $FNCPT (avg 0.000257 USD) │+│ $FNCPT burned 82.4M $FNCPT ● burn tx 5kj3w… │+│ │+│ ALL-TIME │+│ ───────────── │+│ Burned 1.42 B $FNCPT │+│ Supply remaining 8.58 B $FNCPT │+│ Spent on buyback $384,201 USD │+│ │+└──────────────────────────────────────────────────────────────────────────────┘++┌─ SUPPLY CHART ──────────────────────────────────────────────────────────────┐+│ [ time-series chart: total / circulating / burned, last 12 months ] │+└─────────────────────────────────────────────────────────────────────────────┘++┌─ TREASURY ──────────────────────────────────────────────────────────────────┐+│ USDC reserves $1.84M │+│ SOL reserves 234 SOL ($16k) │+│ Runway @ current 19 months │+│ Multi-sig 3-of-5 (squads.so/fincept-treasury) │+└─────────────────────────────────────────────────────────────────────────────┘+```++### 5.3 New services++| Service | Path | Topics |+|---|---|---|+| `BuybackBurnService` | `src/services/wallet/BuybackBurnService.{h,cpp}` | `treasury:buyback_epoch`, `treasury:burn_total`, `treasury:supply_history` |+| `TreasuryService` | `src/services/wallet/TreasuryService.{h,cpp}` | `treasury:reserves`, `treasury:runway` |++These are **terminal-wide** topics (no `<pubkey>` segment) — same data shown to every user.++### 5.4 Automation (off-chain)++The buyback&burn flow runs on a Fincept-operated worker:++1. End of epoch, worker tallies revenue from Stripe + on-chain prediction-market fees.+2. Computes buyback budget (initial split: 50 % buyback, 25 % staker yield, 25 % treasury).+3. Splits into N hourly chunks, executes through Jupiter to avoid frontrunning a single big buy.+4. Burns the bought $FNCPT — direct SPL Token `burn_checked` from a treasury account is sufficient. The signature serves as the receipt; an on-chain event log is *not* required because the worker also publishes the per-epoch summary the dashboard reads (step 5).+5. Publishes per-epoch summary to a Fincept HTTP endpoint that `BuybackBurnService` polls.++Worker code lives in `services/buyback-worker/` (Python or TypeScript — separate repo decision).++### 5.5 Cross-phase reuse++This phase introduces no on-chain program. Direct SPL `burn_checked` from a treasury wallet is enough for a Fincept-operated worker — the receipt is the transaction signature plus the off-chain epoch summary. (User-initiated burns from the TRADE tab were considered for Phase 2 but deferred precisely so this phase, where centralised burn coordination actually pays for itself, owns the burn primitive cleanly.)++### 5.6 Acceptance criteria++- [ ] ROADMAP tab shows live epoch buyback amount, refreshing every 60 s.+- [ ] Supply chart renders last 12 months with three lines.+- [ ] Each burn transaction is clickable → opens Solscan.+- [ ] Treasury runway calculation matches finance team's reconciliation.++---++## 6. SETTINGS tab (lightweight, ships incrementally)++A small SETTINGS tab lands with Phase 2 and grows:++- Phase 2: balance mode (poll/stream), Helius API key entry, default slippage.+- Phase 3: tier display preferences, governance email opt-in.+- Phase 4: market resolution preferences (auto-redeem on win), oracle source filter.+- Phase 5: data refresh cadence per panel.++Keep it boring — `core/keys/KeyConfigManager` plus `SecureStorage` is enough.++---++## 7. Cross-phase concerns++### 7.1 Performance — every panel is a hub subscriber++- Each tab subscribes only when **visible** (already wired via `showEvent` / `hideEvent`).+- Heavy-paint tabs (charts in Phase 5) **must** cache pixmaps per `DESIGN_SYSTEM` + P9.+- The HOLDINGS BAR persists on every tab — single subscription set, owned by the screen, not duplicated per tab.++### 7.2 Storage growth++By Phase 5 the Crypto Center subscribes to roughly 18 hub topics per session. The hub handles topic-state cleanup via `drop_on_idle = true` for per-pubkey topics; terminal-wide topics (`treasury:*`) stay resident.++### 7.3 Wallet permission UX++Every action that prompts the wallet must show **what** is being signed in the terminal **before** the wallet pops:+- Swap: "You will sign a swap of 0.5 SOL for ~12,304 $FNCPT through Jupiter."+- Burn: "You will sign a burn of 100 $FNCPT. This is irreversible."+- Lock: "You will sign a lock of 1,000 $FNCPT for 1 year. You cannot withdraw before <date>."++Pattern: `WalletActionConfirmDialog` (Phase 2) — shared across all phases.++### 7.4 Recovering from drift++If the user disconnects + reconnects with a different wallet, the screen must:+1. Drop subscriptions for the old pubkey.+2. Reseed from on-chain state for the new pubkey.+3. Never show stale balances/locks/positions from the previous session.++This is centralised in `WalletService::wallet_disconnected` → `wallet_connected` signal pair, which every Phase 2+ panel listens to.++### 7.5 Test strategy++Each phase ships with:+- Unit tests for new services (mock RPC and Jupiter responses).+- Integration test against **devnet** (deploy our programs there too).+- Manual smoke test on mainnet with a tiny amount of $FNCPT.+- Security walkthrough doc (like Phase 1's), specifically focused on the new sign-flows.++---++## 8. Order of operations++A reasonable sequencing (each phase ~3–6 weeks of focused work):++| Order | Phase | Why |+|---|---|---|+| 1 | Phase 2 (TRADE + ACTIVITY) | Unlocks revenue (fee discount), ships fastest, lets users actually use $FNCPT. |+| 2 | Phase 5 (Buyback & Burn dashboard) | Marketing surface lights up the moment Phase 2 ships — show the value loop. |+| 3 | Phase 3 (STAKE) | Locks supply once enough users hold the token. |+| 4 | Phase 4 (MARKETS) | Highest engineering risk; benefits most from a captive holder base. |++Phase 5 ships **before** Phase 3 because the dashboard works as soon as buyback automation runs — even if no one is staking yet. It builds confidence. Phase 3 is the hardest UX (yield projection, lock math, governance previews) and benefits from a stable Phase 2.++---++## 9. What we will NOT do across these phases++- **Custodial features.** No "Fincept holds your tokens for you." Ever.+- **Multi-chain.** $FNCPT stays on Solana. Cross-chain bridges are a separate product.+- **Fiat onramp inside the terminal.** Use Phantom/Solflare's built-in onramps; we link, don't host.+- **Auto-trading bots.** `agent:*` topics already exist for that — we don't double-build.+- **NFT marketplace.** Out of scope; partner if needed.+- **Hardware wallet direct USB.** Phantom/Solflare host Ledger fine; direct integration is months of work for marginal UX gain.++These exclusions matter because each one has been pitched in past discussions and each one can swallow a quarter of engineering time without moving the needle.++---++## 10. Success metric++By end of Phase 5, with reasonable adoption (1k DAU on the terminal):++- $FNCPT velocity: > $50k weekly volume on Jupiter pairs.+- Locked supply: > 30 % via veFNCPT.+- Burn rate: ≥ 1 % of supply burned per quarter.+- Real-yield APR: ≥ 6 % USDC for 1-year lockers.+- Prediction market open interest: $250k+ in $FNCPT.++If any of these is < 30 % of target after the corresponding phase, **stop** and fix the loop before adding more features. More mechanics on a token nobody uses is the most common DeFi failure mode, and we are not exempt.++---++## 11. Document maintenance++- Update this doc at each phase kickoff with refined estimates and any scope deltas.+- When a phase ships, **archive** its section into `plans/crypto-center-phase<N>-shipped.md` with the actual implementation diffs from the plan, so future phases inherit verified patterns rather than design speculation.+- Topic catalogue (`docs/DATAHUB_TOPICS.md`) is the source of truth for all hub topics; this doc is the user-story-level map. Discrepancies → fix `DATAHUB_TOPICS.md` first.diff --git a/fincept-qt/plans/crypto-center-phase-2.md b/fincept-qt/plans/crypto-center-phase-2.mdnew file mode 100644index 000000000..df1296722--- /dev/null+++ b/fincept-qt/plans/crypto-center-phase-2.md@@ -0,0 +1,702 @@+# Crypto Center — Phase 2 (TRADE + ACTIVITY + Tabbed Layout)++**Status**: rev 2 — pivoted from Jupiter+Anchor to PumpPortal-only after probing the live APIs and confirming pump.fun/PumpSwap routing covers $FNCPT cleanly without any client-side Solana primitives or custom on-chain program.+**Owner**: tilakpatel22+**Last updated**: 2026-04-28+**Predecessors**: `crypto-center-future-phases.md` §2 (high-level), `crypto-center-wallet-connect.md` (Phase 1, shipped), Phase 1.5 hardening (shipped)+**Companion**: `crypto-center-trade-security.md` — security walkthrough, lands with the Phase 2 PR.++---++## 0. North star++Phase 2 turns Crypto Center from a **read-only identity surface** into a **transactional surface**. Every new capability shares one constraint:++> **The user signs every transaction in their wallet, sees a decoded summary in the terminal *before* the wallet pops, and the terminal never holds a private key longer than it takes to forward a base64 transaction over a loopback HTTP bridge.**++Phase 2 ships three user-visible capabilities:++1. **TRADE tab — Buy / Sell.** Buy or sell $FNCPT (vs SOL) via PumpPortal's `trade-local` endpoint. PumpPortal's `pool: "auto"` routing automatically picks the active venue (pump.fun bonding curve before graduation, PumpSwap AMM after — $FNCPT is graduated). Confirm dialog → wallet signs → terminal polls confirmation → balance refreshes.+2. **ACTIVITY tab.** Last 50 parsed wallet operations (sends, receives, swaps), refreshing every 30 s. Helius parsed-tx when a key is configured, signature-only fallback otherwise.+3. **Fee discount eligibility.** Users holding ≥ 1,000 $FNCPT see a "30 % off" chip on HoldingsBar; future paid screens (Phase 3+) read `billing:fncpt_discount:<pubkey>` and render an UPGRADE-to-discount badge.++**Deferred to a later phase (deliberately):**+- **Burn.** PumpPortal has no burn endpoint. A real `burn_checked` requires either client-side Solana primitives in C++ (~150 lines: base58, ATA derivation, instruction encoding) or a custom Anchor program (Rust). Both add complexity disproportionate to the use-case at this stage. Folded into Phase 5's buyback-worker design instead, where centralised burns from terminal revenue do the heavy lifting on the supply side.++**Already shipped before this rev (do not re-do):**+- HoldingsBar (Stage 2.1), HomeTab, SettingsTab, ComingSoonTab, CryptoCenterScreen tabbed shell, TradeTab + SwapPanel scaffolding, WalletActionConfirmDialog, WalletTxBridge, SignTransactionDialog, SolanaRpcClient extensions (`getLatestBlockhash`, `sendTransaction`, `getSignatureStatuses`, `getSignaturesForAddress`), `swap.html` + vendored `web3.js` slot, hub topics in `DATAHUB_TOPICS.md`.++The pivot reuses all of that. The only thing that **changes** is the swap-tx build path — `JupiterSwapService` is replaced by `PumpFunSwapService` which calls PumpPortal. The swap-html page, the wallet-bridge flow, the confirm dialog, the status-poll machinery — all unchanged.++---++## 1. Decisions locked++| # | Decision | Choice | Rationale |+|---|---|---|---|+| D1 | Swap-tx builder | **PumpPortal `trade-local` API** (`POST https://pumpportal.fun/api/trade-local`). Returns a fully-built unsigned versioned transaction in raw binary (verified live: 1009-byte sell tx, 1098-byte buy tx for $FNCPT). | Jupiter's `/swap` works for $FNCPT but routes through PumpSwap anyway. Going direct removes a layer; PumpPortal is the canonical bridge for pump.fun-launched tokens. No API key required. |+| D2 | Pool routing | **`pool: "auto"`** on every request. | $FNCPT is post-graduation (bonding curve complete), so PumpPortal will pick PumpSwap. If Fincept ever launches a new token pre-graduation, the same code routes it correctly. |+| D3 | Quote / preview | **No separate quote topic.** Estimate output from current spot (`market:price:fncpt`) + slippage budget; render in SwapPanel. | PumpPortal has no quote endpoint, only "build me a tx now". The earlier Jupiter design carried `wallet:quote:*` precisely because Jupiter exposed `/quote` separately. Removing it simplifies the panel and lines up with the tx-on-click flow. |+| D4 | Slippage default / cap | Default **1 %**, user-adjustable up to **5 %** in Settings. The slippage bound is sent to PumpPortal as the `slippage` integer (percent). | Matches earlier rev; Phase 1.5 SettingsTab already persists `wallet.default_slippage_bps`. |+| D5 | Priority fee | Default **0.00005 SOL** (~$0.01 at SOL=$170). Hidden behind an "advanced" disclosure in Settings; not exposed per-trade in Phase 2. | Matches PumpPortal's docs example; covers 95th-percentile network congestion. Per-trade override is a Phase 3 polish. |+| D6 | Burn | **Deferred to Phase 5**, when buyback automation owns burns centrally. Phase 2's TRADE tab shows BUY and SELL only; the BurnPanel placeholder is removed (was Stage 2.3). | Avoids ~150 lines of Solana primitives in C++ or a separate Rust program for a single user-action. Phase 5's buyback-worker burns from a Fincept treasury account using off-chain tooling. |+| D7 | Activity feed source | **Helius parsed-tx REST** (`https://api.helius.xyz/v0/addresses/<pubkey>/transactions`) when `solana.helius_api_key` is set in SecureStorage. Fallback: `SolanaRpcClient::get_signatures_for_address` for raw signatures. | Same as the earlier rev — unchanged. |+| D8 | Fee-discount source | Local computation against the latest `wallet:balance:<pubkey>` publish. Threshold + applied SKUs in `services/billing/FeeDiscountConfig.h`. | Same as earlier rev — unchanged. |+| D9 | Fee-discount threshold | **1,000 $FNCPT** for **30 %** off AI reports / deep backtests / premium screens. | Same as earlier rev. Phase 3's TierService will override based on staked weight. |+| D10 | Tabbed shell | Already shipped Stage 2.1: `QTabWidget` with `HoldingsBar` above. Phase 2 only updates content of TRADE and ACTIVITY tabs. | No layout work in this rev. |+| D11 | When wallet is disconnected | All Phase 2 tabs render their empty state. The CONNECT WALLET CTA from Phase 1 remains the only entry point. | Same as earlier rev. |+| D12 | Confirm dialog scope | The shared `WalletActionConfirmDialog` (Stage 2.0) handles BUY and SELL. Reused as-is for Phase 3+ lock / stake. | Same as earlier rev. |+| D13 | Anti-muscle-memory delay | **1500 ms** for both BUY and SELL. (Earlier rev had 2500 ms for burn; with burn deferred, 1500 ms applies uniformly.) | Conservative default; perceptible enough to break click-through, not so long users hate it. |+| D14 | Where the unsigned tx is built | PumpPortal returns the raw bytes; the terminal **base64-encodes** them and forwards to the existing `WalletTxBridge → swap.html → wallet.signAndSendTransaction`. | Reuses the entire signing path from Stage 2.2; zero changes to `swap.html` or `WalletTxBridge`. |+| D15 | Activity row click target | Solscan in default browser. Cluster is mainnet-only (no devnet $FNCPT supply). | Same as earlier rev. |++---++## 2. Threat model — only the entries that still apply++The earlier rev listed five new attacks beyond Phase 1. With burn deferred and Jupiter dropped, three remain unchanged and two retire.++| Attack | Still applies? | Mitigation |+|---|---|---|+| **PumpPortal MITM** — attacker intercepts the HTTPS call and feeds a malicious tx body that drains the wallet | **Yes** (replaces "quote-API spoofing" entry from the Jupiter rev) | (a) Confirm dialog shows decoded summary before sign — the tx itself is opaque to the user, but they verify _amount_, _direction_, and _slippage_ against what they typed; (b) `simulateTransaction` on the user's RPC and refuse to sign if any non-FNCPT/non-SOL/non-wSOL token balance changes. (c) Optionally pin PumpPortal's TLS leaf cert SHA-256 in SecureStorage and verify on each call — Phase 2.5 polish. |+| **Replay of an old swap transaction** | **Yes** | The unsigned tx from PumpPortal has a recent blockhash baked in. Refuse to sign if `currentBlockHeight > tx.lastValidBlockHeight - 50` (about 25 s buffer). Read the embedded blockhash via `web3.js` after deserialise — already part of `swap.html`'s deserialise step. |+| **Anti-muscle-memory** | **Yes** | `WalletActionConfirmDialog` already enforces a 1.5 s arm delay with a visible countdown. Inherited unchanged from Stage 2.0. |+| **Loopback-bridge stale token** | **Yes** | `WalletTxBridge` already mints a single-use UUID per request, expires after 60 s. Inherited unchanged from Stage 2.0. |+| ~~Burn-program ID swap~~ | **No** — burn deferred to Phase 5 | n/a |+| ~~Anchor program tampering via SecureStorage~~ | **No** — no custom program | n/a |++A separate `crypto-center-trade-security.md` lands with the Phase 2 PR; this section is the spec it walks against.++---++## 3. Architecture (delta from what's already shipped)++Phase 2 rev 2 replaces exactly one component (`JupiterSwapService`) and adds two new ones (`WalletActivityProducer`, `FeeDiscountService`). Everything else is reuse.++```+ ┌──────────────────────────────────────────────────────────────┐+ │ CryptoCenterScreen (already shipped 2.1) │+ │ ┌──────────────────────────────────────────────────────────┐ │+ │ │ HoldingsBar (always visible, identity-level) │ │+ │ │ SOL · $FNCPT · USD · 24h Δ · ● LIVE · HELIUS · 30% OFF │ │+ │ └──────────────────────────────────────────────────────────┘ │+ │ ┌──────────────────────────────────────────────────────────┐ │+ │ │ QTabWidget │ │+ │ │ ┌────┬─────┬───────┬─────┬───────┬───────┬─────────┐ │ │+ │ │ │HOME│TRADE│ACTIV. │SET. │STAKE† │MKTS† │ROADMAP† │ │ │+ │ │ └────┴─────┴───────┴─────┴───────┴───────┴─────────┘ │ │+ │ │ TRADE: SwapPanel only (BurnPanel removed; deferred) │ │+ │ │ ACTIV.: ActivityTab — Helius parsed-tx │ │+ │ └──────────────────────────────────────────────────────────┘ │+ └──────────────────────────────────────────────────────────────┘+ │ subscribe / unsubscribe+ ▼+ ┌─────────────────────────────────────────────────────────────────────────┐+ │ DataHub │+ │ wallet:balance:<pk> (Phase 1, unchanged) │+ │ market:price:fncpt (Phase 1, unchanged) │+ │ wallet:activity:<pk> (NEW, poll 30 s) │+ │ billing:fncpt_discount:<pk> (NEW, derived from balance) │+ │ │+ │ (wallet:quote:* — REMOVED. PumpPortal has no quote endpoint; │+ │ SwapPanel computes the projected output locally from spot.) │+ │ (wallet:burn_receipt:* — REMOVED. Burn deferred to Phase 5.) │+ └─────────────────────────────────────────────────────────────────────────┘+ ▲ publishes+ │+ ┌──────────────────────┴──────────────────────────────────────────────────┐+ │ │+ │ PumpFunSwapService WalletActivityProducer │+ │ - build_swap(action, amt, - 30 s poll Helius │+ │ pubkey, slippage_pct) parsed-tx endpoint │+ │ → tx_base64 - parses tx kinds │+ │ (single HTTP POST to (SWAP, RECEIVE, SEND) │+ │ pumpportal.fun) │+ │ │+ │ FeeDiscountService │+ │ - subscribes to wallet:balance:<pk> │+ │ - publishes billing:fncpt_discount:<pk> │+ │ │+ └──────────────────────┬──────────────────────────────────────────────────┘+ │ uses (already shipped)+ ▼+ ┌─────────────────────────────────────────────────────────────────────────┐+ │ WalletService::sign_and_send (Stage 2.0) │+ │ WalletTxBridge (Stage 2.0) │+ │ resources/wallet/swap.html (Stage 2.2) │+ │ SolanaRpcClient::getSignatureStatuses (Stage 2.0) │+ │ WalletActionConfirmDialog (Stage 2.0) │+ │ HttpClient (Phase 1) │+ └─────────────────────────────────────────────────────────────────────────┘+```++The signing path (`WalletService::sign_and_send` → `WalletTxBridge` → `swap.html` → wallet ext → status poll) is reused without modification. The replacement scope is **the C++ service** that produces the `tx_base64` to feed into `sign_and_send`.++---++## 4. Files to add / change / remove++### New files++```+src/services/wallet/+ PumpFunSwapService.{h,cpp} // POST pumpportal.fun/api/trade-local+ // → returns base64 versioned tx+ WalletActivityProducer.{h,cpp} // Producer for wallet:activity:*+src/services/billing/+ FeeDiscountService.{h,cpp} // Producer for billing:fncpt_discount:*+ FeeDiscountConfig.h // thresholds (decoupled from service)+src/screens/crypto_center/panels/+ FeeDiscountPanel.{h,cpp} // owned by TradeTab — replaces placeholder+src/screens/crypto_center/tabs/+ ActivityTab.{h,cpp} // owned by CryptoCenterScreen — replaces ComingSoonTab in slot 3+docs/+ CRYPTO_CENTER_PHASE_2.md // user-facing "how to swap"+plans/+ crypto-center-trade-security.md // walkthrough doc+```++### Existing files modified++```+src/screens/crypto_center/panels/SwapPanel.{h,cpp}+ - Replace JupiterSwapService dependency with PumpFunSwapService+ - Drop the wallet:quote:* subscription path+ - Compute estimated-out locally: `in_amount * spot_price * (1 - slippage_pct/100)`+ - Submit flow: PumpFunSwapService::build_swap() → sign_and_send() (unchanged below this)+ - Burn-related dead code removed (none made it past Stage 2.2, but verify)++src/screens/crypto_center/tabs/TradeTab.{h,cpp}+ - Burn placeholder QFrame removed+ - FeeDiscountPanel slotted in+ - Layout becomes: SwapPanel (top) + FeeDiscountPanel (right)++src/screens/crypto_center/CryptoCenterScreen.{h,cpp}+ - Replace ComingSoonTab in ACTIVITY slot with real ActivityTab++src/services/wallet/WalletService.{h,cpp}+ - swap_service() accessor changes type from JupiterSwapService* to PumpFunSwapService*+ - Drop wallet:quote:* topic policy (no longer needed)++src/datahub/DataHubMetaTypes.{h,cpp}+ - Drop JupiterQuote registration (no longer needed)+ - Add ParsedActivity registration++src/services/wallet/WalletTypes.h+ - Drop JupiterQuote+ - Add ParsedActivity, FncptDiscount++src/app/main.cpp+ - Construct + register WalletActivityProducer, FeeDiscountService with the hub++docs/DATAHUB_TOPICS.md+ - Remove the wallet:quote:* row (added in Stage 2.0; never used)+ - Remove the wallet:burn_receipt:* row (Burn deferred)+ - Keep wallet:activity:* and billing:fncpt_discount:*++CMakeLists.txt+ - Add PumpFunSwapService.cpp, WalletActivityProducer.cpp, FeeDiscountService.cpp,+ FeeDiscountPanel.cpp, ActivityTab.cpp+ - Remove JupiterSwapService.cpp from the source list+```++### Files removed++```+src/services/wallet/JupiterSwapService.{h,cpp}+ Replaced by PumpFunSwapService. Delete completely — no users beyond SwapPanel,+ which moves to the new service in the same PR.+```++### Files unchanged (keep as-is, do not touch)++```+src/services/wallet/WalletTxBridge.{h,cpp}+src/services/wallet/SignTransactionDialog.{h,cpp}+src/services/wallet/SolanaRpcClient.{h,cpp} (extensions from Stage 2.0)+src/screens/crypto_center/WalletActionConfirmDialog.{h,cpp}+src/screens/crypto_center/WalletActionSummary.h+src/screens/crypto_center/HoldingsBar.{h,cpp}+src/screens/crypto_center/tabs/HomeTab.{h,cpp}+src/screens/crypto_center/tabs/SettingsTab.{h,cpp}+src/screens/crypto_center/tabs/ComingSoonTab.{h,cpp} (still used for STAKE/MKTS/ROADMAP)+resources/wallet/swap.html+resources/wallet/vendor/ (web3.js slot — same need)+```++---++## 5. Stages & tasks++### Stage 2A — Swap-path pivot++**Goal:** swap (BUY + SELL) works end-to-end against PumpPortal. No new features beyond what Stage 2.2 already promised; the same UI, just a different tx-build backend.++**Task 2A.1 — `PumpFunSwapService`**+- Header: `build_swap(action: Buy|Sell, mint, amount_raw, denominated_in_sol, pubkey, slippage_pct, priority_fee_sol, cb)` → `Result<{ tx_base64, last_valid_block_height_hint }>`. The hint is _optional_ — PumpPortal doesn't expose it directly, so we either parse it from the deserialised tx (cheap, post-receive) or skip the freshness gate and rely on the wallet's own blockhash check.+- One HTTP POST to `https://pumpportal.fun/api/trade-local` with the JSON body:+ ```json+ {+ "publicKey": "<pk>",+ "action": "buy" | "sell",+ "mint": "9LUqJ5aQTjQiUCL93gi33LZcscUoSBJNhVCYpPzEpump",+ "amount": <number-or-percent-string>,+ "denominatedInSol": "true" | "false",+ "slippage": <int-percent>,+ "priorityFee": <sol>,+ "pool": "auto"+ }+ ```+- Response is **raw binary** (octet-stream), about 1 KB. Base64-encode and return.+- Reuses the `HttpClient` singleton; mirror `JupiterSwapService.cpp`'s post pattern.+- **Not a Producer** — there's no topic family. It's a one-shot service like `FncptBurnService` was going to be.+- Verification: unit-test the success path with a mocked HTTP reply; live integration test handled in Task 2A.4.++**Task 2A.2 — Replace `JupiterSwapService` plumbing**+- Delete `JupiterSwapService.{h,cpp}` and any `Q_DECLARE_METATYPE(JupiterQuote)` plus its registration in `DataHubMetaTypes`.+- Drop `WalletService::swap_service()` returning `JupiterSwapService*`; replace with `pumpfun_swap()` returning `PumpFunSwapService*`. Both `WalletService.h` and `WalletService.cpp` change.+- Remove the `wallet:quote:*` topic policy from `WalletService::ensure_registered_with_hub`.+- Remove the `wallet:quote:*` row from `docs/DATAHUB_TOPICS.md`. Same commit (D5 in CLAUDE.md).+- Verification: build is green; the screen loads as before; no dangling references in grep.++**Task 2A.3 — Update `SwapPanel`**+- Remove the `wallet:quote:*` subscription. Keep the debounce timer for input changes — but instead of resubscribing, recompute estimated-out locally:+ ```+ estimated_out = in_amount * spot_price * (1 - slippage_pct/100)+ ```+ using the cached `last_fncpt_usd_price_` (BUY) or `1 / last_fncpt_usd_price_` (SELL).+- Show the same `route` / `impact` rows but populate them from a static "PumpSwap (auto)" / "≤ slippage" — there's no live route impact from PumpPortal.+- On SWAP click: build summary as before but with locally-computed numbers, then call `PumpFunSwapService::build_swap` → `WalletService::sign_and_send` → status-poll. The lower half of the flow is unchanged.+- The `slippage_bps()` accessor stays — but we now pass `int slippage_pct = bps / 100` to PumpPortal. PumpPortal expects whole percent.+- Verification: BUY 0.001 SOL of $FNCPT on mainnet returns a signature within 30 s; balance refreshes; ACTIVITY tab shows the swap row.++**Task 2A.4 — Live smoke test**+- Manual: connect a small mainnet wallet, BUY 0.001 SOL of $FNCPT, then SELL 50 % of the resulting balance. Both must show "confirmed" within 30 s.+- Smoke for the slippage cap: try a swap with the slippage slider at 0.10 % on a low-liquidity moment → expect the wallet to reject the tx, error strip surfaces it cleanly.+- Smoke for cancel: open Confirm, click Cancel → no signature ever requested, no bridge token leaks.++**Stage 2A acceptance:**+- BUY of 0.001 SOL succeeds and balance updates in HoldingsBar within 5 s of `confirmed`.+- SELL of N $FNCPT for the resulting SOL succeeds.+- A swap whose blockhash expired during the dialog is rejected with a clear error. (No special handling needed — wallet rejects the tx; we surface the error string.)+- Slippage > 5 %: SettingsTab clamps the slider; `SwapPanel` rejects user-typed amounts that would breach impact.++### Stage 2A.5 — Multi-token holdings++**Goal:** Crypto Center shows **every** asset the user holds (SOL + every SPL token), with a USD price for each, a portfolio total at the top, and TRADE's swap dropdown populated from real holdings instead of a hard-coded `[SOL, $FNCPT]` pair. Today's FNCPT-only flow only worked because the user happened to be looking at a token they held; the moment someone wants to sell BONK or USDC for $FNCPT, the panel falls over.++The fix is small and self-contained — three producers/services, one new POD, one shared metadata cache. It belongs **before** Stage 2B because the Activity feed wants to render `SWAP SOL → BONK` rows that reference the same metadata cache.++**Why it's a separate stage and not part of 2A:** 2A was already shipped against the FNCPT-only assumption. The pivot to PumpPortal didn't change that assumption (PumpPortal is FNCPT-only by design — it's the issuer's own swap endpoint). Generalising to arbitrary holdings is its own capability with its own data plumbing.++#### 2A.5.0 Decisions locked++| # | Decision | Choice | Rationale |+|---|---|---|---|+| D.5.1 | Source of holdings | `getTokenAccountsByOwner` with `programId = TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA` (no mint filter). Single call returns every SPL account for the wallet. | Already wrapped in `SolanaRpcClient::get_token_balance`; we generalise the existing helper rather than adding a parallel one. |+| D.5.2 | Source of token metadata | **Jupiter "verified" tagged token list** (`https://api.jup.ag/tokens/v2/tagged/verified`) as the primary source; fallback to truncated mint address (`9LUq…pump`) for unverified mints. | Verified live; no key required; covers everything routable. The previous Solana Labs `token-list` repo is frozen. |+| D.5.3 | Source of token prices | **Jupiter Lite Price API** (`lite-api.jup.ag/price/v3?ids=…`) — comma-separated mints. | Already wired for `market:price:fncpt`; same host, same response shape, just batched. Verified live: SOL + USDC + FNCPT in one round-trip. |+| D.5.4 | Spam-token policy | **Hide unverified-list tokens by default**, with a Settings toggle "Show all token accounts (incl. unverified)" that reveals them. Show count in the holdings header: `7 verified · 12 unverified hidden`. | Pump.fun wallets routinely accumulate airdropped junk; defaulting to unverified-only avoids a noisy first-run. The toggle is the escape hatch. |+| D.5.5 | Topic family for prices | Generalise the existing `market:price:fncpt` into `market:price:token:<mint>` family. The `market:price:fncpt` topic stays as an alias of `market:price:token:9LUq…pump` for backward compat with existing subscribers (HoldingsBar, HomeTab, SwapPanel). | Lets any panel subscribe per-mint without a custom service. The producer batches all currently-subscribed mints into one Jupiter call per refresh cycle. |+| D.5.6 | Topic family for holdings | Reuse `wallet:balance:<pubkey>` — change the `WalletBalance` payload shape to carry `QVector<TokenHolding>` instead of just FNCPT fields. | Avoids a separate topic family. All existing consumers (HoldingsBar, HomeTab, SwapPanel, FeeDiscount) already subscribe; they just read different fields. |+| D.5.7 | Where the metadata cache lives | New `TokenMetadataService` (singleton, not a hub Producer — it's a synchronous lookup table fed by one slow background fetch). Cache TTL **24 hours**; persisted to `SecureStorage` so cold starts don't block on a 1 MB download. | A service is the right scope: balance/price producers all need it; the holdings panel needs it; SwapPanel needs it for the FROM/TO combos. |+| D.5.8 | Fallback when metadata is missing | Show `<truncated_mint>` (e.g. `9LUq…pump`) as the symbol, decimals from on-chain `getTokenAccountsByOwner` result, no icon. | Solana RPC always returns decimals in the parsed token-account info, so we never lie about scale even for unknown tokens. |+| D.5.9 | When prices are missing | Show the row but USD column reads `—`; total USD excludes that row and surfaces a footnote `1 token has no price` if any are missing. | A token in the wallet that Jupiter doesn't price is real (held); just unmonetisable for now. Don't hide it — the user might want to swap it. |+| D.5.10 | Total-USD precision | 2 dp when ≥ $1, 6 dp otherwise. Always show even at `$0.00`. | Mirrors Phase 2's Stage 2A formatter fix — zero is a real value, not "unknown". |+| D.5.11 | Trade-FROM token selector | Combo populated from holdings sorted by USD value descending, with verified Jupiter tokens appended as a "swap into" option only on the TO side. | Users sell what they have; users buy what's tradeable. Asymmetric population is the right shape. |+| D.5.12 | Phase-1.5 patterns | Single stylesheet per screen. Producer-owned heartbeats (`TokenPriceProducer` re-fetches all subscribed mints on its TTL). Force-refresh through `WalletService` (existing `force_balance_refresh()` regenerates the holdings list). | Same conventions §1.5.3 established. |+| D.5.13 | Backward compat for `market:price:fncpt` | Keep publishing the alias for one phase. Mark deprecated in `DATAHUB_TOPICS.md`. Remove in Phase 3 cleanup. | Avoids touching every existing consumer in this PR; one cleanup pass later is cheaper than one big PR now. |+| D.5.14 | Filter / sort / search in the holdings table | None this stage. Show top-N by USD value (10 by default), "Show all" link reveals the rest. Search lives with Phase 3 polish. | Keeps stage 2A.5 small. |+| D.5.15 | Out of scope | NFT holdings (Helius DAS would give them; deferred). Hardware-wallet account discovery. Multi-account aggregation (one wallet at a time, same as today). | |++#### 2A.5.1 Architecture++```+┌──────────────────────────────────────────────────────────────────────────┐+│ TokenMetadataService (singleton, NOT a Producer) │+│ - load_from_storage() // <1ms, called from main() │+│ - refresh_from_jupiter() // background, async, fires once a day │+│ - lookup(mint) → {symbol,name,decimals,icon_url} | not_found │+│ - notify_changed signal // panels listen for first-load + daily │+│ - persistence: SecureStorage key "token_metadata.cache_v1" (JSON blob)│+│ - hot path is a QReadWriteLock-guarded QHash<QString, TokenMetadata> │+└────────────┬─────────────────────────────────────────────────────────────┘+ │ called synchronously (read-mostly, ~1µs per lookup)+ ▼+┌──────────────────────────────────────────────────────────────────────────┐+│ WalletBalanceProducer (existing — payload shape upgraded) │+│ - getTokenAccountsByOwner without a mint filter │+│ - merges parsed accounts with TokenMetadataService::lookup │+│ - publishes WalletBalance{ pubkey, sol_lamports, tokens[], ts_ms } │+│ - QVector<TokenHolding> tokens — sorted by USD value at publish time │+│ (price taken from the price producer's last cache; if no cache, raw │+│ order from RPC). │+└────────────┬─────────────────────────────────────────────────────────────┘+ │ publishes+ ▼+ wallet:balance:<pk>+ │ subscribed by:+ ▼+ HoldingsBar · HomeTab BalancePanel · SwapPanel · FeeDiscountService++┌──────────────────────────────────────────────────────────────────────────┐+│ TokenPriceProducer (NEW — replaces FncptPriceProducer) │+│ - topic_patterns: ["market:price:token:*", "market:price:fncpt"] │+│ - refresh(topics) — collects all mints from subscribed topics, makes │+│ ONE Jupiter Lite call: ?ids=<mint1>,<mint2>,…,<mintN> │+│ - publishes per-mint TokenPrice{usd, sol, ts_ms, valid} │+│ - aliases the FNCPT mint to the legacy market:price:fncpt topic │+│ - max_requests_per_sec = 2 (one batched call per ~30s, tolerant) │+└──────────────────────────────────────────────────────────────────────────┘+```++#### 2A.5.2 Topic catalogue changes++| Pattern | Producer | TTL | Min interval | Notes |+|---|---|---|---|---|+| `wallet:balance:<pubkey>` | `WalletBalanceProducer` | 30 s / push | 10 s | **Payload shape upgraded** — see `WalletBalance` POD below. Same producer, same TTL. |+| `market:price:token:<mint>` | `TokenPriceProducer` | 60 s | 30 s | One Jupiter Lite call serves all subscribed mints. Coalesce 250 ms across rapid subscribe events. Shape: `TokenPrice{ mint, usd, sol, ts_ms, valid }`. |+| `market:price:fncpt` (alias) | `TokenPriceProducer` | 60 s | 30 s | Backward-compat alias of `market:price:token:9LUqJ5aQTjQiUCL93gi33LZcscUoSBJNhVCYpPzEpump`. Marked **deprecated** in this rev. Remove in Phase 3. |++#### 2A.5.3 Type changes++```cpp+// services/wallet/WalletTypes.h++struct TokenHolding {+ QString mint; // base58 SPL mint+ QString symbol; // resolved via TokenMetadataService; truncated mint if unknown+ QString name; // "USD Coin" / "" if unknown+ QString amount_raw; // integer string+ int decimals = 0; // always known (RPC parsed value)+ bool verified = false;// in Jupiter's verified tagged list+ QString icon_url; // empty if unknown+ double ui_amount() const noexcept; // amount_raw / 10^decimals+};++struct WalletBalance {+ QString pubkey_b58;+ quint64 sol_lamports = 0;+ QVector<TokenHolding> tokens; // sorted by USD value desc at publish time+ qint64 ts_ms = 0;+ double sol() const noexcept { return sol_lamports / 1e9; }+ // Convenience accessor for legacy callers that still want FNCPT specifically:+ const TokenHolding* fncpt_holding() const noexcept;+ double fncpt_ui() const noexcept; // 0.0 if not held+ int fncpt_decimals() const noexcept;+};++struct TokenPrice {+ QString mint;+ double usd = 0.0;+ double sol = 0.0;+ qint64 ts_ms = 0;+ bool valid = false;+};++struct TokenMetadata {+ QString mint;+ QString symbol;+ QString name;+ int decimals = 0;+ QString icon_url;+ bool verified = false;+};+```++The legacy `FncptPrice` POD is **kept** as a typedef of `TokenPrice` so `WalletService.cpp` and the price subscribers don't break.++#### 2A.5.4 UI changes++**HoldingsBar** — replaces today's `SOL · $FNCPT · USD · PRICE · UPDATED` with:++```+SOL 9.7425 · $FNCPT 0 · TOTAL $1,247.82 · UPDATED 3s · ● LIVE · HELIUS+```++`TOTAL` is the sum of `(holding.ui_amount × usd_price)` across SOL + every priced verified holding; rows without prices are excluded with a footnote tooltip on the chip.++**HomeTab / BalancePanel** — replaces the three-stat-box layout with a holdings table:++```+TOKEN BALANCE PRICE USD VALUE % OF PORT+SOL 9.7425 $84.28 $820.31 65.7%+USDC 420.10 $1.00 $420.10 33.7%+$FNCPT 0 $0.0000185 $0.00 0.0%+WIF 12.500 $1.42 $17.75 1.4%+─── 7 verified · 12 unverified hidden · [Show all] ─────────────────+```++Click a row → SwapPanel pre-fills FROM with that token. Click "Show all" → reveals unverified tokens with a faint "(unverified)" tag and the truncated mint instead of a symbol.++**SwapPanel** — token combos populated from real holdings:+- FROM combo: every token from `wallet:balance` sorted by USD value desc; SOL always at top.+- TO combo: every entry from FROM **plus** Jupiter verified list (filtered to remove the FROM mint). For Phase 2 we'll keep the constraint "$FNCPT must be one side of the trade" until Stage 2C, but the combo wires up to support arbitrary pairs immediately.+- MAX button reads from the selected token's balance.++**SettingsTab** — new "Show unverified tokens" toggle. Persists to `SecureStorage` key `wallet.show_unverified_tokens`.++#### 2A.5.5 Files to add / change / remove++**New files:**++```+src/services/wallet/+ TokenMetadataService.{h,cpp} // singleton, JSON cache + Jupiter fetch+ TokenPriceProducer.{h,cpp} // replaces FncptPriceProducer++src/screens/crypto_center/panels/+ HoldingsTable.{h,cpp} // owned by HomeTab; replaces three-box layout+```++**Files modified:**++```+src/services/wallet/WalletTypes.h+ - Upgrade WalletBalance shape (TokenHolding vector)+ - Add TokenHolding, TokenPrice, TokenMetadata PODs+ - FncptPrice → typedef of TokenPrice (back-compat)++src/services/wallet/WalletBalanceProducer.{h,cpp}+ - Drop the kFncptMint hard-coding inside the fetch path+ - Call SolanaRpcClient::get_all_token_balances (new helper, see below)+ - Merge metadata via TokenMetadataService::lookup+ - Sort tokens by USD value (read TokenPriceProducer's cache via a non-blocking peek)++src/services/wallet/SolanaRpcClient.{h,cpp}+ - Add: void get_all_token_balances(owner_b58, callback) — getTokenAccountsByOwner+ with programId filter only (no mint filter). Returns vector<SplTokenBalance>.++src/services/wallet/WalletService.{h,cpp}+ - Replace price_producer_ pointer type from FncptPriceProducer* to TokenPriceProducer*+ - ensure_registered_with_hub: register the new producer; update the topic-policy+ pattern from market:price:fncpt to market:price:token:* (alias retained)++src/screens/crypto_center/HoldingsBar.{h,cpp}+ - Replace per-cell SOL/$FNCPT/USD with TOTAL USD + signature SOL/$FNCPT+ - Iterate WalletBalance.tokens to compute total++src/screens/crypto_center/tabs/HomeTab.{h,cpp}+ - Drop the three stat boxes; embed HoldingsTable in their place+ - REFRESH button still calls WalletService::force_balance_refresh++src/screens/crypto_center/panels/SwapPanel.{h,cpp}+ - Populate combos from holdings + Jupiter verified list+ - Compute estimate using selected pair's prices, not FNCPT-only++src/services/billing/FeeDiscountService.{h,cpp} // when Stage 2C lands+ - Read FNCPT from WalletBalance.fncpt_ui() helper++src/datahub/DataHubMetaTypes.{h,cpp}+ - Register TokenHolding, TokenPrice (FncptPrice still works via typedef)+ - Drop the JupiterQuote registration (already gone, just sanity-check)++src/app/main.cpp+ - Construct + load TokenMetadataService::instance() before WalletService::ensure_registered_with_hub()+ - Service registration already routes through WalletService — no change needed there.++docs/DATAHUB_TOPICS.md+ - Replace the market:price:fncpt row with the new market:price:token:* family+ - Note that market:price:fncpt is a deprecated alias for one phase++CMakeLists.txt+ - Add TokenMetadataService.cpp, TokenPriceProducer.cpp, HoldingsTable.cpp+ - Remove FncptPriceProducer.cpp (file deleted)+```++**Files removed:**++```+src/services/wallet/FncptPriceProducer.{h,cpp} // replaced by TokenPriceProducer+```++#### 2A.5.6 Tasks++**2A.5.1 — Type plumbing** (foundation; nothing UI-visible)+- New PODs in `WalletTypes.h`; `FncptPrice` typedef of `TokenPrice`.+- Register metatypes in `DataHubMetaTypes.cpp`.+- Verification: builds clean; existing consumers compile against the legacy aliases.++**2A.5.2 — `TokenMetadataService`**+- Singleton; on first instantiation, restore JSON blob from SecureStorage.+- Public API: `lookup(mint) → optional<TokenMetadata>`, `bool is_verified(mint)`.+- Background `refresh_from_jupiter()` runs once on startup if cache is older than 24 h, or on first `lookup()` of a mint absent from cache.+- Backed by `QHash<QString, TokenMetadata>` under a `QReadWriteLock`.+- Verification: unit test the SecureStorage round-trip; manual test that hitting `api.jup.ag/tokens/v2/tagged/verified` (rate-limit-tolerantly) populates the cache.++**2A.5.3 — `SolanaRpcClient::get_all_token_balances`**+- Call `getTokenAccountsByOwner(owner, {programId: TOKEN_PROGRAM_ID}, {encoding: jsonParsed})`.+- Return the same `vector<SplTokenBalance>` shape as today's `get_token_balance`, just unfiltered.+- Verification: against a known-multi-token wallet; expect ≥ 2 entries.++**2A.5.4 — `WalletBalanceProducer` upgrade**+- Replace the FNCPT-only fetch path with `get_all_token_balances`.+- For each `SplTokenBalance`, build a `TokenHolding` with metadata from `TokenMetadataService::lookup()`. Filter spam (decimals=0 amount=1 unless whitelisted) before publish if Settings says so.+- Sort tokens by USD value (read `TokenPriceProducer`'s last-cached value; if no cache yet, sort by raw amount).+- Verification: subscribe to `wallet:balance:<pk>` from a test harness with a multi-token wallet; expect ≥ 2 entries.++**2A.5.5 — `TokenPriceProducer`**+- Topic patterns: `"market:price:token:*"`, `"market:price:fncpt"` (alias).+- `refresh(topics)`: collect all mints, build one `?ids=...` call, publish per-mint.+- Set policy: TTL 60 s, min_interval 30 s, coalesce 250 ms.+- Delete `FncptPriceProducer.{h,cpp}`; route the alias topic into the new producer's mint-extraction logic.+- Verification: subscribe to two arbitrary mints simultaneously; expect a single network call within 250 ms.++**2A.5.6 — `WalletService` rewiring**+- Construct `TokenPriceProducer` instead of `FncptPriceProducer`.+- Update topic-policy registration to cover both `market:price:token:*` and the alias.+- Verification: `market:price:fncpt` still publishes; `market:price:token:So111…1112` (SOL) also publishes.++**2A.5.7 — `HoldingsTable` widget**+- New widget owned by `HomeTab`. Subscribes to `wallet:balance:<pk>` and to `market:price:token:<mint>` for each currently-held mint.+- Renders the table; whole-row click → emits a `select_token(mint)` signal (wired to `SwapPanel` in 2A.5.10).+- "Show all" link toggles unverified visibility for the current session; persisted state lives in SettingsTab.+- Verification: connected wallet shows ≥ 1 row (SOL); a multi-token wallet shows USDC, FNCPT, etc.++**2A.5.8 — `HoldingsBar` rewrite**+- Iterate `WalletBalance.tokens` for the total. Show SOL + signature $FNCPT + TOTAL USD + feed pill + RPC chip.+- Verification: total matches manual sum across SOL + all verified holdings × Jupiter prices.++**2A.5.9 — `HomeTab` BalancePanel layout swap**+- Replace the three stat boxes with the `HoldingsTable` widget. Keep REFRESH + the POLL/STREAM toggle on the panel head.+- Verification: layout renders cleanly at narrow widths (no horizontal scroll).++**2A.5.10 — `SwapPanel` token combos**+- FROM combo populated from `WalletBalance.tokens` sorted by USD value desc. SOL always at top.+- TO combo: union of FROM holdings and Jupiter verified list (minus the FROM mint). For Phase 2, default TO = $FNCPT; Phase 3 lifts the constraint.+- MAX button reads from the **selected** mint's `ui_amount`, with a 0.005 SOL reserve only when the FROM is SOL.+- Estimate: read prices for both FROM and TO from `TokenPriceProducer`; fall back to "estimate unavailable" if either missing.+- Verification: select USDC FROM → MAX → see correct USDC balance prefilled; estimate shows USDC→FNCPT in $FNCPT units.++**2A.5.11 — `SettingsTab` "show unverified" toggle**+- Persist to `SecureStorage` key `wallet.show_unverified_tokens`.+- HoldingsTable + SwapPanel honor the flag.++**2A.5.12 — Doc + topic catalogue update**+- `docs/DATAHUB_TOPICS.md`: replace `market:price:fncpt` row with `market:price:token:*`. Mark legacy alias deprecated. Document `wallet:balance:<pubkey>` shape change.+- `plans/crypto-center-future-phases.md` §2.5: bring the topics list in line.++#### 2A.5.7 Acceptance criteria++- [ ] HoldingsBar shows TOTAL USD = sum of (SOL × SOL price) + Σ (token × token price) for verified holdings.+- [ ] HomeTab shows a holdings table with at least the user's actually-held tokens (SOL, FNCPT, plus whatever airdrops they have if "Show all" is on).+- [ ] SwapPanel FROM combo lists every held token; selecting a non-FNCPT token populates balance correctly and estimate shows in TO units.+- [ ] First-run cold cache: TokenMetadataService loads from SecureStorage in < 5 ms; UI never shows raw mint addresses for verified tokens after the first balance publish.+- [ ] No Rust source. No new on-chain code. No Helius dependency for the verified-tokens path (Helius only used for parsed-tx in Stage 2B).+- [ ] Phase 1.5 patterns honored: single stylesheet per screen, FeedStatus on HoldingsBar still drives via objectName swap, force-refresh through `WalletService::force_balance_refresh`.++#### 2A.5.8 Risks & open questions++1. **Jupiter token-list size.** Verified list is ~500KB-1MB. SecureStorage handles strings of that size today, but worth confirming on first-run write. Fallback if SecureStorage chokes: write to a plain JSON file under `AppData/.../cache/`.+2. **Jupiter rate limits.** The `tokens/v2` endpoint rate-limited me during planning. The price endpoint is fine. We refresh metadata once a day so the rate-limit risk is low; but cold-start on a fresh install needs to handle a 429 by retrying with backoff.+3. **NFTs.** SPL-token-account RPC returns NFTs (decimals=0, amount=1). Spam filter handles them by default; user can opt in via "Show all". A real NFT panel ships in a later phase.+4. **Sort-by-USD when no price.** Producer publishes before the price call returns on first run. Tokens without prices sort to the bottom (alphabetical fallback by symbol), then re-sort on the next publish once prices arrive. Acceptable jitter; documented.+5. **Total-USD precision over time.** Rounding errors across 50 tokens at 6dp could accumulate. Sum at full precision, format only at display.+6. **`market:price:fncpt` alias retirement.** D.5.13 says one phase. Need a follow-up TODO when Phase 3 starts.++---++### Stage 2B — Activity feed++**Goal:** users can see what their wallet has done.++**Task 2B.1 — `WalletActivityProducer`**+- Topic `wallet:activity:<pubkey>`. Policy `ttl_ms=30_000, min_interval_ms=10_000`.+- `refresh()` calls Helius `/v0/addresses/<pk>/transactions?limit=50` (auth via existing `solana.helius_api_key`).+- Parses each tx into `ParsedActivity { ts, kind: SWAP|RECEIVE|SEND|OTHER, asset, amount_ui, signature }`. Helius parsing handles SWAP / RECEIVE / SEND directly; OTHER for everything we can't classify.+- Fall back: if Helius key missing, use `SolanaRpcClient::get_signatures_for_address` for raw signatures + show "Add a Helius key for parsed activity" footer in the tab.+- Verification: subscribe in a test harness, observe publish, change pubkey, observe new topic.++**Task 2B.2 — `ActivityTab` UI**+- `QTableView` with TIMESTAMP / EVENT / ASSET / AMOUNT / STATUS columns + whole-row click → Solscan.+- Filter chips above the table for SWAP / SEND / RECEIVE / OTHER.+- Empty state shows "No transactions yet" with a CONNECT WALLET fallback if disconnected.+- Replaces the `ComingSoonTab` in CryptoCenterScreen's ACTIVITY slot.+- Verification: ACTIVITY tab shows the swap from Stage 2A within one refresh cycle.++**Stage 2B acceptance:**+- ACTIVITY tab populates with the last 50 parsed events for the connected wallet.+- Clicking a row opens Solscan in the default browser.+- Filter chips narrow the list correctly.++### Stage 2C — Fee discount++**Goal:** eligible users see a "30 % off" badge wherever applicable.++**Task 2C.1 — `FeeDiscountConfig.h`**+- Constants: `kThresholdRaw = 1_000 * 10^6` (1,000 $FNCPT, 6 decimals); `kDiscountPct = 30`; `kAppliedSkus = {"ai-report", "deep-backtest", "premium-screen"}`.+- Header-only; no .cpp.++**Task 2C.2 — `FeeDiscountService`**+- Subscribes `wallet:balance:<pk>` internally (consumer-producer pattern from Phase 1's price-balance interplay).+- Publishes `billing:fncpt_discount:<pk>` = `{ eligible, threshold_raw, threshold_decimals, applied_skus }`.+- Re-publishes whenever the balance topic emits.+- Register in main.cpp alongside the other Phase 2 producers.+- Verification: balance publishes ≥ 1,000 → eligibility chip lights up; balance drops below threshold → chip extinguishes within one publish cycle.++**Task 2C.3 — `FeeDiscountPanel`**+- Owned by `TradeTab`; replaces today's placeholder.+- Subscribes `billing:fncpt_discount:<pk>`.+- Shows: balance-vs-threshold bar, applied SKUs as bullet list, projected savings on a hypothetical AI report ($x → $y).+- Read-only. Phase 3's Tier service will swap this for a richer panel.++**Task 2C.4 — `HoldingsBar` chip**+- The `discount_chip_` widget already exists (placeholder in Stage 2.1).+- Wire it: subscribe `billing:fncpt_discount:<current_pubkey>`, show/hide based on `eligible`.+- No new layout work.++**Stage 2C acceptance:**+- HoldingsBar and FeeDiscountPanel show "30 % off" for an account holding ≥ 1,000 $FNCPT.+- Balance dropping below threshold flips the chip back inside one publish cycle.++### Stage 2D — Polish, docs, security walkthrough++- Update `docs/CRYPTO_CENTER_PHASE_2.md` with screenshots of BUY, SELL, ACTIVITY.+- Walk every threat in §2 against the implementation; sign off in `plans/crypto-center-trade-security.md`.+- Update `plans/crypto-center-future-phases.md` to mark Phase 2 shipped (move §2 into a `crypto-center-phase-2-shipped.md` snapshot, including the burn-deferred decision).+- Confirm Phase 1.5 patterns (single stylesheet, FeedStatus pill, force-refresh through services, producer-owned heartbeats, endpoint-capability checks, screen-side staleness, error-strip pattern, RPC chip) were honored throughout.++---++## 6. Risks & open questions++1. **PumpPortal availability.** The endpoint is third-party; if pumpportal.fun goes down, swaps break. Mitigation: the screen renders an empty TRADE tab with "Swap service temporarily unavailable" instead of crashing. We can fall back to Jupiter (the earlier rev's code) on Phase 3 or later if reliability becomes an issue — keeping the swap.html signing path generic means the swap-build service is hot-swappable.+2. **PumpPortal rate limits.** No public spec. Empirically tolerant for low-volume use. If we hit limits, add a `min_interval_ms` on the build call (note: this is one-shot, not a hub topic, so the throttle would live inside `PumpFunSwapService`).+3. **PumpPortal MITM.** TLS pinning would close the residual risk; out of scope this phase, listed as Phase 2.5 polish.+4. **Helius parsed-tx coverage.** Some swap routes don't decode into a clean SWAP row. Acceptable: those show as OTHER with the signature link.+5. **Burn deferral.** Real users will ask for it. Holding line on Phase 5 buyback worker as the right place.+6. **Slippage UX.** 1 %/5 % defaults are correct for $FNCPT today (thin liquidity); revisit when Phase 5 buyback narrows spreads.+7. **Failure during multi-leg swap.** PumpPortal returns a single versioned tx so partial fills aren't a concern; we just surface the error.++---++## 7. Out of scope for Phase 2++- **Burn UI.** Deferred to Phase 5 (buyback automation).+- **Direct Ledger USB.** Use Phantom/Solflare's Ledger support.+- **Multi-chain.** $FNCPT stays on Solana.+- **Server-backed entitlement** (Phase 3 owns this).+- **WebSocket parsed-tx feed for activity** (poll is enough for Phase 2 traffic).+- **Per-trade priority-fee override** (Settings-level only this phase).+- **Limit orders, advanced order types.** PumpPortal doesn't support them; out of scope.++---++## 8. Definition of Done++- [ ] User opens TRADE tab, sees a SwapPanel with current spot price and projected output. BUY of 0.001 SOL on mainnet succeeds in ≤ 30 s.+- [ ] User opens TRADE tab, can SELL 50 % of their $FNCPT and see the resulting SOL within ≤ 30 s.+- [ ] HoldingsBar shows live SOL · $FNCPT · USD · feed pill on every tab.+- [ ] ACTIVITY tab populates with the last 50 parsed events; clicking a row opens Solscan.+- [ ] FeeDiscount chip appears on HoldingsBar at ≥ 1,000 $FNCPT and disappears below.+- [ ] All P-rules and D-rules from CLAUDE.md hold; lint passes.+- [ ] Phase 1.5 patterns (single stylesheet per screen, FeedStatus pill, force-refresh through services) are honored.+- [ ] `docs/DATAHUB_TOPICS.md` lists `wallet:activity:*` and `billing:fncpt_discount:*` (and **does not** list `wallet:quote:*` or `wallet:burn_receipt:*`).+- [ ] `crypto-center-trade-security.md` is signed off.+- [ ] No Rust source anywhere in the tree.++---++## 9. Document maintenance++Update this doc at each stage kickoff with the actual PR diffs. When Phase 2 ships, archive into `crypto-center-phase-2-shipped.md` with the verified-pattern subset of §1.5.3 expanded for transactional flows. The pivot-to-PumpPortal decision (D1) and the burn-deferral (D6) should be called out at the top of that archive so future phases inherit the rationale, not just the diff.diff --git a/fincept-qt/plans/crypto-center-security-walkthrough.md b/fincept-qt/plans/crypto-center-security-walkthrough.mdnew file mode 100644index 000000000..9e45d852b--- /dev/null+++ b/fincept-qt/plans/crypto-center-security-walkthrough.md@@ -0,0 +1,129 @@+# Crypto Center — Security walkthrough (Phase 3.3)++This document records the manual security review of the wallet-connect flow built in Phase 1.++**Plan**: `plans/crypto-center-wallet-connect.md`+**Date**: 2026-04-27+**Reviewer**: claude (initial pass — to be re-signed by tilakpatel22 after a clean build run)++The plan §3 enumerated nine threats. Each is reproduced below with its mitigation as implemented and a self-attack note.++## Threat 1 — Pubkey spoofing++**Attack**: an attacker gets the user to paste/save someone else's public key, the terminal happily renders that wallet's balance and treats it as the user's identity for future operations.++**Mitigation**: every connect runs a signed-message challenge.+- `ConnectWalletDialog::start_handshake()` generates a 32-byte cryptographically random nonce via `QRandomGenerator::system()` (CSPRNG, not the deterministic generator).+- The browser-side JS asks the wallet to sign the literal bytes `Fincept Terminal wallet-connect challenge. Nonce: <hex>`.+- `ConnectWalletDialog::on_payload()` calls `Ed25519Verifier::verify(pubkey, message, signature)` on the returned bundle. If the signature is invalid, the dialog rejects with "signature verification failed" and never persists anything.+- `Ed25519Verifier::verify()` uses the public-domain `orlp/ed25519` reference implementation (FetchContent pinned to a SHA), wrapped in our base58 decoder.++**Self-attack**: simulated by sending a fake `delivered()` payload over the bridge with someone else's pubkey + my own valid signature → must fail. The verifier checks `signature` against `pubkey` directly via the underlying ed25519 primitive — a signature produced by key X cannot validate against key Y.++**Status**: ✅ mitigated.++## Threat 2 — Bridge hijack from other browser tabs++**Attack**: any tab in the user's browser (or any program on the LAN) sends a forged POST to the local bridge, claiming to be the wallet, before the legitimate flow completes.++**Mitigation**:+- `LocalWalletBridge::start()` calls `QTcpServer::listen(QHostAddress::LocalHost, 0)`. **`LocalHost` binds to `127.0.0.1` only** — not `0.0.0.0`, not the LAN address. Verifiable post-deploy via `netstat -an | findstr LISTEN` showing only `127.0.0.1:<port>`.+- The port number is selected by the OS (`port=0`), so it's unpredictable.+- Each connect generates a fresh 16-byte (`random_token_hex(16)` → 32 hex chars) `connect_token`. The token is included in both the URL (`/connect?token=...`) and the callback URL (`/callback?token=...`).+- `LocalWalletBridge::handle_request()` rejects any request whose query token doesn't match — returns 403 and disconnects.+- The server stops itself on the first valid `/callback` POST or after the timeout (default 120s).++**Self-attack**: a different browser tab opens `http://127.0.0.1:<port>/connect` without the token → 403 forbidden. With the token guessed (1 in 2¹²⁸ probability per attempt) → connect page loads, but cannot reach the wallet because the wallet only signs messages the user explicitly approves in the wallet UI. Even with a stolen token, the attacker cannot mint a valid signature for the nonce.++**Status**: ✅ mitigated.++## Threat 3 — Replay of signed nonce++**Attack**: an attacker captures a previously-signed challenge and replays it to a future connect attempt.++**Mitigation**:+- The nonce is regenerated on every `start_handshake()` call (per-dialog, per-connect).+- The nonce never leaves memory — not written to disk, not logged.+- The bridge's `connect_token` is regenerated on every `start()`. A captured pair is bound to a specific `(nonce, token, port)` triple that never recurs.+- Even if the `(nonce, signature)` pair is somehow resurrected, replaying requires the **right port and token** — both ephemeral.++**Status**: ✅ mitigated.++## Threat 4 — Long-lived session abuse++**Attack**: an attacker who briefly gains code execution while the terminal is unlocked uses the persisted session to perform privileged operations later (e.g., signing transactions, moving funds).++**Mitigation**:+- The persisted session contains only the public key + label + timestamp. It cannot itself authorise any operation.+- The current Phase 1 scope is **read-only** — the wallet identity is used to look up balances. No transaction signing flows exist yet.+- When transaction signing is added in Phase 2, every signing operation **must** re-prompt the wallet UI. The terminal cannot auto-sign anything because it does not hold private keys.++**Status**: ✅ mitigated by scope; will need re-review when Phase 2 (signing) lands.++## Threat 5 — SecureStorage tampering++**Attack**: an attacker overwrites the saved public key with their own, so future "soft-connected" sessions display attacker-controlled balances and an attacker-controlled identity.++**Mitigation**:+- Live balances are always re-fetched from RPC for whatever pubkey is in storage. A tampered pubkey shows the *attacker's* balance — visible to the user.+- For any future privileged action, the next sign-message challenge regenerates trust; a tampered pubkey will not be able to produce a valid signature, so the operation fails.+- `WalletService::restore_from_storage()` marks the state as `soft_connected = true`. Any flow needing on-chain authority must check this and trigger a fresh challenge before acting.++**Status**: ✅ mitigated for Phase 1. Phase 2 callers must honour `soft_connected`.++## Threat 6 — Local web bridge exposed beyond loopback++Already covered in Threat 2. Reiterated here because it's the most common misconfiguration in similar tools.++**Verification**:+- `QHostAddress::LocalHost` is the literal address `127.0.0.1`, not the hostname `localhost`. This avoids DNS rebinding attacks where a malicious site resolves `localhost` to its own IP.+- The page sets `Access-Control-Allow-Origin` headers? No — there's no CORS header at all, which is correct: same-origin requests don't need it, cross-origin requests must be blocked. The `X-Content-Type-Options: nosniff` header is set on every response.++**Status**: ✅ mitigated.++## Threat 7 — Malicious wallet provider++**Attack**: the user installs a fake "Phantom" extension that exfiltrates their seed phrase or signs unintended transactions.++**Mitigation**: out of scope. The wallet provider is owned by the user; this is no different from any web dApp. We reduce attack surface by letting the user pick from named providers (Phantom, Solflare, Backpack, Glow, `window.solana`) but cannot validate the provider itself.++The user-facing doc warns that sources should be downloaded only from official wallet sites.++**Status**: ⚠️ acknowledged, not mitigated. Inherent to the wallet-extension model.++## Threat 8 — Browser-side connect page tampering++**Attack**: the connect page (`resources/wallet/connect.html`) is replaced with a malicious version that exfiltrates the signed nonce or sends additional `signMessage` requests for things the user didn't authorise.++**Mitigation**:+- The connect page is bundled at build time (CMake `copy_if_different` step) into `$<TARGET_FILE_DIR:FinceptTerminal>/resources/wallet/connect.html`. Tampering requires write access to the install directory.+- The page's CSP locks `default-src` to `'self'`, blocks remote images/scripts, and only allows fetch to `127.0.0.1` and `localhost`. No CDN, no analytics, no third-party domains.+- The page never loads remote JavaScript — all the connect code is inline.++**Status**: ✅ mitigated against opportunistic tampering. A privileged attacker with file-write access to the install dir can swap the page; same threat model as patching the EXE itself.++## Threat 9 — Signed-message UX phishing++**Attack**: the user clicks "Sign" on a message they don't actually understand, granting the terminal an unintended capability.++**Mitigation**:+- The signed message is human-readable: `Fincept Terminal wallet-connect challenge. Nonce: <hex>`. It contains no fund-movement primitives — it is a literal text message, not a transaction.+- The user-facing doc explicitly tells users to verify the message begins with this prefix before signing.+- This is signed-message authentication only. We never use signed messages to authorise on-chain state changes — those will require a real transaction in Phase 2.++**Status**: ✅ mitigated.++## Sign-off checklist++Once the build runs cleanly and the dialog has been exercised end-to-end, manually verify:++- [ ] `netstat -an | findstr LISTEN` while the dialog is open shows the bridge port bound to `127.0.0.1` only, never `0.0.0.0` or LAN IP.+- [ ] Cancelling the dialog from the GUI closes the bridge port within 1 second (verify with a second `netstat`).+- [ ] After a successful connect, the SecureStorage file/registry contains pubkey + label + timestamp, **no signature**, **no nonce**.+- [ ] Disconnect clears the SecureStorage entries.+- [ ] Restarting the app with a saved connection rehydrates the pubkey and starts balance polling — without re-prompting the wallet.+- [ ] Crashing the wallet extension mid-handshake (close browser before signing) leads to a graceful "timed out" error after 120 s.+- [ ] Manually crafting a curl POST to `/callback?token=wrong` returns 403.+- [ ] Manually crafting a curl POST to `/callback?token=<right>` with a fabricated `{pubkey, signature}` (signature for a different pubkey) is rejected by `Ed25519Verifier::verify` and the dialog stays open.++The first six can be checked during Phase 3 manual QA. The last two should be scripted as integration tests under `tests/wallet/` in a follow-up commit.diff --git a/fincept-qt/plans/crypto-center-wallet-connect.md b/fincept-qt/plans/crypto-center-wallet-connect.mdnew file mode 100644index 000000000..6c5eb059b--- /dev/null+++ b/fincept-qt/plans/crypto-center-wallet-connect.md@@ -0,0 +1,294 @@+# Crypto Center — Wallet Connect (Phase 1)++**Status**: draft+**Owner**: tilakpatel22+**Last updated**: 2026-04-27++---++## 1. Goal++Build a new **Crypto Center** screen in the Fincept Terminal where users can:+- Connect any major Solana wallet (Phantom, Solflare, Backpack, Glow, Coinbase Solana) and any WalletConnect-v2 mobile wallet.+- See live $FNCPT + SOL balances.+- Disconnect cleanly. Re-connect on next launch without re-prompting (session persistence).++This is **Phase 1** of a longer $FNCPT integration roadmap (gating, burn, staking, prediction markets, buyback). Phase 1 ships **wallet identity + balance display only**. No transactions. No swaps. That comes in Phase 2.++---++## 2. Decisions locked++| # | Decision | Choice |+|---|---|---|+| D1 | Browser-extension transport | **QWebEngineView** hosting Solana Wallet Adapter + WalletConnect v2 SDK |+| D2 | Initial chain scope | **Solana-only** (EVM/MetaMask deferred) |+| D3 | Hardware wallets | **Via Phantom/Solflare host** (no direct Ledger USB in v1) |+| D4 | Sign-in proof | **Signed-message challenge** (random nonce, 5 min TTL, ed25519 verify) |+| D5 | Persisted state | pubkey + label + connected_at in `SecureStorage`; **never** keys/signatures |+| D6 | RPC provider | **Helius** (free tier) — fall back to public `api.mainnet-beta.solana.com` if key missing |+| D7 | $FNCPT mint | `9LUqJ5aQTjQiUCL93gi33LZcscUoSBJNhVCYpPzEpump` (pump.fun, devnet/mainnet TBD) |+| D8 | Screen registration | **Lazy** (`router_->register_factory(...)`) per P2 |+| D9 | Data path | New DataHub producer; `wallet:balance:<pubkey>` topic family per D1/D2 |++---++## 3. Threat model (mandatory before any code)++**Assets to protect:**+1. User's private keys → **never touched, never seen**. Phantom/etc. is the sole signer.+2. User's pubkey → low-sensitivity but tied to identity; stored in `SecureStorage`.+3. Connection session → if hijacked, an attacker can phish the user with fake "sign this" prompts.+4. Local web bridge → if exposed beyond loopback, remote sites could trigger connect/sign UI.++**Attacks considered + mitigations:**++| Attack | Mitigation |+|---|---|+| Pubkey spoofing (user pastes any address) | Signed-message challenge: server generates `nonce`, web page calls `wallet.signMessage(nonce)`, server verifies sig matches pubkey |+| Bridge hijack from other browser tabs | Bind to `127.0.0.1` only, randomly chosen port, single-use connect token in URL, kill server on success/timeout/30s |+| Replay of signed nonce | Nonce includes timestamp + random; expires in 5 min; one-time use, persisted in memory only |+| Long-lived session abuse | Session = pubkey only; every signing op (Phase 2+) re-prompts wallet UI; no auto-sign anywhere ever |+| `SecureStorage` tampering | Live balance always re-fetched from RPC; pubkey treated as untrusted until next sig challenge on critical ops |+| QWebEngine sandbox escape | All web content loaded from local resource (`qrc://`); no remote JS; CSP `default-src 'self'`; navigation locked |+| Malicious WC pairing relay | Use official relay `wss://relay.walletconnect.org`; pin project ID; verify session metadata before showing prompts |+| Clipboard / address swap malware | Show pubkey prominently after connect; user must visually verify before any future tx |++**Out of scope for Phase 1:** transaction signing, fund movement, swap, burn. These have their own threat model and ship in Phase 2 with separate review.++---++## 4. Architecture++```+┌─────────────────────────────────────────────────────────────────────┐+│ CryptoCenterScreen (UI only — P6) │+│ ┌────────────────────┐ ┌────────────────────┐ │+│ │ Wallet status card │ │ Balances card │ │+│ │ (pubkey, label) │ │ ($FNCPT, SOL) │ │+│ └────────────────────┘ └────────────────────┘ │+│ ┌────────────────────┐ │+│ │ Connect / disconnect button → ConnectWalletDialog │+│ └────────────────────┘ │+└─────────────────────────────────────────────────────────────────────┘+ │ subscribes to DataHub topics ▲+ ▼ │+┌─────────────────────────────────────────────────────────────────────┐+│ DataHub (existing) │+│ topic: wallet:state (push-only, owned by WalletService) │+│ topic: wallet:balance:<pk> (TTL 30s, min_interval 10s) │+│ topic: market:price:fncpt (TTL 60s — Jupiter price API) │+└─────────────────────────────────────────────────────────────────────┘+ ▲ publishes+ │+┌─────────────────────────────────────────────────────────────────────┐+│ WalletService (singleton, QObject) │+│ - connect_extension() → spawns ConnectWalletDialog │+│ - connect_walletconnect() │+│ - disconnect() │+│ - current_pubkey() / is_connected() │+│ - signals: wallet_connected, wallet_disconnected, balance_updated │+│ WalletBalanceProducer → wallet:balance:<pk> │+│ FncptPriceProducer → market:price:fncpt │+└─────────────────────────────────────────────────────────────────────┘+ ▲ uses+ │+┌─────────────────────────────────────────────────────────────────────┐+│ ConnectWalletDialog (modal, QWebEngineView host) │+│ - loads qrc:/wallet/index.html │+│ - QWebChannel exposes WalletBridge to JS │+│ - JS uses Solana Wallet Adapter (extensions) + │+│ @walletconnect/sign-client (QR for mobile) │+│ - on connect: bridge.delivered(pubkey, signed_nonce) │+└─────────────────────────────────────────────────────────────────────┘+ ▲ verifies sig+ │+┌─────────────────────────────────────────────────────────────────────┐+│ Ed25519Verifier (libsodium or Botan — pick one in Task 0) │+│ - verify(pubkey_b58, message, signature_b58) → bool │+└─────────────────────────────────────────────────────────────────────┘+```++**Key files (planned):**+- `src/screens/crypto_center/CryptoCenterScreen.{h,cpp}`+- `src/screens/crypto_center/ConnectWalletDialog.{h,cpp}`+- `src/screens/crypto_center/WalletStatusCard.{h,cpp}`+- `src/screens/crypto_center/BalanceCard.{h,cpp}`+- `src/services/wallet/WalletService.{h,cpp}`+- `src/services/wallet/WalletBalanceProducer.{h,cpp}`+- `src/services/wallet/FncptPriceProducer.{h,cpp}`+- `src/services/wallet/Ed25519Verifier.{h,cpp}`+- `src/services/wallet/SolanaRpcClient.{h,cpp}` (thin wrapper over `HttpClient`)+- `resources/wallet/index.html` + `wallet.js` (Wallet Adapter + WC v2 SDK bundle)+- `docs/DATAHUB_TOPICS.md` — add `wallet:state`, `wallet:balance:*`, `market:price:fncpt`+- `fincept-qt/CMakeLists.txt` — add `Qt6::WebEngineWidgets`, `Qt6::WebChannel`, ed25519 lib++**Existing files touched:**+- `src/app/main.cpp` — register `CryptoCenterScreen` factory; bootstrap `WalletService` singleton; register producers with hub.+- `src/screens/(navigation registry)` — add nav entry.++---++## 5. Phases & tasks++### Phase 0 — Plumbing (no UI yet)++**Task 0.1 — Pick & integrate ed25519 lib**+- Add **libsodium** via FetchContent (already used by some crypto deps; small, BSD-licensed). Confirm no conflict with existing deps.+- Wrap in `Ed25519Verifier::verify(QString pubkey_b58, QByteArray msg, QString sig_b58)`.+- Verification: unit test with known-good vector (Solana's `nacl_test` vectors).++**Task 0.2 — Add Qt WebEngine + WebChannel deps**+- Update `CMakeLists.txt`: `find_package(Qt6 REQUIRED COMPONENTS WebEngineWidgets WebChannel)`.+- Update Windows deploy to bundle QtWebEngineProcess.exe + resources.+- Verification: minimal QWebEngineView test compiles, links, runs.++**Task 0.3 — Build the wallet bridge HTML+JS**+- `resources/wallet/index.html` — minimal page with Wallet Adapter UI + WC v2 SDK.+- Bundled offline (no remote CDN). Use `pnpm` or `npm` to build `wallet.js` and check the bundle into `resources/wallet/dist/wallet.bundle.js`.+- Loaded from `qrc:/wallet/index.html` — **never from `https://`**.+- CSP meta tag locks origins.+- Exposes one `WalletBridge` over QWebChannel with: `request_connect()`, `request_disconnect()`, `delivered(pubkey, signature)`, `error(code, msg)`, `qr_uri(uri)` (for WC).+- Verification: load page in standalone `QWebEngineView` test app, click "Connect", verify Phantom prompt fires.++**Task 0.4 — SolanaRpcClient**+- Wrap `HttpClient` for: `getBalance`, `getTokenAccountsByOwner`, `getRecentBlockhash` (future).+- Helius URL from `KeyConfigManager` (`solana/helius_api_key`); fallback to public RPC.+- Verification: unit test against devnet known-balance pubkey.++### Phase 1 — WalletService + producers++**Task 1.1 — WalletService skeleton**+- Singleton, lives in `main.cpp` bootstrap.+- State: `current_pubkey_`, `connected_at_`, `label_`. Restored from `SecureStorage` on startup (read-only — no signature trust until next challenge).+- Signals: `wallet_connected(QString pubkey)`, `wallet_disconnected()`, `balance_updated(QString pubkey, double sol, double fncpt)`.+- Methods: `connect_with_dialog(QWidget* parent)`, `disconnect()`, `is_connected()`, `current_pubkey()`.+- Verification: write/read pubkey roundtrips through SecureStorage in a unit test.++**Task 1.2 — ConnectWalletDialog**+- `QDialog` modal, hosts `QWebEngineView`, sets up `QWebChannel`, exposes `WalletBridge`.+- Generates 32-byte nonce, sends to JS via bridge property.+- Receives `delivered(pubkey, sig_b58)` → calls `Ed25519Verifier::verify(...)` → on success, emits `connected(pubkey)`.+- 60s overall timeout, cancel button, clear error states.+- Verification: end-to-end manual test — open dialog, connect Phantom (devnet), confirm pubkey lands.++**Task 1.3 — WalletBalanceProducer**+- Subscribes hub topic `wallet:balance:<pubkey>`.+- Policy: TTL 30s, min_interval 10s, push_only false.+- On request: `SolanaRpcClient::getBalance(pubkey)` → SOL; `getTokenAccountsByOwner(pubkey, FNCPT_MINT)` → FNCPT.+- Publishes `WalletBalance{ sol_lamports, fncpt_raw, fncpt_decimals }`.+- Verification: subscribe in a test harness, observe publish, change pubkey, observe new topic.++**Task 1.4 — FncptPriceProducer**+- Subscribes hub topic `market:price:fncpt`.+- Policy: TTL 60s, min_interval 30s.+- Calls Jupiter Price API: `https://api.jup.ag/price/v2?ids=<FNCPT_MINT>`.+- Publishes `{ usd_price, sol_price, ts }`.+- Verification: hit the API live, confirm parse.++**Task 1.5 — Register everything in main.cpp**+- After `DataHub` is up: `WalletService::instance().ensure_registered_with_hub()`.+- After router is built: `router_->register_factory("crypto_center", []{ return new CryptoCenterScreen(...); });`.+- Verification: app boots, screen reachable from nav, no producers spawn until subscribed.++**Task 1.6 — Update DataHub docs**+- Append rows to `docs/DATAHUB_TOPICS.md` for `wallet:state`, `wallet:balance:*`, `market:price:fncpt`.+- Per D5 in CLAUDE.md (DataHub rules): **same commit as producers**.+- Verification: doc renders, every topic the producers publish is documented.++### Phase 2 — UI (CryptoCenterScreen)++**Task 2.1 — Screen shell**+- Header: "Crypto Center" + connection chip (green/red).+- Empty state: big "Connect Wallet" button + 1-paragraph explainer + security note ("we never see your keys").+- Connected state: WalletStatusCard + BalanceCard side-by-side, then activity placeholder ("coming Phase 2").+- Theme: follow Obsidian DESIGN_SYSTEM.md, no inline styles per P7.+- Verification: visual review on dark + light themes.++**Task 2.2 — WalletStatusCard**+- Shows pubkey (truncated `9LUq…Epump`, full on hover/copy click), connected_at (relative), wallet label ("Phantom", "Solflare" — from Wallet Adapter).+- "Disconnect" button → `WalletService::disconnect()`.+- "Copy address" button → `QClipboard`.+- Verification: copy works, disconnect clears state, UI swaps to empty state.++**Task 2.3 — BalanceCard**+- Subscribes `wallet:balance:<pubkey>` and `market:price:fncpt`.+- Shows: SOL (lamports / 1e9), $FNCPT (raw / 10^decimals), USD value.+- Loading skeleton while data arrives. Stale indicator if last update > 60s ago.+- Refresh button → `hub.request(topic, /*force=*/true)`.+- Verification: kill network → cached value stays + stale indicator; restore → updates.++**Task 2.4 — showEvent / hideEvent lifecycle (P3)**+- subscribe in `showEvent`, `unsubscribe(this)` in `hideEvent`.+- No timers in constructors.+- Verification: navigate away → producer goes idle (verify in DataHub introspection log).++**Task 2.5 — Nav registration**+- Add Crypto Center entry under a new nav group "Crypto" (or under Tools, decide in PR review).+- Icon: wallet glyph (use existing icon set or add SVG).+- Verification: nav shows item, click routes to screen, lazy factory triggers first time only.++### Phase 3 — Polish & verification++**Task 3.1 — Reconnect-on-startup flow**+- On app launch, if `SecureStorage` has a pubkey: `WalletService` enters "soft-connected" state (UI shows pubkey + balances), but **no signing trust** — the next operation that needs a signature will trigger a fresh challenge.+- Verification: restart app, see pubkey + balances without re-prompt.++**Task 3.2 — Disconnect hardens**+- Clears `SecureStorage` keys (pubkey, label, connected_at).+- Calls JS `wallet.disconnect()` if bridge available.+- Unsubscribes balance producer for that pubkey (hub auto-cleans on no subscribers).+- Verification: post-disconnect, no producer activity for that pubkey; restart confirms blank state.++**Task 3.3 — Manual security walkthrough**+- Run through every threat in §3, confirm mitigation works.+- Try to spoof a pubkey by sending a fake `delivered()` over the bridge with someone else's pubkey + your signature → must reject.+- Confirm bridge port is loopback-only (`netstat -an | grep <port>` shows `127.0.0.1` only).+- Verification: signed report attached to plan or PR.++**Task 3.4 — Docs**+- Add a short user-facing doc: "How to connect your wallet" (`docs/CRYPTO_WALLET_CONNECT.md`).+- 1-page max, screenshots for Phantom + Solflare.+- Verification: doc renders, links from screen "Help" icon.++---++## 6. Out of scope (do NOT do in this plan)++- Sending or signing transactions+- Buying/swapping $FNCPT (Jupiter integration)+- Burning $FNCPT+- Staking/lock UI+- Prediction markets+- Multi-chain (EVM)+- Direct Ledger USB+- Backup/restore wallet flows (we don't store keys, so n/a)++These have separate plans.++---++## 7. Risks & open questions++1. **QWebEngine binary size**: ~50 MB extra. Acceptable trade for the cleanest path. Confirm with installer pipeline owner.+2. **Bundled `wallet.js`**: needs a Node build step the first time. Check it in pre-built so end-developers don't need Node.+3. **WalletConnect v2 project ID**: requires a free signup at WalletConnect Cloud. Need to register one for "Fincept Terminal" before Task 0.3.+4. **Helius API key**: need to provision and wire through `KeyConfigManager`. Free tier OK initially.+5. **$FNCPT mint cluster**: pump.fun lives on mainnet. Devnet won't have the token — for dev testing, mock the balance producer or fork the mint to devnet.+6. **Coinbase Wallet (Solana mode)**: support via Wallet Adapter is recent; verify it works on the bundled version we ship.++---++## 8. Definition of Done (Phase 1)++- [ ] User opens Crypto Center, sees empty state.+- [ ] Clicks "Connect Wallet" → browser-extension prompt fires (Phantom/Solflare/etc.).+- [ ] After approving, screen shows their pubkey + SOL + $FNCPT balance + USD value.+- [ ] Disconnect works; restart with disconnect persists; restart with connection persists.+- [ ] No private keys, signatures, or seed phrases ever leave Phantom.+- [ ] No `PythonRunner` calls in any new file (D1 enforced).+- [ ] All data flows via DataHub topics (D4 enforced).+- [ ] All topics added to `docs/DATAHUB_TOPICS.md` (D5 enforced).+- [ ] Screen registered with `register_factory()` (P2 enforced).+- [ ] Producers subscribe-only via `showEvent`/`hideEvent` (P3, D3 enforced).+- [ ] CI green, manual security walkthrough signed off.diff --git a/fincept-qt/resources/component_catalog.json b/fincept-qt/resources/component_catalog.jsonindex c29f5070d..5e2ff6ad6 100644--- a/fincept-qt/resources/component_catalog.json+++ b/fincept-qt/resources/component_catalog.json@@ -6,6 +6,7 @@{ "id": "watchlist", "title": "Watchlist", "category": "Core", "description": "Symbol lists with live quotes", "tags": ["watchlist","quotes","symbols"] },{ "id": "news", "title": "News", "category": "Core", "description": "Global news wire with category filters and sentiment", "tags": ["news","wire","headlines"] },+ { "id": "crypto_center", "title": "Crypto Center", "category": "Crypto", "description": "Connect your Solana wallet, view $FNCPT + SOL balances", "tags": ["wallet","solana","fncpt","crypto","balance","phantom"] },{ "id": "crypto_trading", "title": "Crypto Trading", "category": "Trading", "description": "Order entry + real-time book for Kraken / HyperLiquid", "tags": ["crypto","trading","order"] },{ "id": "equity_trading", "title": "Equity Trading", "category": "Trading", "description": "Multi-account equity trading across 16+ brokers", "tags": ["equity","trading","brokers"] },{ "id": "algo_trading", "title": "Algo Trading", "category": "Trading", "description": "Strategy runner, order router, and execution analytics", "tags": ["algo","strategy","execution"] },diff --git a/fincept-qt/resources/wallet/connect.html b/fincept-qt/resources/wallet/connect.htmlnew file mode 100644index 000000000..a85ff45be--- /dev/null+++ b/fincept-qt/resources/wallet/connect.html@@ -0,0 +1,452 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta http-equiv="Content-Security-Policy"+ content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self' http://127.0.0.1:* http://localhost:*; img-src 'self' data:;">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>Fincept — Connect Wallet</title>+ <link rel="icon" href="data:,">+ <style>+ :root {+ color-scheme: dark;+ --bg-base: #080808;+ --bg-surface: #0a0a0a;+ --bg-raised: #111111;+ --bg-hover: #161616;+ --border-dim: #1a1a1a;+ --border-med: #222222;+ --border-bright: #303030;+ --text-primary: #e0e0e0;+ --text-secondary: #999999;+ --text-tertiary: #707070;+ --text-dim: #555555;+ --accent: #d97706;+ --accent-dim: #78350f;+ --accent-bg: rgba(217, 119, 6, 0.08);+ --positive: #10b981;+ --negative: #ef4444;+ --info: #3b82f6;+ --mono: ui-monospace, "SF Mono", "Cascadia Mono", "JetBrains Mono", Consolas, monospace;+ --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", "Inter", Roboto, sans-serif;+ }+ * { box-sizing: border-box; }+ html, body {+ margin: 0; padding: 0; min-height: 100vh;+ background: var(--bg-base);+ color: var(--text-primary);+ font: 13px/1.5 var(--sans);+ display: flex; align-items: center; justify-content: center;+ letter-spacing: 0.01em;+ }+ .panel {+ background: var(--bg-surface);+ border: 1px solid var(--border-dim);+ border-radius: 4px;+ padding: 0;+ max-width: 480px;+ width: calc(100% - 32px);+ box-shadow: 0 8px 24px rgba(0,0,0,0.6);+ overflow: hidden;+ }+ .header {+ padding: 14px 20px;+ border-bottom: 1px solid var(--border-dim);+ background: var(--bg-raised);+ display: flex; align-items: center; gap: 10px;+ }+ .header .brand {+ font-family: var(--mono);+ font-size: 11px;+ letter-spacing: 0.18em;+ color: var(--accent);+ text-transform: uppercase;+ font-weight: 600;+ }+ .header .sep {+ color: var(--border-bright);+ font-family: var(--mono);+ }+ .header .route {+ font-family: var(--mono);+ font-size: 11px;+ color: var(--text-tertiary);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ }+ .body { padding: 20px; }+ h1 {+ font-size: 16px;+ margin: 0 0 6px 0;+ font-weight: 600;+ letter-spacing: 0.005em;+ }+ .lede {+ color: var(--text-secondary);+ font-size: 12px;+ margin: 0 0 18px 0;+ line-height: 1.55;+ }+ .section-label {+ font-family: var(--mono);+ font-size: 10px;+ letter-spacing: 0.2em;+ color: var(--text-tertiary);+ text-transform: uppercase;+ margin: 4px 0 8px 0;+ }+ .wallet-row {+ display: flex; align-items: center; justify-content: space-between;+ padding: 10px 12px;+ border: 1px solid var(--border-dim);+ background: var(--bg-base);+ border-radius: 3px;+ margin-bottom: 6px;+ cursor: pointer;+ transition: border-color 80ms linear, background 80ms linear;+ }+ .wallet-row:hover {+ border-color: var(--accent);+ background: var(--bg-hover);+ }+ .wallet-row.active {+ border-color: var(--accent);+ background: var(--accent-bg);+ }+ .wallet-row[data-disabled="true"] {+ opacity: 0.35; cursor: not-allowed;+ background: transparent;+ }+ .wallet-row[data-disabled="true"]:hover {+ border-color: var(--border-dim);+ background: transparent;+ }+ .wallet-name {+ font-weight: 500;+ font-size: 13px;+ color: var(--text-primary);+ }+ .wallet-status {+ font-family: var(--mono);+ font-size: 10px;+ color: var(--text-tertiary);+ letter-spacing: 0.12em;+ text-transform: uppercase;+ }+ .wallet-status.detected {+ color: var(--positive);+ }+ .wallet-status.detected::before {+ content: "● ";+ }+ .status {+ margin-top: 14px;+ padding: 10px 12px;+ border-radius: 3px;+ background: var(--bg-base);+ border: 1px solid var(--border-dim);+ display: none;+ font-family: var(--mono);+ font-size: 11px;+ line-height: 1.5;+ word-break: break-all;+ color: var(--text-secondary);+ }+ .status.show { display: block; }+ .status.error {+ border-color: var(--negative);+ color: var(--negative);+ background: rgba(239, 68, 68, 0.04);+ }+ .status.success {+ border-color: var(--positive);+ color: var(--positive);+ background: rgba(16, 185, 129, 0.04);+ }+ .status.working {+ border-color: var(--accent);+ color: var(--accent);+ background: var(--accent-bg);+ }+ .footer {+ margin-top: 18px;+ padding-top: 14px;+ border-top: 1px solid var(--border-dim);+ font-family: var(--mono);+ font-size: 10px;+ color: var(--text-dim);+ letter-spacing: 0.06em;+ line-height: 1.6;+ }+ .footer .key {+ color: var(--text-tertiary);+ }+ .pulse {+ display: inline-block;+ width: 6px; height: 6px;+ border-radius: 50%;+ background: var(--accent);+ margin-right: 6px;+ animation: pulse 1.4s ease-in-out infinite;+ }+ @keyframes pulse {+ 0%, 100% { opacity: 0.4; }+ 50% { opacity: 1; }+ }+ </style>+</head>+<body>+ <main class="panel">+ <div class="header">+ <span class="brand">Fincept Terminal</span>+ <span class="sep">/</span>+ <span class="route">Crypto Center</span>+ </div>+ <div class="body">+ <h1>Connect your Solana wallet</h1>+ <p class="lede">+ Fincept Terminal will read your wallet's public address and balances only.+ Your private keys never leave your wallet.+ </p>++ <div class="section-label">Available wallets</div>+ <div id="wallet-list">+ <div class="wallet-row" data-provider="phantom">+ <span class="wallet-name">Phantom</span>+ <span class="wallet-status">checking…</span>+ </div>+ <div class="wallet-row" data-provider="solflare">+ <span class="wallet-name">Solflare</span>+ <span class="wallet-status">checking…</span>+ </div>+ <div class="wallet-row" data-provider="backpack">+ <span class="wallet-name">Backpack</span>+ <span class="wallet-status">checking…</span>+ </div>+ <div class="wallet-row" data-provider="glow">+ <span class="wallet-name">Glow</span>+ <span class="wallet-status">checking…</span>+ </div>+ <div class="wallet-row" data-provider="generic">+ <span class="wallet-name">Other (window.solana)</span>+ <span class="wallet-status">checking…</span>+ </div>+ </div>++ <div id="status" class="status"></div>++ <div class="footer">+ <span class="key">SECURITY</span> · keys never leave your wallet ·+ <span class="key">SCOPE</span> · public address + balance only ·+ <span class="key">SESSION</span> · close this tab when done+ </div>+ </div>+ </main>++ <script>+ (function() {+ "use strict";++ var NONCE_HEX = "__NONCE_HEX__";+ var TOKEN = "__CALLBACK_TOKEN__";++ function logToTerminal(level, msg) {+ try {+ fetch("/log?token=" + encodeURIComponent(TOKEN), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ level: level, msg: String(msg) })+ }).catch(function() {});+ } catch (_) {}+ if (level === "error") console.error("[FinceptWallet]", msg);+ else if (level === "warn") console.warn("[FinceptWallet]", msg);+ else console.log("[FinceptWallet]", msg);+ }+ window.addEventListener("error", function(e) {+ logToTerminal("error", "uncaught: " + (e && e.message));+ });+ window.addEventListener("unhandledrejection", function(e) {+ logToTerminal("error", "unhandled rejection: " ++ (e && e.reason && e.reason.message ? e.reason.message : String(e && e.reason)));+ });+ logToTerminal("info", "connect.html loaded; nonce_len=" + NONCE_HEX.length + " token_len=" + TOKEN.length);++ function statusBox(text, kind) {+ var el = document.getElementById("status");+ el.textContent = text;+ el.className = "status show" + (kind ? " " + kind : "");+ }+ function statusWorking(text) {+ var el = document.getElementById("status");+ el.innerHTML = "<span class=\"pulse\"></span>" + text;+ el.className = "status show working";+ }++ // ── Base58 (Bitcoin alphabet) ─────────────────────────────────────────+ // Reference algorithm from the bitcoin core / bs58 package, transcribed+ // for the browser. Avoids the "Invalid array length" overflow that+ // happens with the naive worst-case allocation when the input contains+ // the unusual leading-bytes that pump.fun signatures occasionally have.+ var B58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";++ function b58encode(bytes) {+ if (!(bytes instanceof Uint8Array)) bytes = new Uint8Array(bytes);+ if (bytes.length === 0) return "";+ // Count leading zeros.+ var zeros = 0;+ while (zeros < bytes.length && bytes[zeros] === 0) zeros++;++ // Convert base-256 digits to base-58 digits using big-int free arithmetic.+ // Worst case: ceil(N * log(256)/log(58)) ~ N * 1.366 bytes.+ var size = ((bytes.length - zeros) * 138 / 100 | 0) + 1;+ var b58 = new Uint8Array(size);+ var length = 0;++ for (var i = zeros; i < bytes.length; i++) {+ var carry = bytes[i];+ var j = 0;+ // Apply "carry" to the entire b58 array, working from right to left.+ for (var k = size - 1; (carry !== 0 || j < length) && k >= 0; k--, j++) {+ carry += 256 * b58[k];+ b58[k] = carry % 58;+ carry = (carry / 58) | 0;+ }+ if (carry !== 0) {+ throw new Error("base58 encode: non-zero carry");+ }+ length = j;+ }++ // Skip leading zeros in b58 result.+ var it = size - length;+ while (it < size && b58[it] === 0) it++;++ var str = "";+ for (var z = 0; z < zeros; z++) str += "1";+ for (; it < size; it++) str += B58_ALPHABET.charAt(b58[it]);+ return str;+ }++ function resolveProvider(name) {+ switch (name) {+ case "phantom":+ return (window.phantom && window.phantom.solana && window.phantom.solana.isPhantom)+ ? window.phantom.solana : null;+ case "solflare":+ return (window.solflare && window.solflare.isSolflare) ? window.solflare : null;+ case "backpack":+ return (window.backpack && window.backpack.isBackpack) ? window.backpack : null;+ case "glow":+ return (window.glowSolana || (window.glow && window.glow.solana)) || null;+ case "generic":+ return (window.solana && typeof window.solana.connect === "function")+ ? window.solana : null;+ }+ return null;+ }++ var connecting = false;+ function refreshDetections() {+ var rows = document.querySelectorAll(".wallet-row");+ rows.forEach(function(row) {+ var name = row.getAttribute("data-provider");+ var provider = resolveProvider(name);+ var statusEl = row.querySelector(".wallet-status");+ if (provider) {+ statusEl.textContent = "detected";+ statusEl.classList.add("detected");+ row.setAttribute("data-disabled", "false");+ row.onclick = function() { if (!connecting) connect(name, provider, row); };+ } else {+ statusEl.textContent = "not installed";+ statusEl.classList.remove("detected");+ row.setAttribute("data-disabled", "true");+ row.onclick = null;+ }+ });+ }++ async function connect(name, provider, rowEl) {+ try {+ connecting = true;+ document.querySelectorAll(".wallet-row").forEach(function(r) { r.classList.remove("active"); });+ if (rowEl) rowEl.classList.add("active");++ logToTerminal("info", "connect() start for " + name);+ statusWorking("Requesting wallet authorisation…");++ var conn = await provider.connect();+ logToTerminal("info", "provider.connect() returned");+ var pubkey = (conn && conn.publicKey) ? conn.publicKey : provider.publicKey;+ if (!pubkey) throw new Error("wallet did not return a public key");+ var pubkeyB58 = (typeof pubkey.toBase58 === "function")+ ? pubkey.toBase58()+ : (typeof pubkey === "string" ? pubkey : "");+ if (!pubkeyB58) throw new Error("could not stringify public key");+ logToTerminal("info", "got pubkey " + pubkeyB58);++ statusWorking("Please sign the verification message in your wallet…");+ var message = new TextEncoder().encode(+ "Fincept Terminal wallet-connect challenge. Nonce: " + NONCE_HEX);+ logToTerminal("info", "calling signMessage (" + message.length + " bytes)");+ var signed = await provider.signMessage(message, "utf8");+ logToTerminal("info", "signMessage resolved; type=" ++ (signed && signed.constructor && signed.constructor.name));++ var sigBytes = (signed && signed.signature) ? signed.signature : signed;+ if (!sigBytes) throw new Error("wallet returned no signature field");+ if (!(sigBytes instanceof Uint8Array)) {+ if (Array.isArray(sigBytes)) {+ sigBytes = new Uint8Array(sigBytes);+ } else if (typeof sigBytes === "object" && typeof sigBytes.length === "number") {+ sigBytes = new Uint8Array(Array.from(sigBytes));+ } else if (sigBytes && typeof sigBytes === "object") {+ // ArrayBuffer-like+ try { sigBytes = new Uint8Array(sigBytes); }+ catch (e) { throw new Error("could not coerce signature to bytes: " + e.message); }+ } else {+ throw new Error("unexpected signature type");+ }+ }+ logToTerminal("info", "signature bytes len=" + sigBytes.length);+ if (sigBytes.length !== 64) {+ logToTerminal("warn", "unexpected signature length " + sigBytes.length + " (expected 64)");+ }+ var sigB58;+ try {+ sigB58 = b58encode(sigBytes);+ } catch (e) {+ throw new Error("base58 encode failed: " + e.message);+ }+ logToTerminal("info", "POST /callback (sig_b58_len=" + sigB58.length + ")");++ var resp = await fetch("/callback?token=" + encodeURIComponent(TOKEN), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ pubkey: pubkeyB58,+ signature: sigB58,+ label: name+ })+ });+ logToTerminal("info", "callback POST done; status=" + resp.status);+ if (!resp.ok) {+ throw new Error("server returned " + resp.status);+ }+ statusBox("Connected. You may close this tab.", "success");+ } catch (err) {+ var msg = (err && err.message) ? err.message : String(err);+ logToTerminal("error", "connect() failed: " + msg);+ statusBox("Connect failed: " + msg, "error");+ connecting = false;+ if (rowEl) rowEl.classList.remove("active");+ }+ }++ refreshDetections();+ setTimeout(refreshDetections, 500);+ setTimeout(refreshDetections, 1500);+ })();+ </script>+</body>+</html>diff --git a/fincept-qt/resources/wallet/swap.html b/fincept-qt/resources/wallet/swap.htmlnew file mode 100644index 000000000..713a3b7de--- /dev/null+++ b/fincept-qt/resources/wallet/swap.html@@ -0,0 +1,336 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta http-equiv="Content-Security-Policy"+ content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self' http://127.0.0.1:* http://localhost:*; img-src 'self' data:;">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>Fincept — Sign Transaction</title>+ <link rel="icon" href="data:,">+ <!-- Vendored @solana/web3.js UMD bundle. If missing, the page degrades to+ a base64 passthrough that some wallets accept directly. See+ resources/wallet/vendor/README.md. -->+ <script src="vendor/web3.js"></script>+ <style>+ :root {+ color-scheme: dark;+ --bg-base: #080808;+ --bg-surface: #0a0a0a;+ --bg-raised: #111111;+ --bg-hover: #161616;+ --border-dim: #1a1a1a;+ --border-med: #222222;+ --border-bright: #303030;+ --text-primary: #e0e0e0;+ --text-secondary: #999999;+ --text-tertiary: #707070;+ --accent: #d97706;+ --accent-bg: rgba(217, 119, 6, 0.08);+ --positive: #10b981;+ --negative: #ef4444;+ --mono: ui-monospace, "SF Mono", "Cascadia Mono", "JetBrains Mono", Consolas, monospace;+ --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", "Inter", Roboto, sans-serif;+ }+ * { box-sizing: border-box; }+ html, body {+ margin: 0; padding: 0; min-height: 100vh;+ background: var(--bg-base);+ color: var(--text-primary);+ font: 13px/1.5 var(--sans);+ display: flex; align-items: center; justify-content: center;+ }+ .panel {+ background: var(--bg-surface);+ border: 1px solid var(--border-dim);+ max-width: 480px;+ width: calc(100% - 32px);+ box-shadow: 0 8px 24px rgba(0,0,0,0.6);+ overflow: hidden;+ }+ .header {+ padding: 14px 20px;+ border-bottom: 1px solid var(--border-dim);+ background: var(--bg-raised);+ display: flex; align-items: center; gap: 10px;+ }+ .header .brand {+ font-family: var(--mono);+ font-size: 11px;+ letter-spacing: 0.18em;+ color: var(--accent);+ text-transform: uppercase;+ font-weight: 600;+ }+ .header .sep { color: var(--border-bright); font-family: var(--mono); }+ .header .route {+ font-family: var(--mono);+ font-size: 11px;+ color: var(--text-tertiary);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ }+ .body { padding: 22px 20px 20px 20px; }+ h1 { font-size: 15px; margin: 0 0 8px 0; font-weight: 600; }+ p { color: var(--text-secondary); margin: 8px 0; }+ .wallet-row {+ display: flex; align-items: center; justify-content: space-between;+ padding: 12px 14px;+ border: 1px solid var(--border-dim);+ background: var(--bg-raised);+ margin-bottom: 6px;+ cursor: pointer;+ font-family: var(--mono);+ font-size: 12px;+ letter-spacing: 0.05em;+ transition: background 0.1s, border-color 0.1s;+ }+ .wallet-row:hover { background: var(--bg-hover); border-color: var(--border-bright); }+ .wallet-row.disabled { opacity: 0.4; cursor: not-allowed; }+ .wallet-row .name { color: var(--text-primary); text-transform: uppercase; }+ .wallet-row .status { color: var(--text-tertiary); font-size: 10px; }+ .status-line {+ margin-top: 14px;+ padding: 10px 12px;+ background: var(--bg-raised);+ border: 1px solid var(--border-dim);+ font-family: var(--mono);+ font-size: 11px;+ color: var(--text-secondary);+ min-height: 32px;+ }+ .status-line.error { color: var(--negative); border-color: var(--negative); background: rgba(239, 68, 68, 0.08); }+ .status-line.ok { color: var(--positive); border-color: var(--positive); background: rgba(16, 185, 129, 0.08); }+ </style>+</head>+<body>+ <div class="panel">+ <div class="header">+ <span class="brand">FINCEPT</span>+ <span class="sep">/</span>+ <span class="route">SIGN TRANSACTION</span>+ </div>+ <div class="body">+ <h1>Sign and forward to the network</h1>+ <p>The terminal has built a transaction and is waiting for your wallet to+ approve it. Click the wallet you want to use; the wallet will pop up+ with the decoded transaction. <b>You sign in the wallet, not in the+ terminal — your private key never leaves the wallet.</b></p>++ <div id="walletList">+ <div class="wallet-row" data-provider="phantom">+ <span class="name">Phantom</span>+ <span class="status">checking…</span>+ </div>+ <div class="wallet-row" data-provider="solflare">+ <span class="name">Solflare</span>+ <span class="status">checking…</span>+ </div>+ <div class="wallet-row" data-provider="backpack">+ <span class="name">Backpack</span>+ <span class="status">checking…</span>+ </div>+ <div class="wallet-row" data-provider="glow">+ <span class="name">Glow</span>+ <span class="status">checking…</span>+ </div>+ </div>++ <div id="status" class="status-line">Loading transaction body from local bridge…</div>+ </div>+ </div>++<script>+(function() {+ "use strict";++ // ── URL params ──────────────────────────────────────────────────────────+ const params = new URLSearchParams(window.location.search);+ const req = params.get("req");+ const token = params.get("token");+ const baseUrl = window.location.origin;++ // ── Diagnostic logging ─────────────────────────────────────────────────+ function logToTerminal(level, msg) {+ try {+ fetch(baseUrl + "/log?token=" + encodeURIComponent(token), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ level: level, msg: msg })+ }).catch(function() {});+ } catch (e) {}+ }++ // ── DOM helpers ────────────────────────────────────────────────────────+ function setStatus(text, kind) {+ const el = document.getElementById("status");+ el.textContent = text;+ el.className = "status-line" + (kind ? (" " + kind) : "");+ }++ // ── Provider resolution (mirrors connect.html) ─────────────────────────+ function resolveProvider(name) {+ switch (name) {+ case "phantom":+ return (window.phantom && window.phantom.solana && window.phantom.solana.isPhantom)+ ? window.phantom.solana : null;+ case "solflare":+ return (window.solflare && window.solflare.isSolflare) ? window.solflare : null;+ case "backpack":+ return (window.backpack && window.backpack.isBackpack) ? window.backpack : null;+ case "glow":+ return (window.glow && window.glow.isGlow) ? window.glow : null;+ default:+ return null;+ }+ }++ function refreshAvailability() {+ const rows = document.querySelectorAll(".wallet-row");+ rows.forEach(function(row) {+ const name = row.getAttribute("data-provider");+ const provider = resolveProvider(name);+ const status = row.querySelector(".status");+ if (provider) {+ status.textContent = "available";+ row.classList.remove("disabled");+ } else {+ status.textContent = "not detected";+ row.classList.add("disabled");+ }+ });+ }++ // ── Base64 helpers (no dependency on web3.js) ──────────────────────────+ function base64ToBytes(b64) {+ const bin = atob(b64);+ const out = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; ++i) out[i] = bin.charCodeAt(i);+ return out;+ }+ function bytesToBase64(bytes) {+ let s = "";+ for (let i = 0; i < bytes.length; ++i) s += String.fromCharCode(bytes[i]);+ return btoa(s);+ }++ // ── Transaction body fetch ─────────────────────────────────────────────+ let txBase64 = null;+ async function fetchTxBody() {+ try {+ const r = await fetch(baseUrl + "/tx?req=" + encodeURIComponent(req)+ + "&token=" + encodeURIComponent(token));+ if (!r.ok) throw new Error("/tx returned " + r.status);+ const j = await r.json();+ txBase64 = j.tx_base64;+ if (!txBase64) throw new Error("missing tx_base64");+ logToTerminal("info", "tx body received (" + txBase64.length + " b64 chars)");+ setStatus("Transaction loaded. Pick a wallet to sign.");+ } catch (e) {+ const msg = (e && e.message) ? e.message : String(e);+ logToTerminal("error", "tx fetch failed: " + msg);+ setStatus("Could not load transaction: " + msg, "error");+ }+ }++ // ── Result delivery ────────────────────────────────────────────────────+ async function postResult(payload) {+ try {+ await fetch(baseUrl + "/result?req=" + encodeURIComponent(req)+ + "&token=" + encodeURIComponent(token), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload)+ });+ } catch (e) {+ logToTerminal("error", "result delivery failed: " + e);+ }+ }++ // ── Sign + send via the chosen wallet ──────────────────────────────────+ let signing = false;+ async function signWith(name, provider) {+ if (signing) return;+ if (!txBase64) {+ setStatus("Transaction not loaded yet.", "error");+ return;+ }+ signing = true;+ setStatus("Connecting to " + name + " — approve in the wallet popup…");+ try {+ // Connect first; many wallets require this even when already authorised.+ try { await provider.connect({ onlyIfTrusted: false }); } catch (e) {+ logToTerminal("warn", "connect threw (continuing): " + e);+ }+ const txBytes = base64ToBytes(txBase64);++ let signature = null;+ // Preferred path: deserialize via vendored web3.js, then signAndSendTransaction.+ if (window.solanaWeb3 && window.solanaWeb3.VersionedTransaction) {+ const tx = window.solanaWeb3.VersionedTransaction.deserialize(txBytes);+ if (typeof provider.signAndSendTransaction === "function") {+ const r = await provider.signAndSendTransaction(tx);+ signature = (r && r.signature) ? r.signature : r;+ logToTerminal("info", "signAndSendTransaction returned");+ } else if (typeof provider.signTransaction === "function") {+ // Some wallets only signTransaction — caller forwards via RPC.+ const signed = await provider.signTransaction(tx);+ const serialised = signed.serialize();+ signature = "BYTES:" + bytesToBase64(serialised);+ logToTerminal("info", "signTransaction returned signed bytes");+ } else {+ throw new Error("wallet exposes neither signAndSendTransaction nor signTransaction");+ }+ } else {+ // Degraded path: web3.js missing. Try the raw base64 passthrough.+ if (typeof provider.signAndSendTransactionRaw === "function") {+ const r = await provider.signAndSendTransactionRaw(txBytes);+ signature = (r && r.signature) ? r.signature : r;+ logToTerminal("warn", "fallback signAndSendTransactionRaw used (web3.js missing)");+ } else {+ throw new Error("vendored @solana/web3.js missing — see resources/wallet/vendor/README.md");+ }+ }++ if (!signature) throw new Error("wallet returned empty signature");+ setStatus("Submitted. Closing window…", "ok");+ await postResult({ signature: signature });+ setTimeout(function() { try { window.close(); } catch (e) {} }, 800);+ } catch (e) {+ const msg = (e && e.message) ? e.message : String(e);+ logToTerminal("error", "sign failed: " + msg);+ setStatus("Sign failed: " + msg, "error");+ await postResult({ error: msg });+ signing = false;+ }+ }++ // ── Wire up rows ───────────────────────────────────────────────────────+ function wireRows() {+ document.querySelectorAll(".wallet-row").forEach(function(row) {+ const name = row.getAttribute("data-provider");+ row.addEventListener("click", function() {+ if (row.classList.contains("disabled")) return;+ const provider = resolveProvider(name);+ if (!provider) return;+ signWith(name, provider);+ });+ });+ }++ // ── Bootstrap ──────────────────────────────────────────────────────────+ if (!req || !token) {+ setStatus("Missing req/token in URL — open this page through the terminal.",+ "error");+ return;+ }+ refreshAvailability();+ wireRows();+ fetchTxBody();+ // Re-check provider availability after extensions inject — they sometimes+ // arrive after the initial load.+ setTimeout(refreshAvailability, 500);+ setTimeout(refreshAvailability, 1500);+})();+</script>+</body>+</html>diff --git a/fincept-qt/resources/wallet/vendor/README.md b/fincept-qt/resources/wallet/vendor/README.mdnew file mode 100644index 000000000..db88ef575--- /dev/null+++ b/fincept-qt/resources/wallet/vendor/README.md@@ -0,0 +1,49 @@+# Wallet HTML — vendored libraries++This directory holds third-party JavaScript bundles that the wallet HTML pages+embed at load time. Everything here is **vendored** — committed verbatim into+the repository, served from `qrc://`, never fetched at runtime.++## Why vendored++The wallet pages run inside a `QWebEngineView` with a strict CSP+(`connect-src 'self'`). A network-loaded library would either require+relaxing the CSP or running our own loader proxy. Both options enlarge the+attack surface; vendoring the exact bytes we ship is simpler.++## Required files++### `web3.js` — `@solana/web3.js` UMD bundle++- **Origin:** https://github.com/solana-labs/solana-web3.js (releases page)+- **Version expected:** 1.95.x (latest 1.x stable as of Phase 2 plan)+- **Filename in this directory:** `web3.js`+- **Approximate size:** ~150 KB minified+- **Module exposure:** the UMD build defines `window.solanaWeb3` globally; that's+ the entry point our HTML uses.++### How to refresh the bundle++1. Download the official UMD release from the GitHub releases page (e.g.+ `https://github.com/solana-labs/solana-web3.js/releases/download/v1.95.X/solana-web3.iife.js`).+2. Copy it into this directory as `web3.js`.+3. Verify with `sha256sum web3.js`; record the hash + version + date in the+ table below before committing.+4. Update the wallet HTML's CSP if any new origins are required (none should+ be — the bundle is self-contained).++## Version log++| Date | web3.js version | sha256 |+|---|---|---|+| 2026-04-28 | 1.95.8 (IIFE minified, via unpkg) | `a759deca1b65df140e8dda5ad8645c19579536bf822e5c0c7e4adb7793a5bd08` |++## What this directory is NOT++- Not a place to fetch from a CDN at runtime.+- Not a place to run `npm install`.+- Not a place for compiled TypeScript output (we host pre-built bundles only).++If you need a library that doesn't ship a hand-buildable UMD bundle, talk to+the wallet-bridge owner first — adding a Node-build dependency to the Qt+project is a serious decision.diff --git a/fincept-qt/resources/wallet/vendor/web3.js b/fincept-qt/resources/wallet/vendor/web3.jsnew file mode 100644index 000000000..d3c3c204e--- /dev/null+++ b/fincept-qt/resources/wallet/vendor/web3.js@@ -0,0 +1,20 @@+var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x["default"]:x}function getAugmentedNamespace(n){if(n.__esModule)return n;var f=n.default;if(typeof f=="function"){var a=function a(){if(this instanceof a){return Reflect.construct(f,arguments,this.constructor)}return f.apply(this,arguments)};a.prototype=f.prototype}else a={};Object.defineProperty(a,"__esModule",{value:true});Object.keys(n).forEach((function(k){var d=Object.getOwnPropertyDescriptor(n,k);Object.defineProperty(a,k,d.get?d:{enumerable:true,get:function(){return n[k]}})}));return a}var buffer={};var base64Js={};var hasRequiredBase64Js;function requireBase64Js(){if(hasRequiredBase64Js)return base64Js;hasRequiredBase64Js=1;base64Js.byteLength=byteLength;base64Js.toByteArray=toByteArray;base64Js.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i<len;++i){lookup[i]=code[i];revLookup[code.charCodeAt(i)]=i}revLookup["-".charCodeAt(0)]=62;revLookup["_".charCodeAt(0)]=63;function getLens(b64){var len=b64.length;if(len%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var validLen=b64.indexOf("=");if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i<len;i+=4){tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)];arr[curByte++]=tmp>>16&255;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&255}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;i<end;i+=3){tmp=(uint8[i]<<16&16711680)+(uint8[i+1]<<8&65280)+(uint8[i+2]&255);output.push(tripletToBase64(tmp))}return output.join("")}function fromByteArray(uint8){var tmp;var len=uint8.length;var extraBytes=len%3;var parts=[];var maxChunkLength=16383;for(var i=0,len2=len-extraBytes;i<len2;i+=maxChunkLength){parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")}return parts.join("")}return base64Js}var ieee754={};+/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */var hasRequiredIeee754;function requireIeee754(){if(hasRequiredIeee754)return ieee754;hasRequiredIeee754=1;ieee754.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};ieee754.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128};return ieee754}+/*!+ * The buffer module from node.js, for the browser.+ *+ * @author Feross Aboukhadijeh <https://feross.org>+ * @license MIT+ */var hasRequiredBuffer;function requireBuffer(){if(hasRequiredBuffer)return buffer;hasRequiredBuffer=1;(function(exports){const base64=requireBase64Js();const ieee754=requireIeee754();const customInspectSymbol=typeof Symbol==="function"&&typeof Symbol["for"]==="function"?Symbol["for"]("nodejs.util.inspect.custom"):null;exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;const K_MAX_LENGTH=2147483647;exports.kMaxLength=K_MAX_LENGTH;Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport();if(!Buffer.TYPED_ARRAY_SUPPORT&&typeof console!=="undefined"&&typeof console.error==="function"){console.error("This browser lacks typed array (Uint8Array) support which is required by "+"`buffer` v5.x. Use `buffer` v4.x if you require old browser support.")}function typedArraySupport(){try{const arr=new Uint8Array(1);const proto={foo:function(){return 42}};Object.setPrototypeOf(proto,Uint8Array.prototype);Object.setPrototypeOf(arr,proto);return arr.foo()===42}catch(e){return false}}Object.defineProperty(Buffer.prototype,"parent",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.buffer}});Object.defineProperty(Buffer.prototype,"offset",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.byteOffset}});function createBuffer(length){if(length>K_MAX_LENGTH){throw new RangeError('The value "'+length+'" is invalid for option "size"')}const buf=new Uint8Array(length);Object.setPrototypeOf(buf,Buffer.prototype);return buf}function Buffer(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new TypeError('The "string" argument must be of type string. Received type number')}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}Buffer.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="string"){return fromString(value,encodingOrOffset)}if(ArrayBuffer.isView(value)){return fromArrayView(value)}if(value==null){throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof SharedArrayBuffer!=="undefined"&&(isInstance(value,SharedArrayBuffer)||value&&isInstance(value.buffer,SharedArrayBuffer))){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('The "value" argument must not be of type number. Received type number')}const valueOf=value.valueOf&&value.valueOf();if(valueOf!=null&&valueOf!==value){return Buffer.from(valueOf,encodingOrOffset,length)}const b=fromObject(value);if(b)return b;if(typeof Symbol!=="undefined"&&Symbol.toPrimitive!=null&&typeof value[Symbol.toPrimitive]==="function"){return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length)}throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Object.setPrototypeOf(Buffer.prototype,Uint8Array.prototype);Object.setPrototypeOf(Buffer,Uint8Array);function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be of type number')}else if(size<0){throw new RangeError('The value "'+size+'" is invalid for option "size"')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==undefined){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer.allocUnsafe=function(size){return allocUnsafe(size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}const length=byteLength(string,encoding)|0;let buf=createBuffer(length);const actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){const length=array.length<0?0:checked(array.length)|0;const buf=createBuffer(length);for(let i=0;i<length;i+=1){buf[i]=array[i]&255}return buf}function fromArrayView(arrayView){if(isInstance(arrayView,Uint8Array)){const copy=new Uint8Array(arrayView);return fromArrayBuffer(copy.buffer,copy.byteOffset,copy.byteLength)}return fromArrayLike(arrayView)}function fromArrayBuffer(array,byteOffset,length){if(byteOffset<0||array.byteLength<byteOffset){throw new RangeError('"offset" is outside of buffer bounds')}if(array.byteLength<byteOffset+(length||0)){throw new RangeError('"length" is outside of buffer bounds')}let buf;if(byteOffset===undefined&&length===undefined){buf=new Uint8Array(array)}else if(length===undefined){buf=new Uint8Array(array,byteOffset)}else{buf=new Uint8Array(array,byteOffset,length)}Object.setPrototypeOf(buf,Buffer.prototype);return buf}function fromObject(obj){if(Buffer.isBuffer(obj)){const len=checked(obj.length)|0;const buf=createBuffer(len);if(buf.length===0){return buf}obj.copy(buf,0,0,len);return buf}if(obj.length!==undefined){if(typeof obj.length!=="number"||numberIsNaN(obj.length)){return createBuffer(0)}return fromArrayLike(obj)}if(obj.type==="Buffer"&&Array.isArray(obj.data)){return fromArrayLike(obj.data)}}function checked(length){if(length>=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true&&b!==Buffer.prototype};Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array))a=Buffer.from(a,a.offset,a.byteLength);if(isInstance(b,Uint8Array))b=Buffer.from(b,b.offset,b.byteLength);if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array')}if(a===b)return 0;let x=a.length;let y=b.length;for(let i=0,len=Math.min(x,y);i<len;++i){if(a[i]!==b[i]){x=a[i];y=b[i];break}}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function concat(list,length){if(!Array.isArray(list)){throw new TypeError('"list" argument must be an Array of Buffers')}if(list.length===0){return Buffer.alloc(0)}let i;if(length===undefined){length=0;for(i=0;i<list.length;++i){length+=list[i].length}}const buffer=Buffer.allocUnsafe(length);let pos=0;for(i=0;i<list.length;++i){let buf=list[i];if(isInstance(buf,Uint8Array)){if(pos+buf.length>buffer.length){if(!Buffer.isBuffer(buf))buf=Buffer.from(buf);buf.copy(buffer,pos)}else{Uint8Array.prototype.set.call(buffer,buf,pos)}}else if(!Buffer.isBuffer(buf)){throw new TypeError('"list" argument must be an Array of Buffers')}else{buf.copy(buffer,pos)}pos+=buf.length}return buffer};function byteLength(string,encoding){if(Buffer.isBuffer(string)){return string.length}if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer)){return string.byteLength}if(typeof string!=="string"){throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. '+"Received type "+typeof string)}const len=string.length;const mustMatch=arguments.length>2&&arguments[2]===true;if(!mustMatch&&len===0)return 0;let loweredCase=false;for(;;){switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return len*2;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase){return mustMatch?-1:utf8ToBytes(string).length}encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){let loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){const i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){const len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(let i=0;i<len;i+=2){swap(this,i,i+1)}return this};Buffer.prototype.swap32=function swap32(){const len=this.length;if(len%4!==0){throw new RangeError("Buffer size must be a multiple of 32-bits")}for(let i=0;i<len;i+=4){swap(this,i,i+3);swap(this,i+1,i+2)}return this};Buffer.prototype.swap64=function swap64(){const len=this.length;if(len%8!==0){throw new RangeError("Buffer size must be a multiple of 64-bits")}for(let i=0;i<len;i+=8){swap(this,i,i+7);swap(this,i+1,i+6);swap(this,i+2,i+5);swap(this,i+3,i+4)}return this};Buffer.prototype.toString=function toString(){const length=this.length;if(length===0)return"";if(arguments.length===0)return utf8Slice(this,0,length);return slowToString.apply(this,arguments)};Buffer.prototype.toLocaleString=Buffer.prototype.toString;Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return true;return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function inspect(){let str="";const max=exports.INSPECT_MAX_BYTES;str=this.toString("hex",0,max).replace(/(.{2})/g,"$1 ").trim();if(this.length>max)str+=" ... ";return"<Buffer "+str+">"};if(customInspectSymbol){Buffer.prototype[customInspectSymbol]=Buffer.prototype.inspect}Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)){target=Buffer.from(target,target.offset,target.byteLength)}if(!Buffer.isBuffer(target)){throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. '+"Received type "+typeof target)}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;let x=thisEnd-thisStart;let y=end-start;const len=Math.min(x,y);const thisCopy=this.slice(thisStart,thisEnd);const targetCopy=target.slice(start,end);for(let i=0;i<len;++i){if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i];y=targetCopy[i];break}}if(x<y)return-1;if(y<x)return 1;return 0};function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(buffer.length===0)return-1;if(typeof byteOffset==="string"){encoding=byteOffset;byteOffset=0}else if(byteOffset>2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){let indexSize=1;let arrLength=arr.length;let valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}let i;if(dir){let foundIndex=-1;for(i=byteOffset;i<arrLength;i++){if(read(arr,i)===read(val,foundIndex===-1?0:i-foundIndex)){if(foundIndex===-1)foundIndex=i;if(i-foundIndex+1===valLength)return foundIndex*indexSize}else{if(foundIndex!==-1)i-=i-foundIndex;foundIndex=-1}}}else{if(byteOffset+valLength>arrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){let found=true;for(let j=0;j<valLength;j++){if(read(arr,i+j)!==read(val,j)){found=false;break}}if(found)return i}}return-1}Buffer.prototype.includes=function includes(val,byteOffset,encoding){return this.indexOf(val,byteOffset,encoding)!==-1};Buffer.prototype.indexOf=function indexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,true)};Buffer.prototype.lastIndexOf=function lastIndexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,false)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;const remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}const strLen=string.length;if(length>strLen/2){length=strLen/2}let i;for(i=0;i<length;++i){const parsed=parseInt(string.substr(i*2,2),16);if(numberIsNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}Buffer.prototype.write=function write(string,offset,length,encoding){if(offset===undefined){encoding="utf8";length=this.length;offset=0}else if(length===undefined&&typeof offset==="string"){encoding=offset;length=this.length;offset=0}else if(isFinite(offset)){offset=offset>>>0;if(isFinite(length)){length=length>>>0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}const remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";let loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":case"latin1":case"binary":return asciiWrite(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);const res=[];let i=start;while(i<end){const firstByte=buf[i];let codePoint=null;let bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){let secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}const MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){const len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}let res="";let i=0;while(i<len){res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH))}return res}function asciiSlice(buf,start,end){let ret="";end=Math.min(buf.length,end);for(let i=start;i<end;++i){ret+=String.fromCharCode(buf[i]&127)}return ret}function latin1Slice(buf,start,end){let ret="";end=Math.min(buf.length,end);for(let i=start;i<end;++i){ret+=String.fromCharCode(buf[i])}return ret}function hexSlice(buf,start,end){const len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;let out="";for(let i=start;i<end;++i){out+=hexSliceLookupTable[buf[i]]}return out}function utf16leSlice(buf,start,end){const bytes=buf.slice(start,end);let res="";for(let i=0;i<bytes.length-1;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function slice(start,end){const len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;const newBuf=this.subarray(start,end);Object.setPrototypeOf(newBuf,Buffer.prototype);return newBuf};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUintLE=Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);let val=this[offset];let mul=1;let i=0;while(++i<byteLength&&(mul*=256)){val+=this[offset+i]*mul}return val};Buffer.prototype.readUintBE=Buffer.prototype.readUIntBE=function readUIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){checkOffset(offset,byteLength,this.length)}let val=this[offset+--byteLength];let mul=1;while(byteLength>0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readBigUInt64LE=defineBigIntMethod((function readBigUInt64LE(offset){offset=offset>>>0;validateNumber(offset,"offset");const first=this[offset];const last=this[offset+7];if(first===undefined||last===undefined){boundsError(offset,this.length-8)}const lo=first+this[++offset]*2**8+this[++offset]*2**16+this[++offset]*2**24;const hi=this[++offset]+this[++offset]*2**8+this[++offset]*2**16+last*2**24;return BigInt(lo)+(BigInt(hi)<<BigInt(32))}));Buffer.prototype.readBigUInt64BE=defineBigIntMethod((function readBigUInt64BE(offset){offset=offset>>>0;validateNumber(offset,"offset");const first=this[offset];const last=this[offset+7];if(first===undefined||last===undefined){boundsError(offset,this.length-8)}const hi=first*2**24+this[++offset]*2**16+this[++offset]*2**8+this[++offset];const lo=this[++offset]*2**24+this[++offset]*2**16+this[++offset]*2**8+last;return(BigInt(hi)<<BigInt(32))+BigInt(lo)}));Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);let val=this[offset];let mul=1;let i=0;while(++i<byteLength&&(mul*=256)){val+=this[offset+i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);let i=byteLength;let mul=1;let val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);const val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);const val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readBigInt64LE=defineBigIntMethod((function readBigInt64LE(offset){offset=offset>>>0;validateNumber(offset,"offset");const first=this[offset];const last=this[offset+7];if(first===undefined||last===undefined){boundsError(offset,this.length-8)}const val=this[offset+4]+this[offset+5]*2**8+this[offset+6]*2**16+(last<<24);return(BigInt(val)<<BigInt(32))+BigInt(first+this[++offset]*2**8+this[++offset]*2**16+this[++offset]*2**24)}));Buffer.prototype.readBigInt64BE=defineBigIntMethod((function readBigInt64BE(offset){offset=offset>>>0;validateNumber(offset,"offset");const first=this[offset];const last=this[offset+7];if(first===undefined||last===undefined){boundsError(offset,this.length-8)}const val=(first<<24)+this[++offset]*2**16+this[++offset]*2**8+this[++offset];return(BigInt(val)<<BigInt(32))+BigInt(this[++offset]*2**24+this[++offset]*2**16+this[++offset]*2**8+last)}));Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||value<min)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){const maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}let mul=1;let i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUintBE=Buffer.prototype.writeUIntBE=function writeUIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){const maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}let i=byteLength-1;let mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function wrtBigUInt64LE(buf,value,offset,min,max){checkIntBI(value,min,max,buf,offset,7);let lo=Number(value&BigInt(4294967295));buf[offset++]=lo;lo=lo>>8;buf[offset++]=lo;lo=lo>>8;buf[offset++]=lo;lo=lo>>8;buf[offset++]=lo;let hi=Number(value>>BigInt(32)&BigInt(4294967295));buf[offset++]=hi;hi=hi>>8;buf[offset++]=hi;hi=hi>>8;buf[offset++]=hi;hi=hi>>8;buf[offset++]=hi;return offset}function wrtBigUInt64BE(buf,value,offset,min,max){checkIntBI(value,min,max,buf,offset,7);let lo=Number(value&BigInt(4294967295));buf[offset+7]=lo;lo=lo>>8;buf[offset+6]=lo;lo=lo>>8;buf[offset+5]=lo;lo=lo>>8;buf[offset+4]=lo;let hi=Number(value>>BigInt(32)&BigInt(4294967295));buf[offset+3]=hi;hi=hi>>8;buf[offset+2]=hi;hi=hi>>8;buf[offset+1]=hi;hi=hi>>8;buf[offset]=hi;return offset+8}Buffer.prototype.writeBigUInt64LE=defineBigIntMethod((function writeBigUInt64LE(value,offset=0){return wrtBigUInt64LE(this,value,offset,BigInt(0),BigInt("0xffffffffffffffff"))}));Buffer.prototype.writeBigUInt64BE=defineBigIntMethod((function writeBigUInt64BE(value,offset=0){return wrtBigUInt64BE(this,value,offset,BigInt(0),BigInt("0xffffffffffffffff"))}));Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){const limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}let i=0;let mul=1;let sub=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){if(value<0&&sub===0&&this[offset+i-1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){const limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}let i=byteLength-1;let mul=1;let sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer.prototype.writeBigInt64LE=defineBigIntMethod((function writeBigInt64LE(value,offset=0){return wrtBigUInt64LE(this,value,offset,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}));Buffer.prototype.writeBigInt64BE=defineBigIntMethod((function writeBigInt64BE(value,offset=0){return wrtBigUInt64BE(this,value,offset,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}));function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end<start)end=start;if(end===start)return 0;if(target.length===0||this.length===0)return 0;if(targetStart<0){throw new RangeError("targetStart out of bounds")}if(start<0||start>=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart<end-start){end=target.length-targetStart+start}const len=end-start;if(this===target&&typeof Uint8Array.prototype.copyWithin==="function"){this.copyWithin(targetStart,start,end)}else{Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart)}return len};Buffer.prototype.fill=function fill(val,start,end,encoding){if(typeof val==="string"){if(typeof start==="string"){encoding=start;start=0;end=this.length}else if(typeof end==="string"){encoding=end;end=this.length}if(encoding!==undefined&&typeof encoding!=="string"){throw new TypeError("encoding must be a string")}if(typeof encoding==="string"&&!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}if(val.length===1){const code=val.charCodeAt(0);if(encoding==="utf8"&&code<128||encoding==="latin1"){val=code}}}else if(typeof val==="number"){val=val&255}else if(typeof val==="boolean"){val=Number(val)}if(start<0||this.length<start||this.length<end){throw new RangeError("Out of range index")}if(end<=start){return this}start=start>>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;let i;if(typeof val==="number"){for(i=start;i<end;++i){this[i]=val}}else{const bytes=Buffer.isBuffer(val)?val:Buffer.from(val,encoding);const len=bytes.length;if(len===0){throw new TypeError('The value "'+val+'" is invalid for argument "value"')}for(i=0;i<end-start;++i){this[i+start]=bytes[i%len]}}return this};const errors={};function E(sym,getMessage,Base){errors[sym]=class NodeError extends Base{constructor(){super();Object.defineProperty(this,"message",{value:getMessage.apply(this,arguments),writable:true,configurable:true});this.name=`${this.name} [${sym}]`;this.stack;delete this.name}get code(){return sym}set code(value){Object.defineProperty(this,"code",{configurable:true,enumerable:true,value:value,writable:true})}toString(){return`${this.name} [${sym}]: ${this.message}`}}}E("ERR_BUFFER_OUT_OF_BOUNDS",(function(name){if(name){return`${name} is outside of buffer bounds`}return"Attempt to access memory outside buffer bounds"}),RangeError);E("ERR_INVALID_ARG_TYPE",(function(name,actual){return`The "${name}" argument must be of type number. Received type ${typeof actual}`}),TypeError);E("ERR_OUT_OF_RANGE",(function(str,range,input){let msg=`The value of "${str}" is out of range.`;let received=input;if(Number.isInteger(input)&&Math.abs(input)>2**32){received=addNumericalSeparator(String(input))}else if(typeof input==="bigint"){received=String(input);if(input>BigInt(2)**BigInt(32)||input<-(BigInt(2)**BigInt(32))){received=addNumericalSeparator(received)}received+="n"}msg+=` It must be ${range}. Received ${received}`;return msg}),RangeError);function addNumericalSeparator(val){let res="";let i=val.length;const start=val[0]==="-"?1:0;for(;i>=start+4;i-=3){res=`_${val.slice(i-3,i)}${res}`}return`${val.slice(0,i)}${res}`}function checkBounds(buf,offset,byteLength){validateNumber(offset,"offset");if(buf[offset]===undefined||buf[offset+byteLength]===undefined){boundsError(offset,buf.length-(byteLength+1))}}function checkIntBI(value,min,max,buf,offset,byteLength){if(value>max||value<min){const n=typeof min==="bigint"?"n":"";let range;{if(min===0||min===BigInt(0)){range=`>= 0${n} and < 2${n} ** ${(byteLength+1)*8}${n}`}else{range=`>= -(2${n} ** ${(byteLength+1)*8-1}${n}) and < 2 ** `+`${(byteLength+1)*8-1}${n}`}}throw new errors.ERR_OUT_OF_RANGE("value",range,value)}checkBounds(buf,offset,byteLength)}function validateNumber(value,name){if(typeof value!=="number"){throw new errors.ERR_INVALID_ARG_TYPE(name,"number",value)}}function boundsError(value,length,type){if(Math.floor(value)!==value){validateNumber(value,type);throw new errors.ERR_OUT_OF_RANGE("offset","an integer",value)}if(length<0){throw new errors.ERR_BUFFER_OUT_OF_BOUNDS}throw new errors.ERR_OUT_OF_RANGE("offset",`>= ${0} and <= ${length}`,value)}const INVALID_BASE64_RE=/[^+/0-9A-Za-z-_]/g;function base64clean(str){str=str.split("=")[0];str=str.trim().replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}function utf8ToBytes(string,units){units=units||Infinity;let codePoint;const length=string.length;let leadSurrogate=null;const bytes=[];for(let i=0;i<length;++i){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){const byteArray=[];for(let i=0;i<str.length;++i){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str,units){let c,hi,lo;const byteArray=[];for(let i=0;i<str.length;++i){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){let i;for(i=0;i<length;++i){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}const hexSliceLookupTable=function(){const alphabet="0123456789abcdef";const table=new Array(256);for(let i=0;i<16;++i){const i16=i*16;for(let j=0;j<16;++j){table[i16+j]=alphabet[i]+alphabet[j]}}return table}();function defineBigIntMethod(fn){return typeof BigInt==="undefined"?BufferBigIntNotDefined:fn}function BufferBigIntNotDefined(){throw new Error("BigInt not supported")}})(buffer);return buffer}var bufferExports=requireBuffer();function anumber$1(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function isBytes$2(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function abytes$2(b,...lengths){if(!isBytes$2(b))throw new Error("Uint8Array expected");if(lengths.length>0&&!lengths.includes(b.length))throw new Error("Uint8Array expected of length "+lengths+", got length="+b.length)}function ahash(h){if(typeof h!=="function"||typeof h.create!=="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");anumber$1(h.outputLen);anumber$1(h.blockLen)}function aexists$1(instance,checkFinished=true){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")}function aoutput$1(out,instance){abytes$2(out);const min=instance.outputLen;if(out.length<min){throw new Error("digestInto() expects output buffer of length at least "+min)}}const crypto$1=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:undefined;+/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const createView$1=arr=>new DataView(arr.buffer,arr.byteOffset,arr.byteLength);const rotr$1=(word,shift)=>word<<32-shift|word>>>shift;function utf8ToBytes$2(str){if(typeof str!=="string")throw new Error("utf8ToBytes expected string, got "+typeof str);return new Uint8Array((new TextEncoder).encode(str))}function toBytes$1(data){if(typeof data==="string")data=utf8ToBytes$2(data);abytes$2(data);return data}function concatBytes$1(...arrays){let sum=0;for(let i=0;i<arrays.length;i++){const a=arrays[i];abytes$2(a);sum+=a.length}const res=new Uint8Array(sum);for(let i=0,pad=0;i<arrays.length;i++){const a=arrays[i];res.set(a,pad);pad+=a.length}return res}let Hash$1=class Hash{clone(){return this._cloneInto()}};function wrapConstructor$1(hashCons){const hashC=msg=>hashCons().update(toBytes$1(msg)).digest();const tmp=hashCons();hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=()=>hashCons();return hashC}function randomBytes(bytesLength=32){if(crypto$1&&typeof crypto$1.getRandomValues==="function"){return crypto$1.getRandomValues(new Uint8Array(bytesLength))}if(crypto$1&&typeof crypto$1.randomBytes==="function"){return crypto$1.randomBytes(bytesLength)}throw new Error("crypto.getRandomValues must be defined")}function setBigUint64$1(view,byteOffset,value,isLE){if(typeof view.setBigUint64==="function")return view.setBigUint64(byteOffset,value,isLE);const _32n=BigInt(32);const _u32_max=BigInt(4294967295);const wh=Number(value>>_32n&_u32_max);const wl=Number(value&_u32_max);const h=isLE?4:0;const l=isLE?0:4;view.setUint32(byteOffset+h,wh,isLE);view.setUint32(byteOffset+l,wl,isLE)}const Chi$1=(a,b,c)=>a&b^~a&c;const Maj$1=(a,b,c)=>a&b^a&c^b&c;let HashMD$1=class HashMD extends Hash$1{constructor(blockLen,outputLen,padOffset,isLE){super();this.blockLen=blockLen;this.outputLen=outputLen;this.padOffset=padOffset;this.isLE=isLE;this.finished=false;this.length=0;this.pos=0;this.destroyed=false;this.buffer=new Uint8Array(blockLen);this.view=createView$1(this.buffer)}update(data){aexists$1(this);const{view:view,buffer:buffer,blockLen:blockLen}=this;data=toBytes$1(data);const len=data.length;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);if(take===blockLen){const dataView=createView$1(data);for(;blockLen<=len-pos;pos+=blockLen)this.process(dataView,pos);continue}buffer.set(data.subarray(pos,pos+take),this.pos);this.pos+=take;pos+=take;if(this.pos===blockLen){this.process(view,0);this.pos=0}}this.length+=data.length;this.roundClean();return this}digestInto(out){aexists$1(this);aoutput$1(out,this);this.finished=true;const{buffer:buffer,view:view,blockLen:blockLen,isLE:isLE}=this;let{pos:pos}=this;buffer[pos++]=128;this.buffer.subarray(pos).fill(0);if(this.padOffset>blockLen-pos){this.process(view,0);pos=0}for(let i=pos;i<blockLen;i++)buffer[i]=0;setBigUint64$1(view,blockLen-8,BigInt(this.length*8),isLE);this.process(view,0);const oview=createView$1(out);const len=this.outputLen;if(len%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const outLen=len/4;const state=this.get();if(outLen>state.length)throw new Error("_sha2: outputLen bigger than state");for(let i=0;i<outLen;i++)oview.setUint32(4*i,state[i],isLE)}digest(){const{buffer:buffer,outputLen:outputLen}=this;this.digestInto(buffer);const res=buffer.slice(0,outputLen);this.destroy();return res}_cloneInto(to){to||(to=new this.constructor);to.set(...this.get());const{blockLen:blockLen,buffer:buffer,length:length,finished:finished,destroyed:destroyed,pos:pos}=this;to.length=length;to.pos=pos;to.finished=finished;to.destroyed=destroyed;if(length%blockLen)to.buffer.set(buffer);return to}};const U32_MASK64$1=BigInt(2**32-1);const _32n$1=BigInt(32);function fromBig$1(n,le=false){if(le)return{h:Number(n&U32_MASK64$1),l:Number(n>>_32n$1&U32_MASK64$1)};return{h:Number(n>>_32n$1&U32_MASK64$1)|0,l:Number(n&U32_MASK64$1)|0}}function split$1(lst,le=false){let Ah=new Uint32Array(lst.length);let Al=new Uint32Array(lst.length);for(let i=0;i<lst.length;i++){const{h:h,l:l}=fromBig$1(lst[i],le);[Ah[i],Al[i]]=[h,l]}return[Ah,Al]}const toBig=(h,l)=>BigInt(h>>>0)<<_32n$1|BigInt(l>>>0);const shrSH=(h,_l,s)=>h>>>s;const shrSL=(h,l,s)=>h<<32-s|l>>>s;const rotrSH=(h,l,s)=>h>>>s|l<<32-s;const rotrSL=(h,l,s)=>h<<32-s|l>>>s;const rotrBH=(h,l,s)=>h<<64-s|l>>>s-32;const rotrBL=(h,l,s)=>h>>>s-32|l<<64-s;const rotr32H=(_h,l)=>l;const rotr32L=(h,_l)=>h;const rotlSH$1=(h,l,s)=>h<<s|l>>>32-s;const rotlSL$1=(h,l,s)=>l<<s|h>>>32-s;const rotlBH$1=(h,l,s)=>l<<s-32|h>>>64-s;const rotlBL$1=(h,l,s)=>h<<s-32|l>>>64-s;function add(Ah,Al,Bh,Bl){const l=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l/2**32|0)|0,l:l|0}}const add3L=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0);const add3H=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0;const add4L=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0);const add4H=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0;const add5L=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0);const add5H=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0;const u64$1={fromBig:fromBig$1,split:split$1,toBig:toBig,shrSH:shrSH,shrSL:shrSL,rotrSH:rotrSH,rotrSL:rotrSL,rotrBH:rotrBH,rotrBL:rotrBL,rotr32H:rotr32H,rotr32L:rotr32L,rotlSH:rotlSH$1,rotlSL:rotlSL$1,rotlBH:rotlBH$1,rotlBL:rotlBL$1,add:add,add3L:add3L,add3H:add3H,add4L:add4L,add4H:add4H,add5H:add5H,add5L:add5L};const[SHA512_Kh,SHA512_Kl]=(()=>u64$1.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((n=>BigInt(n)))))();const SHA512_W_H=new Uint32Array(80);const SHA512_W_L=new Uint32Array(80);class SHA512 extends HashMD$1{constructor(){super(128,64,16,false);this.Ah=1779033703|0;this.Al=4089235720|0;this.Bh=3144134277|0;this.Bl=2227873595|0;this.Ch=1013904242|0;this.Cl=4271175723|0;this.Dh=2773480762|0;this.Dl=1595750129|0;this.Eh=1359893119|0;this.El=2917565137|0;this.Fh=2600822924|0;this.Fl=725511199|0;this.Gh=528734635|0;this.Gl=4215389547|0;this.Hh=1541459225|0;this.Hl=327033209|0}get(){const{Ah:Ah,Al:Al,Bh:Bh,Bl:Bl,Ch:Ch,Cl:Cl,Dh:Dh,Dl:Dl,Eh:Eh,El:El,Fh:Fh,Fl:Fl,Gh:Gh,Gl:Gl,Hh:Hh,Hl:Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=Ah|0;this.Al=Al|0;this.Bh=Bh|0;this.Bl=Bl|0;this.Ch=Ch|0;this.Cl=Cl|0;this.Dh=Dh|0;this.Dl=Dl|0;this.Eh=Eh|0;this.El=El|0;this.Fh=Fh|0;this.Fl=Fl|0;this.Gh=Gh|0;this.Gl=Gl|0;this.Hh=Hh|0;this.Hl=Hl|0}process(view,offset){for(let i=0;i<16;i++,offset+=4){SHA512_W_H[i]=view.getUint32(offset);SHA512_W_L[i]=view.getUint32(offset+=4)}for(let i=16;i<80;i++){const W15h=SHA512_W_H[i-15]|0;const W15l=SHA512_W_L[i-15]|0;const s0h=u64$1.rotrSH(W15h,W15l,1)^u64$1.rotrSH(W15h,W15l,8)^u64$1.shrSH(W15h,W15l,7);const s0l=u64$1.rotrSL(W15h,W15l,1)^u64$1.rotrSL(W15h,W15l,8)^u64$1.shrSL(W15h,W15l,7);const W2h=SHA512_W_H[i-2]|0;const W2l=SHA512_W_L[i-2]|0;const s1h=u64$1.rotrSH(W2h,W2l,19)^u64$1.rotrBH(W2h,W2l,61)^u64$1.shrSH(W2h,W2l,6);const s1l=u64$1.rotrSL(W2h,W2l,19)^u64$1.rotrBL(W2h,W2l,61)^u64$1.shrSL(W2h,W2l,6);const SUMl=u64$1.add4L(s0l,s1l,SHA512_W_L[i-7],SHA512_W_L[i-16]);const SUMh=u64$1.add4H(SUMl,s0h,s1h,SHA512_W_H[i-7],SHA512_W_H[i-16]);SHA512_W_H[i]=SUMh|0;SHA512_W_L[i]=SUMl|0}let{Ah:Ah,Al:Al,Bh:Bh,Bl:Bl,Ch:Ch,Cl:Cl,Dh:Dh,Dl:Dl,Eh:Eh,El:El,Fh:Fh,Fl:Fl,Gh:Gh,Gl:Gl,Hh:Hh,Hl:Hl}=this;for(let i=0;i<80;i++){const sigma1h=u64$1.rotrSH(Eh,El,14)^u64$1.rotrSH(Eh,El,18)^u64$1.rotrBH(Eh,El,41);const sigma1l=u64$1.rotrSL(Eh,El,14)^u64$1.rotrSL(Eh,El,18)^u64$1.rotrBL(Eh,El,41);const CHIh=Eh&Fh^~Eh&Gh;const CHIl=El&Fl^~El&Gl;const T1ll=u64$1.add5L(Hl,sigma1l,CHIl,SHA512_Kl[i],SHA512_W_L[i]);const T1h=u64$1.add5H(T1ll,Hh,sigma1h,CHIh,SHA512_Kh[i],SHA512_W_H[i]);const T1l=T1ll|0;const sigma0h=u64$1.rotrSH(Ah,Al,28)^u64$1.rotrBH(Ah,Al,34)^u64$1.rotrBH(Ah,Al,39);const sigma0l=u64$1.rotrSL(Ah,Al,28)^u64$1.rotrBL(Ah,Al,34)^u64$1.rotrBL(Ah,Al,39);const MAJh=Ah&Bh^Ah&Ch^Bh&Ch;const MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=Gh|0;Hl=Gl|0;Gh=Fh|0;Gl=Fl|0;Fh=Eh|0;Fl=El|0;({h:Eh,l:El}=u64$1.add(Dh|0,Dl|0,T1h|0,T1l|0));Dh=Ch|0;Dl=Cl|0;Ch=Bh|0;Cl=Bl|0;Bh=Ah|0;Bl=Al|0;const All=u64$1.add3L(T1l,sigma0l,MAJl);Ah=u64$1.add3H(All,T1h,sigma0h,MAJh);Al=All|0}({h:Ah,l:Al}=u64$1.add(this.Ah|0,this.Al|0,Ah|0,Al|0));({h:Bh,l:Bl}=u64$1.add(this.Bh|0,this.Bl|0,Bh|0,Bl|0));({h:Ch,l:Cl}=u64$1.add(this.Ch|0,this.Cl|0,Ch|0,Cl|0));({h:Dh,l:Dl}=u64$1.add(this.Dh|0,this.Dl|0,Dh|0,Dl|0));({h:Eh,l:El}=u64$1.add(this.Eh|0,this.El|0,Eh|0,El|0));({h:Fh,l:Fl}=u64$1.add(this.Fh|0,this.Fl|0,Fh|0,Fl|0));({h:Gh,l:Gl}=u64$1.add(this.Gh|0,this.Gl|0,Gh|0,Gl|0));({h:Hh,l:Hl}=u64$1.add(this.Hh|0,this.Hl|0,Hh|0,Hl|0));this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){SHA512_W_H.fill(0);SHA512_W_L.fill(0)}destroy(){this.buffer.fill(0);this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const sha512=wrapConstructor$1((()=>new SHA512));+/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$5=BigInt(0);const _1n$7=BigInt(1);const _2n$5=BigInt(2);function isBytes$1(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function abytes$1(item){if(!isBytes$1(item))throw new Error("Uint8Array expected")}function abool(title,value){if(typeof value!=="boolean")throw new Error(title+" boolean expected, got "+value)}const hexes=Array.from({length:256},((_,i)=>i.toString(16).padStart(2,"0")));function bytesToHex(bytes){abytes$1(bytes);let hex="";for(let i=0;i<bytes.length;i++){hex+=hexes[bytes[i]]}return hex}function numberToHexUnpadded(num){const hex=num.toString(16);return hex.length&1?"0"+hex:hex}function hexToNumber(hex){if(typeof hex!=="string")throw new Error("hex string expected, got "+typeof hex);return hex===""?_0n$5:BigInt("0x"+hex)}const asciis={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16(ch){if(ch>=asciis._0&&ch<=asciis._9)return ch-asciis._0;if(ch>=asciis.A&&ch<=asciis.F)return ch-(asciis.A-10);if(ch>=asciis.a&&ch<=asciis.f)return ch-(asciis.a-10);return}function hexToBytes(hex){if(typeof hex!=="string")throw new Error("hex string expected, got "+typeof hex);const hl=hex.length;const al=hl/2;if(hl%2)throw new Error("hex string expected, got unpadded hex of length "+hl);const array=new Uint8Array(al);for(let ai=0,hi=0;ai<al;ai++,hi+=2){const n1=asciiToBase16(hex.charCodeAt(hi));const n2=asciiToBase16(hex.charCodeAt(hi+1));if(n1===undefined||n2===undefined){const char=hex[hi]+hex[hi+1];throw new Error('hex string expected, got non-hex character "'+char+'" at index '+hi)}array[ai]=n1*16+n2}return array}function bytesToNumberBE(bytes){return hexToNumber(bytesToHex(bytes))}function bytesToNumberLE(bytes){abytes$1(bytes);return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()))}function numberToBytesBE(n,len){return hexToBytes(n.toString(16).padStart(len*2,"0"))}function numberToBytesLE(n,len){return numberToBytesBE(n,len).reverse()}function numberToVarBytesBE(n){return hexToBytes(numberToHexUnpadded(n))}function ensureBytes(title,hex,expectedLength){let res;if(typeof hex==="string"){try{res=hexToBytes(hex)}catch(e){throw new Error(title+" must be hex string or Uint8Array, cause: "+e)}}else if(isBytes$1(hex)){res=Uint8Array.from(hex)}else{throw new Error(title+" must be hex string or Uint8Array")}const len=res.length;if(typeof expectedLength==="number"&&len!==expectedLength)throw new Error(title+" of length "+expectedLength+" expected, got "+len);return res}function concatBytes(...arrays){let sum=0;for(let i=0;i<arrays.length;i++){const a=arrays[i];abytes$1(a);sum+=a.length}const res=new Uint8Array(sum);for(let i=0,pad=0;i<arrays.length;i++){const a=arrays[i];res.set(a,pad);pad+=a.length}return res}function equalBytes(a,b){if(a.length!==b.length)return false;let diff=0;for(let i=0;i<a.length;i++)diff|=a[i]^b[i];return diff===0}function utf8ToBytes$1(str){if(typeof str!=="string")throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(str))}const isPosBig=n=>typeof n==="bigint"&&_0n$5<=n;function inRange(n,min,max){return isPosBig(n)&&isPosBig(min)&&isPosBig(max)&&min<=n&&n<max}function aInRange(title,n,min,max){if(!inRange(n,min,max))throw new Error("expected valid "+title+": "+min+" <= n < "+max+", got "+n)}function bitLen(n){let len;for(len=0;n>_0n$5;n>>=_1n$7,len+=1);return len}function bitGet(n,pos){return n>>BigInt(pos)&_1n$7}function bitSet(n,pos,value){return n|(value?_1n$7:_0n$5)<<BigInt(pos)}const bitMask=n=>(_2n$5<<BigInt(n-1))-_1n$7;const u8n=data=>new Uint8Array(data);const u8fr=arr=>Uint8Array.from(arr);function createHmacDrbg(hashLen,qByteLen,hmacFn){if(typeof hashLen!=="number"||hashLen<2)throw new Error("hashLen must be a number");if(typeof qByteLen!=="number"||qByteLen<2)throw new Error("qByteLen must be a number");if(typeof hmacFn!=="function")throw new Error("hmacFn must be a function");let v=u8n(hashLen);let k=u8n(hashLen);let i=0;const reset=()=>{v.fill(1);k.fill(0);i=0};const h=(...b)=>hmacFn(k,v,...b);const reseed=(seed=u8n())=>{k=h(u8fr([0]),seed);v=h();if(seed.length===0)return;k=h(u8fr([1]),seed);v=h()};const gen=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let len=0;const out=[];while(len<qByteLen){v=h();const sl=v.slice();out.push(sl);len+=v.length}return concatBytes(...out)};const genUntil=(seed,pred)=>{reset();reseed(seed);let res=undefined;while(!(res=pred(gen())))reseed();reset();return res};return genUntil}const validatorFns={bigint:val=>typeof val==="bigint",function:val=>typeof val==="function",boolean:val=>typeof val==="boolean",string:val=>typeof val==="string",stringOrUint8Array:val=>typeof val==="string"||isBytes$1(val),isSafeInteger:val=>Number.isSafeInteger(val),array:val=>Array.isArray(val),field:(val,object)=>object.Fp.isValid(val),hash:val=>typeof val==="function"&&Number.isSafeInteger(val.outputLen)};function validateObject(object,validators,optValidators={}){const checkField=(fieldName,type,isOptional)=>{const checkVal=validatorFns[type];if(typeof checkVal!=="function")throw new Error("invalid validator function");const val=object[fieldName];if(isOptional&&val===undefined)return;if(!checkVal(val,object)){throw new Error("param "+String(fieldName)+" is invalid. Expected "+type+", got "+val)}};for(const[fieldName,type]of Object.entries(validators))checkField(fieldName,type,false);for(const[fieldName,type]of Object.entries(optValidators))checkField(fieldName,type,true);return object}const notImplemented=()=>{throw new Error("not implemented")};function memoized(fn){const map=new WeakMap;return(arg,...args)=>{const val=map.get(arg);if(val!==undefined)return val;const computed=fn(arg,...args);map.set(arg,computed);return computed}}var ut=Object.freeze({__proto__:null,aInRange:aInRange,abool:abool,abytes:abytes$1,bitGet:bitGet,bitLen:bitLen,bitMask:bitMask,bitSet:bitSet,bytesToHex:bytesToHex,bytesToNumberBE:bytesToNumberBE,bytesToNumberLE:bytesToNumberLE,concatBytes:concatBytes,createHmacDrbg:createHmacDrbg,ensureBytes:ensureBytes,equalBytes:equalBytes,hexToBytes:hexToBytes,hexToNumber:hexToNumber,inRange:inRange,isBytes:isBytes$1,memoized:memoized,notImplemented:notImplemented,numberToBytesBE:numberToBytesBE,numberToBytesLE:numberToBytesLE,numberToHexUnpadded:numberToHexUnpadded,numberToVarBytesBE:numberToVarBytesBE,utf8ToBytes:utf8ToBytes$1,validateObject:validateObject});+/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$4=BigInt(0),_1n$6=BigInt(1),_2n$4=BigInt(2),_3n$1=BigInt(3);const _4n=BigInt(4),_5n$1=BigInt(5),_8n$2=BigInt(8);function mod(a,b){const result=a%b;return result>=_0n$4?result:b+result}function pow(num,power,modulo){if(power<_0n$4)throw new Error("invalid exponent, negatives unsupported");if(modulo<=_0n$4)throw new Error("invalid modulus");if(modulo===_1n$6)return _0n$4;let res=_1n$6;while(power>_0n$4){if(power&_1n$6)res=res*num%modulo;num=num*num%modulo;power>>=_1n$6}return res}function pow2(x,power,modulo){let res=x;while(power-- >_0n$4){res*=res;res%=modulo}return res}function invert(number,modulo){if(number===_0n$4)throw new Error("invert: expected non-zero number");if(modulo<=_0n$4)throw new Error("invert: expected positive modulus, got "+modulo);let a=mod(number,modulo);let b=modulo;let x=_0n$4,u=_1n$6;while(a!==_0n$4){const q=b/a;const r=b%a;const m=x-u*q;b=a,a=r,x=u,u=m}const gcd=b;if(gcd!==_1n$6)throw new Error("invert: does not exist");return mod(x,modulo)}function tonelliShanks(P){const legendreC=(P-_1n$6)/_2n$4;let Q,S,Z;for(Q=P-_1n$6,S=0;Q%_2n$4===_0n$4;Q/=_2n$4,S++);for(Z=_2n$4;Z<P&&pow(Z,legendreC,P)!==P-_1n$6;Z++){if(Z>1e3)throw new Error("Cannot find square root: likely non-prime P")}if(S===1){const p1div4=(P+_1n$6)/_4n;return function tonelliFast(Fp,n){const root=Fp.pow(n,p1div4);if(!Fp.eql(Fp.sqr(root),n))throw new Error("Cannot find square root");return root}}const Q1div2=(Q+_1n$6)/_2n$4;return function tonelliSlow(Fp,n){if(Fp.pow(n,legendreC)===Fp.neg(Fp.ONE))throw new Error("Cannot find square root");let r=S;let g=Fp.pow(Fp.mul(Fp.ONE,Z),Q);let x=Fp.pow(n,Q1div2);let b=Fp.pow(n,Q);while(!Fp.eql(b,Fp.ONE)){if(Fp.eql(b,Fp.ZERO))return Fp.ZERO;let m=1;for(let t2=Fp.sqr(b);m<r;m++){if(Fp.eql(t2,Fp.ONE))break;t2=Fp.sqr(t2)}const ge=Fp.pow(g,_1n$6<<BigInt(r-m-1));g=Fp.sqr(ge);x=Fp.mul(x,ge);b=Fp.mul(b,g);r=m}return x}}function FpSqrt(P){if(P%_4n===_3n$1){const p1div4=(P+_1n$6)/_4n;return function sqrt3mod4(Fp,n){const root=Fp.pow(n,p1div4);if(!Fp.eql(Fp.sqr(root),n))throw new Error("Cannot find square root");return root}}if(P%_8n$2===_5n$1){const c1=(P-_5n$1)/_8n$2;return function sqrt5mod8(Fp,n){const n2=Fp.mul(n,_2n$4);const v=Fp.pow(n2,c1);const nv=Fp.mul(n,v);const i=Fp.mul(Fp.mul(nv,_2n$4),v);const root=Fp.mul(nv,Fp.sub(i,Fp.ONE));if(!Fp.eql(Fp.sqr(root),n))throw new Error("Cannot find square root");return root}}return tonelliShanks(P)}const isNegativeLE=(num,modulo)=>(mod(num,modulo)&_1n$6)===_1n$6;const FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(field){const initial={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"};const opts=FIELD_FIELDS.reduce(((map,val)=>{map[val]="function";return map}),initial);return validateObject(field,opts)}function FpPow(f,num,power){if(power<_0n$4)throw new Error("invalid exponent, negatives unsupported");if(power===_0n$4)return f.ONE;if(power===_1n$6)return num;let p=f.ONE;let d=num;while(power>_0n$4){if(power&_1n$6)p=f.mul(p,d);d=f.sqr(d);power>>=_1n$6}return p}function FpInvertBatch(f,nums){const tmp=new Array(nums.length);const lastMultiplied=nums.reduce(((acc,num,i)=>{if(f.is0(num))return acc;tmp[i]=acc;return f.mul(acc,num)}),f.ONE);const inverted=f.inv(lastMultiplied);nums.reduceRight(((acc,num,i)=>{if(f.is0(num))return acc;tmp[i]=f.mul(acc,tmp[i]);return f.mul(acc,num)}),inverted);return tmp}function nLength(n,nBitLength){const _nBitLength=nBitLength!==undefined?nBitLength:n.toString(2).length;const nByteLength=Math.ceil(_nBitLength/8);return{nBitLength:_nBitLength,nByteLength:nByteLength}}function Field(ORDER,bitLen,isLE=false,redef={}){if(ORDER<=_0n$4)throw new Error("invalid field: expected ORDER > 0, got "+ORDER);const{nBitLength:BITS,nByteLength:BYTES}=nLength(ORDER,bitLen);if(BYTES>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let sqrtP;const f=Object.freeze({ORDER:ORDER,BITS:BITS,BYTES:BYTES,MASK:bitMask(BITS),ZERO:_0n$4,ONE:_1n$6,create:num=>mod(num,ORDER),isValid:num=>{if(typeof num!=="bigint")throw new Error("invalid field element: expected bigint, got "+typeof num);return _0n$4<=num&&num<ORDER},is0:num=>num===_0n$4,isOdd:num=>(num&_1n$6)===_1n$6,neg:num=>mod(-num,ORDER),eql:(lhs,rhs)=>lhs===rhs,sqr:num=>mod(num*num,ORDER),add:(lhs,rhs)=>mod(lhs+rhs,ORDER),sub:(lhs,rhs)=>mod(lhs-rhs,ORDER),mul:(lhs,rhs)=>mod(lhs*rhs,ORDER),pow:(num,power)=>FpPow(f,num,power),div:(lhs,rhs)=>mod(lhs*invert(rhs,ORDER),ORDER),sqrN:num=>num*num,addN:(lhs,rhs)=>lhs+rhs,subN:(lhs,rhs)=>lhs-rhs,mulN:(lhs,rhs)=>lhs*rhs,inv:num=>invert(num,ORDER),sqrt:redef.sqrt||(n=>{if(!sqrtP)sqrtP=FpSqrt(ORDER);return sqrtP(f,n)}),invertBatch:lst=>FpInvertBatch(f,lst),cmov:(a,b,c)=>c?b:a,toBytes:num=>isLE?numberToBytesLE(num,BYTES):numberToBytesBE(num,BYTES),fromBytes:bytes=>{if(bytes.length!==BYTES)throw new Error("Field.fromBytes: expected "+BYTES+" bytes, got "+bytes.length);return isLE?bytesToNumberLE(bytes):bytesToNumberBE(bytes)}});return Object.freeze(f)}function getFieldBytesLength(fieldOrder){if(typeof fieldOrder!=="bigint")throw new Error("field order must be bigint");const bitLength=fieldOrder.toString(2).length;return Math.ceil(bitLength/8)}function getMinHashLength(fieldOrder){const length=getFieldBytesLength(fieldOrder);return length+Math.ceil(length/2)}function mapHashToField(key,fieldOrder,isLE=false){const len=key.length;const fieldLen=getFieldBytesLength(fieldOrder);const minLen=getMinHashLength(fieldOrder);if(len<16||len<minLen||len>1024)throw new Error("expected "+minLen+"-1024 bytes of input, got "+len);const num=isLE?bytesToNumberBE(key):bytesToNumberLE(key);const reduced=mod(num,fieldOrder-_1n$6)+_1n$6;return isLE?numberToBytesLE(reduced,fieldLen):numberToBytesBE(reduced,fieldLen)}+/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$3=BigInt(0);const _1n$5=BigInt(1);function constTimeNegate(condition,item){const neg=item.negate();return condition?neg:item}function validateW(W,bits){if(!Number.isSafeInteger(W)||W<=0||W>bits)throw new Error("invalid window size, expected [1.."+bits+"], got W="+W)}function calcWOpts(W,bits){validateW(W,bits);const windows=Math.ceil(bits/W)+1;const windowSize=2**(W-1);return{windows:windows,windowSize:windowSize}}function validateMSMPoints(points,c){if(!Array.isArray(points))throw new Error("array expected");points.forEach(((p,i)=>{if(!(p instanceof c))throw new Error("invalid point at index "+i)}))}function validateMSMScalars(scalars,field){if(!Array.isArray(scalars))throw new Error("array of scalars expected");scalars.forEach(((s,i)=>{if(!field.isValid(s))throw new Error("invalid scalar at index "+i)}))}const pointPrecomputes=new WeakMap;const pointWindowSizes=new WeakMap;function getW(P){return pointWindowSizes.get(P)||1}function wNAF(c,bits){return{constTimeNegate:constTimeNegate,hasPrecomputes(elm){return getW(elm)!==1},unsafeLadder(elm,n,p=c.ZERO){let d=elm;while(n>_0n$3){if(n&_1n$5)p=p.add(d);d=d.double();n>>=_1n$5}return p},precomputeWindow(elm,W){const{windows:windows,windowSize:windowSize}=calcWOpts(W,bits);const points=[];let p=elm;let base=p;for(let window=0;window<windows;window++){base=p;points.push(base);for(let i=1;i<windowSize;i++){base=base.add(p);points.push(base)}p=base.double()}return points},wNAF(W,precomputes,n){const{windows:windows,windowSize:windowSize}=calcWOpts(W,bits);let p=c.ZERO;let f=c.BASE;const mask=BigInt(2**W-1);const maxNumber=2**W;const shiftBy=BigInt(W);for(let window=0;window<windows;window++){const offset=window*windowSize;let wbits=Number(n&mask);n>>=shiftBy;if(wbits>windowSize){wbits-=maxNumber;n+=_1n$5}const offset1=offset;const offset2=offset+Math.abs(wbits)-1;const cond1=window%2!==0;const cond2=wbits<0;if(wbits===0){f=f.add(constTimeNegate(cond1,precomputes[offset1]))}else{p=p.add(constTimeNegate(cond2,precomputes[offset2]))}}return{p:p,f:f}},wNAFUnsafe(W,precomputes,n,acc=c.ZERO){const{windows:windows,windowSize:windowSize}=calcWOpts(W,bits);const mask=BigInt(2**W-1);const maxNumber=2**W;const shiftBy=BigInt(W);for(let window=0;window<windows;window++){const offset=window*windowSize;if(n===_0n$3)break;let wbits=Number(n&mask);n>>=shiftBy;if(wbits>windowSize){wbits-=maxNumber;n+=_1n$5}if(wbits===0)continue;let curr=precomputes[offset+Math.abs(wbits)-1];if(wbits<0)curr=curr.negate();acc=acc.add(curr)}return acc},getPrecomputes(W,P,transform){let comp=pointPrecomputes.get(P);if(!comp){comp=this.precomputeWindow(P,W);if(W!==1)pointPrecomputes.set(P,transform(comp))}return comp},wNAFCached(P,n,transform){const W=getW(P);return this.wNAF(W,this.getPrecomputes(W,P,transform),n)},wNAFCachedUnsafe(P,n,transform,prev){const W=getW(P);if(W===1)return this.unsafeLadder(P,n,prev);return this.wNAFUnsafe(W,this.getPrecomputes(W,P,transform),n,prev)},setWindowSize(P,W){validateW(W,bits);pointWindowSizes.set(P,W);pointPrecomputes.delete(P)}}}function pippenger(c,fieldN,points,scalars){validateMSMPoints(points,c);validateMSMScalars(scalars,fieldN);if(points.length!==scalars.length)throw new Error("arrays of points and scalars must have equal length");const zero=c.ZERO;const wbits=bitLen(BigInt(points.length));const windowSize=wbits>12?wbits-3:wbits>4?wbits-2:wbits?2:1;const MASK=(1<<windowSize)-1;const buckets=new Array(MASK+1).fill(zero);const lastBits=Math.floor((fieldN.BITS-1)/windowSize)*windowSize;let sum=zero;for(let i=lastBits;i>=0;i-=windowSize){buckets.fill(zero);for(let j=0;j<scalars.length;j++){const scalar=scalars[j];const wbits=Number(scalar>>BigInt(i)&BigInt(MASK));buckets[wbits]=buckets[wbits].add(points[j])}let resI=zero;for(let j=buckets.length-1,sumI=zero;j>0;j--){sumI=sumI.add(buckets[j]);resI=resI.add(sumI)}sum=sum.add(resI);if(i!==0)for(let j=0;j<windowSize;j++)sum=sum.double()}return sum}function validateBasic(curve){validateField(curve.Fp);validateObject(curve,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"});return Object.freeze({...nLength(curve.n,curve.nBitLength),...curve,...{p:curve.Fp.ORDER}})}+/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$4=BigInt(1),_2n$3=BigInt(2),_8n$1=BigInt(8);const VERIFY_DEFAULT={zip215:true};function validateOpts$1(curve){const opts=validateBasic(curve);validateObject(curve,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"});return Object.freeze({...opts})}function twistedEdwards(curveDef){const CURVE=validateOpts$1(curveDef);const{Fp:Fp,n:CURVE_ORDER,prehash:prehash,hash:cHash,randomBytes:randomBytes,nByteLength:nByteLength,h:cofactor}=CURVE;const MASK=_2n$3<<BigInt(nByteLength*8)-_1n$4;const modP=Fp.create;const Fn=Field(CURVE.n,CURVE.nBitLength);const uvRatio=CURVE.uvRatio||((u,v)=>{try{return{isValid:true,value:Fp.sqrt(u*Fp.inv(v))}}catch(e){return{isValid:false,value:_0n$2}}});const adjustScalarBytes=CURVE.adjustScalarBytes||(bytes=>bytes);const domain=CURVE.domain||((data,ctx,phflag)=>{abool("phflag",phflag);if(ctx.length||phflag)throw new Error("Contexts/pre-hash are not supported");return data});function aCoordinate(title,n){aInRange("coordinate "+title,n,_0n$2,MASK)}function assertPoint(other){if(!(other instanceof Point))throw new Error("ExtendedPoint expected")}const toAffineMemo=memoized(((p,iz)=>{const{ex:x,ey:y,ez:z}=p;const is0=p.is0();if(iz==null)iz=is0?_8n$1:Fp.inv(z);const ax=modP(x*iz);const ay=modP(y*iz);const zz=modP(z*iz);if(is0)return{x:_0n$2,y:_1n$4};if(zz!==_1n$4)throw new Error("invZ was invalid");return{x:ax,y:ay}}));const assertValidMemo=memoized((p=>{const{a:a,d:d}=CURVE;if(p.is0())throw new Error("bad point: ZERO");const{ex:X,ey:Y,ez:Z,et:T}=p;const X2=modP(X*X);const Y2=modP(Y*Y);const Z2=modP(Z*Z);const Z4=modP(Z2*Z2);const aX2=modP(X2*a);const left=modP(Z2*modP(aX2+Y2));const right=modP(Z4+modP(d*modP(X2*Y2)));if(left!==right)throw new Error("bad point: equation left != right (1)");const XY=modP(X*Y);const ZT=modP(Z*T);if(XY!==ZT)throw new Error("bad point: equation left != right (2)");return true}));class Point{constructor(ex,ey,ez,et){this.ex=ex;this.ey=ey;this.ez=ez;this.et=et;aCoordinate("x",ex);aCoordinate("y",ey);aCoordinate("z",ez);aCoordinate("t",et);Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(p){if(p instanceof Point)throw new Error("extended point not allowed");const{x:x,y:y}=p||{};aCoordinate("x",x);aCoordinate("y",y);return new Point(x,y,_1n$4,modP(x*y))}static normalizeZ(points){const toInv=Fp.invertBatch(points.map((p=>p.ez)));return points.map(((p,i)=>p.toAffine(toInv[i]))).map(Point.fromAffine)}static msm(points,scalars){return pippenger(Point,Fn,points,scalars)}_setWindowSize(windowSize){wnaf.setWindowSize(this,windowSize)}assertValidity(){assertValidMemo(this)}equals(other){assertPoint(other);const{ex:X1,ey:Y1,ez:Z1}=this;const{ex:X2,ey:Y2,ez:Z2}=other;const X1Z2=modP(X1*Z2);const X2Z1=modP(X2*Z1);const Y1Z2=modP(Y1*Z2);const Y2Z1=modP(Y2*Z1);return X1Z2===X2Z1&&Y1Z2===Y2Z1}is0(){return this.equals(Point.ZERO)}negate(){return new Point(modP(-this.ex),this.ey,this.ez,modP(-this.et))}double(){const{a:a}=CURVE;const{ex:X1,ey:Y1,ez:Z1}=this;const A=modP(X1*X1);const B=modP(Y1*Y1);const C=modP(_2n$3*modP(Z1*Z1));const D=modP(a*A);const x1y1=X1+Y1;const E=modP(modP(x1y1*x1y1)-A-B);const G=D+B;const F=G-C;const H=D-B;const X3=modP(E*F);const Y3=modP(G*H);const T3=modP(E*H);const Z3=modP(F*G);return new Point(X3,Y3,Z3,T3)}add(other){assertPoint(other);const{a:a,d:d}=CURVE;const{ex:X1,ey:Y1,ez:Z1,et:T1}=this;const{ex:X2,ey:Y2,ez:Z2,et:T2}=other;if(a===BigInt(-1)){const A=modP((Y1-X1)*(Y2+X2));const B=modP((Y1+X1)*(Y2-X2));const F=modP(B-A);if(F===_0n$2)return this.double();const C=modP(Z1*_2n$3*T2);const D=modP(T1*_2n$3*Z2);const E=D+C;const G=B+A;const H=D-C;const X3=modP(E*F);const Y3=modP(G*H);const T3=modP(E*H);const Z3=modP(F*G);return new Point(X3,Y3,Z3,T3)}const A=modP(X1*X2);const B=modP(Y1*Y2);const C=modP(T1*d*T2);const D=modP(Z1*Z2);const E=modP((X1+Y1)*(X2+Y2)-A-B);const F=D-C;const G=D+C;const H=modP(B-a*A);const X3=modP(E*F);const Y3=modP(G*H);const T3=modP(E*H);const Z3=modP(F*G);return new Point(X3,Y3,Z3,T3)}subtract(other){return this.add(other.negate())}wNAF(n){return wnaf.wNAFCached(this,n,Point.normalizeZ)}multiply(scalar){const n=scalar;aInRange("scalar",n,_1n$4,CURVE_ORDER);const{p:p,f:f}=this.wNAF(n);return Point.normalizeZ([p,f])[0]}multiplyUnsafe(scalar,acc=Point.ZERO){const n=scalar;aInRange("scalar",n,_0n$2,CURVE_ORDER);if(n===_0n$2)return I;if(this.is0()||n===_1n$4)return this;return wnaf.wNAFCachedUnsafe(this,n,Point.normalizeZ,acc)}isSmallOrder(){return this.multiplyUnsafe(cofactor).is0()}isTorsionFree(){return wnaf.unsafeLadder(this,CURVE_ORDER).is0()}toAffine(iz){return toAffineMemo(this,iz)}clearCofactor(){const{h:cofactor}=CURVE;if(cofactor===_1n$4)return this;return this.multiplyUnsafe(cofactor)}static fromHex(hex,zip215=false){const{d:d,a:a}=CURVE;const len=Fp.BYTES;hex=ensureBytes("pointHex",hex,len);abool("zip215",zip215);const normed=hex.slice();const lastByte=hex[len-1];normed[len-1]=lastByte&~128;const y=bytesToNumberLE(normed);const max=zip215?MASK:Fp.ORDER;aInRange("pointHex.y",y,_0n$2,max);const y2=modP(y*y);const u=modP(y2-_1n$4);const v=modP(d*y2-a);let{isValid:isValid,value:x}=uvRatio(u,v);if(!isValid)throw new Error("Point.fromHex: invalid y coordinate");const isXOdd=(x&_1n$4)===_1n$4;const isLastByteOdd=(lastByte&128)!==0;if(!zip215&&x===_0n$2&&isLastByteOdd)throw new Error("Point.fromHex: x=0 and x_0=1");if(isLastByteOdd!==isXOdd)x=modP(-x);return Point.fromAffine({x:x,y:y})}static fromPrivateKey(privKey){return getExtendedPublicKey(privKey).point}toRawBytes(){const{x:x,y:y}=this.toAffine();const bytes=numberToBytesLE(y,Fp.BYTES);bytes[bytes.length-1]|=x&_1n$4?128:0;return bytes}toHex(){return bytesToHex(this.toRawBytes())}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy,_1n$4,modP(CURVE.Gx*CURVE.Gy));Point.ZERO=new Point(_0n$2,_1n$4,_1n$4,_0n$2);const{BASE:G,ZERO:I}=Point;const wnaf=wNAF(Point,nByteLength*8);function modN(a){return mod(a,CURVE_ORDER)}function modN_LE(hash){return modN(bytesToNumberLE(hash))}function getExtendedPublicKey(key){const len=Fp.BYTES;key=ensureBytes("private key",key,len);const hashed=ensureBytes("hashed private key",cHash(key),2*len);const head=adjustScalarBytes(hashed.slice(0,len));const prefix=hashed.slice(len,2*len);const scalar=modN_LE(head);const point=G.multiply(scalar);const pointBytes=point.toRawBytes();return{head:head,prefix:prefix,scalar:scalar,point:point,pointBytes:pointBytes}}function getPublicKey(privKey){return getExtendedPublicKey(privKey).pointBytes}function hashDomainToScalar(context=new Uint8Array,...msgs){const msg=concatBytes(...msgs);return modN_LE(cHash(domain(msg,ensureBytes("context",context),!!prehash)))}function sign(msg,privKey,options={}){msg=ensureBytes("message",msg);if(prehash)msg=prehash(msg);const{prefix:prefix,scalar:scalar,pointBytes:pointBytes}=getExtendedPublicKey(privKey);const r=hashDomainToScalar(options.context,prefix,msg);const R=G.multiply(r).toRawBytes();const k=hashDomainToScalar(options.context,R,pointBytes,msg);const s=modN(r+k*scalar);aInRange("signature.s",s,_0n$2,CURVE_ORDER);const res=concatBytes(R,numberToBytesLE(s,Fp.BYTES));return ensureBytes("result",res,Fp.BYTES*2)}const verifyOpts=VERIFY_DEFAULT;function verify(sig,msg,publicKey,options=verifyOpts){const{context:context,zip215:zip215}=options;const len=Fp.BYTES;sig=ensureBytes("signature",sig,2*len);msg=ensureBytes("message",msg);publicKey=ensureBytes("publicKey",publicKey,len);if(zip215!==undefined)abool("zip215",zip215);if(prehash)msg=prehash(msg);const s=bytesToNumberLE(sig.slice(len,2*len));let A,R,SB;try{A=Point.fromHex(publicKey,zip215);R=Point.fromHex(sig.slice(0,len),zip215);SB=G.multiplyUnsafe(s)}catch(error){return false}if(!zip215&&A.isSmallOrder())return false;const k=hashDomainToScalar(context,R.toRawBytes(),A.toRawBytes(),msg);const RkA=R.add(A.multiplyUnsafe(k));return RkA.subtract(SB).clearCofactor().equals(Point.ZERO)}G._setWindowSize(8);const utils={getExtendedPublicKey:getExtendedPublicKey,randomPrivateKey:()=>randomBytes(Fp.BYTES),precompute(windowSize=8,point=Point.BASE){point._setWindowSize(windowSize);point.multiply(BigInt(3));return point}};return{CURVE:CURVE,getPublicKey:getPublicKey,sign:sign,verify:verify,ExtendedPoint:Point,utils:utils}}+/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ED25519_P=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");const ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const _1n$3=BigInt(1),_2n$2=BigInt(2);BigInt(3);const _5n=BigInt(5),_8n=BigInt(8);function ed25519_pow_2_252_3(x){const _10n=BigInt(10),_20n=BigInt(20),_40n=BigInt(40),_80n=BigInt(80);const P=ED25519_P;const x2=x*x%P;const b2=x2*x%P;const b4=pow2(b2,_2n$2,P)*b2%P;const b5=pow2(b4,_1n$3,P)*x%P;const b10=pow2(b5,_5n,P)*b5%P;const b20=pow2(b10,_10n,P)*b10%P;const b40=pow2(b20,_20n,P)*b20%P;const b80=pow2(b40,_40n,P)*b40%P;const b160=pow2(b80,_80n,P)*b80%P;const b240=pow2(b160,_80n,P)*b80%P;const b250=pow2(b240,_10n,P)*b10%P;const pow_p_5_8=pow2(b250,_2n$2,P)*x%P;return{pow_p_5_8:pow_p_5_8,b2:b2}}function adjustScalarBytes(bytes){bytes[0]&=248;bytes[31]&=127;bytes[31]|=64;return bytes}function uvRatio(u,v){const P=ED25519_P;const v3=mod(v*v*v,P);const v7=mod(v3*v3*v,P);const pow=ed25519_pow_2_252_3(u*v7).pow_p_5_8;let x=mod(u*v3*pow,P);const vx2=mod(v*x*x,P);const root1=x;const root2=mod(x*ED25519_SQRT_M1,P);const useRoot1=vx2===u;const useRoot2=vx2===mod(-u,P);const noRoot=vx2===mod(-u*ED25519_SQRT_M1,P);if(useRoot1)x=root1;if(useRoot2||noRoot)x=root2;if(isNegativeLE(x,P))x=mod(-x,P);return{isValid:useRoot1||useRoot2,value:x}}const Fp=(()=>Field(ED25519_P,undefined,true))();const ed25519Defaults=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Fp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:_8n,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:sha512,randomBytes:randomBytes,adjustScalarBytes:adjustScalarBytes,uvRatio:uvRatio}))();const ed25519=(()=>twistedEdwards(ed25519Defaults))();const generatePrivateKey=ed25519.utils.randomPrivateKey;const generateKeypair=()=>{const privateScalar=ed25519.utils.randomPrivateKey();const publicKey=getPublicKey(privateScalar);const secretKey=new Uint8Array(64);secretKey.set(privateScalar);secretKey.set(publicKey,32);return{publicKey:publicKey,secretKey:secretKey}};const getPublicKey=ed25519.getPublicKey;function isOnCurve(publicKey){try{ed25519.ExtendedPoint.fromHex(publicKey);return true}catch{return false}}const sign=(message,secretKey)=>ed25519.sign(message,secretKey.slice(0,32));const verify=ed25519.verify;const toBuffer=arr=>{if(bufferExports.Buffer.isBuffer(arr)){return arr}else if(arr instanceof Uint8Array){return bufferExports.Buffer.from(arr.buffer,arr.byteOffset,arr.byteLength)}else{return bufferExports.Buffer.from(arr)}};var bn$1={exports:{}};var _nodeResolve_empty={};var _nodeResolve_empty$1=Object.freeze({__proto__:null,default:_nodeResolve_empty});var require$$0$1=getAugmentedNamespace(_nodeResolve_empty$1);var bn=bn$1.exports;var hasRequiredBn;function requireBn(){if(hasRequiredBn)return bn$1.exports;hasRequiredBn=1;(function(module){(function(module,exports){function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}function BN(number,base,endian){if(BN.isBN(number)){return number}this.negative=0;this.words=null;this.length=0;this.red=null;if(number!==null){if(base==="le"||base==="be"){endian=base;base=10}this._init(number||0,base||10,endian||"be")}}if(typeof module==="object"){module.exports=BN}else{exports.BN=BN}BN.BN=BN;BN.wordSize=26;var Buffer;try{if(typeof window!=="undefined"&&typeof window.Buffer!=="undefined"){Buffer=window.Buffer}else{Buffer=require$$0$1.Buffer}}catch(e){}BN.isBN=function isBN(num){if(num instanceof BN){return true}return num!==null&&typeof num==="object"&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)};BN.max=function max(left,right){if(left.cmp(right)>0)return left;return right};BN.min=function min(left,right){if(left.cmp(right)<0)return left;return right};BN.prototype._init=function init(number,base,endian){if(typeof number==="number"){return this._initNumber(number,base,endian)}if(typeof number==="object"){return this._initArray(number,base,endian)}if(base==="hex"){base=16}assert(base===(base|0)&&base>=2&&base<=36);number=number.toString().replace(/\s+/g,"");var start=0;if(number[0]==="-"){start++;this.negative=1}if(start<number.length){if(base===16){this._parseHex(number,start,endian)}else{this._parseBase(number,base,start);if(endian==="le"){this._initArray(this.toArray(),base,endian)}}}};BN.prototype._initNumber=function _initNumber(number,base,endian){if(number<0){this.negative=1;number=-number}if(number<67108864){this.words=[number&67108863];this.length=1}else if(number<4503599627370496){this.words=[number&67108863,number/67108864&67108863];this.length=2}else{assert(number<9007199254740992);this.words=[number&67108863,number/67108864&67108863,1];this.length=3}if(endian!=="le")return;this._initArray(this.toArray(),base,endian)};BN.prototype._initArray=function _initArray(number,base,endian){assert(typeof number.length==="number");if(number.length<=0){this.words=[0];this.length=1;return this}this.length=Math.ceil(number.length/3);this.words=new Array(this.length);for(var i=0;i<this.length;i++){this.words[i]=0}var j,w;var off=0;if(endian==="be"){for(i=number.length-1,j=0;i>=0;i-=3){w=number[i]|number[i-1]<<8|number[i-2]<<16;this.words[j]|=w<<off&67108863;this.words[j+1]=w>>>26-off&67108863;off+=24;if(off>=26){off-=26;j++}}}else if(endian==="le"){for(i=0,j=0;i<number.length;i+=3){w=number[i]|number[i+1]<<8|number[i+2]<<16;this.words[j]|=w<<off&67108863;this.words[j+1]=w>>>26-off&67108863;off+=24;if(off>=26){off-=26;j++}}}return this._strip()};function parseHex4Bits(string,index){var c=string.charCodeAt(index);if(c>=48&&c<=57){return c-48}else if(c>=65&&c<=70){return c-55}else if(c>=97&&c<=102){return c-87}else{assert(false,"Invalid character in "+string)}}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);if(index-1>=lowerBound){r|=parseHex4Bits(string,index-1)<<4}return r}BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=Math.ceil((number.length-start)/6);this.words=new Array(this.length);for(var i=0;i<this.length;i++){this.words[i]=0}var off=0;var j=0;var w;if(endian==="be"){for(i=number.length-1;i>=start;i-=2){w=parseHexByte(number,start,i)<<off;this.words[j]|=w&67108863;if(off>=18){off-=18;j+=1;this.words[j]|=w>>>26}else{off+=8}}}else{var parseLength=number.length-start;for(i=parseLength%2===0?start+1:start;i<number.length;i+=2){w=parseHexByte(number,start,i)<<off;this.words[j]|=w&67108863;if(off>=18){off-=18;j+=1;this.words[j]|=w>>>26}else{off+=8}}}this._strip()};function parseBase(str,start,end,mul){var r=0;var b=0;var len=Math.min(str.length,end);for(var i=start;i<len;i++){var c=str.charCodeAt(i)-48;r*=mul;if(c>=49){b=c-49+10}else if(c>=17){b=c-17+10}else{b=c}assert(c>=0&&b<mul,"Invalid character");r+=b}return r}BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0];this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base){limbLen++}limbLen--;limbPow=limbPow/base|0;var total=number.length-start;var mod=total%limbLen;var end=Math.min(total,total-mod)+start;var word=0;for(var i=start;i<end;i+=limbLen){word=parseBase(number,i,i+limbLen,base);this.imuln(limbPow);if(this.words[0]+word<67108864){this.words[0]+=word}else{this._iaddn(word)}}if(mod!==0){var pow=1;word=parseBase(number,i,number.length,base);for(i=0;i<mod;i++){pow*=base}this.imuln(pow);if(this.words[0]+word<67108864){this.words[0]+=word}else{this._iaddn(word)}}this._strip()};BN.prototype.copy=function copy(dest){dest.words=new Array(this.length);for(var i=0;i<this.length;i++){dest.words[i]=this.words[i]}dest.length=this.length;dest.negative=this.negative;dest.red=this.red};function move(dest,src){dest.words=src.words;dest.length=src.length;dest.negative=src.negative;dest.red=src.red}BN.prototype._move=function _move(dest){move(dest,this)};BN.prototype.clone=function clone(){var r=new BN(null);this.copy(r);return r};BN.prototype._expand=function _expand(size){while(this.length<size){this.words[this.length++]=0}return this};BN.prototype._strip=function strip(){while(this.length>1&&this.words[this.length-1]===0){this.length--}return this._normSign()};BN.prototype._normSign=function _normSign(){if(this.length===1&&this.words[0]===0){this.negative=0}return this};if(typeof Symbol!=="undefined"&&typeof Symbol.for==="function"){try{BN.prototype[Symbol.for("nodejs.util.inspect.custom")]=inspect}catch(e){BN.prototype.inspect=inspect}}else{BN.prototype.inspect=inspect}function inspect(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"];var groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5];var groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){base=base||10;padding=padding|0||1;var out;if(base===16||base==="hex"){out="";var off=0;var carry=0;for(var i=0;i<this.length;i++){var w=this.words[i];var word=((w<<off|carry)&16777215).toString(16);carry=w>>>24-off&16777215;off+=2;if(off>=26){off-=26;i--}if(carry!==0||i!==this.length-1){out=zeros[6-word.length]+word+out}else{out=word+out}}if(carry!==0){out=carry.toString(16)+out}while(out.length%padding!==0){out="0"+out}if(this.negative!==0){out="-"+out}return out}if(base===(base|0)&&base>=2&&base<=36){var groupSize=groupSizes[base];var groupBase=groupBases[base];out="";var c=this.clone();c.negative=0;while(!c.isZero()){var r=c.modrn(groupBase).toString(base);c=c.idivn(groupBase);if(!c.isZero()){out=zeros[groupSize-r.length]+r+out}else{out=r+out}}if(this.isZero()){out="0"+out}while(out.length%padding!==0){out="0"+out}if(this.negative!==0){out="-"+out}return out}assert(false,"Base should be between 2 and 36")};BN.prototype.toNumber=function toNumber(){var ret=this.words[0];if(this.length===2){ret+=this.words[1]*67108864}else if(this.length===3&&this.words[2]===1){ret+=4503599627370496+this.words[1]*67108864}else if(this.length>2){assert(false,"Number can only safely store up to 53 bits")}return this.negative!==0?-ret:ret};BN.prototype.toJSON=function toJSON(){return this.toString(16,2)};if(Buffer){BN.prototype.toBuffer=function toBuffer(endian,length){return this.toArrayLike(Buffer,endian,length)}}BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)};var allocate=function allocate(ArrayType,size){if(ArrayType.allocUnsafe){return ArrayType.allocUnsafe(size)}return new ArrayType(size)};BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){this._strip();var byteLength=this.byteLength();var reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length");assert(reqLength>0,"Requested array length <= 0");var res=allocate(ArrayType,reqLength);var postfix=endian==="le"?"LE":"BE";this["_toArrayLike"+postfix](res,byteLength);return res};BN.prototype._toArrayLikeLE=function _toArrayLikeLE(res,byteLength){var position=0;var carry=0;for(var i=0,shift=0;i<this.length;i++){var word=this.words[i]<<shift|carry;res[position++]=word&255;if(position<res.length){res[position++]=word>>8&255}if(position<res.length){res[position++]=word>>16&255}if(shift===6){if(position<res.length){res[position++]=word>>24&255}carry=0;shift=0}else{carry=word>>>24;shift+=2}}if(position<res.length){res[position++]=carry;while(position<res.length){res[position++]=0}}};BN.prototype._toArrayLikeBE=function _toArrayLikeBE(res,byteLength){var position=res.length-1;var carry=0;for(var i=0,shift=0;i<this.length;i++){var word=this.words[i]<<shift|carry;res[position--]=word&255;if(position>=0){res[position--]=word>>8&255}if(position>=0){res[position--]=word>>16&255}if(shift===6){if(position>=0){res[position--]=word>>24&255}carry=0;shift=0}else{carry=word>>>24;shift+=2}}if(position>=0){res[position--]=carry;while(position>=0){res[position--]=0}}};if(Math.clz32){BN.prototype._countBits=function _countBits(w){return 32-Math.clz32(w)}}else{BN.prototype._countBits=function _countBits(w){var t=w;var r=0;if(t>=4096){r+=13;t>>>=13}if(t>=64){r+=7;t>>>=7}if(t>=8){r+=4;t>>>=4}if(t>=2){r+=2;t>>>=2}return r+t}}BN.prototype._zeroBits=function _zeroBits(w){if(w===0)return 26;var t=w;var r=0;if((t&8191)===0){r+=13;t>>>=13}if((t&127)===0){r+=7;t>>>=7}if((t&15)===0){r+=4;t>>>=4}if((t&3)===0){r+=2;t>>>=2}if((t&1)===0){r++}return r};BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1];var hi=this._countBits(w);return(this.length-1)*26+hi};function toBitArray(num){var w=new Array(num.bitLength());for(var bit=0;bit<w.length;bit++){var off=bit/26|0;var wbit=bit%26;w[bit]=num.words[off]>>>wbit&1}return w}BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;var r=0;for(var i=0;i<this.length;i++){var b=this._zeroBits(this.words[i]);r+=b;if(b!==26)break}return r};BN.prototype.byteLength=function byteLength(){return Math.ceil(this.bitLength()/8)};BN.prototype.toTwos=function toTwos(width){if(this.negative!==0){return this.abs().inotn(width).iaddn(1)}return this.clone()};BN.prototype.fromTwos=function fromTwos(width){if(this.testn(width-1)){return this.notn(width).iaddn(1).ineg()}return this.clone()};BN.prototype.isNeg=function isNeg(){return this.negative!==0};BN.prototype.neg=function neg(){return this.clone().ineg()};BN.prototype.ineg=function ineg(){if(!this.isZero()){this.negative^=1}return this};BN.prototype.iuor=function iuor(num){while(this.length<num.length){this.words[this.length++]=0}for(var i=0;i<num.length;i++){this.words[i]=this.words[i]|num.words[i]}return this._strip()};BN.prototype.ior=function ior(num){assert((this.negative|num.negative)===0);return this.iuor(num)};BN.prototype.or=function or(num){if(this.length>num.length)return this.clone().ior(num);return num.clone().ior(this)};BN.prototype.uor=function uor(num){if(this.length>num.length)return this.clone().iuor(num);return num.clone().iuor(this)};BN.prototype.iuand=function iuand(num){var b;if(this.length>num.length){b=num}else{b=this}for(var i=0;i<b.length;i++){this.words[i]=this.words[i]&num.words[i]}this.length=b.length;return this._strip()};BN.prototype.iand=function iand(num){assert((this.negative|num.negative)===0);return this.iuand(num)};BN.prototype.and=function and(num){if(this.length>num.length)return this.clone().iand(num);return num.clone().iand(this)};BN.prototype.uand=function uand(num){if(this.length>num.length)return this.clone().iuand(num);return num.clone().iuand(this)};BN.prototype.iuxor=function iuxor(num){var a;var b;if(this.length>num.length){a=this;b=num}else{a=num;b=this}for(var i=0;i<b.length;i++){this.words[i]=a.words[i]^b.words[i]}if(this!==a){for(;i<a.length;i++){this.words[i]=a.words[i]}}this.length=a.length;return this._strip()};BN.prototype.ixor=function ixor(num){assert((this.negative|num.negative)===0);return this.iuxor(num)};BN.prototype.xor=function xor(num){if(this.length>num.length)return this.clone().ixor(num);return num.clone().ixor(this)};BN.prototype.uxor=function uxor(num){if(this.length>num.length)return this.clone().iuxor(num);return num.clone().iuxor(this)};BN.prototype.inotn=function inotn(width){assert(typeof width==="number"&&width>=0);var bytesNeeded=Math.ceil(width/26)|0;var bitsLeft=width%26;this._expand(bytesNeeded);if(bitsLeft>0){bytesNeeded--}for(var i=0;i<bytesNeeded;i++){this.words[i]=~this.words[i]&67108863}if(bitsLeft>0){this.words[i]=~this.words[i]&67108863>>26-bitsLeft}return this._strip()};BN.prototype.notn=function notn(width){return this.clone().inotn(width)};BN.prototype.setn=function setn(bit,val){assert(typeof bit==="number"&&bit>=0);var off=bit/26|0;var wbit=bit%26;this._expand(off+1);if(val){this.words[off]=this.words[off]|1<<wbit}else{this.words[off]=this.words[off]&~(1<<wbit)}return this._strip()};BN.prototype.iadd=function iadd(num){var r;if(this.negative!==0&&num.negative===0){this.negative=0;r=this.isub(num);this.negative^=1;return this._normSign()}else if(this.negative===0&&num.negative!==0){num.negative=0;r=this.isub(num);num.negative=1;return r._normSign()}var a,b;if(this.length>num.length){a=this;b=num}else{a=num;b=this}var carry=0;for(var i=0;i<b.length;i++){r=(a.words[i]|0)+(b.words[i]|0)+carry;this.words[i]=r&67108863;carry=r>>>26}for(;carry!==0&&i<a.length;i++){r=(a.words[i]|0)+carry;this.words[i]=r&67108863;carry=r>>>26}this.length=a.length;if(carry!==0){this.words[this.length]=carry;this.length++}else if(a!==this){for(;i<a.length;i++){this.words[i]=a.words[i]}}return this};BN.prototype.add=function add(num){var res;if(num.negative!==0&&this.negative===0){num.negative=0;res=this.sub(num);num.negative^=1;return res}else if(num.negative===0&&this.negative!==0){this.negative=0;res=num.sub(this);this.negative=1;return res}if(this.length>num.length)return this.clone().iadd(num);return num.clone().iadd(this)};BN.prototype.isub=function isub(num){if(num.negative!==0){num.negative=0;var r=this.iadd(num);num.negative=1;return r._normSign()}else if(this.negative!==0){this.negative=0;this.iadd(num);this.negative=1;return this._normSign()}var cmp=this.cmp(num);if(cmp===0){this.negative=0;this.length=1;this.words[0]=0;return this}var a,b;if(cmp>0){a=this;b=num}else{a=num;b=this}var carry=0;for(var i=0;i<b.length;i++){r=(a.words[i]|0)-(b.words[i]|0)+carry;carry=r>>26;this.words[i]=r&67108863}for(;carry!==0&&i<a.length;i++){r=(a.words[i]|0)+carry;carry=r>>26;this.words[i]=r&67108863}if(carry===0&&i<a.length&&a!==this){for(;i<a.length;i++){this.words[i]=a.words[i]}}this.length=Math.max(this.length,i);if(a!==this){this.negative=1}return this._strip()};BN.prototype.sub=function sub(num){return this.clone().isub(num)};function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=self.length+num.length|0;out.length=len;len=len-1|0;var a=self.words[0]|0;var b=num.words[0]|0;var r=a*b;var lo=r&67108863;var carry=r/67108864|0;out.words[0]=lo;for(var k=1;k<len;k++){var ncarry=carry>>>26;var rword=carry&67108863;var maxJ=Math.min(k,num.length-1);for(var j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;a=self.words[i]|0;b=num.words[j]|0;r=a*b+rword;ncarry+=r/67108864|0;rword=r&67108863}out.words[k]=rword|0;carry=ncarry|0}if(carry!==0){out.words[k]=carry|0}else{out.length--}return out._strip()}var comb10MulTo=function comb10MulTo(self,num,out){var a=self.words;var b=num.words;var o=out.words;var c=0;var lo;var mid;var hi;var a0=a[0]|0;var al0=a0&8191;var ah0=a0>>>13;var a1=a[1]|0;var al1=a1&8191;var ah1=a1>>>13;var a2=a[2]|0;var al2=a2&8191;var ah2=a2>>>13;var a3=a[3]|0;var al3=a3&8191;var ah3=a3>>>13;var a4=a[4]|0;var al4=a4&8191;var ah4=a4>>>13;var a5=a[5]|0;var al5=a5&8191;var ah5=a5>>>13;var a6=a[6]|0;var al6=a6&8191;var ah6=a6>>>13;var a7=a[7]|0;var al7=a7&8191;var ah7=a7>>>13;var a8=a[8]|0;var al8=a8&8191;var ah8=a8>>>13;var a9=a[9]|0;var al9=a9&8191;var ah9=a9>>>13;var b0=b[0]|0;var bl0=b0&8191;var bh0=b0>>>13;var b1=b[1]|0;var bl1=b1&8191;var bh1=b1>>>13;var b2=b[2]|0;var bl2=b2&8191;var bh2=b2>>>13;var b3=b[3]|0;var bl3=b3&8191;var bh3=b3>>>13;var b4=b[4]|0;var bl4=b4&8191;var bh4=b4>>>13;var b5=b[5]|0;var bl5=b5&8191;var bh5=b5>>>13;var b6=b[6]|0;var bl6=b6&8191;var bh6=b6>>>13;var b7=b[7]|0;var bl7=b7&8191;var bh7=b7>>>13;var b8=b[8]|0;var bl8=b8&8191;var bh8=b8>>>13;var b9=b[9]|0;var bl9=b9&8191;var bh9=b9>>>13;out.negative=self.negative^num.negative;out.length=19;lo=Math.imul(al0,bl0);mid=Math.imul(al0,bh0);mid=mid+Math.imul(ah0,bl0)|0;hi=Math.imul(ah0,bh0);var w0=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w0>>>26)|0;w0&=67108863;lo=Math.imul(al1,bl0);mid=Math.imul(al1,bh0);mid=mid+Math.imul(ah1,bl0)|0;hi=Math.imul(ah1,bh0);lo=lo+Math.imul(al0,bl1)|0;mid=mid+Math.imul(al0,bh1)|0;mid=mid+Math.imul(ah0,bl1)|0;hi=hi+Math.imul(ah0,bh1)|0;var w1=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w1>>>26)|0;w1&=67108863;lo=Math.imul(al2,bl0);mid=Math.imul(al2,bh0);mid=mid+Math.imul(ah2,bl0)|0;hi=Math.imul(ah2,bh0);lo=lo+Math.imul(al1,bl1)|0;mid=mid+Math.imul(al1,bh1)|0;mid=mid+Math.imul(ah1,bl1)|0;hi=hi+Math.imul(ah1,bh1)|0;lo=lo+Math.imul(al0,bl2)|0;mid=mid+Math.imul(al0,bh2)|0;mid=mid+Math.imul(ah0,bl2)|0;hi=hi+Math.imul(ah0,bh2)|0;var w2=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w2>>>26)|0;w2&=67108863;lo=Math.imul(al3,bl0);mid=Math.imul(al3,bh0);mid=mid+Math.imul(ah3,bl0)|0;hi=Math.imul(ah3,bh0);lo=lo+Math.imul(al2,bl1)|0;mid=mid+Math.imul(al2,bh1)|0;mid=mid+Math.imul(ah2,bl1)|0;hi=hi+Math.imul(ah2,bh1)|0;lo=lo+Math.imul(al1,bl2)|0;mid=mid+Math.imul(al1,bh2)|0;mid=mid+Math.imul(ah1,bl2)|0;hi=hi+Math.imul(ah1,bh2)|0;lo=lo+Math.imul(al0,bl3)|0;mid=mid+Math.imul(al0,bh3)|0;mid=mid+Math.imul(ah0,bl3)|0;hi=hi+Math.imul(ah0,bh3)|0;var w3=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w3>>>26)|0;w3&=67108863;lo=Math.imul(al4,bl0);mid=Math.imul(al4,bh0);mid=mid+Math.imul(ah4,bl0)|0;hi=Math.imul(ah4,bh0);lo=lo+Math.imul(al3,bl1)|0;mid=mid+Math.imul(al3,bh1)|0;mid=mid+Math.imul(ah3,bl1)|0;hi=hi+Math.imul(ah3,bh1)|0;lo=lo+Math.imul(al2,bl2)|0;mid=mid+Math.imul(al2,bh2)|0;mid=mid+Math.imul(ah2,bl2)|0;hi=hi+Math.imul(ah2,bh2)|0;lo=lo+Math.imul(al1,bl3)|0;mid=mid+Math.imul(al1,bh3)|0;mid=mid+Math.imul(ah1,bl3)|0;hi=hi+Math.imul(ah1,bh3)|0;lo=lo+Math.imul(al0,bl4)|0;mid=mid+Math.imul(al0,bh4)|0;mid=mid+Math.imul(ah0,bl4)|0;hi=hi+Math.imul(ah0,bh4)|0;var w4=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w4>>>26)|0;w4&=67108863;lo=Math.imul(al5,bl0);mid=Math.imul(al5,bh0);mid=mid+Math.imul(ah5,bl0)|0;hi=Math.imul(ah5,bh0);lo=lo+Math.imul(al4,bl1)|0;mid=mid+Math.imul(al4,bh1)|0;mid=mid+Math.imul(ah4,bl1)|0;hi=hi+Math.imul(ah4,bh1)|0;lo=lo+Math.imul(al3,bl2)|0;mid=mid+Math.imul(al3,bh2)|0;mid=mid+Math.imul(ah3,bl2)|0;hi=hi+Math.imul(ah3,bh2)|0;lo=lo+Math.imul(al2,bl3)|0;mid=mid+Math.imul(al2,bh3)|0;mid=mid+Math.imul(ah2,bl3)|0;hi=hi+Math.imul(ah2,bh3)|0;lo=lo+Math.imul(al1,bl4)|0;mid=mid+Math.imul(al1,bh4)|0;mid=mid+Math.imul(ah1,bl4)|0;hi=hi+Math.imul(ah1,bh4)|0;lo=lo+Math.imul(al0,bl5)|0;mid=mid+Math.imul(al0,bh5)|0;mid=mid+Math.imul(ah0,bl5)|0;hi=hi+Math.imul(ah0,bh5)|0;var w5=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w5>>>26)|0;w5&=67108863;lo=Math.imul(al6,bl0);mid=Math.imul(al6,bh0);mid=mid+Math.imul(ah6,bl0)|0;hi=Math.imul(ah6,bh0);lo=lo+Math.imul(al5,bl1)|0;mid=mid+Math.imul(al5,bh1)|0;mid=mid+Math.imul(ah5,bl1)|0;hi=hi+Math.imul(ah5,bh1)|0;lo=lo+Math.imul(al4,bl2)|0;mid=mid+Math.imul(al4,bh2)|0;mid=mid+Math.imul(ah4,bl2)|0;hi=hi+Math.imul(ah4,bh2)|0;lo=lo+Math.imul(al3,bl3)|0;mid=mid+Math.imul(al3,bh3)|0;mid=mid+Math.imul(ah3,bl3)|0;hi=hi+Math.imul(ah3,bh3)|0;lo=lo+Math.imul(al2,bl4)|0;mid=mid+Math.imul(al2,bh4)|0;mid=mid+Math.imul(ah2,bl4)|0;hi=hi+Math.imul(ah2,bh4)|0;lo=lo+Math.imul(al1,bl5)|0;mid=mid+Math.imul(al1,bh5)|0;mid=mid+Math.imul(ah1,bl5)|0;hi=hi+Math.imul(ah1,bh5)|0;lo=lo+Math.imul(al0,bl6)|0;mid=mid+Math.imul(al0,bh6)|0;mid=mid+Math.imul(ah0,bl6)|0;hi=hi+Math.imul(ah0,bh6)|0;var w6=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w6>>>26)|0;w6&=67108863;lo=Math.imul(al7,bl0);mid=Math.imul(al7,bh0);mid=mid+Math.imul(ah7,bl0)|0;hi=Math.imul(ah7,bh0);lo=lo+Math.imul(al6,bl1)|0;mid=mid+Math.imul(al6,bh1)|0;mid=mid+Math.imul(ah6,bl1)|0;hi=hi+Math.imul(ah6,bh1)|0;lo=lo+Math.imul(al5,bl2)|0;mid=mid+Math.imul(al5,bh2)|0;mid=mid+Math.imul(ah5,bl2)|0;hi=hi+Math.imul(ah5,bh2)|0;lo=lo+Math.imul(al4,bl3)|0;mid=mid+Math.imul(al4,bh3)|0;mid=mid+Math.imul(ah4,bl3)|0;hi=hi+Math.imul(ah4,bh3)|0;lo=lo+Math.imul(al3,bl4)|0;mid=mid+Math.imul(al3,bh4)|0;mid=mid+Math.imul(ah3,bl4)|0;hi=hi+Math.imul(ah3,bh4)|0;lo=lo+Math.imul(al2,bl5)|0;mid=mid+Math.imul(al2,bh5)|0;mid=mid+Math.imul(ah2,bl5)|0;hi=hi+Math.imul(ah2,bh5)|0;lo=lo+Math.imul(al1,bl6)|0;mid=mid+Math.imul(al1,bh6)|0;mid=mid+Math.imul(ah1,bl6)|0;hi=hi+Math.imul(ah1,bh6)|0;lo=lo+Math.imul(al0,bl7)|0;mid=mid+Math.imul(al0,bh7)|0;mid=mid+Math.imul(ah0,bl7)|0;hi=hi+Math.imul(ah0,bh7)|0;var w7=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w7>>>26)|0;w7&=67108863;lo=Math.imul(al8,bl0);mid=Math.imul(al8,bh0);mid=mid+Math.imul(ah8,bl0)|0;hi=Math.imul(ah8,bh0);lo=lo+Math.imul(al7,bl1)|0;mid=mid+Math.imul(al7,bh1)|0;mid=mid+Math.imul(ah7,bl1)|0;hi=hi+Math.imul(ah7,bh1)|0;lo=lo+Math.imul(al6,bl2)|0;mid=mid+Math.imul(al6,bh2)|0;mid=mid+Math.imul(ah6,bl2)|0;hi=hi+Math.imul(ah6,bh2)|0;lo=lo+Math.imul(al5,bl3)|0;mid=mid+Math.imul(al5,bh3)|0;mid=mid+Math.imul(ah5,bl3)|0;hi=hi+Math.imul(ah5,bh3)|0;lo=lo+Math.imul(al4,bl4)|0;mid=mid+Math.imul(al4,bh4)|0;mid=mid+Math.imul(ah4,bl4)|0;hi=hi+Math.imul(ah4,bh4)|0;lo=lo+Math.imul(al3,bl5)|0;mid=mid+Math.imul(al3,bh5)|0;mid=mid+Math.imul(ah3,bl5)|0;hi=hi+Math.imul(ah3,bh5)|0;lo=lo+Math.imul(al2,bl6)|0;mid=mid+Math.imul(al2,bh6)|0;mid=mid+Math.imul(ah2,bl6)|0;hi=hi+Math.imul(ah2,bh6)|0;lo=lo+Math.imul(al1,bl7)|0;mid=mid+Math.imul(al1,bh7)|0;mid=mid+Math.imul(ah1,bl7)|0;hi=hi+Math.imul(ah1,bh7)|0;lo=lo+Math.imul(al0,bl8)|0;mid=mid+Math.imul(al0,bh8)|0;mid=mid+Math.imul(ah0,bl8)|0;hi=hi+Math.imul(ah0,bh8)|0;var w8=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w8>>>26)|0;w8&=67108863;lo=Math.imul(al9,bl0);mid=Math.imul(al9,bh0);mid=mid+Math.imul(ah9,bl0)|0;hi=Math.imul(ah9,bh0);lo=lo+Math.imul(al8,bl1)|0;mid=mid+Math.imul(al8,bh1)|0;mid=mid+Math.imul(ah8,bl1)|0;hi=hi+Math.imul(ah8,bh1)|0;lo=lo+Math.imul(al7,bl2)|0;mid=mid+Math.imul(al7,bh2)|0;mid=mid+Math.imul(ah7,bl2)|0;hi=hi+Math.imul(ah7,bh2)|0;lo=lo+Math.imul(al6,bl3)|0;mid=mid+Math.imul(al6,bh3)|0;mid=mid+Math.imul(ah6,bl3)|0;hi=hi+Math.imul(ah6,bh3)|0;lo=lo+Math.imul(al5,bl4)|0;mid=mid+Math.imul(al5,bh4)|0;mid=mid+Math.imul(ah5,bl4)|0;hi=hi+Math.imul(ah5,bh4)|0;lo=lo+Math.imul(al4,bl5)|0;mid=mid+Math.imul(al4,bh5)|0;mid=mid+Math.imul(ah4,bl5)|0;hi=hi+Math.imul(ah4,bh5)|0;lo=lo+Math.imul(al3,bl6)|0;mid=mid+Math.imul(al3,bh6)|0;mid=mid+Math.imul(ah3,bl6)|0;hi=hi+Math.imul(ah3,bh6)|0;lo=lo+Math.imul(al2,bl7)|0;mid=mid+Math.imul(al2,bh7)|0;mid=mid+Math.imul(ah2,bl7)|0;hi=hi+Math.imul(ah2,bh7)|0;lo=lo+Math.imul(al1,bl8)|0;mid=mid+Math.imul(al1,bh8)|0;mid=mid+Math.imul(ah1,bl8)|0;hi=hi+Math.imul(ah1,bh8)|0;lo=lo+Math.imul(al0,bl9)|0;mid=mid+Math.imul(al0,bh9)|0;mid=mid+Math.imul(ah0,bl9)|0;hi=hi+Math.imul(ah0,bh9)|0;var w9=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w9>>>26)|0;w9&=67108863;lo=Math.imul(al9,bl1);mid=Math.imul(al9,bh1);mid=mid+Math.imul(ah9,bl1)|0;hi=Math.imul(ah9,bh1);lo=lo+Math.imul(al8,bl2)|0;mid=mid+Math.imul(al8,bh2)|0;mid=mid+Math.imul(ah8,bl2)|0;hi=hi+Math.imul(ah8,bh2)|0;lo=lo+Math.imul(al7,bl3)|0;mid=mid+Math.imul(al7,bh3)|0;mid=mid+Math.imul(ah7,bl3)|0;hi=hi+Math.imul(ah7,bh3)|0;lo=lo+Math.imul(al6,bl4)|0;mid=mid+Math.imul(al6,bh4)|0;mid=mid+Math.imul(ah6,bl4)|0;hi=hi+Math.imul(ah6,bh4)|0;lo=lo+Math.imul(al5,bl5)|0;mid=mid+Math.imul(al5,bh5)|0;mid=mid+Math.imul(ah5,bl5)|0;hi=hi+Math.imul(ah5,bh5)|0;lo=lo+Math.imul(al4,bl6)|0;mid=mid+Math.imul(al4,bh6)|0;mid=mid+Math.imul(ah4,bl6)|0;hi=hi+Math.imul(ah4,bh6)|0;lo=lo+Math.imul(al3,bl7)|0;mid=mid+Math.imul(al3,bh7)|0;mid=mid+Math.imul(ah3,bl7)|0;hi=hi+Math.imul(ah3,bh7)|0;lo=lo+Math.imul(al2,bl8)|0;mid=mid+Math.imul(al2,bh8)|0;mid=mid+Math.imul(ah2,bl8)|0;hi=hi+Math.imul(ah2,bh8)|0;lo=lo+Math.imul(al1,bl9)|0;mid=mid+Math.imul(al1,bh9)|0;mid=mid+Math.imul(ah1,bl9)|0;hi=hi+Math.imul(ah1,bh9)|0;var w10=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w10>>>26)|0;w10&=67108863;lo=Math.imul(al9,bl2);mid=Math.imul(al9,bh2);mid=mid+Math.imul(ah9,bl2)|0;hi=Math.imul(ah9,bh2);lo=lo+Math.imul(al8,bl3)|0;mid=mid+Math.imul(al8,bh3)|0;mid=mid+Math.imul(ah8,bl3)|0;hi=hi+Math.imul(ah8,bh3)|0;lo=lo+Math.imul(al7,bl4)|0;mid=mid+Math.imul(al7,bh4)|0;mid=mid+Math.imul(ah7,bl4)|0;hi=hi+Math.imul(ah7,bh4)|0;lo=lo+Math.imul(al6,bl5)|0;mid=mid+Math.imul(al6,bh5)|0;mid=mid+Math.imul(ah6,bl5)|0;hi=hi+Math.imul(ah6,bh5)|0;lo=lo+Math.imul(al5,bl6)|0;mid=mid+Math.imul(al5,bh6)|0;mid=mid+Math.imul(ah5,bl6)|0;hi=hi+Math.imul(ah5,bh6)|0;lo=lo+Math.imul(al4,bl7)|0;mid=mid+Math.imul(al4,bh7)|0;mid=mid+Math.imul(ah4,bl7)|0;hi=hi+Math.imul(ah4,bh7)|0;lo=lo+Math.imul(al3,bl8)|0;mid=mid+Math.imul(al3,bh8)|0;mid=mid+Math.imul(ah3,bl8)|0;hi=hi+Math.imul(ah3,bh8)|0;lo=lo+Math.imul(al2,bl9)|0;mid=mid+Math.imul(al2,bh9)|0;mid=mid+Math.imul(ah2,bl9)|0;hi=hi+Math.imul(ah2,bh9)|0;var w11=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w11>>>26)|0;w11&=67108863;lo=Math.imul(al9,bl3);mid=Math.imul(al9,bh3);mid=mid+Math.imul(ah9,bl3)|0;hi=Math.imul(ah9,bh3);lo=lo+Math.imul(al8,bl4)|0;mid=mid+Math.imul(al8,bh4)|0;mid=mid+Math.imul(ah8,bl4)|0;hi=hi+Math.imul(ah8,bh4)|0;lo=lo+Math.imul(al7,bl5)|0;mid=mid+Math.imul(al7,bh5)|0;mid=mid+Math.imul(ah7,bl5)|0;hi=hi+Math.imul(ah7,bh5)|0;lo=lo+Math.imul(al6,bl6)|0;mid=mid+Math.imul(al6,bh6)|0;mid=mid+Math.imul(ah6,bl6)|0;hi=hi+Math.imul(ah6,bh6)|0;lo=lo+Math.imul(al5,bl7)|0;mid=mid+Math.imul(al5,bh7)|0;mid=mid+Math.imul(ah5,bl7)|0;hi=hi+Math.imul(ah5,bh7)|0;lo=lo+Math.imul(al4,bl8)|0;mid=mid+Math.imul(al4,bh8)|0;mid=mid+Math.imul(ah4,bl8)|0;hi=hi+Math.imul(ah4,bh8)|0;lo=lo+Math.imul(al3,bl9)|0;mid=mid+Math.imul(al3,bh9)|0;mid=mid+Math.imul(ah3,bl9)|0;hi=hi+Math.imul(ah3,bh9)|0;var w12=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w12>>>26)|0;w12&=67108863;lo=Math.imul(al9,bl4);mid=Math.imul(al9,bh4);mid=mid+Math.imul(ah9,bl4)|0;hi=Math.imul(ah9,bh4);lo=lo+Math.imul(al8,bl5)|0;mid=mid+Math.imul(al8,bh5)|0;mid=mid+Math.imul(ah8,bl5)|0;hi=hi+Math.imul(ah8,bh5)|0;lo=lo+Math.imul(al7,bl6)|0;mid=mid+Math.imul(al7,bh6)|0;mid=mid+Math.imul(ah7,bl6)|0;hi=hi+Math.imul(ah7,bh6)|0;lo=lo+Math.imul(al6,bl7)|0;mid=mid+Math.imul(al6,bh7)|0;mid=mid+Math.imul(ah6,bl7)|0;hi=hi+Math.imul(ah6,bh7)|0;lo=lo+Math.imul(al5,bl8)|0;mid=mid+Math.imul(al5,bh8)|0;mid=mid+Math.imul(ah5,bl8)|0;hi=hi+Math.imul(ah5,bh8)|0;lo=lo+Math.imul(al4,bl9)|0;mid=mid+Math.imul(al4,bh9)|0;mid=mid+Math.imul(ah4,bl9)|0;hi=hi+Math.imul(ah4,bh9)|0;var w13=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w13>>>26)|0;w13&=67108863;lo=Math.imul(al9,bl5);mid=Math.imul(al9,bh5);mid=mid+Math.imul(ah9,bl5)|0;hi=Math.imul(ah9,bh5);lo=lo+Math.imul(al8,bl6)|0;mid=mid+Math.imul(al8,bh6)|0;mid=mid+Math.imul(ah8,bl6)|0;hi=hi+Math.imul(ah8,bh6)|0;lo=lo+Math.imul(al7,bl7)|0;mid=mid+Math.imul(al7,bh7)|0;mid=mid+Math.imul(ah7,bl7)|0;hi=hi+Math.imul(ah7,bh7)|0;lo=lo+Math.imul(al6,bl8)|0;mid=mid+Math.imul(al6,bh8)|0;mid=mid+Math.imul(ah6,bl8)|0;hi=hi+Math.imul(ah6,bh8)|0;lo=lo+Math.imul(al5,bl9)|0;mid=mid+Math.imul(al5,bh9)|0;mid=mid+Math.imul(ah5,bl9)|0;hi=hi+Math.imul(ah5,bh9)|0;var w14=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w14>>>26)|0;w14&=67108863;lo=Math.imul(al9,bl6);mid=Math.imul(al9,bh6);mid=mid+Math.imul(ah9,bl6)|0;hi=Math.imul(ah9,bh6);lo=lo+Math.imul(al8,bl7)|0;mid=mid+Math.imul(al8,bh7)|0;mid=mid+Math.imul(ah8,bl7)|0;hi=hi+Math.imul(ah8,bh7)|0;lo=lo+Math.imul(al7,bl8)|0;mid=mid+Math.imul(al7,bh8)|0;mid=mid+Math.imul(ah7,bl8)|0;hi=hi+Math.imul(ah7,bh8)|0;lo=lo+Math.imul(al6,bl9)|0;mid=mid+Math.imul(al6,bh9)|0;mid=mid+Math.imul(ah6,bl9)|0;hi=hi+Math.imul(ah6,bh9)|0;var w15=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w15>>>26)|0;w15&=67108863;lo=Math.imul(al9,bl7);mid=Math.imul(al9,bh7);mid=mid+Math.imul(ah9,bl7)|0;hi=Math.imul(ah9,bh7);lo=lo+Math.imul(al8,bl8)|0;mid=mid+Math.imul(al8,bh8)|0;mid=mid+Math.imul(ah8,bl8)|0;hi=hi+Math.imul(ah8,bh8)|0;lo=lo+Math.imul(al7,bl9)|0;mid=mid+Math.imul(al7,bh9)|0;mid=mid+Math.imul(ah7,bl9)|0;hi=hi+Math.imul(ah7,bh9)|0;var w16=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w16>>>26)|0;w16&=67108863;lo=Math.imul(al9,bl8);mid=Math.imul(al9,bh8);mid=mid+Math.imul(ah9,bl8)|0;hi=Math.imul(ah9,bh8);lo=lo+Math.imul(al8,bl9)|0;mid=mid+Math.imul(al8,bh9)|0;mid=mid+Math.imul(ah8,bl9)|0;hi=hi+Math.imul(ah8,bh9)|0;var w17=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w17>>>26)|0;w17&=67108863;lo=Math.imul(al9,bl9);mid=Math.imul(al9,bh9);mid=mid+Math.imul(ah9,bl9)|0;hi=Math.imul(ah9,bh9);var w18=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w18>>>26)|0;w18&=67108863;o[0]=w0;o[1]=w1;o[2]=w2;o[3]=w3;o[4]=w4;o[5]=w5;o[6]=w6;o[7]=w7;o[8]=w8;o[9]=w9;o[10]=w10;o[11]=w11;o[12]=w12;o[13]=w13;o[14]=w14;o[15]=w15;o[16]=w16;o[17]=w17;o[18]=w18;if(c!==0){o[19]=c;out.length++}return out};if(!Math.imul){comb10MulTo=smallMulTo}function bigMulTo(self,num,out){out.negative=num.negative^self.negative;out.length=self.length+num.length;var carry=0;var hncarry=0;for(var k=0;k<out.length-1;k++){var ncarry=hncarry;hncarry=0;var rword=carry&67108863;var maxJ=Math.min(k,num.length-1);for(var j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j;var a=self.words[i]|0;var b=num.words[j]|0;var r=a*b;var lo=r&67108863;ncarry=ncarry+(r/67108864|0)|0;lo=lo+rword|0;rword=lo&67108863;ncarry=ncarry+(lo>>>26)|0;hncarry+=ncarry>>>26;ncarry&=67108863}out.words[k]=rword;carry=ncarry;ncarry=hncarry}if(carry!==0){out.words[k]=carry}else{out.length--}return out._strip()}function jumboMulTo(self,num,out){return bigMulTo(self,num,out)}BN.prototype.mulTo=function mulTo(num,out){var res;var len=this.length+num.length;if(this.length===10&&num.length===10){res=comb10MulTo(this,num,out)}else if(len<63){res=smallMulTo(this,num,out)}else if(len<1024){res=bigMulTo(this,num,out)}else{res=jumboMulTo(this,num,out)}return res};BN.prototype.mul=function mul(num){var out=new BN(null);out.words=new Array(this.length+num.length);return this.mulTo(num,out)};BN.prototype.mulf=function mulf(num){var out=new BN(null);out.words=new Array(this.length+num.length);return jumboMulTo(this,num,out)};BN.prototype.imul=function imul(num){return this.clone().mulTo(num,this)};BN.prototype.imuln=function imuln(num){var isNegNum=num<0;if(isNegNum)num=-num;assert(typeof num==="number");assert(num<67108864);var carry=0;for(var i=0;i<this.length;i++){var w=(this.words[i]|0)*num;var lo=(w&67108863)+(carry&67108863);carry>>=26;carry+=w/67108864|0;carry+=lo>>>26;this.words[i]=lo&67108863}if(carry!==0){this.words[i]=carry;this.length++}return isNegNum?this.ineg():this};BN.prototype.muln=function muln(num){return this.clone().imuln(num)};BN.prototype.sqr=function sqr(){return this.mul(this)};BN.prototype.isqr=function isqr(){return this.imul(this.clone())};BN.prototype.pow=function pow(num){var w=toBitArray(num);if(w.length===0)return new BN(1);var res=this;for(var i=0;i<w.length;i++,res=res.sqr()){if(w[i]!==0)break}if(++i<w.length){for(var q=res.sqr();i<w.length;i++,q=q.sqr()){if(w[i]===0)continue;res=res.mul(q)}}return res};BN.prototype.iushln=function iushln(bits){assert(typeof bits==="number"&&bits>=0);var r=bits%26;var s=(bits-r)/26;var carryMask=67108863>>>26-r<<26-r;var i;if(r!==0){var carry=0;for(i=0;i<this.length;i++){var newCarry=this.words[i]&carryMask;var c=(this.words[i]|0)-newCarry<<r;this.words[i]=c|carry;carry=newCarry>>>26-r}if(carry){this.words[i]=carry;this.length++}}if(s!==0){for(i=this.length-1;i>=0;i--){this.words[i+s]=this.words[i]}for(i=0;i<s;i++){this.words[i]=0}this.length+=s}return this._strip()};BN.prototype.ishln=function ishln(bits){assert(this.negative===0);return this.iushln(bits)};BN.prototype.iushrn=function iushrn(bits,hint,extended){assert(typeof bits==="number"&&bits>=0);var h;if(hint){h=(hint-hint%26)/26}else{h=0}var r=bits%26;var s=Math.min((bits-r)/26,this.length);var mask=67108863^67108863>>>r<<r;var maskedWords=extended;h-=s;h=Math.max(0,h);if(maskedWords){for(var i=0;i<s;i++){maskedWords.words[i]=this.words[i]}maskedWords.length=s}if(s===0);else if(this.length>s){this.length-=s;for(i=0;i<this.length;i++){this.words[i]=this.words[i+s]}}else{this.words[0]=0;this.length=1}var carry=0;for(i=this.length-1;i>=0&&(carry!==0||i>=h);i--){var word=this.words[i]|0;this.words[i]=carry<<26-r|word>>>r;carry=word&mask}if(maskedWords&&carry!==0){maskedWords.words[maskedWords.length++]=carry}if(this.length===0){this.words[0]=0;this.length=1}return this._strip()};BN.prototype.ishrn=function ishrn(bits,hint,extended){assert(this.negative===0);return this.iushrn(bits,hint,extended)};BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)};BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)};BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)};BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)};BN.prototype.testn=function testn(bit){assert(typeof bit==="number"&&bit>=0);var r=bit%26;var s=(bit-r)/26;var q=1<<r;if(this.length<=s)return false;var w=this.words[s];return!!(w&q)};BN.prototype.imaskn=function imaskn(bits){assert(typeof bits==="number"&&bits>=0);var r=bits%26;var s=(bits-r)/26;assert(this.negative===0,"imaskn works only with positive numbers");if(this.length<=s){return this}if(r!==0){s++}this.length=Math.min(s,this.length);if(r!==0){var mask=67108863^67108863>>>r<<r;this.words[this.length-1]&=mask}return this._strip()};BN.prototype.maskn=function maskn(bits){return this.clone().imaskn(bits)};BN.prototype.iaddn=function iaddn(num){assert(typeof num==="number");assert(num<67108864);if(num<0)return this.isubn(-num);if(this.negative!==0){if(this.length===1&&(this.words[0]|0)<=num){this.words[0]=num-(this.words[0]|0);this.negative=0;return this}this.negative=0;this.isubn(num);this.negative=1;return this}return this._iaddn(num)};BN.prototype._iaddn=function _iaddn(num){this.words[0]+=num;for(var i=0;i<this.length&&this.words[i]>=67108864;i++){this.words[i]-=67108864;if(i===this.length-1){this.words[i+1]=1}else{this.words[i+1]++}}this.length=Math.max(this.length,i+1);return this};BN.prototype.isubn=function isubn(num){assert(typeof num==="number");assert(num<67108864);if(num<0)return this.iaddn(-num);if(this.negative!==0){this.negative=0;this.iaddn(num);this.negative=1;return this}this.words[0]-=num;if(this.length===1&&this.words[0]<0){this.words[0]=-this.words[0];this.negative=1}else{for(var i=0;i<this.length&&this.words[i]<0;i++){this.words[i]+=67108864;this.words[i+1]-=1}}return this._strip()};BN.prototype.addn=function addn(num){return this.clone().iaddn(num)};BN.prototype.subn=function subn(num){return this.clone().isubn(num)};BN.prototype.iabs=function iabs(){this.negative=0;return this};BN.prototype.abs=function abs(){return this.clone().iabs()};BN.prototype._ishlnsubmul=function _ishlnsubmul(num,mul,shift){var len=num.length+shift;var i;this._expand(len);var w;var carry=0;for(i=0;i<num.length;i++){w=(this.words[i+shift]|0)+carry;var right=(num.words[i]|0)*mul;w-=right&67108863;carry=(w>>26)-(right/67108864|0);this.words[i+shift]=w&67108863}for(;i<this.length-shift;i++){w=(this.words[i+shift]|0)+carry;carry=w>>26;this.words[i+shift]=w&67108863}if(carry===0)return this._strip();assert(carry===-1);carry=0;for(i=0;i<this.length;i++){w=-(this.words[i]|0)+carry;carry=w>>26;this.words[i]=w&67108863}this.negative=1;return this._strip()};BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=this.length-num.length;var a=this.clone();var b=num;var bhi=b.words[b.length-1]|0;var bhiBits=this._countBits(bhi);shift=26-bhiBits;if(shift!==0){b=b.ushln(shift);a.iushln(shift);bhi=b.words[b.length-1]|0}var m=a.length-b.length;var q;if(mode!=="mod"){q=new BN(null);q.length=m+1;q.words=new Array(q.length);for(var i=0;i<q.length;i++){q.words[i]=0}}var diff=a.clone()._ishlnsubmul(b,1,m);if(diff.negative===0){a=diff;if(q){q.words[m]=1}}for(var j=m-1;j>=0;j--){var qj=(a.words[b.length+j]|0)*67108864+(a.words[b.length+j-1]|0);qj=Math.min(qj/bhi|0,67108863);a._ishlnsubmul(b,qj,j);while(a.negative!==0){qj--;a.negative=0;a._ishlnsubmul(b,1,j);if(!a.isZero()){a.negative^=1}}if(q){q.words[j]=qj}}if(q){q._strip()}a._strip();if(mode!=="div"&&shift!==0){a.iushrn(shift)}return{div:q||null,mod:a}};BN.prototype.divmod=function divmod(num,mode,positive){assert(!num.isZero());if(this.isZero()){return{div:new BN(0),mod:new BN(0)}}var div,mod,res;if(this.negative!==0&&num.negative===0){res=this.neg().divmod(num,mode);if(mode!=="mod"){div=res.div.neg()}if(mode!=="div"){mod=res.mod.neg();if(positive&&mod.negative!==0){mod.iadd(num)}}return{div:div,mod:mod}}if(this.negative===0&&num.negative!==0){res=this.divmod(num.neg(),mode);if(mode!=="mod"){div=res.div.neg()}return{div:div,mod:res.mod}}if((this.negative&num.negative)!==0){res=this.neg().divmod(num.neg(),mode);if(mode!=="div"){mod=res.mod.neg();if(positive&&mod.negative!==0){mod.isub(num)}}return{div:res.div,mod:mod}}if(num.length>this.length||this.cmp(num)<0){return{div:new BN(0),mod:this}}if(num.length===1){if(mode==="div"){return{div:this.divn(num.words[0]),mod:null}}if(mode==="mod"){return{div:null,mod:new BN(this.modrn(num.words[0]))}}return{div:this.divn(num.words[0]),mod:new BN(this.modrn(num.words[0]))}}return this._wordDiv(num,mode)};BN.prototype.div=function div(num){return this.divmod(num,"div",false).div};BN.prototype.mod=function mod(num){return this.divmod(num,"mod",false).mod};BN.prototype.umod=function umod(num){return this.divmod(num,"mod",true).mod};BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=dm.div.negative!==0?dm.mod.isub(num):dm.mod;var half=num.ushrn(1);var r2=num.andln(1);var cmp=mod.cmp(half);if(cmp<0||r2===1&&cmp===0)return dm.div;return dm.div.negative!==0?dm.div.isubn(1):dm.div.iaddn(1)};BN.prototype.modrn=function modrn(num){var isNegNum=num<0;if(isNegNum)num=-num;assert(num<=67108863);var p=(1<<26)%num;var acc=0;for(var i=this.length-1;i>=0;i--){acc=(p*acc+(this.words[i]|0))%num}return isNegNum?-acc:acc};BN.prototype.modn=function modn(num){return this.modrn(num)};BN.prototype.idivn=function idivn(num){var isNegNum=num<0;if(isNegNum)num=-num;assert(num<=67108863);var carry=0;for(var i=this.length-1;i>=0;i--){var w=(this.words[i]|0)+carry*67108864;this.words[i]=w/num|0;carry=w%num}this._strip();return isNegNum?this.ineg():this};BN.prototype.divn=function divn(num){return this.clone().idivn(num)};BN.prototype.egcd=function egcd(p){assert(p.negative===0);assert(!p.isZero());var x=this;var y=p.clone();if(x.negative!==0){x=x.umod(p)}else{x=x.clone()}var A=new BN(1);var B=new BN(0);var C=new BN(0);var D=new BN(1);var g=0;while(x.isEven()&&y.isEven()){x.iushrn(1);y.iushrn(1);++g}var yp=y.clone();var xp=x.clone();while(!x.isZero()){for(var i=0,im=1;(x.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0){x.iushrn(i);while(i-- >0){if(A.isOdd()||B.isOdd()){A.iadd(yp);B.isub(xp)}A.iushrn(1);B.iushrn(1)}}for(var j=0,jm=1;(y.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0){y.iushrn(j);while(j-- >0){if(C.isOdd()||D.isOdd()){C.iadd(yp);D.isub(xp)}C.iushrn(1);D.iushrn(1)}}if(x.cmp(y)>=0){x.isub(y);A.isub(C);B.isub(D)}else{y.isub(x);C.isub(A);D.isub(B)}}return{a:C,b:D,gcd:y.iushln(g)}};BN.prototype._invmp=function _invmp(p){assert(p.negative===0);assert(!p.isZero());var a=this;var b=p.clone();if(a.negative!==0){a=a.umod(p)}else{a=a.clone()}var x1=new BN(1);var x2=new BN(0);var delta=b.clone();while(a.cmpn(1)>0&&b.cmpn(1)>0){for(var i=0,im=1;(a.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0){a.iushrn(i);while(i-- >0){if(x1.isOdd()){x1.iadd(delta)}x1.iushrn(1)}}for(var j=0,jm=1;(b.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0){b.iushrn(j);while(j-- >0){if(x2.isOdd()){x2.iadd(delta)}x2.iushrn(1)}}if(a.cmp(b)>=0){a.isub(b);x1.isub(x2)}else{b.isub(a);x2.isub(x1)}}var res;if(a.cmpn(1)===0){res=x1}else{res=x2}if(res.cmpn(0)<0){res.iadd(p)}return res};BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone();var b=num.clone();a.negative=0;b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++){a.iushrn(1);b.iushrn(1)}do{while(a.isEven()){a.iushrn(1)}while(b.isEven()){b.iushrn(1)}var r=a.cmp(b);if(r<0){var t=a;a=b;b=t}else if(r===0||b.cmpn(1)===0){break}a.isub(b)}while(true);return b.iushln(shift)};BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)};BN.prototype.isEven=function isEven(){return(this.words[0]&1)===0};BN.prototype.isOdd=function isOdd(){return(this.words[0]&1)===1};BN.prototype.andln=function andln(num){return this.words[0]&num};BN.prototype.bincn=function bincn(bit){assert(typeof bit==="number");var r=bit%26;var s=(bit-r)/26;var q=1<<r;if(this.length<=s){this._expand(s+1);this.words[s]|=q;return this}var carry=q;for(var i=s;carry!==0&&i<this.length;i++){var w=this.words[i]|0;w+=carry;carry=w>>>26;w&=67108863;this.words[i]=w}if(carry!==0){this.words[i]=carry;this.length++}return this};BN.prototype.isZero=function isZero(){return this.length===1&&this.words[0]===0};BN.prototype.cmpn=function cmpn(num){var negative=num<0;if(this.negative!==0&&!negative)return-1;if(this.negative===0&&negative)return 1;this._strip();var res;if(this.length>1){res=1}else{if(negative){num=-num}assert(num<=67108863,"Number is too big");var w=this.words[0]|0;res=w===num?0:w<num?-1:1}if(this.negative!==0)return-res|0;return res};BN.prototype.cmp=function cmp(num){if(this.negative!==0&&num.negative===0)return-1;if(this.negative===0&&num.negative!==0)return 1;var res=this.ucmp(num);if(this.negative!==0)return-res|0;return res};BN.prototype.ucmp=function ucmp(num){if(this.length>num.length)return 1;if(this.length<num.length)return-1;var res=0;for(var i=this.length-1;i>=0;i--){var a=this.words[i]|0;var b=num.words[i]|0;if(a===b)continue;if(a<b){res=-1}else if(a>b){res=1}break}return res};BN.prototype.gtn=function gtn(num){return this.cmpn(num)===1};BN.prototype.gt=function gt(num){return this.cmp(num)===1};BN.prototype.gten=function gten(num){return this.cmpn(num)>=0};BN.prototype.gte=function gte(num){return this.cmp(num)>=0};BN.prototype.ltn=function ltn(num){return this.cmpn(num)===-1};BN.prototype.lt=function lt(num){return this.cmp(num)===-1};BN.prototype.lten=function lten(num){return this.cmpn(num)<=0};BN.prototype.lte=function lte(num){return this.cmp(num)<=0};BN.prototype.eqn=function eqn(num){return this.cmpn(num)===0};BN.prototype.eq=function eq(num){return this.cmp(num)===0};BN.red=function red(num){return new Red(num)};BN.prototype.toRed=function toRed(ctx){assert(!this.red,"Already a number in reduction context");assert(this.negative===0,"red works only with positives");return ctx.convertTo(this)._forceRed(ctx)};BN.prototype.fromRed=function fromRed(){assert(this.red,"fromRed works only with numbers in reduction context");return this.red.convertFrom(this)};BN.prototype._forceRed=function _forceRed(ctx){this.red=ctx;return this};BN.prototype.forceRed=function forceRed(ctx){assert(!this.red,"Already a number in reduction context");return this._forceRed(ctx)};BN.prototype.redAdd=function redAdd(num){assert(this.red,"redAdd works only with red numbers");return this.red.add(this,num)};BN.prototype.redIAdd=function redIAdd(num){assert(this.red,"redIAdd works only with red numbers");return this.red.iadd(this,num)};BN.prototype.redSub=function redSub(num){assert(this.red,"redSub works only with red numbers");return this.red.sub(this,num)};BN.prototype.redISub=function redISub(num){assert(this.red,"redISub works only with red numbers");return this.red.isub(this,num)};BN.prototype.redShl=function redShl(num){assert(this.red,"redShl works only with red numbers");return this.red.shl(this,num)};BN.prototype.redMul=function redMul(num){assert(this.red,"redMul works only with red numbers");this.red._verify2(this,num);return this.red.mul(this,num)};BN.prototype.redIMul=function redIMul(num){assert(this.red,"redMul works only with red numbers");this.red._verify2(this,num);return this.red.imul(this,num)};BN.prototype.redSqr=function redSqr(){assert(this.red,"redSqr works only with red numbers");this.red._verify1(this);return this.red.sqr(this)};BN.prototype.redISqr=function redISqr(){assert(this.red,"redISqr works only with red numbers");this.red._verify1(this);return this.red.isqr(this)};BN.prototype.redSqrt=function redSqrt(){assert(this.red,"redSqrt works only with red numbers");this.red._verify1(this);return this.red.sqrt(this)};BN.prototype.redInvm=function redInvm(){assert(this.red,"redInvm works only with red numbers");this.red._verify1(this);return this.red.invm(this)};BN.prototype.redNeg=function redNeg(){assert(this.red,"redNeg works only with red numbers");this.red._verify1(this);return this.red.neg(this)};BN.prototype.redPow=function redPow(num){assert(this.red&&!num.red,"redPow(normalNum)");this.red._verify1(this);return this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name;this.p=new BN(p,16);this.n=this.p.bitLength();this.k=new BN(1).iushln(this.n).isub(this.p);this.tmp=this._tmp()}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);tmp.words=new Array(Math.ceil(this.n/13));return tmp};MPrime.prototype.ireduce=function ireduce(num){var r=num;var rlen;do{this.split(r,this.tmp);r=this.imulK(r);r=r.iadd(this.tmp);rlen=r.bitLength()}while(rlen>this.n);var cmp=rlen<this.n?-1:r.ucmp(this.p);if(cmp===0){r.words[0]=0;r.length=1}else if(cmp>0){r.isub(this.p)}else{if(r.strip!==undefined){r.strip()}else{r._strip()}}return r};MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)};MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)};function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}inherits(K256,MPrime);K256.prototype.split=function split(input,output){var mask=4194303;var outLen=Math.min(input.length,9);for(var i=0;i<outLen;i++){output.words[i]=input.words[i]}output.length=outLen;if(input.length<=9){input.words[0]=0;input.length=1;return}var prev=input.words[9];output.words[output.length++]=prev&mask;for(i=10;i<input.length;i++){var next=input.words[i]|0;input.words[i-10]=(next&mask)<<4|prev>>>22;prev=next}prev>>>=22;input.words[i-10]=prev;if(prev===0&&input.length>10){input.length-=10}else{input.length-=9}};K256.prototype.imulK=function imulK(num){num.words[num.length]=0;num.words[num.length+1]=0;num.length+=2;var lo=0;for(var i=0;i<num.length;i++){var w=num.words[i]|0;lo+=w*977;num.words[i]=lo&67108863;lo=w*64+(lo/67108864|0)}if(num.words[num.length-1]===0){num.length--;if(num.words[num.length-1]===0){num.length--}}return num};function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}inherits(P224,MPrime);function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}inherits(P192,MPrime);function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}inherits(P25519,MPrime);P25519.prototype.imulK=function imulK(num){var carry=0;for(var i=0;i<num.length;i++){var hi=(num.words[i]|0)*19+carry;var lo=hi&67108863;hi>>>=26;num.words[i]=lo;carry=hi}if(carry!==0){num.words[num.length++]=carry}return num};BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if(name==="k256"){prime=new K256}else if(name==="p224"){prime=new P224}else if(name==="p192"){prime=new P192}else if(name==="p25519"){prime=new P25519}else{throw new Error("Unknown prime "+name)}primes[name]=prime;return prime};function Red(m){if(typeof m==="string"){var prime=BN._prime(m);this.m=prime.p;this.prime=prime}else{assert(m.gtn(1),"modulus must be greater than 1");this.m=m;this.prime=null}}Red.prototype._verify1=function _verify1(a){assert(a.negative===0,"red works only with positives");assert(a.red,"red works only with red numbers")};Red.prototype._verify2=function _verify2(a,b){assert((a.negative|b.negative)===0,"red works only with positives");assert(a.red&&a.red===b.red,"red works only with red numbers")};Red.prototype.imod=function imod(a){if(this.prime)return this.prime.ireduce(a)._forceRed(this);move(a,a.umod(this.m)._forceRed(this));return a};Red.prototype.neg=function neg(a){if(a.isZero()){return a.clone()}return this.m.sub(a)._forceRed(this)};Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);if(res.cmp(this.m)>=0){res.isub(this.m)}return res._forceRed(this)};Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);if(res.cmp(this.m)>=0){res.isub(this.m)}return res};Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);if(res.cmpn(0)<0){res.iadd(this.m)}return res._forceRed(this)};Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);if(res.cmpn(0)<0){res.iadd(this.m)}return res};Red.prototype.shl=function shl(a,num){this._verify1(a);return this.imod(a.ushln(num))};Red.prototype.imul=function imul(a,b){this._verify2(a,b);return this.imod(a.imul(b))};Red.prototype.mul=function mul(a,b){this._verify2(a,b);return this.imod(a.mul(b))};Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())};Red.prototype.sqr=function sqr(a){return this.mul(a,a)};Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);assert(mod3%2===1);if(mod3===3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}var q=this.m.subn(1);var s=0;while(!q.isZero()&&q.andln(1)===0){s++;q.iushrn(1)}assert(!q.isZero());var one=new BN(1).toRed(this);var nOne=one.redNeg();var lpow=this.m.subn(1).iushrn(1);var z=this.m.bitLength();z=new BN(2*z*z).toRed(this);while(this.pow(z,lpow).cmp(nOne)!==0){z.redIAdd(nOne)}var c=this.pow(z,q);var r=this.pow(a,q.addn(1).iushrn(1));var t=this.pow(a,q);var m=s;while(t.cmp(one)!==0){var tmp=t;for(var i=0;tmp.cmp(one)!==0;i++){tmp=tmp.redSqr()}assert(i<m);var b=this.pow(c,new BN(1).iushln(m-i-1));r=r.redMul(b);c=b.redSqr();t=t.redMul(c);m=i}return r};Red.prototype.invm=function invm(a){var inv=a._invmp(this.m);if(inv.negative!==0){inv.negative=0;return this.imod(inv).redNeg()}else{return this.imod(inv)}};Red.prototype.pow=function pow(a,num){if(num.isZero())return new BN(1).toRed(this);if(num.cmpn(1)===0)return a.clone();var windowSize=4;var wnd=new Array(1<<windowSize);wnd[0]=new BN(1).toRed(this);wnd[1]=a;for(var i=2;i<wnd.length;i++){wnd[i]=this.mul(wnd[i-1],a)}var res=wnd[0];var current=0;var currentLen=0;var start=num.bitLength()%26;if(start===0){start=26}for(i=num.length-1;i>=0;i--){var word=num.words[i];for(var j=start-1;j>=0;j--){var bit=word>>j&1;if(res!==wnd[0]){res=this.sqr(res)}if(bit===0&¤t===0){currentLen=0;continue}current<<=1;current|=bit;currentLen++;if(currentLen!==windowSize&&(i!==0||j!==0))continue;res=this.mul(res,wnd[current]);currentLen=0;current=0}start=26}return res};Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r};Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();res.red=null;return res};BN.mont=function mont(num){return new Mont(num)};function Mont(m){Red.call(this,m);this.shift=this.m.bitLength();if(this.shift%26!==0){this.shift+=26-this.shift%26}this.r=new BN(1).iushln(this.shift);this.r2=this.imod(this.r.sqr());this.rinv=this.r._invmp(this.m);this.minv=this.rinv.mul(this.r).isubn(1).div(this.m);this.minv=this.minv.umod(this.r);this.minv=this.r.sub(this.minv)}inherits(Mont,Red);Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))};Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));r.red=null;return r};Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero()){a.words[0]=0;a.length=1;return a}var t=a.imul(b);var c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);var u=t.isub(c).iushrn(this.shift);var res=u;if(u.cmp(this.m)>=0){res=u.isub(this.m)}else if(u.cmpn(0)<0){res=u.iadd(this.m)}return res._forceRed(this)};Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b);var c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);var u=t.isub(c).iushrn(this.shift);var res=u;if(u.cmp(this.m)>=0){res=u.isub(this.m)}else if(u.cmpn(0)<0){res=u.iadd(this.m)}return res._forceRed(this)};Mont.prototype.invm=function invm(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})(module,bn)})(bn$1);return bn$1.exports}var bnExports=requireBn();var BN=getDefaultExportFromCjs(bnExports);var safeBuffer={exports:{}};+/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var hasRequiredSafeBuffer;function requireSafeBuffer(){if(hasRequiredSafeBuffer)return safeBuffer.exports;hasRequiredSafeBuffer=1;(function(module,exports){var buffer=requireBuffer();var Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src){dst[key]=src[key]}}if(Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow){module.exports=buffer}else{copyProps(buffer,exports);exports.Buffer=SafeBuffer}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}SafeBuffer.prototype=Object.create(Buffer.prototype);copyProps(Buffer,SafeBuffer);SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==="number"){throw new TypeError("Argument must not be a number")}return Buffer(arg,encodingOrOffset,length)};SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}var buf=Buffer(size);if(fill!==undefined){if(typeof encoding==="string"){buf.fill(fill,encoding)}else{buf.fill(fill)}}else{buf.fill(0)}return buf};SafeBuffer.allocUnsafe=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return Buffer(size)};SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return buffer.SlowBuffer(size)}})(safeBuffer,safeBuffer.exports);return safeBuffer.exports}var src;var hasRequiredSrc;function requireSrc(){if(hasRequiredSrc)return src;hasRequiredSrc=1;var _Buffer=requireSafeBuffer().Buffer;function base(ALPHABET){if(ALPHABET.length>=255){throw new TypeError("Alphabet too long")}var BASE_MAP=new Uint8Array(256);for(var j=0;j<BASE_MAP.length;j++){BASE_MAP[j]=255}for(var i=0;i<ALPHABET.length;i++){var x=ALPHABET.charAt(i);var xc=x.charCodeAt(0);if(BASE_MAP[xc]!==255){throw new TypeError(x+" is ambiguous")}BASE_MAP[xc]=i}var BASE=ALPHABET.length;var LEADER=ALPHABET.charAt(0);var FACTOR=Math.log(BASE)/Math.log(256);var iFACTOR=Math.log(256)/Math.log(BASE);function encode(source){if(Array.isArray(source)||source instanceof Uint8Array){source=_Buffer.from(source)}if(!_Buffer.isBuffer(source)){throw new TypeError("Expected Buffer")}if(source.length===0){return""}var zeroes=0;var length=0;var pbegin=0;var pend=source.length;while(pbegin!==pend&&source[pbegin]===0){pbegin++;zeroes++}var size=(pend-pbegin)*iFACTOR+1>>>0;var b58=new Uint8Array(size);while(pbegin!==pend){var carry=source[pbegin];var i=0;for(var it1=size-1;(carry!==0||i<length)&&it1!==-1;it1--,i++){carry+=256*b58[it1]>>>0;b58[it1]=carry%BASE>>>0;carry=carry/BASE>>>0}if(carry!==0){throw new Error("Non-zero carry")}length=i;pbegin++}var it2=size-length;while(it2!==size&&b58[it2]===0){it2++}var str=LEADER.repeat(zeroes);for(;it2<size;++it2){str+=ALPHABET.charAt(b58[it2])}return str}function decodeUnsafe(source){if(typeof source!=="string"){throw new TypeError("Expected String")}if(source.length===0){return _Buffer.alloc(0)}var psz=0;var zeroes=0;var length=0;while(source[psz]===LEADER){zeroes++;psz++}var size=(source.length-psz)*FACTOR+1>>>0;var b256=new Uint8Array(size);while(source[psz]){var carry=BASE_MAP[source.charCodeAt(psz)];if(carry===255){return}var i=0;for(var it3=size-1;(carry!==0||i<length)&&it3!==-1;it3--,i++){carry+=BASE*b256[it3]>>>0;b256[it3]=carry%256>>>0;carry=carry/256>>>0}if(carry!==0){throw new Error("Non-zero carry")}length=i;psz++}var it4=size-length;while(it4!==size&&b256[it4]===0){it4++}var vch=_Buffer.allocUnsafe(zeroes+(size-it4));vch.fill(0,0,zeroes);var j=zeroes;while(it4!==size){vch[j++]=b256[it4++]}return vch}function decode(string){var buffer=decodeUnsafe(string);if(buffer){return buffer}throw new Error("Non-base"+BASE+" character")}return{encode:encode,decodeUnsafe:decodeUnsafe,decode:decode}}src=base;return src}var bs58$1;var hasRequiredBs58;function requireBs58(){if(hasRequiredBs58)return bs58$1;hasRequiredBs58=1;var basex=requireSrc();var ALPHABET="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";bs58$1=basex(ALPHABET);return bs58$1}var bs58Exports=requireBs58();var bs58=getDefaultExportFromCjs(bs58Exports);function anumber(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function isBytes(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function abytes(b,...lengths){if(!isBytes(b))throw new Error("Uint8Array expected");if(lengths.length>0&&!lengths.includes(b.length))throw new Error("Uint8Array expected of length "+lengths+", got length="+b.length)}function aexists(instance,checkFinished=true){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")}function aoutput(out,instance){abytes(out);const min=instance.outputLen;if(out.length<min){throw new Error("digestInto() expects output buffer of length at least "+min)}}+/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const u32=arr=>new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4));const createView=arr=>new DataView(arr.buffer,arr.byteOffset,arr.byteLength);const rotr=(word,shift)=>word<<32-shift|word>>>shift;const isLE=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();const byteSwap=word=>word<<24&4278190080|word<<8&16711680|word>>>8&65280|word>>>24&255;function byteSwap32(arr){for(let i=0;i<arr.length;i++){arr[i]=byteSwap(arr[i])}}function utf8ToBytes(str){if(typeof str!=="string")throw new Error("utf8ToBytes expected string, got "+typeof str);return new Uint8Array((new TextEncoder).encode(str))}function toBytes(data){if(typeof data==="string")data=utf8ToBytes(data);abytes(data);return data}class Hash{clone(){return this._cloneInto()}}function wrapConstructor(hashCons){const hashC=msg=>hashCons().update(toBytes(msg)).digest();const tmp=hashCons();hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=()=>hashCons();return hashC}function setBigUint64(view,byteOffset,value,isLE){if(typeof view.setBigUint64==="function")return view.setBigUint64(byteOffset,value,isLE);const _32n=BigInt(32);const _u32_max=BigInt(4294967295);const wh=Number(value>>_32n&_u32_max);const wl=Number(value&_u32_max);const h=isLE?4:0;const l=isLE?0:4;view.setUint32(byteOffset+h,wh,isLE);view.setUint32(byteOffset+l,wl,isLE)}const Chi=(a,b,c)=>a&b^~a&c;const Maj=(a,b,c)=>a&b^a&c^b&c;class HashMD extends Hash{constructor(blockLen,outputLen,padOffset,isLE){super();this.blockLen=blockLen;this.outputLen=outputLen;this.padOffset=padOffset;this.isLE=isLE;this.finished=false;this.length=0;this.pos=0;this.destroyed=false;this.buffer=new Uint8Array(blockLen);this.view=createView(this.buffer)}update(data){aexists(this);const{view:view,buffer:buffer,blockLen:blockLen}=this;data=toBytes(data);const len=data.length;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);if(take===blockLen){const dataView=createView(data);for(;blockLen<=len-pos;pos+=blockLen)this.process(dataView,pos);continue}buffer.set(data.subarray(pos,pos+take),this.pos);this.pos+=take;pos+=take;if(this.pos===blockLen){this.process(view,0);this.pos=0}}this.length+=data.length;this.roundClean();return this}digestInto(out){aexists(this);aoutput(out,this);this.finished=true;const{buffer:buffer,view:view,blockLen:blockLen,isLE:isLE}=this;let{pos:pos}=this;buffer[pos++]=128;this.buffer.subarray(pos).fill(0);if(this.padOffset>blockLen-pos){this.process(view,0);pos=0}for(let i=pos;i<blockLen;i++)buffer[i]=0;setBigUint64(view,blockLen-8,BigInt(this.length*8),isLE);this.process(view,0);const oview=createView(out);const len=this.outputLen;if(len%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const outLen=len/4;const state=this.get();if(outLen>state.length)throw new Error("_sha2: outputLen bigger than state");for(let i=0;i<outLen;i++)oview.setUint32(4*i,state[i],isLE)}digest(){const{buffer:buffer,outputLen:outputLen}=this;this.digestInto(buffer);const res=buffer.slice(0,outputLen);this.destroy();return res}_cloneInto(to){to||(to=new this.constructor);to.set(...this.get());const{blockLen:blockLen,buffer:buffer,length:length,finished:finished,destroyed:destroyed,pos:pos}=this;to.length=length;to.pos=pos;to.finished=finished;to.destroyed=destroyed;if(length%blockLen)to.buffer.set(buffer);return to}}const SHA256_K$1=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);const SHA256_IV$1=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);const SHA256_W$1=new Uint32Array(64);let SHA256$1=class SHA256 extends HashMD{constructor(){super(64,32,8,false);this.A=SHA256_IV$1[0]|0;this.B=SHA256_IV$1[1]|0;this.C=SHA256_IV$1[2]|0;this.D=SHA256_IV$1[3]|0;this.E=SHA256_IV$1[4]|0;this.F=SHA256_IV$1[5]|0;this.G=SHA256_IV$1[6]|0;this.H=SHA256_IV$1[7]|0}get(){const{A:A,B:B,C:C,D:D,E:E,F:F,G:G,H:H}=this;return[A,B,C,D,E,F,G,H]}set(A,B,C,D,E,F,G,H){this.A=A|0;this.B=B|0;this.C=C|0;this.D=D|0;this.E=E|0;this.F=F|0;this.G=G|0;this.H=H|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W$1[i]=view.getUint32(offset,false);for(let i=16;i<64;i++){const W15=SHA256_W$1[i-15];const W2=SHA256_W$1[i-2];const s0=rotr(W15,7)^rotr(W15,18)^W15>>>3;const s1=rotr(W2,17)^rotr(W2,19)^W2>>>10;SHA256_W$1[i]=s1+SHA256_W$1[i-7]+s0+SHA256_W$1[i-16]|0}let{A:A,B:B,C:C,D:D,E:E,F:F,G:G,H:H}=this;for(let i=0;i<64;i++){const sigma1=rotr(E,6)^rotr(E,11)^rotr(E,25);const T1=H+sigma1+Chi(E,F,G)+SHA256_K$1[i]+SHA256_W$1[i]|0;const sigma0=rotr(A,2)^rotr(A,13)^rotr(A,22);const T2=sigma0+Maj(A,B,C)|0;H=G;G=F;F=E;E=D+T1|0;D=C;C=B;B=A;A=T1+T2|0}A=A+this.A|0;B=B+this.B|0;C=C+this.C|0;D=D+this.D|0;E=E+this.E|0;F=F+this.F|0;G=G+this.G|0;H=H+this.H|0;this.set(A,B,C,D,E,F,G,H)}roundClean(){SHA256_W$1.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0);this.buffer.fill(0)}};const sha256$1=wrapConstructor((()=>new SHA256$1));var lib={};var encoding_lib={};var hasRequiredEncoding_lib;function requireEncoding_lib(){if(hasRequiredEncoding_lib)return encoding_lib;hasRequiredEncoding_lib=1;function inRange(a,min,max){return min<=a&&a<=max}function ToDictionary(o){if(o===undefined)return{};if(o===Object(o))return o;throw TypeError("Could not convert argument to dictionary")}function stringToCodePoints(string){var s=String(string);var n=s.length;var i=0;var u=[];while(i<n){var c=s.charCodeAt(i);if(c<55296||c>57343){u.push(c)}else if(56320<=c&&c<=57343){u.push(65533)}else if(55296<=c&&c<=56319){if(i===n-1){u.push(65533)}else{var d=string.charCodeAt(i+1);if(56320<=d&&d<=57343){var a=c&1023;var b=d&1023;u.push(65536+(a<<10)+b);i+=1}else{u.push(65533)}}}i+=1}return u}function codePointsToString(code_points){var s="";for(var i=0;i<code_points.length;++i){var cp=code_points[i];if(cp<=65535){s+=String.fromCharCode(cp)}else{cp-=65536;s+=String.fromCharCode((cp>>10)+55296,(cp&1023)+56320)}}return s}var end_of_stream=-1;function Stream(tokens){this.tokens=[].slice.call(tokens)}Stream.prototype={endOfStream:function(){return!this.tokens.length},read:function(){if(!this.tokens.length)return end_of_stream;return this.tokens.shift()},prepend:function(token){if(Array.isArray(token)){var tokens=token;while(tokens.length)this.tokens.unshift(tokens.pop())}else{this.tokens.unshift(token)}},push:function(token){if(Array.isArray(token)){var tokens=token;while(tokens.length)this.tokens.push(tokens.shift())}else{this.tokens.push(token)}}};var finished=-1;function decoderError(fatal,opt_code_point){if(fatal)throw TypeError("Decoder error");return opt_code_point||65533}var DEFAULT_ENCODING="utf-8";function TextDecoder(encoding,options){if(!(this instanceof TextDecoder)){return new TextDecoder(encoding,options)}encoding=encoding!==undefined?String(encoding).toLowerCase():DEFAULT_ENCODING;if(encoding!==DEFAULT_ENCODING){throw new Error("Encoding not supported. Only utf-8 is supported")}options=ToDictionary(options);this._streaming=false;this._BOMseen=false;this._decoder=null;this._fatal=Boolean(options["fatal"]);this._ignoreBOM=Boolean(options["ignoreBOM"]);Object.defineProperty(this,"encoding",{value:"utf-8"});Object.defineProperty(this,"fatal",{value:this._fatal});Object.defineProperty(this,"ignoreBOM",{value:this._ignoreBOM})}TextDecoder.prototype={decode:function decode(input,options){var bytes;if(typeof input==="object"&&input instanceof ArrayBuffer){bytes=new Uint8Array(input)}else if(typeof input==="object"&&"buffer"in input&&input.buffer instanceof ArrayBuffer){bytes=new Uint8Array(input.buffer,input.byteOffset,input.byteLength)}else{bytes=new Uint8Array(0)}options=ToDictionary(options);if(!this._streaming){this._decoder=new UTF8Decoder({fatal:this._fatal});this._BOMseen=false}this._streaming=Boolean(options["stream"]);var input_stream=new Stream(bytes);var code_points=[];var result;while(!input_stream.endOfStream()){result=this._decoder.handler(input_stream,input_stream.read());if(result===finished)break;if(result===null)continue;if(Array.isArray(result))code_points.push.apply(code_points,result);else code_points.push(result)}if(!this._streaming){do{result=this._decoder.handler(input_stream,input_stream.read());if(result===finished)break;if(result===null)continue;if(Array.isArray(result))code_points.push.apply(code_points,result);else code_points.push(result)}while(!input_stream.endOfStream());this._decoder=null}if(code_points.length){if(["utf-8"].indexOf(this.encoding)!==-1&&!this._ignoreBOM&&!this._BOMseen){if(code_points[0]===65279){this._BOMseen=true;code_points.shift()}else{this._BOMseen=true}}}return codePointsToString(code_points)}};function TextEncoder(encoding,options){if(!(this instanceof TextEncoder))return new TextEncoder(encoding,options);encoding=encoding!==undefined?String(encoding).toLowerCase():DEFAULT_ENCODING;if(encoding!==DEFAULT_ENCODING){throw new Error("Encoding not supported. Only utf-8 is supported")}options=ToDictionary(options);this._streaming=false;this._encoder=null;this._options={fatal:Boolean(options["fatal"])};Object.defineProperty(this,"encoding",{value:"utf-8"})}TextEncoder.prototype={encode:function encode(opt_string,options){opt_string=opt_string?String(opt_string):"";options=ToDictionary(options);if(!this._streaming)this._encoder=new UTF8Encoder(this._options);this._streaming=Boolean(options["stream"]);var bytes=[];var input_stream=new Stream(stringToCodePoints(opt_string));var result;while(!input_stream.endOfStream()){result=this._encoder.handler(input_stream,input_stream.read());if(result===finished)break;if(Array.isArray(result))bytes.push.apply(bytes,result);else bytes.push(result)}if(!this._streaming){while(true){result=this._encoder.handler(input_stream,input_stream.read());if(result===finished)break;if(Array.isArray(result))bytes.push.apply(bytes,result);else bytes.push(result)}this._encoder=null}return new Uint8Array(bytes)}};function UTF8Decoder(options){var fatal=options.fatal;var utf8_code_point=0,utf8_bytes_seen=0,utf8_bytes_needed=0,utf8_lower_boundary=128,utf8_upper_boundary=191;this.handler=function(stream,bite){if(bite===end_of_stream&&utf8_bytes_needed!==0){utf8_bytes_needed=0;return decoderError(fatal)}if(bite===end_of_stream)return finished;if(utf8_bytes_needed===0){if(inRange(bite,0,127)){return bite}if(inRange(bite,194,223)){utf8_bytes_needed=1;utf8_code_point=bite-192}else if(inRange(bite,224,239)){if(bite===224)utf8_lower_boundary=160;if(bite===237)utf8_upper_boundary=159;utf8_bytes_needed=2;utf8_code_point=bite-224}else if(inRange(bite,240,244)){if(bite===240)utf8_lower_boundary=144;if(bite===244)utf8_upper_boundary=143;utf8_bytes_needed=3;utf8_code_point=bite-240}else{return decoderError(fatal)}utf8_code_point=utf8_code_point<<6*utf8_bytes_needed;return null}if(!inRange(bite,utf8_lower_boundary,utf8_upper_boundary)){utf8_code_point=utf8_bytes_needed=utf8_bytes_seen=0;utf8_lower_boundary=128;utf8_upper_boundary=191;stream.prepend(bite);return decoderError(fatal)}utf8_lower_boundary=128;utf8_upper_boundary=191;utf8_bytes_seen+=1;utf8_code_point+=bite-128<<6*(utf8_bytes_needed-utf8_bytes_seen);if(utf8_bytes_seen!==utf8_bytes_needed)return null;var code_point=utf8_code_point;utf8_code_point=utf8_bytes_needed=utf8_bytes_seen=0;return code_point}}function UTF8Encoder(options){options.fatal;this.handler=function(stream,code_point){if(code_point===end_of_stream)return finished;if(inRange(code_point,0,127))return code_point;var count,offset;if(inRange(code_point,128,2047)){count=1;offset=192}else if(inRange(code_point,2048,65535)){count=2;offset=224}else if(inRange(code_point,65536,1114111)){count=3;offset=240}var bytes=[(code_point>>6*count)+offset];while(count>0){var temp=code_point>>6*(count-1);bytes.push(128|temp&63);count-=1}return bytes}}encoding_lib.TextEncoder=TextEncoder;encoding_lib.TextDecoder=TextDecoder;return encoding_lib}var hasRequiredLib;function requireLib(){if(hasRequiredLib)return lib;hasRequiredLib=1;var __createBinding=lib&&lib.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __setModuleDefault=lib&&lib.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:true,value:v})}:function(o,v){o["default"]=v});var __decorate=lib&&lib.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};var __importStar=lib&&lib.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)if(k!=="default"&&Object.hasOwnProperty.call(mod,k))__createBinding(result,mod,k);__setModuleDefault(result,mod);return result};var __importDefault=lib&&lib.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(lib,"__esModule",{value:true});lib.deserializeUnchecked=lib.deserialize=lib.serialize=lib.BinaryReader=lib.BinaryWriter=lib.BorshError=lib.baseDecode=lib.baseEncode=void 0;const bn_js_1=__importDefault(requireBn());const bs58_1=__importDefault(requireBs58());const encoding=__importStar(requireEncoding_lib());const ResolvedTextDecoder=typeof TextDecoder!=="function"?encoding.TextDecoder:TextDecoder;const textDecoder=new ResolvedTextDecoder("utf-8",{fatal:true});function baseEncode(value){if(typeof value==="string"){value=Buffer.from(value,"utf8")}return bs58_1.default.encode(Buffer.from(value))}lib.baseEncode=baseEncode;function baseDecode(value){return Buffer.from(bs58_1.default.decode(value))}lib.baseDecode=baseDecode;const INITIAL_LENGTH=1024;class BorshError extends Error{constructor(message){super(message);this.fieldPath=[];this.originalMessage=message}addToFieldPath(fieldName){this.fieldPath.splice(0,0,fieldName);this.message=this.originalMessage+": "+this.fieldPath.join(".")}}lib.BorshError=BorshError;class BinaryWriter{constructor(){this.buf=Buffer.alloc(INITIAL_LENGTH);this.length=0}maybeResize(){if(this.buf.length<16+this.length){this.buf=Buffer.concat([this.buf,Buffer.alloc(INITIAL_LENGTH)])}}writeU8(value){this.maybeResize();this.buf.writeUInt8(value,this.length);this.length+=1}writeU16(value){this.maybeResize();this.buf.writeUInt16LE(value,this.length);this.length+=2}writeU32(value){this.maybeResize();this.buf.writeUInt32LE(value,this.length);this.length+=4}writeU64(value){this.maybeResize();this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le",8)))}writeU128(value){this.maybeResize();this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le",16)))}writeU256(value){this.maybeResize();this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le",32)))}writeU512(value){this.maybeResize();this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le",64)))}writeBuffer(buffer){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),buffer,Buffer.alloc(INITIAL_LENGTH)]);this.length+=buffer.length}writeString(str){this.maybeResize();const b=Buffer.from(str,"utf8");this.writeU32(b.length);this.writeBuffer(b)}writeFixedArray(array){this.writeBuffer(Buffer.from(array))}writeArray(array,fn){this.maybeResize();this.writeU32(array.length);for(const elem of array){this.maybeResize();fn(elem)}}toArray(){return this.buf.subarray(0,this.length)}}lib.BinaryWriter=BinaryWriter;function handlingRangeError(target,propertyKey,propertyDescriptor){const originalMethod=propertyDescriptor.value;propertyDescriptor.value=function(...args){try{return originalMethod.apply(this,args)}catch(e){if(e instanceof RangeError){const code=e.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(code)>=0){throw new BorshError("Reached the end of buffer when deserializing")}}throw e}}}class BinaryReader{constructor(buf){this.buf=buf;this.offset=0}readU8(){const value=this.buf.readUInt8(this.offset);this.offset+=1;return value}readU16(){const value=this.buf.readUInt16LE(this.offset);this.offset+=2;return value}readU32(){const value=this.buf.readUInt32LE(this.offset);this.offset+=4;return value}readU64(){const buf=this.readBuffer(8);return new bn_js_1.default(buf,"le")}readU128(){const buf=this.readBuffer(16);return new bn_js_1.default(buf,"le")}readU256(){const buf=this.readBuffer(32);return new bn_js_1.default(buf,"le")}readU512(){const buf=this.readBuffer(64);return new bn_js_1.default(buf,"le")}readBuffer(len){if(this.offset+len>this.buf.length){throw new BorshError(`Expected buffer length ${len} isn't within bounds`)}const result=this.buf.slice(this.offset,this.offset+len);this.offset+=len;return result}readString(){const len=this.readU32();const buf=this.readBuffer(len);try{return textDecoder.decode(buf)}catch(e){throw new BorshError(`Error decoding UTF-8 string: ${e}`)}}readFixedArray(len){return new Uint8Array(this.readBuffer(len))}readArray(fn){const len=this.readU32();const result=Array();for(let i=0;i<len;++i){result.push(fn())}return result}}__decorate([handlingRangeError],BinaryReader.prototype,"readU8",null);__decorate([handlingRangeError],BinaryReader.prototype,"readU16",null);__decorate([handlingRangeError],BinaryReader.prototype,"readU32",null);__decorate([handlingRangeError],BinaryReader.prototype,"readU64",null);__decorate([handlingRangeError],BinaryReader.prototype,"readU128",null);__decorate([handlingRangeError],BinaryReader.prototype,"readU256",null);__decorate([handlingRangeError],BinaryReader.prototype,"readU512",null);__decorate([handlingRangeError],BinaryReader.prototype,"readString",null);__decorate([handlingRangeError],BinaryReader.prototype,"readFixedArray",null);__decorate([handlingRangeError],BinaryReader.prototype,"readArray",null);lib.BinaryReader=BinaryReader;function capitalizeFirstLetter(string){return string.charAt(0).toUpperCase()+string.slice(1)}function serializeField(schema,fieldName,value,fieldType,writer){try{if(typeof fieldType==="string"){writer[`write${capitalizeFirstLetter(fieldType)}`](value)}else if(fieldType instanceof Array){if(typeof fieldType[0]==="number"){if(value.length!==fieldType[0]){throw new BorshError(`Expecting byte array of length ${fieldType[0]}, but got ${value.length} bytes`)}writer.writeFixedArray(value)}else if(fieldType.length===2&&typeof fieldType[1]==="number"){if(value.length!==fieldType[1]){throw new BorshError(`Expecting byte array of length ${fieldType[1]}, but got ${value.length} bytes`)}for(let i=0;i<fieldType[1];i++){serializeField(schema,null,value[i],fieldType[0],writer)}}else{writer.writeArray(value,(item=>{serializeField(schema,fieldName,item,fieldType[0],writer)}))}}else if(fieldType.kind!==undefined){switch(fieldType.kind){case"option":{if(value===null||value===undefined){writer.writeU8(0)}else{writer.writeU8(1);serializeField(schema,fieldName,value,fieldType.type,writer)}break}case"map":{writer.writeU32(value.size);value.forEach(((val,key)=>{serializeField(schema,fieldName,key,fieldType.key,writer);serializeField(schema,fieldName,val,fieldType.value,writer)}));break}default:throw new BorshError(`FieldType ${fieldType} unrecognized`)}}else{serializeStruct(schema,value,writer)}}catch(error){if(error instanceof BorshError){error.addToFieldPath(fieldName)}throw error}}function serializeStruct(schema,obj,writer){if(typeof obj.borshSerialize==="function"){obj.borshSerialize(writer);return}const structSchema=schema.get(obj.constructor);if(!structSchema){throw new BorshError(`Class ${obj.constructor.name} is missing in schema`)}if(structSchema.kind==="struct"){structSchema.fields.map((([fieldName,fieldType])=>{serializeField(schema,fieldName,obj[fieldName],fieldType,writer)}))}else if(structSchema.kind==="enum"){const name=obj[structSchema.field];for(let idx=0;idx<structSchema.values.length;++idx){const[fieldName,fieldType]=structSchema.values[idx];if(fieldName===name){writer.writeU8(idx);serializeField(schema,fieldName,obj[fieldName],fieldType,writer);break}}}else{throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${obj.constructor.name}`)}}function serialize(schema,obj,Writer=BinaryWriter){const writer=new Writer;serializeStruct(schema,obj,writer);return writer.toArray()}lib.serialize=serialize;function deserializeField(schema,fieldName,fieldType,reader){try{if(typeof fieldType==="string"){return reader[`read${capitalizeFirstLetter(fieldType)}`]()}if(fieldType instanceof Array){if(typeof fieldType[0]==="number"){return reader.readFixedArray(fieldType[0])}else if(typeof fieldType[1]==="number"){const arr=[];for(let i=0;i<fieldType[1];i++){arr.push(deserializeField(schema,null,fieldType[0],reader))}return arr}else{return reader.readArray((()=>deserializeField(schema,fieldName,fieldType[0],reader)))}}if(fieldType.kind==="option"){const option=reader.readU8();if(option){return deserializeField(schema,fieldName,fieldType.type,reader)}return undefined}if(fieldType.kind==="map"){let map=new Map;const length=reader.readU32();for(let i=0;i<length;i++){const key=deserializeField(schema,fieldName,fieldType.key,reader);const val=deserializeField(schema,fieldName,fieldType.value,reader);map.set(key,val)}return map}return deserializeStruct(schema,fieldType,reader)}catch(error){if(error instanceof BorshError){error.addToFieldPath(fieldName)}throw error}}function deserializeStruct(schema,classType,reader){if(typeof classType.borshDeserialize==="function"){return classType.borshDeserialize(reader)}const structSchema=schema.get(classType);if(!structSchema){throw new BorshError(`Class ${classType.name} is missing in schema`)}if(structSchema.kind==="struct"){const result={};for(const[fieldName,fieldType]of schema.get(classType).fields){result[fieldName]=deserializeField(schema,fieldName,fieldType,reader)}return new classType(result)}if(structSchema.kind==="enum"){const idx=reader.readU8();if(idx>=structSchema.values.length){throw new BorshError(`Enum index: ${idx} is out of range`)}const[fieldName,fieldType]=structSchema.values[idx];const fieldValue=deserializeField(schema,fieldName,fieldType,reader);return new classType({[fieldName]:fieldValue})}throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${classType.constructor.name}`)}function deserialize(schema,classType,buffer,Reader=BinaryReader){const reader=new Reader(buffer);const result=deserializeStruct(schema,classType,reader);if(reader.offset<buffer.length){throw new BorshError(`Unexpected ${buffer.length-reader.offset} bytes after deserialized data`)}return result}lib.deserialize=deserialize;function deserializeUnchecked(schema,classType,buffer,Reader=BinaryReader){const reader=new Reader(buffer);return deserializeStruct(schema,classType,reader)}lib.deserializeUnchecked=deserializeUnchecked;return lib}var libExports=requireLib();let Struct$1=class Struct{constructor(properties){Object.assign(this,properties)}encode(){return bufferExports.Buffer.from(libExports.serialize(SOLANA_SCHEMA,this))}static decode(data){return libExports.deserialize(SOLANA_SCHEMA,this,data)}static decodeUnchecked(data){return libExports.deserializeUnchecked(SOLANA_SCHEMA,this,data)}};class Enum extends Struct$1{constructor(properties){super(properties);this.enum="";if(Object.keys(properties).length!==1){throw new Error("Enum can only take single value")}Object.keys(properties).map((key=>{this.enum=key}))}}const SOLANA_SCHEMA=new Map;var _PublicKey;const MAX_SEED_LENGTH=32;const PUBLIC_KEY_LENGTH=32;function isPublicKeyData(value){return value._bn!==undefined}let uniquePublicKeyCounter=1;class PublicKey extends Struct$1{constructor(value){super({});this._bn=void 0;if(isPublicKeyData(value)){this._bn=value._bn}else{if(typeof value==="string"){const decoded=bs58.decode(value);if(decoded.length!=PUBLIC_KEY_LENGTH){throw new Error(`Invalid public key input`)}this._bn=new BN(decoded)}else{this._bn=new BN(value)}if(this._bn.byteLength()>PUBLIC_KEY_LENGTH){throw new Error(`Invalid public key input`)}}}static unique(){const key=new PublicKey(uniquePublicKeyCounter);uniquePublicKeyCounter+=1;return new PublicKey(key.toBuffer())}equals(publicKey){return this._bn.eq(publicKey._bn)}toBase58(){return bs58.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const buf=this.toBuffer();return new Uint8Array(buf.buffer,buf.byteOffset,buf.byteLength)}toBuffer(){const b=this._bn.toArrayLike(bufferExports.Buffer);if(b.length===PUBLIC_KEY_LENGTH){return b}const zeroPad=bufferExports.Buffer.alloc(32);b.copy(zeroPad,32-b.length);return zeroPad}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(fromPublicKey,seed,programId){const buffer=bufferExports.Buffer.concat([fromPublicKey.toBuffer(),bufferExports.Buffer.from(seed),programId.toBuffer()]);const publicKeyBytes=sha256$1(buffer);return new PublicKey(publicKeyBytes)}static createProgramAddressSync(seeds,programId){let buffer=bufferExports.Buffer.alloc(0);seeds.forEach((function(seed){if(seed.length>MAX_SEED_LENGTH){throw new TypeError(`Max seed length exceeded`)}buffer=bufferExports.Buffer.concat([buffer,toBuffer(seed)])}));buffer=bufferExports.Buffer.concat([buffer,programId.toBuffer(),bufferExports.Buffer.from("ProgramDerivedAddress")]);const publicKeyBytes=sha256$1(buffer);if(isOnCurve(publicKeyBytes)){throw new Error(`Invalid seeds, address must fall off the curve`)}return new PublicKey(publicKeyBytes)}static async createProgramAddress(seeds,programId){return this.createProgramAddressSync(seeds,programId)}static findProgramAddressSync(seeds,programId){let nonce=255;let address;while(nonce!=0){try{const seedsWithNonce=seeds.concat(bufferExports.Buffer.from([nonce]));address=this.createProgramAddressSync(seedsWithNonce,programId)}catch(err){if(err instanceof TypeError){throw err}nonce--;continue}return[address,nonce]}throw new Error(`Unable to find a viable program address nonce`)}static async findProgramAddress(seeds,programId){return this.findProgramAddressSync(seeds,programId)}static isOnCurve(pubkeyData){const pubkey=new PublicKey(pubkeyData);return isOnCurve(pubkey.toBytes())}}_PublicKey=PublicKey;PublicKey.default=new _PublicKey("11111111111111111111111111111111");SOLANA_SCHEMA.set(PublicKey,{kind:"struct",fields:[["_bn","u256"]]});class Account{constructor(secretKey){this._publicKey=void 0;this._secretKey=void 0;if(secretKey){const secretKeyBuffer=toBuffer(secretKey);if(secretKey.length!==64){throw new Error("bad secret key size")}this._publicKey=secretKeyBuffer.slice(32,64);this._secretKey=secretKeyBuffer.slice(0,32)}else{this._secretKey=toBuffer(generatePrivateKey());this._publicKey=toBuffer(getPublicKey(this._secretKey))}}get publicKey(){return new PublicKey(this._publicKey)}get secretKey(){return bufferExports.Buffer.concat([this._secretKey,this._publicKey],64)}}const BPF_LOADER_DEPRECATED_PROGRAM_ID=new PublicKey("BPFLoader1111111111111111111111111111111111");var Layout={};var hasRequiredLayout;function requireLayout(){if(hasRequiredLayout)return Layout;hasRequiredLayout=1;Object.defineProperty(Layout,"__esModule",{value:true});Layout.s16=Layout.s8=Layout.nu64be=Layout.u48be=Layout.u40be=Layout.u32be=Layout.u24be=Layout.u16be=Layout.nu64=Layout.u48=Layout.u40=Layout.u32=Layout.u24=Layout.u16=Layout.u8=Layout.offset=Layout.greedy=Layout.Constant=Layout.UTF8=Layout.CString=Layout.Blob=Layout.Boolean=Layout.BitField=Layout.BitStructure=Layout.VariantLayout=Layout.Union=Layout.UnionLayoutDiscriminator=Layout.UnionDiscriminator=Layout.Structure=Layout.Sequence=Layout.DoubleBE=Layout.Double=Layout.FloatBE=Layout.Float=Layout.NearInt64BE=Layout.NearInt64=Layout.NearUInt64BE=Layout.NearUInt64=Layout.IntBE=Layout.Int=Layout.UIntBE=Layout.UInt=Layout.OffsetLayout=Layout.GreedyCount=Layout.ExternalLayout=Layout.bindConstructorLayout=Layout.nameWithProperty=Layout.Layout=Layout.uint8ArrayToBuffer=Layout.checkUint8Array=void 0;Layout.constant=Layout.utf8=Layout.cstr=Layout.blob=Layout.unionLayoutDiscriminator=Layout.union=Layout.seq=Layout.bits=Layout.struct=Layout.f64be=Layout.f64=Layout.f32be=Layout.f32=Layout.ns64be=Layout.s48be=Layout.s40be=Layout.s32be=Layout.s24be=Layout.s16be=Layout.ns64=Layout.s48=Layout.s40=Layout.s32=Layout.s24=void 0;const buffer_1=requireBuffer();function checkUint8Array(b){if(!(b instanceof Uint8Array)){throw new TypeError("b must be a Uint8Array")}}Layout.checkUint8Array=checkUint8Array;function uint8ArrayToBuffer(b){checkUint8Array(b);return buffer_1.Buffer.from(b.buffer,b.byteOffset,b.length)}Layout.uint8ArrayToBuffer=uint8ArrayToBuffer;let Layout$1=class Layout{constructor(span,property){if(!Number.isInteger(span)){throw new TypeError("span must be an integer")}this.span=span;this.property=property}makeDestinationObject(){return{}}getSpan(b,offset){if(0>this.span){throw new RangeError("indeterminate span")}return this.span}replicate(property){const rv=Object.create(this.constructor.prototype);Object.assign(rv,this);rv.property=property;return rv}fromArray(values){return undefined}};Layout.Layout=Layout$1;function nameWithProperty(name,lo){if(lo.property){return name+"["+lo.property+"]"}return name}Layout.nameWithProperty=nameWithProperty;function bindConstructorLayout(Class,layout){if("function"!==typeof Class){throw new TypeError("Class must be constructor")}if(Object.prototype.hasOwnProperty.call(Class,"layout_")){throw new Error("Class is already bound to a layout")}if(!(layout&&layout instanceof Layout$1)){throw new TypeError("layout must be a Layout")}if(Object.prototype.hasOwnProperty.call(layout,"boundConstructor_")){throw new Error("layout is already bound to a constructor")}Class.layout_=layout;layout.boundConstructor_=Class;layout.makeDestinationObject=()=>new Class;Object.defineProperty(Class.prototype,"encode",{value(b,offset){return layout.encode(this,b,offset)},writable:true});Object.defineProperty(Class,"decode",{value(b,offset){return layout.decode(b,offset)},writable:true})}Layout.bindConstructorLayout=bindConstructorLayout;class ExternalLayout extends Layout$1{isCount(){throw new Error("ExternalLayout is abstract")}}Layout.ExternalLayout=ExternalLayout;class GreedyCount extends ExternalLayout{constructor(elementSpan=1,property){if(!Number.isInteger(elementSpan)||0>=elementSpan){throw new TypeError("elementSpan must be a (positive) integer")}super(-1,property);this.elementSpan=elementSpan}isCount(){return true}decode(b,offset=0){checkUint8Array(b);const rem=b.length-offset;return Math.floor(rem/this.elementSpan)}encode(src,b,offset){return 0}}Layout.GreedyCount=GreedyCount;class OffsetLayout extends ExternalLayout{constructor(layout,offset=0,property){if(!(layout instanceof Layout$1)){throw new TypeError("layout must be a Layout")}if(!Number.isInteger(offset)){throw new TypeError("offset must be integer or undefined")}super(layout.span,property||layout.property);this.layout=layout;this.offset=offset}isCount(){return this.layout instanceof UInt||this.layout instanceof UIntBE}decode(b,offset=0){return this.layout.decode(b,offset+this.offset)}encode(src,b,offset=0){return this.layout.encode(src,b,offset+this.offset)}}Layout.OffsetLayout=OffsetLayout;class UInt extends Layout$1{constructor(span,property){super(span,property);if(6<this.span){throw new RangeError("span must not exceed 6 bytes")}}decode(b,offset=0){return uint8ArrayToBuffer(b).readUIntLE(offset,this.span)}encode(src,b,offset=0){uint8ArrayToBuffer(b).writeUIntLE(src,offset,this.span);return this.span}}Layout.UInt=UInt;class UIntBE extends Layout$1{constructor(span,property){super(span,property);if(6<this.span){throw new RangeError("span must not exceed 6 bytes")}}decode(b,offset=0){return uint8ArrayToBuffer(b).readUIntBE(offset,this.span)}encode(src,b,offset=0){uint8ArrayToBuffer(b).writeUIntBE(src,offset,this.span);return this.span}}Layout.UIntBE=UIntBE;class Int extends Layout$1{constructor(span,property){super(span,property);if(6<this.span){throw new RangeError("span must not exceed 6 bytes")}}decode(b,offset=0){return uint8ArrayToBuffer(b).readIntLE(offset,this.span)}encode(src,b,offset=0){uint8ArrayToBuffer(b).writeIntLE(src,offset,this.span);return this.span}}Layout.Int=Int;class IntBE extends Layout$1{constructor(span,property){super(span,property);if(6<this.span){throw new RangeError("span must not exceed 6 bytes")}}decode(b,offset=0){return uint8ArrayToBuffer(b).readIntBE(offset,this.span)}encode(src,b,offset=0){uint8ArrayToBuffer(b).writeIntBE(src,offset,this.span);return this.span}}Layout.IntBE=IntBE;const V2E32=Math.pow(2,32);function divmodInt64(src){const hi32=Math.floor(src/V2E32);const lo32=src-hi32*V2E32;return{hi32:hi32,lo32:lo32}}function roundedInt64(hi32,lo32){return hi32*V2E32+lo32}class NearUInt64 extends Layout$1{constructor(property){super(8,property)}decode(b,offset=0){const buffer=uint8ArrayToBuffer(b);const lo32=buffer.readUInt32LE(offset);const hi32=buffer.readUInt32LE(offset+4);return roundedInt64(hi32,lo32)}encode(src,b,offset=0){const split=divmodInt64(src);const buffer=uint8ArrayToBuffer(b);buffer.writeUInt32LE(split.lo32,offset);buffer.writeUInt32LE(split.hi32,offset+4);return 8}}Layout.NearUInt64=NearUInt64;class NearUInt64BE extends Layout$1{constructor(property){super(8,property)}decode(b,offset=0){const buffer=uint8ArrayToBuffer(b);const hi32=buffer.readUInt32BE(offset);const lo32=buffer.readUInt32BE(offset+4);return roundedInt64(hi32,lo32)}encode(src,b,offset=0){const split=divmodInt64(src);const buffer=uint8ArrayToBuffer(b);buffer.writeUInt32BE(split.hi32,offset);buffer.writeUInt32BE(split.lo32,offset+4);return 8}}Layout.NearUInt64BE=NearUInt64BE;class NearInt64 extends Layout$1{constructor(property){super(8,property)}decode(b,offset=0){const buffer=uint8ArrayToBuffer(b);const lo32=buffer.readUInt32LE(offset);const hi32=buffer.readInt32LE(offset+4);return roundedInt64(hi32,lo32)}encode(src,b,offset=0){const split=divmodInt64(src);const buffer=uint8ArrayToBuffer(b);buffer.writeUInt32LE(split.lo32,offset);buffer.writeInt32LE(split.hi32,offset+4);return 8}}Layout.NearInt64=NearInt64;class NearInt64BE extends Layout$1{constructor(property){super(8,property)}decode(b,offset=0){const buffer=uint8ArrayToBuffer(b);const hi32=buffer.readInt32BE(offset);const lo32=buffer.readUInt32BE(offset+4);return roundedInt64(hi32,lo32)}encode(src,b,offset=0){const split=divmodInt64(src);const buffer=uint8ArrayToBuffer(b);buffer.writeInt32BE(split.hi32,offset);buffer.writeUInt32BE(split.lo32,offset+4);return 8}}Layout.NearInt64BE=NearInt64BE;class Float extends Layout$1{constructor(property){super(4,property)}decode(b,offset=0){return uint8ArrayToBuffer(b).readFloatLE(offset)}encode(src,b,offset=0){uint8ArrayToBuffer(b).writeFloatLE(src,offset);return 4}}Layout.Float=Float;class FloatBE extends Layout$1{constructor(property){super(4,property)}decode(b,offset=0){return uint8ArrayToBuffer(b).readFloatBE(offset)}encode(src,b,offset=0){uint8ArrayToBuffer(b).writeFloatBE(src,offset);return 4}}Layout.FloatBE=FloatBE;class Double extends Layout$1{constructor(property){super(8,property)}decode(b,offset=0){return uint8ArrayToBuffer(b).readDoubleLE(offset)}encode(src,b,offset=0){uint8ArrayToBuffer(b).writeDoubleLE(src,offset);return 8}}Layout.Double=Double;class DoubleBE extends Layout$1{constructor(property){super(8,property)}decode(b,offset=0){return uint8ArrayToBuffer(b).readDoubleBE(offset)}encode(src,b,offset=0){uint8ArrayToBuffer(b).writeDoubleBE(src,offset);return 8}}Layout.DoubleBE=DoubleBE;class Sequence extends Layout$1{constructor(elementLayout,count,property){if(!(elementLayout instanceof Layout$1)){throw new TypeError("elementLayout must be a Layout")}if(!(count instanceof ExternalLayout&&count.isCount()||Number.isInteger(count)&&0<=count)){throw new TypeError("count must be non-negative integer "+"or an unsigned integer ExternalLayout")}let span=-1;if(!(count instanceof ExternalLayout)&&0<elementLayout.span){span=count*elementLayout.span}super(span,property);this.elementLayout=elementLayout;this.count=count}getSpan(b,offset=0){if(0<=this.span){return this.span}let span=0;let count=this.count;if(count instanceof ExternalLayout){count=count.decode(b,offset)}if(0<this.elementLayout.span){span=count*this.elementLayout.span}else{let idx=0;while(idx<count){span+=this.elementLayout.getSpan(b,offset+span);++idx}}return span}decode(b,offset=0){const rv=[];let i=0;let count=this.count;if(count instanceof ExternalLayout){count=count.decode(b,offset)}while(i<count){rv.push(this.elementLayout.decode(b,offset));offset+=this.elementLayout.getSpan(b,offset);i+=1}return rv}encode(src,b,offset=0){const elo=this.elementLayout;const span=src.reduce(((span,v)=>span+elo.encode(v,b,offset+span)),0);if(this.count instanceof ExternalLayout){this.count.encode(src.length,b,offset)}return span}}Layout.Sequence=Sequence;class Structure extends Layout$1{constructor(fields,property,decodePrefixes){if(!(Array.isArray(fields)&&fields.reduce(((acc,v)=>acc&&v instanceof Layout$1),true))){throw new TypeError("fields must be array of Layout instances")}if("boolean"===typeof property&&undefined===decodePrefixes){decodePrefixes=property;property=undefined}for(const fd of fields){if(0>fd.span&&undefined===fd.property){throw new Error("fields cannot contain unnamed variable-length layout")}}let span=-1;try{span=fields.reduce(((span,fd)=>span+fd.getSpan()),0)}catch(e){}super(span,property);this.fields=fields;this.decodePrefixes=!!decodePrefixes}getSpan(b,offset=0){if(0<=this.span){return this.span}let span=0;try{span=this.fields.reduce(((span,fd)=>{const fsp=fd.getSpan(b,offset);offset+=fsp;return span+fsp}),0)}catch(e){throw new RangeError("indeterminate span")}return span}decode(b,offset=0){checkUint8Array(b);const dest=this.makeDestinationObject();for(const fd of this.fields){if(undefined!==fd.property){dest[fd.property]=fd.decode(b,offset)}offset+=fd.getSpan(b,offset);if(this.decodePrefixes&&b.length===offset){break}}return dest}encode(src,b,offset=0){const firstOffset=offset;let lastOffset=0;let lastWrote=0;for(const fd of this.fields){let span=fd.span;lastWrote=0<span?span:0;if(undefined!==fd.property){const fv=src[fd.property];if(undefined!==fv){lastWrote=fd.encode(fv,b,offset);if(0>span){span=fd.getSpan(b,offset)}}}lastOffset=offset;offset+=span}return lastOffset+lastWrote-firstOffset}fromArray(values){const dest=this.makeDestinationObject();for(const fd of this.fields){if(undefined!==fd.property&&0<values.length){dest[fd.property]=values.shift()}}return dest}layoutFor(property){if("string"!==typeof property){throw new TypeError("property must be string")}for(const fd of this.fields){if(fd.property===property){return fd}}return undefined}offsetOf(property){if("string"!==typeof property){throw new TypeError("property must be string")}let offset=0;for(const fd of this.fields){if(fd.property===property){return offset}if(0>fd.span){offset=-1}else if(0<=offset){offset+=fd.span}}return undefined}}Layout.Structure=Structure;class UnionDiscriminator{constructor(property){this.property=property}decode(b,offset){throw new Error("UnionDiscriminator is abstract")}encode(src,b,offset){throw new Error("UnionDiscriminator is abstract")}}Layout.UnionDiscriminator=UnionDiscriminator;class UnionLayoutDiscriminator extends UnionDiscriminator{constructor(layout,property){if(!(layout instanceof ExternalLayout&&layout.isCount())){throw new TypeError("layout must be an unsigned integer ExternalLayout")}super(property||layout.property||"variant");this.layout=layout}decode(b,offset){return this.layout.decode(b,offset)}encode(src,b,offset){return this.layout.encode(src,b,offset)}}Layout.UnionLayoutDiscriminator=UnionLayoutDiscriminator;class Union extends Layout$1{constructor(discr,defaultLayout,property){let discriminator;if(discr instanceof UInt||discr instanceof UIntBE){discriminator=new UnionLayoutDiscriminator(new OffsetLayout(discr))}else if(discr instanceof ExternalLayout&&discr.isCount()){discriminator=new UnionLayoutDiscriminator(discr)}else if(!(discr instanceof UnionDiscriminator)){throw new TypeError("discr must be a UnionDiscriminator "+"or an unsigned integer layout")}else{discriminator=discr}if(undefined===defaultLayout){defaultLayout=null}if(!(null===defaultLayout||defaultLayout instanceof Layout$1)){throw new TypeError("defaultLayout must be null or a Layout")}if(null!==defaultLayout){if(0>defaultLayout.span){throw new Error("defaultLayout must have constant span")}if(undefined===defaultLayout.property){defaultLayout=defaultLayout.replicate("content")}}let span=-1;if(defaultLayout){span=defaultLayout.span;if(0<=span&&(discr instanceof UInt||discr instanceof UIntBE)){span+=discriminator.layout.span}}super(span,property);this.discriminator=discriminator;this.usesPrefixDiscriminator=discr instanceof UInt||discr instanceof UIntBE;this.defaultLayout=defaultLayout;this.registry={};let boundGetSourceVariant=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(src){return boundGetSourceVariant(src)};this.configGetSourceVariant=function(gsv){boundGetSourceVariant=gsv.bind(this)}}getSpan(b,offset=0){if(0<=this.span){return this.span}const vlo=this.getVariant(b,offset);if(!vlo){throw new Error("unable to determine span for unrecognized variant")}return vlo.getSpan(b,offset)}defaultGetSourceVariant(src){if(Object.prototype.hasOwnProperty.call(src,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(src,this.defaultLayout.property)){return undefined}const vlo=this.registry[src[this.discriminator.property]];if(vlo&&(!vlo.layout||vlo.property&&Object.prototype.hasOwnProperty.call(src,vlo.property))){return vlo}}else{for(const tag in this.registry){const vlo=this.registry[tag];if(vlo.property&&Object.prototype.hasOwnProperty.call(src,vlo.property)){return vlo}}}throw new Error("unable to infer src variant")}decode(b,offset=0){let dest;const dlo=this.discriminator;const discr=dlo.decode(b,offset);const clo=this.registry[discr];if(undefined===clo){const defaultLayout=this.defaultLayout;let contentOffset=0;if(this.usesPrefixDiscriminator){contentOffset=dlo.layout.span}dest=this.makeDestinationObject();dest[dlo.property]=discr;dest[defaultLayout.property]=defaultLayout.decode(b,offset+contentOffset)}else{dest=clo.decode(b,offset)}return dest}encode(src,b,offset=0){const vlo=this.getSourceVariant(src);if(undefined===vlo){const dlo=this.discriminator;const clo=this.defaultLayout;let contentOffset=0;if(this.usesPrefixDiscriminator){contentOffset=dlo.layout.span}dlo.encode(src[dlo.property],b,offset);return contentOffset+clo.encode(src[clo.property],b,offset+contentOffset)}return vlo.encode(src,b,offset)}addVariant(variant,layout,property){const rv=new VariantLayout(this,variant,layout,property);this.registry[variant]=rv;return rv}getVariant(vb,offset=0){let variant;if(vb instanceof Uint8Array){variant=this.discriminator.decode(vb,offset)}else{variant=vb}return this.registry[variant]}}Layout.Union=Union;class VariantLayout extends Layout$1{constructor(union,variant,layout,property){if(!(union instanceof Union)){throw new TypeError("union must be a Union")}if(!Number.isInteger(variant)||0>variant){throw new TypeError("variant must be a (non-negative) integer")}if("string"===typeof layout&&undefined===property){property=layout;layout=null}if(layout){if(!(layout instanceof Layout$1)){throw new TypeError("layout must be a Layout")}if(null!==union.defaultLayout&&0<=layout.span&&layout.span>union.defaultLayout.span){throw new Error("variant span exceeds span of containing union")}if("string"!==typeof property){throw new TypeError("variant must have a String property")}}let span=union.span;if(0>union.span){span=layout?layout.span:0;if(0<=span&&union.usesPrefixDiscriminator){span+=union.discriminator.layout.span}}super(span,property);this.union=union;this.variant=variant;this.layout=layout||null}getSpan(b,offset=0){if(0<=this.span){return this.span}let contentOffset=0;if(this.union.usesPrefixDiscriminator){contentOffset=this.union.discriminator.layout.span}let span=0;if(this.layout){span=this.layout.getSpan(b,offset+contentOffset)}return contentOffset+span}decode(b,offset=0){const dest=this.makeDestinationObject();if(this!==this.union.getVariant(b,offset)){throw new Error("variant mismatch")}let contentOffset=0;if(this.union.usesPrefixDiscriminator){contentOffset=this.union.discriminator.layout.span}if(this.layout){dest[this.property]=this.layout.decode(b,offset+contentOffset)}else if(this.property){dest[this.property]=true}else if(this.union.usesPrefixDiscriminator){dest[this.union.discriminator.property]=this.variant}return dest}encode(src,b,offset=0){let contentOffset=0;if(this.union.usesPrefixDiscriminator){contentOffset=this.union.discriminator.layout.span}if(this.layout&&!Object.prototype.hasOwnProperty.call(src,this.property)){throw new TypeError("variant lacks property "+this.property)}this.union.discriminator.encode(this.variant,b,offset);let span=contentOffset;if(this.layout){this.layout.encode(src[this.property],b,offset+contentOffset);span+=this.layout.getSpan(b,offset+contentOffset);if(0<=this.union.span&&span>this.union.span){throw new Error("encoded variant overruns containing union")}}return span}fromArray(values){if(this.layout){return this.layout.fromArray(values)}return undefined}}Layout.VariantLayout=VariantLayout;function fixBitwiseResult(v){if(0>v){v+=4294967296}return v}class BitStructure extends Layout$1{constructor(word,msb,property){if(!(word instanceof UInt||word instanceof UIntBE)){throw new TypeError("word must be a UInt or UIntBE layout")}if("string"===typeof msb&&undefined===property){property=msb;msb=false}if(4<word.span){throw new RangeError("word cannot exceed 32 bits")}super(word.span,property);this.word=word;this.msb=!!msb;this.fields=[];let value=0;this._packedSetValue=function(v){value=fixBitwiseResult(v);return this};this._packedGetValue=function(){return value}}decode(b,offset=0){const dest=this.makeDestinationObject();const value=this.word.decode(b,offset);this._packedSetValue(value);for(const fd of this.fields){if(undefined!==fd.property){dest[fd.property]=fd.decode(b)}}return dest}encode(src,b,offset=0){const value=this.word.decode(b,offset);this._packedSetValue(value);for(const fd of this.fields){if(undefined!==fd.property){const fv=src[fd.property];if(undefined!==fv){fd.encode(fv)}}}return this.word.encode(this._packedGetValue(),b,offset)}addField(bits,property){const bf=new BitField(this,bits,property);this.fields.push(bf);return bf}addBoolean(property){const bf=new Boolean(this,property);this.fields.push(bf);return bf}fieldFor(property){if("string"!==typeof property){throw new TypeError("property must be string")}for(const fd of this.fields){if(fd.property===property){return fd}}return undefined}}Layout.BitStructure=BitStructure;class BitField{constructor(container,bits,property){if(!(container instanceof BitStructure)){throw new TypeError("container must be a BitStructure")}if(!Number.isInteger(bits)||0>=bits){throw new TypeError("bits must be positive integer")}const totalBits=8*container.span;const usedBits=container.fields.reduce(((sum,fd)=>sum+fd.bits),0);if(bits+usedBits>totalBits){throw new Error("bits too long for span remainder ("+(totalBits-usedBits)+" of "+totalBits+" remain)")}this.container=container;this.bits=bits;this.valueMask=(1<<bits)-1;if(32===bits){this.valueMask=4294967295}this.start=usedBits;if(this.container.msb){this.start=totalBits-usedBits-bits}this.wordMask=fixBitwiseResult(this.valueMask<<this.start);this.property=property}decode(b,offset){const word=this.container._packedGetValue();const wordValue=fixBitwiseResult(word&this.wordMask);const value=wordValue>>>this.start;return value}encode(value){if("number"!==typeof value||!Number.isInteger(value)||value!==fixBitwiseResult(value&this.valueMask)){throw new TypeError(nameWithProperty("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask)}const word=this.container._packedGetValue();const wordValue=fixBitwiseResult(value<<this.start);this.container._packedSetValue(fixBitwiseResult(word&~this.wordMask)|wordValue)}}Layout.BitField=BitField;class Boolean extends BitField{constructor(container,property){super(container,1,property)}decode(b,offset){return!!super.decode(b,offset)}encode(value){if("boolean"===typeof value){value=+value}super.encode(value)}}Layout.Boolean=Boolean;class Blob extends Layout$1{constructor(length,property){if(!(length instanceof ExternalLayout&&length.isCount()||Number.isInteger(length)&&0<=length)){throw new TypeError("length must be positive integer "+"or an unsigned integer ExternalLayout")}let span=-1;if(!(length instanceof ExternalLayout)){span=length}super(span,property);this.length=length}getSpan(b,offset){let span=this.span;if(0>span){span=this.length.decode(b,offset)}return span}decode(b,offset=0){let span=this.span;if(0>span){span=this.length.decode(b,offset)}return uint8ArrayToBuffer(b).slice(offset,offset+span)}encode(src,b,offset){let span=this.length;if(this.length instanceof ExternalLayout){span=src.length}if(!(src instanceof Uint8Array&&span===src.length)){throw new TypeError(nameWithProperty("Blob.encode",this)+" requires (length "+span+") Uint8Array as src")}if(offset+span>b.length){throw new RangeError("encoding overruns Uint8Array")}const srcBuffer=uint8ArrayToBuffer(src);uint8ArrayToBuffer(b).write(srcBuffer.toString("hex"),offset,span,"hex");if(this.length instanceof ExternalLayout){this.length.encode(span,b,offset)}return span}}Layout.Blob=Blob;class CString extends Layout$1{constructor(property){super(-1,property)}getSpan(b,offset=0){checkUint8Array(b);let idx=offset;while(idx<b.length&&0!==b[idx]){idx+=1}return 1+idx-offset}decode(b,offset=0){const span=this.getSpan(b,offset);return uint8ArrayToBuffer(b).slice(offset,offset+span-1).toString("utf-8")}encode(src,b,offset=0){if("string"!==typeof src){src=String(src)}const srcb=buffer_1.Buffer.from(src,"utf8");const span=srcb.length;if(offset+span>b.length){throw new RangeError("encoding overruns Buffer")}const buffer=uint8ArrayToBuffer(b);srcb.copy(buffer,offset);buffer[offset+span]=0;return span+1}}Layout.CString=CString;class UTF8 extends Layout$1{constructor(maxSpan,property){if("string"===typeof maxSpan&&undefined===property){property=maxSpan;maxSpan=undefined}if(undefined===maxSpan){maxSpan=-1}else if(!Number.isInteger(maxSpan)){throw new TypeError("maxSpan must be an integer")}super(-1,property);this.maxSpan=maxSpan}getSpan(b,offset=0){checkUint8Array(b);return b.length-offset}decode(b,offset=0){const span=this.getSpan(b,offset);if(0<=this.maxSpan&&this.maxSpan<span){throw new RangeError("text length exceeds maxSpan")}return uint8ArrayToBuffer(b).slice(offset,offset+span).toString("utf-8")}encode(src,b,offset=0){if("string"!==typeof src){src=String(src)}const srcb=buffer_1.Buffer.from(src,"utf8");const span=srcb.length;if(0<=this.maxSpan&&this.maxSpan<span){throw new RangeError("text length exceeds maxSpan")}if(offset+span>b.length){throw new RangeError("encoding overruns Buffer")}srcb.copy(uint8ArrayToBuffer(b),offset);return span}}Layout.UTF8=UTF8;class Constant extends Layout$1{constructor(value,property){super(0,property);this.value=value}decode(b,offset){return this.value}encode(src,b,offset){return 0}}Layout.Constant=Constant;Layout.greedy=(elementSpan,property)=>new GreedyCount(elementSpan,property);Layout.offset=(layout,offset,property)=>new OffsetLayout(layout,offset,property);Layout.u8=property=>new UInt(1,property);Layout.u16=property=>new UInt(2,property);Layout.u24=property=>new UInt(3,property);Layout.u32=property=>new UInt(4,property);Layout.u40=property=>new UInt(5,property);Layout.u48=property=>new UInt(6,property);Layout.nu64=property=>new NearUInt64(property);Layout.u16be=property=>new UIntBE(2,property);Layout.u24be=property=>new UIntBE(3,property);Layout.u32be=property=>new UIntBE(4,property);Layout.u40be=property=>new UIntBE(5,property);Layout.u48be=property=>new UIntBE(6,property);Layout.nu64be=property=>new NearUInt64BE(property);Layout.s8=property=>new Int(1,property);Layout.s16=property=>new Int(2,property);Layout.s24=property=>new Int(3,property);Layout.s32=property=>new Int(4,property);Layout.s40=property=>new Int(5,property);Layout.s48=property=>new Int(6,property);Layout.ns64=property=>new NearInt64(property);Layout.s16be=property=>new IntBE(2,property);Layout.s24be=property=>new IntBE(3,property);Layout.s32be=property=>new IntBE(4,property);Layout.s40be=property=>new IntBE(5,property);Layout.s48be=property=>new IntBE(6,property);Layout.ns64be=property=>new NearInt64BE(property);Layout.f32=property=>new Float(property);Layout.f32be=property=>new FloatBE(property);Layout.f64=property=>new Double(property);Layout.f64be=property=>new DoubleBE(property);Layout.struct=(fields,property,decodePrefixes)=>new Structure(fields,property,decodePrefixes);Layout.bits=(word,msb,property)=>new BitStructure(word,msb,property);Layout.seq=(elementLayout,count,property)=>new Sequence(elementLayout,count,property);Layout.union=(discr,defaultLayout,property)=>new Union(discr,defaultLayout,property);Layout.unionLayoutDiscriminator=(layout,property)=>new UnionLayoutDiscriminator(layout,property);Layout.blob=(length,property)=>new Blob(length,property);Layout.cstr=property=>new CString(property);Layout.utf8=(maxSpan,property)=>new UTF8(maxSpan,property);Layout.constant=(value,property)=>new Constant(value,property);return Layout}var LayoutExports=requireLayout();const PACKET_DATA_SIZE=1280-40-8;const VERSION_PREFIX_MASK=127;const SIGNATURE_LENGTH_IN_BYTES=64;class TransactionExpiredBlockheightExceededError extends Error{constructor(signature){super(`Signature ${signature} has expired: block height exceeded.`);this.signature=void 0;this.signature=signature}}Object.defineProperty(TransactionExpiredBlockheightExceededError.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class TransactionExpiredTimeoutError extends Error{constructor(signature,timeoutSeconds){super(`Transaction was not confirmed in ${timeoutSeconds.toFixed(2)} seconds. It is `+"unknown if it succeeded or failed. Check signature "+`${signature} using the Solana Explorer or CLI tools.`);this.signature=void 0;this.signature=signature}}Object.defineProperty(TransactionExpiredTimeoutError.prototype,"name",{value:"TransactionExpiredTimeoutError"});class TransactionExpiredNonceInvalidError extends Error{constructor(signature){super(`Signature ${signature} has expired: the nonce is no longer valid.`);this.signature=void 0;this.signature=signature}}Object.defineProperty(TransactionExpiredNonceInvalidError.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class MessageAccountKeys{constructor(staticAccountKeys,accountKeysFromLookups){this.staticAccountKeys=void 0;this.accountKeysFromLookups=void 0;this.staticAccountKeys=staticAccountKeys;this.accountKeysFromLookups=accountKeysFromLookups}keySegments(){const keySegments=[this.staticAccountKeys];if(this.accountKeysFromLookups){keySegments.push(this.accountKeysFromLookups.writable);keySegments.push(this.accountKeysFromLookups.readonly)}return keySegments}get(index){for(const keySegment of this.keySegments()){if(index<keySegment.length){return keySegment[index]}else{index-=keySegment.length}}return}get length(){return this.keySegments().flat().length}compileInstructions(instructions){const U8_MAX=255;if(this.length>U8_MAX+1){throw new Error("Account index overflow encountered during compilation")}const keyIndexMap=new Map;this.keySegments().flat().forEach(((key,index)=>{keyIndexMap.set(key.toBase58(),index)}));const findKeyIndex=key=>{const keyIndex=keyIndexMap.get(key.toBase58());if(keyIndex===undefined)throw new Error("Encountered an unknown instruction account key during compilation");return keyIndex};return instructions.map((instruction=>({programIdIndex:findKeyIndex(instruction.programId),accountKeyIndexes:instruction.keys.map((meta=>findKeyIndex(meta.pubkey))),data:instruction.data})))}}const publicKey=(property="publicKey")=>LayoutExports.blob(32,property);const signature=(property="signature")=>LayoutExports.blob(64,property);const rustString=(property="string")=>{const rsl=LayoutExports.struct([LayoutExports.u32("length"),LayoutExports.u32("lengthPadding"),LayoutExports.blob(LayoutExports.offset(LayoutExports.u32(),-8),"chars")],property);const _decode=rsl.decode.bind(rsl);const _encode=rsl.encode.bind(rsl);const rslShim=rsl;rslShim.decode=(b,offset)=>{const data=_decode(b,offset);return data["chars"].toString()};rslShim.encode=(str,b,offset)=>{const data={chars:bufferExports.Buffer.from(str,"utf8")};return _encode(data,b,offset)};rslShim.alloc=str=>LayoutExports.u32().span+LayoutExports.u32().span+bufferExports.Buffer.from(str,"utf8").length;return rslShim};const authorized=(property="authorized")=>LayoutExports.struct([publicKey("staker"),publicKey("withdrawer")],property);const lockup=(property="lockup")=>LayoutExports.struct([LayoutExports.ns64("unixTimestamp"),LayoutExports.ns64("epoch"),publicKey("custodian")],property);const voteInit=(property="voteInit")=>LayoutExports.struct([publicKey("nodePubkey"),publicKey("authorizedVoter"),publicKey("authorizedWithdrawer"),LayoutExports.u8("commission")],property);const voteAuthorizeWithSeedArgs=(property="voteAuthorizeWithSeedArgs")=>LayoutExports.struct([LayoutExports.u32("voteAuthorizationType"),publicKey("currentAuthorityDerivedKeyOwnerPubkey"),rustString("currentAuthorityDerivedKeySeed"),publicKey("newAuthorized")],property);function getAlloc(type,fields){const getItemAlloc=item=>{if(item.span>=0){return item.span}else if(typeof item.alloc==="function"){return item.alloc(fields[item.property])}else if("count"in item&&"elementLayout"in item){const field=fields[item.property];if(Array.isArray(field)){return field.length*getItemAlloc(item.elementLayout)}}else if("fields"in item){return getAlloc({layout:item},fields[item.property])}return 0};let alloc=0;type.layout.fields.forEach((item=>{alloc+=getItemAlloc(item)}));return alloc}function decodeLength(bytes){let len=0;let size=0;for(;;){let elem=bytes.shift();len|=(elem&127)<<size*7;size+=1;if((elem&128)===0){break}}return len}function encodeLength(bytes,len){let rem_len=len;for(;;){let elem=rem_len&127;rem_len>>=7;if(rem_len==0){bytes.push(elem);break}else{elem|=128;bytes.push(elem)}}}function assert$1(condition,message){if(!condition){throw new Error(message||"Assertion failed")}}class CompiledKeys{constructor(payer,keyMetaMap){this.payer=void 0;this.keyMetaMap=void 0;this.payer=payer;this.keyMetaMap=keyMetaMap}static compile(instructions,payer){const keyMetaMap=new Map;const getOrInsertDefault=pubkey=>{const address=pubkey.toBase58();let keyMeta=keyMetaMap.get(address);if(keyMeta===undefined){keyMeta={isSigner:false,isWritable:false,isInvoked:false};keyMetaMap.set(address,keyMeta)}return keyMeta};const payerKeyMeta=getOrInsertDefault(payer);payerKeyMeta.isSigner=true;payerKeyMeta.isWritable=true;for(const ix of instructions){getOrInsertDefault(ix.programId).isInvoked=true;for(const accountMeta of ix.keys){const keyMeta=getOrInsertDefault(accountMeta.pubkey);keyMeta.isSigner||=accountMeta.isSigner;keyMeta.isWritable||=accountMeta.isWritable}}return new CompiledKeys(payer,keyMetaMap)}getMessageComponents(){const mapEntries=[...this.keyMetaMap.entries()];assert$1(mapEntries.length<=256,"Max static account keys length exceeded");const writableSigners=mapEntries.filter((([,meta])=>meta.isSigner&&meta.isWritable));const readonlySigners=mapEntries.filter((([,meta])=>meta.isSigner&&!meta.isWritable));const writableNonSigners=mapEntries.filter((([,meta])=>!meta.isSigner&&meta.isWritable));const readonlyNonSigners=mapEntries.filter((([,meta])=>!meta.isSigner&&!meta.isWritable));const header={numRequiredSignatures:writableSigners.length+readonlySigners.length,numReadonlySignedAccounts:readonlySigners.length,numReadonlyUnsignedAccounts:readonlyNonSigners.length};{assert$1(writableSigners.length>0,"Expected at least one writable signer key");const[payerAddress]=writableSigners[0];assert$1(payerAddress===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}const staticAccountKeys=[...writableSigners.map((([address])=>new PublicKey(address))),...readonlySigners.map((([address])=>new PublicKey(address))),...writableNonSigners.map((([address])=>new PublicKey(address))),...readonlyNonSigners.map((([address])=>new PublicKey(address)))];return[header,staticAccountKeys]}extractTableLookup(lookupTable){const[writableIndexes,drainedWritableKeys]=this.drainKeysFoundInLookupTable(lookupTable.state.addresses,(keyMeta=>!keyMeta.isSigner&&!keyMeta.isInvoked&&keyMeta.isWritable));const[readonlyIndexes,drainedReadonlyKeys]=this.drainKeysFoundInLookupTable(lookupTable.state.addresses,(keyMeta=>!keyMeta.isSigner&&!keyMeta.isInvoked&&!keyMeta.isWritable));if(writableIndexes.length===0&&readonlyIndexes.length===0){return}return[{accountKey:lookupTable.key,writableIndexes:writableIndexes,readonlyIndexes:readonlyIndexes},{writable:drainedWritableKeys,readonly:drainedReadonlyKeys}]}drainKeysFoundInLookupTable(lookupTableEntries,keyMetaFilter){const lookupTableIndexes=new Array;const drainedKeys=new Array;for(const[address,keyMeta]of this.keyMetaMap.entries()){if(keyMetaFilter(keyMeta)){const key=new PublicKey(address);const lookupTableIndex=lookupTableEntries.findIndex((entry=>entry.equals(key)));if(lookupTableIndex>=0){assert$1(lookupTableIndex<256,"Max lookup table index exceeded");lookupTableIndexes.push(lookupTableIndex);drainedKeys.push(key);this.keyMetaMap.delete(address)}}}return[lookupTableIndexes,drainedKeys]}}const END_OF_BUFFER_ERROR_MESSAGE="Reached end of buffer unexpectedly";function guardedShift(byteArray){if(byteArray.length===0){throw new Error(END_OF_BUFFER_ERROR_MESSAGE)}return byteArray.shift()}function guardedSplice(byteArray,...args){const[start]=args;if(args.length===2?start+(args[1]??0)>byteArray.length:start>=byteArray.length){throw new Error(END_OF_BUFFER_ERROR_MESSAGE)}return byteArray.splice(...args)}class Message{constructor(args){this.header=void 0;this.accountKeys=void 0;this.recentBlockhash=void 0;this.instructions=void 0;this.indexToProgramIds=new Map;this.header=args.header;this.accountKeys=args.accountKeys.map((account=>new PublicKey(account)));this.recentBlockhash=args.recentBlockhash;this.instructions=args.instructions;this.instructions.forEach((ix=>this.indexToProgramIds.set(ix.programIdIndex,this.accountKeys[ix.programIdIndex])))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map((ix=>({programIdIndex:ix.programIdIndex,accountKeyIndexes:ix.accounts,data:bs58.decode(ix.data)})))}get addressTableLookups(){return[]}getAccountKeys(){return new MessageAccountKeys(this.staticAccountKeys)}static compile(args){const compiledKeys=CompiledKeys.compile(args.instructions,args.payerKey);const[header,staticAccountKeys]=compiledKeys.getMessageComponents();const accountKeys=new MessageAccountKeys(staticAccountKeys);const instructions=accountKeys.compileInstructions(args.instructions).map((ix=>({programIdIndex:ix.programIdIndex,accounts:ix.accountKeyIndexes,data:bs58.encode(ix.data)})));return new Message({header:header,accountKeys:staticAccountKeys,recentBlockhash:args.recentBlockhash,instructions:instructions})}isAccountSigner(index){return index<this.header.numRequiredSignatures}isAccountWritable(index){const numSignedAccounts=this.header.numRequiredSignatures;if(index>=this.header.numRequiredSignatures){const unsignedAccountIndex=index-numSignedAccounts;const numUnsignedAccounts=this.accountKeys.length-numSignedAccounts;const numWritableUnsignedAccounts=numUnsignedAccounts-this.header.numReadonlyUnsignedAccounts;return unsignedAccountIndex<numWritableUnsignedAccounts}else{const numWritableSignedAccounts=numSignedAccounts-this.header.numReadonlySignedAccounts;return index<numWritableSignedAccounts}}isProgramId(index){return this.indexToProgramIds.has(index)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter(((_,index)=>!this.isProgramId(index)))}serialize(){const numKeys=this.accountKeys.length;let keyCount=[];encodeLength(keyCount,numKeys);const instructions=this.instructions.map((instruction=>{const{accounts:accounts,programIdIndex:programIdIndex}=instruction;const data=Array.from(bs58.decode(instruction.data));let keyIndicesCount=[];encodeLength(keyIndicesCount,accounts.length);let dataCount=[];encodeLength(dataCount,data.length);return{programIdIndex:programIdIndex,keyIndicesCount:bufferExports.Buffer.from(keyIndicesCount),keyIndices:accounts,dataLength:bufferExports.Buffer.from(dataCount),data:data}}));let instructionCount=[];encodeLength(instructionCount,instructions.length);let instructionBuffer=bufferExports.Buffer.alloc(PACKET_DATA_SIZE);bufferExports.Buffer.from(instructionCount).copy(instructionBuffer);let instructionBufferLength=instructionCount.length;instructions.forEach((instruction=>{const instructionLayout=LayoutExports.struct([LayoutExports.u8("programIdIndex"),LayoutExports.blob(instruction.keyIndicesCount.length,"keyIndicesCount"),LayoutExports.seq(LayoutExports.u8("keyIndex"),instruction.keyIndices.length,"keyIndices"),LayoutExports.blob(instruction.dataLength.length,"dataLength"),LayoutExports.seq(LayoutExports.u8("userdatum"),instruction.data.length,"data")]);const length=instructionLayout.encode(instruction,instructionBuffer,instructionBufferLength);instructionBufferLength+=length}));instructionBuffer=instructionBuffer.slice(0,instructionBufferLength);const signDataLayout=LayoutExports.struct([LayoutExports.blob(1,"numRequiredSignatures"),LayoutExports.blob(1,"numReadonlySignedAccounts"),LayoutExports.blob(1,"numReadonlyUnsignedAccounts"),LayoutExports.blob(keyCount.length,"keyCount"),LayoutExports.seq(publicKey("key"),numKeys,"keys"),publicKey("recentBlockhash")]);const transaction={numRequiredSignatures:bufferExports.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:bufferExports.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:bufferExports.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:bufferExports.Buffer.from(keyCount),keys:this.accountKeys.map((key=>toBuffer(key.toBytes()))),recentBlockhash:bs58.decode(this.recentBlockhash)};let signData=bufferExports.Buffer.alloc(2048);const length=signDataLayout.encode(transaction,signData);instructionBuffer.copy(signData,length);return signData.slice(0,length+instructionBuffer.length)}static from(buffer){let byteArray=[...buffer];const numRequiredSignatures=guardedShift(byteArray);if(numRequiredSignatures!==(numRequiredSignatures&VERSION_PREFIX_MASK)){throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()")}const numReadonlySignedAccounts=guardedShift(byteArray);const numReadonlyUnsignedAccounts=guardedShift(byteArray);const accountCount=decodeLength(byteArray);let accountKeys=[];for(let i=0;i<accountCount;i++){const account=guardedSplice(byteArray,0,PUBLIC_KEY_LENGTH);accountKeys.push(new PublicKey(bufferExports.Buffer.from(account)))}const recentBlockhash=guardedSplice(byteArray,0,PUBLIC_KEY_LENGTH);const instructionCount=decodeLength(byteArray);let instructions=[];for(let i=0;i<instructionCount;i++){const programIdIndex=guardedShift(byteArray);const accountCount=decodeLength(byteArray);const accounts=guardedSplice(byteArray,0,accountCount);const dataLength=decodeLength(byteArray);const dataSlice=guardedSplice(byteArray,0,dataLength);const data=bs58.encode(bufferExports.Buffer.from(dataSlice));instructions.push({programIdIndex:programIdIndex,accounts:accounts,data:data})}const messageArgs={header:{numRequiredSignatures:numRequiredSignatures,numReadonlySignedAccounts:numReadonlySignedAccounts,numReadonlyUnsignedAccounts:numReadonlyUnsignedAccounts},recentBlockhash:bs58.encode(bufferExports.Buffer.from(recentBlockhash)),accountKeys:accountKeys,instructions:instructions};return new Message(messageArgs)}}class MessageV0{constructor(args){this.header=void 0;this.staticAccountKeys=void 0;this.recentBlockhash=void 0;this.compiledInstructions=void 0;this.addressTableLookups=void 0;this.header=args.header;this.staticAccountKeys=args.staticAccountKeys;this.recentBlockhash=args.recentBlockhash;this.compiledInstructions=args.compiledInstructions;this.addressTableLookups=args.addressTableLookups}get version(){return 0}get numAccountKeysFromLookups(){let count=0;for(const lookup of this.addressTableLookups){count+=lookup.readonlyIndexes.length+lookup.writableIndexes.length}return count}getAccountKeys(args){let accountKeysFromLookups;if(args&&"accountKeysFromLookups"in args&&args.accountKeysFromLookups){if(this.numAccountKeysFromLookups!=args.accountKeysFromLookups.writable.length+args.accountKeysFromLookups.readonly.length){throw new Error("Failed to get account keys because of a mismatch in the number of account keys from lookups")}accountKeysFromLookups=args.accountKeysFromLookups}else if(args&&"addressLookupTableAccounts"in args&&args.addressLookupTableAccounts){accountKeysFromLookups=this.resolveAddressTableLookups(args.addressLookupTableAccounts)}else if(this.addressTableLookups.length>0){throw new Error("Failed to get account keys because address table lookups were not resolved")}return new MessageAccountKeys(this.staticAccountKeys,accountKeysFromLookups)}isAccountSigner(index){return index<this.header.numRequiredSignatures}isAccountWritable(index){const numSignedAccounts=this.header.numRequiredSignatures;const numStaticAccountKeys=this.staticAccountKeys.length;if(index>=numStaticAccountKeys){const lookupAccountKeysIndex=index-numStaticAccountKeys;const numWritableLookupAccountKeys=this.addressTableLookups.reduce(((count,lookup)=>count+lookup.writableIndexes.length),0);return lookupAccountKeysIndex<numWritableLookupAccountKeys}else if(index>=this.header.numRequiredSignatures){const unsignedAccountIndex=index-numSignedAccounts;const numUnsignedAccounts=numStaticAccountKeys-numSignedAccounts;const numWritableUnsignedAccounts=numUnsignedAccounts-this.header.numReadonlyUnsignedAccounts;return unsignedAccountIndex<numWritableUnsignedAccounts}else{const numWritableSignedAccounts=numSignedAccounts-this.header.numReadonlySignedAccounts;return index<numWritableSignedAccounts}}resolveAddressTableLookups(addressLookupTableAccounts){const accountKeysFromLookups={writable:[],readonly:[]};for(const tableLookup of this.addressTableLookups){const tableAccount=addressLookupTableAccounts.find((account=>account.key.equals(tableLookup.accountKey)));if(!tableAccount){throw new Error(`Failed to find address lookup table account for table key ${tableLookup.accountKey.toBase58()}`)}for(const index of tableLookup.writableIndexes){if(index<tableAccount.state.addresses.length){accountKeysFromLookups.writable.push(tableAccount.state.addresses[index])}else{throw new Error(`Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`)}}for(const index of tableLookup.readonlyIndexes){if(index<tableAccount.state.addresses.length){accountKeysFromLookups.readonly.push(tableAccount.state.addresses[index])}else{throw new Error(`Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`)}}}return accountKeysFromLookups}static compile(args){const compiledKeys=CompiledKeys.compile(args.instructions,args.payerKey);const addressTableLookups=new Array;const accountKeysFromLookups={writable:new Array,readonly:new Array};const lookupTableAccounts=args.addressLookupTableAccounts||[];for(const lookupTable of lookupTableAccounts){const extractResult=compiledKeys.extractTableLookup(lookupTable);if(extractResult!==undefined){const[addressTableLookup,{writable:writable,readonly:readonly}]=extractResult;addressTableLookups.push(addressTableLookup);accountKeysFromLookups.writable.push(...writable);accountKeysFromLookups.readonly.push(...readonly)}}const[header,staticAccountKeys]=compiledKeys.getMessageComponents();const accountKeys=new MessageAccountKeys(staticAccountKeys,accountKeysFromLookups);const compiledInstructions=accountKeys.compileInstructions(args.instructions);return new MessageV0({header:header,staticAccountKeys:staticAccountKeys,recentBlockhash:args.recentBlockhash,compiledInstructions:compiledInstructions,addressTableLookups:addressTableLookups})}serialize(){const encodedStaticAccountKeysLength=Array();encodeLength(encodedStaticAccountKeysLength,this.staticAccountKeys.length);const serializedInstructions=this.serializeInstructions();const encodedInstructionsLength=Array();encodeLength(encodedInstructionsLength,this.compiledInstructions.length);const serializedAddressTableLookups=this.serializeAddressTableLookups();const encodedAddressTableLookupsLength=Array();encodeLength(encodedAddressTableLookupsLength,this.addressTableLookups.length);const messageLayout=LayoutExports.struct([LayoutExports.u8("prefix"),LayoutExports.struct([LayoutExports.u8("numRequiredSignatures"),LayoutExports.u8("numReadonlySignedAccounts"),LayoutExports.u8("numReadonlyUnsignedAccounts")],"header"),LayoutExports.blob(encodedStaticAccountKeysLength.length,"staticAccountKeysLength"),LayoutExports.seq(publicKey(),this.staticAccountKeys.length,"staticAccountKeys"),publicKey("recentBlockhash"),LayoutExports.blob(encodedInstructionsLength.length,"instructionsLength"),LayoutExports.blob(serializedInstructions.length,"serializedInstructions"),LayoutExports.blob(encodedAddressTableLookupsLength.length,"addressTableLookupsLength"),LayoutExports.blob(serializedAddressTableLookups.length,"serializedAddressTableLookups")]);const serializedMessage=new Uint8Array(PACKET_DATA_SIZE);const MESSAGE_VERSION_0_PREFIX=1<<7;const serializedMessageLength=messageLayout.encode({prefix:MESSAGE_VERSION_0_PREFIX,header:this.header,staticAccountKeysLength:new Uint8Array(encodedStaticAccountKeysLength),staticAccountKeys:this.staticAccountKeys.map((key=>key.toBytes())),recentBlockhash:bs58.decode(this.recentBlockhash),instructionsLength:new Uint8Array(encodedInstructionsLength),serializedInstructions:serializedInstructions,addressTableLookupsLength:new Uint8Array(encodedAddressTableLookupsLength),serializedAddressTableLookups:serializedAddressTableLookups},serializedMessage);return serializedMessage.slice(0,serializedMessageLength)}serializeInstructions(){let serializedLength=0;const serializedInstructions=new Uint8Array(PACKET_DATA_SIZE);for(const instruction of this.compiledInstructions){const encodedAccountKeyIndexesLength=Array();encodeLength(encodedAccountKeyIndexesLength,instruction.accountKeyIndexes.length);const encodedDataLength=Array();encodeLength(encodedDataLength,instruction.data.length);const instructionLayout=LayoutExports.struct([LayoutExports.u8("programIdIndex"),LayoutExports.blob(encodedAccountKeyIndexesLength.length,"encodedAccountKeyIndexesLength"),LayoutExports.seq(LayoutExports.u8(),instruction.accountKeyIndexes.length,"accountKeyIndexes"),LayoutExports.blob(encodedDataLength.length,"encodedDataLength"),LayoutExports.blob(instruction.data.length,"data")]);serializedLength+=instructionLayout.encode({programIdIndex:instruction.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(encodedAccountKeyIndexesLength),accountKeyIndexes:instruction.accountKeyIndexes,encodedDataLength:new Uint8Array(encodedDataLength),data:instruction.data},serializedInstructions,serializedLength)}return serializedInstructions.slice(0,serializedLength)}serializeAddressTableLookups(){let serializedLength=0;const serializedAddressTableLookups=new Uint8Array(PACKET_DATA_SIZE);for(const lookup of this.addressTableLookups){const encodedWritableIndexesLength=Array();encodeLength(encodedWritableIndexesLength,lookup.writableIndexes.length);const encodedReadonlyIndexesLength=Array();encodeLength(encodedReadonlyIndexesLength,lookup.readonlyIndexes.length);const addressTableLookupLayout=LayoutExports.struct([publicKey("accountKey"),LayoutExports.blob(encodedWritableIndexesLength.length,"encodedWritableIndexesLength"),LayoutExports.seq(LayoutExports.u8(),lookup.writableIndexes.length,"writableIndexes"),LayoutExports.blob(encodedReadonlyIndexesLength.length,"encodedReadonlyIndexesLength"),LayoutExports.seq(LayoutExports.u8(),lookup.readonlyIndexes.length,"readonlyIndexes")]);serializedLength+=addressTableLookupLayout.encode({accountKey:lookup.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(encodedWritableIndexesLength),writableIndexes:lookup.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(encodedReadonlyIndexesLength),readonlyIndexes:lookup.readonlyIndexes},serializedAddressTableLookups,serializedLength)}return serializedAddressTableLookups.slice(0,serializedLength)}static deserialize(serializedMessage){let byteArray=[...serializedMessage];const prefix=guardedShift(byteArray);const maskedPrefix=prefix&VERSION_PREFIX_MASK;assert$1(prefix!==maskedPrefix,`Expected versioned message but received legacy message`);const version=maskedPrefix;assert$1(version===0,`Expected versioned message with version 0 but found version ${version}`);const header={numRequiredSignatures:guardedShift(byteArray),numReadonlySignedAccounts:guardedShift(byteArray),numReadonlyUnsignedAccounts:guardedShift(byteArray)};const staticAccountKeys=[];const staticAccountKeysLength=decodeLength(byteArray);for(let i=0;i<staticAccountKeysLength;i++){staticAccountKeys.push(new PublicKey(guardedSplice(byteArray,0,PUBLIC_KEY_LENGTH)))}const recentBlockhash=bs58.encode(guardedSplice(byteArray,0,PUBLIC_KEY_LENGTH));const instructionCount=decodeLength(byteArray);const compiledInstructions=[];for(let i=0;i<instructionCount;i++){const programIdIndex=guardedShift(byteArray);const accountKeyIndexesLength=decodeLength(byteArray);const accountKeyIndexes=guardedSplice(byteArray,0,accountKeyIndexesLength);const dataLength=decodeLength(byteArray);const data=new Uint8Array(guardedSplice(byteArray,0,dataLength));compiledInstructions.push({programIdIndex:programIdIndex,accountKeyIndexes:accountKeyIndexes,data:data})}const addressTableLookupsCount=decodeLength(byteArray);const addressTableLookups=[];for(let i=0;i<addressTableLookupsCount;i++){const accountKey=new PublicKey(guardedSplice(byteArray,0,PUBLIC_KEY_LENGTH));const writableIndexesLength=decodeLength(byteArray);const writableIndexes=guardedSplice(byteArray,0,writableIndexesLength);const readonlyIndexesLength=decodeLength(byteArray);const readonlyIndexes=guardedSplice(byteArray,0,readonlyIndexesLength);addressTableLookups.push({accountKey:accountKey,writableIndexes:writableIndexes,readonlyIndexes:readonlyIndexes})}return new MessageV0({header:header,staticAccountKeys:staticAccountKeys,recentBlockhash:recentBlockhash,compiledInstructions:compiledInstructions,addressTableLookups:addressTableLookups})}}const VersionedMessage={deserializeMessageVersion(serializedMessage){const prefix=serializedMessage[0];const maskedPrefix=prefix&VERSION_PREFIX_MASK;if(maskedPrefix===prefix){return"legacy"}return maskedPrefix},deserialize:serializedMessage=>{const version=VersionedMessage.deserializeMessageVersion(serializedMessage);if(version==="legacy"){return Message.from(serializedMessage)}if(version===0){return MessageV0.deserialize(serializedMessage)}else{throw new Error(`Transaction message version ${version} deserialization is not supported`)}}};let TransactionStatus=function(TransactionStatus){TransactionStatus[TransactionStatus["BLOCKHEIGHT_EXCEEDED"]=0]="BLOCKHEIGHT_EXCEEDED";TransactionStatus[TransactionStatus["PROCESSED"]=1]="PROCESSED";TransactionStatus[TransactionStatus["TIMED_OUT"]=2]="TIMED_OUT";TransactionStatus[TransactionStatus["NONCE_INVALID"]=3]="NONCE_INVALID";return TransactionStatus}({});const DEFAULT_SIGNATURE=bufferExports.Buffer.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0);class TransactionInstruction{constructor(opts){this.keys=void 0;this.programId=void 0;this.data=bufferExports.Buffer.alloc(0);this.programId=opts.programId;this.keys=opts.keys;if(opts.data){this.data=opts.data}}toJSON(){return{keys:this.keys.map((({pubkey:pubkey,isSigner:isSigner,isWritable:isWritable})=>({pubkey:pubkey.toJSON(),isSigner:isSigner,isWritable:isWritable}))),programId:this.programId.toJSON(),data:[...this.data]}}}class Transaction{get signature(){if(this.signatures.length>0){return this.signatures[0].signature}return null}constructor(opts){this.signatures=[];this.feePayer=void 0;this.instructions=[];this.recentBlockhash=void 0;this.lastValidBlockHeight=void 0;this.nonceInfo=void 0;this.minNonceContextSlot=void 0;this._message=void 0;this._json=void 0;if(!opts){return}if(opts.feePayer){this.feePayer=opts.feePayer}if(opts.signatures){this.signatures=opts.signatures}if(Object.prototype.hasOwnProperty.call(opts,"nonceInfo")){const{minContextSlot:minContextSlot,nonceInfo:nonceInfo}=opts;this.minNonceContextSlot=minContextSlot;this.nonceInfo=nonceInfo}else if(Object.prototype.hasOwnProperty.call(opts,"lastValidBlockHeight")){const{blockhash:blockhash,lastValidBlockHeight:lastValidBlockHeight}=opts;this.recentBlockhash=blockhash;this.lastValidBlockHeight=lastValidBlockHeight}else{const{recentBlockhash:recentBlockhash,nonceInfo:nonceInfo}=opts;if(nonceInfo){this.nonceInfo=nonceInfo}this.recentBlockhash=recentBlockhash}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map((instruction=>instruction.toJSON())),signers:this.signatures.map((({publicKey:publicKey})=>publicKey.toJSON()))}}add(...items){if(items.length===0){throw new Error("No instructions")}items.forEach((item=>{if("instructions"in item){this.instructions=this.instructions.concat(item.instructions)}else if("data"in item&&"programId"in item&&"keys"in item){this.instructions.push(item)}else{this.instructions.push(new TransactionInstruction(item))}}));return this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json)){return this._message}let recentBlockhash;let instructions;if(this.nonceInfo){recentBlockhash=this.nonceInfo.nonce;if(this.instructions[0]!=this.nonceInfo.nonceInstruction){instructions=[this.nonceInfo.nonceInstruction,...this.instructions]}else{instructions=this.instructions}}else{recentBlockhash=this.recentBlockhash;instructions=this.instructions}if(!recentBlockhash){throw new Error("Transaction recentBlockhash required")}if(instructions.length<1){console.warn("No instructions provided")}let feePayer;if(this.feePayer){feePayer=this.feePayer}else if(this.signatures.length>0&&this.signatures[0].publicKey){feePayer=this.signatures[0].publicKey}else{throw new Error("Transaction fee payer required")}for(let i=0;i<instructions.length;i++){if(instructions[i].programId===undefined){throw new Error(`Transaction instruction index ${i} has undefined program id`)}}const programIds=[];const accountMetas=[];instructions.forEach((instruction=>{instruction.keys.forEach((accountMeta=>{accountMetas.push({...accountMeta})}));const programId=instruction.programId.toString();if(!programIds.includes(programId)){programIds.push(programId)}}));programIds.forEach((programId=>{accountMetas.push({pubkey:new PublicKey(programId),isSigner:false,isWritable:false})}));const uniqueMetas=[];accountMetas.forEach((accountMeta=>{const pubkeyString=accountMeta.pubkey.toString();const uniqueIndex=uniqueMetas.findIndex((x=>x.pubkey.toString()===pubkeyString));if(uniqueIndex>-1){uniqueMetas[uniqueIndex].isWritable=uniqueMetas[uniqueIndex].isWritable||accountMeta.isWritable;uniqueMetas[uniqueIndex].isSigner=uniqueMetas[uniqueIndex].isSigner||accountMeta.isSigner}else{uniqueMetas.push(accountMeta)}}));uniqueMetas.sort((function(x,y){if(x.isSigner!==y.isSigner){return x.isSigner?-1:1}if(x.isWritable!==y.isWritable){return x.isWritable?-1:1}const options={localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:false,numeric:false,caseFirst:"lower"};return x.pubkey.toBase58().localeCompare(y.pubkey.toBase58(),"en",options)}));const feePayerIndex=uniqueMetas.findIndex((x=>x.pubkey.equals(feePayer)));if(feePayerIndex>-1){const[payerMeta]=uniqueMetas.splice(feePayerIndex,1);payerMeta.isSigner=true;payerMeta.isWritable=true;uniqueMetas.unshift(payerMeta)}else{uniqueMetas.unshift({pubkey:feePayer,isSigner:true,isWritable:true})}for(const signature of this.signatures){const uniqueIndex=uniqueMetas.findIndex((x=>x.pubkey.equals(signature.publicKey)));if(uniqueIndex>-1){if(!uniqueMetas[uniqueIndex].isSigner){uniqueMetas[uniqueIndex].isSigner=true;console.warn("Transaction references a signature that is unnecessary, "+"only the fee payer and instruction signer accounts should sign a transaction. "+"This behavior is deprecated and will throw an error in the next major version release.")}}else{throw new Error(`unknown signer: ${signature.publicKey.toString()}`)}}let numRequiredSignatures=0;let numReadonlySignedAccounts=0;let numReadonlyUnsignedAccounts=0;const signedKeys=[];const unsignedKeys=[];uniqueMetas.forEach((({pubkey:pubkey,isSigner:isSigner,isWritable:isWritable})=>{if(isSigner){signedKeys.push(pubkey.toString());numRequiredSignatures+=1;if(!isWritable){numReadonlySignedAccounts+=1}}else{unsignedKeys.push(pubkey.toString());if(!isWritable){numReadonlyUnsignedAccounts+=1}}}));const accountKeys=signedKeys.concat(unsignedKeys);const compiledInstructions=instructions.map((instruction=>{const{data:data,programId:programId}=instruction;return{programIdIndex:accountKeys.indexOf(programId.toString()),accounts:instruction.keys.map((meta=>accountKeys.indexOf(meta.pubkey.toString()))),data:bs58.encode(data)}}));compiledInstructions.forEach((instruction=>{assert$1(instruction.programIdIndex>=0);instruction.accounts.forEach((keyIndex=>assert$1(keyIndex>=0)))}));return new Message({header:{numRequiredSignatures:numRequiredSignatures,numReadonlySignedAccounts:numReadonlySignedAccounts,numReadonlyUnsignedAccounts:numReadonlyUnsignedAccounts},accountKeys:accountKeys,recentBlockhash:recentBlockhash,instructions:compiledInstructions})}_compile(){const message=this.compileMessage();const signedKeys=message.accountKeys.slice(0,message.header.numRequiredSignatures);if(this.signatures.length===signedKeys.length){const valid=this.signatures.every(((pair,index)=>signedKeys[index].equals(pair.publicKey)));if(valid)return message}this.signatures=signedKeys.map((publicKey=>({signature:null,publicKey:publicKey})));return message}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(connection){return(await connection.getFeeForMessage(this.compileMessage())).value}setSigners(...signers){if(signers.length===0){throw new Error("No signers")}const seen=new Set;this.signatures=signers.filter((publicKey=>{const key=publicKey.toString();if(seen.has(key)){return false}else{seen.add(key);return true}})).map((publicKey=>({signature:null,publicKey:publicKey})))}sign(...signers){if(signers.length===0){throw new Error("No signers")}const seen=new Set;const uniqueSigners=[];for(const signer of signers){const key=signer.publicKey.toString();if(seen.has(key)){continue}else{seen.add(key);uniqueSigners.push(signer)}}this.signatures=uniqueSigners.map((signer=>({signature:null,publicKey:signer.publicKey})));const message=this._compile();this._partialSign(message,...uniqueSigners)}partialSign(...signers){if(signers.length===0){throw new Error("No signers")}const seen=new Set;const uniqueSigners=[];for(const signer of signers){const key=signer.publicKey.toString();if(seen.has(key)){continue}else{seen.add(key);uniqueSigners.push(signer)}}const message=this._compile();this._partialSign(message,...uniqueSigners)}_partialSign(message,...signers){const signData=message.serialize();signers.forEach((signer=>{const signature=sign(signData,signer.secretKey);this._addSignature(signer.publicKey,toBuffer(signature))}))}addSignature(pubkey,signature){this._compile();this._addSignature(pubkey,signature)}_addSignature(pubkey,signature){assert$1(signature.length===64);const index=this.signatures.findIndex((sigpair=>pubkey.equals(sigpair.publicKey)));if(index<0){throw new Error(`unknown signer: ${pubkey.toString()}`)}this.signatures[index].signature=bufferExports.Buffer.from(signature)}verifySignatures(requireAllSignatures=true){const signatureErrors=this._getMessageSignednessErrors(this.serializeMessage(),requireAllSignatures);return!signatureErrors}_getMessageSignednessErrors(message,requireAllSignatures){const errors={};for(const{signature:signature,publicKey:publicKey}of this.signatures){if(signature===null){if(requireAllSignatures){(errors.missing||=[]).push(publicKey)}}else{if(!verify(signature,message,publicKey.toBytes())){(errors.invalid||=[]).push(publicKey)}}}return errors.invalid||errors.missing?errors:undefined}serialize(config){const{requireAllSignatures:requireAllSignatures,verifySignatures:verifySignatures}=Object.assign({requireAllSignatures:true,verifySignatures:true},config);const signData=this.serializeMessage();if(verifySignatures){const sigErrors=this._getMessageSignednessErrors(signData,requireAllSignatures);if(sigErrors){let errorMessage="Signature verification failed.";if(sigErrors.invalid){errorMessage+=`\nInvalid signature for public key${sigErrors.invalid.length===1?"":"(s)"} [\`${sigErrors.invalid.map((p=>p.toBase58())).join("`, `")}\`].`}if(sigErrors.missing){errorMessage+=`\nMissing signature for public key${sigErrors.missing.length===1?"":"(s)"} [\`${sigErrors.missing.map((p=>p.toBase58())).join("`, `")}\`].`}throw new Error(errorMessage)}}return this._serialize(signData)}_serialize(signData){const{signatures:signatures}=this;const signatureCount=[];encodeLength(signatureCount,signatures.length);const transactionLength=signatureCount.length+signatures.length*64+signData.length;const wireTransaction=bufferExports.Buffer.alloc(transactionLength);assert$1(signatures.length<256);bufferExports.Buffer.from(signatureCount).copy(wireTransaction,0);signatures.forEach((({signature:signature},index)=>{if(signature!==null){assert$1(signature.length===64,`signature has invalid length`);bufferExports.Buffer.from(signature).copy(wireTransaction,signatureCount.length+index*64)}}));signData.copy(wireTransaction,signatureCount.length+signatures.length*64);assert$1(wireTransaction.length<=PACKET_DATA_SIZE,`Transaction too large: ${wireTransaction.length} > ${PACKET_DATA_SIZE}`);return wireTransaction}get keys(){assert$1(this.instructions.length===1);return this.instructions[0].keys.map((keyObj=>keyObj.pubkey))}get programId(){assert$1(this.instructions.length===1);return this.instructions[0].programId}get data(){assert$1(this.instructions.length===1);return this.instructions[0].data}static from(buffer){let byteArray=[...buffer];const signatureCount=decodeLength(byteArray);let signatures=[];for(let i=0;i<signatureCount;i++){const signature=guardedSplice(byteArray,0,SIGNATURE_LENGTH_IN_BYTES);signatures.push(bs58.encode(bufferExports.Buffer.from(signature)))}return Transaction.populate(Message.from(byteArray),signatures)}static populate(message,signatures=[]){const transaction=new Transaction;transaction.recentBlockhash=message.recentBlockhash;if(message.header.numRequiredSignatures>0){transaction.feePayer=message.accountKeys[0]}signatures.forEach(((signature,index)=>{const sigPubkeyPair={signature:signature==bs58.encode(DEFAULT_SIGNATURE)?null:bs58.decode(signature),publicKey:message.accountKeys[index]};transaction.signatures.push(sigPubkeyPair)}));message.instructions.forEach((instruction=>{const keys=instruction.accounts.map((account=>{const pubkey=message.accountKeys[account];return{pubkey:pubkey,isSigner:transaction.signatures.some((keyObj=>keyObj.publicKey.toString()===pubkey.toString()))||message.isAccountSigner(account),isWritable:message.isAccountWritable(account)}}));transaction.instructions.push(new TransactionInstruction({keys:keys,programId:message.accountKeys[instruction.programIdIndex],data:bs58.decode(instruction.data)}))}));transaction._message=message;transaction._json=transaction.toJSON();return transaction}}class TransactionMessage{constructor(args){this.payerKey=void 0;this.instructions=void 0;this.recentBlockhash=void 0;this.payerKey=args.payerKey;this.instructions=args.instructions;this.recentBlockhash=args.recentBlockhash}static decompile(message,args){const{header:header,compiledInstructions:compiledInstructions,recentBlockhash:recentBlockhash}=message;const{numRequiredSignatures:numRequiredSignatures,numReadonlySignedAccounts:numReadonlySignedAccounts,numReadonlyUnsignedAccounts:numReadonlyUnsignedAccounts}=header;const numWritableSignedAccounts=numRequiredSignatures-numReadonlySignedAccounts;assert$1(numWritableSignedAccounts>0,"Message header is invalid");const numWritableUnsignedAccounts=message.staticAccountKeys.length-numRequiredSignatures-numReadonlyUnsignedAccounts;assert$1(numWritableUnsignedAccounts>=0,"Message header is invalid");const accountKeys=message.getAccountKeys(args);const payerKey=accountKeys.get(0);if(payerKey===undefined){throw new Error("Failed to decompile message because no account keys were found")}const instructions=[];for(const compiledIx of compiledInstructions){const keys=[];for(const keyIndex of compiledIx.accountKeyIndexes){const pubkey=accountKeys.get(keyIndex);if(pubkey===undefined){throw new Error(`Failed to find key for account key index ${keyIndex}`)}const isSigner=keyIndex<numRequiredSignatures;let isWritable;if(isSigner){isWritable=keyIndex<numWritableSignedAccounts}else if(keyIndex<accountKeys.staticAccountKeys.length){isWritable=keyIndex-numRequiredSignatures<numWritableUnsignedAccounts}else{isWritable=keyIndex-accountKeys.staticAccountKeys.length<accountKeys.accountKeysFromLookups.writable.length}keys.push({pubkey:pubkey,isSigner:keyIndex<header.numRequiredSignatures,isWritable:isWritable})}const programId=accountKeys.get(compiledIx.programIdIndex);if(programId===undefined){throw new Error(`Failed to find program id for program id index ${compiledIx.programIdIndex}`)}instructions.push(new TransactionInstruction({programId:programId,data:toBuffer(compiledIx.data),keys:keys}))}return new TransactionMessage({payerKey:payerKey,instructions:instructions,recentBlockhash:recentBlockhash})}compileToLegacyMessage(){return Message.compile({payerKey:this.payerKey,recentBlockhash:this.recentBlockhash,instructions:this.instructions})}compileToV0Message(addressLookupTableAccounts){return MessageV0.compile({payerKey:this.payerKey,recentBlockhash:this.recentBlockhash,instructions:this.instructions,addressLookupTableAccounts:addressLookupTableAccounts})}}class VersionedTransaction{get version(){return this.message.version}constructor(message,signatures){this.signatures=void 0;this.message=void 0;if(signatures!==undefined){assert$1(signatures.length===message.header.numRequiredSignatures,"Expected signatures length to be equal to the number of required signatures");this.signatures=signatures}else{const defaultSignatures=[];for(let i=0;i<message.header.numRequiredSignatures;i++){defaultSignatures.push(new Uint8Array(SIGNATURE_LENGTH_IN_BYTES))}this.signatures=defaultSignatures}this.message=message}serialize(){const serializedMessage=this.message.serialize();const encodedSignaturesLength=Array();encodeLength(encodedSignaturesLength,this.signatures.length);const transactionLayout=LayoutExports.struct([LayoutExports.blob(encodedSignaturesLength.length,"encodedSignaturesLength"),LayoutExports.seq(signature(),this.signatures.length,"signatures"),LayoutExports.blob(serializedMessage.length,"serializedMessage")]);const serializedTransaction=new Uint8Array(2048);const serializedTransactionLength=transactionLayout.encode({encodedSignaturesLength:new Uint8Array(encodedSignaturesLength),signatures:this.signatures,serializedMessage:serializedMessage},serializedTransaction);return serializedTransaction.slice(0,serializedTransactionLength)}static deserialize(serializedTransaction){let byteArray=[...serializedTransaction];const signatures=[];const signaturesLength=decodeLength(byteArray);for(let i=0;i<signaturesLength;i++){signatures.push(new Uint8Array(guardedSplice(byteArray,0,SIGNATURE_LENGTH_IN_BYTES)))}const message=VersionedMessage.deserialize(new Uint8Array(byteArray));return new VersionedTransaction(message,signatures)}sign(signers){const messageData=this.message.serialize();const signerPubkeys=this.message.staticAccountKeys.slice(0,this.message.header.numRequiredSignatures);for(const signer of signers){const signerIndex=signerPubkeys.findIndex((pubkey=>pubkey.equals(signer.publicKey)));assert$1(signerIndex>=0,`Cannot sign with non signer key ${signer.publicKey.toBase58()}`);this.signatures[signerIndex]=sign(messageData,signer.secretKey)}}addSignature(publicKey,signature){assert$1(signature.byteLength===64,"Signature must be 64 bytes long");const signerPubkeys=this.message.staticAccountKeys.slice(0,this.message.header.numRequiredSignatures);const signerIndex=signerPubkeys.findIndex((pubkey=>pubkey.equals(publicKey)));assert$1(signerIndex>=0,`Can not add signature; \`${publicKey.toBase58()}\` is not required to sign this transaction`);this.signatures[signerIndex]=signature}}const NUM_TICKS_PER_SECOND=160;const DEFAULT_TICKS_PER_SLOT=64;const NUM_SLOTS_PER_SECOND=NUM_TICKS_PER_SECOND/DEFAULT_TICKS_PER_SLOT;const MS_PER_SLOT=1e3/NUM_SLOTS_PER_SECOND;const SYSVAR_CLOCK_PUBKEY=new PublicKey("SysvarC1ock11111111111111111111111111111111");const SYSVAR_EPOCH_SCHEDULE_PUBKEY=new PublicKey("SysvarEpochSchedu1e111111111111111111111111");const SYSVAR_INSTRUCTIONS_PUBKEY=new PublicKey("Sysvar1nstructions1111111111111111111111111");const SYSVAR_RECENT_BLOCKHASHES_PUBKEY=new PublicKey("SysvarRecentB1ockHashes11111111111111111111");const SYSVAR_RENT_PUBKEY=new PublicKey("SysvarRent111111111111111111111111111111111");const SYSVAR_REWARDS_PUBKEY=new PublicKey("SysvarRewards111111111111111111111111111111");const SYSVAR_SLOT_HASHES_PUBKEY=new PublicKey("SysvarS1otHashes111111111111111111111111111");const SYSVAR_SLOT_HISTORY_PUBKEY=new PublicKey("SysvarS1otHistory11111111111111111111111111");const SYSVAR_STAKE_HISTORY_PUBKEY=new PublicKey("SysvarStakeHistory1111111111111111111111111");class SendTransactionError extends Error{constructor({action:action,signature:signature,transactionMessage:transactionMessage,logs:logs}){const maybeLogsOutput=logs?`Logs: \n${JSON.stringify(logs.slice(-10),null,2)}. `:"";const guideText="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let message;switch(action){case"send":message=`Transaction ${signature} resulted in an error. \n`+`${transactionMessage}. `+maybeLogsOutput+guideText;break;case"simulate":message=`Simulation failed. \nMessage: ${transactionMessage}. \n`+maybeLogsOutput+guideText;break;default:{message=`Unknown action '${(a=>a)(action)}'`}}super(message);this.signature=void 0;this.transactionMessage=void 0;this.transactionLogs=void 0;this.signature=signature;this.transactionMessage=transactionMessage;this.transactionLogs=logs?logs:undefined}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:undefined}}get logs(){const cachedLogs=this.transactionLogs;if(cachedLogs!=null&&typeof cachedLogs==="object"&&"then"in cachedLogs){return undefined}return cachedLogs}async getLogs(connection){if(!Array.isArray(this.transactionLogs)){this.transactionLogs=new Promise(((resolve,reject)=>{connection.getTransaction(this.signature).then((tx=>{if(tx&&tx.meta&&tx.meta.logMessages){const logs=tx.meta.logMessages;this.transactionLogs=logs;resolve(logs)}else{reject(new Error("Log messages not found"))}})).catch(reject)}))}return await this.transactionLogs}}const SolanaJSONRPCErrorCode={JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP:-32001,JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE:-32002,JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE:-32003,JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE:-32004,JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY:-32005,JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:-32006,JSON_RPC_SERVER_ERROR_SLOT_SKIPPED:-32007,JSON_RPC_SERVER_ERROR_NO_SNAPSHOT:-32008,JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:-32009,JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:-32010,JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE:-32011,JSON_RPC_SCAN_ERROR:-32012,JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH:-32013,JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:-32014,JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:-32015,JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED:-32016};class SolanaJSONRPCError extends Error{constructor({code:code,message:message,data:data},customMessage){super(customMessage!=null?`${customMessage}: ${message}`:message);this.code=void 0;this.data=void 0;this.code=code;this.data=data;this.name="SolanaJSONRPCError"}}async function sendAndConfirmTransaction(connection,transaction,signers,options){const sendOptions=options&&{skipPreflight:options.skipPreflight,preflightCommitment:options.preflightCommitment||options.commitment,maxRetries:options.maxRetries,minContextSlot:options.minContextSlot};const signature=await connection.sendTransaction(transaction,signers,sendOptions);let status;if(transaction.recentBlockhash!=null&&transaction.lastValidBlockHeight!=null){status=(await connection.confirmTransaction({abortSignal:options?.abortSignal,signature:signature,blockhash:transaction.recentBlockhash,lastValidBlockHeight:transaction.lastValidBlockHeight},options&&options.commitment)).value}else if(transaction.minNonceContextSlot!=null&&transaction.nonceInfo!=null){const{nonceInstruction:nonceInstruction}=transaction.nonceInfo;const nonceAccountPubkey=nonceInstruction.keys[0].pubkey;status=(await connection.confirmTransaction({abortSignal:options?.abortSignal,minContextSlot:transaction.minNonceContextSlot,nonceAccountPubkey:nonceAccountPubkey,nonceValue:transaction.nonceInfo.nonce,signature:signature},options&&options.commitment)).value}else{if(options?.abortSignal!=null){console.warn("sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was "+"supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` "+"or a combination of `nonceInfo` and `minNonceContextSlot` are abortable.")}status=(await connection.confirmTransaction(signature,options&&options.commitment)).value}if(status.err){if(signature!=null){throw new SendTransactionError({action:"send",signature:signature,transactionMessage:`Status: (${JSON.stringify(status)})`})}throw new Error(`Transaction ${signature} failed (${JSON.stringify(status)})`)}return signature}function sleep(ms){return new Promise((resolve=>setTimeout(resolve,ms)))}function encodeData(type,fields){const allocLength=type.layout.span>=0?type.layout.span:getAlloc(type,fields);const data=bufferExports.Buffer.alloc(allocLength);const layoutFields=Object.assign({instruction:type.index},fields);type.layout.encode(layoutFields,data);return data}function decodeData$1(type,buffer){let data;try{data=type.layout.decode(buffer)}catch(err){throw new Error("invalid instruction; "+err)}if(data.instruction!==type.index){throw new Error(`invalid instruction; instruction index mismatch ${data.instruction} != ${type.index}`)}return data}const FeeCalculatorLayout=LayoutExports.nu64("lamportsPerSignature");const NonceAccountLayout=LayoutExports.struct([LayoutExports.u32("version"),LayoutExports.u32("state"),publicKey("authorizedPubkey"),publicKey("nonce"),LayoutExports.struct([FeeCalculatorLayout],"feeCalculator")]);const NONCE_ACCOUNT_LENGTH=NonceAccountLayout.span;class NonceAccount{constructor(args){this.authorizedPubkey=void 0;this.nonce=void 0;this.feeCalculator=void 0;this.authorizedPubkey=args.authorizedPubkey;this.nonce=args.nonce;this.feeCalculator=args.feeCalculator}static fromAccountData(buffer){const nonceAccount=NonceAccountLayout.decode(toBuffer(buffer),0);return new NonceAccount({authorizedPubkey:new PublicKey(nonceAccount.authorizedPubkey),nonce:new PublicKey(nonceAccount.nonce).toString(),feeCalculator:nonceAccount.feeCalculator})}}var browser$1={};var hasRequiredBrowser$1;function requireBrowser$1(){if(hasRequiredBrowser$1)return browser$1;hasRequiredBrowser$1=1;Object.defineProperty(browser$1,"__esModule",{value:true});function toBigIntLE(buf){{const reversed=Buffer.from(buf);reversed.reverse();const hex=reversed.toString("hex");if(hex.length===0){return BigInt(0)}return BigInt(`0x${hex}`)}}browser$1.toBigIntLE=toBigIntLE;function toBigIntBE(buf){{const hex=buf.toString("hex");if(hex.length===0){return BigInt(0)}return BigInt(`0x${hex}`)}}browser$1.toBigIntBE=toBigIntBE;function toBufferLE(num,width){{const hex=num.toString(16);const buffer=Buffer.from(hex.padStart(width*2,"0").slice(0,width*2),"hex");buffer.reverse();return buffer}}browser$1.toBufferLE=toBufferLE;function toBufferBE(num,width){{const hex=num.toString(16);return Buffer.from(hex.padStart(width*2,"0").slice(0,width*2),"hex")}}browser$1.toBufferBE=toBufferBE;return browser$1}var browserExports$1=requireBrowser$1();const encodeDecode=layout=>{const decode=layout.decode.bind(layout);const encode=layout.encode.bind(layout);return{decode:decode,encode:encode}};const bigInt=length=>property=>{const layout=LayoutExports.blob(length,property);const{encode:encode,decode:decode}=encodeDecode(layout);const bigIntLayout=layout;bigIntLayout.decode=(buffer,offset)=>{const src=decode(buffer,offset);return browserExports$1.toBigIntLE(bufferExports.Buffer.from(src))};bigIntLayout.encode=(bigInt,buffer,offset)=>{const src=browserExports$1.toBufferLE(bigInt,length);return encode(src,buffer,offset)};return bigIntLayout};const u64=bigInt(8);class SystemInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const instructionTypeLayout=LayoutExports.u32("instruction");const typeIndex=instructionTypeLayout.decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(SYSTEM_INSTRUCTION_LAYOUTS)){if(layout.index==typeIndex){type=ixType;break}}if(!type){throw new Error("Instruction type incorrect; not a SystemInstruction")}return type}static decodeCreateAccount(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{lamports:lamports,space:space,programId:programId}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Create,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,newAccountPubkey:instruction.keys[1].pubkey,lamports:lamports,space:space,programId:new PublicKey(programId)}}static decodeTransfer(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{lamports:lamports}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Transfer,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,toPubkey:instruction.keys[1].pubkey,lamports:lamports}}static decodeTransferWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{lamports:lamports,seed:seed,programId:programId}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,basePubkey:instruction.keys[1].pubkey,toPubkey:instruction.keys[2].pubkey,lamports:lamports,seed:seed,programId:new PublicKey(programId)}}static decodeAllocate(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,1);const{space:space}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Allocate,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,space:space}}static decodeAllocateWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,1);const{base:base,seed:seed,space:space,programId:programId}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,basePubkey:new PublicKey(base),seed:seed,space:space,programId:new PublicKey(programId)}}static decodeAssign(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,1);const{programId:programId}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Assign,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,programId:new PublicKey(programId)}}static decodeAssignWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,1);const{base:base,seed:seed,programId:programId}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed,instruction.data);return{accountPubkey:instruction.keys[0].pubkey,basePubkey:new PublicKey(base),seed:seed,programId:new PublicKey(programId)}}static decodeCreateWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{base:base,seed:seed,lamports:lamports,space:space,programId:programId}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed,instruction.data);return{fromPubkey:instruction.keys[0].pubkey,newAccountPubkey:instruction.keys[1].pubkey,basePubkey:new PublicKey(base),seed:seed,lamports:lamports,space:space,programId:new PublicKey(programId)}}static decodeNonceInitialize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{authorized:authorized}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,authorizedPubkey:new PublicKey(authorized)}}static decodeNonceAdvance(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey}}static decodeNonceWithdraw(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,5);const{lamports:lamports}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,toPubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[4].pubkey,lamports:lamports}}static decodeNonceAuthorize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{authorized:authorized}=decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount,instruction.data);return{noncePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[1].pubkey,newAuthorizedPubkey:new PublicKey(authorized)}}static checkProgramId(programId){if(!programId.equals(SystemProgram.programId)){throw new Error("invalid instruction; programId is not SystemProgram")}}static checkKeyLength(keys,expectedLength){if(keys.length<expectedLength){throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`)}}}const SYSTEM_INSTRUCTION_LAYOUTS=Object.freeze({Create:{index:0,layout:LayoutExports.struct([LayoutExports.u32("instruction"),LayoutExports.ns64("lamports"),LayoutExports.ns64("space"),publicKey("programId")])},Assign:{index:1,layout:LayoutExports.struct([LayoutExports.u32("instruction"),publicKey("programId")])},Transfer:{index:2,layout:LayoutExports.struct([LayoutExports.u32("instruction"),u64("lamports")])},CreateWithSeed:{index:3,layout:LayoutExports.struct([LayoutExports.u32("instruction"),publicKey("base"),rustString("seed"),LayoutExports.ns64("lamports"),LayoutExports.ns64("space"),publicKey("programId")])},AdvanceNonceAccount:{index:4,layout:LayoutExports.struct([LayoutExports.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:LayoutExports.struct([LayoutExports.u32("instruction"),LayoutExports.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:LayoutExports.struct([LayoutExports.u32("instruction"),publicKey("authorized")])},AuthorizeNonceAccount:{index:7,layout:LayoutExports.struct([LayoutExports.u32("instruction"),publicKey("authorized")])},Allocate:{index:8,layout:LayoutExports.struct([LayoutExports.u32("instruction"),LayoutExports.ns64("space")])},AllocateWithSeed:{index:9,layout:LayoutExports.struct([LayoutExports.u32("instruction"),publicKey("base"),rustString("seed"),LayoutExports.ns64("space"),publicKey("programId")])},AssignWithSeed:{index:10,layout:LayoutExports.struct([LayoutExports.u32("instruction"),publicKey("base"),rustString("seed"),publicKey("programId")])},TransferWithSeed:{index:11,layout:LayoutExports.struct([LayoutExports.u32("instruction"),u64("lamports"),rustString("seed"),publicKey("programId")])},UpgradeNonceAccount:{index:12,layout:LayoutExports.struct([LayoutExports.u32("instruction")])}});class SystemProgram{constructor(){}static createAccount(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.Create;const data=encodeData(type,{lamports:params.lamports,space:params.space,programId:toBuffer(params.programId.toBuffer())});return new TransactionInstruction({keys:[{pubkey:params.fromPubkey,isSigner:true,isWritable:true},{pubkey:params.newAccountPubkey,isSigner:true,isWritable:true}],programId:this.programId,data:data})}static transfer(params){let data;let keys;if("basePubkey"in params){const type=SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;data=encodeData(type,{lamports:BigInt(params.lamports),seed:params.seed,programId:toBuffer(params.programId.toBuffer())});keys=[{pubkey:params.fromPubkey,isSigner:false,isWritable:true},{pubkey:params.basePubkey,isSigner:true,isWritable:false},{pubkey:params.toPubkey,isSigner:false,isWritable:true}]}else{const type=SYSTEM_INSTRUCTION_LAYOUTS.Transfer;data=encodeData(type,{lamports:BigInt(params.lamports)});keys=[{pubkey:params.fromPubkey,isSigner:true,isWritable:true},{pubkey:params.toPubkey,isSigner:false,isWritable:true}]}return new TransactionInstruction({keys:keys,programId:this.programId,data:data})}static assign(params){let data;let keys;if("basePubkey"in params){const type=SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed;data=encodeData(type,{base:toBuffer(params.basePubkey.toBuffer()),seed:params.seed,programId:toBuffer(params.programId.toBuffer())});keys=[{pubkey:params.accountPubkey,isSigner:false,isWritable:true},{pubkey:params.basePubkey,isSigner:true,isWritable:false}]}else{const type=SYSTEM_INSTRUCTION_LAYOUTS.Assign;data=encodeData(type,{programId:toBuffer(params.programId.toBuffer())});keys=[{pubkey:params.accountPubkey,isSigner:true,isWritable:true}]}return new TransactionInstruction({keys:keys,programId:this.programId,data:data})}static createAccountWithSeed(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed;const data=encodeData(type,{base:toBuffer(params.basePubkey.toBuffer()),seed:params.seed,lamports:params.lamports,space:params.space,programId:toBuffer(params.programId.toBuffer())});let keys=[{pubkey:params.fromPubkey,isSigner:true,isWritable:true},{pubkey:params.newAccountPubkey,isSigner:false,isWritable:true}];if(!params.basePubkey.equals(params.fromPubkey)){keys.push({pubkey:params.basePubkey,isSigner:true,isWritable:false})}return new TransactionInstruction({keys:keys,programId:this.programId,data:data})}static createNonceAccount(params){const transaction=new Transaction;if("basePubkey"in params&&"seed"in params){transaction.add(SystemProgram.createAccountWithSeed({fromPubkey:params.fromPubkey,newAccountPubkey:params.noncePubkey,basePubkey:params.basePubkey,seed:params.seed,lamports:params.lamports,space:NONCE_ACCOUNT_LENGTH,programId:this.programId}))}else{transaction.add(SystemProgram.createAccount({fromPubkey:params.fromPubkey,newAccountPubkey:params.noncePubkey,lamports:params.lamports,space:NONCE_ACCOUNT_LENGTH,programId:this.programId}))}const initParams={noncePubkey:params.noncePubkey,authorizedPubkey:params.authorizedPubkey};transaction.add(this.nonceInitialize(initParams));return transaction}static nonceInitialize(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount;const data=encodeData(type,{authorized:toBuffer(params.authorizedPubkey.toBuffer())});const instructionData={keys:[{pubkey:params.noncePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RECENT_BLOCKHASHES_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false}],programId:this.programId,data:data};return new TransactionInstruction(instructionData)}static nonceAdvance(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount;const data=encodeData(type);const instructionData={keys:[{pubkey:params.noncePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RECENT_BLOCKHASHES_PUBKEY,isSigner:false,isWritable:false},{pubkey:params.authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data};return new TransactionInstruction(instructionData)}static nonceWithdraw(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount;const data=encodeData(type,{lamports:params.lamports});return new TransactionInstruction({keys:[{pubkey:params.noncePubkey,isSigner:false,isWritable:true},{pubkey:params.toPubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RECENT_BLOCKHASHES_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false},{pubkey:params.authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static nonceAuthorize(params){const type=SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount;const data=encodeData(type,{authorized:toBuffer(params.newAuthorizedPubkey.toBuffer())});return new TransactionInstruction({keys:[{pubkey:params.noncePubkey,isSigner:false,isWritable:true},{pubkey:params.authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static allocate(params){let data;let keys;if("basePubkey"in params){const type=SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;data=encodeData(type,{base:toBuffer(params.basePubkey.toBuffer()),seed:params.seed,space:params.space,programId:toBuffer(params.programId.toBuffer())});keys=[{pubkey:params.accountPubkey,isSigner:false,isWritable:true},{pubkey:params.basePubkey,isSigner:true,isWritable:false}]}else{const type=SYSTEM_INSTRUCTION_LAYOUTS.Allocate;data=encodeData(type,{space:params.space});keys=[{pubkey:params.accountPubkey,isSigner:true,isWritable:true}]}return new TransactionInstruction({keys:keys,programId:this.programId,data:data})}}SystemProgram.programId=new PublicKey("11111111111111111111111111111111");const CHUNK_SIZE=PACKET_DATA_SIZE-300;class Loader{constructor(){}static getMinNumSignatures(dataLength){return 2*(Math.ceil(dataLength/Loader.chunkSize)+1+1)}static async load(connection,payer,program,programId,data){{const balanceNeeded=await connection.getMinimumBalanceForRentExemption(data.length);const programInfo=await connection.getAccountInfo(program.publicKey,"confirmed");let transaction=null;if(programInfo!==null){if(programInfo.executable){console.error("Program load failed, account is already executable");return false}if(programInfo.data.length!==data.length){transaction=transaction||new Transaction;transaction.add(SystemProgram.allocate({accountPubkey:program.publicKey,space:data.length}))}if(!programInfo.owner.equals(programId)){transaction=transaction||new Transaction;transaction.add(SystemProgram.assign({accountPubkey:program.publicKey,programId:programId}))}if(programInfo.lamports<balanceNeeded){transaction=transaction||new Transaction;transaction.add(SystemProgram.transfer({fromPubkey:payer.publicKey,toPubkey:program.publicKey,lamports:balanceNeeded-programInfo.lamports}))}}else{transaction=(new Transaction).add(SystemProgram.createAccount({fromPubkey:payer.publicKey,newAccountPubkey:program.publicKey,lamports:balanceNeeded>0?balanceNeeded:1,space:data.length,programId:programId}))}if(transaction!==null){await sendAndConfirmTransaction(connection,transaction,[payer,program],{commitment:"confirmed"})}}const dataLayout=LayoutExports.struct([LayoutExports.u32("instruction"),LayoutExports.u32("offset"),LayoutExports.u32("bytesLength"),LayoutExports.u32("bytesLengthPadding"),LayoutExports.seq(LayoutExports.u8("byte"),LayoutExports.offset(LayoutExports.u32(),-8),"bytes")]);const chunkSize=Loader.chunkSize;let offset=0;let array=data;let transactions=[];while(array.length>0){const bytes=array.slice(0,chunkSize);const data=bufferExports.Buffer.alloc(chunkSize+16);dataLayout.encode({instruction:0,offset:offset,bytes:bytes,bytesLength:0,bytesLengthPadding:0},data);const transaction=(new Transaction).add({keys:[{pubkey:program.publicKey,isSigner:true,isWritable:true}],programId:programId,data:data});transactions.push(sendAndConfirmTransaction(connection,transaction,[payer,program],{commitment:"confirmed"}));if(connection._rpcEndpoint.includes("solana.com")){const REQUESTS_PER_SECOND=4;await sleep(1e3/REQUESTS_PER_SECOND)}offset+=chunkSize;array=array.slice(chunkSize)}await Promise.all(transactions);{const dataLayout=LayoutExports.struct([LayoutExports.u32("instruction")]);const data=bufferExports.Buffer.alloc(dataLayout.span);dataLayout.encode({instruction:1},data);const transaction=(new Transaction).add({keys:[{pubkey:program.publicKey,isSigner:true,isWritable:true},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false}],programId:programId,data:data});const deployCommitment="processed";const finalizeSignature=await connection.sendTransaction(transaction,[payer,program],{preflightCommitment:deployCommitment});const{context:context,value:value}=await connection.confirmTransaction({signature:finalizeSignature,lastValidBlockHeight:transaction.lastValidBlockHeight,blockhash:transaction.recentBlockhash},deployCommitment);if(value.err){throw new Error(`Transaction ${finalizeSignature} failed (${JSON.stringify(value)})`)}while(true){try{const currentSlot=await connection.getSlot({commitment:deployCommitment});if(currentSlot>context.slot){break}}catch{}await new Promise((resolve=>setTimeout(resolve,Math.round(MS_PER_SLOT/2))))}}return true}}Loader.chunkSize=CHUNK_SIZE;const BPF_LOADER_PROGRAM_ID=new PublicKey("BPFLoader2111111111111111111111111111111111");class BpfLoader{static getMinNumSignatures(dataLength){return Loader.getMinNumSignatures(dataLength)}static load(connection,payer,program,elf,loaderProgramId){return Loader.load(connection,payer,program,loaderProgramId,elf)}}var fastStableStringify$1;var hasRequiredFastStableStringify;function requireFastStableStringify(){if(hasRequiredFastStableStringify)return fastStableStringify$1;hasRequiredFastStableStringify=1;var objToString=Object.prototype.toString;var objKeys=Object.keys||function(obj){var keys=[];for(var name in obj){keys.push(name)}return keys};function stringify(val,isArrayProp){var i,max,str,keys,key,propVal,toStr;if(val===true){return"true"}if(val===false){return"false"}switch(typeof val){case"object":if(val===null){return null}else if(val.toJSON&&typeof val.toJSON==="function"){return stringify(val.toJSON(),isArrayProp)}else{toStr=objToString.call(val);if(toStr==="[object Array]"){str="[";max=val.length-1;for(i=0;i<max;i++){str+=stringify(val[i],true)+","}if(max>-1){str+=stringify(val[i],true)}return str+"]"}else if(toStr==="[object Object]"){keys=objKeys(val).sort();max=keys.length;str="";i=0;while(i<max){key=keys[i];propVal=stringify(val[key],false);if(propVal!==undefined){if(str){str+=","}str+=JSON.stringify(key)+":"+propVal}i++}return"{"+str+"}"}else{return JSON.stringify(val)}}case"function":case"undefined":return isArrayProp?null:undefined;case"string":return JSON.stringify(val);default:return isFinite(val)?val:null}}fastStableStringify$1=function(val){var returnVal=stringify(val,false);if(returnVal!==undefined){return""+returnVal}};return fastStableStringify$1}var fastStableStringifyExports=requireFastStableStringify();var fastStableStringify=getDefaultExportFromCjs(fastStableStringifyExports);class StructError extends TypeError{constructor(failure,failures){let cached;const{message:message,explanation:explanation,...rest}=failure;const{path:path}=failure;const msg=path.length===0?message:`At path: ${path.join(".")} -- ${message}`;super(explanation??msg);if(explanation!=null)this.cause=msg;Object.assign(this,rest);this.name=this.constructor.name;this.failures=()=>cached??(cached=[failure,...failures()])}}function isIterable(x){return isObject(x)&&typeof x[Symbol.iterator]==="function"}function isObject(x){return typeof x==="object"&&x!=null}function isNonArrayObject(x){return isObject(x)&&!Array.isArray(x)}function print(value){if(typeof value==="symbol"){return value.toString()}return typeof value==="string"?JSON.stringify(value):`${value}`}function shiftIterator(input){const{done:done,value:value}=input.next();return done?undefined:value}function toFailure(result,context,struct,value){if(result===true){return}else if(result===false){result={}}else if(typeof result==="string"){result={message:result}}const{path:path,branch:branch}=context;const{type:type}=struct;const{refinement:refinement,message:message=`Expected a value of type \`${type}\`${refinement?` with refinement \`${refinement}\``:""}, but received: \`${print(value)}\``}=result;return{value:value,type:type,refinement:refinement,key:path[path.length-1],path:path,branch:branch,...result,message:message}}function*toFailures(result,context,struct,value){if(!isIterable(result)){result=[result]}for(const r of result){const failure=toFailure(r,context,struct,value);if(failure){yield failure}}}function*run(value,struct,options={}){const{path:path=[],branch:branch=[value],coerce:coerce=false,mask:mask=false}=options;const ctx={path:path,branch:branch,mask:mask};if(coerce){value=struct.coercer(value,ctx)}let status="valid";for(const failure of struct.validator(value,ctx)){failure.explanation=options.message;status="not_valid";yield[failure,undefined]}for(let[k,v,s]of struct.entries(value,ctx)){const ts=run(v,s,{path:k===undefined?path:[...path,k],branch:k===undefined?branch:[...branch,v],coerce:coerce,mask:mask,message:options.message});for(const t of ts){if(t[0]){status=t[0].refinement!=null?"not_refined":"not_valid";yield[t[0],undefined]}else if(coerce){v=t[1];if(k===undefined){value=v}else if(value instanceof Map){value.set(k,v)}else if(value instanceof Set){value.add(v)}else if(isObject(value)){if(v!==undefined||k in value)value[k]=v}}}}if(status!=="not_valid"){for(const failure of struct.refiner(value,ctx)){failure.explanation=options.message;status="not_refined";yield[failure,undefined]}}if(status==="valid"){yield[undefined,value]}}class Struct{constructor(props){const{type:type,schema:schema,validator:validator,refiner:refiner,coercer:coercer=(value=>value),entries:entries=function*(){}}=props;this.type=type;this.schema=schema;this.entries=entries;this.coercer=coercer;if(validator){this.validator=(value,context)=>{const result=validator(value,context);return toFailures(result,context,this,value)}}else{this.validator=()=>[]}if(refiner){this.refiner=(value,context)=>{const result=refiner(value,context);return toFailures(result,context,this,value)}}else{this.refiner=()=>[]}}assert(value,message){return assert(value,this,message)}create(value,message){return create(value,this,message)}is(value){return is(value,this)}mask(value,message){return mask(value,this,message)}validate(value,options={}){return validate$1(value,this,options)}}function assert(value,struct,message){const result=validate$1(value,struct,{message:message});if(result[0]){throw result[0]}}function create(value,struct,message){const result=validate$1(value,struct,{coerce:true,message:message});if(result[0]){throw result[0]}else{return result[1]}}function mask(value,struct,message){const result=validate$1(value,struct,{coerce:true,mask:true,message:message});if(result[0]){throw result[0]}else{return result[1]}}function is(value,struct){const result=validate$1(value,struct);return!result[0]}function validate$1(value,struct,options={}){const tuples=run(value,struct,options);const tuple=shiftIterator(tuples);if(tuple[0]){const error=new StructError(tuple[0],(function*(){for(const t of tuples){if(t[0]){yield t[0]}}}));return[error,undefined]}else{const v=tuple[1];return[undefined,v]}}function define(name,validator){return new Struct({type:name,schema:null,validator:validator})}function any(){return define("any",(()=>true))}function array(Element){return new Struct({type:"array",schema:Element,*entries(value){if(Element&&Array.isArray(value)){for(const[i,v]of value.entries()){yield[i,v,Element]}}},coercer(value){return Array.isArray(value)?value.slice():value},validator(value){return Array.isArray(value)||`Expected an array value, but received: ${print(value)}`}})}function boolean(){return define("boolean",(value=>typeof value==="boolean"))}function instance(Class){return define("instance",(value=>value instanceof Class||`Expected a \`${Class.name}\` instance, but received: ${print(value)}`))}function literal(constant){const description=print(constant);const t=typeof constant;return new Struct({type:"literal",schema:t==="string"||t==="number"||t==="boolean"?constant:null,validator(value){return value===constant||`Expected the literal \`${description}\`, but received: ${print(value)}`}})}function never(){return define("never",(()=>false))}function nullable(struct){return new Struct({...struct,validator:(value,ctx)=>value===null||struct.validator(value,ctx),refiner:(value,ctx)=>value===null||struct.refiner(value,ctx)})}function number(){return define("number",(value=>typeof value==="number"&&!isNaN(value)||`Expected a number, but received: ${print(value)}`))}function optional(struct){return new Struct({...struct,validator:(value,ctx)=>value===undefined||struct.validator(value,ctx),refiner:(value,ctx)=>value===undefined||struct.refiner(value,ctx)})}function record(Key,Value){return new Struct({type:"record",schema:null,*entries(value){if(isObject(value)){for(const k in value){const v=value[k];yield[k,k,Key];yield[k,v,Value]}}},validator(value){return isNonArrayObject(value)||`Expected an object, but received: ${print(value)}`},coercer(value){return isNonArrayObject(value)?{...value}:value}})}function string(){return define("string",(value=>typeof value==="string"||`Expected a string, but received: ${print(value)}`))}function tuple(Structs){const Never=never();return new Struct({type:"tuple",schema:null,*entries(value){if(Array.isArray(value)){const length=Math.max(Structs.length,value.length);for(let i=0;i<length;i++){yield[i,value[i],Structs[i]||Never]}}},validator(value){return Array.isArray(value)||`Expected an array, but received: ${print(value)}`},coercer(value){return Array.isArray(value)?value.slice():value}})}function type(schema){const keys=Object.keys(schema);return new Struct({type:"type",schema:schema,*entries(value){if(isObject(value)){for(const k of keys){yield[k,value[k],schema[k]]}}},validator(value){return isNonArrayObject(value)||`Expected an object, but received: ${print(value)}`},coercer(value){return isNonArrayObject(value)?{...value}:value}})}function union(Structs){const description=Structs.map((s=>s.type)).join(" | ");return new Struct({type:"union",schema:null,coercer(value,ctx){for(const S of Structs){const[error,coerced]=S.validate(value,{coerce:true,mask:ctx.mask});if(!error){return coerced}}return value},validator(value,ctx){const failures=[];for(const S of Structs){const[...tuples]=run(value,S,ctx);const[first]=tuples;if(!first[0]){return[]}else{for(const[failure]of tuples){if(failure){failures.push(failure)}}}}return[`Expected the value to satisfy a union of \`${description}\`, but received: ${print(value)}`,...failures]}})}function unknown(){return define("unknown",(()=>true))}function coerce(struct,condition,coercer){return new Struct({...struct,coercer:(value,ctx)=>is(value,condition)?struct.coercer(coercer(value,ctx),ctx):struct.coercer(value,ctx)})}var getRandomValues;var rnds8=new Uint8Array(16);function rng(){if(!getRandomValues){getRandomValues=typeof crypto!=="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!=="undefined"&&typeof msCrypto.getRandomValues==="function"&&msCrypto.getRandomValues.bind(msCrypto);if(!getRandomValues){throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported")}}return getRandomValues(rnds8)}var REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function validate(uuid){return typeof uuid==="string"&®EX.test(uuid)}var byteToHex=[];for(var i=0;i<256;++i){byteToHex.push((i+256).toString(16).substr(1))}function stringify(arr){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var uuid=(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase();if(!validate(uuid)){throw TypeError("Stringified UUID is invalid")}return uuid}var _nodeId;var _clockseq;var _lastMSecs=0;var _lastNSecs=0;function v1(options,buf,offset){var i=buf&&offset||0;var b=buf||new Array(16);options=options||{};var node=options.node||_nodeId;var clockseq=options.clockseq!==undefined?options.clockseq:_clockseq;if(node==null||clockseq==null){var seedBytes=options.random||(options.rng||rng)();if(node==null){node=_nodeId=[seedBytes[0]|1,seedBytes[1],seedBytes[2],seedBytes[3],seedBytes[4],seedBytes[5]]}if(clockseq==null){clockseq=_clockseq=(seedBytes[6]<<8|seedBytes[7])&16383}}var msecs=options.msecs!==undefined?options.msecs:Date.now();var nsecs=options.nsecs!==undefined?options.nsecs:_lastNSecs+1;var dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/1e4;if(dt<0&&options.clockseq===undefined){clockseq=clockseq+1&16383}if((dt<0||msecs>_lastMSecs)&&options.nsecs===undefined){nsecs=0}if(nsecs>=1e4){throw new Error("uuid.v1(): Can't create more than 10M uuids/sec")}_lastMSecs=msecs;_lastNSecs=nsecs;_clockseq=clockseq;msecs+=122192928e5;var tl=((msecs&268435455)*1e4+nsecs)%4294967296;b[i++]=tl>>>24&255;b[i++]=tl>>>16&255;b[i++]=tl>>>8&255;b[i++]=tl&255;var tmh=msecs/4294967296*1e4&268435455;b[i++]=tmh>>>8&255;b[i++]=tmh&255;b[i++]=tmh>>>24&15|16;b[i++]=tmh>>>16&255;b[i++]=clockseq>>>8|128;b[i++]=clockseq&255;for(var n=0;n<6;++n){b[i+n]=node[n]}return buf||stringify(b)}function parse(uuid){if(!validate(uuid)){throw TypeError("Invalid UUID")}var v;var arr=new Uint8Array(16);arr[0]=(v=parseInt(uuid.slice(0,8),16))>>>24;arr[1]=v>>>16&255;arr[2]=v>>>8&255;arr[3]=v&255;arr[4]=(v=parseInt(uuid.slice(9,13),16))>>>8;arr[5]=v&255;arr[6]=(v=parseInt(uuid.slice(14,18),16))>>>8;arr[7]=v&255;arr[8]=(v=parseInt(uuid.slice(19,23),16))>>>8;arr[9]=v&255;arr[10]=(v=parseInt(uuid.slice(24,36),16))/1099511627776&255;arr[11]=v/4294967296&255;arr[12]=v>>>24&255;arr[13]=v>>>16&255;arr[14]=v>>>8&255;arr[15]=v&255;return arr}function stringToBytes(str){str=unescape(encodeURIComponent(str));var bytes=[];for(var i=0;i<str.length;++i){bytes.push(str.charCodeAt(i))}return bytes}var DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8";var URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function v35(name,version,hashfunc){function generateUUID(value,namespace,buf,offset){if(typeof value==="string"){value=stringToBytes(value)}if(typeof namespace==="string"){namespace=parse(namespace)}if(namespace.length!==16){throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)")}var bytes=new Uint8Array(16+value.length);bytes.set(namespace);bytes.set(value,namespace.length);bytes=hashfunc(bytes);bytes[6]=bytes[6]&15|version;bytes[8]=bytes[8]&63|128;if(buf){offset=offset||0;for(var i=0;i<16;++i){buf[offset+i]=bytes[i]}return buf}return stringify(bytes)}try{generateUUID.name=name}catch(err){}generateUUID.DNS=DNS;generateUUID.URL=URL;return generateUUID}function md5(bytes){if(typeof bytes==="string"){var msg=unescape(encodeURIComponent(bytes));bytes=new Uint8Array(msg.length);for(var i=0;i<msg.length;++i){bytes[i]=msg.charCodeAt(i)}}return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes),bytes.length*8))}function md5ToHexEncodedArray(input){var output=[];var length32=input.length*32;var hexTab="0123456789abcdef";for(var i=0;i<length32;i+=8){var x=input[i>>5]>>>i%32&255;var hex=parseInt(hexTab.charAt(x>>>4&15)+hexTab.charAt(x&15),16);output.push(hex)}return output}function getOutputLength(inputLength8){return(inputLength8+64>>>9<<4)+14+1}function wordsToMd5(x,len){x[len>>5]|=128<<len%32;x[getOutputLength(len)-1]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i<x.length;i+=16){var olda=a;var oldb=b;var oldc=c;var oldd=d;a=md5ff(a,b,c,d,x[i],7,-680876936);d=md5ff(d,a,b,c,x[i+1],12,-389564586);c=md5ff(c,d,a,b,x[i+2],17,606105819);b=md5ff(b,c,d,a,x[i+3],22,-1044525330);a=md5ff(a,b,c,d,x[i+4],7,-176418897);d=md5ff(d,a,b,c,x[i+5],12,1200080426);c=md5ff(c,d,a,b,x[i+6],17,-1473231341);b=md5ff(b,c,d,a,x[i+7],22,-45705983);a=md5ff(a,b,c,d,x[i+8],7,1770035416);d=md5ff(d,a,b,c,x[i+9],12,-1958414417);c=md5ff(c,d,a,b,x[i+10],17,-42063);b=md5ff(b,c,d,a,x[i+11],22,-1990404162);a=md5ff(a,b,c,d,x[i+12],7,1804603682);d=md5ff(d,a,b,c,x[i+13],12,-40341101);c=md5ff(c,d,a,b,x[i+14],17,-1502002290);b=md5ff(b,c,d,a,x[i+15],22,1236535329);a=md5gg(a,b,c,d,x[i+1],5,-165796510);d=md5gg(d,a,b,c,x[i+6],9,-1069501632);c=md5gg(c,d,a,b,x[i+11],14,643717713);b=md5gg(b,c,d,a,x[i],20,-373897302);a=md5gg(a,b,c,d,x[i+5],5,-701558691);d=md5gg(d,a,b,c,x[i+10],9,38016083);c=md5gg(c,d,a,b,x[i+15],14,-660478335);b=md5gg(b,c,d,a,x[i+4],20,-405537848);a=md5gg(a,b,c,d,x[i+9],5,568446438);d=md5gg(d,a,b,c,x[i+14],9,-1019803690);c=md5gg(c,d,a,b,x[i+3],14,-187363961);b=md5gg(b,c,d,a,x[i+8],20,1163531501);a=md5gg(a,b,c,d,x[i+13],5,-1444681467);d=md5gg(d,a,b,c,x[i+2],9,-51403784);c=md5gg(c,d,a,b,x[i+7],14,1735328473);b=md5gg(b,c,d,a,x[i+12],20,-1926607734);a=md5hh(a,b,c,d,x[i+5],4,-378558);d=md5hh(d,a,b,c,x[i+8],11,-2022574463);c=md5hh(c,d,a,b,x[i+11],16,1839030562);b=md5hh(b,c,d,a,x[i+14],23,-35309556);a=md5hh(a,b,c,d,x[i+1],4,-1530992060);d=md5hh(d,a,b,c,x[i+4],11,1272893353);c=md5hh(c,d,a,b,x[i+7],16,-155497632);b=md5hh(b,c,d,a,x[i+10],23,-1094730640);a=md5hh(a,b,c,d,x[i+13],4,681279174);d=md5hh(d,a,b,c,x[i],11,-358537222);c=md5hh(c,d,a,b,x[i+3],16,-722521979);b=md5hh(b,c,d,a,x[i+6],23,76029189);a=md5hh(a,b,c,d,x[i+9],4,-640364487);d=md5hh(d,a,b,c,x[i+12],11,-421815835);c=md5hh(c,d,a,b,x[i+15],16,530742520);b=md5hh(b,c,d,a,x[i+2],23,-995338651);a=md5ii(a,b,c,d,x[i],6,-198630844);d=md5ii(d,a,b,c,x[i+7],10,1126891415);c=md5ii(c,d,a,b,x[i+14],15,-1416354905);b=md5ii(b,c,d,a,x[i+5],21,-57434055);a=md5ii(a,b,c,d,x[i+12],6,1700485571);d=md5ii(d,a,b,c,x[i+3],10,-1894986606);c=md5ii(c,d,a,b,x[i+10],15,-1051523);b=md5ii(b,c,d,a,x[i+1],21,-2054922799);a=md5ii(a,b,c,d,x[i+8],6,1873313359);d=md5ii(d,a,b,c,x[i+15],10,-30611744);c=md5ii(c,d,a,b,x[i+6],15,-1560198380);b=md5ii(b,c,d,a,x[i+13],21,1309151649);a=md5ii(a,b,c,d,x[i+4],6,-145523070);d=md5ii(d,a,b,c,x[i+11],10,-1120210379);c=md5ii(c,d,a,b,x[i+2],15,718787259);b=md5ii(b,c,d,a,x[i+9],21,-343485551);a=safeAdd(a,olda);b=safeAdd(b,oldb);c=safeAdd(c,oldc);d=safeAdd(d,oldd)}return[a,b,c,d]}function bytesToWords(input){if(input.length===0){return[]}var length8=input.length*8;var output=new Uint32Array(getOutputLength(length8));for(var i=0;i<length8;i+=8){output[i>>5]|=(input[i/8]&255)<<i%32}return output}function safeAdd(x,y){var lsw=(x&65535)+(y&65535);var msw=(x>>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bitRotateLeft(num,cnt){return num<<cnt|num>>>32-cnt}function md5cmn(q,a,b,x,s,t){return safeAdd(bitRotateLeft(safeAdd(safeAdd(a,q),safeAdd(x,t)),s),b)}function md5ff(a,b,c,d,x,s,t){return md5cmn(b&c|~b&d,a,b,x,s,t)}function md5gg(a,b,c,d,x,s,t){return md5cmn(b&d|c&~d,a,b,x,s,t)}function md5hh(a,b,c,d,x,s,t){return md5cmn(b^c^d,a,b,x,s,t)}function md5ii(a,b,c,d,x,s,t){return md5cmn(c^(b|~d),a,b,x,s,t)}var v3=v35("v3",48,md5);function v4(options,buf,offset){options=options||{};var rnds=options.random||(options.rng||rng)();rnds[6]=rnds[6]&15|64;rnds[8]=rnds[8]&63|128;if(buf){offset=offset||0;for(var i=0;i<16;++i){buf[offset+i]=rnds[i]}return buf}return stringify(rnds)}function f(s,x,y,z){switch(s){case 0:return x&y^~x&z;case 1:return x^y^z;case 2:return x&y^x&z^y&z;case 3:return x^y^z}}function ROTL(x,n){return x<<n|x>>>32-n}function sha1(bytes){var K=[1518500249,1859775393,2400959708,3395469782];var H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof bytes==="string"){var msg=unescape(encodeURIComponent(bytes));bytes=[];for(var i=0;i<msg.length;++i){bytes.push(msg.charCodeAt(i))}}else if(!Array.isArray(bytes)){bytes=Array.prototype.slice.call(bytes)}bytes.push(128);var l=bytes.length/4+2;var N=Math.ceil(l/16);var M=new Array(N);for(var _i=0;_i<N;++_i){var arr=new Uint32Array(16);for(var j=0;j<16;++j){arr[j]=bytes[_i*64+j*4]<<24|bytes[_i*64+j*4+1]<<16|bytes[_i*64+j*4+2]<<8|bytes[_i*64+j*4+3]}M[_i]=arr}M[N-1][14]=(bytes.length-1)*8/Math.pow(2,32);M[N-1][14]=Math.floor(M[N-1][14]);M[N-1][15]=(bytes.length-1)*8&4294967295;for(var _i2=0;_i2<N;++_i2){var W=new Uint32Array(80);for(var t=0;t<16;++t){W[t]=M[_i2][t]}for(var _t=16;_t<80;++_t){W[_t]=ROTL(W[_t-3]^W[_t-8]^W[_t-14]^W[_t-16],1)}var a=H[0];var b=H[1];var c=H[2];var d=H[3];var e=H[4];for(var _t2=0;_t2<80;++_t2){var s=Math.floor(_t2/20);var T=ROTL(a,5)+f(s,b,c,d)+e+K[s]+W[_t2]>>>0;e=d;d=c;c=ROTL(b,30)>>>0;b=a;a=T}H[0]=H[0]+a>>>0;H[1]=H[1]+b>>>0;H[2]=H[2]+c>>>0;H[3]=H[3]+d>>>0;H[4]=H[4]+e>>>0}return[H[0]>>24&255,H[0]>>16&255,H[0]>>8&255,H[0]&255,H[1]>>24&255,H[1]>>16&255,H[1]>>8&255,H[1]&255,H[2]>>24&255,H[2]>>16&255,H[2]>>8&255,H[2]&255,H[3]>>24&255,H[3]>>16&255,H[3]>>8&255,H[3]&255,H[4]>>24&255,H[4]>>16&255,H[4]>>8&255,H[4]&255]}var v5=v35("v5",80,sha1);var nil="00000000-0000-0000-0000-000000000000";function version(uuid){if(!validate(uuid)){throw TypeError("Invalid UUID")}return parseInt(uuid.substr(14,1),16)}var esmBrowser=Object.freeze({__proto__:null,NIL:nil,parse:parse,stringify:stringify,v1:v1,v3:v3,v4:v4,v5:v5,validate:validate,version:version});var require$$0=getAugmentedNamespace(esmBrowser);var generateRequest_1;var hasRequiredGenerateRequest;function requireGenerateRequest(){if(hasRequiredGenerateRequest)return generateRequest_1;hasRequiredGenerateRequest=1;const uuid=require$$0.v4;const generateRequest=function(method,params,id,options){if(typeof method!=="string"){throw new TypeError(method+" must be a string")}options=options||{};const version=typeof options.version==="number"?options.version:2;if(version!==1&&version!==2){throw new TypeError(version+" must be 1 or 2")}const request={method:method};if(version===2){request.jsonrpc="2.0"}if(params){if(typeof params!=="object"&&!Array.isArray(params)){throw new TypeError(params+" must be an object, array or omitted")}request.params=params}if(typeof id==="undefined"){const generator=typeof options.generator==="function"?options.generator:function(){return uuid()};request.id=generator(request,options)}else if(version===2&&id===null){if(options.notificationIdNull){request.id=null}}else{request.id=id}return request};generateRequest_1=generateRequest;return generateRequest_1}var browser;var hasRequiredBrowser;function requireBrowser(){if(hasRequiredBrowser)return browser;hasRequiredBrowser=1;const uuid=require$$0.v4;const generateRequest=requireGenerateRequest();const ClientBrowser=function(callServer,options){if(!(this instanceof ClientBrowser)){return new ClientBrowser(callServer,options)}if(!options){options={}}this.options={reviver:typeof options.reviver!=="undefined"?options.reviver:null,replacer:typeof options.replacer!=="undefined"?options.replacer:null,generator:typeof options.generator!=="undefined"?options.generator:function(){return uuid()},version:typeof options.version!=="undefined"?options.version:2,notificationIdNull:typeof options.notificationIdNull==="boolean"?options.notificationIdNull:false};this.callServer=callServer};browser=ClientBrowser;ClientBrowser.prototype.request=function(method,params,id,callback){const self=this;let request=null;const isBatch=Array.isArray(method)&&typeof params==="function";if(this.options.version===1&&isBatch){throw new TypeError("JSON-RPC 1.0 does not support batching")}const isRaw=!isBatch&&method&&typeof method==="object"&&typeof params==="function";if(isBatch||isRaw){callback=params;request=method}else{if(typeof id==="function"){callback=id;id=undefined}const hasCallback=typeof callback==="function";try{request=generateRequest(method,params,id,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(err){if(hasCallback){return callback(err)}throw err}if(!hasCallback){return request}}let message;try{message=JSON.stringify(request,this.options.replacer)}catch(err){return callback(err)}this.callServer(message,(function(err,response){self._parseResponse(err,response,callback)}));return request};ClientBrowser.prototype._parseResponse=function(err,responseText,callback){if(err){callback(err);return}if(!responseText){return callback()}let response;try{response=JSON.parse(responseText,this.options.reviver)}catch(err){return callback(err)}if(callback.length===3){if(Array.isArray(response)){const isError=function(res){return typeof res.error!=="undefined"};const isNotError=function(res){return!isError(res)};return callback(null,response.filter(isError),response.filter(isNotError))}else{return callback(null,response.error,response.result)}}callback(null,response)};return browser}var browserExports=requireBrowser();var RpcClient=getDefaultExportFromCjs(browserExports);const MINIMUM_SLOT_PER_EPOCH=32;function trailingZeros(n){let trailingZeros=0;while(n>1){n/=2;trailingZeros++}return trailingZeros}function nextPowerOfTwo(n){if(n===0)return 1;n--;n|=n>>1;n|=n>>2;n|=n>>4;n|=n>>8;n|=n>>16;n|=n>>32;return n+1}class EpochSchedule{constructor(slotsPerEpoch,leaderScheduleSlotOffset,warmup,firstNormalEpoch,firstNormalSlot){this.slotsPerEpoch=void 0;this.leaderScheduleSlotOffset=void 0;this.warmup=void 0;this.firstNormalEpoch=void 0;this.firstNormalSlot=void 0;this.slotsPerEpoch=slotsPerEpoch;this.leaderScheduleSlotOffset=leaderScheduleSlotOffset;this.warmup=warmup;this.firstNormalEpoch=firstNormalEpoch;this.firstNormalSlot=firstNormalSlot}getEpoch(slot){return this.getEpochAndSlotIndex(slot)[0]}getEpochAndSlotIndex(slot){if(slot<this.firstNormalSlot){const epoch=trailingZeros(nextPowerOfTwo(slot+MINIMUM_SLOT_PER_EPOCH+1))-trailingZeros(MINIMUM_SLOT_PER_EPOCH)-1;const epochLen=this.getSlotsInEpoch(epoch);const slotIndex=slot-(epochLen-MINIMUM_SLOT_PER_EPOCH);return[epoch,slotIndex]}else{const normalSlotIndex=slot-this.firstNormalSlot;const normalEpochIndex=Math.floor(normalSlotIndex/this.slotsPerEpoch);const epoch=this.firstNormalEpoch+normalEpochIndex;const slotIndex=normalSlotIndex%this.slotsPerEpoch;return[epoch,slotIndex]}}getFirstSlotInEpoch(epoch){if(epoch<=this.firstNormalEpoch){return(Math.pow(2,epoch)-1)*MINIMUM_SLOT_PER_EPOCH}else{return(epoch-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}}getLastSlotInEpoch(epoch){return this.getFirstSlotInEpoch(epoch)+this.getSlotsInEpoch(epoch)-1}getSlotsInEpoch(epoch){if(epoch<this.firstNormalEpoch){return Math.pow(2,epoch+trailingZeros(MINIMUM_SLOT_PER_EPOCH))}else{return this.slotsPerEpoch}}}var fetchImpl=globalThis.fetch;var eventemitter3={exports:{}};var hasRequiredEventemitter3;function requireEventemitter3(){if(hasRequiredEventemitter3)return eventemitter3.exports;hasRequiredEventemitter3=1;(function(module){var has=Object.prototype.hasOwnProperty,prefix="~";function Events(){}if(Object.create){Events.prototype=Object.create(null);if(!(new Events).__proto__)prefix=false}function EE(fn,context,once){this.fn=fn;this.context=context;this.once=once||false}function addListener(emitter,event,fn,context,once){if(typeof fn!=="function"){throw new TypeError("The listener must be a function")}var listener=new EE(fn,context||emitter,once),evt=prefix?prefix+event:event;if(!emitter._events[evt])emitter._events[evt]=listener,emitter._eventsCount++;else if(!emitter._events[evt].fn)emitter._events[evt].push(listener);else emitter._events[evt]=[emitter._events[evt],listener];return emitter}function clearEvent(emitter,evt){if(--emitter._eventsCount===0)emitter._events=new Events;else delete emitter._events[evt]}function EventEmitter(){this._events=new Events;this._eventsCount=0}EventEmitter.prototype.eventNames=function eventNames(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events){if(has.call(events,name))names.push(prefix?name.slice(1):name)}if(Object.getOwnPropertySymbols){return names.concat(Object.getOwnPropertySymbols(events))}return names};EventEmitter.prototype.listeners=function listeners(event){var evt=prefix?prefix+event:event,handlers=this._events[evt];if(!handlers)return[];if(handlers.fn)return[handlers.fn];for(var i=0,l=handlers.length,ee=new Array(l);i<l;i++){ee[i]=handlers[i].fn}return ee};EventEmitter.prototype.listenerCount=function listenerCount(event){var evt=prefix?prefix+event:event,listeners=this._events[evt];if(!listeners)return 0;if(listeners.fn)return 1;return listeners.length};EventEmitter.prototype.emit=function emit(event,a1,a2,a3,a4,a5){var evt=prefix?prefix+event:event;if(!this._events[evt])return false;var listeners=this._events[evt],len=arguments.length,args,i;if(listeners.fn){if(listeners.once)this.removeListener(event,listeners.fn,undefined,true);switch(len){case 1:return listeners.fn.call(listeners.context),true;case 2:return listeners.fn.call(listeners.context,a1),true;case 3:return listeners.fn.call(listeners.context,a1,a2),true;case 4:return listeners.fn.call(listeners.context,a1,a2,a3),true;case 5:return listeners.fn.call(listeners.context,a1,a2,a3,a4),true;case 6:return listeners.fn.call(listeners.context,a1,a2,a3,a4,a5),true}for(i=1,args=new Array(len-1);i<len;i++){args[i-1]=arguments[i]}listeners.fn.apply(listeners.context,args)}else{var length=listeners.length,j;for(i=0;i<length;i++){if(listeners[i].once)this.removeListener(event,listeners[i].fn,undefined,true);switch(len){case 1:listeners[i].fn.call(listeners[i].context);break;case 2:listeners[i].fn.call(listeners[i].context,a1);break;case 3:listeners[i].fn.call(listeners[i].context,a1,a2);break;case 4:listeners[i].fn.call(listeners[i].context,a1,a2,a3);break;default:if(!args)for(j=1,args=new Array(len-1);j<len;j++){args[j-1]=arguments[j]}listeners[i].fn.apply(listeners[i].context,args)}}}return true};EventEmitter.prototype.on=function on(event,fn,context){return addListener(this,event,fn,context,false)};EventEmitter.prototype.once=function once(event,fn,context){return addListener(this,event,fn,context,true)};EventEmitter.prototype.removeListener=function removeListener(event,fn,context,once){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn){clearEvent(this,evt);return this}var listeners=this._events[evt];if(listeners.fn){if(listeners.fn===fn&&(!once||listeners.once)&&(!context||listeners.context===context)){clearEvent(this,evt)}}else{for(var i=0,events=[],length=listeners.length;i<length;i++){if(listeners[i].fn!==fn||once&&!listeners[i].once||context&&listeners[i].context!==context){events.push(listeners[i])}}if(events.length)this._events[evt]=events.length===1?events[0]:events;else clearEvent(this,evt)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(event){var evt;if(event){evt=prefix?prefix+event:event;if(this._events[evt])clearEvent(this,evt)}else{this._events=new Events;this._eventsCount=0}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=prefix;EventEmitter.EventEmitter=EventEmitter;{module.exports=EventEmitter}})(eventemitter3);return eventemitter3.exports}var eventemitter3Exports=requireEventemitter3();var EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);var WebSocketBrowserImpl=class extends EventEmitter{socket;constructor(address,options,protocols){super();this.socket=new window.WebSocket(address,protocols);this.socket.onopen=()=>this.emit("open");this.socket.onmessage=event=>this.emit("message",event.data);this.socket.onerror=error=>this.emit("error",error);this.socket.onclose=event=>{this.emit("close",event.code,event.reason)}}send(data,optionsOrCallback,callback){const cb=callback||optionsOrCallback;try{this.socket.send(data);cb()}catch(error){cb(error)}}close(code,reason){this.socket.close(code,reason)}addEventListener(type,listener,options){this.socket.addEventListener(type,listener,options)}};function WebSocket(address,options){return new WebSocketBrowserImpl(address,options)}var DefaultDataPack=class{encode(value){return JSON.stringify(value)}decode(value){return JSON.parse(value)}};var CommonClient=class extends EventEmitter{address;rpc_id;queue;options;autoconnect;ready;reconnect;reconnect_timer_id;reconnect_interval;max_reconnects;rest_options;current_reconnects;generate_request_id;socket;webSocketFactory;dataPack;constructor(webSocketFactory,address="ws://localhost:8080",{autoconnect:autoconnect=true,reconnect:reconnect=true,reconnect_interval:reconnect_interval=1e3,max_reconnects:max_reconnects=5,...rest_options}={},generate_request_id,dataPack){super();this.webSocketFactory=webSocketFactory;this.queue={};this.rpc_id=0;this.address=address;this.autoconnect=autoconnect;this.ready=false;this.reconnect=reconnect;this.reconnect_timer_id=void 0;this.reconnect_interval=reconnect_interval;this.max_reconnects=max_reconnects;this.rest_options=rest_options;this.current_reconnects=0;this.generate_request_id=generate_request_id||(()=>++this.rpc_id);if(!dataPack)this.dataPack=new DefaultDataPack;else this.dataPack=dataPack;if(this.autoconnect)this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}connect(){if(this.socket)return;this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}call(method,params,timeout,ws_opts){if(!ws_opts&&"object"===typeof timeout){ws_opts=timeout;timeout=null}return new Promise(((resolve,reject)=>{if(!this.ready)return reject(new Error("socket not ready"));const rpc_id=this.generate_request_id(method,params);const message={jsonrpc:"2.0",method:method,params:params||void 0,id:rpc_id};this.socket.send(this.dataPack.encode(message),ws_opts,(error=>{if(error)return reject(error);this.queue[rpc_id]={promise:[resolve,reject]};if(timeout){this.queue[rpc_id].timeout=setTimeout((()=>{delete this.queue[rpc_id];reject(new Error("reply timeout"))}),timeout)}}))}))}async login(params){const resp=await this.call("rpc.login",params);if(!resp)throw new Error("authentication failed");return resp}async listMethods(){return await this.call("__listMethods")}notify(method,params){return new Promise(((resolve,reject)=>{if(!this.ready)return reject(new Error("socket not ready"));const message={jsonrpc:"2.0",method:method,params:params};this.socket.send(this.dataPack.encode(message),(error=>{if(error)return reject(error);resolve()}))}))}async subscribe(event){if(typeof event==="string")event=[event];const result=await this.call("rpc.on",event);if(typeof event==="string"&&result[event]!=="ok")throw new Error("Failed subscribing to an event '"+event+"' with: "+result[event]);return result}async unsubscribe(event){if(typeof event==="string")event=[event];const result=await this.call("rpc.off",event);if(typeof event==="string"&&result[event]!=="ok")throw new Error("Failed unsubscribing from an event with: "+result);return result}close(code,data){this.socket.close(code||1e3,data)}setAutoReconnect(reconnect){this.reconnect=reconnect}setReconnectInterval(interval){this.reconnect_interval=interval}setMaxReconnects(max_reconnects){this.max_reconnects=max_reconnects}_connect(address,options){clearTimeout(this.reconnect_timer_id);this.socket=this.webSocketFactory(address,options);this.socket.addEventListener("open",(()=>{this.ready=true;this.emit("open");this.current_reconnects=0}));this.socket.addEventListener("message",(({data:message})=>{if(message instanceof ArrayBuffer)message=bufferExports.Buffer.from(message).toString();try{message=this.dataPack.decode(message)}catch(error){return}if(message.notification&&this.listeners(message.notification).length){if(!Object.keys(message.params).length)return this.emit(message.notification);const args=[message.notification];if(message.params.constructor===Object)args.push(message.params);else for(let i=0;i<message.params.length;i++)args.push(message.params[i]);return Promise.resolve().then((()=>{this.emit.apply(this,args)}))}if(!this.queue[message.id]){if(message.method){return Promise.resolve().then((()=>{this.emit(message.method,message?.params)}))}return}if("error"in message==="result"in message)this.queue[message.id].promise[1](new Error('Server response malformed. Response must include either "result" or "error", but not both.'));if(this.queue[message.id].timeout)clearTimeout(this.queue[message.id].timeout);if(message.error)this.queue[message.id].promise[1](message.error);else this.queue[message.id].promise[0](message.result);delete this.queue[message.id]}));this.socket.addEventListener("error",(error=>this.emit("error",error)));this.socket.addEventListener("close",(({code:code,reason:reason})=>{if(this.ready)setTimeout((()=>this.emit("close",code,reason)),0);this.ready=false;this.socket=void 0;if(code===1e3)return;this.current_reconnects++;if(this.reconnect&&(this.max_reconnects>this.current_reconnects||this.max_reconnects===0))this.reconnect_timer_id=setTimeout((()=>this._connect(address,options)),this.reconnect_interval)}))}};class RpcWebSocketClient extends CommonClient{constructor(address,options,generate_request_id){const webSocketFactory=url=>{const rpc=WebSocket(url,{autoconnect:true,max_reconnects:5,reconnect:true,reconnect_interval:1e3,...options});if("socket"in rpc){this.underlyingSocket=rpc.socket}else{this.underlyingSocket=rpc}return rpc};super(webSocketFactory,address,options,generate_request_id);this.underlyingSocket=void 0}call(...args){const readyState=this.underlyingSocket?.readyState;if(readyState===1){return super.call(...args)}return Promise.reject(new Error("Tried to call a JSON-RPC method `"+args[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+readyState+")"))}notify(...args){const readyState=this.underlyingSocket?.readyState;if(readyState===1){return super.notify(...args)}return Promise.reject(new Error("Tried to send a JSON-RPC notification `"+args[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+readyState+")"))}}function decodeData(type,data){let decoded;try{decoded=type.layout.decode(data)}catch(err){throw new Error("invalid instruction; "+err)}if(decoded.typeIndex!==type.index){throw new Error(`invalid account data; account type mismatch ${decoded.typeIndex} != ${type.index}`)}return decoded}const LOOKUP_TABLE_META_SIZE=56;class AddressLookupTableAccount{constructor(args){this.key=void 0;this.state=void 0;this.key=args.key;this.state=args.state}isActive(){const U64_MAX=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===U64_MAX}static deserialize(accountData){const meta=decodeData(LookupTableMetaLayout,accountData);const serializedAddressesLen=accountData.length-LOOKUP_TABLE_META_SIZE;assert$1(serializedAddressesLen>=0,"lookup table is invalid");assert$1(serializedAddressesLen%32===0,"lookup table is invalid");const numSerializedAddresses=serializedAddressesLen/32;const{addresses:addresses}=LayoutExports.struct([LayoutExports.seq(publicKey(),numSerializedAddresses,"addresses")]).decode(accountData.slice(LOOKUP_TABLE_META_SIZE));return{deactivationSlot:meta.deactivationSlot,lastExtendedSlot:meta.lastExtendedSlot,lastExtendedSlotStartIndex:meta.lastExtendedStartIndex,authority:meta.authority.length!==0?new PublicKey(meta.authority[0]):undefined,addresses:addresses.map((address=>new PublicKey(address)))}}}const LookupTableMetaLayout={index:1,layout:LayoutExports.struct([LayoutExports.u32("typeIndex"),u64("deactivationSlot"),LayoutExports.nu64("lastExtendedSlot"),LayoutExports.u8("lastExtendedStartIndex"),LayoutExports.u8(),LayoutExports.seq(publicKey(),LayoutExports.offset(LayoutExports.u8(),-1),"authority")])};const URL_RE=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;function makeWebsocketUrl(endpoint){const matches=endpoint.match(URL_RE);if(matches==null){throw TypeError(`Failed to validate endpoint URL \`${endpoint}\``)}const[_,hostish,portWithColon,rest]=matches;const protocol=endpoint.startsWith("https:")?"wss:":"ws:";const startPort=portWithColon==null?null:parseInt(portWithColon.slice(1),10);const websocketPort=startPort==null?"":`:${startPort+1}`;return`${protocol}//${hostish}${websocketPort}${rest}`}const PublicKeyFromString=coerce(instance(PublicKey),string(),(value=>new PublicKey(value)));const RawAccountDataResult=tuple([string(),literal("base64")]);const BufferFromRawAccountData=coerce(instance(bufferExports.Buffer),RawAccountDataResult,(value=>bufferExports.Buffer.from(value[0],"base64")));const BLOCKHASH_CACHE_TIMEOUT_MS=30*1e3;function assertEndpointUrl(putativeUrl){if(/^https?:/.test(putativeUrl)===false){throw new TypeError("Endpoint URL must start with `http:` or `https:`.")}return putativeUrl}function extractCommitmentFromConfig(commitmentOrConfig){let commitment;let config;if(typeof commitmentOrConfig==="string"){commitment=commitmentOrConfig}else if(commitmentOrConfig){const{commitment:specifiedCommitment,...specifiedConfig}=commitmentOrConfig;commitment=specifiedCommitment;config=specifiedConfig}return{commitment:commitment,config:config}}function applyDefaultMemcmpEncodingToFilters(filters){return filters.map((filter=>"memcmp"in filter?{...filter,memcmp:{...filter.memcmp,encoding:filter.memcmp.encoding??"base58"}}:filter))}function createRpcResult(result){return union([type({jsonrpc:literal("2.0"),id:string(),result:result}),type({jsonrpc:literal("2.0"),id:string(),error:type({code:unknown(),message:string(),data:optional(any())})})])}const UnknownRpcResult=createRpcResult(unknown());function jsonRpcResult(schema){return coerce(createRpcResult(schema),UnknownRpcResult,(value=>{if("error"in value){return value}else{return{...value,result:create(value.result,schema)}}}))}function jsonRpcResultAndContext(value){return jsonRpcResult(type({context:type({slot:number()}),value:value}))}function notificationResultAndContext(value){return type({context:type({slot:number()}),value:value})}function versionedMessageFromResponse(version,response){if(version===0){return new MessageV0({header:response.header,staticAccountKeys:response.accountKeys.map((accountKey=>new PublicKey(accountKey))),recentBlockhash:response.recentBlockhash,compiledInstructions:response.instructions.map((ix=>({programIdIndex:ix.programIdIndex,accountKeyIndexes:ix.accounts,data:bs58.decode(ix.data)}))),addressTableLookups:response.addressTableLookups})}else{return new Message(response)}}const GetInflationGovernorResult=type({foundation:number(),foundationTerm:number(),initial:number(),taper:number(),terminal:number()});const GetInflationRewardResult=jsonRpcResult(array(nullable(type({epoch:number(),effectiveSlot:number(),amount:number(),postBalance:number(),commission:optional(nullable(number()))}))));const GetRecentPrioritizationFeesResult=array(type({slot:number(),prioritizationFee:number()}));const GetInflationRateResult=type({total:number(),validator:number(),foundation:number(),epoch:number()});const GetEpochInfoResult=type({epoch:number(),slotIndex:number(),slotsInEpoch:number(),absoluteSlot:number(),blockHeight:optional(number()),transactionCount:optional(number())});const GetEpochScheduleResult=type({slotsPerEpoch:number(),leaderScheduleSlotOffset:number(),warmup:boolean(),firstNormalEpoch:number(),firstNormalSlot:number()});const GetLeaderScheduleResult=record(string(),array(number()));const TransactionErrorResult=nullable(union([type({}),string()]));const SignatureStatusResult=type({err:TransactionErrorResult});const SignatureReceivedResult=literal("receivedSignature");const VersionResult=type({"solana-core":string(),"feature-set":optional(number())});const ParsedInstructionStruct=type({program:string(),programId:PublicKeyFromString,parsed:unknown()});const PartiallyDecodedInstructionStruct=type({programId:PublicKeyFromString,accounts:array(PublicKeyFromString),data:string()});const SimulatedTransactionResponseStruct=jsonRpcResultAndContext(type({err:nullable(union([type({}),string()])),logs:nullable(array(string())),accounts:optional(nullable(array(nullable(type({executable:boolean(),owner:string(),lamports:number(),data:array(string()),rentEpoch:optional(number())}))))),unitsConsumed:optional(number()),returnData:optional(nullable(type({programId:string(),data:tuple([string(),literal("base64")])}))),innerInstructions:optional(nullable(array(type({index:number(),instructions:array(union([ParsedInstructionStruct,PartiallyDecodedInstructionStruct]))}))))}));const BlockProductionResponseStruct=jsonRpcResultAndContext(type({byIdentity:record(string(),array(number())),range:type({firstSlot:number(),lastSlot:number()})}));function createRpcClient(url,httpHeaders,customFetch,fetchMiddleware,disableRetryOnRateLimit,httpAgent){const fetch=customFetch?customFetch:fetchImpl;let agent;{if(httpAgent!=null){console.warn("You have supplied an `httpAgent` when creating a `Connection` in a browser environment."+"It has been ignored; `httpAgent` is only used in Node environments.")}}let fetchWithMiddleware;if(fetchMiddleware){fetchWithMiddleware=async(info,init)=>{const modifiedFetchArgs=await new Promise(((resolve,reject)=>{try{fetchMiddleware(info,init,((modifiedInfo,modifiedInit)=>resolve([modifiedInfo,modifiedInit])))}catch(error){reject(error)}}));return await fetch(...modifiedFetchArgs)}}const clientBrowser=new RpcClient((async(request,callback)=>{const options={method:"POST",body:request,agent:agent,headers:Object.assign({"Content-Type":"application/json"},httpHeaders||{},COMMON_HTTP_HEADERS)};try{let too_many_requests_retries=5;let res;let waitTime=500;for(;;){if(fetchWithMiddleware){res=await fetchWithMiddleware(url,options)}else{res=await fetch(url,options)}if(res.status!==429){break}if(disableRetryOnRateLimit===true){break}too_many_requests_retries-=1;if(too_many_requests_retries===0){break}console.error(`Server responded with ${res.status} ${res.statusText}. Retrying after ${waitTime}ms delay...`);await sleep(waitTime);waitTime*=2}const text=await res.text();if(res.ok){callback(null,text)}else{callback(new Error(`${res.status} ${res.statusText}: ${text}`))}}catch(err){if(err instanceof Error)callback(err)}}),{});return clientBrowser}function createRpcRequest(client){return(method,args)=>new Promise(((resolve,reject)=>{client.request(method,args,((err,response)=>{if(err){reject(err);return}resolve(response)}))}))}function createRpcBatchRequest(client){return requests=>new Promise(((resolve,reject)=>{if(requests.length===0)resolve([]);const batch=requests.map((params=>client.request(params.methodName,params.args)));client.request(batch,((err,response)=>{if(err){reject(err);return}resolve(response)}))}))}const GetInflationGovernorRpcResult=jsonRpcResult(GetInflationGovernorResult);const GetInflationRateRpcResult=jsonRpcResult(GetInflationRateResult);const GetRecentPrioritizationFeesRpcResult=jsonRpcResult(GetRecentPrioritizationFeesResult);const GetEpochInfoRpcResult=jsonRpcResult(GetEpochInfoResult);const GetEpochScheduleRpcResult=jsonRpcResult(GetEpochScheduleResult);const GetLeaderScheduleRpcResult=jsonRpcResult(GetLeaderScheduleResult);const SlotRpcResult=jsonRpcResult(number());const GetSupplyRpcResult=jsonRpcResultAndContext(type({total:number(),circulating:number(),nonCirculating:number(),nonCirculatingAccounts:array(PublicKeyFromString)}));const TokenAmountResult=type({amount:string(),uiAmount:nullable(number()),decimals:number(),uiAmountString:optional(string())});const GetTokenLargestAccountsResult=jsonRpcResultAndContext(array(type({address:PublicKeyFromString,amount:string(),uiAmount:nullable(number()),decimals:number(),uiAmountString:optional(string())})));const GetTokenAccountsByOwner=jsonRpcResultAndContext(array(type({pubkey:PublicKeyFromString,account:type({executable:boolean(),owner:PublicKeyFromString,lamports:number(),data:BufferFromRawAccountData,rentEpoch:number()})})));const ParsedAccountDataResult=type({program:string(),parsed:unknown(),space:number()});const GetParsedTokenAccountsByOwner=jsonRpcResultAndContext(array(type({pubkey:PublicKeyFromString,account:type({executable:boolean(),owner:PublicKeyFromString,lamports:number(),data:ParsedAccountDataResult,rentEpoch:number()})})));const GetLargestAccountsRpcResult=jsonRpcResultAndContext(array(type({lamports:number(),address:PublicKeyFromString})));const AccountInfoResult=type({executable:boolean(),owner:PublicKeyFromString,lamports:number(),data:BufferFromRawAccountData,rentEpoch:number()});const KeyedAccountInfoResult=type({pubkey:PublicKeyFromString,account:AccountInfoResult});const ParsedOrRawAccountData=coerce(union([instance(bufferExports.Buffer),ParsedAccountDataResult]),union([RawAccountDataResult,ParsedAccountDataResult]),(value=>{if(Array.isArray(value)){return create(value,BufferFromRawAccountData)}else{return value}}));const ParsedAccountInfoResult=type({executable:boolean(),owner:PublicKeyFromString,lamports:number(),data:ParsedOrRawAccountData,rentEpoch:number()});const KeyedParsedAccountInfoResult=type({pubkey:PublicKeyFromString,account:ParsedAccountInfoResult});const StakeActivationResult=type({state:union([literal("active"),literal("inactive"),literal("activating"),literal("deactivating")]),active:number(),inactive:number()});const GetConfirmedSignaturesForAddress2RpcResult=jsonRpcResult(array(type({signature:string(),slot:number(),err:TransactionErrorResult,memo:nullable(string()),blockTime:optional(nullable(number()))})));const GetSignaturesForAddressRpcResult=jsonRpcResult(array(type({signature:string(),slot:number(),err:TransactionErrorResult,memo:nullable(string()),blockTime:optional(nullable(number()))})));const AccountNotificationResult=type({subscription:number(),result:notificationResultAndContext(AccountInfoResult)});const ProgramAccountInfoResult=type({pubkey:PublicKeyFromString,account:AccountInfoResult});const ProgramAccountNotificationResult=type({subscription:number(),result:notificationResultAndContext(ProgramAccountInfoResult)});const SlotInfoResult=type({parent:number(),slot:number(),root:number()});const SlotNotificationResult=type({subscription:number(),result:SlotInfoResult});const SlotUpdateResult=union([type({type:union([literal("firstShredReceived"),literal("completed"),literal("optimisticConfirmation"),literal("root")]),slot:number(),timestamp:number()}),type({type:literal("createdBank"),parent:number(),slot:number(),timestamp:number()}),type({type:literal("frozen"),slot:number(),timestamp:number(),stats:type({numTransactionEntries:number(),numSuccessfulTransactions:number(),numFailedTransactions:number(),maxTransactionsPerEntry:number()})}),type({type:literal("dead"),slot:number(),timestamp:number(),err:string()})]);const SlotUpdateNotificationResult=type({subscription:number(),result:SlotUpdateResult});const SignatureNotificationResult=type({subscription:number(),result:notificationResultAndContext(union([SignatureStatusResult,SignatureReceivedResult]))});const RootNotificationResult=type({subscription:number(),result:number()});const ContactInfoResult=type({pubkey:string(),gossip:nullable(string()),tpu:nullable(string()),rpc:nullable(string()),version:nullable(string())});const VoteAccountInfoResult=type({votePubkey:string(),nodePubkey:string(),activatedStake:number(),epochVoteAccount:boolean(),epochCredits:array(tuple([number(),number(),number()])),commission:number(),lastVote:number(),rootSlot:nullable(number())});const GetVoteAccounts=jsonRpcResult(type({current:array(VoteAccountInfoResult),delinquent:array(VoteAccountInfoResult)}));const ConfirmationStatus=union([literal("processed"),literal("confirmed"),literal("finalized")]);const SignatureStatusResponse=type({slot:number(),confirmations:nullable(number()),err:TransactionErrorResult,confirmationStatus:optional(ConfirmationStatus)});const GetSignatureStatusesRpcResult=jsonRpcResultAndContext(array(nullable(SignatureStatusResponse)));const GetMinimumBalanceForRentExemptionRpcResult=jsonRpcResult(number());const AddressTableLookupStruct=type({accountKey:PublicKeyFromString,writableIndexes:array(number()),readonlyIndexes:array(number())});const ConfirmedTransactionResult=type({signatures:array(string()),message:type({accountKeys:array(string()),header:type({numRequiredSignatures:number(),numReadonlySignedAccounts:number(),numReadonlyUnsignedAccounts:number()}),instructions:array(type({accounts:array(number()),data:string(),programIdIndex:number()})),recentBlockhash:string(),addressTableLookups:optional(array(AddressTableLookupStruct))})});const AnnotatedAccountKey=type({pubkey:PublicKeyFromString,signer:boolean(),writable:boolean(),source:optional(union([literal("transaction"),literal("lookupTable")]))});const ConfirmedTransactionAccountsModeResult=type({accountKeys:array(AnnotatedAccountKey),signatures:array(string())});const ParsedInstructionResult=type({parsed:unknown(),program:string(),programId:PublicKeyFromString});const RawInstructionResult=type({accounts:array(PublicKeyFromString),data:string(),programId:PublicKeyFromString});const InstructionResult=union([RawInstructionResult,ParsedInstructionResult]);const UnknownInstructionResult=union([type({parsed:unknown(),program:string(),programId:string()}),type({accounts:array(string()),data:string(),programId:string()})]);const ParsedOrRawInstruction=coerce(InstructionResult,UnknownInstructionResult,(value=>{if("accounts"in value){return create(value,RawInstructionResult)}else{return create(value,ParsedInstructionResult)}}));const ParsedConfirmedTransactionResult=type({signatures:array(string()),message:type({accountKeys:array(AnnotatedAccountKey),instructions:array(ParsedOrRawInstruction),recentBlockhash:string(),addressTableLookups:optional(nullable(array(AddressTableLookupStruct)))})});const TokenBalanceResult=type({accountIndex:number(),mint:string(),owner:optional(string()),programId:optional(string()),uiTokenAmount:TokenAmountResult});const LoadedAddressesResult=type({writable:array(PublicKeyFromString),readonly:array(PublicKeyFromString)});const ConfirmedTransactionMetaResult=type({err:TransactionErrorResult,fee:number(),innerInstructions:optional(nullable(array(type({index:number(),instructions:array(type({accounts:array(number()),data:string(),programIdIndex:number()}))})))),preBalances:array(number()),postBalances:array(number()),logMessages:optional(nullable(array(string()))),preTokenBalances:optional(nullable(array(TokenBalanceResult))),postTokenBalances:optional(nullable(array(TokenBalanceResult))),loadedAddresses:optional(LoadedAddressesResult),computeUnitsConsumed:optional(number())});const ParsedConfirmedTransactionMetaResult=type({err:TransactionErrorResult,fee:number(),innerInstructions:optional(nullable(array(type({index:number(),instructions:array(ParsedOrRawInstruction)})))),preBalances:array(number()),postBalances:array(number()),logMessages:optional(nullable(array(string()))),preTokenBalances:optional(nullable(array(TokenBalanceResult))),postTokenBalances:optional(nullable(array(TokenBalanceResult))),loadedAddresses:optional(LoadedAddressesResult),computeUnitsConsumed:optional(number())});const TransactionVersionStruct=union([literal(0),literal("legacy")]);const RewardsResult=type({pubkey:string(),lamports:number(),postBalance:nullable(number()),rewardType:nullable(string()),commission:optional(nullable(number()))});const GetBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ConfirmedTransactionResult,meta:nullable(ConfirmedTransactionMetaResult),version:optional(TransactionVersionStruct)})),rewards:optional(array(RewardsResult)),blockTime:nullable(number()),blockHeight:nullable(number())})));const GetNoneModeBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),rewards:optional(array(RewardsResult)),blockTime:nullable(number()),blockHeight:nullable(number())})));const GetAccountsModeBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ConfirmedTransactionAccountsModeResult,meta:nullable(ConfirmedTransactionMetaResult),version:optional(TransactionVersionStruct)})),rewards:optional(array(RewardsResult)),blockTime:nullable(number()),blockHeight:nullable(number())})));const GetParsedBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ParsedConfirmedTransactionResult,meta:nullable(ParsedConfirmedTransactionMetaResult),version:optional(TransactionVersionStruct)})),rewards:optional(array(RewardsResult)),blockTime:nullable(number()),blockHeight:nullable(number())})));const GetParsedAccountsModeBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ConfirmedTransactionAccountsModeResult,meta:nullable(ParsedConfirmedTransactionMetaResult),version:optional(TransactionVersionStruct)})),rewards:optional(array(RewardsResult)),blockTime:nullable(number()),blockHeight:nullable(number())})));const GetParsedNoneModeBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),rewards:optional(array(RewardsResult)),blockTime:nullable(number()),blockHeight:nullable(number())})));const GetConfirmedBlockRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),transactions:array(type({transaction:ConfirmedTransactionResult,meta:nullable(ConfirmedTransactionMetaResult)})),rewards:optional(array(RewardsResult)),blockTime:nullable(number())})));const GetBlockSignaturesRpcResult=jsonRpcResult(nullable(type({blockhash:string(),previousBlockhash:string(),parentSlot:number(),signatures:array(string()),blockTime:nullable(number())})));const GetTransactionRpcResult=jsonRpcResult(nullable(type({slot:number(),meta:nullable(ConfirmedTransactionMetaResult),blockTime:optional(nullable(number())),transaction:ConfirmedTransactionResult,version:optional(TransactionVersionStruct)})));const GetParsedTransactionRpcResult=jsonRpcResult(nullable(type({slot:number(),transaction:ParsedConfirmedTransactionResult,meta:nullable(ParsedConfirmedTransactionMetaResult),blockTime:optional(nullable(number())),version:optional(TransactionVersionStruct)})));const GetRecentBlockhashAndContextRpcResult=jsonRpcResultAndContext(type({blockhash:string(),feeCalculator:type({lamportsPerSignature:number()})}));const GetLatestBlockhashRpcResult=jsonRpcResultAndContext(type({blockhash:string(),lastValidBlockHeight:number()}));const IsBlockhashValidRpcResult=jsonRpcResultAndContext(boolean());const PerfSampleResult=type({slot:number(),numTransactions:number(),numSlots:number(),samplePeriodSecs:number()});const GetRecentPerformanceSamplesRpcResult=jsonRpcResult(array(PerfSampleResult));const GetFeeCalculatorRpcResult=jsonRpcResultAndContext(nullable(type({feeCalculator:type({lamportsPerSignature:number()})})));const RequestAirdropRpcResult=jsonRpcResult(string());const SendTransactionRpcResult=jsonRpcResult(string());const LogsResult=type({err:TransactionErrorResult,logs:array(string()),signature:string()});const LogsNotificationResult=type({result:notificationResultAndContext(LogsResult),subscription:number()});const COMMON_HTTP_HEADERS={"solana-client":`js/${"1.95.8"}`};class Connection{constructor(endpoint,_commitmentOrConfig){this._commitment=void 0;this._confirmTransactionInitialTimeout=void 0;this._rpcEndpoint=void 0;this._rpcWsEndpoint=void 0;this._rpcClient=void 0;this._rpcRequest=void 0;this._rpcBatchRequest=void 0;this._rpcWebSocket=void 0;this._rpcWebSocketConnected=false;this._rpcWebSocketHeartbeat=null;this._rpcWebSocketIdleTimeout=null;this._rpcWebSocketGeneration=0;this._disableBlockhashCaching=false;this._pollingBlockhash=false;this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]};this._nextClientSubscriptionId=0;this._subscriptionDisposeFunctionsByClientSubscriptionId={};this._subscriptionHashByClientSubscriptionId={};this._subscriptionStateChangeCallbacksByHash={};this._subscriptionCallbacksByServerSubscriptionId={};this._subscriptionsByHash={};this._subscriptionsAutoDisposedByRpc=new Set;this.getBlockHeight=(()=>{const requestPromises={};return async commitmentOrConfig=>{const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([],commitment,undefined,config);const requestHash=fastStableStringify(args);requestPromises[requestHash]=requestPromises[requestHash]??(async()=>{try{const unsafeRes=await this._rpcRequest("getBlockHeight",args);const res=create(unsafeRes,jsonRpcResult(number()));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get block height information")}return res.result}finally{delete requestPromises[requestHash]}})();return await requestPromises[requestHash]}})();let wsEndpoint;let httpHeaders;let fetch;let fetchMiddleware;let disableRetryOnRateLimit;let httpAgent;if(_commitmentOrConfig&&typeof _commitmentOrConfig==="string"){this._commitment=_commitmentOrConfig}else if(_commitmentOrConfig){this._commitment=_commitmentOrConfig.commitment;this._confirmTransactionInitialTimeout=_commitmentOrConfig.confirmTransactionInitialTimeout;wsEndpoint=_commitmentOrConfig.wsEndpoint;httpHeaders=_commitmentOrConfig.httpHeaders;fetch=_commitmentOrConfig.fetch;fetchMiddleware=_commitmentOrConfig.fetchMiddleware;disableRetryOnRateLimit=_commitmentOrConfig.disableRetryOnRateLimit;httpAgent=_commitmentOrConfig.httpAgent}this._rpcEndpoint=assertEndpointUrl(endpoint);this._rpcWsEndpoint=wsEndpoint||makeWebsocketUrl(endpoint);this._rpcClient=createRpcClient(endpoint,httpHeaders,fetch,fetchMiddleware,disableRetryOnRateLimit,httpAgent);this._rpcRequest=createRpcRequest(this._rpcClient);this._rpcBatchRequest=createRpcBatchRequest(this._rpcClient);this._rpcWebSocket=new RpcWebSocketClient(this._rpcWsEndpoint,{autoconnect:false,max_reconnects:Infinity});this._rpcWebSocket.on("open",this._wsOnOpen.bind(this));this._rpcWebSocket.on("error",this._wsOnError.bind(this));this._rpcWebSocket.on("close",this._wsOnClose.bind(this));this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this));this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this));this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this));this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this));this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this));this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this));this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(publicKey,commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([publicKey.toBase58()],commitment,undefined,config);const unsafeRes=await this._rpcRequest("getBalance",args);const res=create(unsafeRes,jsonRpcResultAndContext(number()));if("error"in res){throw new SolanaJSONRPCError(res.error,`failed to get balance for ${publicKey.toBase58()}`)}return res.result}async getBalance(publicKey,commitmentOrConfig){return await this.getBalanceAndContext(publicKey,commitmentOrConfig).then((x=>x.value)).catch((e=>{throw new Error("failed to get balance of account "+publicKey.toBase58()+": "+e)}))}async getBlockTime(slot){const unsafeRes=await this._rpcRequest("getBlockTime",[slot]);const res=create(unsafeRes,jsonRpcResult(nullable(number())));if("error"in res){throw new SolanaJSONRPCError(res.error,`failed to get block time for slot ${slot}`)}return res.result}async getMinimumLedgerSlot(){const unsafeRes=await this._rpcRequest("minimumLedgerSlot",[]);const res=create(unsafeRes,jsonRpcResult(number()));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get minimum ledger slot")}return res.result}async getFirstAvailableBlock(){const unsafeRes=await this._rpcRequest("getFirstAvailableBlock",[]);const res=create(unsafeRes,SlotRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get first available block")}return res.result}async getSupply(config){let configArg={};if(typeof config==="string"){configArg={commitment:config}}else if(config){configArg={...config,commitment:config&&config.commitment||this.commitment}}else{configArg={commitment:this.commitment}}const unsafeRes=await this._rpcRequest("getSupply",[configArg]);const res=create(unsafeRes,GetSupplyRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get supply")}return res.result}async getTokenSupply(tokenMintAddress,commitment){const args=this._buildArgs([tokenMintAddress.toBase58()],commitment);const unsafeRes=await this._rpcRequest("getTokenSupply",args);const res=create(unsafeRes,jsonRpcResultAndContext(TokenAmountResult));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get token supply")}return res.result}async getTokenAccountBalance(tokenAddress,commitment){const args=this._buildArgs([tokenAddress.toBase58()],commitment);const unsafeRes=await this._rpcRequest("getTokenAccountBalance",args);const res=create(unsafeRes,jsonRpcResultAndContext(TokenAmountResult));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get token account balance")}return res.result}async getTokenAccountsByOwner(ownerAddress,filter,commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);let _args=[ownerAddress.toBase58()];if("mint"in filter){_args.push({mint:filter.mint.toBase58()})}else{_args.push({programId:filter.programId.toBase58()})}const args=this._buildArgs(_args,commitment,"base64",config);const unsafeRes=await this._rpcRequest("getTokenAccountsByOwner",args);const res=create(unsafeRes,GetTokenAccountsByOwner);if("error"in res){throw new SolanaJSONRPCError(res.error,`failed to get token accounts owned by account ${ownerAddress.toBase58()}`)}return res.result}async getParsedTokenAccountsByOwner(ownerAddress,filter,commitment){let _args=[ownerAddress.toBase58()];if("mint"in filter){_args.push({mint:filter.mint.toBase58()})}else{_args.push({programId:filter.programId.toBase58()})}const args=this._buildArgs(_args,commitment,"jsonParsed");const unsafeRes=await this._rpcRequest("getTokenAccountsByOwner",args);const res=create(unsafeRes,GetParsedTokenAccountsByOwner);if("error"in res){throw new SolanaJSONRPCError(res.error,`failed to get token accounts owned by account ${ownerAddress.toBase58()}`)}return res.result}async getLargestAccounts(config){const arg={...config,commitment:config&&config.commitment||this.commitment};const args=arg.filter||arg.commitment?[arg]:[];const unsafeRes=await this._rpcRequest("getLargestAccounts",args);const res=create(unsafeRes,GetLargestAccountsRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get largest accounts")}return res.result}async getTokenLargestAccounts(mintAddress,commitment){const args=this._buildArgs([mintAddress.toBase58()],commitment);const unsafeRes=await this._rpcRequest("getTokenLargestAccounts",args);const res=create(unsafeRes,GetTokenLargestAccountsResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get token largest accounts")}return res.result}async getAccountInfoAndContext(publicKey,commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([publicKey.toBase58()],commitment,"base64",config);const unsafeRes=await this._rpcRequest("getAccountInfo",args);const res=create(unsafeRes,jsonRpcResultAndContext(nullable(AccountInfoResult)));if("error"in res){throw new SolanaJSONRPCError(res.error,`failed to get info about account ${publicKey.toBase58()}`)}return res.result}async getParsedAccountInfo(publicKey,commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([publicKey.toBase58()],commitment,"jsonParsed",config);const unsafeRes=await this._rpcRequest("getAccountInfo",args);const res=create(unsafeRes,jsonRpcResultAndContext(nullable(ParsedAccountInfoResult)));if("error"in res){throw new SolanaJSONRPCError(res.error,`failed to get info about account ${publicKey.toBase58()}`)}return res.result}async getAccountInfo(publicKey,commitmentOrConfig){try{const res=await this.getAccountInfoAndContext(publicKey,commitmentOrConfig);return res.value}catch(e){throw new Error("failed to get info about account "+publicKey.toBase58()+": "+e)}}async getMultipleParsedAccounts(publicKeys,rawConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(rawConfig);const keys=publicKeys.map((key=>key.toBase58()));const args=this._buildArgs([keys],commitment,"jsonParsed",config);const unsafeRes=await this._rpcRequest("getMultipleAccounts",args);const res=create(unsafeRes,jsonRpcResultAndContext(array(nullable(ParsedAccountInfoResult))));if("error"in res){throw new SolanaJSONRPCError(res.error,`failed to get info for accounts ${keys}`)}return res.result}async getMultipleAccountsInfoAndContext(publicKeys,commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const keys=publicKeys.map((key=>key.toBase58()));const args=this._buildArgs([keys],commitment,"base64",config);const unsafeRes=await this._rpcRequest("getMultipleAccounts",args);const res=create(unsafeRes,jsonRpcResultAndContext(array(nullable(AccountInfoResult))));if("error"in res){throw new SolanaJSONRPCError(res.error,`failed to get info for accounts ${keys}`)}return res.result}async getMultipleAccountsInfo(publicKeys,commitmentOrConfig){const res=await this.getMultipleAccountsInfoAndContext(publicKeys,commitmentOrConfig);return res.value}async getStakeActivation(publicKey,commitmentOrConfig,epoch){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([publicKey.toBase58()],commitment,undefined,{...config,epoch:epoch!=null?epoch:config?.epoch});const unsafeRes=await this._rpcRequest("getStakeActivation",args);const res=create(unsafeRes,jsonRpcResult(StakeActivationResult));if("error"in res){throw new SolanaJSONRPCError(res.error,`failed to get Stake Activation ${publicKey.toBase58()}`)}return res.result}async getProgramAccounts(programId,configOrCommitment){const{commitment:commitment,config:config}=extractCommitmentFromConfig(configOrCommitment);const{encoding:encoding,...configWithoutEncoding}=config||{};const args=this._buildArgs([programId.toBase58()],commitment,encoding||"base64",{...configWithoutEncoding,...configWithoutEncoding.filters?{filters:applyDefaultMemcmpEncodingToFilters(configWithoutEncoding.filters)}:null});const unsafeRes=await this._rpcRequest("getProgramAccounts",args);const baseSchema=array(KeyedAccountInfoResult);const res=configWithoutEncoding.withContext===true?create(unsafeRes,jsonRpcResultAndContext(baseSchema)):create(unsafeRes,jsonRpcResult(baseSchema));if("error"in res){throw new SolanaJSONRPCError(res.error,`failed to get accounts owned by program ${programId.toBase58()}`)}return res.result}async getParsedProgramAccounts(programId,configOrCommitment){const{commitment:commitment,config:config}=extractCommitmentFromConfig(configOrCommitment);const args=this._buildArgs([programId.toBase58()],commitment,"jsonParsed",config);const unsafeRes=await this._rpcRequest("getProgramAccounts",args);const res=create(unsafeRes,jsonRpcResult(array(KeyedParsedAccountInfoResult)));if("error"in res){throw new SolanaJSONRPCError(res.error,`failed to get accounts owned by program ${programId.toBase58()}`)}return res.result}async confirmTransaction(strategy,commitment){let rawSignature;if(typeof strategy=="string"){rawSignature=strategy}else{const config=strategy;if(config.abortSignal?.aborted){return Promise.reject(config.abortSignal.reason)}rawSignature=config.signature}let decodedSignature;try{decodedSignature=bs58.decode(rawSignature)}catch(err){throw new Error("signature must be base58 encoded: "+rawSignature)}assert$1(decodedSignature.length===64,"signature has invalid length");if(typeof strategy==="string"){return await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:commitment||this.commitment,signature:rawSignature})}else if("lastValidBlockHeight"in strategy){return await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:commitment||this.commitment,strategy:strategy})}else{return await this.confirmTransactionUsingDurableNonceStrategy({commitment:commitment||this.commitment,strategy:strategy})}}getCancellationPromise(signal){return new Promise(((_,reject)=>{if(signal==null){return}if(signal.aborted){reject(signal.reason)}else{signal.addEventListener("abort",(()=>{reject(signal.reason)}))}}))}getTransactionConfirmationPromise({commitment:commitment,signature:signature}){let signatureSubscriptionId;let disposeSignatureSubscriptionStateChangeObserver;let done=false;const confirmationPromise=new Promise(((resolve,reject)=>{try{signatureSubscriptionId=this.onSignature(signature,((result,context)=>{signatureSubscriptionId=undefined;const response={context:context,value:result};resolve({__type:TransactionStatus.PROCESSED,response:response})}),commitment);const subscriptionSetupPromise=new Promise((resolveSubscriptionSetup=>{if(signatureSubscriptionId==null){resolveSubscriptionSetup()}else{disposeSignatureSubscriptionStateChangeObserver=this._onSubscriptionStateChange(signatureSubscriptionId,(nextState=>{if(nextState==="subscribed"){resolveSubscriptionSetup()}}))}}));(async()=>{await subscriptionSetupPromise;if(done)return;const response=await this.getSignatureStatus(signature);if(done)return;if(response==null){return}const{context:context,value:value}=response;if(value==null){return}if(value?.err){reject(value.err)}else{switch(commitment){case"confirmed":case"single":case"singleGossip":{if(value.confirmationStatus==="processed"){return}break}case"finalized":case"max":case"root":{if(value.confirmationStatus==="processed"||value.confirmationStatus==="confirmed"){return}break}case"processed":case"recent":}done=true;resolve({__type:TransactionStatus.PROCESSED,response:{context:context,value:value}})}})()}catch(err){reject(err)}}));const abortConfirmation=()=>{if(disposeSignatureSubscriptionStateChangeObserver){disposeSignatureSubscriptionStateChangeObserver();disposeSignatureSubscriptionStateChangeObserver=undefined}if(signatureSubscriptionId!=null){this.removeSignatureListener(signatureSubscriptionId);signatureSubscriptionId=undefined}};return{abortConfirmation:abortConfirmation,confirmationPromise:confirmationPromise}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:commitment,strategy:{abortSignal:abortSignal,lastValidBlockHeight:lastValidBlockHeight,signature:signature}}){let done=false;const expiryPromise=new Promise((resolve=>{const checkBlockHeight=async()=>{try{const blockHeight=await this.getBlockHeight(commitment);return blockHeight}catch(_e){return-1}};(async()=>{let currentBlockHeight=await checkBlockHeight();if(done)return;while(currentBlockHeight<=lastValidBlockHeight){await sleep(1e3);if(done)return;currentBlockHeight=await checkBlockHeight();if(done)return}resolve({__type:TransactionStatus.BLOCKHEIGHT_EXCEEDED})})()}));const{abortConfirmation:abortConfirmation,confirmationPromise:confirmationPromise}=this.getTransactionConfirmationPromise({commitment:commitment,signature:signature});const cancellationPromise=this.getCancellationPromise(abortSignal);let result;try{const outcome=await Promise.race([cancellationPromise,confirmationPromise,expiryPromise]);if(outcome.__type===TransactionStatus.PROCESSED){result=outcome.response}else{throw new TransactionExpiredBlockheightExceededError(signature)}}finally{done=true;abortConfirmation()}return result}async confirmTransactionUsingDurableNonceStrategy({commitment:commitment,strategy:{abortSignal:abortSignal,minContextSlot:minContextSlot,nonceAccountPubkey:nonceAccountPubkey,nonceValue:nonceValue,signature:signature}}){let done=false;const expiryPromise=new Promise((resolve=>{let currentNonceValue=nonceValue;let lastCheckedSlot=null;const getCurrentNonceValue=async()=>{try{const{context:context,value:nonceAccount}=await this.getNonceAndContext(nonceAccountPubkey,{commitment:commitment,minContextSlot:minContextSlot});lastCheckedSlot=context.slot;return nonceAccount?.nonce}catch(e){return currentNonceValue}};(async()=>{currentNonceValue=await getCurrentNonceValue();if(done)return;while(true){if(nonceValue!==currentNonceValue){resolve({__type:TransactionStatus.NONCE_INVALID,slotInWhichNonceDidAdvance:lastCheckedSlot});return}await sleep(2e3);if(done)return;currentNonceValue=await getCurrentNonceValue();if(done)return}})()}));const{abortConfirmation:abortConfirmation,confirmationPromise:confirmationPromise}=this.getTransactionConfirmationPromise({commitment:commitment,signature:signature});const cancellationPromise=this.getCancellationPromise(abortSignal);let result;try{const outcome=await Promise.race([cancellationPromise,confirmationPromise,expiryPromise]);if(outcome.__type===TransactionStatus.PROCESSED){result=outcome.response}else{let signatureStatus;while(true){const status=await this.getSignatureStatus(signature);if(status==null){break}if(status.context.slot<(outcome.slotInWhichNonceDidAdvance??minContextSlot)){await sleep(400);continue}signatureStatus=status;break}if(signatureStatus?.value){const commitmentForStatus=commitment||"finalized";const{confirmationStatus:confirmationStatus}=signatureStatus.value;switch(commitmentForStatus){case"processed":case"recent":if(confirmationStatus!=="processed"&&confirmationStatus!=="confirmed"&&confirmationStatus!=="finalized"){throw new TransactionExpiredNonceInvalidError(signature)}break;case"confirmed":case"single":case"singleGossip":if(confirmationStatus!=="confirmed"&&confirmationStatus!=="finalized"){throw new TransactionExpiredNonceInvalidError(signature)}break;case"finalized":case"max":case"root":if(confirmationStatus!=="finalized"){throw new TransactionExpiredNonceInvalidError(signature)}break;default:(_=>{})(commitmentForStatus)}result={context:signatureStatus.context,value:{err:signatureStatus.value.err}}}else{throw new TransactionExpiredNonceInvalidError(signature)}}}finally{done=true;abortConfirmation()}return result}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:commitment,signature:signature}){let timeoutId;const expiryPromise=new Promise((resolve=>{let timeoutMs=this._confirmTransactionInitialTimeout||60*1e3;switch(commitment){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":{timeoutMs=this._confirmTransactionInitialTimeout||30*1e3;break}}timeoutId=setTimeout((()=>resolve({__type:TransactionStatus.TIMED_OUT,timeoutMs:timeoutMs})),timeoutMs)}));const{abortConfirmation:abortConfirmation,confirmationPromise:confirmationPromise}=this.getTransactionConfirmationPromise({commitment:commitment,signature:signature});let result;try{const outcome=await Promise.race([confirmationPromise,expiryPromise]);if(outcome.__type===TransactionStatus.PROCESSED){result=outcome.response}else{throw new TransactionExpiredTimeoutError(signature,outcome.timeoutMs/1e3)}}finally{clearTimeout(timeoutId);abortConfirmation()}return result}async getClusterNodes(){const unsafeRes=await this._rpcRequest("getClusterNodes",[]);const res=create(unsafeRes,jsonRpcResult(array(ContactInfoResult)));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get cluster nodes")}return res.result}async getVoteAccounts(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getVoteAccounts",args);const res=create(unsafeRes,GetVoteAccounts);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get vote accounts")}return res.result}async getSlot(commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([],commitment,undefined,config);const unsafeRes=await this._rpcRequest("getSlot",args);const res=create(unsafeRes,jsonRpcResult(number()));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get slot")}return res.result}async getSlotLeader(commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([],commitment,undefined,config);const unsafeRes=await this._rpcRequest("getSlotLeader",args);const res=create(unsafeRes,jsonRpcResult(string()));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get slot leader")}return res.result}async getSlotLeaders(startSlot,limit){const args=[startSlot,limit];const unsafeRes=await this._rpcRequest("getSlotLeaders",args);const res=create(unsafeRes,jsonRpcResult(array(PublicKeyFromString)));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get slot leaders")}return res.result}async getSignatureStatus(signature,config){const{context:context,value:values}=await this.getSignatureStatuses([signature],config);assert$1(values.length===1);const value=values[0];return{context:context,value:value}}async getSignatureStatuses(signatures,config){const params=[signatures];if(config){params.push(config)}const unsafeRes=await this._rpcRequest("getSignatureStatuses",params);const res=create(unsafeRes,GetSignatureStatusesRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get signature status")}return res.result}async getTransactionCount(commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([],commitment,undefined,config);const unsafeRes=await this._rpcRequest("getTransactionCount",args);const res=create(unsafeRes,jsonRpcResult(number()));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get transaction count")}return res.result}async getTotalSupply(commitment){const result=await this.getSupply({commitment:commitment,excludeNonCirculatingAccountsList:true});return result.value.total}async getInflationGovernor(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getInflationGovernor",args);const res=create(unsafeRes,GetInflationGovernorRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get inflation")}return res.result}async getInflationReward(addresses,epoch,commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([addresses.map((pubkey=>pubkey.toBase58()))],commitment,undefined,{...config,epoch:epoch!=null?epoch:config?.epoch});const unsafeRes=await this._rpcRequest("getInflationReward",args);const res=create(unsafeRes,GetInflationRewardResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get inflation reward")}return res.result}async getInflationRate(){const unsafeRes=await this._rpcRequest("getInflationRate",[]);const res=create(unsafeRes,GetInflationRateRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get inflation rate")}return res.result}async getEpochInfo(commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([],commitment,undefined,config);const unsafeRes=await this._rpcRequest("getEpochInfo",args);const res=create(unsafeRes,GetEpochInfoRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get epoch info")}return res.result}async getEpochSchedule(){const unsafeRes=await this._rpcRequest("getEpochSchedule",[]);const res=create(unsafeRes,GetEpochScheduleRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get epoch schedule")}const epochSchedule=res.result;return new EpochSchedule(epochSchedule.slotsPerEpoch,epochSchedule.leaderScheduleSlotOffset,epochSchedule.warmup,epochSchedule.firstNormalEpoch,epochSchedule.firstNormalSlot)}async getLeaderSchedule(){const unsafeRes=await this._rpcRequest("getLeaderSchedule",[]);const res=create(unsafeRes,GetLeaderScheduleRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get leader schedule")}return res.result}async getMinimumBalanceForRentExemption(dataLength,commitment){const args=this._buildArgs([dataLength],commitment);const unsafeRes=await this._rpcRequest("getMinimumBalanceForRentExemption",args);const res=create(unsafeRes,GetMinimumBalanceForRentExemptionRpcResult);if("error"in res){console.warn("Unable to fetch minimum balance for rent exemption");return 0}return res.result}async getRecentBlockhashAndContext(commitment){const args=this._buildArgs([],commitment);const unsafeRes=await this._rpcRequest("getRecentBlockhash",args);const res=create(unsafeRes,GetRecentBlockhashAndContextRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get recent blockhash")}return res.result}async getRecentPerformanceSamples(limit){const unsafeRes=await this._rpcRequest("getRecentPerformanceSamples",limit?[limit]:[]);const res=create(unsafeRes,GetRecentPerformanceSamplesRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get recent performance samples")}return res.result}async getFeeCalculatorForBlockhash(blockhash,commitment){const args=this._buildArgs([blockhash],commitment);const unsafeRes=await this._rpcRequest("getFeeCalculatorForBlockhash",args);const res=create(unsafeRes,GetFeeCalculatorRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get fee calculator")}const{context:context,value:value}=res.result;return{context:context,value:value!==null?value.feeCalculator:null}}async getFeeForMessage(message,commitment){const wireMessage=toBuffer(message.serialize()).toString("base64");const args=this._buildArgs([wireMessage],commitment);const unsafeRes=await this._rpcRequest("getFeeForMessage",args);const res=create(unsafeRes,jsonRpcResultAndContext(nullable(number())));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get fee for message")}if(res.result===null){throw new Error("invalid blockhash")}return res.result}async getRecentPrioritizationFees(config){const accounts=config?.lockedWritableAccounts?.map((key=>key.toBase58()));const args=accounts?.length?[accounts]:[];const unsafeRes=await this._rpcRequest("getRecentPrioritizationFees",args);const res=create(unsafeRes,GetRecentPrioritizationFeesRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get recent prioritization fees")}return res.result}async getRecentBlockhash(commitment){try{const res=await this.getRecentBlockhashAndContext(commitment);return res.value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhash(commitmentOrConfig){try{const res=await this.getLatestBlockhashAndContext(commitmentOrConfig);return res.value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhashAndContext(commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([],commitment,undefined,config);const unsafeRes=await this._rpcRequest("getLatestBlockhash",args);const res=create(unsafeRes,GetLatestBlockhashRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get latest blockhash")}return res.result}async isBlockhashValid(blockhash,rawConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(rawConfig);const args=this._buildArgs([blockhash],commitment,undefined,config);const unsafeRes=await this._rpcRequest("isBlockhashValid",args);const res=create(unsafeRes,IsBlockhashValidRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to determine if the blockhash `"+blockhash+"`is valid")}return res.result}async getVersion(){const unsafeRes=await this._rpcRequest("getVersion",[]);const res=create(unsafeRes,jsonRpcResult(VersionResult));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get version")}return res.result}async getGenesisHash(){const unsafeRes=await this._rpcRequest("getGenesisHash",[]);const res=create(unsafeRes,jsonRpcResult(string()));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get genesis hash")}return res.result}async getBlock(slot,rawConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(rawConfig);const args=this._buildArgsAtLeastConfirmed([slot],commitment,undefined,config);const unsafeRes=await this._rpcRequest("getBlock",args);try{switch(config?.transactionDetails){case"accounts":{const res=create(unsafeRes,GetAccountsModeBlockRpcResult);if("error"in res){throw res.error}return res.result}case"none":{const res=create(unsafeRes,GetNoneModeBlockRpcResult);if("error"in res){throw res.error}return res.result}default:{const res=create(unsafeRes,GetBlockRpcResult);if("error"in res){throw res.error}const{result:result}=res;return result?{...result,transactions:result.transactions.map((({transaction:transaction,meta:meta,version:version})=>({meta:meta,transaction:{...transaction,message:versionedMessageFromResponse(version,transaction.message)},version:version})))}:null}}}catch(e){throw new SolanaJSONRPCError(e,"failed to get confirmed block")}}async getParsedBlock(slot,rawConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(rawConfig);const args=this._buildArgsAtLeastConfirmed([slot],commitment,"jsonParsed",config);const unsafeRes=await this._rpcRequest("getBlock",args);try{switch(config?.transactionDetails){case"accounts":{const res=create(unsafeRes,GetParsedAccountsModeBlockRpcResult);if("error"in res){throw res.error}return res.result}case"none":{const res=create(unsafeRes,GetParsedNoneModeBlockRpcResult);if("error"in res){throw res.error}return res.result}default:{const res=create(unsafeRes,GetParsedBlockRpcResult);if("error"in res){throw res.error}return res.result}}}catch(e){throw new SolanaJSONRPCError(e,"failed to get block")}}async getBlockProduction(configOrCommitment){let extra;let commitment;if(typeof configOrCommitment==="string"){commitment=configOrCommitment}else if(configOrCommitment){const{commitment:c,...rest}=configOrCommitment;commitment=c;extra=rest}const args=this._buildArgs([],commitment,"base64",extra);const unsafeRes=await this._rpcRequest("getBlockProduction",args);const res=create(unsafeRes,BlockProductionResponseStruct);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get block production information")}return res.result}async getTransaction(signature,rawConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(rawConfig);const args=this._buildArgsAtLeastConfirmed([signature],commitment,undefined,config);const unsafeRes=await this._rpcRequest("getTransaction",args);const res=create(unsafeRes,GetTransactionRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get transaction")}const result=res.result;if(!result)return result;return{...result,transaction:{...result.transaction,message:versionedMessageFromResponse(result.version,result.transaction.message)}}}async getParsedTransaction(signature,commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed",config);const unsafeRes=await this._rpcRequest("getTransaction",args);const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get transaction")}return res.result}async getParsedTransactions(signatures,commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const batch=signatures.map((signature=>{const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed",config);return{methodName:"getTransaction",args:args}}));const unsafeRes=await this._rpcBatchRequest(batch);const res=unsafeRes.map((unsafeRes=>{const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get transactions")}return res.result}));return res}async getTransactions(signatures,commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const batch=signatures.map((signature=>{const args=this._buildArgsAtLeastConfirmed([signature],commitment,undefined,config);return{methodName:"getTransaction",args:args}}));const unsafeRes=await this._rpcBatchRequest(batch);const res=unsafeRes.map((unsafeRes=>{const res=create(unsafeRes,GetTransactionRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get transactions")}const result=res.result;if(!result)return result;return{...result,transaction:{...result.transaction,message:versionedMessageFromResponse(result.version,result.transaction.message)}}}));return res}async getConfirmedBlock(slot,commitment){const args=this._buildArgsAtLeastConfirmed([slot],commitment);const unsafeRes=await this._rpcRequest("getConfirmedBlock",args);const res=create(unsafeRes,GetConfirmedBlockRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get confirmed block")}const result=res.result;if(!result){throw new Error("Confirmed block "+slot+" not found")}const block={...result,transactions:result.transactions.map((({transaction:transaction,meta:meta})=>{const message=new Message(transaction.message);return{meta:meta,transaction:{...transaction,message:message}}}))};return{...block,transactions:block.transactions.map((({transaction:transaction,meta:meta})=>({meta:meta,transaction:Transaction.populate(transaction.message,transaction.signatures)})))}}async getBlocks(startSlot,endSlot,commitment){const args=this._buildArgsAtLeastConfirmed(endSlot!==undefined?[startSlot,endSlot]:[startSlot],commitment);const unsafeRes=await this._rpcRequest("getBlocks",args);const res=create(unsafeRes,jsonRpcResult(array(number())));if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get blocks")}return res.result}async getBlockSignatures(slot,commitment){const args=this._buildArgsAtLeastConfirmed([slot],commitment,undefined,{transactionDetails:"signatures",rewards:false});const unsafeRes=await this._rpcRequest("getBlock",args);const res=create(unsafeRes,GetBlockSignaturesRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get block")}const result=res.result;if(!result){throw new Error("Block "+slot+" not found")}return result}async getConfirmedBlockSignatures(slot,commitment){const args=this._buildArgsAtLeastConfirmed([slot],commitment,undefined,{transactionDetails:"signatures",rewards:false});const unsafeRes=await this._rpcRequest("getConfirmedBlock",args);const res=create(unsafeRes,GetBlockSignaturesRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get confirmed block")}const result=res.result;if(!result){throw new Error("Confirmed block "+slot+" not found")}return result}async getConfirmedTransaction(signature,commitment){const args=this._buildArgsAtLeastConfirmed([signature],commitment);const unsafeRes=await this._rpcRequest("getConfirmedTransaction",args);const res=create(unsafeRes,GetTransactionRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get transaction")}const result=res.result;if(!result)return result;const message=new Message(result.transaction.message);const signatures=result.transaction.signatures;return{...result,transaction:Transaction.populate(message,signatures)}}async getParsedConfirmedTransaction(signature,commitment){const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed");const unsafeRes=await this._rpcRequest("getConfirmedTransaction",args);const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get confirmed transaction")}return res.result}async getParsedConfirmedTransactions(signatures,commitment){const batch=signatures.map((signature=>{const args=this._buildArgsAtLeastConfirmed([signature],commitment,"jsonParsed");return{methodName:"getConfirmedTransaction",args:args}}));const unsafeRes=await this._rpcBatchRequest(batch);const res=unsafeRes.map((unsafeRes=>{const res=create(unsafeRes,GetParsedTransactionRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get confirmed transactions")}return res.result}));return res}async getConfirmedSignaturesForAddress(address,startSlot,endSlot){let options={};let firstAvailableBlock=await this.getFirstAvailableBlock();while(!("until"in options)){startSlot--;if(startSlot<=0||startSlot<firstAvailableBlock){break}try{const block=await this.getConfirmedBlockSignatures(startSlot,"finalized");if(block.signatures.length>0){options.until=block.signatures[block.signatures.length-1].toString()}}catch(err){if(err instanceof Error&&err.message.includes("skipped")){continue}else{throw err}}}let highestConfirmedRoot=await this.getSlot("finalized");while(!("before"in options)){endSlot++;if(endSlot>highestConfirmedRoot){break}try{const block=await this.getConfirmedBlockSignatures(endSlot);if(block.signatures.length>0){options.before=block.signatures[block.signatures.length-1].toString()}}catch(err){if(err instanceof Error&&err.message.includes("skipped")){continue}else{throw err}}}const confirmedSignatureInfo=await this.getConfirmedSignaturesForAddress2(address,options);return confirmedSignatureInfo.map((info=>info.signature))}async getConfirmedSignaturesForAddress2(address,options,commitment){const args=this._buildArgsAtLeastConfirmed([address.toBase58()],commitment,undefined,options);const unsafeRes=await this._rpcRequest("getConfirmedSignaturesForAddress2",args);const res=create(unsafeRes,GetConfirmedSignaturesForAddress2RpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get confirmed signatures for address")}return res.result}async getSignaturesForAddress(address,options,commitment){const args=this._buildArgsAtLeastConfirmed([address.toBase58()],commitment,undefined,options);const unsafeRes=await this._rpcRequest("getSignaturesForAddress",args);const res=create(unsafeRes,GetSignaturesForAddressRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,"failed to get signatures for address")}return res.result}async getAddressLookupTable(accountKey,config){const{context:context,value:accountInfo}=await this.getAccountInfoAndContext(accountKey,config);let value=null;if(accountInfo!==null){value=new AddressLookupTableAccount({key:accountKey,state:AddressLookupTableAccount.deserialize(accountInfo.data)})}return{context:context,value:value}}async getNonceAndContext(nonceAccount,commitmentOrConfig){const{context:context,value:accountInfo}=await this.getAccountInfoAndContext(nonceAccount,commitmentOrConfig);let value=null;if(accountInfo!==null){value=NonceAccount.fromAccountData(accountInfo.data)}return{context:context,value:value}}async getNonce(nonceAccount,commitmentOrConfig){return await this.getNonceAndContext(nonceAccount,commitmentOrConfig).then((x=>x.value)).catch((e=>{throw new Error("failed to get nonce for account "+nonceAccount.toBase58()+": "+e)}))}async requestAirdrop(to,lamports){const unsafeRes=await this._rpcRequest("requestAirdrop",[to.toBase58(),lamports]);const res=create(unsafeRes,RequestAirdropRpcResult);if("error"in res){throw new SolanaJSONRPCError(res.error,`airdrop to ${to.toBase58()} failed`)}return res.result}async _blockhashWithExpiryBlockHeight(disableCache){if(!disableCache){while(this._pollingBlockhash){await sleep(100)}const timeSinceFetch=Date.now()-this._blockhashInfo.lastFetch;const expired=timeSinceFetch>=BLOCKHASH_CACHE_TIMEOUT_MS;if(this._blockhashInfo.latestBlockhash!==null&&!expired){return this._blockhashInfo.latestBlockhash}}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=true;try{const startTime=Date.now();const cachedLatestBlockhash=this._blockhashInfo.latestBlockhash;const cachedBlockhash=cachedLatestBlockhash?cachedLatestBlockhash.blockhash:null;for(let i=0;i<50;i++){const latestBlockhash=await this.getLatestBlockhash("finalized");if(cachedBlockhash!==latestBlockhash.blockhash){this._blockhashInfo={latestBlockhash:latestBlockhash,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]};return latestBlockhash}await sleep(MS_PER_SLOT/2)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-startTime}ms`)}finally{this._pollingBlockhash=false}}async getStakeMinimumDelegation(config){const{commitment:commitment,config:configArg}=extractCommitmentFromConfig(config);const args=this._buildArgs([],commitment,"base64",configArg);const unsafeRes=await this._rpcRequest("getStakeMinimumDelegation",args);const res=create(unsafeRes,jsonRpcResultAndContext(number()));if("error"in res){throw new SolanaJSONRPCError(res.error,`failed to get stake minimum delegation`)}return res.result}async simulateTransaction(transactionOrMessage,configOrSigners,includeAccounts){if("message"in transactionOrMessage){const versionedTx=transactionOrMessage;const wireTransaction=versionedTx.serialize();const encodedTransaction=bufferExports.Buffer.from(wireTransaction).toString("base64");if(Array.isArray(configOrSigners)||includeAccounts!==undefined){throw new Error("Invalid arguments")}const config=configOrSigners||{};config.encoding="base64";if(!("commitment"in config)){config.commitment=this.commitment}if(configOrSigners&&typeof configOrSigners==="object"&&"innerInstructions"in configOrSigners){config.innerInstructions=configOrSigners.innerInstructions}const args=[encodedTransaction,config];const unsafeRes=await this._rpcRequest("simulateTransaction",args);const res=create(unsafeRes,SimulatedTransactionResponseStruct);if("error"in res){throw new Error("failed to simulate transaction: "+res.error.message)}return res.result}let transaction;if(transactionOrMessage instanceof Transaction){let originalTx=transactionOrMessage;transaction=new Transaction;transaction.feePayer=originalTx.feePayer;transaction.instructions=transactionOrMessage.instructions;transaction.nonceInfo=originalTx.nonceInfo;transaction.signatures=originalTx.signatures}else{transaction=Transaction.populate(transactionOrMessage);transaction._message=transaction._json=undefined}if(configOrSigners!==undefined&&!Array.isArray(configOrSigners)){throw new Error("Invalid arguments")}const signers=configOrSigners;if(transaction.nonceInfo&&signers){transaction.sign(...signers)}else{let disableCache=this._disableBlockhashCaching;for(;;){const latestBlockhash=await this._blockhashWithExpiryBlockHeight(disableCache);transaction.lastValidBlockHeight=latestBlockhash.lastValidBlockHeight;transaction.recentBlockhash=latestBlockhash.blockhash;if(!signers)break;transaction.sign(...signers);if(!transaction.signature){throw new Error("!signature")}const signature=transaction.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(signature)&&!this._blockhashInfo.transactionSignatures.includes(signature)){this._blockhashInfo.simulatedSignatures.push(signature);break}else{disableCache=true}}}const message=transaction._compile();const signData=message.serialize();const wireTransaction=transaction._serialize(signData);const encodedTransaction=wireTransaction.toString("base64");const config={encoding:"base64",commitment:this.commitment};if(includeAccounts){const addresses=(Array.isArray(includeAccounts)?includeAccounts:message.nonProgramIds()).map((key=>key.toBase58()));config["accounts"]={encoding:"base64",addresses:addresses}}if(signers){config.sigVerify=true}if(configOrSigners&&typeof configOrSigners==="object"&&"innerInstructions"in configOrSigners){config.innerInstructions=configOrSigners.innerInstructions}const args=[encodedTransaction,config];const unsafeRes=await this._rpcRequest("simulateTransaction",args);const res=create(unsafeRes,SimulatedTransactionResponseStruct);if("error"in res){let logs;if("data"in res.error){logs=res.error.data.logs;if(logs&&Array.isArray(logs)){const traceIndent="\n ";const logTrace=traceIndent+logs.join(traceIndent);console.error(res.error.message,logTrace)}}throw new SendTransactionError({action:"simulate",signature:"",transactionMessage:res.error.message,logs:logs})}return res.result}async sendTransaction(transaction,signersOrOptions,options){if("version"in transaction){if(signersOrOptions&&Array.isArray(signersOrOptions)){throw new Error("Invalid arguments")}const wireTransaction=transaction.serialize();return await this.sendRawTransaction(wireTransaction,signersOrOptions)}if(signersOrOptions===undefined||!Array.isArray(signersOrOptions)){throw new Error("Invalid arguments")}const signers=signersOrOptions;if(transaction.nonceInfo){transaction.sign(...signers)}else{let disableCache=this._disableBlockhashCaching;for(;;){const latestBlockhash=await this._blockhashWithExpiryBlockHeight(disableCache);transaction.lastValidBlockHeight=latestBlockhash.lastValidBlockHeight;transaction.recentBlockhash=latestBlockhash.blockhash;transaction.sign(...signers);if(!transaction.signature){throw new Error("!signature")}const signature=transaction.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(signature)){this._blockhashInfo.transactionSignatures.push(signature);break}else{disableCache=true}}}const wireTransaction=transaction.serialize();return await this.sendRawTransaction(wireTransaction,options)}async sendRawTransaction(rawTransaction,options){const encodedTransaction=toBuffer(rawTransaction).toString("base64");const result=await this.sendEncodedTransaction(encodedTransaction,options);return result}async sendEncodedTransaction(encodedTransaction,options){const config={encoding:"base64"};const skipPreflight=options&&options.skipPreflight;const preflightCommitment=skipPreflight===true?"processed":options&&options.preflightCommitment||this.commitment;if(options&&options.maxRetries!=null){config.maxRetries=options.maxRetries}if(options&&options.minContextSlot!=null){config.minContextSlot=options.minContextSlot}if(skipPreflight){config.skipPreflight=skipPreflight}if(preflightCommitment){config.preflightCommitment=preflightCommitment}const args=[encodedTransaction,config];const unsafeRes=await this._rpcRequest("sendTransaction",args);const res=create(unsafeRes,SendTransactionRpcResult);if("error"in res){let logs=undefined;if("data"in res.error){logs=res.error.data.logs}throw new SendTransactionError({action:skipPreflight?"send":"simulate",signature:"",transactionMessage:res.error.message,logs:logs})}return res.result}_wsOnOpen(){this._rpcWebSocketConnected=true;this._rpcWebSocketHeartbeat=setInterval((()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch{}})()}),5e3);this._updateSubscriptions()}_wsOnError(err){this._rpcWebSocketConnected=false;console.error("ws error:",err.message)}_wsOnClose(code){this._rpcWebSocketConnected=false;this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER;if(this._rpcWebSocketIdleTimeout){clearTimeout(this._rpcWebSocketIdleTimeout);this._rpcWebSocketIdleTimeout=null}if(this._rpcWebSocketHeartbeat){clearInterval(this._rpcWebSocketHeartbeat);this._rpcWebSocketHeartbeat=null}if(code===1e3){this._updateSubscriptions();return}this._subscriptionCallbacksByServerSubscriptionId={};Object.entries(this._subscriptionsByHash).forEach((([hash,subscription])=>{this._setSubscription(hash,{...subscription,state:"pending"})}))}_setSubscription(hash,nextSubscription){const prevState=this._subscriptionsByHash[hash]?.state;this._subscriptionsByHash[hash]=nextSubscription;if(prevState!==nextSubscription.state){const stateChangeCallbacks=this._subscriptionStateChangeCallbacksByHash[hash];if(stateChangeCallbacks){stateChangeCallbacks.forEach((cb=>{try{cb(nextSubscription.state)}catch{}}))}}}_onSubscriptionStateChange(clientSubscriptionId,callback){const hash=this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];if(hash==null){return()=>{}}const stateChangeCallbacks=this._subscriptionStateChangeCallbacksByHash[hash]||=new Set;stateChangeCallbacks.add(callback);return()=>{stateChangeCallbacks.delete(callback);if(stateChangeCallbacks.size===0){delete this._subscriptionStateChangeCallbacksByHash[hash]}}}async _updateSubscriptions(){if(Object.keys(this._subscriptionsByHash).length===0){if(this._rpcWebSocketConnected){this._rpcWebSocketConnected=false;this._rpcWebSocketIdleTimeout=setTimeout((()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(err){if(err instanceof Error){console.log(`Error when closing socket connection: ${err.message}`)}}}),500)}return}if(this._rpcWebSocketIdleTimeout!==null){clearTimeout(this._rpcWebSocketIdleTimeout);this._rpcWebSocketIdleTimeout=null;this._rpcWebSocketConnected=true}if(!this._rpcWebSocketConnected){this._rpcWebSocket.connect();return}const activeWebSocketGeneration=this._rpcWebSocketGeneration;const isCurrentConnectionStillActive=()=>activeWebSocketGeneration===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map((async hash=>{const subscription=this._subscriptionsByHash[hash];if(subscription===undefined){return}switch(subscription.state){case"pending":case"unsubscribed":if(subscription.callbacks.size===0){delete this._subscriptionsByHash[hash];if(subscription.state==="unsubscribed"){delete this._subscriptionCallbacksByServerSubscriptionId[subscription.serverSubscriptionId]}await this._updateSubscriptions();return}await(async()=>{const{args:args,method:method}=subscription;try{this._setSubscription(hash,{...subscription,state:"subscribing"});const serverSubscriptionId=await this._rpcWebSocket.call(method,args);this._setSubscription(hash,{...subscription,serverSubscriptionId:serverSubscriptionId,state:"subscribed"});this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId]=subscription.callbacks;await this._updateSubscriptions()}catch(e){console.error(`Received ${e instanceof Error?"":"JSON-RPC "}error calling \`${method}\``,{args:args,error:e});if(!isCurrentConnectionStillActive()){return}this._setSubscription(hash,{...subscription,state:"pending"});await this._updateSubscriptions()}})();break;case"subscribed":if(subscription.callbacks.size===0){await(async()=>{const{serverSubscriptionId:serverSubscriptionId,unsubscribeMethod:unsubscribeMethod}=subscription;if(this._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId)){this._subscriptionsAutoDisposedByRpc.delete(serverSubscriptionId)}else{this._setSubscription(hash,{...subscription,state:"unsubscribing"});this._setSubscription(hash,{...subscription,state:"unsubscribing"});try{await this._rpcWebSocket.call(unsubscribeMethod,[serverSubscriptionId])}catch(e){if(e instanceof Error){console.error(`${unsubscribeMethod} error:`,e.message)}if(!isCurrentConnectionStillActive()){return}this._setSubscription(hash,{...subscription,state:"subscribed"});await this._updateSubscriptions();return}}this._setSubscription(hash,{...subscription,state:"unsubscribed"});await this._updateSubscriptions()})()}break}})))}_handleServerNotification(serverSubscriptionId,callbackArgs){const callbacks=this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId];if(callbacks===undefined){return}callbacks.forEach((cb=>{try{cb(...callbackArgs)}catch(e){console.error(e)}}))}_wsOnAccountNotification(notification){const{result:result,subscription:subscription}=create(notification,AccountNotificationResult);this._handleServerNotification(subscription,[result.value,result.context])}_makeSubscription(subscriptionConfig,args){const clientSubscriptionId=this._nextClientSubscriptionId++;const hash=fastStableStringify([subscriptionConfig.method,args]);const existingSubscription=this._subscriptionsByHash[hash];if(existingSubscription===undefined){this._subscriptionsByHash[hash]={...subscriptionConfig,args:args,callbacks:new Set([subscriptionConfig.callback]),state:"pending"}}else{existingSubscription.callbacks.add(subscriptionConfig.callback)}this._subscriptionHashByClientSubscriptionId[clientSubscriptionId]=hash;this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId];delete this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];const subscription=this._subscriptionsByHash[hash];assert$1(subscription!==undefined,`Could not find a \`Subscription\` when tearing down client subscription #${clientSubscriptionId}`);subscription.callbacks.delete(subscriptionConfig.callback);await this._updateSubscriptions()};this._updateSubscriptions();return clientSubscriptionId}onAccountChange(publicKey,callback,commitmentOrConfig){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([publicKey.toBase58()],commitment||this._commitment||"finalized","base64",config);return this._makeSubscription({callback:callback,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},args)}async removeAccountChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"account change")}_wsOnProgramAccountNotification(notification){const{result:result,subscription:subscription}=create(notification,ProgramAccountNotificationResult);this._handleServerNotification(subscription,[{accountId:result.value.pubkey,accountInfo:result.value.account},result.context])}onProgramAccountChange(programId,callback,commitmentOrConfig,maybeFilters){const{commitment:commitment,config:config}=extractCommitmentFromConfig(commitmentOrConfig);const args=this._buildArgs([programId.toBase58()],commitment||this._commitment||"finalized","base64",config?config:maybeFilters?{filters:applyDefaultMemcmpEncodingToFilters(maybeFilters)}:undefined);return this._makeSubscription({callback:callback,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},args)}async removeProgramAccountChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"program account change")}onLogs(filter,callback,commitment){const args=this._buildArgs([typeof filter==="object"?{mentions:[filter.toString()]}:filter],commitment||this._commitment||"finalized");return this._makeSubscription({callback:callback,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},args)}async removeOnLogsListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"logs")}_wsOnLogsNotification(notification){const{result:result,subscription:subscription}=create(notification,LogsNotificationResult);this._handleServerNotification(subscription,[result.value,result.context])}_wsOnSlotNotification(notification){const{result:result,subscription:subscription}=create(notification,SlotNotificationResult);this._handleServerNotification(subscription,[result])}onSlotChange(callback){return this._makeSubscription({callback:callback,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"slot change")}_wsOnSlotUpdatesNotification(notification){const{result:result,subscription:subscription}=create(notification,SlotUpdateNotificationResult);this._handleServerNotification(subscription,[result])}onSlotUpdate(callback){return this._makeSubscription({callback:callback,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"slot update")}async _unsubscribeClientSubscription(clientSubscriptionId,subscriptionName){const dispose=this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId];if(dispose){await dispose()}else{console.warn("Ignored unsubscribe request because an active subscription with id "+`\`${clientSubscriptionId}\` for '${subscriptionName}' events `+"could not be found.")}}_buildArgs(args,override,encoding,extra){const commitment=override||this._commitment;if(commitment||encoding||extra){let options={};if(encoding){options.encoding=encoding}if(commitment){options.commitment=commitment}if(extra){options=Object.assign(options,extra)}args.push(options)}return args}_buildArgsAtLeastConfirmed(args,override,encoding,extra){const commitment=override||this._commitment;if(commitment&&!["confirmed","finalized"].includes(commitment)){throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`")}return this._buildArgs(args,override,encoding,extra)}_wsOnSignatureNotification(notification){const{result:result,subscription:subscription}=create(notification,SignatureNotificationResult);if(result.value!=="receivedSignature"){this._subscriptionsAutoDisposedByRpc.add(subscription)}this._handleServerNotification(subscription,result.value==="receivedSignature"?[{type:"received"},result.context]:[{type:"status",result:result.value},result.context])}onSignature(signature,callback,commitment){const args=this._buildArgs([signature],commitment||this._commitment||"finalized");const clientSubscriptionId=this._makeSubscription({callback:(notification,context)=>{if(notification.type==="status"){callback(notification.result,context);try{this.removeSignatureListener(clientSubscriptionId)}catch(_err){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},args);return clientSubscriptionId}onSignatureWithOptions(signature,callback,options){const{commitment:commitment,...extra}={...options,commitment:options&&options.commitment||this._commitment||"finalized"};const args=this._buildArgs([signature],commitment,undefined,extra);const clientSubscriptionId=this._makeSubscription({callback:(notification,context)=>{callback(notification,context);try{this.removeSignatureListener(clientSubscriptionId)}catch(_err){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},args);return clientSubscriptionId}async removeSignatureListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"signature result")}_wsOnRootNotification(notification){const{result:result,subscription:subscription}=create(notification,RootNotificationResult);this._handleServerNotification(subscription,[result])}onRootChange(callback){return this._makeSubscription({callback:callback,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(clientSubscriptionId){await this._unsubscribeClientSubscription(clientSubscriptionId,"root change")}}class Keypair{constructor(keypair){this._keypair=void 0;this._keypair=keypair??generateKeypair()}static generate(){return new Keypair(generateKeypair())}static fromSecretKey(secretKey,options){if(secretKey.byteLength!==64){throw new Error("bad secret key size")}const publicKey=secretKey.slice(32,64);if(!options||!options.skipValidation){const privateScalar=secretKey.slice(0,32);const computedPublicKey=getPublicKey(privateScalar);for(let ii=0;ii<32;ii++){if(publicKey[ii]!==computedPublicKey[ii]){throw new Error("provided secretKey is invalid")}}}return new Keypair({publicKey:publicKey,secretKey:secretKey})}static fromSeed(seed){const publicKey=getPublicKey(seed);const secretKey=new Uint8Array(64);secretKey.set(seed);secretKey.set(publicKey,32);return new Keypair({publicKey:publicKey,secretKey:secretKey})}get publicKey(){return new PublicKey(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}const LOOKUP_TABLE_INSTRUCTION_LAYOUTS=Object.freeze({CreateLookupTable:{index:0,layout:LayoutExports.struct([LayoutExports.u32("instruction"),u64("recentSlot"),LayoutExports.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:LayoutExports.struct([LayoutExports.u32("instruction")])},ExtendLookupTable:{index:2,layout:LayoutExports.struct([LayoutExports.u32("instruction"),u64(),LayoutExports.seq(publicKey(),LayoutExports.offset(LayoutExports.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:LayoutExports.struct([LayoutExports.u32("instruction")])},CloseLookupTable:{index:4,layout:LayoutExports.struct([LayoutExports.u32("instruction")])}});class AddressLookupTableInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const instructionTypeLayout=LayoutExports.u32("instruction");const index=instructionTypeLayout.decode(instruction.data);let type;for(const[layoutType,layout]of Object.entries(LOOKUP_TABLE_INSTRUCTION_LAYOUTS)){if(layout.index==index){type=layoutType;break}}if(!type){throw new Error("Invalid Instruction. Should be a LookupTable Instruction")}return type}static decodeCreateLookupTable(instruction){this.checkProgramId(instruction.programId);this.checkKeysLength(instruction.keys,4);const{recentSlot:recentSlot}=decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable,instruction.data);return{authority:instruction.keys[1].pubkey,payer:instruction.keys[2].pubkey,recentSlot:Number(recentSlot)}}static decodeExtendLookupTable(instruction){this.checkProgramId(instruction.programId);if(instruction.keys.length<2){throw new Error(`invalid instruction; found ${instruction.keys.length} keys, expected at least 2`)}const{addresses:addresses}=decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable,instruction.data);return{lookupTable:instruction.keys[0].pubkey,authority:instruction.keys[1].pubkey,payer:instruction.keys.length>2?instruction.keys[2].pubkey:undefined,addresses:addresses.map((buffer=>new PublicKey(buffer)))}}static decodeCloseLookupTable(instruction){this.checkProgramId(instruction.programId);this.checkKeysLength(instruction.keys,3);return{lookupTable:instruction.keys[0].pubkey,authority:instruction.keys[1].pubkey,recipient:instruction.keys[2].pubkey}}static decodeFreezeLookupTable(instruction){this.checkProgramId(instruction.programId);this.checkKeysLength(instruction.keys,2);return{lookupTable:instruction.keys[0].pubkey,authority:instruction.keys[1].pubkey}}static decodeDeactivateLookupTable(instruction){this.checkProgramId(instruction.programId);this.checkKeysLength(instruction.keys,2);return{lookupTable:instruction.keys[0].pubkey,authority:instruction.keys[1].pubkey}}static checkProgramId(programId){if(!programId.equals(AddressLookupTableProgram.programId)){throw new Error("invalid instruction; programId is not AddressLookupTable Program")}}static checkKeysLength(keys,expectedLength){if(keys.length<expectedLength){throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`)}}}class AddressLookupTableProgram{constructor(){}static createLookupTable(params){const[lookupTableAddress,bumpSeed]=PublicKey.findProgramAddressSync([params.authority.toBuffer(),browserExports$1.toBufferLE(BigInt(params.recentSlot),8)],this.programId);const type=LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable;const data=encodeData(type,{recentSlot:BigInt(params.recentSlot),bumpSeed:bumpSeed});const keys=[{pubkey:lookupTableAddress,isSigner:false,isWritable:true},{pubkey:params.authority,isSigner:true,isWritable:false},{pubkey:params.payer,isSigner:true,isWritable:true},{pubkey:SystemProgram.programId,isSigner:false,isWritable:false}];return[new TransactionInstruction({programId:this.programId,keys:keys,data:data}),lookupTableAddress]}static freezeLookupTable(params){const type=LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable;const data=encodeData(type);const keys=[{pubkey:params.lookupTable,isSigner:false,isWritable:true},{pubkey:params.authority,isSigner:true,isWritable:false}];return new TransactionInstruction({programId:this.programId,keys:keys,data:data})}static extendLookupTable(params){const type=LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable;const data=encodeData(type,{addresses:params.addresses.map((addr=>addr.toBytes()))});const keys=[{pubkey:params.lookupTable,isSigner:false,isWritable:true},{pubkey:params.authority,isSigner:true,isWritable:false}];if(params.payer){keys.push({pubkey:params.payer,isSigner:true,isWritable:true},{pubkey:SystemProgram.programId,isSigner:false,isWritable:false})}return new TransactionInstruction({programId:this.programId,keys:keys,data:data})}static deactivateLookupTable(params){const type=LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable;const data=encodeData(type);const keys=[{pubkey:params.lookupTable,isSigner:false,isWritable:true},{pubkey:params.authority,isSigner:true,isWritable:false}];return new TransactionInstruction({programId:this.programId,keys:keys,data:data})}static closeLookupTable(params){const type=LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable;const data=encodeData(type);const keys=[{pubkey:params.lookupTable,isSigner:false,isWritable:true},{pubkey:params.authority,isSigner:true,isWritable:false},{pubkey:params.recipient,isSigner:false,isWritable:true}];return new TransactionInstruction({programId:this.programId,keys:keys,data:data})}}AddressLookupTableProgram.programId=new PublicKey("AddressLookupTab1e1111111111111111111111111");class ComputeBudgetInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const instructionTypeLayout=LayoutExports.u8("instruction");const typeIndex=instructionTypeLayout.decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS)){if(layout.index==typeIndex){type=ixType;break}}if(!type){throw new Error("Instruction type incorrect; not a ComputeBudgetInstruction")}return type}static decodeRequestUnits(instruction){this.checkProgramId(instruction.programId);const{units:units,additionalFee:additionalFee}=decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits,instruction.data);return{units:units,additionalFee:additionalFee}}static decodeRequestHeapFrame(instruction){this.checkProgramId(instruction.programId);const{bytes:bytes}=decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame,instruction.data);return{bytes:bytes}}static decodeSetComputeUnitLimit(instruction){this.checkProgramId(instruction.programId);const{units:units}=decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit,instruction.data);return{units:units}}static decodeSetComputeUnitPrice(instruction){this.checkProgramId(instruction.programId);const{microLamports:microLamports}=decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice,instruction.data);return{microLamports:microLamports}}static checkProgramId(programId){if(!programId.equals(ComputeBudgetProgram.programId)){throw new Error("invalid instruction; programId is not ComputeBudgetProgram")}}}const COMPUTE_BUDGET_INSTRUCTION_LAYOUTS=Object.freeze({RequestUnits:{index:0,layout:LayoutExports.struct([LayoutExports.u8("instruction"),LayoutExports.u32("units"),LayoutExports.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:LayoutExports.struct([LayoutExports.u8("instruction"),LayoutExports.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:LayoutExports.struct([LayoutExports.u8("instruction"),LayoutExports.u32("units")])},SetComputeUnitPrice:{index:3,layout:LayoutExports.struct([LayoutExports.u8("instruction"),u64("microLamports")])}});class ComputeBudgetProgram{constructor(){}static requestUnits(params){const type=COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits;const data=encodeData(type,params);return new TransactionInstruction({keys:[],programId:this.programId,data:data})}static requestHeapFrame(params){const type=COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame;const data=encodeData(type,params);return new TransactionInstruction({keys:[],programId:this.programId,data:data})}static setComputeUnitLimit(params){const type=COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit;const data=encodeData(type,params);return new TransactionInstruction({keys:[],programId:this.programId,data:data})}static setComputeUnitPrice(params){const type=COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice;const data=encodeData(type,{microLamports:BigInt(params.microLamports)});return new TransactionInstruction({keys:[],programId:this.programId,data:data})}}ComputeBudgetProgram.programId=new PublicKey("ComputeBudget111111111111111111111111111111");const PRIVATE_KEY_BYTES$1=64;const PUBLIC_KEY_BYTES$1=32;const SIGNATURE_BYTES=64;const ED25519_INSTRUCTION_LAYOUT=LayoutExports.struct([LayoutExports.u8("numSignatures"),LayoutExports.u8("padding"),LayoutExports.u16("signatureOffset"),LayoutExports.u16("signatureInstructionIndex"),LayoutExports.u16("publicKeyOffset"),LayoutExports.u16("publicKeyInstructionIndex"),LayoutExports.u16("messageDataOffset"),LayoutExports.u16("messageDataSize"),LayoutExports.u16("messageInstructionIndex")]);class Ed25519Program{constructor(){}static createInstructionWithPublicKey(params){const{publicKey:publicKey,message:message,signature:signature,instructionIndex:instructionIndex}=params;assert$1(publicKey.length===PUBLIC_KEY_BYTES$1,`Public Key must be ${PUBLIC_KEY_BYTES$1} bytes but received ${publicKey.length} bytes`);assert$1(signature.length===SIGNATURE_BYTES,`Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`);const publicKeyOffset=ED25519_INSTRUCTION_LAYOUT.span;const signatureOffset=publicKeyOffset+publicKey.length;const messageDataOffset=signatureOffset+signature.length;const numSignatures=1;const instructionData=bufferExports.Buffer.alloc(messageDataOffset+message.length);const index=instructionIndex==null?65535:instructionIndex;ED25519_INSTRUCTION_LAYOUT.encode({numSignatures:numSignatures,padding:0,signatureOffset:signatureOffset,signatureInstructionIndex:index,publicKeyOffset:publicKeyOffset,publicKeyInstructionIndex:index,messageDataOffset:messageDataOffset,messageDataSize:message.length,messageInstructionIndex:index},instructionData);instructionData.fill(publicKey,publicKeyOffset);instructionData.fill(signature,signatureOffset);instructionData.fill(message,messageDataOffset);return new TransactionInstruction({keys:[],programId:Ed25519Program.programId,data:instructionData})}static createInstructionWithPrivateKey(params){const{privateKey:privateKey,message:message,instructionIndex:instructionIndex}=params;assert$1(privateKey.length===PRIVATE_KEY_BYTES$1,`Private key must be ${PRIVATE_KEY_BYTES$1} bytes but received ${privateKey.length} bytes`);try{const keypair=Keypair.fromSecretKey(privateKey);const publicKey=keypair.publicKey.toBytes();const signature=sign(message,keypair.secretKey);return this.createInstructionWithPublicKey({publicKey:publicKey,message:message,signature:signature,instructionIndex:instructionIndex})}catch(error){throw new Error(`Error creating instruction; ${error}`)}}}Ed25519Program.programId=new PublicKey("Ed25519SigVerify111111111111111111111111111");const U32_MASK64=BigInt(2**32-1);const _32n=BigInt(32);function fromBig(n,le=false){if(le)return{h:Number(n&U32_MASK64),l:Number(n>>_32n&U32_MASK64)};return{h:Number(n>>_32n&U32_MASK64)|0,l:Number(n&U32_MASK64)|0}}function split(lst,le=false){let Ah=new Uint32Array(lst.length);let Al=new Uint32Array(lst.length);for(let i=0;i<lst.length;i++){const{h:h,l:l}=fromBig(lst[i],le);[Ah[i],Al[i]]=[h,l]}return[Ah,Al]}const rotlSH=(h,l,s)=>h<<s|l>>>32-s;const rotlSL=(h,l,s)=>l<<s|h>>>32-s;const rotlBH=(h,l,s)=>l<<s-32|h>>>64-s;const rotlBL=(h,l,s)=>h<<s-32|l>>>64-s;const SHA3_PI=[];const SHA3_ROTL=[];const _SHA3_IOTA=[];const _0n$1=BigInt(0);const _1n$2=BigInt(1);const _2n$1=BigInt(2);const _7n=BigInt(7);const _256n=BigInt(256);const _0x71n=BigInt(113);for(let round=0,R=_1n$2,x=1,y=0;round<24;round++){[x,y]=[y,(2*x+3*y)%5];SHA3_PI.push(2*(5*y+x));SHA3_ROTL.push((round+1)*(round+2)/2%64);let t=_0n$1;for(let j=0;j<7;j++){R=(R<<_1n$2^(R>>_7n)*_0x71n)%_256n;if(R&_2n$1)t^=_1n$2<<(_1n$2<<BigInt(j))-_1n$2}_SHA3_IOTA.push(t)}const[SHA3_IOTA_H,SHA3_IOTA_L]=split(_SHA3_IOTA,true);const rotlH=(h,l,s)=>s>32?rotlBH(h,l,s):rotlSH(h,l,s);const rotlL=(h,l,s)=>s>32?rotlBL(h,l,s):rotlSL(h,l,s);function keccakP(s,rounds=24){const B=new Uint32Array(5*2);for(let round=24-rounds;round<24;round++){for(let x=0;x<10;x++)B[x]=s[x]^s[x+10]^s[x+20]^s[x+30]^s[x+40];for(let x=0;x<10;x+=2){const idx1=(x+8)%10;const idx0=(x+2)%10;const B0=B[idx0];const B1=B[idx0+1];const Th=rotlH(B0,B1,1)^B[idx1];const Tl=rotlL(B0,B1,1)^B[idx1+1];for(let y=0;y<50;y+=10){s[x+y]^=Th;s[x+y+1]^=Tl}}let curH=s[2];let curL=s[3];for(let t=0;t<24;t++){const shift=SHA3_ROTL[t];const Th=rotlH(curH,curL,shift);const Tl=rotlL(curH,curL,shift);const PI=SHA3_PI[t];curH=s[PI];curL=s[PI+1];s[PI]=Th;s[PI+1]=Tl}for(let y=0;y<50;y+=10){for(let x=0;x<10;x++)B[x]=s[y+x];for(let x=0;x<10;x++)s[y+x]^=~B[(x+2)%10]&B[(x+4)%10]}s[0]^=SHA3_IOTA_H[round];s[1]^=SHA3_IOTA_L[round]}B.fill(0)}class Keccak extends Hash{constructor(blockLen,suffix,outputLen,enableXOF=false,rounds=24){super();this.blockLen=blockLen;this.suffix=suffix;this.outputLen=outputLen;this.enableXOF=enableXOF;this.rounds=rounds;this.pos=0;this.posOut=0;this.finished=false;this.destroyed=false;anumber(outputLen);if(0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200);this.state32=u32(this.state)}keccak(){if(!isLE)byteSwap32(this.state32);keccakP(this.state32,this.rounds);if(!isLE)byteSwap32(this.state32);this.posOut=0;this.pos=0}update(data){aexists(this);const{blockLen:blockLen,state:state}=this;data=toBytes(data);const len=data.length;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);for(let i=0;i<take;i++)state[this.pos++]^=data[pos++];if(this.pos===blockLen)this.keccak()}return this}finish(){if(this.finished)return;this.finished=true;const{state:state,suffix:suffix,pos:pos,blockLen:blockLen}=this;state[pos]^=suffix;if((suffix&128)!==0&&pos===blockLen-1)this.keccak();state[blockLen-1]^=128;this.keccak()}writeInto(out){aexists(this,false);abytes(out);this.finish();const bufferOut=this.state;const{blockLen:blockLen}=this;for(let pos=0,len=out.length;pos<len;){if(this.posOut>=blockLen)this.keccak();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos);this.posOut+=take;pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){anumber(bytes);return this.xofInto(new Uint8Array(bytes))}digestInto(out){aoutput(out,this);if(this.finished)throw new Error("digest() was already called");this.writeInto(out);this.destroy();return out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=true;this.state.fill(0)}_cloneInto(to){const{blockLen:blockLen,suffix:suffix,outputLen:outputLen,rounds:rounds,enableXOF:enableXOF}=this;to||(to=new Keccak(blockLen,suffix,outputLen,enableXOF,rounds));to.state32.set(this.state32);to.pos=this.pos;to.posOut=this.posOut;to.finished=this.finished;to.rounds=rounds;to.suffix=suffix;to.outputLen=outputLen;to.enableXOF=enableXOF;to.destroyed=this.destroyed;return to}}const gen=(suffix,blockLen,outputLen)=>wrapConstructor((()=>new Keccak(blockLen,suffix,outputLen)));const keccak_256=gen(1,136,256/8);const SHA256_K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);const SHA256_IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);const SHA256_W=new Uint32Array(64);class SHA256 extends HashMD$1{constructor(){super(64,32,8,false);this.A=SHA256_IV[0]|0;this.B=SHA256_IV[1]|0;this.C=SHA256_IV[2]|0;this.D=SHA256_IV[3]|0;this.E=SHA256_IV[4]|0;this.F=SHA256_IV[5]|0;this.G=SHA256_IV[6]|0;this.H=SHA256_IV[7]|0}get(){const{A:A,B:B,C:C,D:D,E:E,F:F,G:G,H:H}=this;return[A,B,C,D,E,F,G,H]}set(A,B,C,D,E,F,G,H){this.A=A|0;this.B=B|0;this.C=C|0;this.D=D|0;this.E=E|0;this.F=F|0;this.G=G|0;this.H=H|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W[i]=view.getUint32(offset,false);for(let i=16;i<64;i++){const W15=SHA256_W[i-15];const W2=SHA256_W[i-2];const s0=rotr$1(W15,7)^rotr$1(W15,18)^W15>>>3;const s1=rotr$1(W2,17)^rotr$1(W2,19)^W2>>>10;SHA256_W[i]=s1+SHA256_W[i-7]+s0+SHA256_W[i-16]|0}let{A:A,B:B,C:C,D:D,E:E,F:F,G:G,H:H}=this;for(let i=0;i<64;i++){const sigma1=rotr$1(E,6)^rotr$1(E,11)^rotr$1(E,25);const T1=H+sigma1+Chi$1(E,F,G)+SHA256_K[i]+SHA256_W[i]|0;const sigma0=rotr$1(A,2)^rotr$1(A,13)^rotr$1(A,22);const T2=sigma0+Maj$1(A,B,C)|0;H=G;G=F;F=E;E=D+T1|0;D=C;C=B;B=A;A=T1+T2|0}A=A+this.A|0;B=B+this.B|0;C=C+this.C|0;D=D+this.D|0;E=E+this.E|0;F=F+this.F|0;G=G+this.G|0;H=H+this.H|0;this.set(A,B,C,D,E,F,G,H)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0);this.buffer.fill(0)}}const sha256=wrapConstructor$1((()=>new SHA256));class HMAC extends Hash$1{constructor(hash,_key){super();this.finished=false;this.destroyed=false;ahash(hash);const key=toBytes$1(_key);this.iHash=hash.create();if(typeof this.iHash.update!=="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen;this.outputLen=this.iHash.outputLen;const blockLen=this.blockLen;const pad=new Uint8Array(blockLen);pad.set(key.length>blockLen?hash.create().update(key).digest():key);for(let i=0;i<pad.length;i++)pad[i]^=54;this.iHash.update(pad);this.oHash=hash.create();for(let i=0;i<pad.length;i++)pad[i]^=54^92;this.oHash.update(pad);pad.fill(0)}update(buf){aexists$1(this);this.iHash.update(buf);return this}digestInto(out){aexists$1(this);abytes$2(out,this.outputLen);this.finished=true;this.iHash.digestInto(out);this.oHash.update(out);this.oHash.digestInto(out);this.destroy()}digest(){const out=new Uint8Array(this.oHash.outputLen);this.digestInto(out);return out}_cloneInto(to){to||(to=Object.create(Object.getPrototypeOf(this),{}));const{oHash:oHash,iHash:iHash,finished:finished,destroyed:destroyed,blockLen:blockLen,outputLen:outputLen}=this;to=to;to.finished=finished;to.destroyed=destroyed;to.blockLen=blockLen;to.outputLen=outputLen;to.oHash=oHash._cloneInto(to.oHash);to.iHash=iHash._cloneInto(to.iHash);return to}destroy(){this.destroyed=true;this.oHash.destroy();this.iHash.destroy()}}const hmac=(hash,key,message)=>new HMAC(hash,key).update(message).digest();hmac.create=(hash,key)=>new HMAC(hash,key)+/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */;function validateSigVerOpts(opts){if(opts.lowS!==undefined)abool("lowS",opts.lowS);if(opts.prehash!==undefined)abool("prehash",opts.prehash)}function validatePointOpts(curve){const opts=validateBasic(curve);validateObject(opts,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:endo,Fp:Fp,a:a}=opts;if(endo){if(!Fp.eql(a,Fp.ZERO)){throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0")}if(typeof endo!=="object"||typeof endo.beta!=="bigint"||typeof endo.splitScalar!=="function"){throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}}return Object.freeze({...opts})}const{bytesToNumberBE:b2n,hexToBytes:h2b}=ut;const DER={Err:class DERErr extends Error{constructor(m=""){super(m)}},_tlv:{encode:(tag,data)=>{const{Err:E}=DER;if(tag<0||tag>256)throw new E("tlv.encode: wrong tag");if(data.length&1)throw new E("tlv.encode: unpadded data");const dataLen=data.length/2;const len=numberToHexUnpadded(dataLen);if(len.length/2&128)throw new E("tlv.encode: long form length too big");const lenLen=dataLen>127?numberToHexUnpadded(len.length/2|128):"";const t=numberToHexUnpadded(tag);return t+lenLen+len+data},decode(tag,data){const{Err:E}=DER;let pos=0;if(tag<0||tag>256)throw new E("tlv.encode: wrong tag");if(data.length<2||data[pos++]!==tag)throw new E("tlv.decode: wrong tlv");const first=data[pos++];const isLong=!!(first&128);let length=0;if(!isLong)length=first;else{const lenLen=first&127;if(!lenLen)throw new E("tlv.decode(long): indefinite length not supported");if(lenLen>4)throw new E("tlv.decode(long): byte length is too big");const lengthBytes=data.subarray(pos,pos+lenLen);if(lengthBytes.length!==lenLen)throw new E("tlv.decode: length bytes not complete");if(lengthBytes[0]===0)throw new E("tlv.decode(long): zero leftmost byte");for(const b of lengthBytes)length=length<<8|b;pos+=lenLen;if(length<128)throw new E("tlv.decode(long): not minimal encoding")}const v=data.subarray(pos,pos+length);if(v.length!==length)throw new E("tlv.decode: wrong value length");return{v:v,l:data.subarray(pos+length)}}},_int:{encode(num){const{Err:E}=DER;if(num<_0n)throw new E("integer: negative integers are not allowed");let hex=numberToHexUnpadded(num);if(Number.parseInt(hex[0],16)&8)hex="00"+hex;if(hex.length&1)throw new E("unexpected DER parsing assertion: unpadded hex");return hex},decode(data){const{Err:E}=DER;if(data[0]&128)throw new E("invalid signature integer: negative");if(data[0]===0&&!(data[1]&128))throw new E("invalid signature integer: unnecessary leading zero");return b2n(data)}},toSig(hex){const{Err:E,_int:int,_tlv:tlv}=DER;const data=typeof hex==="string"?h2b(hex):hex;abytes$1(data);const{v:seqBytes,l:seqLeftBytes}=tlv.decode(48,data);if(seqLeftBytes.length)throw new E("invalid signature: left bytes after parsing");const{v:rBytes,l:rLeftBytes}=tlv.decode(2,seqBytes);const{v:sBytes,l:sLeftBytes}=tlv.decode(2,rLeftBytes);if(sLeftBytes.length)throw new E("invalid signature: left bytes after parsing");return{r:int.decode(rBytes),s:int.decode(sBytes)}},hexFromSig(sig){const{_tlv:tlv,_int:int}=DER;const rs=tlv.encode(2,int.encode(sig.r));const ss=tlv.encode(2,int.encode(sig.s));const seq=rs+ss;return tlv.encode(48,seq)}};const _0n=BigInt(0),_1n$1=BigInt(1);BigInt(2);const _3n=BigInt(3);BigInt(4);function weierstrassPoints(opts){const CURVE=validatePointOpts(opts);const{Fp:Fp}=CURVE;const Fn=Field(CURVE.n,CURVE.nBitLength);const toBytes=CURVE.toBytes||((_c,point,_isCompressed)=>{const a=point.toAffine();return concatBytes(Uint8Array.from([4]),Fp.toBytes(a.x),Fp.toBytes(a.y))});const fromBytes=CURVE.fromBytes||(bytes=>{const tail=bytes.subarray(1);const x=Fp.fromBytes(tail.subarray(0,Fp.BYTES));const y=Fp.fromBytes(tail.subarray(Fp.BYTES,2*Fp.BYTES));return{x:x,y:y}});function weierstrassEquation(x){const{a:a,b:b}=CURVE;const x2=Fp.sqr(x);const x3=Fp.mul(x2,x);return Fp.add(Fp.add(x3,Fp.mul(x,a)),b)}if(!Fp.eql(Fp.sqr(CURVE.Gy),weierstrassEquation(CURVE.Gx)))throw new Error("bad generator point: equation left != right");function isWithinCurveOrder(num){return inRange(num,_1n$1,CURVE.n)}function normPrivateKeyToScalar(key){const{allowedPrivateKeyLengths:lengths,nByteLength:nByteLength,wrapPrivateKey:wrapPrivateKey,n:N}=CURVE;if(lengths&&typeof key!=="bigint"){if(isBytes$1(key))key=bytesToHex(key);if(typeof key!=="string"||!lengths.includes(key.length))throw new Error("invalid private key");key=key.padStart(nByteLength*2,"0")}let num;try{num=typeof key==="bigint"?key:bytesToNumberBE(ensureBytes("private key",key,nByteLength))}catch(error){throw new Error("invalid private key, expected hex or "+nByteLength+" bytes, got "+typeof key)}if(wrapPrivateKey)num=mod(num,N);aInRange("private key",num,_1n$1,N);return num}function assertPrjPoint(other){if(!(other instanceof Point))throw new Error("ProjectivePoint expected")}const toAffineMemo=memoized(((p,iz)=>{const{px:x,py:y,pz:z}=p;if(Fp.eql(z,Fp.ONE))return{x:x,y:y};const is0=p.is0();if(iz==null)iz=is0?Fp.ONE:Fp.inv(z);const ax=Fp.mul(x,iz);const ay=Fp.mul(y,iz);const zz=Fp.mul(z,iz);if(is0)return{x:Fp.ZERO,y:Fp.ZERO};if(!Fp.eql(zz,Fp.ONE))throw new Error("invZ was invalid");return{x:ax,y:ay}}));const assertValidMemo=memoized((p=>{if(p.is0()){if(CURVE.allowInfinityPoint&&!Fp.is0(p.py))return;throw new Error("bad point: ZERO")}const{x:x,y:y}=p.toAffine();if(!Fp.isValid(x)||!Fp.isValid(y))throw new Error("bad point: x or y not FE");const left=Fp.sqr(y);const right=weierstrassEquation(x);if(!Fp.eql(left,right))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return true}));class Point{constructor(px,py,pz){this.px=px;this.py=py;this.pz=pz;if(px==null||!Fp.isValid(px))throw new Error("x required");if(py==null||!Fp.isValid(py))throw new Error("y required");if(pz==null||!Fp.isValid(pz))throw new Error("z required");Object.freeze(this)}static fromAffine(p){const{x:x,y:y}=p||{};if(!p||!Fp.isValid(x)||!Fp.isValid(y))throw new Error("invalid affine point");if(p instanceof Point)throw new Error("projective point not allowed");const is0=i=>Fp.eql(i,Fp.ZERO);if(is0(x)&&is0(y))return Point.ZERO;return new Point(x,y,Fp.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(points){const toInv=Fp.invertBatch(points.map((p=>p.pz)));return points.map(((p,i)=>p.toAffine(toInv[i]))).map(Point.fromAffine)}static fromHex(hex){const P=Point.fromAffine(fromBytes(ensureBytes("pointHex",hex)));P.assertValidity();return P}static fromPrivateKey(privateKey){return Point.BASE.multiply(normPrivateKeyToScalar(privateKey))}static msm(points,scalars){return pippenger(Point,Fn,points,scalars)}_setWindowSize(windowSize){wnaf.setWindowSize(this,windowSize)}assertValidity(){assertValidMemo(this)}hasEvenY(){const{y:y}=this.toAffine();if(Fp.isOdd)return!Fp.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(other){assertPrjPoint(other);const{px:X1,py:Y1,pz:Z1}=this;const{px:X2,py:Y2,pz:Z2}=other;const U1=Fp.eql(Fp.mul(X1,Z2),Fp.mul(X2,Z1));const U2=Fp.eql(Fp.mul(Y1,Z2),Fp.mul(Y2,Z1));return U1&&U2}negate(){return new Point(this.px,Fp.neg(this.py),this.pz)}double(){const{a:a,b:b}=CURVE;const b3=Fp.mul(b,_3n);const{px:X1,py:Y1,pz:Z1}=this;let X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO;let t0=Fp.mul(X1,X1);let t1=Fp.mul(Y1,Y1);let t2=Fp.mul(Z1,Z1);let t3=Fp.mul(X1,Y1);t3=Fp.add(t3,t3);Z3=Fp.mul(X1,Z1);Z3=Fp.add(Z3,Z3);X3=Fp.mul(a,Z3);Y3=Fp.mul(b3,t2);Y3=Fp.add(X3,Y3);X3=Fp.sub(t1,Y3);Y3=Fp.add(t1,Y3);Y3=Fp.mul(X3,Y3);X3=Fp.mul(t3,X3);Z3=Fp.mul(b3,Z3);t2=Fp.mul(a,t2);t3=Fp.sub(t0,t2);t3=Fp.mul(a,t3);t3=Fp.add(t3,Z3);Z3=Fp.add(t0,t0);t0=Fp.add(Z3,t0);t0=Fp.add(t0,t2);t0=Fp.mul(t0,t3);Y3=Fp.add(Y3,t0);t2=Fp.mul(Y1,Z1);t2=Fp.add(t2,t2);t0=Fp.mul(t2,t3);X3=Fp.sub(X3,t0);Z3=Fp.mul(t2,t1);Z3=Fp.add(Z3,Z3);Z3=Fp.add(Z3,Z3);return new Point(X3,Y3,Z3)}add(other){assertPrjPoint(other);const{px:X1,py:Y1,pz:Z1}=this;const{px:X2,py:Y2,pz:Z2}=other;let X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO;const a=CURVE.a;const b3=Fp.mul(CURVE.b,_3n);let t0=Fp.mul(X1,X2);let t1=Fp.mul(Y1,Y2);let t2=Fp.mul(Z1,Z2);let t3=Fp.add(X1,Y1);let t4=Fp.add(X2,Y2);t3=Fp.mul(t3,t4);t4=Fp.add(t0,t1);t3=Fp.sub(t3,t4);t4=Fp.add(X1,Z1);let t5=Fp.add(X2,Z2);t4=Fp.mul(t4,t5);t5=Fp.add(t0,t2);t4=Fp.sub(t4,t5);t5=Fp.add(Y1,Z1);X3=Fp.add(Y2,Z2);t5=Fp.mul(t5,X3);X3=Fp.add(t1,t2);t5=Fp.sub(t5,X3);Z3=Fp.mul(a,t4);X3=Fp.mul(b3,t2);Z3=Fp.add(X3,Z3);X3=Fp.sub(t1,Z3);Z3=Fp.add(t1,Z3);Y3=Fp.mul(X3,Z3);t1=Fp.add(t0,t0);t1=Fp.add(t1,t0);t2=Fp.mul(a,t2);t4=Fp.mul(b3,t4);t1=Fp.add(t1,t2);t2=Fp.sub(t0,t2);t2=Fp.mul(a,t2);t4=Fp.add(t4,t2);t0=Fp.mul(t1,t4);Y3=Fp.add(Y3,t0);t0=Fp.mul(t5,t4);X3=Fp.mul(t3,X3);X3=Fp.sub(X3,t0);t0=Fp.mul(t3,t1);Z3=Fp.mul(t5,Z3);Z3=Fp.add(Z3,t0);return new Point(X3,Y3,Z3)}subtract(other){return this.add(other.negate())}is0(){return this.equals(Point.ZERO)}wNAF(n){return wnaf.wNAFCached(this,n,Point.normalizeZ)}multiplyUnsafe(sc){const{endo:endo,n:N}=CURVE;aInRange("scalar",sc,_0n,N);const I=Point.ZERO;if(sc===_0n)return I;if(this.is0()||sc===_1n$1)return this;if(!endo||wnaf.hasPrecomputes(this))return wnaf.wNAFCachedUnsafe(this,sc,Point.normalizeZ);let{k1neg:k1neg,k1:k1,k2neg:k2neg,k2:k2}=endo.splitScalar(sc);let k1p=I;let k2p=I;let d=this;while(k1>_0n||k2>_0n){if(k1&_1n$1)k1p=k1p.add(d);if(k2&_1n$1)k2p=k2p.add(d);d=d.double();k1>>=_1n$1;k2>>=_1n$1}if(k1neg)k1p=k1p.negate();if(k2neg)k2p=k2p.negate();k2p=new Point(Fp.mul(k2p.px,endo.beta),k2p.py,k2p.pz);return k1p.add(k2p)}multiply(scalar){const{endo:endo,n:N}=CURVE;aInRange("scalar",scalar,_1n$1,N);let point,fake;if(endo){const{k1neg:k1neg,k1:k1,k2neg:k2neg,k2:k2}=endo.splitScalar(scalar);let{p:k1p,f:f1p}=this.wNAF(k1);let{p:k2p,f:f2p}=this.wNAF(k2);k1p=wnaf.constTimeNegate(k1neg,k1p);k2p=wnaf.constTimeNegate(k2neg,k2p);k2p=new Point(Fp.mul(k2p.px,endo.beta),k2p.py,k2p.pz);point=k1p.add(k2p);fake=f1p.add(f2p)}else{const{p:p,f:f}=this.wNAF(scalar);point=p;fake=f}return Point.normalizeZ([point,fake])[0]}multiplyAndAddUnsafe(Q,a,b){const G=Point.BASE;const mul=(P,a)=>a===_0n||a===_1n$1||!P.equals(G)?P.multiplyUnsafe(a):P.multiply(a);const sum=mul(this,a).add(mul(Q,b));return sum.is0()?undefined:sum}toAffine(iz){return toAffineMemo(this,iz)}isTorsionFree(){const{h:cofactor,isTorsionFree:isTorsionFree}=CURVE;if(cofactor===_1n$1)return true;if(isTorsionFree)return isTorsionFree(Point,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:cofactor,clearCofactor:clearCofactor}=CURVE;if(cofactor===_1n$1)return this;if(clearCofactor)return clearCofactor(Point,this);return this.multiplyUnsafe(CURVE.h)}toRawBytes(isCompressed=true){abool("isCompressed",isCompressed);this.assertValidity();return toBytes(Point,this,isCompressed)}toHex(isCompressed=true){abool("isCompressed",isCompressed);return bytesToHex(this.toRawBytes(isCompressed))}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy,Fp.ONE);Point.ZERO=new Point(Fp.ZERO,Fp.ONE,Fp.ZERO);const _bits=CURVE.nBitLength;const wnaf=wNAF(Point,CURVE.endo?Math.ceil(_bits/2):_bits);return{CURVE:CURVE,ProjectivePoint:Point,normPrivateKeyToScalar:normPrivateKeyToScalar,weierstrassEquation:weierstrassEquation,isWithinCurveOrder:isWithinCurveOrder}}function validateOpts(curve){const opts=validateBasic(curve);validateObject(opts,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"});return Object.freeze({lowS:true,...opts})}function weierstrass(curveDef){const CURVE=validateOpts(curveDef);const{Fp:Fp,n:CURVE_ORDER}=CURVE;const compressedLen=Fp.BYTES+1;const uncompressedLen=2*Fp.BYTES+1;function modN(a){return mod(a,CURVE_ORDER)}function invN(a){return invert(a,CURVE_ORDER)}const{ProjectivePoint:Point,normPrivateKeyToScalar:normPrivateKeyToScalar,weierstrassEquation:weierstrassEquation,isWithinCurveOrder:isWithinCurveOrder}=weierstrassPoints({...CURVE,toBytes(_c,point,isCompressed){const a=point.toAffine();const x=Fp.toBytes(a.x);const cat=concatBytes;abool("isCompressed",isCompressed);if(isCompressed){return cat(Uint8Array.from([point.hasEvenY()?2:3]),x)}else{return cat(Uint8Array.from([4]),x,Fp.toBytes(a.y))}},fromBytes(bytes){const len=bytes.length;const head=bytes[0];const tail=bytes.subarray(1);if(len===compressedLen&&(head===2||head===3)){const x=bytesToNumberBE(tail);if(!inRange(x,_1n$1,Fp.ORDER))throw new Error("Point is not on curve");const y2=weierstrassEquation(x);let y;try{y=Fp.sqrt(y2)}catch(sqrtError){const suffix=sqrtError instanceof Error?": "+sqrtError.message:"";throw new Error("Point is not on curve"+suffix)}const isYOdd=(y&_1n$1)===_1n$1;const isHeadOdd=(head&1)===1;if(isHeadOdd!==isYOdd)y=Fp.neg(y);return{x:x,y:y}}else if(len===uncompressedLen&&head===4){const x=Fp.fromBytes(tail.subarray(0,Fp.BYTES));const y=Fp.fromBytes(tail.subarray(Fp.BYTES,2*Fp.BYTES));return{x:x,y:y}}else{const cl=compressedLen;const ul=uncompressedLen;throw new Error("invalid Point, expected length of "+cl+", or uncompressed "+ul+", got "+len)}}});const numToNByteStr=num=>bytesToHex(numberToBytesBE(num,CURVE.nByteLength));function isBiggerThanHalfOrder(number){const HALF=CURVE_ORDER>>_1n$1;return number>HALF}function normalizeS(s){return isBiggerThanHalfOrder(s)?modN(-s):s}const slcNum=(b,from,to)=>bytesToNumberBE(b.slice(from,to));class Signature{constructor(r,s,recovery){this.r=r;this.s=s;this.recovery=recovery;this.assertValidity()}static fromCompact(hex){const l=CURVE.nByteLength;hex=ensureBytes("compactSignature",hex,l*2);return new Signature(slcNum(hex,0,l),slcNum(hex,l,2*l))}static fromDER(hex){const{r:r,s:s}=DER.toSig(ensureBytes("DER",hex));return new Signature(r,s)}assertValidity(){aInRange("r",this.r,_1n$1,CURVE_ORDER);aInRange("s",this.s,_1n$1,CURVE_ORDER)}addRecoveryBit(recovery){return new Signature(this.r,this.s,recovery)}recoverPublicKey(msgHash){const{r:r,s:s,recovery:rec}=this;const h=bits2int_modN(ensureBytes("msgHash",msgHash));if(rec==null||![0,1,2,3].includes(rec))throw new Error("recovery id invalid");const radj=rec===2||rec===3?r+CURVE.n:r;if(radj>=Fp.ORDER)throw new Error("recovery id 2 or 3 invalid");const prefix=(rec&1)===0?"02":"03";const R=Point.fromHex(prefix+numToNByteStr(radj));const ir=invN(radj);const u1=modN(-h*ir);const u2=modN(s*ir);const Q=Point.BASE.multiplyAndAddUnsafe(R,u1,u2);if(!Q)throw new Error("point at infinify");Q.assertValidity();return Q}hasHighS(){return isBiggerThanHalfOrder(this.s)}normalizeS(){return this.hasHighS()?new Signature(this.r,modN(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){return DER.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return numToNByteStr(this.r)+numToNByteStr(this.s)}}const utils={isValidPrivateKey(privateKey){try{normPrivateKeyToScalar(privateKey);return true}catch(error){return false}},normPrivateKeyToScalar:normPrivateKeyToScalar,randomPrivateKey:()=>{const length=getMinHashLength(CURVE.n);return mapHashToField(CURVE.randomBytes(length),CURVE.n)},precompute(windowSize=8,point=Point.BASE){point._setWindowSize(windowSize);point.multiply(BigInt(3));return point}};function getPublicKey(privateKey,isCompressed=true){return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed)}function isProbPub(item){const arr=isBytes$1(item);const str=typeof item==="string";const len=(arr||str)&&item.length;if(arr)return len===compressedLen||len===uncompressedLen;if(str)return len===2*compressedLen||len===2*uncompressedLen;if(item instanceof Point)return true;return false}function getSharedSecret(privateA,publicB,isCompressed=true){if(isProbPub(privateA))throw new Error("first arg must be private key");if(!isProbPub(publicB))throw new Error("second arg must be public key");const b=Point.fromHex(publicB);return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed)}const bits2int=CURVE.bits2int||function(bytes){if(bytes.length>8192)throw new Error("input is too large");const num=bytesToNumberBE(bytes);const delta=bytes.length*8-CURVE.nBitLength;return delta>0?num>>BigInt(delta):num};const bits2int_modN=CURVE.bits2int_modN||function(bytes){return modN(bits2int(bytes))};const ORDER_MASK=bitMask(CURVE.nBitLength);function int2octets(num){aInRange("num < 2^"+CURVE.nBitLength,num,_0n,ORDER_MASK);return numberToBytesBE(num,CURVE.nByteLength)}function prepSig(msgHash,privateKey,opts=defaultSigOpts){if(["recovered","canonical"].some((k=>k in opts)))throw new Error("sign() legacy options not supported");const{hash:hash,randomBytes:randomBytes}=CURVE;let{lowS:lowS,prehash:prehash,extraEntropy:ent}=opts;if(lowS==null)lowS=true;msgHash=ensureBytes("msgHash",msgHash);validateSigVerOpts(opts);if(prehash)msgHash=ensureBytes("prehashed msgHash",hash(msgHash));const h1int=bits2int_modN(msgHash);const d=normPrivateKeyToScalar(privateKey);const seedArgs=[int2octets(d),int2octets(h1int)];if(ent!=null&&ent!==false){const e=ent===true?randomBytes(Fp.BYTES):ent;seedArgs.push(ensureBytes("extraEntropy",e))}const seed=concatBytes(...seedArgs);const m=h1int;function k2sig(kBytes){const k=bits2int(kBytes);if(!isWithinCurveOrder(k))return;const ik=invN(k);const q=Point.BASE.multiply(k).toAffine();const r=modN(q.x);if(r===_0n)return;const s=modN(ik*modN(m+r*d));if(s===_0n)return;let recovery=(q.x===r?0:2)|Number(q.y&_1n$1);let normS=s;if(lowS&&isBiggerThanHalfOrder(s)){normS=normalizeS(s);recovery^=1}return new Signature(r,normS,recovery)}return{seed:seed,k2sig:k2sig}}const defaultSigOpts={lowS:CURVE.lowS,prehash:false};const defaultVerOpts={lowS:CURVE.lowS,prehash:false};function sign(msgHash,privKey,opts=defaultSigOpts){const{seed:seed,k2sig:k2sig}=prepSig(msgHash,privKey,opts);const C=CURVE;const drbg=createHmacDrbg(C.hash.outputLen,C.nByteLength,C.hmac);return drbg(seed,k2sig)}Point.BASE._setWindowSize(8);function verify(signature,msgHash,publicKey,opts=defaultVerOpts){const sg=signature;msgHash=ensureBytes("msgHash",msgHash);publicKey=ensureBytes("publicKey",publicKey);const{lowS:lowS,prehash:prehash,format:format}=opts;validateSigVerOpts(opts);if("strict"in opts)throw new Error("options.strict was renamed to lowS");if(format!==undefined&&format!=="compact"&&format!=="der")throw new Error("format must be compact or der");const isHex=typeof sg==="string"||isBytes$1(sg);const isObj=!isHex&&!format&&typeof sg==="object"&&sg!==null&&typeof sg.r==="bigint"&&typeof sg.s==="bigint";if(!isHex&&!isObj)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let _sig=undefined;let P;try{if(isObj)_sig=new Signature(sg.r,sg.s);if(isHex){try{if(format!=="compact")_sig=Signature.fromDER(sg)}catch(derError){if(!(derError instanceof DER.Err))throw derError}if(!_sig&&format!=="der")_sig=Signature.fromCompact(sg)}P=Point.fromHex(publicKey)}catch(error){return false}if(!_sig)return false;if(lowS&&_sig.hasHighS())return false;if(prehash)msgHash=CURVE.hash(msgHash);const{r:r,s:s}=_sig;const h=bits2int_modN(msgHash);const is=invN(s);const u1=modN(h*is);const u2=modN(r*is);const R=Point.BASE.multiplyAndAddUnsafe(P,u1,u2)?.toAffine();if(!R)return false;const v=modN(R.x);return v===r}return{CURVE:CURVE,getPublicKey:getPublicKey,getSharedSecret:getSharedSecret,sign:sign,verify:verify,ProjectivePoint:Point,Signature:Signature,utils:utils}}+/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function getHash(hash){return{hash:hash,hmac:(key,...msgs)=>hmac(hash,key,concatBytes$1(...msgs)),randomBytes:randomBytes}}function createCurve(curveDef,defHash){const create=hash=>weierstrass({...curveDef,...getHash(hash)});return Object.freeze({...create(defHash),create:create})}+/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1P=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");const secp256k1N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");const _1n=BigInt(1);const _2n=BigInt(2);const divNearest=(a,b)=>(a+b/_2n)/b;function sqrtMod(y){const P=secp256k1P;const _3n=BigInt(3),_6n=BigInt(6),_11n=BigInt(11),_22n=BigInt(22);const _23n=BigInt(23),_44n=BigInt(44),_88n=BigInt(88);const b2=y*y*y%P;const b3=b2*b2*y%P;const b6=pow2(b3,_3n,P)*b3%P;const b9=pow2(b6,_3n,P)*b3%P;const b11=pow2(b9,_2n,P)*b2%P;const b22=pow2(b11,_11n,P)*b11%P;const b44=pow2(b22,_22n,P)*b22%P;const b88=pow2(b44,_44n,P)*b44%P;const b176=pow2(b88,_88n,P)*b88%P;const b220=pow2(b176,_44n,P)*b44%P;const b223=pow2(b220,_3n,P)*b3%P;const t1=pow2(b223,_23n,P)*b22%P;const t2=pow2(t1,_6n,P)*b2%P;const root=pow2(t2,_2n,P);if(!Fpk1.eql(Fpk1.sqr(root),y))throw new Error("Cannot find square root");return root}const Fpk1=Field(secp256k1P,undefined,undefined,{sqrt:sqrtMod});const secp256k1=createCurve({a:BigInt(0),b:BigInt(7),Fp:Fpk1,n:secp256k1N,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:true,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:k=>{const n=secp256k1N;const a1=BigInt("0x3086d221a7d46bcde86c90e49284eb15");const b1=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3");const a2=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");const b2=a1;const POW_2_128=BigInt("0x100000000000000000000000000000000");const c1=divNearest(b2*k,n);const c2=divNearest(-b1*k,n);let k1=mod(k-c1*a1-c2*a2,n);let k2=mod(-c1*b1-c2*b2,n);const k1neg=k1>POW_2_128;const k2neg=k2>POW_2_128;if(k1neg)k1=n-k1;if(k2neg)k2=n-k2;if(k1>POW_2_128||k2>POW_2_128){throw new Error("splitScalar: Endomorphism failed, k="+k)}return{k1neg:k1neg,k1:k1,k2neg:k2neg,k2:k2}}}},sha256);BigInt(0);secp256k1.ProjectivePoint;const ecdsaSign=(msgHash,privKey)=>{const signature=secp256k1.sign(msgHash,privKey);return[signature.toCompactRawBytes(),signature.recovery]};secp256k1.utils.isValidPrivateKey;const publicKeyCreate=secp256k1.getPublicKey;const PRIVATE_KEY_BYTES=32;const ETHEREUM_ADDRESS_BYTES=20;const PUBLIC_KEY_BYTES=64;const SIGNATURE_OFFSETS_SERIALIZED_SIZE=11;const SECP256K1_INSTRUCTION_LAYOUT=LayoutExports.struct([LayoutExports.u8("numSignatures"),LayoutExports.u16("signatureOffset"),LayoutExports.u8("signatureInstructionIndex"),LayoutExports.u16("ethAddressOffset"),LayoutExports.u8("ethAddressInstructionIndex"),LayoutExports.u16("messageDataOffset"),LayoutExports.u16("messageDataSize"),LayoutExports.u8("messageInstructionIndex"),LayoutExports.blob(20,"ethAddress"),LayoutExports.blob(64,"signature"),LayoutExports.u8("recoveryId")]);class Secp256k1Program{constructor(){}static publicKeyToEthAddress(publicKey){assert$1(publicKey.length===PUBLIC_KEY_BYTES,`Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey.length} bytes`);try{return bufferExports.Buffer.from(keccak_256(toBuffer(publicKey))).slice(-ETHEREUM_ADDRESS_BYTES)}catch(error){throw new Error(`Error constructing Ethereum address: ${error}`)}}static createInstructionWithPublicKey(params){const{publicKey:publicKey,message:message,signature:signature,recoveryId:recoveryId,instructionIndex:instructionIndex}=params;return Secp256k1Program.createInstructionWithEthAddress({ethAddress:Secp256k1Program.publicKeyToEthAddress(publicKey),message:message,signature:signature,recoveryId:recoveryId,instructionIndex:instructionIndex})}static createInstructionWithEthAddress(params){const{ethAddress:rawAddress,message:message,signature:signature,recoveryId:recoveryId,instructionIndex:instructionIndex=0}=params;let ethAddress;if(typeof rawAddress==="string"){if(rawAddress.startsWith("0x")){ethAddress=bufferExports.Buffer.from(rawAddress.substr(2),"hex")}else{ethAddress=bufferExports.Buffer.from(rawAddress,"hex")}}else{ethAddress=rawAddress}assert$1(ethAddress.length===ETHEREUM_ADDRESS_BYTES,`Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddress.length} bytes`);const dataStart=1+SIGNATURE_OFFSETS_SERIALIZED_SIZE;const ethAddressOffset=dataStart;const signatureOffset=dataStart+ethAddress.length;const messageDataOffset=signatureOffset+signature.length+1;const numSignatures=1;const instructionData=bufferExports.Buffer.alloc(SECP256K1_INSTRUCTION_LAYOUT.span+message.length);SECP256K1_INSTRUCTION_LAYOUT.encode({numSignatures:numSignatures,signatureOffset:signatureOffset,signatureInstructionIndex:instructionIndex,ethAddressOffset:ethAddressOffset,ethAddressInstructionIndex:instructionIndex,messageDataOffset:messageDataOffset,messageDataSize:message.length,messageInstructionIndex:instructionIndex,signature:toBuffer(signature),ethAddress:toBuffer(ethAddress),recoveryId:recoveryId},instructionData);instructionData.fill(toBuffer(message),SECP256K1_INSTRUCTION_LAYOUT.span);return new TransactionInstruction({keys:[],programId:Secp256k1Program.programId,data:instructionData})}static createInstructionWithPrivateKey(params){const{privateKey:pkey,message:message,instructionIndex:instructionIndex}=params;assert$1(pkey.length===PRIVATE_KEY_BYTES,`Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${pkey.length} bytes`);try{const privateKey=toBuffer(pkey);const publicKey=publicKeyCreate(privateKey,false).slice(1);const messageHash=bufferExports.Buffer.from(keccak_256(toBuffer(message)));const[signature,recoveryId]=ecdsaSign(messageHash,privateKey);return this.createInstructionWithPublicKey({publicKey:publicKey,message:message,signature:signature,recoveryId:recoveryId,instructionIndex:instructionIndex})}catch(error){throw new Error(`Error creating instruction; ${error}`)}}}Secp256k1Program.programId=new PublicKey("KeccakSecp256k11111111111111111111111111111");var _Lockup;const STAKE_CONFIG_ID=new PublicKey("StakeConfig11111111111111111111111111111111");class Authorized{constructor(staker,withdrawer){this.staker=void 0;this.withdrawer=void 0;this.staker=staker;this.withdrawer=withdrawer}}class Lockup{constructor(unixTimestamp,epoch,custodian){this.unixTimestamp=void 0;this.epoch=void 0;this.custodian=void 0;this.unixTimestamp=unixTimestamp;this.epoch=epoch;this.custodian=custodian}}_Lockup=Lockup;Lockup.default=new _Lockup(0,0,PublicKey.default);class StakeInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const instructionTypeLayout=LayoutExports.u32("instruction");const typeIndex=instructionTypeLayout.decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(STAKE_INSTRUCTION_LAYOUTS)){if(layout.index==typeIndex){type=ixType;break}}if(!type){throw new Error("Instruction type incorrect; not a StakeInstruction")}return type}static decodeInitialize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{authorized:authorized,lockup:lockup}=decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Initialize,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,authorized:new Authorized(new PublicKey(authorized.staker),new PublicKey(authorized.withdrawer)),lockup:new Lockup(lockup.unixTimestamp,lockup.epoch,new PublicKey(lockup.custodian))}}static decodeDelegate(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,6);decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Delegate,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,votePubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[5].pubkey}}static decodeAuthorize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{newAuthorized:newAuthorized,stakeAuthorizationType:stakeAuthorizationType}=decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Authorize,instruction.data);const o={stakePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey,newAuthorizedPubkey:new PublicKey(newAuthorized),stakeAuthorizationType:{index:stakeAuthorizationType}};if(instruction.keys.length>3){o.custodianPubkey=instruction.keys[3].pubkey}return o}static decodeAuthorizeWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,2);const{newAuthorized:newAuthorized,stakeAuthorizationType:stakeAuthorizationType,authoritySeed:authoritySeed,authorityOwner:authorityOwner}=decodeData$1(STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,instruction.data);const o={stakePubkey:instruction.keys[0].pubkey,authorityBase:instruction.keys[1].pubkey,authoritySeed:authoritySeed,authorityOwner:new PublicKey(authorityOwner),newAuthorizedPubkey:new PublicKey(newAuthorized),stakeAuthorizationType:{index:stakeAuthorizationType}};if(instruction.keys.length>3){o.custodianPubkey=instruction.keys[3].pubkey}return o}static decodeSplit(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{lamports:lamports}=decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Split,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,splitStakePubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[2].pubkey,lamports:lamports}}static decodeMerge(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Merge,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,sourceStakePubKey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[4].pubkey}}static decodeWithdraw(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,5);const{lamports:lamports}=decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Withdraw,instruction.data);const o={stakePubkey:instruction.keys[0].pubkey,toPubkey:instruction.keys[1].pubkey,authorizedPubkey:instruction.keys[4].pubkey,lamports:lamports};if(instruction.keys.length>5){o.custodianPubkey=instruction.keys[5].pubkey}return o}static decodeDeactivate(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Deactivate,instruction.data);return{stakePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey}}static checkProgramId(programId){if(!programId.equals(StakeProgram.programId)){throw new Error("invalid instruction; programId is not StakeProgram")}}static checkKeyLength(keys,expectedLength){if(keys.length<expectedLength){throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`)}}}const STAKE_INSTRUCTION_LAYOUTS=Object.freeze({Initialize:{index:0,layout:LayoutExports.struct([LayoutExports.u32("instruction"),authorized(),lockup()])},Authorize:{index:1,layout:LayoutExports.struct([LayoutExports.u32("instruction"),publicKey("newAuthorized"),LayoutExports.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:LayoutExports.struct([LayoutExports.u32("instruction")])},Split:{index:3,layout:LayoutExports.struct([LayoutExports.u32("instruction"),LayoutExports.ns64("lamports")])},Withdraw:{index:4,layout:LayoutExports.struct([LayoutExports.u32("instruction"),LayoutExports.ns64("lamports")])},Deactivate:{index:5,layout:LayoutExports.struct([LayoutExports.u32("instruction")])},Merge:{index:7,layout:LayoutExports.struct([LayoutExports.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:LayoutExports.struct([LayoutExports.u32("instruction"),publicKey("newAuthorized"),LayoutExports.u32("stakeAuthorizationType"),rustString("authoritySeed"),publicKey("authorityOwner")])}});const StakeAuthorizationLayout=Object.freeze({Staker:{index:0},Withdrawer:{index:1}});class StakeProgram{constructor(){}static initialize(params){const{stakePubkey:stakePubkey,authorized:authorized,lockup:maybeLockup}=params;const lockup=maybeLockup||Lockup.default;const type=STAKE_INSTRUCTION_LAYOUTS.Initialize;const data=encodeData(type,{authorized:{staker:toBuffer(authorized.staker.toBuffer()),withdrawer:toBuffer(authorized.withdrawer.toBuffer())},lockup:{unixTimestamp:lockup.unixTimestamp,epoch:lockup.epoch,custodian:toBuffer(lockup.custodian.toBuffer())}});const instructionData={keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false}],programId:this.programId,data:data};return new TransactionInstruction(instructionData)}static createAccountWithSeed(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccountWithSeed({fromPubkey:params.fromPubkey,newAccountPubkey:params.stakePubkey,basePubkey:params.basePubkey,seed:params.seed,lamports:params.lamports,space:this.space,programId:this.programId}));const{stakePubkey:stakePubkey,authorized:authorized,lockup:lockup}=params;return transaction.add(this.initialize({stakePubkey:stakePubkey,authorized:authorized,lockup:lockup}))}static createAccount(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccount({fromPubkey:params.fromPubkey,newAccountPubkey:params.stakePubkey,lamports:params.lamports,space:this.space,programId:this.programId}));const{stakePubkey:stakePubkey,authorized:authorized,lockup:lockup}=params;return transaction.add(this.initialize({stakePubkey:stakePubkey,authorized:authorized,lockup:lockup}))}static delegate(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,votePubkey:votePubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Delegate;const data=encodeData(type);return(new Transaction).add({keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:votePubkey,isSigner:false,isWritable:false},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_STAKE_HISTORY_PUBKEY,isSigner:false,isWritable:false},{pubkey:STAKE_CONFIG_ID,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static authorize(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,newAuthorizedPubkey:newAuthorizedPubkey,stakeAuthorizationType:stakeAuthorizationType,custodianPubkey:custodianPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Authorize;const data=encodeData(type,{newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),stakeAuthorizationType:stakeAuthorizationType.index});const keys=[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:true},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}];if(custodianPubkey){keys.push({pubkey:custodianPubkey,isSigner:true,isWritable:false})}return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static authorizeWithSeed(params){const{stakePubkey:stakePubkey,authorityBase:authorityBase,authoritySeed:authoritySeed,authorityOwner:authorityOwner,newAuthorizedPubkey:newAuthorizedPubkey,stakeAuthorizationType:stakeAuthorizationType,custodianPubkey:custodianPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;const data=encodeData(type,{newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),stakeAuthorizationType:stakeAuthorizationType.index,authoritySeed:authoritySeed,authorityOwner:toBuffer(authorityOwner.toBuffer())});const keys=[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:authorityBase,isSigner:true,isWritable:false},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false}];if(custodianPubkey){keys.push({pubkey:custodianPubkey,isSigner:true,isWritable:false})}return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static splitInstruction(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,splitStakePubkey:splitStakePubkey,lamports:lamports}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Split;const data=encodeData(type,{lamports:lamports});return new TransactionInstruction({keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:splitStakePubkey,isSigner:false,isWritable:true},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static split(params,rentExemptReserve){const transaction=new Transaction;transaction.add(SystemProgram.createAccount({fromPubkey:params.authorizedPubkey,newAccountPubkey:params.splitStakePubkey,lamports:rentExemptReserve,space:this.space,programId:this.programId}));return transaction.add(this.splitInstruction(params))}static splitWithSeed(params,rentExemptReserve){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,splitStakePubkey:splitStakePubkey,basePubkey:basePubkey,seed:seed,lamports:lamports}=params;const transaction=new Transaction;transaction.add(SystemProgram.allocate({accountPubkey:splitStakePubkey,basePubkey:basePubkey,seed:seed,space:this.space,programId:this.programId}));if(rentExemptReserve&&rentExemptReserve>0){transaction.add(SystemProgram.transfer({fromPubkey:params.authorizedPubkey,toPubkey:splitStakePubkey,lamports:rentExemptReserve}))}return transaction.add(this.splitInstruction({stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,splitStakePubkey:splitStakePubkey,lamports:lamports}))}static merge(params){const{stakePubkey:stakePubkey,sourceStakePubKey:sourceStakePubKey,authorizedPubkey:authorizedPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Merge;const data=encodeData(type);return(new Transaction).add({keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:sourceStakePubKey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_STAKE_HISTORY_PUBKEY,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}static withdraw(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey,toPubkey:toPubkey,lamports:lamports,custodianPubkey:custodianPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Withdraw;const data=encodeData(type,{lamports:lamports});const keys=[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:toPubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_STAKE_HISTORY_PUBKEY,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}];if(custodianPubkey){keys.push({pubkey:custodianPubkey,isSigner:true,isWritable:false})}return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static deactivate(params){const{stakePubkey:stakePubkey,authorizedPubkey:authorizedPubkey}=params;const type=STAKE_INSTRUCTION_LAYOUTS.Deactivate;const data=encodeData(type);return(new Transaction).add({keys:[{pubkey:stakePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data})}}StakeProgram.programId=new PublicKey("Stake11111111111111111111111111111111111111");StakeProgram.space=200;class VoteInit{constructor(nodePubkey,authorizedVoter,authorizedWithdrawer,commission){this.nodePubkey=void 0;this.authorizedVoter=void 0;this.authorizedWithdrawer=void 0;this.commission=void 0;this.nodePubkey=nodePubkey;this.authorizedVoter=authorizedVoter;this.authorizedWithdrawer=authorizedWithdrawer;this.commission=commission}}class VoteInstruction{constructor(){}static decodeInstructionType(instruction){this.checkProgramId(instruction.programId);const instructionTypeLayout=LayoutExports.u32("instruction");const typeIndex=instructionTypeLayout.decode(instruction.data);let type;for(const[ixType,layout]of Object.entries(VOTE_INSTRUCTION_LAYOUTS)){if(layout.index==typeIndex){type=ixType;break}}if(!type){throw new Error("Instruction type incorrect; not a VoteInstruction")}return type}static decodeInitializeAccount(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,4);const{voteInit:voteInit}=decodeData$1(VOTE_INSTRUCTION_LAYOUTS.InitializeAccount,instruction.data);return{votePubkey:instruction.keys[0].pubkey,nodePubkey:instruction.keys[3].pubkey,voteInit:new VoteInit(new PublicKey(voteInit.nodePubkey),new PublicKey(voteInit.authorizedVoter),new PublicKey(voteInit.authorizedWithdrawer),voteInit.commission)}}static decodeAuthorize(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{newAuthorized:newAuthorized,voteAuthorizationType:voteAuthorizationType}=decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Authorize,instruction.data);return{votePubkey:instruction.keys[0].pubkey,authorizedPubkey:instruction.keys[2].pubkey,newAuthorizedPubkey:new PublicKey(newAuthorized),voteAuthorizationType:{index:voteAuthorizationType}}}static decodeAuthorizeWithSeed(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{voteAuthorizeWithSeedArgs:{currentAuthorityDerivedKeyOwnerPubkey:currentAuthorityDerivedKeyOwnerPubkey,currentAuthorityDerivedKeySeed:currentAuthorityDerivedKeySeed,newAuthorized:newAuthorized,voteAuthorizationType:voteAuthorizationType}}=decodeData$1(VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,instruction.data);return{currentAuthorityDerivedKeyBasePubkey:instruction.keys[2].pubkey,currentAuthorityDerivedKeyOwnerPubkey:new PublicKey(currentAuthorityDerivedKeyOwnerPubkey),currentAuthorityDerivedKeySeed:currentAuthorityDerivedKeySeed,newAuthorizedPubkey:new PublicKey(newAuthorized),voteAuthorizationType:{index:voteAuthorizationType},votePubkey:instruction.keys[0].pubkey}}static decodeWithdraw(instruction){this.checkProgramId(instruction.programId);this.checkKeyLength(instruction.keys,3);const{lamports:lamports}=decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Withdraw,instruction.data);return{votePubkey:instruction.keys[0].pubkey,authorizedWithdrawerPubkey:instruction.keys[2].pubkey,lamports:lamports,toPubkey:instruction.keys[1].pubkey}}static checkProgramId(programId){if(!programId.equals(VoteProgram.programId)){throw new Error("invalid instruction; programId is not VoteProgram")}}static checkKeyLength(keys,expectedLength){if(keys.length<expectedLength){throw new Error(`invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`)}}}const VOTE_INSTRUCTION_LAYOUTS=Object.freeze({InitializeAccount:{index:0,layout:LayoutExports.struct([LayoutExports.u32("instruction"),voteInit()])},Authorize:{index:1,layout:LayoutExports.struct([LayoutExports.u32("instruction"),publicKey("newAuthorized"),LayoutExports.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:LayoutExports.struct([LayoutExports.u32("instruction"),LayoutExports.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:LayoutExports.struct([LayoutExports.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:LayoutExports.struct([LayoutExports.u32("instruction"),voteAuthorizeWithSeedArgs()])}});const VoteAuthorizationLayout=Object.freeze({Voter:{index:0},Withdrawer:{index:1}});class VoteProgram{constructor(){}static initializeAccount(params){const{votePubkey:votePubkey,nodePubkey:nodePubkey,voteInit:voteInit}=params;const type=VOTE_INSTRUCTION_LAYOUTS.InitializeAccount;const data=encodeData(type,{voteInit:{nodePubkey:toBuffer(voteInit.nodePubkey.toBuffer()),authorizedVoter:toBuffer(voteInit.authorizedVoter.toBuffer()),authorizedWithdrawer:toBuffer(voteInit.authorizedWithdrawer.toBuffer()),commission:voteInit.commission}});const instructionData={keys:[{pubkey:votePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_RENT_PUBKEY,isSigner:false,isWritable:false},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:nodePubkey,isSigner:true,isWritable:false}],programId:this.programId,data:data};return new TransactionInstruction(instructionData)}static createAccount(params){const transaction=new Transaction;transaction.add(SystemProgram.createAccount({fromPubkey:params.fromPubkey,newAccountPubkey:params.votePubkey,lamports:params.lamports,space:this.space,programId:this.programId}));return transaction.add(this.initializeAccount({votePubkey:params.votePubkey,nodePubkey:params.voteInit.nodePubkey,voteInit:params.voteInit}))}static authorize(params){const{votePubkey:votePubkey,authorizedPubkey:authorizedPubkey,newAuthorizedPubkey:newAuthorizedPubkey,voteAuthorizationType:voteAuthorizationType}=params;const type=VOTE_INSTRUCTION_LAYOUTS.Authorize;const data=encodeData(type,{newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),voteAuthorizationType:voteAuthorizationType.index});const keys=[{pubkey:votePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:authorizedPubkey,isSigner:true,isWritable:false}];return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static authorizeWithSeed(params){const{currentAuthorityDerivedKeyBasePubkey:currentAuthorityDerivedKeyBasePubkey,currentAuthorityDerivedKeyOwnerPubkey:currentAuthorityDerivedKeyOwnerPubkey,currentAuthorityDerivedKeySeed:currentAuthorityDerivedKeySeed,newAuthorizedPubkey:newAuthorizedPubkey,voteAuthorizationType:voteAuthorizationType,votePubkey:votePubkey}=params;const type=VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;const data=encodeData(type,{voteAuthorizeWithSeedArgs:{currentAuthorityDerivedKeyOwnerPubkey:toBuffer(currentAuthorityDerivedKeyOwnerPubkey.toBuffer()),currentAuthorityDerivedKeySeed:currentAuthorityDerivedKeySeed,newAuthorized:toBuffer(newAuthorizedPubkey.toBuffer()),voteAuthorizationType:voteAuthorizationType.index}});const keys=[{pubkey:votePubkey,isSigner:false,isWritable:true},{pubkey:SYSVAR_CLOCK_PUBKEY,isSigner:false,isWritable:false},{pubkey:currentAuthorityDerivedKeyBasePubkey,isSigner:true,isWritable:false}];return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static withdraw(params){const{votePubkey:votePubkey,authorizedWithdrawerPubkey:authorizedWithdrawerPubkey,lamports:lamports,toPubkey:toPubkey}=params;const type=VOTE_INSTRUCTION_LAYOUTS.Withdraw;const data=encodeData(type,{lamports:lamports});const keys=[{pubkey:votePubkey,isSigner:false,isWritable:true},{pubkey:toPubkey,isSigner:false,isWritable:true},{pubkey:authorizedWithdrawerPubkey,isSigner:true,isWritable:false}];return(new Transaction).add({keys:keys,programId:this.programId,data:data})}static safeWithdraw(params,currentVoteAccountBalance,rentExemptMinimum){if(params.lamports>currentVoteAccountBalance-rentExemptMinimum){throw new Error("Withdraw will leave vote account with insufficient funds.")}return VoteProgram.withdraw(params)}static updateValidatorIdentity(params){const{votePubkey:votePubkey,authorizedWithdrawerPubkey:authorizedWithdrawerPubkey,nodePubkey:nodePubkey}=params;const type=VOTE_INSTRUCTION_LAYOUTS.UpdateValidatorIdentity;const data=encodeData(type);const keys=[{pubkey:votePubkey,isSigner:false,isWritable:true},{pubkey:nodePubkey,isSigner:true,isWritable:false},{pubkey:authorizedWithdrawerPubkey,isSigner:true,isWritable:false}];return(new Transaction).add({keys:keys,programId:this.programId,data:data})}}VoteProgram.programId=new PublicKey("Vote111111111111111111111111111111111111111");VoteProgram.space=3762;const VALIDATOR_INFO_KEY=new PublicKey("Va1idator1nfo111111111111111111111111111111");const InfoString=type({name:string(),website:optional(string()),details:optional(string()),iconUrl:optional(string()),keybaseUsername:optional(string())});class ValidatorInfo{constructor(key,info){this.key=void 0;this.info=void 0;this.key=key;this.info=info}static fromConfigData(buffer){let byteArray=[...buffer];const configKeyCount=decodeLength(byteArray);if(configKeyCount!==2)return null;const configKeys=[];for(let i=0;i<2;i++){const publicKey=new PublicKey(guardedSplice(byteArray,0,PUBLIC_KEY_LENGTH));const isSigner=guardedShift(byteArray)===1;configKeys.push({publicKey:publicKey,isSigner:isSigner})}if(configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)){if(configKeys[1].isSigner){const rawInfo=rustString().decode(bufferExports.Buffer.from(byteArray));const info=JSON.parse(rawInfo);assert(info,InfoString);return new ValidatorInfo(configKeys[1].publicKey,info)}}return null}}const VOTE_PROGRAM_ID=new PublicKey("Vote111111111111111111111111111111111111111");const VoteAccountLayout=LayoutExports.struct([publicKey("nodePubkey"),publicKey("authorizedWithdrawer"),LayoutExports.u8("commission"),LayoutExports.nu64(),LayoutExports.seq(LayoutExports.struct([LayoutExports.nu64("slot"),LayoutExports.u32("confirmationCount")]),LayoutExports.offset(LayoutExports.u32(),-8),"votes"),LayoutExports.u8("rootSlotValid"),LayoutExports.nu64("rootSlot"),LayoutExports.nu64(),LayoutExports.seq(LayoutExports.struct([LayoutExports.nu64("epoch"),publicKey("authorizedVoter")]),LayoutExports.offset(LayoutExports.u32(),-8),"authorizedVoters"),LayoutExports.struct([LayoutExports.seq(LayoutExports.struct([publicKey("authorizedPubkey"),LayoutExports.nu64("epochOfLastAuthorizedSwitch"),LayoutExports.nu64("targetEpoch")]),32,"buf"),LayoutExports.nu64("idx"),LayoutExports.u8("isEmpty")],"priorVoters"),LayoutExports.nu64(),LayoutExports.seq(LayoutExports.struct([LayoutExports.nu64("epoch"),LayoutExports.nu64("credits"),LayoutExports.nu64("prevCredits")]),LayoutExports.offset(LayoutExports.u32(),-8),"epochCredits"),LayoutExports.struct([LayoutExports.nu64("slot"),LayoutExports.nu64("timestamp")],"lastTimestamp")]);class VoteAccount{constructor(args){this.nodePubkey=void 0;this.authorizedWithdrawer=void 0;this.commission=void 0;this.rootSlot=void 0;this.votes=void 0;this.authorizedVoters=void 0;this.priorVoters=void 0;this.epochCredits=void 0;this.lastTimestamp=void 0;this.nodePubkey=args.nodePubkey;this.authorizedWithdrawer=args.authorizedWithdrawer;this.commission=args.commission;this.rootSlot=args.rootSlot;this.votes=args.votes;this.authorizedVoters=args.authorizedVoters;this.priorVoters=args.priorVoters;this.epochCredits=args.epochCredits;this.lastTimestamp=args.lastTimestamp}static fromAccountData(buffer){const versionOffset=4;const va=VoteAccountLayout.decode(toBuffer(buffer),versionOffset);let rootSlot=va.rootSlot;if(!va.rootSlotValid){rootSlot=null}return new VoteAccount({nodePubkey:new PublicKey(va.nodePubkey),authorizedWithdrawer:new PublicKey(va.authorizedWithdrawer),commission:va.commission,votes:va.votes,rootSlot:rootSlot,authorizedVoters:va.authorizedVoters.map(parseAuthorizedVoter),priorVoters:getPriorVoters(va.priorVoters),epochCredits:va.epochCredits,lastTimestamp:va.lastTimestamp})}}function parseAuthorizedVoter({authorizedVoter:authorizedVoter,epoch:epoch}){return{epoch:epoch,authorizedVoter:new PublicKey(authorizedVoter)}}function parsePriorVoters({authorizedPubkey:authorizedPubkey,epochOfLastAuthorizedSwitch:epochOfLastAuthorizedSwitch,targetEpoch:targetEpoch}){return{authorizedPubkey:new PublicKey(authorizedPubkey),epochOfLastAuthorizedSwitch:epochOfLastAuthorizedSwitch,targetEpoch:targetEpoch}}function getPriorVoters({buf:buf,idx:idx,isEmpty:isEmpty}){if(isEmpty){return[]}return[...buf.slice(idx+1).map(parsePriorVoters),...buf.slice(0,idx).map(parsePriorVoters)]}const endpoint={http:{devnet:"http://api.devnet.solana.com",testnet:"http://api.testnet.solana.com","mainnet-beta":"http://api.mainnet-beta.solana.com/"},https:{devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com","mainnet-beta":"https://api.mainnet-beta.solana.com/"}};function clusterApiUrl(cluster,tls){const key=tls===false?"http":"https";if(!cluster){return endpoint[key]["devnet"]}const url=endpoint[key][cluster];if(!url){throw new Error(`Unknown ${key} cluster: ${cluster}`)}return url}async function sendAndConfirmRawTransaction(connection,rawTransaction,confirmationStrategyOrConfirmOptions,maybeConfirmOptions){let confirmationStrategy;let options;if(confirmationStrategyOrConfirmOptions&&Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions,"lastValidBlockHeight")){confirmationStrategy=confirmationStrategyOrConfirmOptions;options=maybeConfirmOptions}else if(confirmationStrategyOrConfirmOptions&&Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions,"nonceValue")){confirmationStrategy=confirmationStrategyOrConfirmOptions;options=maybeConfirmOptions}else{options=confirmationStrategyOrConfirmOptions}const sendOptions=options&&{skipPreflight:options.skipPreflight,preflightCommitment:options.preflightCommitment||options.commitment,minContextSlot:options.minContextSlot};const signature=await connection.sendRawTransaction(rawTransaction,sendOptions);const commitment=options&&options.commitment;const confirmationPromise=confirmationStrategy?connection.confirmTransaction(confirmationStrategy,commitment):connection.confirmTransaction(signature,commitment);const status=(await confirmationPromise).value;if(status.err){if(signature!=null){throw new SendTransactionError({action:sendOptions?.skipPreflight?"send":"simulate",signature:signature,transactionMessage:`Status: (${JSON.stringify(status)})`})}throw new Error(`Raw transaction ${signature} failed (${JSON.stringify(status)})`)}return signature}const LAMPORTS_PER_SOL=1e9;exports.Account=Account;exports.AddressLookupTableAccount=AddressLookupTableAccount;exports.AddressLookupTableInstruction=AddressLookupTableInstruction;exports.AddressLookupTableProgram=AddressLookupTableProgram;exports.Authorized=Authorized;exports.BLOCKHASH_CACHE_TIMEOUT_MS=BLOCKHASH_CACHE_TIMEOUT_MS;exports.BPF_LOADER_DEPRECATED_PROGRAM_ID=BPF_LOADER_DEPRECATED_PROGRAM_ID;exports.BPF_LOADER_PROGRAM_ID=BPF_LOADER_PROGRAM_ID;exports.BpfLoader=BpfLoader;exports.COMPUTE_BUDGET_INSTRUCTION_LAYOUTS=COMPUTE_BUDGET_INSTRUCTION_LAYOUTS;exports.ComputeBudgetInstruction=ComputeBudgetInstruction;exports.ComputeBudgetProgram=ComputeBudgetProgram;exports.Connection=Connection;exports.Ed25519Program=Ed25519Program;exports.Enum=Enum;exports.EpochSchedule=EpochSchedule;exports.FeeCalculatorLayout=FeeCalculatorLayout;exports.Keypair=Keypair;exports.LAMPORTS_PER_SOL=LAMPORTS_PER_SOL;exports.LOOKUP_TABLE_INSTRUCTION_LAYOUTS=LOOKUP_TABLE_INSTRUCTION_LAYOUTS;exports.Loader=Loader;exports.Lockup=Lockup;exports.MAX_SEED_LENGTH=MAX_SEED_LENGTH;exports.Message=Message;exports.MessageAccountKeys=MessageAccountKeys;exports.MessageV0=MessageV0;exports.NONCE_ACCOUNT_LENGTH=NONCE_ACCOUNT_LENGTH;exports.NonceAccount=NonceAccount;exports.PACKET_DATA_SIZE=PACKET_DATA_SIZE;exports.PUBLIC_KEY_LENGTH=PUBLIC_KEY_LENGTH;exports.PublicKey=PublicKey;exports.SIGNATURE_LENGTH_IN_BYTES=SIGNATURE_LENGTH_IN_BYTES;exports.SOLANA_SCHEMA=SOLANA_SCHEMA;exports.STAKE_CONFIG_ID=STAKE_CONFIG_ID;exports.STAKE_INSTRUCTION_LAYOUTS=STAKE_INSTRUCTION_LAYOUTS;exports.SYSTEM_INSTRUCTION_LAYOUTS=SYSTEM_INSTRUCTION_LAYOUTS;exports.SYSVAR_CLOCK_PUBKEY=SYSVAR_CLOCK_PUBKEY;exports.SYSVAR_EPOCH_SCHEDULE_PUBKEY=SYSVAR_EPOCH_SCHEDULE_PUBKEY;exports.SYSVAR_INSTRUCTIONS_PUBKEY=SYSVAR_INSTRUCTIONS_PUBKEY;exports.SYSVAR_RECENT_BLOCKHASHES_PUBKEY=SYSVAR_RECENT_BLOCKHASHES_PUBKEY;exports.SYSVAR_RENT_PUBKEY=SYSVAR_RENT_PUBKEY;exports.SYSVAR_REWARDS_PUBKEY=SYSVAR_REWARDS_PUBKEY;exports.SYSVAR_SLOT_HASHES_PUBKEY=SYSVAR_SLOT_HASHES_PUBKEY;exports.SYSVAR_SLOT_HISTORY_PUBKEY=SYSVAR_SLOT_HISTORY_PUBKEY;exports.SYSVAR_STAKE_HISTORY_PUBKEY=SYSVAR_STAKE_HISTORY_PUBKEY;exports.Secp256k1Program=Secp256k1Program;exports.SendTransactionError=SendTransactionError;exports.SolanaJSONRPCError=SolanaJSONRPCError;exports.SolanaJSONRPCErrorCode=SolanaJSONRPCErrorCode;exports.StakeAuthorizationLayout=StakeAuthorizationLayout;exports.StakeInstruction=StakeInstruction;exports.StakeProgram=StakeProgram;exports.Struct=Struct$1;exports.SystemInstruction=SystemInstruction;exports.SystemProgram=SystemProgram;exports.Transaction=Transaction;exports.TransactionExpiredBlockheightExceededError=TransactionExpiredBlockheightExceededError;exports.TransactionExpiredNonceInvalidError=TransactionExpiredNonceInvalidError;exports.TransactionExpiredTimeoutError=TransactionExpiredTimeoutError;exports.TransactionInstruction=TransactionInstruction;exports.TransactionMessage=TransactionMessage;exports.TransactionStatus=TransactionStatus;exports.VALIDATOR_INFO_KEY=VALIDATOR_INFO_KEY;exports.VERSION_PREFIX_MASK=VERSION_PREFIX_MASK;exports.VOTE_PROGRAM_ID=VOTE_PROGRAM_ID;exports.ValidatorInfo=ValidatorInfo;exports.VersionedMessage=VersionedMessage;exports.VersionedTransaction=VersionedTransaction;exports.VoteAccount=VoteAccount;exports.VoteAuthorizationLayout=VoteAuthorizationLayout;exports.VoteInit=VoteInit;exports.VoteInstruction=VoteInstruction;exports.VoteProgram=VoteProgram;exports.clusterApiUrl=clusterApiUrl;exports.sendAndConfirmRawTransaction=sendAndConfirmRawTransaction;exports.sendAndConfirmTransaction=sendAndConfirmTransaction;return exports}({});+//# sourceMappingURL=index.iife.min.js.mapdiff --git a/fincept-qt/scripts/Analytics/backtesting/backtestingpy/__init__.py b/fincept-qt/scripts/Analytics/backtesting/backtestingpy/__init__.pyindex 1e9b4d821..01c3c6604 100644--- a/fincept-qt/scripts/Analytics/backtesting/backtestingpy/__init__.py+++ b/fincept-qt/scripts/Analytics/backtesting/backtestingpy/__init__.py@@ -1,8 +1,12 @@"""Backtesting.py ProviderUltra-lightweight and fast backtesting framework-"""--from .backtestingpy_provider import BacktestingPyProvider-__all__ = ['BacktestingPyProvider']+The provider class is intentionally not re-exported here. The CLI entry point+runs as `python -m Analytics.backtesting.backtestingpy.backtestingpy_provider`,+so an eager `from .backtestingpy_provider import ...` would load the module+into sys.modules during package init and trigger a RuntimeWarning when Python+then re-executes it as __main__. Import directly from the submodule when+needed: `from Analytics.backtesting.backtestingpy.backtestingpy_provider+import BacktestingPyProvider`.+"""diff --git a/fincept-qt/scripts/Analytics/backtesting/bt/__init__.py b/fincept-qt/scripts/Analytics/backtesting/bt/__init__.pyindex c214f166f..995fb3a3c 100644--- a/fincept-qt/scripts/Analytics/backtesting/bt/__init__.py+++ b/fincept-qt/scripts/Analytics/backtesting/bt/__init__.py@@ -7,8 +7,8 @@ Portfolio-level strategy backtesting with composable algo blocks:- Composable algo pipeline (bt.algos)Uses bt library (MIT license, v1.1.2+) with ffn for performance stats.-"""--from .bt_provider import BtProvider-__all__ = ['BtProvider']+The provider class is intentionally not re-exported here. See backtestingpy+__init__.py for the rationale (avoids RuntimeWarning when bt_provider is run+via `python -m`).+"""diff --git a/fincept-qt/scripts/Analytics/backtesting/fasttrade/__init__.py b/fincept-qt/scripts/Analytics/backtesting/fasttrade/__init__.pyindex 001413632..fe3fb6f88 100644--- a/fincept-qt/scripts/Analytics/backtesting/fasttrade/__init__.py+++ b/fincept-qt/scripts/Analytics/backtesting/fasttrade/__init__.py@@ -15,24 +15,8 @@ Modules:- ft_utils: Utilities (resample, trend detection, data conversion)- ft_strategies: 20+ pre-built strategy templates- ft_cli: CLI entry points and helpers (backtest_helper, create_plot, save)-"""--# Fix: Avoid relative imports for CLI compatibility-try:- from .fasttrade_provider import FastTradeProvider-except ImportError:- from fasttrade_provider import FastTradeProvider-__all__ = [- 'FastTradeProvider',- # Sub-modules importable as:- # from fasttrade.ft_backtest import run_backtest, validate_backtest, run_multiple_backtests- # from fasttrade.ft_indicators import sma, ema, rsi, macd, bbands, atr, ichimoku, ...- # from fasttrade.ft_data import load_basic_df_from_csv, generate_synthetic_ohlcv, get_binance_klines, ...- # from fasttrade.ft_summary import build_summary, calculate_drawdown_metrics, calculate_trade_quality, ...- # from fasttrade.ft_analysis import enter_position, exit_position, apply_logic_to_df, calculate_fee- # from fasttrade.ft_evaluate import evaluate_rules, handle_rule- # from fasttrade.ft_utils import resample, trending_up, trending_down, to_dataframe- # from fasttrade.ft_strategies import sma_crossover, rsi_strategy, bollinger_bands_strategy, ...- # from fasttrade.ft_cli import backtest_helper, validate_helper, open_strat_file, create_plot, save, MissingStrategyFile-]+The provider class is intentionally not re-exported here. See backtestingpy+__init__.py for the rationale (avoids RuntimeWarning when fasttrade_provider+is run via `python -m`).+"""diff --git a/fincept-qt/scripts/Analytics/backtesting/vectorbt/__init__.py b/fincept-qt/scripts/Analytics/backtesting/vectorbt/__init__.pyindex 9b73a160f..295a4345c 100644--- a/fincept-qt/scripts/Analytics/backtesting/vectorbt/__init__.py+++ b/fincept-qt/scripts/Analytics/backtesting/vectorbt/__init__.py@@ -15,21 +15,8 @@ Modules:- vbt_labels: Label generators (FIXLB, MEANLB, LEXLB, TRENDLB, BOLB)- vbt_splitters: Cross-validation splitters (Rolling, Expanding, Range, PurgedKFold)- vbt_generic: Drawdowns and Ranges analysis classes-"""--from .vectorbt_provider import VectorBTProvider-__all__ = [- 'VectorBTProvider',- # Sub-modules importable as:- # from vectorbt.vbt_portfolio import SimplePortfolio, build_portfolio, build_portfolio_from_order_func- # from vectorbt.vbt_returns import ReturnsAccessor- # from vectorbt.vbt_data import YFData, BinanceData, CCXTData, AlpacaData, GBMData, Data- # from vectorbt.vbt_signals import SignalFactory, RAND, RANDX, STX, OHLCSTX, ...- # from vectorbt.vbt_labels import FIXLB, MEANLB, LEXLB, TRENDLB, BOLB- # from vectorbt.vbt_indicators import IndicatorFactory, calculate_rsi, ...- # from vectorbt.vbt_splitters import RollingSplitter, ExpandingSplitter, RangeSplitter, PurgedKFoldSplitter- # from vectorbt.vbt_generic import Drawdowns, Ranges- # from vectorbt.vbt_metrics import extract_full_metrics- # from vectorbt.vbt_optimization import optimize, walk_forward_optimize-]+The provider class is intentionally not re-exported here. See backtestingpy+__init__.py for the rationale (avoids RuntimeWarning when vectorbt_provider+is run via `python -m`).+"""diff --git a/fincept-qt/scripts/Analytics/backtesting/zipline/__init__.py b/fincept-qt/scripts/Analytics/backtesting/zipline/__init__.pyindex c94741e07..636f74ebb 100644--- a/fincept-qt/scripts/Analytics/backtesting/zipline/__init__.py+++ b/fincept-qt/scripts/Analytics/backtesting/zipline/__init__.py@@ -19,156 +19,9 @@ Comprehensive Zipline API coverage:- Asset types: Asset, Equity, Future, ContinuousFuture- Asset lookup: symbol, symbols, sid, continuous_future, future_symbol- Bundle management: register, ingest, load, clean, unregister-"""--from .zipline_provider import (- ZiplineProvider,- # Execution styles- MarketOrder,- LimitOrder,- StopOrder,- StopLimitOrder,- # Commission models- PerShare,- PerTrade,- PerDollar,- NoCommission,- # Slippage models- FixedSlippage,- VolumeShareSlippage,- NoSlippage,- FixedBasisPointsSlippage,- # Cancel policies- EODCancel,- NeverCancel,- # Asset restrictions- NoRestrictions,- StaticRestrictions,- HistoricalRestrictions,- # Asset classes- Asset,- Equity,- Future,- ContinuousFuture,- # Bundle management- register_bundle,- ingest_bundle,- load_bundle,- clean_bundle,- unregister_bundle,- bundles,- # Scheduling- date_rules,- time_rules,-)-from .zl_pipeline import (- # Pipeline core- Pipeline,- CustomFactor,- CustomFilter,- CustomClassifier,- # Base classes- Term,- Factor,- Filter,- Classifier,- # Data- Column,- BoundColumn,- DataSet,- DataSetFamily,- EquityPricing,- USEquityPricing,- # Built-in factors- Latest,- AverageDollarVolume,- BollingerBands,- DailyReturns,- Returns,- SimpleMovingAverage,- ExponentialWeightedMovingAverage,- ExponentialWeightedMovingStdDev,- VWAP,- RSI,- MACDSignal,- MaxDrawdown,- AnnualizedVolatility,- PercentChange,- RateOfChangePercentage,- TrueRange,- Aroon,- FastStochasticOscillator,- IchimokuKinkoHyo,- SimpleBeta,- RollingPearsonOfReturns,- RollingSpearmanOfReturns,- RollingLinearRegressionOfReturns,- WeightedAverageValue,- PeerCount,- # Built-in filters- StaticAssets,- StaticSids,- AllPresent,- AtLeastN,- SingleAsset,- # Classifiers- Quantiles,- Everything,- # Domains- GENERIC,- US_EQUITIES,- UK_EQUITIES,- CA_EQUITIES,- DE_EQUITIES,- FR_EQUITIES,- JP_EQUITIES,- KR_EQUITIES,- HK_EQUITIES,- CN_EQUITIES,-)--__all__ = [- # Provider- 'ZiplineProvider',- # Execution styles- 'MarketOrder', 'LimitOrder', 'StopOrder', 'StopLimitOrder',- # Commission models- 'PerShare', 'PerTrade', 'PerDollar', 'NoCommission',- # Slippage models- 'FixedSlippage', 'VolumeShareSlippage', 'NoSlippage', 'FixedBasisPointsSlippage',- # Cancel policies- 'EODCancel', 'NeverCancel',- # Asset restrictions- 'NoRestrictions', 'StaticRestrictions', 'HistoricalRestrictions',- # Asset classes- 'Asset', 'Equity', 'Future', 'ContinuousFuture',- # Bundle management- 'register_bundle', 'ingest_bundle', 'load_bundle', 'clean_bundle',- 'unregister_bundle', 'bundles',- # Scheduling- 'date_rules', 'time_rules',- # Pipeline core- 'Pipeline', 'CustomFactor', 'CustomFilter', 'CustomClassifier',- 'Term', 'Factor', 'Filter', 'Classifier',- # Pipeline data- 'Column', 'BoundColumn', 'DataSet', 'DataSetFamily',- 'EquityPricing', 'USEquityPricing',- # Built-in factors- 'Latest', 'AverageDollarVolume', 'BollingerBands', 'DailyReturns',- 'Returns', 'SimpleMovingAverage', 'ExponentialWeightedMovingAverage',- 'ExponentialWeightedMovingStdDev', 'VWAP', 'RSI', 'MACDSignal',- 'MaxDrawdown', 'AnnualizedVolatility', 'PercentChange',- 'RateOfChangePercentage', 'TrueRange', 'Aroon', 'FastStochasticOscillator',- 'IchimokuKinkoHyo', 'SimpleBeta', 'RollingPearsonOfReturns',- 'RollingSpearmanOfReturns', 'RollingLinearRegressionOfReturns',- 'WeightedAverageValue', 'PeerCount',- # Built-in filters- 'StaticAssets', 'StaticSids', 'AllPresent', 'AtLeastN', 'SingleAsset',- # Classifiers- 'Quantiles', 'Everything',- # Domains- 'GENERIC', 'US_EQUITIES', 'UK_EQUITIES', 'CA_EQUITIES',- 'DE_EQUITIES', 'FR_EQUITIES', 'JP_EQUITIES', 'KR_EQUITIES',- 'HK_EQUITIES', 'CN_EQUITIES',-]+The provider class and its re-exports are intentionally not loaded here. See+backtestingpy __init__.py for the rationale (avoids RuntimeWarning when+zipline_provider is run via `python -m`). Import the symbols you need directly+from zipline_provider / zl_pipeline.+"""diff --git a/fincept-qt/scripts/Analytics/economics/__init__.py b/fincept-qt/scripts/Analytics/economics/__init__.pyindex ecc0037f3..f3a788cad 100644--- a/fincept-qt/scripts/Analytics/economics/__init__.py+++ b/fincept-qt/scripts/Analytics/economics/__init__.py@@ -69,11 +69,6 @@ from .policy_analysis import (CentralBankAnalyzer)-from .trade_geopolitics import (- TradeAnalyzer,- GeopoliticalRiskAnalyzer,- TradingBlocAnalyzer-)from .capital_flows import (CapitalFlowAnalyzer,@@ -191,4 +186,33 @@ def get_version_info():'description': 'CFA-based Economics Analysis Module for FinceptTerminal','modules': len(__all__),'cfa_compliance': 'Level I & II'- }\ No newline at end of file+ }+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "TradeAnalyzer": ("trade_geopolitics", "TradeAnalyzer"),+ "GeopoliticalRiskAnalyzer": ("trade_geopolitics", "GeopoliticalRiskAnalyzer"),+ "TradingBlocAnalyzer": ("trade_geopolitics", "TradingBlocAnalyzer"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/ffn_wrapper/__init__.py b/fincept-qt/scripts/Analytics/ffn_wrapper/__init__.pyindex a3864f5e8..ad7e1188c 100644--- a/fincept-qt/scripts/Analytics/ffn_wrapper/__init__.py+++ b/fincept-qt/scripts/Analytics/ffn_wrapper/__init__.py@@ -30,9 +30,6 @@ PARAMETERS:- covar_method: Covariance estimation method (default: 'ledoit-wolf')"""-from .ffn_analytics import FFNAnalyticsEngine, FFNConfig-from .ffn_performance import FFNPerformanceAnalyzer-from .ffn_portfolio import FFNPortfolioOptimizer__all__ = ['FFNAnalyticsEngine',@@ -40,3 +37,33 @@ __all__ = ['FFNPerformanceAnalyzer','FFNPortfolioOptimizer',]+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "FFNAnalyticsEngine": ("ffn_analytics", "FFNAnalyticsEngine"),+ "FFNConfig": ("ffn_analytics", "FFNConfig"),+ "FFNPerformanceAnalyzer": ("ffn_performance", "FFNPerformanceAnalyzer"),+ "FFNPortfolioOptimizer": ("ffn_portfolio", "FFNPortfolioOptimizer"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/finanicalanalysis/specialized_analysis/__init__.py b/fincept-qt/scripts/Analytics/finanicalanalysis/specialized_analysis/__init__.pyindex 445d88fdd..316e71297 100644--- a/fincept-qt/scripts/Analytics/finanicalanalysis/specialized_analysis/__init__.py+++ b/fincept-qt/scripts/Analytics/finanicalanalysis/specialized_analysis/__init__.py@@ -12,7 +12,6 @@ from .inventory_analysis import InventoryAnalyzerfrom .asset_analysis import LongTermAssetAnalyzerfrom .tax_analysis import TaxAnalyzerfrom .quality_analysis import FinancialReportingQualityAnalyzer-from .financial_modeling import FinancialStatementModelingAnalyzer__all__ = [# Inventory Analysis@@ -30,3 +29,30 @@ __all__ = [# Financial Statement Modeling"FinancialStatementModelingAnalyzer",]+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "FinancialStatementModelingAnalyzer": ("financial_modeling", "FinancialStatementModelingAnalyzer"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/fixedIncome/__init__.py b/fincept-qt/scripts/Analytics/fixedIncome/__init__.pyindex e42c4b773..23b5fde5d 100644--- a/fincept-qt/scripts/Analytics/fixedIncome/__init__.py+++ b/fincept-qt/scripts/Analytics/fixedIncome/__init__.py@@ -20,57 +20,6 @@ Modules:- sovereign_credit: Sovereign and municipal credit analysis"""-from .bond_pricing import (- BondPricer,- BondType,- CouponFrequency,- DayCountConvention,-)--from .duration_convexity import (- DurationCalculator,- ConvexityCalculator,-)--from .yield_curve import (- YieldCurveBuilder,- SpreadAnalyzer,-)--from .credit_analysis import (- CreditAnalyzer,- DefaultProbabilityModel,-)--from .structured_products import (- MBSAnalyzer,- ABSAnalyzer,- PrepaymentModel,-)--from .bond_portfolio import (- BondPortfolioAnalyzer,- ImmunizationStrategy,-)--from .bond_features import (- BondFeaturesAnalyzer,-)--from .market_structure import (- MarketStructureAnalyzer,-)--from .floating_rate import (- FloatingRateAnalyzer,- MoneyMarketAnalyzer,-)--from .sovereign_credit import (- SovereignCreditAnalyzer,- MunicipalCreditAnalyzer,- GovernmentVsCorporateComparison,-)__all__ = [# Bond Pricing@@ -108,3 +57,51 @@ __all__ = []__version__ = '1.1.0'+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "BondPricer": ("bond_pricing", "BondPricer"),+ "BondType": ("bond_pricing", "BondType"),+ "CouponFrequency": ("bond_pricing", "CouponFrequency"),+ "DayCountConvention": ("bond_pricing", "DayCountConvention"),+ "DurationCalculator": ("duration_convexity", "DurationCalculator"),+ "ConvexityCalculator": ("duration_convexity", "ConvexityCalculator"),+ "YieldCurveBuilder": ("yield_curve", "YieldCurveBuilder"),+ "SpreadAnalyzer": ("yield_curve", "SpreadAnalyzer"),+ "CreditAnalyzer": ("credit_analysis", "CreditAnalyzer"),+ "DefaultProbabilityModel": ("credit_analysis", "DefaultProbabilityModel"),+ "MBSAnalyzer": ("structured_products", "MBSAnalyzer"),+ "ABSAnalyzer": ("structured_products", "ABSAnalyzer"),+ "PrepaymentModel": ("structured_products", "PrepaymentModel"),+ "BondPortfolioAnalyzer": ("bond_portfolio", "BondPortfolioAnalyzer"),+ "ImmunizationStrategy": ("bond_portfolio", "ImmunizationStrategy"),+ "BondFeaturesAnalyzer": ("bond_features", "BondFeaturesAnalyzer"),+ "MarketStructureAnalyzer": ("market_structure", "MarketStructureAnalyzer"),+ "FloatingRateAnalyzer": ("floating_rate", "FloatingRateAnalyzer"),+ "MoneyMarketAnalyzer": ("floating_rate", "MoneyMarketAnalyzer"),+ "SovereignCreditAnalyzer": ("sovereign_credit", "SovereignCreditAnalyzer"),+ "MunicipalCreditAnalyzer": ("sovereign_credit", "MunicipalCreditAnalyzer"),+ "GovernmentVsCorporateComparison": ("sovereign_credit", "GovernmentVsCorporateComparison"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/functime_wrapper/__init__.py b/fincept-qt/scripts/Analytics/functime_wrapper/__init__.pyindex 873a16707..7c72889fd 100644--- a/fincept-qt/scripts/Analytics/functime_wrapper/__init__.py+++ b/fincept-qt/scripts/Analytics/functime_wrapper/__init__.py@@ -10,69 +10,6 @@ Complete wrapper for functime library covering:- Offsets (Frequency to seasonal period conversion)"""-from .forecasting import (- fit_linear_model,- forecast_linear_model,- fit_lasso,- forecast_lasso,- fit_ridge,- forecast_ridge,- fit_elasticnet,- forecast_elasticnet,- fit_knn,- forecast_knn,- fit_lightgbm,- forecast_lightgbm,- auto_linear_model,- auto_lasso,- auto_ridge,- auto_elasticnet,- auto_knn,- auto_lightgbm-)--from .feature_extraction import (- create_calendar_effects,- create_holiday_effects,- create_future_calendar_effects,- create_future_holiday_effects-)--from .preprocessing import (- apply_boxcox,- find_boxcox_normmax,- coerce_data_types,- difference_data,- impute_missing,- create_lags,- reindex_panel_data,- resample_data,- create_rolling_features,- scale_data,- zero_pad_data-)--from .cross_validation import (- split_train_test,- create_expanding_window_splits,- create_sliding_window_splits-)--from .metrics import (- calculate_mae,- calculate_mape,- calculate_mase,- calculate_mse,- calculate_rmse,- calculate_rmsse,- calculate_smape,- calculate_overforecast,- calculate_underforecast-)--from .offsets import (- frequency_to_seasonal_period-)__all__ = [# Forecasting models@@ -129,3 +66,75 @@ __all__ = [# Offsets'frequency_to_seasonal_period']+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "fit_linear_model": ("forecasting", "fit_linear_model"),+ "forecast_linear_model": ("forecasting", "forecast_linear_model"),+ "fit_lasso": ("forecasting", "fit_lasso"),+ "forecast_lasso": ("forecasting", "forecast_lasso"),+ "fit_ridge": ("forecasting", "fit_ridge"),+ "forecast_ridge": ("forecasting", "forecast_ridge"),+ "fit_elasticnet": ("forecasting", "fit_elasticnet"),+ "forecast_elasticnet": ("forecasting", "forecast_elasticnet"),+ "fit_knn": ("forecasting", "fit_knn"),+ "forecast_knn": ("forecasting", "forecast_knn"),+ "fit_lightgbm": ("forecasting", "fit_lightgbm"),+ "forecast_lightgbm": ("forecasting", "forecast_lightgbm"),+ "auto_linear_model": ("forecasting", "auto_linear_model"),+ "auto_lasso": ("forecasting", "auto_lasso"),+ "auto_ridge": ("forecasting", "auto_ridge"),+ "auto_elasticnet": ("forecasting", "auto_elasticnet"),+ "auto_knn": ("forecasting", "auto_knn"),+ "auto_lightgbm": ("forecasting", "auto_lightgbm"),+ "create_calendar_effects": ("feature_extraction", "create_calendar_effects"),+ "create_holiday_effects": ("feature_extraction", "create_holiday_effects"),+ "create_future_calendar_effects": ("feature_extraction", "create_future_calendar_effects"),+ "create_future_holiday_effects": ("feature_extraction", "create_future_holiday_effects"),+ "apply_boxcox": ("preprocessing", "apply_boxcox"),+ "find_boxcox_normmax": ("preprocessing", "find_boxcox_normmax"),+ "coerce_data_types": ("preprocessing", "coerce_data_types"),+ "difference_data": ("preprocessing", "difference_data"),+ "impute_missing": ("preprocessing", "impute_missing"),+ "create_lags": ("preprocessing", "create_lags"),+ "reindex_panel_data": ("preprocessing", "reindex_panel_data"),+ "resample_data": ("preprocessing", "resample_data"),+ "create_rolling_features": ("preprocessing", "create_rolling_features"),+ "scale_data": ("preprocessing", "scale_data"),+ "zero_pad_data": ("preprocessing", "zero_pad_data"),+ "split_train_test": ("cross_validation", "split_train_test"),+ "create_expanding_window_splits": ("cross_validation", "create_expanding_window_splits"),+ "create_sliding_window_splits": ("cross_validation", "create_sliding_window_splits"),+ "calculate_mae": ("metrics", "calculate_mae"),+ "calculate_mape": ("metrics", "calculate_mape"),+ "calculate_mase": ("metrics", "calculate_mase"),+ "calculate_mse": ("metrics", "calculate_mse"),+ "calculate_rmse": ("metrics", "calculate_rmse"),+ "calculate_rmsse": ("metrics", "calculate_rmsse"),+ "calculate_smape": ("metrics", "calculate_smape"),+ "calculate_overforecast": ("metrics", "calculate_overforecast"),+ "calculate_underforecast": ("metrics", "calculate_underforecast"),+ "frequency_to_seasonal_period": ("offsets", "frequency_to_seasonal_period"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/gluonts_wrapper/__init__.py b/fincept-qt/scripts/Analytics/gluonts_wrapper/__init__.pyindex 8bef554f3..a44c6b838 100644--- a/fincept-qt/scripts/Analytics/gluonts_wrapper/__init__.py+++ b/fincept-qt/scripts/Analytics/gluonts_wrapper/__init__.py@@ -1,13 +1,3 @@-from .forecasters import (- forecast_feedforward, forecast_deepar, forecast_tft, forecast_wavenet,- forecast_dlinear, forecast_patchtst, forecast_tide, forecast_lagtst, forecast_deepnpts-)-from .predictors import (- predict_seasonal_naive, predict_mean, predict_constant-)-from .evaluation import (- evaluate_forecasts-)__all__ = ['forecast_feedforward', 'forecast_deepar', 'forecast_tft', 'forecast_wavenet',@@ -15,3 +5,42 @@ __all__ = ['predict_seasonal_naive', 'predict_mean', 'predict_constant','evaluate_forecasts']+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "forecast_feedforward": ("forecasters", "forecast_feedforward"),+ "forecast_deepar": ("forecasters", "forecast_deepar"),+ "forecast_tft": ("forecasters", "forecast_tft"),+ "forecast_wavenet": ("forecasters", "forecast_wavenet"),+ "forecast_dlinear": ("forecasters", "forecast_dlinear"),+ "forecast_patchtst": ("forecasters", "forecast_patchtst"),+ "forecast_tide": ("forecasters", "forecast_tide"),+ "forecast_lagtst": ("forecasters", "forecast_lagtst"),+ "forecast_deepnpts": ("forecasters", "forecast_deepnpts"),+ "predict_seasonal_naive": ("predictors", "predict_seasonal_naive"),+ "predict_mean": ("predictors", "predict_mean"),+ "predict_constant": ("predictors", "predict_constant"),+ "evaluate_forecasts": ("evaluation", "evaluate_forecasts"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/gs_quant_wrapper/__init__.py b/fincept-qt/scripts/Analytics/gs_quant_wrapper/__init__.pyindex 857614900..70ab56b1c 100644--- a/fincept-qt/scripts/Analytics/gs_quant_wrapper/__init__.py+++ b/fincept-qt/scripts/Analytics/gs_quant_wrapper/__init__.py@@ -25,16 +25,8 @@ Note: All functions work offline with your own data. No GS API required."""# DateTime utilities-from .datetime_utils import (- DateTimeUtils,- DateTimeConfig-)# Timeseries - unified class-from .timeseries_analytics import (- TimeseriesAnalytics,- TimeseriesConfig-)# Timeseries - sub-modulesfrom . import ts_math_statistics@@ -45,29 +37,10 @@ from . import ts_data_transformsfrom . import ts_portfolio_analytics# Instrument wrapper-from .instrument_wrapper import (- InstrumentFactory,- InstrumentConfig,- EquitySpecs,- BondSpecs,- OptionSpecs,- SwapSpecs-)# Risk analytics-from .risk_analytics import (- RiskAnalytics,- RiskConfig,- MarketShock-)# Backtest analytics-from .backtest_analytics import (- BacktestEngine,- BacktestConfig,- Trade,- Position-)__version__ = '1.3.0'__author__ = 'Fincept Corporation'@@ -108,3 +81,46 @@ __all__ = ['Trade','Position',]+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "DateTimeUtils": ("datetime_utils", "DateTimeUtils"),+ "DateTimeConfig": ("datetime_utils", "DateTimeConfig"),+ "TimeseriesAnalytics": ("timeseries_analytics", "TimeseriesAnalytics"),+ "TimeseriesConfig": ("timeseries_analytics", "TimeseriesConfig"),+ "InstrumentFactory": ("instrument_wrapper", "InstrumentFactory"),+ "InstrumentConfig": ("instrument_wrapper", "InstrumentConfig"),+ "EquitySpecs": ("instrument_wrapper", "EquitySpecs"),+ "BondSpecs": ("instrument_wrapper", "BondSpecs"),+ "OptionSpecs": ("instrument_wrapper", "OptionSpecs"),+ "SwapSpecs": ("instrument_wrapper", "SwapSpecs"),+ "RiskAnalytics": ("risk_analytics", "RiskAnalytics"),+ "RiskConfig": ("risk_analytics", "RiskConfig"),+ "MarketShock": ("risk_analytics", "MarketShock"),+ "BacktestEngine": ("backtest_analytics", "BacktestEngine"),+ "BacktestConfig": ("backtest_analytics", "BacktestConfig"),+ "Trade": ("backtest_analytics", "Trade"),+ "Position": ("backtest_analytics", "Position"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/pmdarima_wrapper/__init__.py b/fincept-qt/scripts/Analytics/pmdarima_wrapper/__init__.pyindex 1bb75cf91..9bbe0467b 100644--- a/fincept-qt/scripts/Analytics/pmdarima_wrapper/__init__.py+++ b/fincept-qt/scripts/Analytics/pmdarima_wrapper/__init__.py@@ -10,40 +10,6 @@ Complete wrapper for pmdarima library covering:- Metrics (SMAPE)"""-from .arima import (- fit_auto_arima,- fit_arima,- forecast_auto_arima,- forecast_arima,- update_arima-)--from .preprocessing import (- apply_boxcox_transform,- inverse_boxcox_transform,- apply_log_transform,- inverse_log_transform,- create_date_features,- create_fourier_features-)--from .model_selection import (- split_train_test,- cross_validate_arima,- rolling_forecast_cv,- sliding_window_cv-)--from .utils import (- calculate_acf,- calculate_pacf,- decompose_timeseries,- difference_series,- inverse_difference,- smape_metric,- check_endogenous,- create_c_array-)__all__ = [# ARIMA models@@ -74,3 +40,52 @@ __all__ = ['check_endogenous','create_c_array']+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "fit_auto_arima": ("arima", "fit_auto_arima"),+ "fit_arima": ("arima", "fit_arima"),+ "forecast_auto_arima": ("arima", "forecast_auto_arima"),+ "forecast_arima": ("arima", "forecast_arima"),+ "update_arima": ("arima", "update_arima"),+ "apply_boxcox_transform": ("preprocessing", "apply_boxcox_transform"),+ "inverse_boxcox_transform": ("preprocessing", "inverse_boxcox_transform"),+ "apply_log_transform": ("preprocessing", "apply_log_transform"),+ "inverse_log_transform": ("preprocessing", "inverse_log_transform"),+ "create_date_features": ("preprocessing", "create_date_features"),+ "create_fourier_features": ("preprocessing", "create_fourier_features"),+ "split_train_test": ("model_selection", "split_train_test"),+ "cross_validate_arima": ("model_selection", "cross_validate_arima"),+ "rolling_forecast_cv": ("model_selection", "rolling_forecast_cv"),+ "sliding_window_cv": ("model_selection", "sliding_window_cv"),+ "calculate_acf": ("utils", "calculate_acf"),+ "calculate_pacf": ("utils", "calculate_pacf"),+ "decompose_timeseries": ("utils", "decompose_timeseries"),+ "difference_series": ("utils", "difference_series"),+ "inverse_difference": ("utils", "inverse_difference"),+ "smape_metric": ("utils", "smape_metric"),+ "check_endogenous": ("utils", "check_endogenous"),+ "create_c_array": ("utils", "create_c_array"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/py_vollib_wrapper/__init__.py b/fincept-qt/scripts/Analytics/py_vollib_wrapper/__init__.pyindex 2ae73e348..948924099 100644--- a/fincept-qt/scripts/Analytics/py_vollib_wrapper/__init__.py+++ b/fincept-qt/scripts/Analytics/py_vollib_wrapper/__init__.py@@ -1,15 +1,41 @@-from .black import (- calculate_black_price, calculate_black_greeks, calculate_black_iv-)-from .black_scholes import (- calculate_bs_price, calculate_bs_greeks, calculate_bs_iv-)-from .black_scholes_merton import (- calculate_bsm_price, calculate_bsm_greeks, calculate_bsm_iv-)__all__ = ['calculate_black_price', 'calculate_black_greeks', 'calculate_black_iv','calculate_bs_price', 'calculate_bs_greeks', 'calculate_bs_iv','calculate_bsm_price', 'calculate_bsm_greeks', 'calculate_bsm_iv']+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "calculate_black_price": ("black", "calculate_black_price"),+ "calculate_black_greeks": ("black", "calculate_black_greeks"),+ "calculate_black_iv": ("black", "calculate_black_iv"),+ "calculate_bs_price": ("black_scholes", "calculate_bs_price"),+ "calculate_bs_greeks": ("black_scholes", "calculate_bs_greeks"),+ "calculate_bs_iv": ("black_scholes", "calculate_bs_iv"),+ "calculate_bsm_price": ("black_scholes_merton", "calculate_bsm_price"),+ "calculate_bsm_greeks": ("black_scholes_merton", "calculate_bsm_greeks"),+ "calculate_bsm_iv": ("black_scholes_merton", "calculate_bsm_iv"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/pypme_wrapper/__init__.py b/fincept-qt/scripts/Analytics/pypme_wrapper/__init__.pyindex 62061be3c..b11039aed 100644--- a/fincept-qt/scripts/Analytics/pypme_wrapper/__init__.py+++ b/fincept-qt/scripts/Analytics/pypme_wrapper/__init__.py@@ -8,15 +8,6 @@ Complete wrapper for pypme library covering:- Verbose outputs with detailed calculations"""-from .core import (- calculate_pme,- calculate_verbose_pme,- calculate_xpme,- calculate_verbose_xpme,- calculate_tessa_xpme,- calculate_tessa_verbose_xpme,- pick_prices_from_dataframe-)__all__ = ['calculate_pme',@@ -27,3 +18,36 @@ __all__ = ['calculate_tessa_verbose_xpme','pick_prices_from_dataframe']+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "calculate_pme": ("core", "calculate_pme"),+ "calculate_verbose_pme": ("core", "calculate_verbose_pme"),+ "calculate_xpme": ("core", "calculate_xpme"),+ "calculate_verbose_xpme": ("core", "calculate_verbose_xpme"),+ "calculate_tessa_xpme": ("core", "calculate_tessa_xpme"),+ "calculate_tessa_verbose_xpme": ("core", "calculate_tessa_verbose_xpme"),+ "pick_prices_from_dataframe": ("core", "pick_prices_from_dataframe"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/quant_analytics_cli.py b/fincept-qt/scripts/Analytics/quant_analytics_cli.pyindex 3f4c1d7f6..26034f8a0 100644--- a/fincept-qt/scripts/Analytics/quant_analytics_cli.py+++ b/fincept-qt/scripts/Analytics/quant_analytics_cli.py@@ -161,16 +161,61 @@ class CFAQuantEngine:return Nonereturn obj- def _parse_data(self, data: Union[str, List, Dict]) -> np.ndarray:- if isinstance(data, str):+ def _looks_like_ticker(self, s: str) -> bool:+ s = s.strip()+ if not s or ',' in s or s.startswith('[') or s.startswith('{'):+ return False+ # Letters / dot / dash only (e.g. AAPL, BRK.B, TCS.NS, ^GSPC)+ return all(c.isalpha() or c in '.-^' for c in s)++ def _fetch_ticker_history(self, ticker: str, period: str = '1y',+ interval: str = '1d', column: str = 'Close') -> np.ndarray:+ try:+ import yfinance as yf+ except ImportError as exc:+ raise ImportError(f"yfinance is required to fetch ticker '{ticker}': {exc}")++ df = yf.download(ticker, period=period, interval=interval,+ progress=False, auto_adjust=False)+ if df is None or df.empty:+ raise ValueError(f"No data returned for ticker '{ticker}' (period={period})")++ # yfinance returns a MultiIndex when multiple tickers / multi-level cols+ if isinstance(df.columns, pd.MultiIndex):+ # pick the requested column at level 0try:- parsed = json.loads(data)+ series = df[column].iloc[:, 0]+ except (KeyError, IndexError):+ series = df.iloc[:, 0]+ else:+ series = df[column] if column in df.columns else df.iloc[:, 0]++ values = pd.Series(series).dropna().to_numpy(dtype=float)+ if values.size == 0:+ raise ValueError(f"Ticker '{ticker}' produced an empty series after cleaning")+ return values++ def _parse_data(self, data: Union[str, List, Dict],+ period: str = '1y', interval: str = '1d',+ column: str = 'Close') -> np.ndarray:+ if isinstance(data, str):+ stripped = data.strip()+ # 1. JSON list / array+ if stripped.startswith('[') or stripped.startswith('{'):+ parsed = json.loads(stripped)if isinstance(parsed, list):return np.array(parsed, dtype=float)- return np.array(parsed, dtype=float)- except json.JSONDecodeError:- values = [float(x.strip()) for x in data.split(',') if x.strip()]- return np.array(values)+ if isinstance(parsed, dict):+ return pd.DataFrame(parsed).values+ # 2. Ticker symbol → fetch close prices+ if self._looks_like_ticker(stripped):+ return self._fetch_ticker_history(stripped, period=period,+ interval=interval, column=column)+ # 3. CSV numeric values+ values = [float(x.strip()) for x in stripped.split(',') if x.strip()]+ if not values:+ raise ValueError("Empty data input")+ return np.array(values)elif isinstance(data, list):return np.array(data, dtype=float)elif isinstance(data, dict):@@ -209,11 +254,18 @@ class CFAQuantEngine:'timestamp': datetime.now().isoformat()}+ def _data_kwargs(self, params: Dict[str, Any]) -> Dict[str, str]:+ return {+ 'period': params.get('period', '1y'),+ 'interval': params.get('interval', '1d'),+ 'column': params.get('column', 'Close'),+ }+def trend_analysis(self, params: Dict[str, Any]) -> Dict[str, Any]:if self.analyzer is None:return {'success': False, 'error': f'Module not loaded: {getattr(self, "import_error", "unknown")}'}- data = self._parse_data(params.get('data', []))+ data = self._parse_data(params.get('data', []), **self._data_kwargs(params))trend_type = params.get('trend_type', 'linear')result = self.analyzer.analyze_trend(data, trend_type=trend_type)@@ -223,7 +275,7 @@ class CFAQuantEngine:if self.analyzer is None:return {'success': False, 'error': f'Module not loaded: {getattr(self, "import_error", "unknown")}'}- data = self._parse_data(params.get('data', []))+ data = self._parse_data(params.get('data', []), **self._data_kwargs(params))test_type = params.get('test_type', 'adf')result = self.analyzer.test_stationarity(data, test_type=test_type)@@ -233,7 +285,7 @@ class CFAQuantEngine:if self.analyzer is None:return {'success': False, 'error': f'Module not loaded: {getattr(self, "import_error", "unknown")}'}- data = self._parse_data(params.get('data', []))+ data = self._parse_data(params.get('data', []), **self._data_kwargs(params))# Handle order parameter - ensure it's a tupleorder_param = params.get('order', [1, 0, 1])@@ -258,7 +310,7 @@ class CFAQuantEngine:if self.analyzer is None:return {'success': False, 'error': f'Module not loaded: {getattr(self, "import_error", "unknown")}'}- data = self._parse_data(params.get('data', []))+ data = self._parse_data(params.get('data', []), **self._data_kwargs(params))horizon = params.get('horizon', 5)method = params.get('method', 'simple_exponential')train_size = params.get('train_size', 0.8)@@ -288,7 +340,7 @@ class CFAQuantEngine:if X is None or y is None:data = params.get('data')if data is not None:- data_arr = self._parse_data(data)+ data_arr = self._parse_data(data, **self._data_kwargs(params))n_lags = params.get('n_lags')if n_lags is None or n_lags < 1:n_lags = 5@@ -317,7 +369,7 @@ class CFAQuantEngine:if X is None:data = params.get('data')if data is not None:- data_arr = self._parse_data(data)+ data_arr = self._parse_data(data, **self._data_kwargs(params))n_lags = params.get('n_lags')if n_lags is None or n_lags < 1:n_lags = 5@@ -345,7 +397,7 @@ class CFAQuantEngine:if X is None or y is None:data = params.get('data')if data is not None:- data_arr = self._parse_data(data)+ data_arr = self._parse_data(data, **self._data_kwargs(params))n_lags = params.get('n_lags')if n_lags is None or n_lags < 1:n_lags = 5@@ -380,7 +432,7 @@ class CFAQuantEngine:if self.analyzer is None:return {'success': False, 'error': f'Module not loaded: {getattr(self, "import_error", "unknown")}'}- population = self._parse_data(params.get('population', []))+ population = self._parse_data(params.get('population', []), **self._data_kwargs(params))sample_size = params.get('sample_size', 100)sampling_methods = params.get('sampling_methods', ['simple', 'stratified', 'systematic'])@@ -408,7 +460,7 @@ class CFAQuantEngine:if self.analyzer is None:return {'success': False, 'error': f'Module not loaded: {getattr(self, "import_error", "unknown")}'}- data = self._parse_data(params.get('data', []))+ data = self._parse_data(params.get('data', []), **self._data_kwargs(params))methods = params.get('methods', ['bootstrap', 'jackknife', 'permutation'])n_resamples = params.get('n_resamples', 1000)@@ -438,11 +490,19 @@ class CFAQuantEngine:if self.validator is None:return {'success': False, 'error': f'Module not loaded: {getattr(self, "import_error", "unknown")}'}- data = params.get('data', [])- if isinstance(data, list):- data = pd.Series(data)- elif isinstance(data, dict):- data = pd.DataFrame(data)+ raw = params.get('data', [])+ if isinstance(raw, str):+ try:+ arr = self._parse_data(raw, **self._data_kwargs(params))+ data = pd.Series(arr)+ except Exception as e:+ return {'success': False, 'error': f'Could not parse data: {e}'}+ elif isinstance(raw, list):+ data = pd.Series(raw)+ elif isinstance(raw, dict):+ data = pd.DataFrame(raw)+ else:+ data = pd.Series(raw)data_type = params.get('data_type', 'general')data_name = params.get('data_name', 'data')diff --git a/fincept-qt/scripts/Analytics/statsmodels_wrapper/__init__.py b/fincept-qt/scripts/Analytics/statsmodels_wrapper/__init__.pyindex 187939c74..43ea30aed 100644--- a/fincept-qt/scripts/Analytics/statsmodels_wrapper/__init__.py+++ b/fincept-qt/scripts/Analytics/statsmodels_wrapper/__init__.py@@ -15,138 +15,10 @@ Comprehensive wrapper for statsmodels library covering:- GAM (Generalized Additive Models)"""-from .regression import (- fit_ols,- fit_wls,- fit_gls,- fit_glsar,- fit_recursive_ls,- predict_ols,- regression_diagnostics,- fit_rolling_ols,- fit_rolling_wls-)--from .timeseries_models import (- fit_arima,- forecast_arima,- fit_sarimax,- fit_varmax,- fit_autoreg,- fit_ardl,- fit_exponential_smoothing,- stl_decompose,- fit_dynamic_factor,- fit_unobserved_components,- fit_markov_regression,- fit_vecm,- fit_holt,- fit_simple_exp_smoothing,- fit_markov_autoregression,- stl_forecast-)--from .timeseries_funcs import (- calculate_acf,- calculate_pacf,- calculate_ccf,- adf_test,- kpss_test,- coint_test,- bds_test,- q_stat,- acorr_ljungbox,- seasonal_decompose_additive,- arma_order_select,- detrend_linear,- add_trend_to_data-)--from .glm import (- fit_glm,- fit_logit,- predict_logit,- fit_probit,- fit_poisson,- fit_negative_binomial,- fit_mnlogit,- fit_quantreg,- fit_gee,- fit_zero_inflated_poisson,- fit_conditional_logit,- fit_conditional_poisson,- fit_generalized_poisson,- fit_zero_inflated_generalized_poisson-)# Import stats_extended module (100+ additional statistical functions)from . import stats_extended-from .stats_tests import (- ttest_ind,- ttest_1samp,- ztest,- anova_lm,- proportions_ztest,- proportion_confint,- chisquare_test,- jarque_bera_test,- omnibus_normtest,- durbin_watson_test,- het_breuschpagan,- het_white,- het_arch,- acorr_breusch_godfrey,- linear_reset,- linear_harvey_collier,- multipletests_correction,- fdrcorrection_twostage,- compare_means,- descr_stats-)--from .power_analysis import (- ttest_power,- ftest_power,- proportion_power,- calculate_effect_size_cohens_d,- calculate_effect_size_proportion,- sample_size_proportion_confint,- chisquare_power,- anova_power-)--from .multivariate import (- perform_pca,- perform_factor_analysis,- perform_manova,- canonical_correlation-)--from .robust import (- fit_rlm,- mad,- huber_scale,- huber_location_scale-)--from .survival import (- fit_cox_ph,- survdiff,- kaplan_meier-)--from .nonparametric import (- kernel_density_estimation,- kernel_regression,- lowess_smoothing,- multivariate_kde-)--from .gam import (- fit_glm_gam,- fit_gam_formula-)__all__ = [# Regression@@ -189,3 +61,126 @@ __all__ = [# Extended stats module (100+ functions - access via stats_extended.function_name)'stats_extended']+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "fit_ols": ("regression", "fit_ols"),+ "fit_wls": ("regression", "fit_wls"),+ "fit_gls": ("regression", "fit_gls"),+ "fit_glsar": ("regression", "fit_glsar"),+ "fit_recursive_ls": ("regression", "fit_recursive_ls"),+ "predict_ols": ("regression", "predict_ols"),+ "regression_diagnostics": ("regression", "regression_diagnostics"),+ "fit_rolling_ols": ("regression", "fit_rolling_ols"),+ "fit_rolling_wls": ("regression", "fit_rolling_wls"),+ "fit_arima": ("timeseries_models", "fit_arima"),+ "forecast_arima": ("timeseries_models", "forecast_arima"),+ "fit_sarimax": ("timeseries_models", "fit_sarimax"),+ "fit_varmax": ("timeseries_models", "fit_varmax"),+ "fit_autoreg": ("timeseries_models", "fit_autoreg"),+ "fit_ardl": ("timeseries_models", "fit_ardl"),+ "fit_exponential_smoothing": ("timeseries_models", "fit_exponential_smoothing"),+ "stl_decompose": ("timeseries_models", "stl_decompose"),+ "fit_dynamic_factor": ("timeseries_models", "fit_dynamic_factor"),+ "fit_unobserved_components": ("timeseries_models", "fit_unobserved_components"),+ "fit_markov_regression": ("timeseries_models", "fit_markov_regression"),+ "fit_vecm": ("timeseries_models", "fit_vecm"),+ "fit_holt": ("timeseries_models", "fit_holt"),+ "fit_simple_exp_smoothing": ("timeseries_models", "fit_simple_exp_smoothing"),+ "fit_markov_autoregression": ("timeseries_models", "fit_markov_autoregression"),+ "stl_forecast": ("timeseries_models", "stl_forecast"),+ "calculate_acf": ("timeseries_funcs", "calculate_acf"),+ "calculate_pacf": ("timeseries_funcs", "calculate_pacf"),+ "calculate_ccf": ("timeseries_funcs", "calculate_ccf"),+ "adf_test": ("timeseries_funcs", "adf_test"),+ "kpss_test": ("timeseries_funcs", "kpss_test"),+ "coint_test": ("timeseries_funcs", "coint_test"),+ "bds_test": ("timeseries_funcs", "bds_test"),+ "q_stat": ("timeseries_funcs", "q_stat"),+ "acorr_ljungbox": ("timeseries_funcs", "acorr_ljungbox"),+ "seasonal_decompose_additive": ("timeseries_funcs", "seasonal_decompose_additive"),+ "arma_order_select": ("timeseries_funcs", "arma_order_select"),+ "detrend_linear": ("timeseries_funcs", "detrend_linear"),+ "add_trend_to_data": ("timeseries_funcs", "add_trend_to_data"),+ "fit_glm": ("glm", "fit_glm"),+ "fit_logit": ("glm", "fit_logit"),+ "predict_logit": ("glm", "predict_logit"),+ "fit_probit": ("glm", "fit_probit"),+ "fit_poisson": ("glm", "fit_poisson"),+ "fit_negative_binomial": ("glm", "fit_negative_binomial"),+ "fit_mnlogit": ("glm", "fit_mnlogit"),+ "fit_quantreg": ("glm", "fit_quantreg"),+ "fit_gee": ("glm", "fit_gee"),+ "fit_zero_inflated_poisson": ("glm", "fit_zero_inflated_poisson"),+ "fit_conditional_logit": ("glm", "fit_conditional_logit"),+ "fit_conditional_poisson": ("glm", "fit_conditional_poisson"),+ "fit_generalized_poisson": ("glm", "fit_generalized_poisson"),+ "fit_zero_inflated_generalized_poisson": ("glm", "fit_zero_inflated_generalized_poisson"),+ "ttest_ind": ("stats_tests", "ttest_ind"),+ "ttest_1samp": ("stats_tests", "ttest_1samp"),+ "ztest": ("stats_tests", "ztest"),+ "anova_lm": ("stats_tests", "anova_lm"),+ "proportions_ztest": ("stats_tests", "proportions_ztest"),+ "proportion_confint": ("stats_tests", "proportion_confint"),+ "chisquare_test": ("stats_tests", "chisquare_test"),+ "jarque_bera_test": ("stats_tests", "jarque_bera_test"),+ "omnibus_normtest": ("stats_tests", "omnibus_normtest"),+ "durbin_watson_test": ("stats_tests", "durbin_watson_test"),+ "het_breuschpagan": ("stats_tests", "het_breuschpagan"),+ "het_white": ("stats_tests", "het_white"),+ "het_arch": ("stats_tests", "het_arch"),+ "acorr_breusch_godfrey": ("stats_tests", "acorr_breusch_godfrey"),+ "linear_reset": ("stats_tests", "linear_reset"),+ "linear_harvey_collier": ("stats_tests", "linear_harvey_collier"),+ "multipletests_correction": ("stats_tests", "multipletests_correction"),+ "fdrcorrection_twostage": ("stats_tests", "fdrcorrection_twostage"),+ "compare_means": ("stats_tests", "compare_means"),+ "descr_stats": ("stats_tests", "descr_stats"),+ "ttest_power": ("power_analysis", "ttest_power"),+ "ftest_power": ("power_analysis", "ftest_power"),+ "proportion_power": ("power_analysis", "proportion_power"),+ "calculate_effect_size_cohens_d": ("power_analysis", "calculate_effect_size_cohens_d"),+ "calculate_effect_size_proportion": ("power_analysis", "calculate_effect_size_proportion"),+ "sample_size_proportion_confint": ("power_analysis", "sample_size_proportion_confint"),+ "chisquare_power": ("power_analysis", "chisquare_power"),+ "anova_power": ("power_analysis", "anova_power"),+ "perform_pca": ("multivariate", "perform_pca"),+ "perform_factor_analysis": ("multivariate", "perform_factor_analysis"),+ "perform_manova": ("multivariate", "perform_manova"),+ "canonical_correlation": ("multivariate", "canonical_correlation"),+ "fit_rlm": ("robust", "fit_rlm"),+ "mad": ("robust", "mad"),+ "huber_scale": ("robust", "huber_scale"),+ "huber_location_scale": ("robust", "huber_location_scale"),+ "fit_cox_ph": ("survival", "fit_cox_ph"),+ "survdiff": ("survival", "survdiff"),+ "kaplan_meier": ("survival", "kaplan_meier"),+ "kernel_density_estimation": ("nonparametric", "kernel_density_estimation"),+ "kernel_regression": ("nonparametric", "kernel_regression"),+ "lowess_smoothing": ("nonparametric", "lowess_smoothing"),+ "multivariate_kde": ("nonparametric", "multivariate_kde"),+ "fit_glm_gam": ("gam", "fit_glm_gam"),+ "fit_gam_formula": ("gam", "fit_gam_formula"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/talipp_wrapper/__init__.py b/fincept-qt/scripts/Analytics/talipp_wrapper/__init__.pyindex b831cb2e4..06e81a63e 100644--- a/fincept-qt/scripts/Analytics/talipp_wrapper/__init__.py+++ b/fincept-qt/scripts/Analytics/talipp_wrapper/__init__.py@@ -1,32 +1,3 @@-from .trend import (- calculate_sma, calculate_ema, calculate_wma, calculate_dema, calculate_tema,- calculate_hma, calculate_kama, calculate_alma, calculate_t3, calculate_zlema-)-from .momentum import (- calculate_rsi, calculate_macd, calculate_stoch, calculate_stoch_rsi,- calculate_cci, calculate_roc, calculate_tsi, calculate_williams-)-from .volatility import (- calculate_atr, calculate_bb, calculate_keltner, calculate_donchian,- calculate_chandelier_stop, calculate_natr-)-from .volume import (- calculate_obv, calculate_vwap, calculate_vwma, calculate_mfi,- calculate_chaikin_osc, calculate_force_index-)-from .trend_other import (- calculate_adx, calculate_aroon, calculate_ichimoku, calculate_parabolic_sar,- calculate_supertrend-)-from .specialized import (- calculate_ao, calculate_accu_dist, calculate_bop, calculate_chop,- calculate_coppock_curve, calculate_dpo, calculate_emv, calculate_fibonacci_retracement,- calculate_ibs, calculate_kst, calculate_kvo, calculate_mass_index,- calculate_mcginley_dynamic, calculate_mean_dev, calculate_pivots_hl,- calculate_rogers_satchell, calculate_sfx, calculate_smma, calculate_sobv,- calculate_stc, calculate_std_dev, calculate_trix, calculate_ttm,- calculate_uo, calculate_vtx, calculate_zigzag-)__all__ = ['calculate_sma', 'calculate_ema', 'calculate_wma', 'calculate_dema', 'calculate_tema',@@ -47,3 +18,90 @@ __all__ = ['calculate_stc', 'calculate_std_dev', 'calculate_trix', 'calculate_ttm','calculate_uo', 'calculate_vtx', 'calculate_zigzag']+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "calculate_sma": ("trend", "calculate_sma"),+ "calculate_ema": ("trend", "calculate_ema"),+ "calculate_wma": ("trend", "calculate_wma"),+ "calculate_dema": ("trend", "calculate_dema"),+ "calculate_tema": ("trend", "calculate_tema"),+ "calculate_hma": ("trend", "calculate_hma"),+ "calculate_kama": ("trend", "calculate_kama"),+ "calculate_alma": ("trend", "calculate_alma"),+ "calculate_t3": ("trend", "calculate_t3"),+ "calculate_zlema": ("trend", "calculate_zlema"),+ "calculate_rsi": ("momentum", "calculate_rsi"),+ "calculate_macd": ("momentum", "calculate_macd"),+ "calculate_stoch": ("momentum", "calculate_stoch"),+ "calculate_stoch_rsi": ("momentum", "calculate_stoch_rsi"),+ "calculate_cci": ("momentum", "calculate_cci"),+ "calculate_roc": ("momentum", "calculate_roc"),+ "calculate_tsi": ("momentum", "calculate_tsi"),+ "calculate_williams": ("momentum", "calculate_williams"),+ "calculate_atr": ("volatility", "calculate_atr"),+ "calculate_bb": ("volatility", "calculate_bb"),+ "calculate_keltner": ("volatility", "calculate_keltner"),+ "calculate_donchian": ("volatility", "calculate_donchian"),+ "calculate_chandelier_stop": ("volatility", "calculate_chandelier_stop"),+ "calculate_natr": ("volatility", "calculate_natr"),+ "calculate_obv": ("volume", "calculate_obv"),+ "calculate_vwap": ("volume", "calculate_vwap"),+ "calculate_vwma": ("volume", "calculate_vwma"),+ "calculate_mfi": ("volume", "calculate_mfi"),+ "calculate_chaikin_osc": ("volume", "calculate_chaikin_osc"),+ "calculate_force_index": ("volume", "calculate_force_index"),+ "calculate_adx": ("trend_other", "calculate_adx"),+ "calculate_aroon": ("trend_other", "calculate_aroon"),+ "calculate_ichimoku": ("trend_other", "calculate_ichimoku"),+ "calculate_parabolic_sar": ("trend_other", "calculate_parabolic_sar"),+ "calculate_supertrend": ("trend_other", "calculate_supertrend"),+ "calculate_ao": ("specialized", "calculate_ao"),+ "calculate_accu_dist": ("specialized", "calculate_accu_dist"),+ "calculate_bop": ("specialized", "calculate_bop"),+ "calculate_chop": ("specialized", "calculate_chop"),+ "calculate_coppock_curve": ("specialized", "calculate_coppock_curve"),+ "calculate_dpo": ("specialized", "calculate_dpo"),+ "calculate_emv": ("specialized", "calculate_emv"),+ "calculate_fibonacci_retracement": ("specialized", "calculate_fibonacci_retracement"),+ "calculate_ibs": ("specialized", "calculate_ibs"),+ "calculate_kst": ("specialized", "calculate_kst"),+ "calculate_kvo": ("specialized", "calculate_kvo"),+ "calculate_mass_index": ("specialized", "calculate_mass_index"),+ "calculate_mcginley_dynamic": ("specialized", "calculate_mcginley_dynamic"),+ "calculate_mean_dev": ("specialized", "calculate_mean_dev"),+ "calculate_pivots_hl": ("specialized", "calculate_pivots_hl"),+ "calculate_rogers_satchell": ("specialized", "calculate_rogers_satchell"),+ "calculate_sfx": ("specialized", "calculate_sfx"),+ "calculate_smma": ("specialized", "calculate_smma"),+ "calculate_sobv": ("specialized", "calculate_sobv"),+ "calculate_stc": ("specialized", "calculate_stc"),+ "calculate_std_dev": ("specialized", "calculate_std_dev"),+ "calculate_trix": ("specialized", "calculate_trix"),+ "calculate_ttm": ("specialized", "calculate_ttm"),+ "calculate_uo": ("specialized", "calculate_uo"),+ "calculate_vtx": ("specialized", "calculate_vtx"),+ "calculate_zigzag": ("specialized", "calculate_zigzag"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/tsmoothie_wrapper/__init__.py b/fincept-qt/scripts/Analytics/tsmoothie_wrapper/__init__.pyindex 391cc4ef6..3891a204d 100644--- a/fincept-qt/scripts/Analytics/tsmoothie_wrapper/__init__.py+++ b/fincept-qt/scripts/Analytics/tsmoothie_wrapper/__init__.py@@ -1,12 +1,3 @@-from .smoothers import (- smooth_lowess, smooth_convolution, smooth_spectral,- smooth_polynomial, smooth_spline, smooth_gaussian,- smooth_exponential, smooth_kalman, smooth_binner, smooth_decompose-)-from .intervals import (- get_sigma_intervals, get_confidence_intervals,- get_prediction_intervals, detect_outliers_sigma-)__all__ = ['smooth_lowess', 'smooth_convolution', 'smooth_spectral',@@ -15,3 +6,43 @@ __all__ = ['get_sigma_intervals', 'get_confidence_intervals','get_prediction_intervals', 'detect_outliers_sigma']+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "smooth_lowess": ("smoothers", "smooth_lowess"),+ "smooth_convolution": ("smoothers", "smooth_convolution"),+ "smooth_spectral": ("smoothers", "smooth_spectral"),+ "smooth_polynomial": ("smoothers", "smooth_polynomial"),+ "smooth_spline": ("smoothers", "smooth_spline"),+ "smooth_gaussian": ("smoothers", "smooth_gaussian"),+ "smooth_exponential": ("smoothers", "smooth_exponential"),+ "smooth_kalman": ("smoothers", "smooth_kalman"),+ "smooth_binner": ("smoothers", "smooth_binner"),+ "smooth_decompose": ("smoothers", "smooth_decompose"),+ "get_sigma_intervals": ("intervals", "get_sigma_intervals"),+ "get_confidence_intervals": ("intervals", "get_confidence_intervals"),+ "get_prediction_intervals": ("intervals", "get_prediction_intervals"),+ "detect_outliers_sigma": ("intervals", "detect_outliers_sigma"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/Analytics/vnpy_wrapper/__init__.py b/fincept-qt/scripts/Analytics/vnpy_wrapper/__init__.pyindex 5b63a88f2..07198c4bf 100644--- a/fincept-qt/scripts/Analytics/vnpy_wrapper/__init__.py+++ b/fincept-qt/scripts/Analytics/vnpy_wrapper/__init__.py@@ -1,34 +1,3 @@-from .engine import (- create_main_engine,- send_order,- cancel_order,- subscribe_market_data,- query_history,- get_all_contracts,- get_all_positions,- get_all_orders,- get_all_trades,-)-from .data import (- create_tick_data,- create_bar_data,- create_order_request,- create_cancel_request,- tick_to_dict,- bar_to_dict,- order_to_dict,- trade_to_dict,- position_to_dict,- account_to_dict,-)-from .utility import (- convert_direction,- convert_order_type,- convert_offset,- convert_exchange,- get_trading_date,- calculate_pnl,-)__all__ = ['create_main_engine',@@ -57,3 +26,54 @@ __all__ = ['get_trading_date','calculate_pnl',]+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "create_main_engine": ("engine", "create_main_engine"),+ "send_order": ("engine", "send_order"),+ "cancel_order": ("engine", "cancel_order"),+ "subscribe_market_data": ("engine", "subscribe_market_data"),+ "query_history": ("engine", "query_history"),+ "get_all_contracts": ("engine", "get_all_contracts"),+ "get_all_positions": ("engine", "get_all_positions"),+ "get_all_orders": ("engine", "get_all_orders"),+ "get_all_trades": ("engine", "get_all_trades"),+ "create_tick_data": ("data", "create_tick_data"),+ "create_bar_data": ("data", "create_bar_data"),+ "create_order_request": ("data", "create_order_request"),+ "create_cancel_request": ("data", "create_cancel_request"),+ "tick_to_dict": ("data", "tick_to_dict"),+ "bar_to_dict": ("data", "bar_to_dict"),+ "order_to_dict": ("data", "order_to_dict"),+ "trade_to_dict": ("data", "trade_to_dict"),+ "position_to_dict": ("data", "position_to_dict"),+ "account_to_dict": ("data", "account_to_dict"),+ "convert_direction": ("utility", "convert_direction"),+ "convert_order_type": ("utility", "convert_order_type"),+ "convert_offset": ("utility", "convert_offset"),+ "convert_exchange": ("utility", "convert_exchange"),+ "get_trading_date": ("utility", "get_trading_date"),+ "calculate_pnl": ("utility", "calculate_pnl"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/__init__.py b/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/__init__.pyindex 8e7b97979..a89d091c0 100644--- a/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/__init__.py+++ b/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/__init__.py@@ -22,7 +22,6 @@ Built on Agno framework with ALL key features:- Tracing: Distributed observability with spans and metrics collection"""-from .main import RenaissanceTechnologiesSystemfrom .config import get_config, set_config, RenTechConfig# Teams@@ -208,3 +207,30 @@ __all__ = ["get_metrics_collector",]__version__ = "3.0.0"+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "RenaissanceTechnologiesSystem": ("main", "RenaissanceTechnologiesSystem"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tests/__init__.py b/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tests/__init__.pyindex 95343a8ad..156f1cd53 100644--- a/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tests/__init__.py+++ b/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/tests/__init__.py@@ -4,8 +4,34 @@ Renaissance Technologies Test SuiteTests for the multi-agent system."""-from .test_glm_model import run_all_tests__all__ = ["run_all_tests",]+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "run_all_tests": ("test_glm_model", "run_all_tests"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/__init__.py b/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/__init__.pyindex d4c8d40bd..4b78b5edc 100644--- a/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/__init__.py+++ b/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/utils/__init__.py@@ -24,19 +24,6 @@ from .embedder_factory import (create_embedder_from_config,)-from .paths import (- get_app_data_dir,- get_rentech_data_dir,- get_knowledge_base_path,- get_memory_db_path,- get_logs_dir,- get_cache_dir,- get_frontend_db_path,- get_knowledge_path,- get_memory_path,- get_log_file_path,- get_cache_file_path,-)__all__ = ["StockData",@@ -66,3 +53,40 @@ __all__ = ["get_log_file_path","get_cache_file_path",]+++# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────+# Submodules below have an `if __name__ == "__main__":` block and may be+# invoked via `python -m`. Eagerly importing them here would put each in+# sys.modules before Python re-executes them as __main__, triggering a+# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy+# loader keeps the public API intact while deferring import to first access.+_LAZY_ATTRS: dict[str, tuple[str, str]] = {+ "get_app_data_dir": ("paths", "get_app_data_dir"),+ "get_rentech_data_dir": ("paths", "get_rentech_data_dir"),+ "get_knowledge_base_path": ("paths", "get_knowledge_base_path"),+ "get_memory_db_path": ("paths", "get_memory_db_path"),+ "get_logs_dir": ("paths", "get_logs_dir"),+ "get_cache_dir": ("paths", "get_cache_dir"),+ "get_frontend_db_path": ("paths", "get_frontend_db_path"),+ "get_knowledge_path": ("paths", "get_knowledge_path"),+ "get_memory_path": ("paths", "get_memory_path"),+ "get_log_file_path": ("paths", "get_log_file_path"),+ "get_cache_file_path": ("paths", "get_cache_file_path"),+}+++def __getattr__(name: str): # PEP 562+ target = _LAZY_ATTRS.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ submodule, original_name = target+ import importlib+ mod = importlib.import_module(f".{submodule}", __name__)+ value = getattr(mod, original_name)+ globals()[name] = value # cache for subsequent access+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_LAZY_ATTRS))diff --git a/fincept-qt/scripts/databento_provider.py b/fincept-qt/scripts/databento_provider.pyindex 88fc15b31..56a8d5a51 100644--- a/fincept-qt/scripts/databento_provider.py+++ b/fincept-qt/scripts/databento_provider.py@@ -13,6 +13,7 @@ NOTE: Databento is a paid service - be mindful of API usage costs.import sysimport json+import timefrom datetime import datetime, timedeltafrom typing import Dict, List, Optional, Anyimport math@@ -152,6 +153,10 @@ class DatabentoProvider:raise ValueError("API key cannot be empty")self.api_key = api_key.strip()+ # Per-dataset available end timestamp cache. Populated lazily via+ # _available_end(); used to clamp user-supplied end dates so the+ # API never sees a window that runs past the dataset's edge.+ self._range_cache = {}try:self.client = db.Historical(key=self.api_key)except Exception as e:@@ -336,6 +341,116 @@ class DatabentoProvider:"timestamp": int(datetime.now().timestamp())}+ def _parse_iso(self, s: str) -> Optional[datetime]:+ """+ Parse a Databento ISO string. The API returns 9-digit nanosecond+ precision (e.g. '2026-04-27T13:30:00.000000000Z') which Python's+ strptime cannot handle directly — %f tops out at microseconds. We+ peel the fractional + zone suffix and parse the leading 19 chars.+ """+ if not s:+ return None+ try:+ return datetime.strptime(str(s)[:19], "%Y-%m-%dT%H:%M:%S")+ except (ValueError, TypeError):+ return None++ def _available_end(self, dataset: str, schema: Optional[str] = None) -> Optional[datetime]:+ """+ Return the dataset's most-recent available end as a UTC datetime.+ Cached for the life of the provider instance.++ Databento publishes data with multi-hour-to-multi-day lag depending+ on schema; "today midnight" is almost always *after* the available+ end and yields a `data_end_after_available_end` 422. Callers must+ clamp their end-of-window to this value.++ When `schema` is given, returns the per-schema end (e.g. ohlcv-1d+ often lags definitions by 2-3 days). Otherwise returns the dataset+ envelope's end.++ NOTE: the Databento SDK returns a *dict*, not an object, so we use+ subscript access not getattr.+ """+ cache_key = f"{dataset}:{schema or '*'}"+ if cache_key in self._range_cache:+ return self._range_cache[cache_key]+ try:+ r = self.client.metadata.get_dataset_range(dataset=dataset)+ # SDK returns dict: {"start": "...", "end": "...", "schema": {...}}+ end_str = ""+ if isinstance(r, dict):+ if schema and isinstance(r.get("schema"), dict):+ sch = r["schema"].get(schema)+ if isinstance(sch, dict):+ end_str = sch.get("end") or ""+ if not end_str:+ end_str = r.get("end") or ""+ else:+ # Object-style fallback (older SDK shape)+ end_str = str(getattr(r, "end", "")) or ""+ parsed = self._parse_iso(end_str)+ self._range_cache[cache_key] = parsed+ return parsed+ except Exception:+ self._range_cache[cache_key] = None+ return None++ def _cache_dir(self) -> str:+ """+ Per-user disk cache for expensive Databento responses (definitions,+ OHLCV). Lives under the OS temp dir so it gets cleaned automatically+ on reboot but persists across app sessions for the day.+ """+ import tempfile+ d = os.path.join(tempfile.gettempdir(), "fincept_databento_cache")+ try:+ os.makedirs(d, exist_ok=True)+ except OSError:+ pass+ return d++ def _cache_load(self, key: str, max_age_seconds: int = 6 * 3600):+ """Load a cached JSON blob if it exists and is younger than max_age."""+ path = os.path.join(self._cache_dir(), key + ".json")+ if not os.path.exists(path):+ return None+ try:+ age = time.time() - os.path.getmtime(path)+ if age > max_age_seconds:+ return None+ with open(path, "r", encoding="utf-8") as f:+ return json.load(f)+ except (OSError, ValueError):+ return None++ def _cache_save(self, key: str, value) -> None:+ """Persist a JSON-serialisable blob to the cache. Failures are silent."""+ path = os.path.join(self._cache_dir(), key + ".json")+ try:+ with open(path, "w", encoding="utf-8") as f:+ json.dump(value, f)+ except (OSError, TypeError):+ pass++ def _clamp_window(self, dataset: str, start: datetime, end: datetime,+ schema: Optional[str] = None) -> tuple:+ """+ Clamp [start, end] so end is never beyond the dataset's available end.+ If the resulting window is empty, walk start back enough days to make+ a 24h window valid against the cap.+ """+ cap = self._available_end(dataset, schema)+ if cap is None:+ # Metadata lookup failed — defensive: cap to "yesterday" since+ # Databento data is never published instantaneously.+ cap = datetime.utcnow() - timedelta(days=1)+ if end > cap:+ end = cap+ if start >= end:+ start = end - timedelta(days=1)+ return start, end+def get_options_definitions(self,symbol: str,@@ -356,7 +471,21 @@ class DatabentoProvider:if not date:date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")+ # Definitions are stable for any past date — cache them aggressively.+ # First fetch for SPY takes ~40s (12k rows); subsequent fetches for+ # the same (symbol, date) hit the disk cache in <100ms.+ cache_key = f"defs_{self.OPRA_DATASET.replace('.', '_')}_{symbol}_{date}"+ cached = self._cache_load(cache_key, max_age_seconds=24 * 3600)+ if cached is not None:+ return cached+target_date = datetime.strptime(date, "%Y-%m-%d")+ window_start, window_end = self._clamp_window(+ self.OPRA_DATASET,+ target_date,+ target_date + timedelta(days=1),+ schema="definition",+ )# Fetch option definitions using parent symbologydata = self.client.timeseries.get_range(@@ -364,28 +493,59 @@ class DatabentoProvider:schema="definition",symbols=[f"{symbol}.OPT"],stype_in="parent",- start=target_date.strftime("%Y-%m-%d"),- end=(target_date + timedelta(days=1)).strftime("%Y-%m-%d"),+ start=window_start.strftime("%Y-%m-%dT%H:%M:%S"),+ end=window_end.strftime("%Y-%m-%dT%H:%M:%S"),)- # Process definitions+ # Vectorised processing via pandas — ~5x faster than the row-by-row+ # Python loop on 12k+ rows. Falls back to iteration if pandas is+ # unavailable.options = []- for row in data:- # Handle fixed-point strike price- strike_raw = getattr(row, 'strike_price', 0)- strike = strike_raw / 1e9 if strike_raw > 1e6 else strike_raw-- options.append({- "ts_recv": str(getattr(row, 'ts_recv', 0)),- "raw_symbol": str(getattr(row, 'raw_symbol', '')),- "expiration": str(getattr(row, 'expiration', 0)),- "instrument_class": str(getattr(row, 'instrument_class', '')),- "strike_price": strike,- "underlying": str(getattr(row, 'underlying', '')),- "instrument_id": int(getattr(row, 'instrument_id', 0)),- })+ if PANDAS_AVAILABLE:+ df = data.to_df()+ if not df.empty:+ # Dedup by raw_symbol — OPRA fans out one row per venue.+ if 'raw_symbol' in df.columns:+ df = df.drop_duplicates(subset=['raw_symbol'])+ # Normalise fixed-point strike (1e9 scale).+ if 'strike_price' in df.columns:+ df['_strike'] = df['strike_price'].apply(+ lambda v: v / 1e9 if v and v > 1e6 else v)+ else:+ df['_strike'] = 0.0+ cols = {+ 'ts_recv': df.get('ts_recv', ''),+ 'raw_symbol': df.get('raw_symbol', ''),+ 'expiration': df.get('expiration', 0),+ 'instrument_class': df.get('instrument_class', ''),+ 'underlying': df.get('underlying', ''),+ 'instrument_id': df.get('instrument_id', 0),+ }+ for i in range(len(df)):+ options.append({+ "ts_recv": str(cols['ts_recv'].iloc[i]) if hasattr(cols['ts_recv'], 'iloc') else "",+ "raw_symbol": str(cols['raw_symbol'].iloc[i]) if hasattr(cols['raw_symbol'], 'iloc') else "",+ "expiration": str(cols['expiration'].iloc[i]) if hasattr(cols['expiration'], 'iloc') else "0",+ "instrument_class": str(cols['instrument_class'].iloc[i]) if hasattr(cols['instrument_class'], 'iloc') else "",+ "strike_price": float(df['_strike'].iloc[i]),+ "underlying": str(cols['underlying'].iloc[i]) if hasattr(cols['underlying'], 'iloc') else "",+ "instrument_id": int(cols['instrument_id'].iloc[i]) if hasattr(cols['instrument_id'], 'iloc') else 0,+ })+ else:+ for row in data:+ strike_raw = getattr(row, 'strike_price', 0)+ strike = strike_raw / 1e9 if strike_raw > 1e6 else strike_raw+ options.append({+ "ts_recv": str(getattr(row, 'ts_recv', 0)),+ "raw_symbol": str(getattr(row, 'raw_symbol', '')),+ "expiration": str(getattr(row, 'expiration', 0)),+ "instrument_class": str(getattr(row, 'instrument_class', '')),+ "strike_price": strike,+ "underlying": str(getattr(row, 'underlying', '')),+ "instrument_id": int(getattr(row, 'instrument_id', 0)),+ })- return {+ result = {"error": False,"symbol": symbol,"date": date,@@ -394,6 +554,8 @@ class DatabentoProvider:"data": options,"timestamp": int(datetime.now().timestamp())}+ self._cache_save(cache_key, result)+ return resultexcept Exception as e:error_msg = str(e)@@ -660,6 +822,168 @@ class DatabentoProvider:"timestamp": int(datetime.now().timestamp())}+ def list_publishers(self, dataset: Optional[str] = None) -> Dict[str, Any]:+ """+ List all publishers (venues) — optionally filtered to one dataset.+ Used by the Surface Analytics control panel to populate the OPRA-venue+ multi-select for option-surface fetches.+ """+ try:+ publishers = self.client.metadata.list_publishers()+ rows = []+ for p in publishers:+ row = {+ "publisher_id": getattr(p, "publisher_id", None),+ "dataset": getattr(p, "dataset", None),+ "venue": getattr(p, "venue", None),+ "description": getattr(p, "description", None),+ }+ # Some SDK versions return dicts instead of objects+ if all(v is None for v in row.values()) and isinstance(p, dict):+ row = {k: p.get(k) for k in row}+ if dataset and row.get("dataset") != dataset:+ continue+ rows.append(row)+ return {+ "error": False,+ "dataset": dataset,+ "publishers": rows,+ "count": len(rows),+ "timestamp": int(datetime.now().timestamp())+ }+ except Exception as e:+ return {+ "error": True,+ "message": f"Failed to list publishers: {str(e)}",+ "dataset": dataset,+ "timestamp": int(datetime.now().timestamp())+ }++ def get_dataset_range(self, dataset: str) -> Dict[str, Any]:+ """+ Return per-schema available date range for a dataset. Surface Analytics+ uses this to set sensible default start/end dates in date-edits.+ """+ try:+ r = self.client.metadata.get_dataset_range(dataset=dataset)+ schema_ranges = {}+ schemas = getattr(r, "schema", None)+ if isinstance(schemas, dict):+ for schema_name, rng in schemas.items():+ if isinstance(rng, dict):+ schema_ranges[str(schema_name)] = {+ "start": str(rng.get("start")) if rng.get("start") else None,+ "end": str(rng.get("end")) if rng.get("end") else None,+ }+ else:+ schema_ranges[str(schema_name)] = {+ "start": str(getattr(rng, "start", None)),+ "end": str(getattr(rng, "end", None)),+ }+ return {+ "error": False,+ "dataset": dataset,+ "start": str(getattr(r, "start", None)),+ "end": str(getattr(r, "end", None)),+ "schemas": schema_ranges,+ "timestamp": int(datetime.now().timestamp())+ }+ except Exception as e:+ return {+ "error": True,+ "message": f"Failed to get dataset range: {str(e)}",+ "dataset": dataset,+ "timestamp": int(datetime.now().timestamp())+ }++ def symbol_search(+ self,+ query: str,+ dataset: Optional[str] = None,+ limit: int = 50,+ ) -> Dict[str, Any]:+ """+ Search for raw_symbols whose prefix matches `query` against a dataset's+ instrument definitions. Walks back up to 7 days to give the latest+ in-force universe. Used by the Surface Analytics asset-search field.+ """+ try:+ ds = dataset or self.XNAS_DATASET+ end = datetime.now()+ # Definitions for OPRA / GLBX are end-of-day — walk back enough days+ # to land on a populated session.+ start = end - timedelta(days=7)+ try:+ data = self.client.timeseries.get_range(+ dataset=ds,+ schema="definition",+ start=start.strftime("%Y-%m-%dT00:00:00"),+ end=end.strftime("%Y-%m-%dT00:00:00"),+ limit=2000,+ )+ except Exception:+ # Fallback: if the user has only a search index, try resolving+ # the raw query directly.+ resolution = self.client.symbology.resolve(+ dataset=ds,+ symbols=[query],+ stype_in="raw_symbol",+ stype_out="instrument_id",+ start_date=start.strftime("%Y-%m-%d"),+ end_date=end.strftime("%Y-%m-%d"),+ )+ hits = []+ for sym, mappings in (resolution.get("result", {}) or {}).items():+ if mappings:+ hits.append({"raw_symbol": sym})+ return {+ "error": False,+ "query": query,+ "dataset": ds,+ "matches": hits[:limit],+ "count": len(hits[:limit]),+ "timestamp": int(datetime.now().timestamp())+ }++ seen = set()+ matches = []+ q_upper = query.upper().strip()+ for record in data:+ raw = getattr(record, "raw_symbol", None)+ if not raw:+ continue+ rs = raw.strip()+ if rs in seen:+ continue+ if q_upper and q_upper not in rs.upper():+ continue+ seen.add(rs)+ matches.append({+ "raw_symbol": rs,+ "asset": getattr(record, "asset", None),+ "underlying": getattr(record, "underlying", None),+ "instrument_class": getattr(record, "instrument_class", None),+ "exchange": getattr(record, "exchange", None),+ })+ if len(matches) >= limit:+ break+ return {+ "error": False,+ "query": query,+ "dataset": ds,+ "matches": matches,+ "count": len(matches),+ "timestamp": int(datetime.now().timestamp())+ }+ except Exception as e:+ return {+ "error": True,+ "message": f"Symbol search failed: {str(e)}",+ "query": query,+ "dataset": dataset,+ "timestamp": int(datetime.now().timestamp())+ }+# ========================================================================# Reference Data API (security_master, corporate_actions, adjustment_factors)# ========================================================================@@ -1106,6 +1430,8 @@ class DatabentoProvider:# Fetch quotes using cmbp-1 schema (consolidated market-by-price)market_open = target_date.replace(hour=9, minute=30)market_end = market_open + timedelta(minutes=duration_minutes)+ market_open, market_end = self._clamp_window(+ self.OPRA_DATASET, market_open, market_end, schema="cmbp-1")data = self.client.timeseries.get_range(dataset=self.OPRA_DATASET,@@ -1248,44 +1574,62 @@ class DatabentoProvider:option_symbols = [d["raw_symbol"] for d in filtered[:200]]# Step 2: Get daily close prices via ohlcv-1d- # Use to_df() which resolves symbols properly (raw iteration gives '?')+ # Clamp the window so we never query past the dataset's available end.+ ohlcv_start, ohlcv_end = self._clamp_window(+ self.OPRA_DATASET, target_date, target_date + timedelta(days=1),+ schema="ohlcv-1d")++ # Cache the OHLCV daily bars per (symbol, date). Past sessions+ # are immutable so we can keep them for 24h.+ ohlcv_cache_key = (f"ohlcv1d_{self.OPRA_DATASET.replace('.', '_')}"+ f"_{symbol}_{ohlcv_start.strftime('%Y%m%d')}")+ cached_prices = self._cache_load(ohlcv_cache_key, max_age_seconds=24 * 3600)prices = {}- try:- price_data = self.client.timeseries.get_range(- dataset=self.OPRA_DATASET,- schema="ohlcv-1d",- symbols=option_symbols,- stype_in="raw_symbol",- start=target_date.strftime("%Y-%m-%d"),- end=(target_date + timedelta(days=1)).strftime("%Y-%m-%d"),- )- if PANDAS_AVAILABLE:- df = price_data.to_df()- if not df.empty:- # Group by symbol, aggregate: volume-weighted close- for sym, grp in df.groupby('symbol'):- grp_sorted = grp.sort_values('volume', ascending=False)- row0 = grp_sorted.iloc[0]- close = float(row0['close'])- vol = int(row0['volume'])- if close > 1e6:- close = close / 1e9+ if cached_prices is not None:+ # Cached as {raw_symbol: [close, volume]}+ prices = {k: tuple(v) for k, v in cached_prices.items()}+ else:+ try:+ price_data = self.client.timeseries.get_range(+ dataset=self.OPRA_DATASET,+ schema="ohlcv-1d",+ symbols=option_symbols,+ stype_in="raw_symbol",+ start=ohlcv_start.strftime("%Y-%m-%dT%H:%M:%S"),+ end=ohlcv_end.strftime("%Y-%m-%dT%H:%M:%S"),+ )+ if PANDAS_AVAILABLE:+ df = price_data.to_df()+ if not df.empty:+ # Group by symbol, aggregate: volume-weighted close+ for sym, grp in df.groupby('symbol'):+ grp_sorted = grp.sort_values('volume', ascending=False)+ row0 = grp_sorted.iloc[0]+ close = float(row0['close'])+ vol = int(row0['volume'])+ if close > 1e6:+ close = close / 1e9+ if close > 0 and vol > 0:+ prices[str(sym)] = (close, vol)+ else:+ # Fallback without pandas — use instrument_id matching+ for row in price_data:+ iid = str(getattr(row, 'instrument_id', ''))+ close_raw = getattr(row, 'close', 0)+ close = close_raw / 1e9 if close_raw > 1e6 else close_raw+ vol = getattr(row, 'volume', 0)if close > 0 and vol > 0:- prices[str(sym)] = (close, vol)- else:- # Fallback without pandas — use instrument_id matching- for row in price_data:- iid = str(getattr(row, 'instrument_id', ''))- close_raw = getattr(row, 'close', 0)- close = close_raw / 1e9 if close_raw > 1e6 else close_raw- vol = getattr(row, 'volume', 0)- if close > 0 and vol > 0:- if iid not in prices or vol > prices[iid][1]:- prices[iid] = (close, vol)- except Exception as e:- return {"error": True,- "message": f"Failed to fetch option prices: {e}",- "timestamp": int(datetime.now().timestamp())}+ if iid not in prices or vol > prices[iid][1]:+ prices[iid] = (close, vol)+ # Persist to disk so subsequent fetches for the same date+ # (e.g. switching between vol/delta/gamma views) are instant.+ if prices:+ self._cache_save(ohlcv_cache_key,+ {k: list(v) for k, v in prices.items()})+ except Exception as e:+ return {"error": True,+ "message": f"Failed to fetch option prices: {e}",+ "timestamp": int(datetime.now().timestamp())}if not prices:return {"error": True,@@ -1312,17 +1656,24 @@ class DatabentoProvider:if strike <= 0:continue- # Parse expiration from definition- exp_str = str(defn.get("expiration", ""))- try:- if len(exp_str) > 15: # nanosecond timestamp- ts_val = int(exp_str)- exp_dt = datetime.utcfromtimestamp(ts_val // 1_000_000_000)- elif len(exp_str) >= 10:+ # Parse expiration from definition. Accepts:+ # "1789689600000000000" (nanosecond timestamp, raw SDK)+ # "2026-09-18" (date only)+ # "2026-09-18 00:00:00+00:00" (pandas to_df() Timestamp)+ # "2026-09-18T00:00:00.000000000Z" (ISO with nanos)+ exp_str = str(defn.get("expiration", "")).strip()+ exp_dt = None+ if exp_str.isdigit() and len(exp_str) >= 16:+ try:+ exp_dt = datetime.utcfromtimestamp(int(exp_str) // 1_000_000_000)+ except (ValueError, OSError):+ exp_dt = None+ if exp_dt is None and len(exp_str) >= 10:+ try:exp_dt = datetime.strptime(exp_str[:10], "%Y-%m-%d")- else:- continue- except Exception:+ except ValueError:+ exp_dt = None+ if exp_dt is None:continuedte = max(1, (exp_dt - now).days)@@ -3038,6 +3389,20 @@ def main():dataset = args.get('dataset')result = provider.list_schemas(dataset)+ elif command == "list_publishers" or command == "publishers":+ dataset = args.get('dataset')+ result = provider.list_publishers(dataset)++ elif command == "dataset_range":+ dataset = args.get('dataset', 'OPRA.PILLAR')+ result = provider.get_dataset_range(dataset)++ elif command == "symbol_search":+ query = args.get('query', '')+ dataset = args.get('dataset')+ limit = int(args.get('limit', 50))+ result = provider.symbol_search(query, dataset, limit)+# Reference Data commandselif command == "security_master":symbols = args.get('symbols', ['SPY'])diff --git a/fincept-qt/scripts/mcp/edgar/base.py b/fincept-qt/scripts/mcp/edgar/base.pyindex 94fddf52b..8ae00aa49 100644--- a/fincept-qt/scripts/mcp/edgar/base.py+++ b/fincept-qt/scripts/mcp/edgar/base.py@@ -185,16 +185,23 @@ def find_company_by_name(query: str, top_n: int = 10) -> Dict[str, Any]:"query": query}- # Convert results to list+ # Convert results to list. edgartools.find_company can yield Company+ # objects, plain dicts, or (occasionally) None placeholders depending+ # on version — guard each access so a malformed entry doesn't blow up+ # the whole call.companies = []for i, company in enumerate(results):if i >= top_n:break+ if company is None:+ continue+ tickers = getattr(company, 'tickers', None) or []+ ticker = tickers[0] if tickers else Nonecompanies.append({- "ticker": company.tickers[0] if company.tickers else None,- "cik": company.cik,- "name": company.name,- "industry": company.industry if hasattr(company, 'industry') else None,+ "ticker": ticker,+ "cik": getattr(company, 'cik', None),+ "name": getattr(company, 'name', None),+ "industry": getattr(company, 'industry', None),})return {diff --git a/fincept-qt/src/ai_chat/AiChatScreen.cpp b/fincept-qt/src/ai_chat/AiChatScreen.cppindex adb9dddaa..1ac9bc738 100644--- a/fincept-qt/src/ai_chat/AiChatScreen.cpp+++ b/fincept-qt/src/ai_chat/AiChatScreen.cpp@@ -228,7 +228,10 @@ void AiChatScreen::build_ui() {void AiChatScreen::build_sidebar() {sidebar_ = new QWidget;- sidebar_->setFixedWidth(280);+ // Use min/max width pair instead of setFixedWidth so the collapse+ // animation can drive maximumWidth between 0 and kSidebarExpandedWidth.+ sidebar_->setMinimumWidth(0);+ sidebar_->setMaximumWidth(kSidebarExpandedWidth);sidebar_->setStyleSheet(QString("background:%1;border-right:1px solid %2;").arg(col::BG_SURFACE(), col::BORDER_DIM()));@@ -408,9 +411,24 @@ QWidget* AiChatScreen::build_header_bar() {bar->setFixedHeight(52);bar->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;").arg(col::BG_RAISED(), col::BORDER_DIM()));auto* hl = new QHBoxLayout(bar);- hl->setContentsMargins(20, 0, 16, 0);+ hl->setContentsMargins(8, 0, 16, 0);hl->setSpacing(10);+ // Sidebar collapse toggle. Lives at the left edge of the chat header so+ // it remains visible (and can re-expand the sidebar) even when the+ // sidebar is collapsed to width 0.+ sidebar_toggle_btn_ = new QPushButton("‹");+ sidebar_toggle_btn_->setFixedSize(28, 28);+ sidebar_toggle_btn_->setCursor(Qt::PointingHandCursor);+ sidebar_toggle_btn_->setToolTip("Collapse sidebar (Ctrl+B)");+ sidebar_toggle_btn_->setShortcut(QKeySequence("Ctrl+B"));+ sidebar_toggle_btn_->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"+ "border-radius:0px;font-size:18px;font-weight:700;padding:0;}"+ "QPushButton:hover{background:%3;color:%4;border-color:%4;}")+ .arg(col::TEXT_SECONDARY(), col::BORDER_DIM(), col::BG_HOVER(), col::AMBER()));+ connect(sidebar_toggle_btn_, &QPushButton::clicked, this, &AiChatScreen::on_toggle_sidebar);+ hl->addWidget(sidebar_toggle_btn_);+// Status dothdr_status_dot_ = new QLabel;hdr_status_dot_->setFixedSize(8, 8);@@ -640,6 +658,41 @@ bool AiChatScreen::eventFilter(QObject* obj, QEvent* event) {return QWidget::eventFilter(obj, event);}+void AiChatScreen::on_toggle_sidebar() {+ apply_sidebar_collapsed(!sidebar_collapsed_, /*animate=*/true);+ ScreenStateManager::instance().notify_changed(this);+}++void AiChatScreen::apply_sidebar_collapsed(bool collapsed, bool animate) {+ sidebar_collapsed_ = collapsed;+ if (!sidebar_)+ return;++ const int target = collapsed ? 0 : kSidebarExpandedWidth;++ // Lazily create the animation so the helper works even before the first+ // user toggle (e.g. when restore_state runs before the screen is shown).+ if (!sidebar_anim_) {+ sidebar_anim_ = new QPropertyAnimation(sidebar_, "maximumWidth", this);+ sidebar_anim_->setDuration(180);+ sidebar_anim_->setEasingCurve(QEasingCurve::OutCubic);+ }++ sidebar_anim_->stop();+ if (animate) {+ sidebar_anim_->setStartValue(sidebar_->maximumWidth());+ sidebar_anim_->setEndValue(target);+ sidebar_anim_->start();+ } else {+ sidebar_->setMaximumWidth(target);+ }++ if (sidebar_toggle_btn_) {+ sidebar_toggle_btn_->setText(collapsed ? "›" : "‹");+ sidebar_toggle_btn_->setToolTip(collapsed ? "Expand sidebar (Ctrl+B)" : "Collapse sidebar (Ctrl+B)");+ }+}+void AiChatScreen::on_search_changed(const QString& text) {const QString filter = text.trimmed().toLower();for (int i = 0; i < session_list_->count(); ++i) {@@ -1287,6 +1340,7 @@ QVariantMap AiChatScreen::save_state() const {s.insert("scroll", scroll_area_->verticalScrollBar()->value());if (!attached_file_path_.isEmpty())s.insert("attached_file", attached_file_path_);+ s.insert("sidebar_collapsed", sidebar_collapsed_);return s;}@@ -1327,6 +1381,11 @@ void AiChatScreen::restore_state(const QVariantMap& state) {}}+ // Sidebar collapsed state — apply without animation on restore so the+ // user lands on the previously chosen layout immediately.+ if (state.contains("sidebar_collapsed"))+ apply_sidebar_collapsed(state.value("sidebar_collapsed").toBool(), /*animate=*/false);+// Scroll position — defer until after message_layout has laid out,// otherwise the scrollbar max is still 0.const int scroll = state.value("scroll", -1).toInt();diff --git a/fincept-qt/src/ai_chat/AiChatScreen.h b/fincept-qt/src/ai_chat/AiChatScreen.hindex 7c6d7b998..267945f6b 100644--- a/fincept-qt/src/ai_chat/AiChatScreen.h+++ b/fincept-qt/src/ai_chat/AiChatScreen.h@@ -9,6 +9,7 @@#include <QMutex>#include <QPlainTextEdit>#include <QPointer>+#include <QPropertyAnimation>#include <QPushButton>#include <QScrollArea>#include <QTimer>@@ -28,7 +29,8 @@ class AiChatScreen : public QWidget, public IStatefulScreen {QVariantMap save_state() const override;QString state_key() const override { return "ai_chat"; }// v2 adds: draft text, search text, scroll position, attached file path.- int state_version() const override { return 2; }+ // v3 adds: sidebar_collapsed.+ int state_version() const override { return 3; }protected:void showEvent(QShowEvent* e) override;@@ -48,6 +50,7 @@ class AiChatScreen : public QWidget, public IStatefulScreen {void on_provider_changed();void on_search_changed(const QString& text);void on_typing_indicator_tick();+ void on_toggle_sidebar();private:// ── Sidebar ──────────────────────────────────────────────────────────@@ -60,6 +63,13 @@ class AiChatScreen : public QWidget, public IStatefulScreen {QLabel* provider_lbl_ = nullptr;QLabel* model_lbl_ = nullptr;+ // ── Sidebar collapse state ───────────────────────────────────────────+ QPushButton* sidebar_toggle_btn_ = nullptr;+ QPropertyAnimation* sidebar_anim_ = nullptr;+ bool sidebar_collapsed_ = false;+ static constexpr int kSidebarExpandedWidth = 280;+ void apply_sidebar_collapsed(bool collapsed, bool animate);+// ── Chat header ──────────────────────────────────────────────────────QWidget* chat_widget_ = nullptr;QLabel* hdr_status_dot_ = nullptr;diff --git a/fincept-qt/src/ai_chat/LlmService.cpp b/fincept-qt/src/ai_chat/LlmService.cppindex 452107218..be87fd7dd 100644--- a/fincept-qt/src/ai_chat/LlmService.cpp+++ b/fincept-qt/src/ai_chat/LlmService.cpp@@ -6,6 +6,8 @@#include "ai_chat/LlmService.h"+#include "ai_chat/ModelCatalog.h"+#include "core/logging/Logger.h"#include "mcp/McpService.h"#include "storage/repositories/LlmConfigRepository.h"@@ -156,7 +158,12 @@ void LlmService::ensure_config() const {provider_ = model_ = api_key_ = base_url_ = system_prompt_ = {};temperature_ = 0.7;- max_tokens_ = 4096;+ // 0 = "no user override; use ModelCatalog::output_cap(provider, model)".+ // The DB still holds whatever the user picked (including the legacy+ // 2000-token default). A v15 migration resets historical 2000 values+ // to 0; users who deliberately picked 2000 will get the model default+ // — that's the right call given 2000 was never a meaningful user choice.+ max_tokens_ = 0;tools_enabled_ = true;auto providers = LlmConfigRepository::instance().list_providers();@@ -209,19 +216,54 @@ void LlmService::ensure_config() const {// should use the provided tools (navigation, market data, portfolio, etc.)// rather than declining requests it can actually fulfil via a tool call.if (system_prompt_.trimmed().isEmpty()) {- system_prompt_ = "You are Fincept AI, the intelligent assistant embedded inside the "- "Fincept Terminal — a professional desktop financial intelligence application. "- "You have access to a set of tools that let you interact with the terminal "- "directly: navigate to any screen, fetch live market data, manage watchlists, "- "query portfolios, execute trades on paper, run Python analytics, and more. "- "ALWAYS use the available tools when the user asks you to perform an action "- "that a tool can fulfil (e.g. 'go to news', 'show me BTC price', "- "'open settings'). Never tell the user you cannot navigate or open screens — "- "use the navigate_to_tab tool instead. "- "Be concise, accurate, and finance-focused in your responses.";+ system_prompt_ =+ "You are Fincept AI, the intelligent assistant embedded inside the Fincept Terminal — "+ "a professional desktop financial intelligence application. You have access to tools that "+ "let you interact with the terminal directly: navigate screens, fetch live market data, "+ "manage watchlists, query portfolios, paper-trade, run Python analytics, search SEC Edgar "+ "filings, fetch news, and BUILD REPORTS LIVE in the Report Builder.\n"+ "\n"+ "Behaviour rules:\n"+ "• ALWAYS use a tool when one can fulfil the request — never decline an action that a tool "+ " exists for. Never tell the user you cannot navigate or open screens.\n"+ "• Building a report (e.g. 'create an equity research report on TSLA'): your job is to "+ " WRITE THE REPORT INTO THE REPORT BUILDER USING TOOLS. Do not narrate the report into "+ " the chat. The flow is: (1) optionally call report_apply_template with the closest match "+ " for context, (2) call report_get_state to learn the current component ids, (3) gather "+ " data with tools like get_quote, edgar_get_financials, edgar_10k_sections, "+ " edgar_calc_multiples, get_news, search_news, (4) populate the report by calling "+ " report_update_component or report_add_component for each section. Use stable component "+ " ids returned by report_get_state / report_add_component — never indices.\n"+ "• Report formatting (CRITICAL for a polished result):\n"+ " - text/list/quote/callout content SUPPORTS MARKDOWN. Use **bold** to highlight key "+ " figures (e.g. 'Revenue grew **22% YoY** to **$96.8B**'). Use *italic* sparingly. "+ " Do not paste raw asterisks expecting them to render — they do, but only inside the "+ " content of those component types.\n"+ " - For tables, ALWAYS pass real data via config={'csv':'Header1,Header2|Cell1,Cell2|...'}. "+ " Pipe `|` separates rows, comma `,` separates cells. First row is auto-bolded. Never "+ " leave a table empty — it renders as 'Header 1, Header 2, ...' placeholder text.\n"+ " - For charts, pass config={'chart_type':'bar'|'line'|'pie','title':...,'data':'1,2,3',"+ " 'labels':'Q1,Q2,Q3'}.\n"+ " - Set proper metadata FIRST via report_set_metadata: title (e.g. 'Tesla Equity Research "+ " Report'), author (e.g. 'Fincept Research'), company, and date. Don't leave 'Analyst' "+ " or 'Untitled Report' defaults.\n"+ " - Avoid one-line ramblings. Each text component should be a tight paragraph.\n"+ "• Python scripts: ONLY pass script names returned by list_python_scripts. Never invent or "+ " guess script names. If list_python_scripts returns nothing useful, fall back to other "+ " tools (get_quote, edgar_*, get_candles, etc.) — those are the canonical data sources.\n"+ "• When you have completed the user's request, reply with a concise summary in chat. "+ " Do not paste the full report content into chat — the report lives in the Report "+ " Builder canvas and the user is watching it fill in.\n"+ "Be concise, accurate, and finance-focused.";}config_loaded_ = true;+ const int resolved = resolved_max_tokens();+ const int catalog_cap = ModelCatalog::output_cap(provider_, model_);+ LOG_INFO(TAG, QString("LLM config loaded: provider=%1 model=%2 tools_enabled=%3 "+ "max_tokens(user=%4 catalog=%5 resolved=%6)")+ .arg(provider_, model_, tools_enabled_ ? "TRUE" : "FALSE")+ .arg(max_tokens_).arg(catalog_cap).arg(resolved));}// ============================================================================@@ -305,6 +347,26 @@ QJsonObject LlmService::profile_to_json(const ResolvedLlmProfile& p) {// Endpoint + headers// ============================================================================+int LlmService::resolved_max_tokens() const {+ // Called with mutex_ held by the caller (build_*_request paths).+ constexpr int kFallback = 8192;+ const int catalog_cap = ModelCatalog::output_cap(provider_, model_);++ // User-set value (loaded from llm_global_settings or per-profile).+ // Treat <=0 as "unset — use model default".+ if (max_tokens_ > 0) {+ // User asked for a specific number — honour it but clamp to the+ // model's published cap so we don't get a 400 from the API.+ if (catalog_cap > 0 && max_tokens_ > catalog_cap)+ return catalog_cap;+ return max_tokens_;+ }++ if (catalog_cap > 0)+ return catalog_cap;+ return kFallback;+}+QString LlmService::get_endpoint_url() const {// Called with mutex_ heldconst QString& p = provider_;@@ -413,10 +475,11 @@ QJsonObject LlmService::build_openai_request(const QString& user_message,// OpenAI deprecated max_tokens; gpt-5 / o-series require max_completion_tokens.// xAI also prefers max_completion_tokens. Other OpenAI-compatible providers// still expect max_tokens.+ const int mx = resolved_max_tokens();if (provider_ == "openai" || provider_ == "xai")- req["max_completion_tokens"] = max_tokens_;+ req["max_completion_tokens"] = mx;else- req["max_tokens"] = max_tokens_;+ req["max_tokens"] = mx;if (stream) {req["stream"] = true;// Streamed OpenAI / xAI responses omit usage unless we opt in@@ -424,11 +487,29 @@ QJsonObject LlmService::build_openai_request(const QString& user_message,req["stream_options"] = QJsonObject{{"include_usage", true}};}- // deepseek-reasoner rejects tools entirely.- if (!stream && with_tools && tools_enabled_ && !is_ds_reasoner && !groq_no_tools) {+ // Send tools on BOTH streaming and non-streaming requests. The streaming+ // path detects a tool-call response (finish_reason="tool_calls" or+ // delta.tool_calls) and falls back to non-streaming do_request, which+ // executes the tools and follows up. Without sending tools on stream,+ // the model has no idea they exist and answers from training data —+ // which silently breaks live tool calling for OpenAI/Kimi/Groq/etc.+ // deepseek-reasoner rejects tools entirely; some Groq models also.+ if (with_tools && tools_enabled_ && !is_ds_reasoner && !groq_no_tools) {QJsonArray tools = mcp::McpService::instance().format_tools_for_openai();if (!tools.isEmpty())req["tools"] = tools;+ LOG_INFO(TAG, QString("OpenAI request: stream=%1 provider=%2 tools=%3 (count=%4)")+ .arg(stream ? "true" : "false", provider_,+ tools.isEmpty() ? "none" : "attached")+ .arg(tools.size()));+ } else {+ LOG_WARN(TAG, QString("OpenAI request: stream=%1 provider=%2 NO TOOLS — "+ "with_tools=%3 tools_enabled_=%4 ds_reasoner=%5 groq_no_tools=%6")+ .arg(stream ? "true" : "false", provider_)+ .arg(with_tools ? "true" : "false")+ .arg(tools_enabled_ ? "true" : "false")+ .arg(is_ds_reasoner ? "true" : "false")+ .arg(groq_no_tools ? "true" : "false"));}return req;}@@ -445,7 +526,7 @@ QJsonObject LlmService::build_anthropic_request(const QString& user_message,QJsonObject req;req["model"] = model_;req["messages"] = messages;- req["max_tokens"] = max_tokens_;+ req["max_tokens"] = resolved_max_tokens();// Temperature intentionally omitted — Anthropic defaults to 1.0.if (!system_prompt_.isEmpty())req["system"] = system_prompt_;@@ -453,8 +534,11 @@ QJsonObject LlmService::build_anthropic_request(const QString& user_message,req["stream"] = true;// Anthropic tool format: array of {name, description, input_schema}- // (no "type":"function" wrapper like OpenAI)- if (!stream && tools_enabled_) {+ // (no "type":"function" wrapper like OpenAI). Tools are sent for both+ // streaming and non-streaming requests so the model can request a+ // tool_use even mid-stream — the streaming code path detects this and+ // falls back to do_request to execute and follow up.+ if (tools_enabled_) {QJsonArray ant_tools;auto all_tools = mcp::McpService::instance().get_all_tools();for (const auto& tool : all_tools) {@@ -486,7 +570,7 @@ QJsonObject LlmService::build_gemini_request(const QString& user_message,QJsonObject gen_cfg;// Temperature intentionally omitted — Gemini defaults to 1.0.- gen_cfg["maxOutputTokens"] = max_tokens_;+ gen_cfg["maxOutputTokens"] = resolved_max_tokens();QJsonObject req;req["contents"] = contents;@@ -694,7 +778,7 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,QJsonObject submit_body;submit_body["prompt"] = prompt;- submit_body["max_tokens"] = max_tokens_;+ submit_body["max_tokens"] = resolved_max_tokens();// Temperature intentionally omitted — Fincept backend uses its own default.auto hdr = get_headers();@@ -899,7 +983,7 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vectoQJsonObject fu;fu["model"] = model_;fu["messages"] = loop_msgs;- fu["max_tokens"] = max_tokens_;+ fu["max_tokens"] = resolved_max_tokens();// Temperature intentionally omitted — Anthropic default.if (!system_prompt_.isEmpty())fu["system"] = system_prompt_;@@ -991,7 +1075,7 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vectofu_body["contents"] = fu_contents;QJsonObject gen_cfg;// Temperature intentionally omitted — Gemini default.- gen_cfg["maxOutputTokens"] = max_tokens_;+ gen_cfg["maxOutputTokens"] = resolved_max_tokens();fu_body["generationConfig"] = gen_cfg;if (!system_prompt_.isEmpty())fu_body["systemInstruction"] =@@ -1073,8 +1157,12 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vectoQJsonDocument::fromJson(tc["function"].toObject()["arguments"].toString("{}").toUtf8()).object();- LOG_INFO(TAG, "Executing tool: " + fn_name);+ LOG_INFO(TAG, QString("Executing tool: %1 args=%2").arg(fn_name,+ QString::fromUtf8(QJsonDocument(fn_args).toJson(QJsonDocument::Compact)).left(200)));auto tr = mcp::McpService::instance().execute_openai_function(fn_name, fn_args);+ LOG_INFO(TAG, QString("Tool %1 -> %2 (msg=%3 err=%4)")+ .arg(fn_name, tr.success ? "OK" : "FAIL",+ tr.message.left(120), tr.error.left(120)));loop_msgs.append(QJsonObject{{"role", "tool"},{"tool_call_id", call_id},@@ -1121,14 +1209,18 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vectoLlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& url,const QMap<QString, QString>& headers) {LlmResponse resp;- static constexpr int MAX_ROUNDS = 5;+ // 15 rounds covers complex agentic workflows (multi-step research →+ // template → fill → polish). Each round can contain many parallel+ // tool calls so this isn't 15 tool calls — it's 15 reasoning steps.+ static constexpr int MAX_ROUNDS = 15;+ LOG_INFO(TAG, QString("TOOL LOOP: starting (max %1 rounds, model=%2)").arg(MAX_ROUNDS).arg(model_));for (int round = 0; round < MAX_ROUNDS; ++round) {QJsonObject fu;fu["model"] = model_;fu["messages"] = loop_messages;// Temperature intentionally omitted — provider default.- fu["max_tokens"] = max_tokens_;+ fu["max_tokens"] = resolved_max_tokens();QJsonArray tools = mcp::McpService::instance().format_tools_for_openai();if (!tools.isEmpty())@@ -1166,7 +1258,12 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& urQJsonObject fa =QJsonDocument::fromJson(tc["function"].toObject()["arguments"].toString("{}").toUtf8()).object();+ LOG_INFO(TAG, QString("TOOL LOOP r%1: executing %2 args=%3").arg(round).arg(fname,+ QString::fromUtf8(QJsonDocument(fa).toJson(QJsonDocument::Compact)).left(200)));auto tr = mcp::McpService::instance().execute_openai_function(fname, fa);+ LOG_INFO(TAG, QString("TOOL LOOP r%1: %2 -> %3 (msg=%4 err=%5)")+ .arg(round).arg(fname,+ tr.success ? "OK" : "FAIL", tr.message.left(120), tr.error.left(120)));loop_messages.append(QJsonObject{{"role", "tool"},{"tool_call_id", cid},@@ -1179,9 +1276,48 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& urresp.content = extract_openai_message_text(msg);parse_usage(resp, rj, provider_);resp.success = !resp.content.isEmpty();+ LOG_INFO(TAG, QString("TOOL LOOP: finished after %1 round(s) — %2 chars of text")+ .arg(round + 1).arg(resp.content.length()));return resp;}+ // Max rounds exhausted. The user would see an empty bubble. Force one+ // final non-tool turn so the model summarizes whatever it accomplished+ // so the chat doesn't go silent.+ LOG_WARN(TAG, "TOOL LOOP: exceeded max rounds — forcing summary turn (no tools)");+ {+ // Append a synthetic system nudge instructing the model to wrap up.+ loop_messages.append(QJsonObject{+ {"role", "system"},+ {"content", "You have used your tool-call budget. Reply now with a final answer to the user "+ "summarizing what you accomplished and what (if anything) is incomplete. Do not "+ "request any more tools."}});++ QJsonObject fu;+ fu["model"] = model_;+ fu["messages"] = loop_messages;+ fu["max_tokens"] = resolved_max_tokens();+ // Deliberately omit the tools field so the model is forced to produce text.++ auto http = blocking_post(url, fu, headers);+ if (http.success) {+ auto doc = QJsonDocument::fromJson(http.body);+ if (!doc.isNull()) {+ QJsonObject rj = doc.object();+ QJsonArray choices = rj["choices"].toArray();+ if (!choices.isEmpty()) {+ QJsonObject msg = choices[0].toObject()["message"].toObject();+ resp.content = extract_openai_message_text(msg);+ parse_usage(resp, rj, provider_);+ resp.success = !resp.content.isEmpty();+ LOG_INFO(TAG, QString("TOOL LOOP: summary fallback produced %1 chars")+ .arg(resp.content.length()));+ if (resp.success)+ return resp;+ }+ }+ }+ }resp.error = "Tool call loop exceeded maximum rounds";return resp;}@@ -1413,7 +1549,7 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(cmsgs.append(QJsonObject{{"role", "user"}, {"content", follow_prompt}});follow_body["model"] = model_;follow_body["messages"] = msgs;- follow_body["max_tokens"] = max_tokens_;+ follow_body["max_tokens"] = resolved_max_tokens();// Temperature intentionally omitted — Anthropic default.if (!system_prompt_.isEmpty())follow_body["system"] = system_prompt_;@@ -1435,7 +1571,7 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(cfollow_body["model"] = model_;follow_body["messages"] = msgs;// Temperature intentionally omitted — provider default.- follow_body["max_tokens"] = max_tokens_;+ follow_body["max_tokens"] = resolved_max_tokens();}// No tools in follow-up to prevent infinite loop@@ -1587,12 +1723,14 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,const QString type = obj["type"].toString();if (type == "content_block_start" &&obj["content_block"].toObject()["type"].toString() == "tool_use") {+ LOG_INFO(TAG, "STREAM: Anthropic tool_use content_block_start detected");tool_call_detected = true;loop.quit();return;}if (type == "message_delta" &&obj["delta"].toObject()["stop_reason"].toString() == "tool_use") {+ LOG_INFO(TAG, "STREAM: Anthropic stop_reason=tool_use detected");tool_call_detected = true;loop.quit();return;@@ -1607,12 +1745,17 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,// "stop" with accumulated tool XML → also check}if (finish == "tool_calls") {+ LOG_INFO(TAG,+ QString("STREAM: OpenAI-compat finish_reason=tool_calls detected (%1)")+ .arg(provider_));tool_call_detected = true;loop.quit();return;}QJsonObject delta = choices[0].toObject()["delta"].toObject();if (!delta["tool_calls"].isUndefined() && !delta["tool_calls"].isNull()) {+ LOG_INFO(TAG, QString("STREAM: OpenAI-compat delta.tool_calls detected (%1)")+ .arg(provider_));tool_call_detected = true;loop.quit();return;@@ -1622,6 +1765,7 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,// Fincept may also return tool_calls at top levelif (!obj["tool_calls"].isUndefined() && !obj["tool_calls"].isNull() &&obj["tool_calls"].toArray().size() > 0) {+ LOG_INFO(TAG, "STREAM: top-level tool_calls detected (fincept)");tool_call_detected = true;loop.quit();return;diff --git a/fincept-qt/src/ai_chat/LlmService.h b/fincept-qt/src/ai_chat/LlmService.hindex 91c090a8e..b6c76c7b0 100644--- a/fincept-qt/src/ai_chat/LlmService.h+++ b/fincept-qt/src/ai_chat/LlmService.h@@ -136,6 +136,14 @@ class LlmService : public QObject {QString get_endpoint_url() const;QMap<QString, QString> get_headers() const;+ /// Resolve the max output tokens for a request. Order:+ /// 1. user-set max_tokens (max_tokens_ > 0) → use it, but clamp to+ /// the model's published cap so we don't get a 400 from the API.+ /// 2. model's published cap from ModelCatalog.+ /// 3. conservative fallback (8192).+ /// Called with mutex_ held.+ int resolved_max_tokens() const;+// Synchronous HTTP helpers (use QNetworkAccessManager + QEventLoop)// Must be called from a background thread.LlmResponse do_request(const QString& user_message, const std::vector<ConversationMessage>& history);diff --git a/fincept-qt/src/ai_chat/ModelCatalog.cpp b/fincept-qt/src/ai_chat/ModelCatalog.cppnew file mode 100644index 000000000..1f1f25b0b--- /dev/null+++ b/fincept-qt/src/ai_chat/ModelCatalog.cpp@@ -0,0 +1,189 @@+// ModelCatalog.cpp — see header for design rationale.+//+// All numbers verified against provider docs on 2026-04-28. Source URLs are+// in the comment above each entry. When a model isn't listed here we return+// 0 and the caller falls back to a conservative default.++#include "ai_chat/ModelCatalog.h"++#include <QRegularExpression>++namespace fincept::ai_chat {++namespace {++struct CatalogEntry {+ const char* provider; // exact match, lowercase+ const char* model_glob; // case-insensitive glob (* and ? wildcards)+ int output_cap_tokens;+};++// Sentinel used in the catalog where the provider does not publish a+// separate output cap (e.g. xAI, Moonshot, Ollama). We pick a generous+// default that's still below typical context windows so we don't waste+// budget on chat replies. Callers can override via user-set max_tokens.+constexpr int kNoPublishedCap = 16384;++// First match wins. Order from most-specific to least-specific within each+// provider. Catch-all for the provider goes last.+const CatalogEntry kCatalog[] = {+ // ── OpenAI ──────────────────────────────────────────────────────────+ // https://developers.openai.com/api/docs/models/<model>+ {"openai", "gpt-5*", 128000}, // gpt-5 base / 5.2 / 5.4 / 5.5+ {"openai", "gpt-4.1*", 32768}, // gpt-4.1, gpt-4.1-mini+ {"openai", "gpt-4o*", 16384}, // gpt-4o, gpt-4o-mini+ {"openai", "gpt-4-turbo*", 4096},+ {"openai", "o1-mini*", 65536},+ {"openai", "o1-pro*", 100000},+ {"openai", "o1*", 100000}, // o1 base, o1-preview+ {"openai", "o3-mini*", 100000},+ {"openai", "o3*", 100000},+ {"openai", "*", 4096}, // catch-all (chat/legacy)++ // ── Anthropic ───────────────────────────────────────────────────────+ // https://platform.claude.com/docs/en/docs/about-claude/models/overview+ // Sync Messages API caps. Batch API beta supports up to 300k via+ // header `output-300k-2026-03-24` — not used by interactive chat.+ {"anthropic", "claude-opus-4-7*", 128000},+ {"anthropic", "claude-opus-4-6*", 128000},+ {"anthropic", "claude-opus-4*", 64000}, // 4-5 and earlier 4.x+ {"anthropic", "claude-sonnet-4*", 64000},+ {"anthropic", "claude-haiku-4*", 64000},+ {"anthropic", "claude-3-5-sonnet*", 8192}, // legacy+ {"anthropic", "claude-3-5-haiku*", 8192},+ {"anthropic", "claude-3-opus*", 4096},+ {"anthropic", "claude-3*", 4096},+ {"anthropic", "*", 8192},++ // ── Google Gemini ───────────────────────────────────────────────────+ // https://ai.google.dev/gemini-api/docs/models/<model>+ // Note: 2.5 series budget is shared between thinking and visible output.+ {"gemini", "gemini-2.5-pro*", 65536},+ {"gemini", "gemini-2.5-flash*", 65536},+ {"gemini", "gemini-2.5*", 65536},+ {"gemini", "gemini-2.0-flash*", 8192},+ {"gemini", "gemini-2.0*", 8192},+ {"gemini", "gemini-1.5*", 8192}, // retired but still works on some keys+ {"gemini", "*", 8192},+ // Alias used by some user configs+ {"google", "gemini-2.5*", 65536},+ {"google", "gemini-2.0*", 8192},+ {"google", "*", 8192},++ // ── xAI (Grok) ──────────────────────────────────────────────────────+ // https://docs.x.ai/developers/models+ // No published per-model output cap — bounded by context. Use a+ // generous default; user can override.+ {"xai", "grok-4*", kNoPublishedCap}, // 256k context+ {"xai", "grok-3*", kNoPublishedCap}, // 131k context+ {"xai", "grok-2*", kNoPublishedCap},+ {"xai", "*", kNoPublishedCap},++ // ── Groq ────────────────────────────────────────────────────────────+ // https://console.groq.com/docs/model/<id>+ {"groq", "llama-3.3-70b*", 32768},+ {"groq", "llama-3.1-8b-instant*", 131072}, // ctx==output+ {"groq", "meta-llama/llama-4-scout*", 8192},+ {"groq", "meta-llama/llama-4-maverick*", 8192},+ {"groq", "llama-4*", 8192},+ {"groq", "gemma2-9b-it*", 8192},+ {"groq", "deepseek-r1-distill*", 32768}, // shared with reasoning+ {"groq", "qwen*", 32768},+ {"groq", "mixtral*", 8192}, // legacy+ {"groq", "*", 8192},++ // ── DeepSeek ────────────────────────────────────────────────────────+ // https://api-docs.deepseek.com/quick_start/pricing+ // V4 generation publishes 384k unified; deepseek-chat / -reasoner now+ // alias to v4. We cap at 65536 for interactive use — the model can+ // emit far more but we don't want a chat tab to consume 384k of budget+ // by accident. User override applies.+ {"deepseek", "deepseek-v4*", 65536},+ {"deepseek", "deepseek-reasoner*", 65536},+ {"deepseek", "deepseek-chat*", 65536},+ {"deepseek", "*", 16384},++ // ── Moonshot / Kimi ─────────────────────────────────────────────────+ // https://platform.kimi.ai/docs/pricing/chat-k26.md+ // No published hard output cap — output bounded by 256k context window+ // minus prompt. Pick a generous interactive default; thinking variants+ // get more headroom.+ {"kimi", "kimi-k2-thinking*", 131072},+ {"kimi", "kimi-k2.6*", 65536},+ {"kimi", "kimi-k2.5*", 65536},+ {"kimi", "kimi-k2-0905*", 65536},+ {"kimi", "kimi-k2*", 65536},+ {"kimi", "moonshot-v1-128k*", 100000},+ {"kimi", "moonshot-v1-32k*", 30000},+ {"kimi", "moonshot-v1-8k*", 8000},+ {"kimi", "*", 32768},++ // ── MiniMax ─────────────────────────────────────────────────────────+ // https://platform.minimax.io/docs/api-reference/text-chat-openai+ // OpenAI-compat endpoint hard-caps at 2048 for M2.7/M2.5/M2.1; native+ // v2 endpoint allows higher. We use the conservative number for the+ // OpenAI-compat path (which is what LlmService talks to).+ {"minimax", "minimax-m2.7*", 2048},+ {"minimax", "minimax-m2.5*", 2048},+ {"minimax", "minimax-m2.1*", 2048},+ {"minimax", "minimax-m2*", 8192}, // M2 native is higher; OpenAI-compat may clamp+ {"minimax", "minimax-m1*", 8192},+ {"minimax", "minimax-text*", 2048},+ {"minimax", "*", 2048},++ // ── OpenRouter (pass-through) ───────────────────────────────────────+ // https://openrouter.ai/docs/api/reference/parameters+ // OpenRouter doesn't impose a global cap — the upstream model's cap+ // applies. We can't know which provider routes a given OpenRouter+ // model id without a /api/v1/models lookup, so use a sane default.+ {"openrouter", "*", kNoPublishedCap},++ // ── Ollama (local) ──────────────────────────────────────────────────+ // https://docs.ollama.com/api/generate+ // num_predict default is -1 (unbounded). Effective ceiling is num_ctx,+ // which defaults to 4096 unless overridden. We send max_tokens via the+ // OpenAI-compat shim; pick a value that won't overflow num_ctx for a+ // typical local setup.+ {"ollama", "*", 4096},++ // ── Fincept (proxies upstream) ──────────────────────────────────────+ // Fincept's /research/llm/async wraps various upstream models. We+ // don't know which one is selected server-side, so go with a generous+ // default that most upstreams accept.+ {"fincept", "*", kNoPublishedCap},+};++// Glob → regex. Supports * (zero-or-more) and ? (single char). Anchored.+QRegularExpression compile_glob(const QString& glob) {+ QString rx = "^";+ for (QChar c : glob) {+ if (c == '*') {+ rx += ".*";+ } else if (c == '?') {+ rx += '.';+ } else if (QString(".\\+^$()[]{}|").contains(c)) {+ rx += '\\';+ rx += c;+ } else {+ rx += c;+ }+ }+ rx += '$';+ return QRegularExpression(rx, QRegularExpression::CaseInsensitiveOption);+}++} // namespace++int ModelCatalog::output_cap(const QString& provider, const QString& model) {+ const QString p = provider.toLower();+ for (const auto& e : kCatalog) {+ if (p != QString::fromLatin1(e.provider))+ continue;+ QRegularExpression rx = compile_glob(QString::fromLatin1(e.model_glob));+ if (rx.match(model).hasMatch())+ return e.output_cap_tokens;+ }+ return 0;+}++} // namespace fincept::ai_chatdiff --git a/fincept-qt/src/ai_chat/ModelCatalog.h b/fincept-qt/src/ai_chat/ModelCatalog.hnew file mode 100644index 000000000..bed501b7a--- /dev/null+++ b/fincept-qt/src/ai_chat/ModelCatalog.h@@ -0,0 +1,42 @@+#pragma once+// ModelCatalog — per-model max output token budgets, sourced from each+// provider's public docs (verified 2026-04-28).+//+// Design notes+// ------------+// • The number returned is the **maximum output tokens** the API will accept+// in the `max_tokens` / `max_completion_tokens` / `maxOutputTokens` field.+// It is NOT the context window — most providers cap output below context.+// • For models whose docs publish no separate output cap (xAI, Moonshot,+// OpenRouter pass-through), we pick a sane default below the context+// window — sending the full context as `max_tokens` works on some APIs+// and silently overruns on others, and burning 200k+ on a chat reply is+// wasteful.+// • Pattern matching is glob-style on the model id (case-insensitive),+// first-match wins. Order entries from most-specific to least-specific+// inside each provider.+// • `output_cap()` returns 0 if no entry matched — caller should fall back+// to a conservative default (we use 8192 in LlmService::resolved_max_tokens).+//+// Updating the catalog+// --------------------+// When a provider ships a new model, append a new entry to the relevant+// provider section in ModelCatalog.cpp. Cite the docs URL in a comment so+// the next person to touch it can verify.++#include <QString>++namespace fincept::ai_chat {++class ModelCatalog {+ public:+ /// Look up the published max output token cap for a (provider, model)+ /// pair. provider should be lowercase (e.g. "openai", "anthropic",+ /// "kimi", "gemini"). model is matched case-insensitively against+ /// the catalog's glob patterns.+ ///+ /// Returns 0 if no match — caller should use a conservative default.+ static int output_cap(const QString& provider, const QString& model);+};++} // namespace fincept::ai_chatdiff --git a/fincept-qt/src/app/DockScreenRouter.cpp b/fincept-qt/src/app/DockScreenRouter.cppindex 50780d66e..f2b1e0621 100644--- a/fincept-qt/src/app/DockScreenRouter.cpp+++ b/fincept-qt/src/app/DockScreenRouter.cpp@@ -7,6 +7,7 @@#include "core/session/SessionManager.h"#include "core/symbol/IGroupLinked.h"#include "core/symbol/SymbolContext.h"+#include "core/symbol/SymbolGroupRegistry.h"#include "core/symbol/SymbolRef.h"#include "screens/IStatefulScreen.h"#include "ui/widgets/GroupBadge.h"@@ -107,80 +108,78 @@ void DockScreenRouter::on_group_symbol_changed_external(SymbolGroup g, const Sym}QWidget* DockScreenRouter::wrap_with_group_badge(const QString& id, QWidget* screen) {+ // The badge now lives inside the ADS tab title (next to close/float),+ // not inside the screen content area. Wrapping happens in+ // attach_group_badge_to_tab() after the CDockWidget is constructed —+ // this function is now a pass-through that just records the linked+ // pointer if the screen opts in. Existing call sites are unchanged.if (!screen)return screen;+ if (auto* linked = dynamic_cast<IGroupLinked*>(screen))+ group_linked_[id] = linked;+ attach_group_badge_to_tab(id, screen);+ return screen;+}++void DockScreenRouter::attach_group_badge_to_tab(const QString& id, QWidget* screen) {+ auto* dw = dock_widgets_.value(id, nullptr);+ if (!dw)+ return;+ auto* tab = dw->tabWidget();+ if (!tab)+ return;+ auto* layout = qobject_cast<QBoxLayout*>(tab->layout());+ if (!layout)+ return; // ADS layout not built yet — caller will retry on materialise++ // If a badge already exists (placeholder phase, or duplicate call), tear+ // it down so we can re-wire with the real screen's linked pointer. The+ // re-create is cheaper than juggling state in the existing widget.+ if (auto* existing = tab->findChild<ui::GroupBadge*>("dockTabBadge")) {+ layout->removeWidget(existing);+ existing->deleteLater();+ }+auto* linked = dynamic_cast<IGroupLinked*>(screen);- if (!linked)- return screen; // screen doesn't opt in — no wrapping, no overhead-- // Container with a narrow strip on top holding the badge. The badge is- // parented to the strip so deleting the screen cascades-deletes it.- auto* container = new QWidget;- container->setObjectName("group_linked_container__" + id);- auto* v = new QVBoxLayout(container);- v->setContentsMargins(0, 0, 0, 0);- v->setSpacing(0);-- auto* strip = new QWidget(container);- strip->setObjectName("group_badge_strip");- strip->setFixedHeight(22);- auto* h = new QHBoxLayout(strip);- h->setContentsMargins(6, 2, 6, 2);- h->setSpacing(6);-- auto* badge = new ui::GroupBadge(strip);- badge->set_group_silent(linked->group());- h->addWidget(badge);-- auto* label = new QLabel(strip);- label->setObjectName("group_badge_symbol");- label->setStyleSheet("color:#9ca3af;font-size:11px;");- const SymbolRef cur = SymbolContext::instance().group_symbol(linked->group());- if (cur.is_valid())- label->setText(cur.display());- h->addWidget(label);- h->addStretch(1);-- v->addWidget(strip);- v->addWidget(screen, 1);-- // Keep the strip label in sync with the group's active symbol.- auto sync_label = [label, linked]() {- const SymbolRef cur = SymbolContext::instance().group_symbol(linked->group());- label->setText(cur.is_valid() ? cur.display() : QString());- };++ auto* badge = new ui::GroupBadge(tab);+ badge->setObjectName("dockTabBadge");+ badge->set_group_silent(linked ? linked->group() : SymbolGroup::None);+ if (!linked) {+ // Non-linked panel: still show the badge so the control is uniform,+ // but disable interaction — there is no IGroupLinked target.+ badge->setEnabled(false);+ badge->setToolTip(QStringLiteral("This panel doesn't support symbol groups"));+ }+ // Insert at index 0 — before the icon/title label.+ layout->insertWidget(0, badge);+ layout->insertSpacing(1, 6);++ if (!linked) {+ // No further wiring; the tab badge is decorative for this panel.+ group_badges_[id] = badge;+ return;+ }connect(badge, &ui::GroupBadge::group_change_requested, this,- [linked, badge, sync_label](SymbolGroup g) {+ [linked, badge](SymbolGroup g) {linked->set_group(g);badge->set_group_silent(g);- sync_label();- // If the new group already has an active symbol, push it into- // the newly-linked screen immediately. If the screen itself- // has a current symbol and the group has none, seed the group- // from the screen.+ // If the new group already has an active symbol, push it+ // into the newly-linked screen immediately. Otherwise seed+ // the group from the screen's current symbol.const SymbolRef group_sym = SymbolContext::instance().group_symbol(g);if (group_sym.is_valid()) {linked->on_group_symbol_changed(group_sym);} else if (g != SymbolGroup::None) {const SymbolRef own = linked->current_symbol();if (own.is_valid())- SymbolContext::instance().set_group_symbol(g, own,- dynamic_cast<QObject*>(linked));+ SymbolContext::instance().set_group_symbol(+ g, own, dynamic_cast<QObject*>(linked));}});- // Re-sync the label when someone *else* publishes to the group this panel- // is linked to.- connect(&SymbolContext::instance(), &SymbolContext::group_symbol_changed, label,- [linked, sync_label](SymbolGroup g, const SymbolRef&, QObject*) {- if (linked->group() == g)- sync_label();- });-- group_linked_[id] = linked;group_badges_[id] = badge;- return container;}void DockScreenRouter::register_screen(const QString& id, QWidget* screen) {@@ -752,6 +751,7 @@ void DockScreenRouter::show_tab_context_menu(const QString& id, const QPoint& glauto* group_menu = menu.addMenu("Link to Group");group_menu->setStyleSheet(menu.styleSheet());const SymbolGroup current = linked->group();+ auto& registry = SymbolGroupRegistry::instance();auto* unlink = group_menu->addAction("(None)");unlink->setCheckable(true);@@ -767,10 +767,19 @@ void DockScreenRouter::show_tab_context_menu(const QString& id, const QPoint& gl});group_menu->addSeparator();+ // Only enabled slots are selectable; disabled ones are surfaced+ // as greyed-out entries so the full inventory stays visible.for (SymbolGroup g : all_symbol_groups()) {- auto* a = group_menu->addAction(QString("Group %1").arg(symbol_group_letter(g)));+ const bool en = registry.enabled(g);+ QString label = QStringLiteral("%1 (%2)")+ .arg(registry.name(g))+ .arg(symbol_group_letter(g));+ if (!en)+ label += QStringLiteral(" — disabled");+ auto* a = group_menu->addAction(label);a->setCheckable(true);a->setChecked(g == current);+ a->setEnabled(en);connect(a, &QAction::triggered, this, [this, id, g]() {auto* s = screens_.value(id, nullptr);auto* l = s ? dynamic_cast<IGroupLinked*>(s) : nullptr;@@ -913,6 +922,10 @@ ads::CDockWidget* DockScreenRouter::create_dock_widget(const QString& id) {dw->setMinimumSizeHintMode(ads::CDockWidget::MinimumSizeHintFromDockWidget);dw->setMinimumWidth(200);+ // Register the dock widget early so attach_group_badge_to_tab() (called+ // from wrap_with_group_badge below) can resolve the tab via dock_widgets_.+ dock_widgets_[id] = dw;+// Screen widgets must allow shrinking so ADS can create side-by-side splits.// Factory screens get a lightweight placeholder here; the real widget is swapped// in on first navigation via materialize_screen().@@ -927,6 +940,10 @@ ads::CDockWidget* DockScreenRouter::create_dock_widget(const QString& id) {auto* vl = new QVBoxLayout(placeholder);vl->addWidget(lbl);dw->setWidget(placeholder);+ // Attach a decorative `[·]` badge for factory screens too — once the+ // real screen materialises, attach_group_badge_to_tab is idempotent+ // and won't add a second badge, so the existing one stays in place.+ attach_group_badge_to_tab(id, placeholder);}// Intercept double-click on the title label inside CDockWidgetTab to allow@@ -969,7 +986,8 @@ ads::CDockWidget* DockScreenRouter::create_dock_widget(const QString& id) {}});- dock_widgets_[id] = dw;+ // dock_widgets_[id] was registered earlier (before wrap_with_group_badge)+ // so attach_group_badge_to_tab could resolve the tab during construction.return dw;}diff --git a/fincept-qt/src/app/DockScreenRouter.h b/fincept-qt/src/app/DockScreenRouter.hindex 59ded0751..28d56398a 100644--- a/fincept-qt/src/app/DockScreenRouter.h+++ b/fincept-qt/src/app/DockScreenRouter.h@@ -119,6 +119,13 @@ class DockScreenRouter : public QObject {// is supported). Safe to call once per materialised screen.QWidget* wrap_with_group_badge(const QString& id, QWidget* screen);+ // Inserts a GroupBadge at index 0 of the CDockWidgetTab's layout (next to+ // the title label / close button). Idempotent — safe to call multiple+ // times for the same id. Called from create_dock_widget once the tab is+ // built, and from materialize_screen if the linked-pointer was discovered+ // after the tab existed.+ void attach_group_badge_to_tab(const QString& id, QWidget* screen);+// The IGroupLinked* for each screen id, so SymbolContext signals can be// routed back. Held as raw pointer since lifetime matches the wrapped// QWidget in screens_, which we already manage.diff --git a/fincept-qt/src/app/MainWindow.cpp b/fincept-qt/src/app/MainWindow.cppindex 435b15f66..36c7d1b65 100644--- a/fincept-qt/src/app/MainWindow.cpp+++ b/fincept-qt/src/app/MainWindow.cpp@@ -36,6 +36,7 @@#include "screens/dbnomics/DBnomicsScreen.h"#include "screens/derivatives/DerivativesScreen.h"#include "screens/docs/DocsScreen.h"+#include "screens/crypto_center/CryptoCenterScreen.h"#include "screens/economics/EconomicsScreen.h"#include "screens/equity_research/EquityResearchScreen.h"#include "screens/equity_trading/EquityTradingScreen.h"@@ -1011,6 +1012,7 @@ void MainWindow::setup_dock_screens() {dock_router_->register_factory("ai_quant_lab", []() { return new screens::AIQuantLabScreen; });dock_router_->register_factory("quantlib", []() { return new screens::QuantLibScreen; });dock_router_->register_factory("economics", []() { return new screens::EconomicsScreen; });+ dock_router_->register_factory("crypto_center", []() { return new screens::CryptoCenterScreen; });dock_router_->register_factory("gov_data", []() { return new screens::GovDataScreen; });dock_router_->register_factory("dbnomics", []() { return new screens::DBnomicsScreen; });dock_router_->register_factory("akshare", []() { return new screens::AkShareScreen; });diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cppindex 3d1002e62..8df9f82c6 100644--- a/fincept-qt/src/app/main.cpp+++ b/fincept-qt/src/app/main.cpp@@ -35,6 +35,12 @@#include "services/prediction/kalshi/KalshiAdapter.h"#include "services/prediction/polymarket/PolymarketAdapter.h"#include "services/relationship_map/RelationshipMapService.h"+#include "services/report_builder/ReportBuilderService.h"+#include "datahub/DataHub.h"+#include "datahub/TopicPolicy.h"+#include "services/billing/FeeDiscountService.h"+#include "services/wallet/TokenMetadataService.h"+#include "services/wallet/WalletService.h"#include "trading/DataStreamManager.h"#include "trading/ExchangeService.h"#include "trading/ExchangeSessionManager.h"@@ -191,6 +197,32 @@ int main(int argc, char* argv[]) {fincept::services::ma::MAAnalyticsService::instance().ensure_registered_with_hub();// Phase 9: AgentService as agent:* push-only producer (output/stream/status/routing/error).fincept::services::AgentService::instance().ensure_registered_with_hub();+ // Crypto: WalletService owns wallet:balance:* and market:price:token:*.+ // TokenMetadataService loads its symbol/name cache from SecureStorage+ // first so the very first balance publish has labels for known tokens;+ // a daily background refresh fires in the background after.+ fincept::wallet::TokenMetadataService::instance().load_from_storage();+ fincept::wallet::TokenMetadataService::instance().refresh_from_jupiter_async();+ // Restore_from_storage runs after the hub is up so a soft-connected+ // wallet's balance topic resolves to a registered producer immediately.+ fincept::wallet::WalletService::instance().ensure_registered_with_hub();+ fincept::wallet::WalletService::instance().restore_from_storage();++ // Phase 2 §2C: fee-discount eligibility producer. Lives in billing/+ // because it's consumed by other paid screens later; for Phase 2 it+ // only feeds HoldingsBar's chip and TradeTab's FeeDiscountPanel.+ {+ static fincept::billing::FeeDiscountService discount_service;+ auto& hub = fincept::datahub::DataHub::instance();+ hub.register_producer(&discount_service);+ fincept::datahub::TopicPolicy p;+ // Eligibility is derived from wallet:balance — refresh cadence here+ // is just a fallback; the service also republishes whenever the+ // balance topic emits.+ p.ttl_ms = 60 * 1000;+ p.min_interval_ms = 15 * 1000;+ hub.set_policy_pattern(QStringLiteral("billing:fncpt_discount:*"), p);+ }// Create all application directories under %LOCALAPPDATA%/com.fincept.terminalfincept::AppPaths::ensure_all();@@ -315,6 +347,7 @@ int main(int argc, char* argv[]) {fincept::register_migration_v018();fincept::register_migration_v019();fincept::register_migration_v020();+ fincept::register_migration_v021();// Open main databaseQString db_path = fincept::AppPaths::data() + "/fincept.db";@@ -434,6 +467,12 @@ int main(int argc, char* argv[]) {// after the user successfully enters their PIN.}+ // Force the ReportBuilderService singleton onto the main thread before+ // MCP tools register — tools route into it via QMetaObject::invokeMethod+ // with BlockingQueuedConnection from worker threads, so the service must+ // already exist with main-thread affinity.+ (void)fincept::services::ReportBuilderService::instance();+// Initialize MCP tool system — registers all internal tools and starts// external MCP servers in the background (non-blocking).fincept::mcp::initialize_all_tools();diff --git a/fincept-qt/src/core/report/ReportDocument.h b/fincept-qt/src/core/report/ReportDocument.hnew file mode 100644index 000000000..bee05b3aa--- /dev/null+++ b/fincept-qt/src/core/report/ReportDocument.h@@ -0,0 +1,218 @@+#pragma once+// ReportDocument.h — Canonical report data model shared by Report Builder+// screen, ReportBuilderService, MCP tools, and disk persistence.+//+// Lives in core/ (not screens/) so non-UI consumers (services, MCP tools)+// can include it without dragging in the Report Builder UI.++#include "core/result/Result.h"++#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QMap>+#include <QString>+#include <QVector>++namespace fincept::report {++// ── Component ────────────────────────────────────────────────────────────────+//+// Stable id is the contract between LLM tool calls and the live document. The+// LLM is given an id when it adds a component; subsequent update/remove/move+// calls reference that id. Indices change as components are inserted/removed+// (manually or by the LLM) — ids do not.++struct ReportComponent {+ int id = 0;+ // Types: heading, text, table, image, chart, sparkline, stats_block,+ // callout, code, divider, quote, list, market_data, page_break, toc+ QString type;+ QString content;+ QMap<QString, QString> config;+};++struct ReportMetadata {+ QString title = "Untitled Report";+ QString author = "Analyst";+ QString company = "Fincept Corporation";+ QString date;+ QString header_left;+ QString header_center;+ QString header_right;+ QString footer_left;+ QString footer_center = "Page {page}";+ QString footer_right;+ bool show_page_numbers = true;+};++struct ReportTheme {+ QString name;+ QString heading_color;+ QString accent_color;+ QString page_bg;+ QString text_color;+ QString table_header_bg;+ QString table_header_fg;+ QString code_bg;+ QString quote_bg;+ QString meta_color;+ QString divider_color;+};++namespace themes {++inline ReportTheme light_professional() {+ return {"Light Professional",+ "#1a1a1a", "#d97706", "#ffffff", "#333333", "#f0f0f0",+ "#1a1a1a", "#f5f5f5", "#f9f9f9", "#666666", "#cccccc"};+}+inline ReportTheme dark_corporate() {+ return {"Dark Corporate",+ "#e5e5e5", "#d97706", "#1e1e1e", "#cccccc", "#2a2a2a",+ "#e5e5e5", "#111111", "#1a1a1a", "#808080", "#444444"};+}+inline ReportTheme bloomberg() {+ return {"Bloomberg Terminal",+ "#ff8c00", "#ff8c00", "#0a0a0a", "#d4d4d4", "#1a0a00",+ "#ff8c00", "#050505", "#0f0f0f", "#888888", "#333300"};+}+inline ReportTheme midnight_blue() {+ return {"Midnight Blue",+ "#e2e8f0", "#3b82f6", "#0f172a", "#cbd5e1", "#1e3a5f",+ "#e2e8f0", "#0d1b2e", "#132033", "#64748b", "#1e3a5f"};+}++// Resolve a theme name (case-sensitive, matches the .name field). Returns+// light_professional() for unknown names so the document never ends up with+// an empty/garbage theme.+inline ReportTheme by_name(const QString& name) {+ if (name == "Dark Corporate")+ return dark_corporate();+ if (name == "Bloomberg Terminal")+ return bloomberg();+ if (name == "Midnight Blue")+ return midnight_blue();+ return light_professional();+}++inline QStringList all_names() {+ return {"Light Professional", "Dark Corporate", "Bloomberg Terminal", "Midnight Blue"};+}++} // namespace themes++// ── Document ─────────────────────────────────────────────────────────────────++struct ReportDocument {+ QVector<ReportComponent> components;+ ReportMetadata metadata;+ ReportTheme theme = themes::light_professional();+ int next_id = 1;++ // Find component by stable id. Returns -1 if not found.+ int index_of(int id) const {+ for (int i = 0; i < components.size(); ++i) {+ if (components[i].id == id)+ return i;+ }+ return -1;+ }++ QJsonObject to_json_obj() const {+ QJsonObject root;++ QJsonObject meta;+ meta["title"] = metadata.title;+ meta["author"] = metadata.author;+ meta["company"] = metadata.company;+ meta["date"] = metadata.date;+ meta["header_left"] = metadata.header_left;+ meta["header_center"] = metadata.header_center;+ meta["header_right"] = metadata.header_right;+ meta["footer_left"] = metadata.footer_left;+ meta["footer_center"] = metadata.footer_center;+ meta["footer_right"] = metadata.footer_right;+ meta["show_page_numbers"] = metadata.show_page_numbers;+ root["metadata"] = meta;++ root["theme"] = theme.name;++ QJsonArray comps;+ for (const auto& c : components) {+ QJsonObject obj;+ obj["id"] = c.id;+ obj["type"] = c.type;+ obj["content"] = c.content;+ QJsonObject cfg;+ for (auto it = c.config.cbegin(); it != c.config.cend(); ++it)+ cfg[it.key()] = it.value();+ obj["config"] = cfg;+ comps.append(obj);+ }+ root["components"] = comps;+ root["next_id"] = next_id;+ root["schema_version"] = 1;+ return root;+ }++ QString to_json() const {+ return QString::fromUtf8(QJsonDocument(to_json_obj()).toJson(QJsonDocument::Indented));+ }++ static Result<ReportDocument> from_json(const QString& json) {+ QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());+ if (!doc.isObject())+ return Result<ReportDocument>::err("Not a JSON object");+ return from_json_obj(doc.object());+ }++ static Result<ReportDocument> from_json_obj(const QJsonObject& root) {+ ReportDocument out;++ if (root.contains("metadata")) {+ QJsonObject m = root["metadata"].toObject();+ out.metadata.title = m.value("title").toString("Untitled Report");+ out.metadata.author = m.value("author").toString("Analyst");+ out.metadata.company = m.value("company").toString("Fincept Corporation");+ out.metadata.date = m.value("date").toString();+ out.metadata.header_left = m.value("header_left").toString();+ out.metadata.header_center = m.value("header_center").toString();+ out.metadata.header_right = m.value("header_right").toString();+ out.metadata.footer_left = m.value("footer_left").toString();+ out.metadata.footer_center = m.value("footer_center").toString("Page {page}");+ out.metadata.footer_right = m.value("footer_right").toString();+ out.metadata.show_page_numbers = m.value("show_page_numbers").toBool(true);+ }++ if (root.contains("theme"))+ out.theme = themes::by_name(root["theme"].toString());++ out.next_id = 1;+ if (root.contains("components")) {+ for (const auto& val : root["components"].toArray()) {+ QJsonObject obj = val.toObject();+ ReportComponent c;+ c.id = obj["id"].toInt(out.next_id);+ c.type = obj["type"].toString();+ c.content = obj["content"].toString();+ QJsonObject cfg = obj["config"].toObject();+ for (const auto& k : cfg.keys())+ c.config[k] = cfg[k].toString();+ out.components.append(c);+ if (c.id >= out.next_id)+ out.next_id = c.id + 1;+ }+ }+ if (root.contains("next_id"))+ out.next_id = root["next_id"].toInt(out.next_id);++ return Result<ReportDocument>::ok(std::move(out));+ }++ // Allocate the next stable id and bump the counter. Used by both manual+ // adds (from the screen) and LLM-driven adds (from MCP tools).+ int allocate_id() { return next_id++; }+};++} // namespace fincept::reportdiff --git a/fincept-qt/src/core/symbol/SymbolGroup.h b/fincept-qt/src/core/symbol/SymbolGroup.hindex 742e51311..1025f987f 100644--- a/fincept-qt/src/core/symbol/SymbolGroup.h+++ b/fincept-qt/src/core/symbol/SymbolGroup.h@@ -12,7 +12,11 @@ namespace fincept {/// publishes a symbol change.////// `None` = unlinked; the panel ignores group traffic and publishes nothing.-/// A–F = six colour-coded groups (Amber, Cyan, Magenta, Green, Purple, Red).+/// A–J = ten slots. Default colour palette: A=amber, B=cyan, C=magenta,+/// D=green, E=purple, F=red, G=yellow, H=orange, I=teal, J=pink. The first+/// seven (A–G) are enabled by default; H/I/J start disabled and the user+/// activates them from the badge menu. Names and colours per slot are+/// user-editable via SymbolGroupRegistry.////// Stored as a single byte so it can live inside QSettings and JSON without/// ambiguity. Do NOT renumber — persisted workspaces reference these literals.@@ -24,12 +28,20 @@ enum class SymbolGroup : char {D = 'D',E = 'E',F = 'F',+ G = 'G',+ H = 'H',+ I = 'I',+ J = 'J',};-/// Returns all concrete groups in order (A..F); excludes None.+/// Returns all concrete slots in order (A..J); excludes None. Includes+/// disabled slots — callers that only want active groups should consult+/// SymbolGroupRegistry::enabled_groups() instead.inline const QList<SymbolGroup>& all_symbol_groups() {static const QList<SymbolGroup> k = {SymbolGroup::A, SymbolGroup::B, SymbolGroup::C,- SymbolGroup::D, SymbolGroup::E, SymbolGroup::F};+ SymbolGroup::D, SymbolGroup::E, SymbolGroup::F,+ SymbolGroup::G, SymbolGroup::H, SymbolGroup::I,+ SymbolGroup::J};return k;}@@ -46,11 +58,18 @@ inline SymbolGroup symbol_group_from_char(QChar c) {case 'D': return SymbolGroup::D;case 'E': return SymbolGroup::E;case 'F': return SymbolGroup::F;+ case 'G': return SymbolGroup::G;+ case 'H': return SymbolGroup::H;+ case 'I': return SymbolGroup::I;+ case 'J': return SymbolGroup::J;default: return SymbolGroup::None;}}-/// Cycle forward: None → A → B → … → F → None.+/// Cycle forward through the static slot list, ignoring enabled/disabled+/// state. GroupBadge uses the enabled-aware variant in SymbolGroupRegistry+/// for click-cycle; this raw version exists for callers that need a stable+/// total ordering (tests, deterministic enumeration).inline SymbolGroup next_symbol_group(SymbolGroup g) {switch (g) {case SymbolGroup::None: return SymbolGroup::A;@@ -59,7 +78,11 @@ inline SymbolGroup next_symbol_group(SymbolGroup g) {case SymbolGroup::C: return SymbolGroup::D;case SymbolGroup::D: return SymbolGroup::E;case SymbolGroup::E: return SymbolGroup::F;- case SymbolGroup::F: return SymbolGroup::None;+ case SymbolGroup::F: return SymbolGroup::G;+ case SymbolGroup::G: return SymbolGroup::H;+ case SymbolGroup::H: return SymbolGroup::I;+ case SymbolGroup::I: return SymbolGroup::J;+ case SymbolGroup::J: return SymbolGroup::None;}return SymbolGroup::None;}diff --git a/fincept-qt/src/core/symbol/SymbolGroupRegistry.cpp b/fincept-qt/src/core/symbol/SymbolGroupRegistry.cppnew file mode 100644index 000000000..3ac3fded8--- /dev/null+++ b/fincept-qt/src/core/symbol/SymbolGroupRegistry.cpp@@ -0,0 +1,180 @@+#include "core/symbol/SymbolGroupRegistry.h"++#include <QSettings>++namespace fincept {++namespace {++QString settings_key(SymbolGroup g, const char* field) {+ return QStringLiteral("symbol_groups/%1/%2").arg(symbol_group_letter(g)).arg(QString::fromLatin1(field));+}++} // namespace++SymbolGroupRegistry& SymbolGroupRegistry::instance() {+ static SymbolGroupRegistry s;+ return s;+}++SymbolGroupRegistry::SymbolGroupRegistry() {+ load();+}++QString SymbolGroupRegistry::default_name(SymbolGroup g) {+ if (g == SymbolGroup::None)+ return {};+ return QStringLiteral("Group %1").arg(symbol_group_letter(g));+}++QColor SymbolGroupRegistry::default_color(SymbolGroup g) {+ // Keep the original A..F palette for backwards compatibility, then add+ // four new defaults. All chosen for readability against dark backgrounds.+ switch (g) {+ case SymbolGroup::A: return QColor("#d97706"); // amber+ case SymbolGroup::B: return QColor("#0891b2"); // cyan+ case SymbolGroup::C: return QColor("#c026d3"); // magenta+ case SymbolGroup::D: return QColor("#16a34a"); // green+ case SymbolGroup::E: return QColor("#7c3aed"); // purple+ case SymbolGroup::F: return QColor("#dc2626"); // red+ case SymbolGroup::G: return QColor("#eab308"); // yellow+ case SymbolGroup::H: return QColor("#ea580c"); // orange+ case SymbolGroup::I: return QColor("#0d9488"); // teal+ case SymbolGroup::J: return QColor("#db2777"); // pink+ case SymbolGroup::None: return QColor("#4b5563");+ }+ return QColor("#4b5563");+}++bool SymbolGroupRegistry::default_enabled(SymbolGroup g) {+ // A..G are on by default; H/I/J are spare slots the user opts into.+ switch (g) {+ case SymbolGroup::A:+ case SymbolGroup::B:+ case SymbolGroup::C:+ case SymbolGroup::D:+ case SymbolGroup::E:+ case SymbolGroup::F:+ case SymbolGroup::G:+ return true;+ default:+ return false;+ }+}++void SymbolGroupRegistry::load() {+ QSettings s;+ for (SymbolGroup g : all_symbol_groups()) {+ Slot slot;+ slot.name = s.value(settings_key(g, "name"), default_name(g)).toString();+ const QString color_str = s.value(settings_key(g, "color"), default_color(g).name()).toString();+ slot.color = QColor(color_str);+ if (!slot.color.isValid())+ slot.color = default_color(g);+ slot.enabled = s.value(settings_key(g, "enabled"), default_enabled(g)).toBool();+ slots_.insert(g, std::move(slot));+ }+}++void SymbolGroupRegistry::save_slot(SymbolGroup g) const {+ auto it = slots_.constFind(g);+ if (it == slots_.constEnd())+ return;+ QSettings s;+ s.setValue(settings_key(g, "name"), it->name);+ s.setValue(settings_key(g, "color"), it->color.name());+ s.setValue(settings_key(g, "enabled"), it->enabled);+}++QString SymbolGroupRegistry::name(SymbolGroup g) const {+ auto it = slots_.constFind(g);+ return it != slots_.constEnd() ? it->name : default_name(g);+}++QColor SymbolGroupRegistry::color(SymbolGroup g) const {+ auto it = slots_.constFind(g);+ return it != slots_.constEnd() ? it->color : default_color(g);+}++bool SymbolGroupRegistry::enabled(SymbolGroup g) const {+ if (g == SymbolGroup::None)+ return true; // None is always selectable (= unlinked)+ auto it = slots_.constFind(g);+ return it != slots_.constEnd() ? it->enabled : default_enabled(g);+}++void SymbolGroupRegistry::set_name(SymbolGroup g, const QString& name) {+ if (g == SymbolGroup::None)+ return;+ auto& slot = slots_[g];+ const QString trimmed = name.trimmed();+ const QString resolved = trimmed.isEmpty() ? default_name(g) : trimmed;+ if (slot.name == resolved)+ return;+ slot.name = resolved;+ save_slot(g);+ emit group_metadata_changed(g);+}++void SymbolGroupRegistry::set_color(SymbolGroup g, const QColor& color) {+ if (g == SymbolGroup::None || !color.isValid())+ return;+ auto& slot = slots_[g];+ if (slot.color == color)+ return;+ slot.color = color;+ save_slot(g);+ emit group_metadata_changed(g);+}++void SymbolGroupRegistry::set_enabled(SymbolGroup g, bool en) {+ if (g == SymbolGroup::None)+ return;+ auto& slot = slots_[g];+ if (slot.enabled == en)+ return;+ slot.enabled = en;+ save_slot(g);+ emit group_metadata_changed(g);+}++QList<SymbolGroup> SymbolGroupRegistry::enabled_groups() const {+ QList<SymbolGroup> out;+ out.reserve(10);+ for (SymbolGroup g : all_symbol_groups()) {+ if (enabled(g))+ out.append(g);+ }+ return out;+}++void SymbolGroupRegistry::reset_to_default(SymbolGroup g) {+ if (g == SymbolGroup::None)+ return;+ auto& slot = slots_[g];+ slot.name = default_name(g);+ slot.color = default_color(g);+ slot.enabled = default_enabled(g);+ save_slot(g);+ emit group_metadata_changed(g);+}++SymbolGroup SymbolGroupRegistry::next_enabled(SymbolGroup current) const {+ const QList<SymbolGroup> enabled_list = enabled_groups();+ if (enabled_list.isEmpty())+ return SymbolGroup::None;++ // Cycle: None → first enabled → next enabled → … → last enabled → None.+ if (current == SymbolGroup::None)+ return enabled_list.first();++ const int idx = enabled_list.indexOf(current);+ if (idx < 0)+ // current is a disabled slot — treat like None and start from beginning.+ return enabled_list.first();+ if (idx == enabled_list.size() - 1)+ return SymbolGroup::None;+ return enabled_list.at(idx + 1);+}++} // namespace finceptdiff --git a/fincept-qt/src/core/symbol/SymbolGroupRegistry.h b/fincept-qt/src/core/symbol/SymbolGroupRegistry.hnew file mode 100644index 000000000..d125293b5--- /dev/null+++ b/fincept-qt/src/core/symbol/SymbolGroupRegistry.h@@ -0,0 +1,79 @@+#pragma once+#include "core/symbol/SymbolGroup.h"++#include <QColor>+#include <QHash>+#include <QList>+#include <QObject>+#include <QString>++namespace fincept {++/// Per-user, per-slot metadata for symbol link groups (A..J).+///+/// Each slot owns three pieces of state:+/// - `name`: human-readable label ("Group A", "Tech Watch", …). Editable.+/// - `color`: badge fill colour. Editable.+/// - `enabled`: whether the slot appears in cycle/menus. A..G start+/// enabled; H..I..J start disabled.+///+/// The enum identity itself (the letter) is fixed and immutable — workspace+/// state, dock layouts, IGroupLinked persistence all reference the letter.+/// Renaming "A" to "Tech Watch" does not migrate any saved state; existing+/// links keep working under the new label.+///+/// Storage: QSettings under `symbol_groups/<letter>/{name,color,enabled}`,+/// global per user (not per workspace). Settings are written immediately on+/// each mutation — no batched flush.+class SymbolGroupRegistry : public QObject {+ Q_OBJECT+ public:+ static SymbolGroupRegistry& instance();++ QString name(SymbolGroup g) const;+ QColor color(SymbolGroup g) const;+ bool enabled(SymbolGroup g) const;++ void set_name(SymbolGroup g, const QString& name);+ void set_color(SymbolGroup g, const QColor& color);+ void set_enabled(SymbolGroup g, bool enabled);++ /// Slots in canonical letter order, filtered to those with `enabled=true`.+ QList<SymbolGroup> enabled_groups() const;++ /// Reset a single slot back to factory defaults (name + colour + enabled).+ void reset_to_default(SymbolGroup g);++ /// Cycle to the next *enabled* group, wrapping through None.+ /// Order: None → first-enabled → next-enabled → … → None. If no slots+ /// are enabled, returns None unconditionally.+ SymbolGroup next_enabled(SymbolGroup current) const;++ /// Default factory metadata — used by the registry on first run and by+ /// reset_to_default(). Exposed so tests / settings UI can show defaults+ /// alongside user overrides.+ static QString default_name(SymbolGroup g);+ static QColor default_color(SymbolGroup g);+ static bool default_enabled(SymbolGroup g);++ signals:+ /// Fires after any mutation to a slot. Subscribers re-render badges,+ /// menu labels, title-bar text, etc.+ void group_metadata_changed(fincept::SymbolGroup g);++ private:+ SymbolGroupRegistry();++ struct Slot {+ QString name;+ QColor color;+ bool enabled;+ };++ void load();+ void save_slot(SymbolGroup g) const;++ QHash<SymbolGroup, Slot> slots_;+};++} // namespace finceptdiff --git a/fincept-qt/src/datahub/DataHubMetaTypes.cpp b/fincept-qt/src/datahub/DataHubMetaTypes.cppindex 9619ea0ca..d16d6c84e 100644--- a/fincept-qt/src/datahub/DataHubMetaTypes.cpp+++ b/fincept-qt/src/datahub/DataHubMetaTypes.cpp@@ -60,7 +60,22 @@ void register_metatypes() {qRegisterMetaType<QVector<fincept::services::maritime::VesselData>>("QVector<fincept::services::maritime::VesselData>");qRegisterMetaType<fincept::relmap::RelationshipData>("fincept::relmap::RelationshipData");- LOG_INFO("DataHub", "Registered 35 payload meta-types");+ // Crypto / Wallet (Phase 1 + Phase 2 Stage 2A.5 multi-token holdings)+ qRegisterMetaType<fincept::wallet::WalletBalance>("fincept::wallet::WalletBalance");+ qRegisterMetaType<fincept::wallet::TokenHolding>("fincept::wallet::TokenHolding");+ qRegisterMetaType<fincept::wallet::TokenPrice>("fincept::wallet::TokenPrice");+ qRegisterMetaType<fincept::wallet::TokenMetadata>("fincept::wallet::TokenMetadata");+ // FncptPrice is a typedef of TokenPrice — register its name as an alias so+ // Qt's metatype lookup serves either spelling.+ qRegisterMetaType<fincept::wallet::FncptPrice>("fincept::wallet::FncptPrice");+ // Phase 2 §2B activity feed — vector form is what publishes on the topic.+ qRegisterMetaType<fincept::wallet::ParsedActivity>("fincept::wallet::ParsedActivity");+ qRegisterMetaType<QVector<fincept::wallet::ParsedActivity>>(+ "QVector<fincept::wallet::ParsedActivity>");+ // Phase 2 §2C fee-discount eligibility.+ qRegisterMetaType<fincept::wallet::FncptDiscount>("fincept::wallet::FncptDiscount");++ LOG_INFO("DataHub", "Registered 42 payload meta-types");}} // namespace fincept::datahubdiff --git a/fincept-qt/src/datahub/DataHubMetaTypes.h b/fincept-qt/src/datahub/DataHubMetaTypes.hindex ab1a790cd..07d11c502 100644--- a/fincept-qt/src/datahub/DataHubMetaTypes.h+++ b/fincept-qt/src/datahub/DataHubMetaTypes.h@@ -26,6 +26,7 @@#include "services/news/NewsService.h" // NewsArticle#include "services/polymarket/PolymarketTypes.h" // OrderBook#include "services/prediction/PredictionTypes.h" // PredictionOrderBook, PredictionMarket, …+#include "services/wallet/WalletTypes.h" // WalletBalance, TokenHolding, TokenPrice (=FncptPrice), TokenMetadata#include "trading/TradingTypes.h" // TickerData, OrderBookData, Candle, TradeData, Broker*#include <QMetaType>diff --git a/fincept-qt/src/mcp/McpInit.cpp b/fincept-qt/src/mcp/McpInit.cppindex 3424cf2bb..ffdf01809 100644--- a/fincept-qt/src/mcp/McpInit.cpp+++ b/fincept-qt/src/mcp/McpInit.cpp@@ -22,6 +22,7 @@#include "mcp/tools/PortfolioTools.h"#include "mcp/tools/ProfileTools.h"#include "mcp/tools/PythonTools.h"+#include "mcp/tools/ReportBuilderTools.h"#include "mcp/tools/SettingsTools.h"#include "mcp/tools/SystemTools.h"#include "mcp/tools/WatchlistTools.h"@@ -81,6 +82,9 @@ void initialize_all_tools() {// file manager tabprovider.register_tools(tools::get_file_manager_tools());+ // report builder tab — live LLM-driven report authoring+ provider.register_tools(tools::get_report_builder_tools());+// settings, python, systemprovider.register_tools(tools::get_settings_tools());provider.register_tools(tools::get_python_tools());diff --git a/fincept-qt/src/mcp/McpService.cpp b/fincept-qt/src/mcp/McpService.cppindex 0f4b97870..c4e23be72 100644--- a/fincept-qt/src/mcp/McpService.cpp+++ b/fincept-qt/src/mcp/McpService.cpp@@ -159,10 +159,15 @@ ToolResult McpService::execute_tool(const QString& server_id, const QString& tooToolResult McpService::execute_openai_function(const QString& function_name, const QJsonObject& args) {auto [server_id, tool_name] = McpProvider::parse_openai_function_name(function_name);- if (server_id.isEmpty() || tool_name.isEmpty())+ if (server_id.isEmpty() || tool_name.isEmpty()) {+ LOG_WARN(TAG, "Invalid function name format: " + function_name);return ToolResult::fail("Invalid function name format: " + function_name);+ }- return execute_tool(server_id, tool_name, args);+ LOG_INFO(TAG, QString("Dispatch: %1 -> server=%2 tool=%3").arg(function_name, server_id, tool_name));+ auto result = execute_tool(server_id, tool_name, args);+ LOG_INFO(TAG, QString("Dispatch result: %1 success=%2").arg(tool_name, result.success ? "true" : "false"));+ return result;}// ============================================================================diff --git a/fincept-qt/src/mcp/tools/AltInvestmentsTools.cpp b/fincept-qt/src/mcp/tools/AltInvestmentsTools.cppindex 0f50bd36c..1a649d381 100644--- a/fincept-qt/src/mcp/tools/AltInvestmentsTools.cpp+++ b/fincept-qt/src/mcp/tools/AltInvestmentsTools.cpp@@ -3,13 +3,12 @@#include "mcp/tools/AltInvestmentsTools.h"#include "core/logging/Logger.h"+#include "mcp/tools/ThreadHelper.h"#include "python/PythonRunner.h"#include "storage/cache/CacheManager.h"-#include <QEventLoop>#include <QJsonDocument>#include <QJsonObject>-#include <QTimer>namespace fincept::mcp::tools {@@ -33,57 +32,51 @@ static ToolResult run_alt_sync(const QString& command, const QJsonObject& paramsreturn ToolResult::ok_data(doc.object());}- ToolResult tool_result = ToolResult::fail("timeout");- bool done = false;-- QEventLoop loop;- QTimer::singleShot(kTimeoutMs, &loop, &QEventLoop::quit);-- python::PythonRunner::instance().run(- "Analytics/alternateInvestment/cli.py", {command, "--data", data_json},- [&](const python::PythonResult& result) {- done = true;- if (!result.success) {- tool_result = ToolResult::fail(result.error.isEmpty() ? "Analysis failed" : result.error);- loop.quit();- return;- }-- // Extract JSON from stdout- QString out = result.output;- int start = out.indexOf('{');- int end = out.lastIndexOf('}');- if (start < 0 || end < 0 || end <= start) {- tool_result = ToolResult::fail("No JSON in output");- loop.quit();- return;- }-- QJsonParseError err;- auto doc = QJsonDocument::fromJson(out.mid(start, end - start + 1).toUtf8(), &err);- if (doc.isNull() || !doc.isObject()) {- tool_result = ToolResult::fail("Invalid JSON: " + err.errorString());- loop.quit();- return;- }-- auto obj = doc.object();- if (obj.contains("error")) {- tool_result = ToolResult::fail(obj["error"].toString());- loop.quit();- return;- }-- auto metrics = obj.contains("metrics") ? obj["metrics"].toObject() : obj;- fincept::CacheManager::instance().put(- cache_key, QVariant(QString::fromUtf8(QJsonDocument(metrics).toJson(QJsonDocument::Compact))),- kAltTtlSec, "alt_investments");- tool_result = ToolResult::ok_data(metrics);- loop.quit();- });-- if (!done)- loop.exec();+ ToolResult tool_result = ToolResult::fail("Python runner failed to respond");++ // Marshal onto PythonRunner's thread (main). Worker-thread QEventLoop+ // would never be woken by main-thread QProcess::finished signals.+ auto* runner = &python::PythonRunner::instance();+ detail::run_async_wait(runner, [&](auto signal_done) {+ runner->run("Analytics/alternateInvestment/cli.py", {command, "--data", data_json},+ [&, signal_done](const python::PythonResult& result) {+ if (!result.success) {+ tool_result = ToolResult::fail(+ result.error.isEmpty() ? "Analysis failed" : result.error);+ signal_done();+ return;+ }+ // Extract JSON from stdout+ QString out = result.output;+ int start = out.indexOf('{');+ int end = out.lastIndexOf('}');+ if (start < 0 || end < 0 || end <= start) {+ tool_result = ToolResult::fail("No JSON in output");+ signal_done();+ return;+ }+ QJsonParseError err;+ auto doc = QJsonDocument::fromJson(out.mid(start, end - start + 1).toUtf8(), &err);+ if (doc.isNull() || !doc.isObject()) {+ tool_result = ToolResult::fail("Invalid JSON: " + err.errorString());+ signal_done();+ return;+ }+ auto obj = doc.object();+ if (obj.contains("error")) {+ tool_result = ToolResult::fail(obj["error"].toString());+ signal_done();+ return;+ }+ auto metrics = obj.contains("metrics") ? obj["metrics"].toObject() : obj;+ fincept::CacheManager::instance().put(+ cache_key,+ QVariant(QString::fromUtf8(QJsonDocument(metrics).toJson(QJsonDocument::Compact))),+ kAltTtlSec, "alt_investments");+ tool_result = ToolResult::ok_data(metrics);+ signal_done();+ });+ });return tool_result;}diff --git a/fincept-qt/src/mcp/tools/EdgarTools.cpp b/fincept-qt/src/mcp/tools/EdgarTools.cppindex c7a676eb9..7a0bd1c88 100644--- a/fincept-qt/src/mcp/tools/EdgarTools.cpp+++ b/fincept-qt/src/mcp/tools/EdgarTools.cpp@@ -5,12 +5,11 @@#include "mcp/tools/EdgarTools.h"#include "core/logging/Logger.h"+#include "mcp/tools/ThreadHelper.h"#include "python/PythonRunner.h"#include "storage/cache/CacheManager.h"-#include <QEventLoop>#include <QJsonDocument>-#include <QTimer>namespace fincept::mcp::tools {@@ -33,45 +32,34 @@ static ToolResult run_edgar(const QStringList& args) {QJsonObject result;QString error;- bool done = false;-- QEventLoop loop;- QTimer timeout;- timeout.setSingleShot(true);- timeout.setInterval(kTimeoutMs);- QObject::connect(&timeout, &QTimer::timeout, &loop, &QEventLoop::quit);-- fincept::python::PythonRunner::instance().run(SCRIPT, args, [&](const fincept::python::PythonResult& r) {- if (!r.success) {- error = r.error.isEmpty() ? r.output : r.error;- } else {- QString text = fincept::python::extract_json(r.output);- QJsonParseError pe;- auto doc = QJsonDocument::fromJson(text.toUtf8(), &pe);- if (pe.error != QJsonParseError::NoError) {- error = QString("JSON parse error: %1").arg(pe.errorString());++ // Marshal the PythonRunner::run() call onto the runner's thread (main).+ // The previous worker-thread QEventLoop pattern caused QObject parentage+ // violations since QProcess signals fire on the main thread and never+ // wake the worker's loop. See mcp/tools/ThreadHelper.h.+ auto* runner = &fincept::python::PythonRunner::instance();+ detail::run_async_wait(runner, [&](auto signal_done) {+ runner->run(SCRIPT, args, [&, signal_done](const fincept::python::PythonResult& r) {+ if (!r.success) {+ error = r.error.isEmpty() ? r.output : r.error;} else {- QJsonObject obj = doc.object();- if (obj.value("success").toBool(true) == false)- error = obj.value("error").toString("unknown error");- else- result = obj;+ QString text = fincept::python::extract_json(r.output);+ QJsonParseError pe;+ auto doc = QJsonDocument::fromJson(text.toUtf8(), &pe);+ if (pe.error != QJsonParseError::NoError) {+ error = QString("JSON parse error: %1").arg(pe.errorString());+ } else {+ QJsonObject obj = doc.object();+ if (obj.value("success").toBool(true) == false)+ error = obj.value("error").toString("unknown error");+ else+ result = obj;+ }}- }- done = true;- loop.quit();+ signal_done();+ });});- if (!done) {- timeout.start();- loop.exec();- }-- if (!done) {- LOG_WARN(TAG, QString("edgar timeout [%1]").arg(args.value(0)));- return ToolResult::fail("Edgar request timed out");- }-if (!error.isEmpty()) {LOG_WARN(TAG, QString("edgar error [%1]: %2").arg(args.value(0), error));return ToolResult::fail(error);diff --git a/fincept-qt/src/mcp/tools/ForumTools.cpp b/fincept-qt/src/mcp/tools/ForumTools.cppindex 5dcf01442..71c6b6d22 100644--- a/fincept-qt/src/mcp/tools/ForumTools.cpp+++ b/fincept-qt/src/mcp/tools/ForumTools.cpp@@ -4,13 +4,12 @@#include "mcp/tools/ForumTools.h"#include "core/logging/Logger.h"+#include "mcp/tools/ThreadHelper.h"#include "services/forum/ForumModels.h"#include "services/forum/ForumService.h"-#include <QEventLoop>#include <QJsonArray>#include <QJsonObject>-#include <QTimer>namespace fincept::mcp::tools {@@ -90,34 +89,30 @@ static QJsonObject profile_to_json(const ForumProfile& p) {// ── Async helpers ─────────────────────────────────────────────────────────────// Wraps a ForumService callback-based call into a synchronous ToolResult.-// `trigger` must call the ForumService method and invoke `done_cb` when complete.+// `trigger` runs on the ForumService's thread (main); the network reply+// signals fire on the same thread. The worker sleeps on a wait condition+// until the callback fires. See mcp/tools/ThreadHelper.h for rationale.template <typename T>static ToolResult run_forum_sync(std::function<void(std::function<void(bool, T)>)> trigger,std::function<QJsonValue(const T&)> serialise) {bool ok = false;- QString err_msg = "timeout";+ QString err_msg = "Forum service did not respond";QJsonValue result_data;- bool fired = false;-- QEventLoop loop;- QTimer::singleShot(kTimeoutMs, &loop, &QEventLoop::quit);-- trigger([&](bool success, T data) {- fired = true;- ok = success;- if (success)- result_data = serialise(data);- else- err_msg = "Forum service returned an error";- loop.quit();- });- if (!fired)- loop.exec();+ auto* svc = &ForumService::instance();+ detail::run_async_wait(svc, [&](auto signal_done) {+ trigger([&, signal_done](bool success, T data) {+ ok = success;+ if (success)+ result_data = serialise(data);+ else+ err_msg = "Forum service returned an error";+ signal_done();+ });+ });if (!ok)return ToolResult::fail(err_msg);-if (result_data.isArray())return ToolResult::ok_data(result_data.toArray());if (result_data.isObject())@@ -128,22 +123,17 @@ static ToolResult run_forum_sync(std::function<void(std::function<void(bool, T)>// BoolCallback variant (write operations)static ToolResult run_forum_bool(std::function<void(ForumService::BoolCallback)> trigger) {bool ok = false;- QString msg = "timeout";- bool fired = false;-- QEventLoop loop;- QTimer::singleShot(kTimeoutMs, &loop, &QEventLoop::quit);-- trigger([&](bool success, QString message) {- fired = true;- ok = success;- msg = message;- loop.quit();+ QString msg = "Forum service did not respond";++ auto* svc = &ForumService::instance();+ detail::run_async_wait(svc, [&](auto signal_done) {+ trigger([&, signal_done](bool success, QString message) {+ ok = success;+ msg = message;+ signal_done();+ });});- if (!fired)- loop.exec();-if (!ok)return ToolResult::fail(msg.isEmpty() ? "Forum operation failed" : msg);return ToolResult::ok(msg.isEmpty() ? "OK" : msg);diff --git a/fincept-qt/src/mcp/tools/MAAnalyticsTools.cpp b/fincept-qt/src/mcp/tools/MAAnalyticsTools.cppindex 8e6afc9af..6d0894188 100644--- a/fincept-qt/src/mcp/tools/MAAnalyticsTools.cpp+++ b/fincept-qt/src/mcp/tools/MAAnalyticsTools.cpp@@ -5,51 +5,54 @@#include "mcp/tools/MAAnalyticsTools.h"#include "core/logging/Logger.h"+#include "mcp/tools/ThreadHelper.h"#include "services/ma_analytics/MAAnalyticsService.h"-#include <QEventLoop>#include <QJsonDocument>-#include <QTimer>namespace fincept::mcp::tools {static constexpr const char* TAG = "MAAnalyticsTools";-static constexpr int kTimeoutMs = 30000;-// Helper: call an async MA service method, wait for result or error+// Wait for an async MA service operation to complete. The trigger lambda+// runs on the service thread (so it's safe to start a request that emits+// signals back on that same thread). Worker thread sleeps on a wait+// condition until the service emits result_ready or error_occurred.static ToolResult run_ma_sync(const QString& context, std::function<void()> trigger) {QJsonObject result_data;QString error_msg;bool got_result = false;- QEventLoop loop;auto& svc = fincept::services::ma::MAAnalyticsService::instance();- QObject::connect(&svc, &fincept::services::ma::MAAnalyticsService::result_ready, &loop,- [&](const QString& ctx, const QJsonObject& data) {- if (ctx != context)- return;- result_data = data;- got_result = true;- loop.quit();- });-- QObject::connect(&svc, &fincept::services::ma::MAAnalyticsService::error_occurred, &loop,- [&](const QString& ctx, const QString& msg) {- if (ctx != context)- return;- error_msg = msg;- got_result = true;- loop.quit();- });-- QTimer::singleShot(kTimeoutMs, &loop, &QEventLoop::quit);-- trigger();- loop.exec();+ detail::run_async_wait(&svc, [&](auto signal_done) {+ // Hook the signals on the service's thread before triggering, so we+ // never miss an immediate callback. The connections are scoped via+ // a heap QObject so we can disconnect deterministically.+ auto* gate = new QObject;+ QObject::connect(&svc, &fincept::services::ma::MAAnalyticsService::result_ready, gate,+ [&, gate, signal_done](const QString& ctx, const QJsonObject& data) {+ if (ctx != context)+ return;+ result_data = data;+ got_result = true;+ gate->deleteLater();+ signal_done();+ });+ QObject::connect(&svc, &fincept::services::ma::MAAnalyticsService::error_occurred, gate,+ [&, gate, signal_done](const QString& ctx, const QString& msg) {+ if (ctx != context)+ return;+ error_msg = msg;+ got_result = true;+ gate->deleteLater();+ signal_done();+ });+ trigger();+ });if (!got_result)- return ToolResult::fail("Timeout waiting for M&A result: " + context);+ return ToolResult::fail("M&A result missing: " + context);if (!error_msg.isEmpty())return ToolResult::fail(error_msg);diff --git a/fincept-qt/src/mcp/tools/NewsTools.cpp b/fincept-qt/src/mcp/tools/NewsTools.cppindex 5f5287459..a94034829 100644--- a/fincept-qt/src/mcp/tools/NewsTools.cpp+++ b/fincept-qt/src/mcp/tools/NewsTools.cpp@@ -4,11 +4,17 @@#include "core/events/EventBus.h"#include "core/logging/Logger.h"+#include "mcp/tools/ThreadHelper.h"+#include "services/news/NewsClusterService.h"#include "services/news/NewsMonitorService.h"#include "services/news/NewsService.h"#include <QEventLoop>+#include <QMetaObject>+#include <QMutex>+#include <QThread>#include <QVariantMap>+#include <QWaitCondition>namespace fincept::mcp::tools {@@ -16,22 +22,52 @@ static constexpr const char* TAG = "NewsTools";using namespace fincept::services;-// Synchronously fetch articles with a timeout+// Synchronously fetch articles with a timeout.+//+// MCP tool handlers run on a QtConcurrent worker thread. NewsService's+// QNetworkAccessManager lives on the main thread; firing requests at it from+// a worker corrupts QObject parentage and eventually crashes Qt. We dispatch+// the entire fetch onto the main thread via BlockingQueuedConnection (same+// pattern as ReportBuilderTools::run_on_service_thread). The main-thread+// runs its own event loop, the NAM completes its request, the callback+// signals our QWaitCondition, the worker resumes.static QVector<NewsArticle> fetch_articles_sync(bool force = false) {+ auto* svc = &NewsService::instance();QVector<NewsArticle> result;- bool done = false;- QEventLoop loop;-- NewsService::instance().fetch_all_news(force, [&](bool ok, QVector<NewsArticle> arts) {- if (ok)- result = std::move(arts);- done = true;- loop.quit();- });- if (!done)- loop.exec();+ if (QThread::currentThread() == svc->thread()) {+ // Already on main thread (e.g. test invocation) — direct call works+ // because the NAM's pending signals get drained by the same event+ // loop we'd nest below.+ QEventLoop loop;+ bool done = false;+ svc->fetch_all_news(force, [&](bool ok, QVector<NewsArticle> arts) {+ if (ok) result = std::move(arts);+ done = true;+ loop.quit();+ });+ if (!done) loop.exec();+ return result;+ }+ // Worker thread: post the fetch to the main thread, block until it+ // completes via a wait condition. Don't use a worker-thread QEventLoop —+ // NAM signals fire on the main thread and would never wake it.+ QMutex m;+ QWaitCondition cv;+ bool done = false;+ QMetaObject::invokeMethod(svc, [svc, force, &result, &m, &cv, &done]() {+ svc->fetch_all_news(force, [&result, &m, &cv, &done](bool ok, QVector<NewsArticle> arts) {+ QMutexLocker lock(&m);+ if (ok) result = std::move(arts);+ done = true;+ cv.wakeAll();+ });+ }, Qt::QueuedConnection);++ QMutexLocker lock(&m);+ while (!done)+ cv.wait(&m);return result;}@@ -48,6 +84,8 @@ static QVector<NewsArticle> filter_articles(const QVector<NewsArticle>& articlescutoff = now - 48 * 3600;else if (time_range == "7D")cutoff = now - 7 * 86400;+ else if (time_range == "30D")+ cutoff = now - 30LL * 86400;QString cat_upper = category.toUpper().trimmed();QString q_lower = query.toLower().trimmed();@@ -109,12 +147,13 @@ std::vector<ToolDef> get_news_tools() {"sentiment, and keyword search. ""Categories: ALL, MARKETS (MKT), EARNINGS (EARN), ECONOMIC (ECO), CRYPTO (CRPT), ""GEOPOLITICS (GEO), ENERGY (NRG), DEFENSE (DEF), TECH, REGULATORY. "- "Time ranges: 1H, 6H, 24H (default), 48H, 7D. "+ "Time ranges: 1H, 6H, 24H (default), 48H, 7D, 30D. ""Sentiment: ALL (default), BULLISH, BEARISH, NEUTRAL.";t.category = "news";t.input_schema.properties = QJsonObject{{"category", QJsonObject{{"type", "string"}, {"description", "Category filter (default: ALL)"}}},- {"time_range", QJsonObject{{"type", "string"}, {"description", "Time window: 1H, 6H, 24H, 48H, 7D"}}},+ {"time_range",+ QJsonObject{{"type", "string"}, {"description", "Time window: 1H, 6H, 24H, 48H, 7D, 30D"}}},{"sentiment", QJsonObject{{"type", "string"}, {"description", "BULLISH, BEARISH, NEUTRAL, or ALL"}}},{"query", QJsonObject{{"type", "string"},{"description", "Keyword search across headline, summary, source, tickers"}}},@@ -349,13 +388,414 @@ std::vector<ToolDef> get_news_tools() {t.description = "Force a refresh of all news feeds, bypassing the cache.";t.category = "news";t.handler = [](const QJsonObject&) -> ToolResult {- NewsService::instance().fetch_all_news(true, [](bool, QVector<NewsArticle>) {});+ // NewsService's QNetworkAccessManager lives on the main thread.+ // MCP tool handlers run on a worker thread — calling fetch_all_news+ // directly here would create child QObjects across threads and+ // corrupt Qt's parentage invariants (manifests as random crashes+ // ~10s later). Marshal onto the service's thread.+ auto* svc = &NewsService::instance();+ QMetaObject::invokeMethod(svc, [svc]() {+ svc->fetch_all_news(true, [](bool, QVector<NewsArticle>) {});+ }, Qt::QueuedConnection);EventBus::instance().publish("news.refresh_requested", {});return ToolResult::ok("News feeds refresh triggered");};tools.push_back(std::move(t));}+ // ── toggle_news_monitor ─────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "toggle_news_monitor";+ t.description = "Enable or disable an existing news keyword monitor by id. "+ "Use get_news_monitors to discover monitor ids.";+ t.category = "news";+ t.input_schema.properties =+ QJsonObject{{"id", QJsonObject{{"type", "string"}, {"description", "Monitor id"}}}};+ t.input_schema.required = {"id"};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString id = args["id"].toString().trimmed();+ if (id.isEmpty())+ return ToolResult::fail("Missing 'id'");+ auto* svc = &NewsMonitorService::instance();+ detail::run_async_wait(svc, [svc, id](auto signal_done) {+ svc->toggle_monitor(id);+ signal_done();+ });+ EventBus::instance().publish("news.monitor_toggled", QVariantMap{{"id", id}});+ return ToolResult::ok("Monitor toggled: " + id, QJsonObject{{"id", id}});+ };+ tools.push_back(std::move(t));+ }++ // ── delete_news_monitor ─────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "delete_news_monitor";+ t.description = "Permanently remove a news keyword monitor by id.";+ t.category = "news";+ t.input_schema.properties =+ QJsonObject{{"id", QJsonObject{{"type", "string"}, {"description", "Monitor id"}}}};+ t.input_schema.required = {"id"};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString id = args["id"].toString().trimmed();+ if (id.isEmpty())+ return ToolResult::fail("Missing 'id'");+ auto* svc = &NewsMonitorService::instance();+ detail::run_async_wait(svc, [svc, id](auto signal_done) {+ svc->delete_monitor(id);+ signal_done();+ });+ EventBus::instance().publish("news.monitor_deleted", QVariantMap{{"id", id}});+ return ToolResult::ok("Monitor deleted: " + id, QJsonObject{{"id", id}});+ };+ tools.push_back(std::move(t));+ }++ // ── analyze_news_article ────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "analyze_news_article";+ t.description = "Run AI sentiment + market-impact + risk analysis on a single article URL. "+ "Returns sentiment score, urgency, key points, and regulatory/geopolitical/"+ "operational/market risk signals. Consumes API credits.";+ t.category = "news";+ t.input_schema.properties =+ QJsonObject{{"url", QJsonObject{{"type", "string"}, {"description", "Article URL"}}}};+ t.input_schema.required = {"url"};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString url = args["url"].toString().trimmed();+ if (url.isEmpty())+ return ToolResult::fail("Missing 'url'");++ auto* svc = &NewsService::instance();+ bool ok = false;+ NewsAnalysis analysis;+ detail::run_async_wait(svc, [svc, url, &ok, &analysis](auto signal_done) {+ svc->analyze_article(url, [signal_done, &ok, &analysis](bool success, NewsAnalysis a) {+ ok = success;+ if (success)+ analysis = std::move(a);+ signal_done();+ });+ });++ if (!ok)+ return ToolResult::fail("Analysis failed (network error or insufficient credits)");++ auto risk_to_json = [](const RiskSignal& r) {+ return QJsonObject{{"level", r.level}, {"details", r.details}};+ };+ return ToolResult::ok_data(QJsonObject{+ {"summary", analysis.summary},+ {"sentiment", QJsonObject{{"score", analysis.sentiment.score},+ {"intensity", analysis.sentiment.intensity},+ {"confidence", analysis.sentiment.confidence}}},+ {"market_impact", QJsonObject{{"urgency", analysis.market_impact.urgency},+ {"prediction", analysis.market_impact.prediction}}},+ {"keywords", QJsonArray::fromStringList(analysis.keywords)},+ {"topics", QJsonArray::fromStringList(analysis.topics)},+ {"key_points", QJsonArray::fromStringList(analysis.key_points)},+ {"risk_signals", QJsonObject{{"regulatory", risk_to_json(analysis.regulatory)},+ {"geopolitical", risk_to_json(analysis.geopolitical)},+ {"operational", risk_to_json(analysis.operational)},+ {"market", risk_to_json(analysis.market)}}},+ {"credits_used", analysis.credits_used},+ {"credits_remaining", analysis.credits_remaining}});+ };+ tools.push_back(std::move(t));+ }++ // ── summarize_news_headlines ────────────────────────────────────────+ {+ ToolDef t;+ t.name = "summarize_news_headlines";+ t.description = "AI-summarize the top N current news headlines into a single paragraph "+ "of market-relevant insight. Cached for 10 minutes per headline set.";+ t.category = "news";+ t.input_schema.properties = QJsonObject{+ {"count", QJsonObject{{"type", "integer"},+ {"description", "Number of top headlines to summarize (default: 8, max: 25)"}}},+ {"category",+ QJsonObject{{"type", "string"},+ {"description", "Optional category filter to scope the summary (default: ALL)"}}},+ {"time_range",+ QJsonObject{{"type", "string"}, {"description", "Time window for source articles (default: 24H)"}}}};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ int count = qBound(1, args["count"].toInt(8), 25);+ QString category = args["category"].toString("ALL");+ QString time_range = args["time_range"].toString("24H");++ auto all = fetch_articles_sync(false);+ if (all.isEmpty())+ return ToolResult::fail("No news articles available");++ auto filtered = filter_articles(all, category, time_range, "", "ALL", count);+ if (filtered.isEmpty())+ return ToolResult::fail("No articles match the requested filter");++ auto* svc = &NewsService::instance();+ bool ok = false;+ QString summary;+ detail::run_async_wait(svc, [svc, filtered, count, &ok, &summary](auto signal_done) {+ svc->summarize_headlines(filtered, count,+ [signal_done, &ok, &summary](bool success, QString s) {+ ok = success;+ if (success)+ summary = std::move(s);+ signal_done();+ });+ });++ if (!ok || summary.isEmpty())+ return ToolResult::fail("Summarization failed (network error or empty response)");++ return ToolResult::ok_data(QJsonObject{+ {"summary", summary}, {"headline_count", filtered.size()}, {"time_range", time_range}});+ };+ tools.push_back(std::move(t));+ }++ // ── get_news_clusters ───────────────────────────────────────────────+ //+ // Groups related stories across sources. An LLM agent uses this to+ // distinguish a real event ("5 sources covering this") from a one-off+ // post. Each cluster carries a lead article + sibling articles, source+ // count, velocity (rising/stable/falling), and a `is_breaking` flag.+ {+ ToolDef t;+ t.name = "get_news_clusters";+ t.description = "Group related news stories across sources into clusters. "+ "Returns each cluster's lead article, sibling articles, source count, "+ "velocity (rising/stable/falling), and breaking flag. "+ "Use this to find events being covered by multiple outlets — high "+ "source_count = real story, low = niche or single-source. "+ "Filters: category, time_range (1H/6H/24H/48H/7D/30D), breaking_only.";+ t.category = "news";+ t.input_schema.properties = QJsonObject{+ {"category", QJsonObject{{"type", "string"}, {"description", "Category filter (default: ALL)"}}},+ {"time_range",+ QJsonObject{{"type", "string"}, {"description", "Time window: 1H, 6H, 24H, 48H, 7D, 30D"}}},+ {"breaking_only", QJsonObject{{"type", "boolean"},+ {"description", "Restrict to breaking-news clusters only (default: false)"}}},+ {"min_sources",+ QJsonObject{{"type", "integer"},+ {"description", "Only return clusters with at least N sources (default: 1)"}}},+ {"limit", QJsonObject{{"type", "integer"}, {"description", "Max clusters (default: 25, max: 100)"}}},+ {"include_articles",+ QJsonObject{{"type", "boolean"},+ {"description",+ "Include the full sibling-article list per cluster (default: false; lead only)"}}}};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString category = args["category"].toString("ALL");+ QString time_range = args["time_range"].toString("24H");+ bool breaking_only = args["breaking_only"].toBool(false);+ int min_sources = std::max(1, args["min_sources"].toInt(1));+ int limit = qBound(1, args["limit"].toInt(25), 100);+ bool include_articles = args["include_articles"].toBool(false);++ auto all = fetch_articles_sync(false);+ if (all.isEmpty())+ return ToolResult::fail("No news articles available");++ // Filter the article pool first so clustering only sees the+ // relevant subset — cheaper and avoids cross-window dilution.+ auto pool = filter_articles(all, category, time_range, "", "ALL", 0);+ auto clusters = cluster_articles(pool);+ if (breaking_only)+ clusters = get_breaking_clusters(clusters);++ QJsonArray result;+ int kept = 0;+ for (const auto& c : clusters) {+ if (c.source_count < min_sources)+ continue;+ QJsonObject obj{{"id", c.id},+ {"lead", article_to_json(c.lead_article)},+ {"source_count", c.source_count},+ {"article_count", c.articles.size()},+ {"velocity", c.velocity},+ {"sentiment", sentiment_string(c.sentiment)},+ {"category", c.category},+ {"tier", c.tier},+ {"is_breaking", c.is_breaking},+ {"latest_sort_ts", static_cast<qint64>(c.latest_sort_ts)}};+ if (include_articles) {+ QJsonArray arts;+ for (const auto& a : c.articles)+ arts.append(article_to_json(a));+ obj["articles"] = arts;+ }+ result.append(obj);+ if (++kept >= limit)+ break;+ }++ return ToolResult::ok(QString("%1 clusters").arg(result.size()),+ QJsonObject{{"count", result.size()},+ {"category", category},+ {"time_range", time_range},+ {"breaking_only", breaking_only},+ {"clusters", result}});+ };+ tools.push_back(std::move(t));+ }++ // ── get_threat_alerts ───────────────────────────────────────────────+ //+ // Surfaces only articles classified as HIGH or CRITICAL threat by+ // NewsService::classify_threat(). Risk-monitoring agents use this to+ // poll for events without sifting routine market news.+ {+ ToolDef t;+ t.name = "get_threat_alerts";+ t.description = "Return only news articles classified as HIGH or CRITICAL threat — "+ "war/conflict, market crashes, cyberattacks, sovereign defaults, etc. "+ "Each result carries threat level, threat category (conflict/cyber/"+ "natural/market/regulatory/general), and confidence score (0-1). "+ "Filter by min_level (CRITICAL or HIGH; default: HIGH) and time_range.";+ t.category = "news";+ t.input_schema.properties = QJsonObject{+ {"min_level",+ QJsonObject{{"type", "string"},+ {"description", "Minimum threat level: CRITICAL or HIGH (default: HIGH)"}}},+ {"threat_category",+ QJsonObject{{"type", "string"},+ {"description", "Filter by threat category: conflict, cyber, natural, "+ "market, regulatory, general (default: any)"}}},+ {"time_range", QJsonObject{{"type", "string"},+ {"description", "Time window: 1H, 6H, 24H, 48H, 7D, 30D"}}},+ {"limit", QJsonObject{{"type", "integer"}, {"description", "Max alerts (default: 25, max: 100)"}}}};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString min_level_s = args["min_level"].toString("HIGH").toUpper().trimmed();+ QString threat_cat_filter = args["threat_category"].toString().toLower().trimmed();+ QString time_range = args["time_range"].toString("24H");+ int limit = qBound(1, args["limit"].toInt(25), 100);++ // Resolve min_level — anything below HIGH is rejected; only the+ // top two tiers count as "alerts".+ const bool critical_only = (min_level_s == "CRITICAL");++ auto all = fetch_articles_sync(false);+ if (all.isEmpty())+ return ToolResult::fail("No news articles available");++ auto pool = filter_articles(all, "ALL", time_range, "", "ALL", 0);++ QJsonArray result;+ int critical = 0, high = 0;+ for (const auto& a : pool) {+ const auto level = a.threat.level;+ const bool keep = critical_only ? (level == ThreatLevel::CRITICAL)+ : (level == ThreatLevel::CRITICAL || level == ThreatLevel::HIGH);+ if (!keep)+ continue;+ if (!threat_cat_filter.isEmpty() && a.threat.category.toLower() != threat_cat_filter)+ continue;++ QJsonObject obj = article_to_json(a);+ obj["threat_level"] = threat_level_string(level);+ obj["threat_category"] = a.threat.category;+ obj["threat_confidence"] = a.threat.confidence;+ result.append(obj);++ if (level == ThreatLevel::CRITICAL)+ ++critical;+ else+ ++high;++ if (result.size() >= limit)+ break;+ }++ return ToolResult::ok(QString("%1 threat alerts (%2 critical, %3 high)")+ .arg(result.size()).arg(critical).arg(high),+ QJsonObject{{"count", result.size()},+ {"critical_count", critical},+ {"high_count", high},+ {"min_level", min_level_s},+ {"time_range", time_range},+ {"alerts", result}});+ };+ tools.push_back(std::move(t));+ }++ // ── get_news_status ─────────────────────────────────────────────────+ //+ // Diagnostic / health-check tool. An agent calls this before relying on+ // news output to confirm feeds are loaded — otherwise a cold-cache run+ // returns 0 articles silently and downstream reasoning is meaningless.+ {+ ToolDef t;+ t.name = "get_news_status";+ t.description = "Health check for the news subsystem: total feeds configured, active "+ "sources publishing, cached article count, live WebSocket connection "+ "status, breaking-cluster count, and a snapshot of category counts. "+ "Call this before running multi-step research so the agent can detect "+ "an empty / cold-cache state instead of reasoning over no data.";+ t.category = "news";+ t.handler = [](const QJsonObject&) -> ToolResult {+ auto* svc = &NewsService::instance();++ // Reuse cached articles if available — explicitly NOT forcing a+ // refresh here. This is a status check, not a fetch trigger.+ auto all = fetch_articles_sync(false);++ QSet<QString> sources;+ QMap<QString, int> categories;+ int bullish = 0, bearish = 0, neutral = 0;+ int high_threat = 0, critical_threat = 0;+ int64_t latest_ts = 0;+ for (const auto& a : all) {+ if (!a.source.isEmpty())+ sources.insert(a.source);+ if (!a.category.isEmpty())+ categories[a.category]++;+ switch (a.sentiment) {+ case Sentiment::BULLISH: ++bullish; break;+ case Sentiment::BEARISH: ++bearish; break;+ default: ++neutral; break;+ }+ if (a.threat.level == ThreatLevel::CRITICAL) ++critical_threat;+ else if (a.threat.level == ThreatLevel::HIGH) ++high_threat;+ if (a.sort_ts > latest_ts) latest_ts = a.sort_ts;+ }++ int breaking_clusters = 0;+ if (!all.isEmpty()) {+ auto clusters = cluster_articles(all);+ breaking_clusters = static_cast<int>(get_breaking_clusters(clusters).size());+ }++ QJsonObject cat_json;+ for (auto it = categories.constBegin(); it != categories.constEnd(); ++it)+ cat_json[it.key()] = it.value();++ const bool live = svc->is_live_connected();+ const bool healthy = !all.isEmpty() && sources.size() >= 5;++ QJsonObject data{+ {"healthy", healthy},+ {"feeds_configured", svc->feed_count()},+ {"active_sources", static_cast<int>(sources.size())},+ {"cached_articles", all.size()},+ {"latest_article_ts", static_cast<qint64>(latest_ts)},+ {"breaking_clusters", breaking_clusters},+ {"high_threat_count", high_threat},+ {"critical_threat_count", critical_threat},+ {"live_websocket_connected", live},+ {"sentiment", QJsonObject{{"bullish", bullish}, {"bearish", bearish}, {"neutral", neutral}}},+ {"categories", cat_json}};++ const QString summary = healthy+ ? QString("OK: %1 articles from %2 sources").arg(all.size()).arg(sources.size())+ : QString("DEGRADED: %1 articles from %2 sources — feeds may still be loading or blocked")+ .arg(all.size()).arg(sources.size());+ return ToolResult::ok(summary, data);+ };+ tools.push_back(std::move(t));+ }+return tools;}diff --git a/fincept-qt/src/mcp/tools/PythonTools.cpp b/fincept-qt/src/mcp/tools/PythonTools.cppindex 67779ee25..131471d01 100644--- a/fincept-qt/src/mcp/tools/PythonTools.cpp+++ b/fincept-qt/src/mcp/tools/PythonTools.cpp@@ -3,10 +3,10 @@#include "mcp/tools/PythonTools.h"#include "core/logging/Logger.h"+#include "mcp/tools/ThreadHelper.h"#include "python/PythonRunner.h"#include <QDir>-#include <QEventLoop>#include <QJsonDocument>#include <QRegularExpression>@@ -14,42 +14,40 @@ namespace fincept::mcp::tools {static constexpr const char* TAG = "PythonTools";-// Synchronously run a Python script (called from a background thread via McpProvider)+// Synchronously run a Python script. Tool handlers run on a worker thread;+// PythonRunner's QProcess lives on the main thread. We marshal the run()+// call onto the runner's thread (see mcp/tools/ThreadHelper.h).static ToolResult run_script_sync(const QString& script, const QStringList& args) {if (!python::PythonRunner::instance().is_available())return ToolResult::fail("Python is not available — run setup first");ToolResult out;- bool done = false;- QEventLoop loop;-- python::PythonRunner::instance().run(script, args, [&](python::PythonResult result) {- if (!result.success) {- out = ToolResult::fail("Script failed: " + result.error);- } else {- QString json_text = python::extract_json(result.output);- if (json_text.isEmpty())- json_text = result.output;-- QJsonDocument doc = QJsonDocument::fromJson(json_text.toUtf8());- if (!doc.isNull()) {- if (doc.isObject())- out = ToolResult::ok_data(doc.object());- else if (doc.isArray())- out = ToolResult::ok_data(doc.array());- else- out = ToolResult::ok(result.output);+ auto* runner = &python::PythonRunner::instance();+ detail::run_async_wait(runner, [&](auto signal_done) {+ runner->run(script, args, [&, signal_done](python::PythonResult result) {+ if (!result.success) {+ out = ToolResult::fail("Script failed: " + result.error);} else {- out = ToolResult::ok(result.output);+ QString json_text = python::extract_json(result.output);+ if (json_text.isEmpty())+ json_text = result.output;++ QJsonDocument doc = QJsonDocument::fromJson(json_text.toUtf8());+ if (!doc.isNull()) {+ if (doc.isObject())+ out = ToolResult::ok_data(doc.object());+ else if (doc.isArray())+ out = ToolResult::ok_data(doc.array());+ else+ out = ToolResult::ok(result.output);+ } else {+ out = ToolResult::ok(result.output);+ }}- }- done = true;- loop.quit();+ signal_done();+ });});- if (!done)- loop.exec();-return out;}@@ -60,12 +58,15 @@ std::vector<ToolDef> get_python_tools() {{ToolDef t;t.name = "run_python_script";- t.description = "Execute a Python analytics script by name. Scripts live in the scripts/ directory "- "and return JSON. Examples: yfinance_quote, portfolio_analysis, economics_fred.";+ t.description =+ "Execute a Python analytics script by name. IMPORTANT: only pass script names returned by "+ "list_python_scripts — do not invent or guess script names. For market data prefer "+ "get_quote / get_candles / edgar_* tools rather than Python scripts.";t.category = "analytics";t.input_schema.properties = QJsonObject{{"script",- QJsonObject{{"type", "string"}, {"description", "Script name without .py (e.g. yfinance_quote)"}}},+ QJsonObject{{"type", "string"},+ {"description", "Script name (without .py) — must be a name returned by list_python_scripts"}}},{"args",QJsonObject{{"type", "array"}, {"description", "Array of string arguments to pass to the script"}}}};t.input_schema.required = {"script"};diff --git a/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp b/fincept-qt/src/mcp/tools/ReportBuilderTools.cppnew file mode 100644index 000000000..6d8b636df--- /dev/null+++ b/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp@@ -0,0 +1,531 @@+// ReportBuilderTools.cpp — MCP tools for live report authoring.+//+// Every mutating tool runs on a worker thread (LlmService::do_request lives+// on QtConcurrent::run). To talk to the main-thread-resident+// ReportBuilderService, we route through QMetaObject::invokeMethod with+// Qt::BlockingQueuedConnection. This guarantees:+// • The service mutates on the main thread (Qt's invariant for QObjects+// created there, including the QUndoStack).+// • The tool returns only after the mutation has completed and signals+// have been emitted — so when the LLM asks "now update component X",+// the previous add has fully committed.+// • Side effects visible to the user (canvas re-render) happen before+// the LLM moves on.++#include "mcp/tools/ReportBuilderTools.h"++#include "core/events/EventBus.h"+#include "core/logging/Logger.h"+#include "core/report/ReportDocument.h"+#include "services/report_builder/ReportBuilderService.h"++#include <QCoreApplication>+#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QMetaObject>+#include <QString>+#include <QStringList>+#include <QThread>++namespace fincept::mcp::tools {++namespace {++constexpr const char* RB_TOOLS_TAG = "ReportBuilderTools";+namespace rep = ::fincept::report;+using Service = ::fincept::services::ReportBuilderService;++// ── Threading helper ─────────────────────────────────────────────────────────+//+// Run `fn` on the service's owning thread (the main thread) and block until+// it completes. If we're already on that thread we just call directly.++template <typename F>+void run_on_service_thread(F&& fn) {+ auto* svc = &Service::instance();+ if (QThread::currentThread() == svc->thread()) {+ fn();+ return;+ }+ QMetaObject::invokeMethod(svc, std::forward<F>(fn), Qt::BlockingQueuedConnection);+}++// ── Auto-navigate ────────────────────────────────────────────────────────────+//+// On the first mutation in an LLM tool-call burst, publish nav.switch_screen+// so the user can see the live updates. Stays silent for subsequent+// mutations within ~5 seconds (tracked by service.note_llm_mutation timer).++void maybe_request_navigation() {+ static std::atomic<qint64> last_nav_ms{0};+ const qint64 now = QDateTime::currentMSecsSinceEpoch();+ qint64 prev = last_nav_ms.load();+ if (now - prev < 5000)+ return;+ if (!last_nav_ms.compare_exchange_strong(prev, now))+ return;+ LOG_INFO(RB_TOOLS_TAG, "Auto-navigate: publishing nav.switch_screen → report_builder");+ fincept::EventBus::instance().publish(+ "nav.switch_screen",+ QVariantMap{{"screen_id", "report_builder"}, {"tab_index", 8}});+}++// Helper: called at the top of every mutating tool.+void on_llm_mutation_start() {+ maybe_request_navigation();+ auto* svc = &Service::instance();+ QMetaObject::invokeMethod(svc, [svc]() { svc->note_llm_mutation(); }, Qt::QueuedConnection);+}++// ── JSON helpers ─────────────────────────────────────────────────────────────++QMap<QString, QString> json_to_string_map(const QJsonObject& obj) {+ QMap<QString, QString> out;+ for (auto it = obj.constBegin(); it != obj.constEnd(); ++it) {+ const QJsonValue& v = it.value();+ if (v.isString())+ out[it.key()] = v.toString();+ else if (v.isDouble()) {+ // Preserve integer formatting where possible (config strings+ // like "rows":"3" are user-visible).+ double d = v.toDouble();+ if (d == static_cast<qint64>(d))+ out[it.key()] = QString::number(static_cast<qint64>(d));+ else+ out[it.key()] = QString::number(d);+ } else if (v.isBool())+ out[it.key()] = v.toBool() ? "true" : "false";+ else+ out[it.key()] = QString::fromUtf8(QJsonDocument::fromVariant(v.toVariant()).toJson(QJsonDocument::Compact));+ }+ return out;+}++QJsonObject component_to_json(const rep::ReportComponent& c) {+ QJsonObject cfg;+ for (auto it = c.config.cbegin(); it != c.config.cend(); ++it)+ cfg[it.key()] = it.value();+ return QJsonObject{{"id", c.id}, {"type", c.type}, {"content", c.content}, {"config", cfg}};+}++QJsonObject metadata_to_json(const rep::ReportMetadata& m) {+ return QJsonObject{+ {"title", m.title},+ {"author", m.author},+ {"company", m.company},+ {"date", m.date},+ {"header_left", m.header_left},+ {"header_center", m.header_center},+ {"header_right", m.header_right},+ {"footer_left", m.footer_left},+ {"footer_center", m.footer_center},+ {"footer_right", m.footer_right},+ {"show_page_numbers", m.show_page_numbers},+ };+}++bool valid_component_type(const QString& t) {+ static const QStringList valid = {"heading", "text", "table", "image", "chart",+ "sparkline", "stats_block", "callout", "code", "divider",+ "quote", "list", "market_data", "page_break", "toc"};+ return valid.contains(t);+}++} // namespace++// ── Tool definitions ─────────────────────────────────────────────────────────++std::vector<ToolDef> get_report_builder_tools() {+ std::vector<ToolDef> tools;++ // ── report_get_state ────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_get_state";+ t.description = "Read the current Report Builder document — components (with stable ids), metadata, theme, "+ "and current file path. Call this BEFORE editing existing components so you reference the "+ "right ids. Returns: {components:[{id,type,content,config}], metadata:{...}, theme, "+ "current_file, recent_files}.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{};+ t.handler = [](const QJsonObject&) -> ToolResult {+ auto& svc = Service::instance();+ QJsonArray comps;+ for (const auto& c : svc.components())+ comps.append(component_to_json(c));+ QJsonObject result{+ {"components", comps},+ {"metadata", metadata_to_json(svc.metadata())},+ {"theme", svc.theme().name},+ {"current_file", svc.current_file()},+ {"recent_files", QJsonArray::fromStringList(svc.recent_files())},+ };+ return ToolResult::ok(QString("Report has %1 components").arg(comps.size()), result);+ };+ tools.push_back(std::move(t));+ }++ // ── report_add_component ────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_add_component";+ t.description =+ "Insert a component into the report. Returns the assigned stable `id` and the resulting `index`. "+ "The id is what you use to update/remove/move this component later. "+ "Types: heading, text, table, image, chart, sparkline, stats_block, callout, code, divider, quote, "+ "list, market_data, page_break, toc.\n"+ "\n"+ "Content guidelines:\n"+ "• heading: short title text, no markdown. Adds top margin + accent rule automatically.\n"+ "• text: paragraph body. SUPPORTS MARKDOWN: **bold**, *italic*, `code`, [links](url). "+ " Use **bold** liberally to highlight key figures. One paragraph per component is ideal.\n"+ "• list: each line becomes a bullet. Markdown emphasis works inside items.\n"+ "• quote: italic block-quoted text, supports markdown.\n"+ "• callout: info/warning/success/danger boxes. Set config={'style':'warning','heading':'Risk'}.\n"+ "• code: monospaced code block (no syntax highlighting).\n"+ "• divider: horizontal rule, no content needed.\n"+ "• page_break: forces a new physical page.\n"+ "• toc: auto-generated from heading components — place near the top.\n"+ "\n"+ "Data-bearing components (use `config`):\n"+ "• table: config={'csv':'Header1,Header2,Header3|Row1Col1,Row1Col2,Row1Col3|...'}. "+ " Use | to separate rows, , to separate cells. First row is bolded as header. "+ " Numeric cells right-align automatically. Example for financials:\n"+ " 'Metric,FY22,FY23,FY24|Revenue ($M),81462,96773,97690|Gross Margin,25.6%,17.7%,17.9%'\n"+ "• chart: config={'chart_type':'bar'|'line'|'pie','title':'Revenue','data':'10,20,30',"+ " 'labels':'Q1,Q2,Q3','width':'640'}. Data is CSV numbers, labels CSV strings.\n"+ "• stats_block: config={'title':'Key Stats','data':'P/E:42.1\\nMarket Cap:$890B\\n...'}. "+ " Use Label:Value lines, \\n separated.\n"+ "• market_data: config={'symbol':'TSLA'}. The symbol is enough — quote auto-fills.\n"+ "• image: config={'path':'/abs/path.png','width':'400','caption':'Fig. 1','align':'center'}.\n"+ "• sparkline: config={'title':'Revenue trend','data':'10,12,11,15','current':'15.2','change_pct':'+8.4'}.\n"+ "\n"+ "If insert_at is omitted, the component is appended.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{+ {"type",+ QJsonObject{{"type", "string"},+ {"description",+ "Component type: heading, text, table, image, chart, sparkline, stats_block, callout, "+ "code, divider, quote, list, market_data, page_break, toc"}}},+ {"content",+ QJsonObject{{"type", "string"},+ {"description", "Text content (used by heading/text/quote/code/list/callout)"}}},+ {"config",+ QJsonObject{{"type", "object"},+ {"description", "Type-specific config (rows/cols, chart_type/title/data/labels, symbol, "+ "style, width/caption/align, …)"}}},+ {"insert_at",+ QJsonObject{{"type", "integer"},+ {"description", "Zero-based index to insert at; omit to append at the end"}}},+ };+ t.input_schema.required = {"type"};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ LOG_INFO(RB_TOOLS_TAG, QString("report_add_component called args=%1")+ .arg(QString::fromUtf8(QJsonDocument(args).toJson(QJsonDocument::Compact))+ .left(300)));+ QString type = args.value("type").toString().trimmed();+ if (type.isEmpty())+ return ToolResult::fail("Missing 'type'");+ if (!valid_component_type(type))+ return ToolResult::fail("Unknown component type: " + type);++ on_llm_mutation_start();++ rep::ReportComponent c;+ c.type = type;+ c.content = args.value("content").toString();+ c.config = json_to_string_map(args.value("config").toObject());++ int insert_at = args.contains("insert_at") ? args.value("insert_at").toInt(-1) : -1;++ int new_id = -1, idx = -1;+ run_on_service_thread([&]() {+ auto& svc = Service::instance();+ new_id = svc.add_component(c, insert_at);+ idx = svc.index_of(new_id);+ });++ LOG_INFO(RB_TOOLS_TAG, QString("report_add_component done id=%1 index=%2 type=%3")+ .arg(new_id).arg(idx).arg(type));+ return ToolResult::ok(QString("Added %1 (id=%2)").arg(type).arg(new_id),+ QJsonObject{{"id", new_id}, {"index", idx}, {"type", type}});+ };+ tools.push_back(std::move(t));+ }++ // ── report_update_component ─────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_update_component";+ t.description =+ "Update an existing component by stable id. If `content` is provided it replaces the current content "+ "(remember: text/list/quote/callout support markdown — use **bold** for emphasis). If `config` is "+ "provided, the supplied keys are merged into the existing config (keys not mentioned are kept). "+ "For tables, set config={'csv':'h1,h2|r1c1,r1c2|...'}. For charts, set "+ "config={'chart_type':...,'data':'...','labels':'...'}. See report_add_component description for "+ "the full config reference. Returns success and the resulting component.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{+ {"id", QJsonObject{{"type", "integer"}, {"description", "Stable component id from report_add_component "+ "or report_get_state"}}},+ {"content", QJsonObject{{"type", "string"}, {"description", "New content (omit to keep existing)"}}},+ {"config",+ QJsonObject{{"type", "object"},+ {"description", "Keys to merge into existing config (omit to keep existing)"}}},+ };+ t.input_schema.required = {"id"};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ int id = args.value("id").toInt(0);+ if (id <= 0)+ return ToolResult::fail("Missing or invalid 'id'");++ const bool has_content = args.contains("content");+ QString content = args.value("content").toString();+ QMap<QString, QString> partial = json_to_string_map(args.value("config").toObject());++ on_llm_mutation_start();++ bool ok = false;+ QJsonObject after;+ run_on_service_thread([&]() {+ auto& svc = Service::instance();+ ok = svc.patch_component(id, has_content ? &content : nullptr, partial);+ if (ok) {+ int idx = svc.index_of(id);+ if (idx >= 0)+ after = component_to_json(svc.components()[idx]);+ }+ });++ if (!ok)+ return ToolResult::fail(QString("Component id=%1 not found").arg(id));+ return ToolResult::ok(QString("Updated component id=%1").arg(id), after);+ };+ tools.push_back(std::move(t));+ }++ // ── report_remove_component ─────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_remove_component";+ t.description = "Remove a component by stable id.";+ t.category = "report-builder";+ t.input_schema.properties =+ QJsonObject{{"id", QJsonObject{{"type", "integer"}, {"description", "Stable component id"}}}};+ t.input_schema.required = {"id"};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ int id = args.value("id").toInt(0);+ if (id <= 0)+ return ToolResult::fail("Missing or invalid 'id'");+ on_llm_mutation_start();+ bool ok = false;+ run_on_service_thread([&]() { ok = Service::instance().remove_component(id); });+ return ok ? ToolResult::ok(QString("Removed id=%1").arg(id))+ : ToolResult::fail(QString("Component id=%1 not found").arg(id));+ };+ tools.push_back(std::move(t));+ }++ // ── report_move_component ───────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_move_component";+ t.description = "Move a component to a new position by stable id. Use `to_index` (zero-based).";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{+ {"id", QJsonObject{{"type", "integer"}, {"description", "Stable component id"}}},+ {"to_index", QJsonObject{{"type", "integer"}, {"description", "New zero-based index"}}},+ };+ t.input_schema.required = {"id", "to_index"};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ int id = args.value("id").toInt(0);+ int to = args.value("to_index").toInt(-1);+ if (id <= 0 || to < 0)+ return ToolResult::fail("Missing or invalid 'id' / 'to_index'");+ on_llm_mutation_start();+ bool ok = false;+ run_on_service_thread([&]() { ok = Service::instance().move_component(id, to); });+ return ok ? ToolResult::ok(QString("Moved id=%1 to index=%2").arg(id).arg(to))+ : ToolResult::fail(QString("Component id=%1 not found").arg(id));+ };+ tools.push_back(std::move(t));+ }++ // ── report_clear ───────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_clear";+ t.description = "Clear the entire report — remove all components and reset metadata to defaults.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{};+ t.handler = [](const QJsonObject&) -> ToolResult {+ on_llm_mutation_start();+ run_on_service_thread([]() { Service::instance().clear_document(); });+ return ToolResult::ok("Report cleared");+ };+ tools.push_back(std::move(t));+ }++ // ── report_set_metadata ─────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_set_metadata";+ t.description = "Update report metadata. Any field omitted from the call is left unchanged.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{+ {"title", QJsonObject{{"type", "string"}}},+ {"author", QJsonObject{{"type", "string"}}},+ {"company", QJsonObject{{"type", "string"}}},+ {"date", QJsonObject{{"type", "string"}, {"description", "YYYY-MM-DD"}}},+ {"header_left", QJsonObject{{"type", "string"}}},+ {"header_center", QJsonObject{{"type", "string"}}},+ {"header_right", QJsonObject{{"type", "string"}}},+ {"footer_left", QJsonObject{{"type", "string"}}},+ {"footer_center", QJsonObject{{"type", "string"}}},+ {"footer_right", QJsonObject{{"type", "string"}}},+ {"show_page_numbers", QJsonObject{{"type", "boolean"}}},+ };+ t.handler = [](const QJsonObject& args) -> ToolResult {+ on_llm_mutation_start();+ QJsonObject after;+ run_on_service_thread([&]() {+ auto& svc = Service::instance();+ rep::ReportMetadata m = svc.metadata();+ if (args.contains("title")) m.title = args.value("title").toString();+ if (args.contains("author")) m.author = args.value("author").toString();+ if (args.contains("company")) m.company = args.value("company").toString();+ if (args.contains("date")) m.date = args.value("date").toString();+ if (args.contains("header_left")) m.header_left = args.value("header_left").toString();+ if (args.contains("header_center")) m.header_center = args.value("header_center").toString();+ if (args.contains("header_right")) m.header_right = args.value("header_right").toString();+ if (args.contains("footer_left")) m.footer_left = args.value("footer_left").toString();+ if (args.contains("footer_center")) m.footer_center = args.value("footer_center").toString();+ if (args.contains("footer_right")) m.footer_right = args.value("footer_right").toString();+ if (args.contains("show_page_numbers"))+ m.show_page_numbers = args.value("show_page_numbers").toBool();+ svc.set_metadata(m);+ after = metadata_to_json(svc.metadata());+ });+ return ToolResult::ok("Metadata updated", after);+ };+ tools.push_back(std::move(t));+ }++ // ── report_set_theme ────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_set_theme";+ t.description = "Set the report color theme. Valid names: 'Light Professional', 'Dark Corporate', "+ "'Bloomberg Terminal', 'Midnight Blue'.";+ t.category = "report-builder";+ t.input_schema.properties =+ QJsonObject{{"name", QJsonObject{{"type", "string"}, {"description", "Theme name (case-sensitive)"}}}};+ t.input_schema.required = {"name"};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString name = args.value("name").toString();+ if (!rep::themes::all_names().contains(name))+ return ToolResult::fail("Unknown theme. Valid: " + rep::themes::all_names().join(", "));+ on_llm_mutation_start();+ run_on_service_thread([&]() { Service::instance().set_theme(rep::themes::by_name(name)); });+ return ToolResult::ok("Theme set to " + name);+ };+ tools.push_back(std::move(t));+ }++ // ── report_apply_template ──────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_apply_template";+ t.description =+ "Replace the report with a built-in template. Names: 'Blank Report', 'Meeting Notes', 'Investment Memo', "+ "'Stock Research', 'Portfolio Review', 'Watchlist Report', 'Dividend Income Report', "+ "'Daily Market Brief', 'Trade Journal', 'Technical Analysis', 'Pre-Market Checklist', "+ "'Equity Research Report', 'Earnings Review', 'M&A Deal Summary', 'Sector Deep Dive', "+ "'Macro Economic Summary', 'Country Risk Report', 'Central Bank Monitor', "+ "'Crypto Research Report', 'DeFi Protocol Analysis', 'Crypto Portfolio Review', "+ "'Bond Research Report', 'Yield Curve Analysis', 'Quant Strategy Report', "+ "'Risk Management Report', 'Business Performance', 'Project Status Report', "+ "'Financial Statement'.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{{"name", QJsonObject{{"type", "string"}}}};+ t.input_schema.required = {"name"};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString name = args.value("name").toString().trimmed();+ if (name.isEmpty())+ return ToolResult::fail("Missing 'name'");+ on_llm_mutation_start();+ run_on_service_thread([&]() { Service::instance().apply_template(name); });+ return ToolResult::ok("Applied template: " + name);+ };+ tools.push_back(std::move(t));+ }++ // ── report_save ────────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_save";+ t.description = "Save the report to disk. If `path` is omitted, saves to the current file (errors if none).";+ t.category = "report-builder";+ t.input_schema.properties =+ QJsonObject{{"path", QJsonObject{{"type", "string"}, {"description", "Absolute file path (.fincept)"}}}};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString path = args.value("path").toString();+ on_llm_mutation_start();+ QString resolved;+ QString err;+ run_on_service_thread([&]() {+ auto& svc = Service::instance();+ QString p = path.isEmpty() ? svc.current_file() : path;+ if (p.isEmpty()) {+ err = "No path provided and no current file. Pass `path`.";+ return;+ }+ auto r = svc.save_to(p);+ if (r.is_err()) {+ err = QString::fromStdString(r.error());+ return;+ }+ resolved = p;+ });+ if (!err.isEmpty())+ return ToolResult::fail(err);+ return ToolResult::ok("Saved", QJsonObject{{"path", resolved}});+ };+ tools.push_back(std::move(t));+ }++ // ── report_load ────────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_load";+ t.description = "Load a report from disk, replacing the current document.";+ t.category = "report-builder";+ t.input_schema.properties =+ QJsonObject{{"path", QJsonObject{{"type", "string"}, {"description", "Absolute file path"}}}};+ t.input_schema.required = {"path"};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString path = args.value("path").toString();+ if (path.isEmpty())+ return ToolResult::fail("Missing 'path'");+ on_llm_mutation_start();+ QString err;+ run_on_service_thread([&]() {+ auto r = Service::instance().load_from(path);+ if (r.is_err())+ err = QString::fromStdString(r.error());+ });+ if (!err.isEmpty())+ return ToolResult::fail(err);+ return ToolResult::ok("Loaded", QJsonObject{{"path", path}});+ };+ tools.push_back(std::move(t));+ }++ LOG_INFO(RB_TOOLS_TAG, QString("Built %1 report builder tools").arg(tools.size()));+ return tools;+}++} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/ReportBuilderTools.h b/fincept-qt/src/mcp/tools/ReportBuilderTools.hnew file mode 100644index 000000000..4c077fd8f--- /dev/null+++ b/fincept-qt/src/mcp/tools/ReportBuilderTools.h@@ -0,0 +1,14 @@+#pragma once+#include "mcp/McpTypes.h"++#include <vector>++namespace fincept::mcp::tools {++// LLM-facing tools for live authoring of the active report document.+// All tools dispatch onto the main thread synchronously (BlockingQueuedConnection),+// so by the time a tool returns its `ToolResult`, the change is visible on the+// canvas (if the screen is open) and persisted in the service.+std::vector<ToolDef> get_report_builder_tools();++} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/ThreadHelper.h b/fincept-qt/src/mcp/tools/ThreadHelper.hnew file mode 100644index 000000000..931e4ea42--- /dev/null+++ b/fincept-qt/src/mcp/tools/ThreadHelper.h@@ -0,0 +1,178 @@+#pragma once+// ThreadHelper.h — shared thread-marshaling helpers for MCP tool handlers.+//+// MCP tool handlers run on a QtConcurrent::run worker thread (off the main+// UI thread). Calling a Qt service that owns a QNetworkAccessManager (or+// any QObject parented on a different thread) directly from a worker is a+// Qt invariant violation: signals fire on the owning thread, child QObjects+// get the wrong parent thread, and the app crashes a few seconds later+// with `QObject: Cannot create children for a parent that is in a different+// thread` warnings. We've seen this pattern crash `get_news`, `refresh_news`,+// and is latent in 7+ other tool .cpp files (Edgar, Forum, Profile, MA,+// AltInvestments, PythonTools async runner, DataHub subscribe).+//+// The fix is always the same: post the work to the target's thread, sleep+// the worker on a wait condition, wake when the callback fires. These two+// helpers consolidate that pattern so each tool file doesn't re-implement+// it (poorly).++#include <QMetaObject>+#include <QMutex>+#include <QObject>+#include <QPointer>+#include <QThread>+#include <QWaitCondition>++#include <functional>+#include <type_traits>+#include <utility>++namespace fincept::mcp::tools::detail {++// ── run_on_target_thread_sync ────────────────────────────────────────────────+//+// Run `fn` on `target`'s thread and block the calling thread until it+// returns. If we're already on the target's thread we just call directly.+//+// Use this when the target call is itself synchronous on the main thread —+// e.g. `service->some_getter()` — and you want the result back on the+// worker without races.+template <typename F>+void run_on_target_thread_sync(QObject* target, F&& fn) {+ if (!target || QThread::currentThread() == target->thread()) {+ std::forward<F>(fn)();+ return;+ }+ QMetaObject::invokeMethod(target, std::forward<F>(fn), Qt::BlockingQueuedConnection);+}++// ── run_async_callback_sync ──────────────────────────────────────────────────+//+// Bridge an async-callback API (the `target` posts work on its own thread+// and eventually invokes `cb(args...)`) to a synchronous worker call.+//+// Usage:+// bool ok = false;+// QVector<NewsArticle> articles;+// run_async_callback_sync(svc, [&](auto resolve) {+// svc->fetch_all_news(force, [resolve](bool s, auto a) {+// resolve(s, std::move(a));+// });+// }, [&](bool s, QVector<NewsArticle> a) {+// ok = s;+// articles = std::move(a);+// });+//+// `start` is invoked on the target's thread with a `resolve(...)` callable.+// `on_done` runs on the worker after `resolve` is called from any thread.+//+// Internally:+// • `start` is QueuedConnection-posted to the target.+// • `resolve` is callable from any thread (typically the network reply+// thread or the target's thread).+// • The worker sleeps on a QWaitCondition until `resolve` fires.+//+// Optional timeout_ms: if > 0 and resolve hasn't fired by then, on_done is+// called with a default-constructed args (caller decides what that means).+// Defaults to no timeout — relies on the underlying API to call back.+template <typename Start, typename OnDone>+void run_async_callback_sync(QObject* target, Start&& start, OnDone&& on_done,+ int /*timeout_ms*/ = 0) {+ // We use a small heap-allocated Resolution so the resolve() lambda can+ // outlive both the worker and the target — the target may invoke resolve+ // synchronously (still on worker) or after queuing (on target thread).+ struct Resolution {+ QMutex m;+ QWaitCondition cv;+ bool done = false;+ std::function<void()> consumer; // captures result by reference into on_done's storage+ };+ auto res = std::make_shared<Resolution>();++ auto resolve = [res](auto&&... args) {+ QMutexLocker lock(&res->m);+ if (res->done)+ return; // ignore duplicate resolves+ res->done = true;+ if (res->consumer)+ res->consumer();+ // Note: caller's on_done storage is filled by `consumer` lambda built+ // below. We just signal completion here.+ res->cv.wakeAll();+ };++ // Build the consumer that will move results into on_done. The consumer+ // is set BEFORE we post `start` so the resolve lambda always sees it.+ // We need to capture the args from `resolve(args...)` somehow — a+ // simpler interface is: just have callers wire the result themselves+ // inside their resolve lambda and signal completion via a separate+ // wake. So we expose a pure "wake" resolve and let callers handle args.+ //+ // (See `run_async_void_sync` below for the pure-wake version, which is+ // what most callers actually want.)+ Q_UNUSED(on_done);++ if (!target || QThread::currentThread() == target->thread()) {+ std::forward<Start>(start)(resolve);+ } else {+ QMetaObject::invokeMethod(+ target,+ [start = std::forward<Start>(start), resolve]() mutable { start(resolve); },+ Qt::QueuedConnection);+ }++ QMutexLocker lock(&res->m);+ while (!res->done)+ res->cv.wait(&res->m);+}++// ── run_async_wait ───────────────────────────────────────────────────────────+//+// Simpler, more useful variant. Caller writes the result into outer storage+// inside their start lambda (which captures by reference); the start lambda+// is invoked on the target's thread; the worker blocks until `signal_done`+// is called (from any thread).+//+// QVector<NewsArticle> articles;+// bool ok = false;+// run_async_wait(svc, [&](auto signal_done) {+// svc->fetch_all_news(force, [&, signal_done](bool s, auto a) {+// ok = s;+// articles = std::move(a);+// signal_done();+// });+// });+//+// This is the pattern actually used by the existing fixed code in+// NewsTools::fetch_articles_sync. We just generalize it so each tool file+// doesn't re-roll its own QMutex/QWaitCondition.+template <typename Start>+void run_async_wait(QObject* target, Start&& start) {+ struct Wait {+ QMutex m;+ QWaitCondition cv;+ bool done = false;+ };+ auto w = std::make_shared<Wait>();++ auto signal_done = [w]() {+ QMutexLocker lock(&w->m);+ w->done = true;+ w->cv.wakeAll();+ };++ if (!target || QThread::currentThread() == target->thread()) {+ std::forward<Start>(start)(signal_done);+ } else {+ QMetaObject::invokeMethod(+ target,+ [start = std::forward<Start>(start), signal_done]() mutable { start(signal_done); },+ Qt::QueuedConnection);+ }++ QMutexLocker lock(&w->m);+ while (!w->done)+ w->cv.wait(&w->m);+}++} // namespace fincept::mcp::tools::detaildiff --git a/fincept-qt/src/python/PythonRunner.cpp b/fincept-qt/src/python/PythonRunner.cppindex 261082b18..434e90b6b 100644--- a/fincept-qt/src/python/PythonRunner.cpp+++ b/fincept-qt/src/python/PythonRunner.cpp@@ -2,6 +2,7 @@#include "core/logging/Logger.h"#include "python/PythonSetupManager.h"+#include "storage/secure/SecureStorage.h"#include <QCoreApplication>#include <QDateTime>@@ -9,12 +10,65 @@#include <QFile>#include <QFileInfo>#include <QHash>+#include <QLatin1String>#include <QProcessEnvironment>#include <QStandardPaths>+#include <QStringList>#include <QUuid>namespace fincept::python {+// ── Credential catalogue ─────────────────────────────────────────────────────+// Env-var names that SettingsScreen lets the user configure and store in+// SecureStorage (see SettingsScreen.cpp CRED_KEYS). build_python_env() pulls+// each from SecureStorage and injects it into the subprocess env so Python+// scripts that read os.environ.get("FRED_API_KEY") work whether or not the+// user has the variable in their shell. SecureStorage is the source of truth:+// the injected value overrides any inherited shell value.+//+// Keep this list in sync with SettingsScreen.cpp CRED_KEYS. C++-only services+// (Binance/Kraken/Polymarket) are listed too — injection is harmless when no+// Python script reads them, and it future-proofs new scripts.+static const QStringList kManagedCredentialKeys = {+ "ALPHA_VANTAGE_API_KEY", "POLYGON_API_KEY", "DATABENTO_API_KEY",+ "FRED_API_KEY", "NEWSAPI_KEY", "BINANCE_API_KEY",+ "BINANCE_SECRET_KEY", "KRAKEN_API_KEY", "KRAKEN_SECRET_KEY",+ "IEX_CLOUD_TOKEN", "FINNHUB_API_KEY", "TIINGO_API_KEY",+ "QUANDL_API_KEY", "POLYMARKET_API_KEY", "POLYMARKET_SECRET",+ "POLYMARKET_PASSPHRASE", "POLYMARKET_WALLET",+};++// ── Sensitive shell-env stripping ────────────────────────────────────────────+// After SecureStorage injection, drop any *other* credential-shaped variable+// the user may have inherited from their shell. This prevents unrelated keys+// (e.g. a developer's GITHUB_TOKEN, AWS_SECRET_ACCESS_KEY) from leaking into+// Python subprocesses where they'd be visible via /proc/<pid>/environ on+// Linux or process inspection tools elsewhere.+//+// Suffix list narrowed vs. PR #214: we omit bare _TOKEN because legitimate+// non-credential vars use it (CSRF_TOKEN, GITHUB_TOKEN for tooling). The+// kManagedCredentialKeys allow-list is checked first so any key the user+// configured in Settings is preserved, regardless of suffix.+static void strip_unmanaged_credentials(QProcessEnvironment& env,+ const QStringList& managed) {+ static const QStringList kSuffixes = {+ "_API_KEY", "_SECRET", "_SECRET_KEY", "_ACCESS_TOKEN",+ "_AUTH_TOKEN", "_PASSWORD", "_PRIVATE_KEY",+ };+ const QStringList all_keys = env.keys();+ for (const QString& k : all_keys) {+ if (managed.contains(k))+ continue; // we just injected this one — keep it+ const QString upper = k.toUpper();+ for (const QString& sfx : kSuffixes) {+ if (upper.endsWith(sfx)) {+ env.remove(k);+ break;+ }+ }+ }+}+// Scripts that require NumPy 1.x environmentstatic const QStringList kNumpy1Scripts = {"vectorbt", "backtesting", "gluonts", "functime", "pyportfolioopt", "financepy", "ffn", "ffn_wrapper",@@ -86,6 +140,29 @@ QProcessEnvironment PythonRunner::build_python_env() const {existing_pypath.isEmpty() ? scripts_dir_ : (scripts_dir_ + kPathSep + existing_pypath);env.insert("PYTHONPATH", new_pypath);+ // Inject credentials stored via SettingsScreen → SecureStorage. SecureStorage+ // is the source of truth: any value found there overrides whatever the user's+ // shell happened to have. Without this, Python scripts like fred_data.py that+ // read os.environ.get("FRED_API_KEY") only worked when the user happened to+ // export the variable in their shell before launching the app.+ int injected = 0;+ for (const QString& key : kManagedCredentialKeys) {+ auto r = SecureStorage::instance().retrieve(key);+ if (r.is_ok() && !r.value().isEmpty()) {+ env.insert(key, r.value());+ ++injected;+ }+ }++ // Strip any other credential-shaped variable the user inherited from their+ // shell. The allow-list above is preserved; everything else matching the+ // sensitive suffixes is removed before the subprocess sees it.+ strip_unmanaged_credentials(env, kManagedCredentialKeys);++ if (injected > 0) {+ LOG_DEBUG("Python", QString("Injected %1 credentials from SecureStorage").arg(injected));+ }+return env;}@@ -349,22 +426,19 @@ void PythonRunner::start_next() {// FINAGENT_DATA_DIR, base PYTHONPATH = scripts_dir_).QProcessEnvironment env = build_python_env();- // Script-specific: if the script is inside a sub-package (contains '/'),- // prepend the parent-of-pkg dir so relative imports resolve.- if (!is_code && req.script.contains('/')) {-#ifdef _WIN32- const QChar kPathSep = ';';-#else- const QChar kPathSep = ':';-#endif- QString script_dir = QFileInfo(scripts_dir_ + "/" + req.script).dir().absolutePath();- QString parent_of_pkg = QFileInfo(script_dir).dir().absolutePath();- QString pypath = env.value("PYTHONPATH");- if (parent_of_pkg != scripts_dir_ && !pypath.contains(parent_of_pkg)) {- pypath = parent_of_pkg + kPathSep + pypath;- env.insert("PYTHONPATH", pypath);- }- }+ // NOTE: do NOT prepend parent-of-pkg (e.g. <scripts>/mcp) to PYTHONPATH+ // for sub-package scripts. scripts_dir_ is already on PYTHONPATH (see+ // build_python_env line 141), so `python -m mcp.edgar.main` resolves+ // both the package itself AND its relative imports correctly.+ //+ // Adding parent-of-pkg used to *shadow* third-party libraries: if a+ // local sub-package shares a name with a venv package (e.g. our+ // `<scripts>/mcp/edgar/` vs the `edgartools` PyPI library which+ // exports module `edgar`), Python's `from edgar import Company` would+ // resolve to the local empty package and fail with `ImportError:+ // cannot import name 'Company' from 'edgar'`. Removing this block+ // fixes the SEC EDGAR tools — and any other tool whose Python deps+ // share a top-level name with a local package.proc->setProcessEnvironment(env);proc->setWorkingDirectory(scripts_dir_);diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cppindex 22f7e9220..f21d88960 100644--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp@@ -28,6 +28,7 @@#include <QPlainTextEdit>#include <QProgressBar>#include <QScrollArea>+#include <QStackedWidget>#include <QTabWidget>#include <QTableWidget>#include <QTableWidgetItem>@@ -603,7 +604,7 @@ QWidget* QuantModulePanel::build_cfa_quant_panel() {vl->setContentsMargins(16, 16, 16, 16);vl->setSpacing(12);- // Data input+ // ── Section header ──────────────────────────────────────────────────────auto* data_lbl = new QLabel("DATA INPUT", w);data_lbl->setStyleSheet(QString("color:%1; font-weight:700; font-family:%2;""letter-spacing:1px;")@@ -611,30 +612,374 @@ QWidget* QuantModulePanel::build_cfa_quant_panel() {.arg(ui::fonts::DATA_FAMILY));vl->addWidget(data_lbl);+ // ── Symbol / data input ─────────────────────────────────────────────────auto* symbol = new QLineEdit(w);- symbol->setPlaceholderText("Ticker symbol (e.g. AAPL) or comma-separated values");+ symbol->setPlaceholderText("Ticker (AAPL, ^GSPC, BTC-USD) or comma-separated values");symbol->setStyleSheet(input_ss());+ symbol->setText("AAPL");text_inputs_["cfa_symbol"] = symbol;vl->addWidget(build_input_row("Symbol / Data", symbol, w));- // Analysis type selector+ // Period / interval / column for ticker fetches+ auto* period = new QComboBox(w);+ period->addItems({"1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "max"});+ period->setCurrentText("1y");+ period->setStyleSheet(combo_ss());+ combo_inputs_["cfa_period"] = period;+ vl->addWidget(build_input_row("Period (ticker only)", period, w));++ auto* interval = new QComboBox(w);+ interval->addItems({"1d", "1wk", "1mo"});+ interval->setStyleSheet(combo_ss());+ combo_inputs_["cfa_interval"] = interval;+ vl->addWidget(build_input_row("Interval (ticker only)", interval, w));++ // ── Analysis selector ───────────────────────────────────────────────────auto* analysis_type = new QComboBox(w);- analysis_type->addItems({"trend_analysis", "stationarity_test", "arima_model", "forecasting", "supervised_learning",- "unsupervised_learning", "resampling_methods", "validate_data"});+ const QStringList analyses = {+ "trend_analysis", "stationarity_test", "arima_model", "forecasting",+ "supervised_learning", "unsupervised_learning", "model_evaluation",+ "resampling_methods", "sampling_techniques", "central_limit_theorem",+ "sampling_error_analysis", "validate_data",+ };+ analysis_type->addItems(analyses);analysis_type->setStyleSheet(combo_ss());combo_inputs_["cfa_analysis"] = analysis_type;vl->addWidget(build_input_row("Analysis Type", analysis_type, w));+ // ── Per-analysis parameter stack ────────────────────────────────────────+ auto* params_lbl = new QLabel("ANALYSIS PARAMETERS", w);+ params_lbl->setStyleSheet(QString("color:%1; font-weight:700; font-family:%2;"+ "letter-spacing:1px; margin-top:8px;")+ .arg(module_.color.name())+ .arg(ui::fonts::DATA_FAMILY));+ vl->addWidget(params_lbl);++ auto* stack = new QStackedWidget(w);+ auto add_page = [&](std::initializer_list<QWidget*> rows) {+ auto* page = new QWidget(stack);+ auto* pv = new QVBoxLayout(page);+ pv->setContentsMargins(0, 0, 0, 0);+ pv->setSpacing(6);+ for (auto* r : rows)+ pv->addWidget(r);+ pv->addStretch();+ stack->addWidget(page);+ return page;+ };++ // 0: trend_analysis — trend_type+ {+ auto* t = new QComboBox(stack);+ t->addItems({"linear", "log_linear"});+ t->setStyleSheet(combo_ss());+ combo_inputs_["cfa_trend_type"] = t;+ add_page({build_input_row("Trend Type", t, stack)});+ }+ // 1: stationarity_test — test_type+ {+ auto* t = new QComboBox(stack);+ t->addItems({"adf", "kpss"});+ t->setStyleSheet(combo_ss());+ combo_inputs_["cfa_stationarity_test"] = t;+ add_page({build_input_row("Test Type", t, stack)});+ }+ // 2: arima_model — order p,d,q + optional seasonal+ {+ auto* p = new QSpinBox(stack);+ p->setRange(0, 10);+ p->setValue(1);+ p->setStyleSheet(spinbox_ss());+ int_inputs_["cfa_arima_p"] = p;+ auto* d = new QSpinBox(stack);+ d->setRange(0, 3);+ d->setValue(0);+ d->setStyleSheet(spinbox_ss());+ int_inputs_["cfa_arima_d"] = d;+ auto* q = new QSpinBox(stack);+ q->setRange(0, 10);+ q->setValue(1);+ q->setStyleSheet(spinbox_ss());+ int_inputs_["cfa_arima_q"] = q;+ add_page({+ build_input_row("AR order (p)", p, stack),+ build_input_row("Differencing (d)", d, stack),+ build_input_row("MA order (q)", q, stack),+ });+ }+ // 3: forecasting — horizon, method, train_size+ {+ auto* h = new QSpinBox(stack);+ h->setRange(1, 252);+ h->setValue(5);+ h->setStyleSheet(spinbox_ss());+ int_inputs_["cfa_forecast_horizon"] = h;+ auto* m = new QComboBox(stack);+ m->addItems({"simple_exponential", "holt", "holt_winters", "arima", "naive", "drift"});+ m->setStyleSheet(combo_ss());+ combo_inputs_["cfa_forecast_method"] = m;+ auto* ts = make_double_spin(0.5, 0.95, 0.8, 2, "", stack);+ double_inputs_["cfa_forecast_train_size"] = ts;+ add_page({+ build_input_row("Horizon (steps)", h, stack),+ build_input_row("Method", m, stack),+ build_input_row("Train Size", ts, stack),+ });+ }+ // 4: supervised_learning — n_lags, problem_type, algorithms+ {+ auto* lags = new QSpinBox(stack);+ lags->setRange(1, 50);+ lags->setValue(5);+ lags->setStyleSheet(spinbox_ss());+ int_inputs_["cfa_sup_lags"] = lags;+ auto* pt = new QComboBox(stack);+ pt->addItems({"regression", "classification"});+ pt->setStyleSheet(combo_ss());+ combo_inputs_["cfa_sup_problem"] = pt;+ auto* algos = new QLineEdit(stack);+ algos->setText("ridge,random_forest");+ algos->setPlaceholderText("comma-separated: ridge,lasso,random_forest,svr,knn");+ algos->setStyleSheet(input_ss());+ text_inputs_["cfa_sup_algorithms"] = algos;+ add_page({+ build_input_row("Lag features (n_lags)", lags, stack),+ build_input_row("Problem Type", pt, stack),+ build_input_row("Algorithms", algos, stack),+ });+ }+ // 5: unsupervised_learning — n_lags, methods+ {+ auto* lags = new QSpinBox(stack);+ lags->setRange(1, 50);+ lags->setValue(5);+ lags->setStyleSheet(spinbox_ss());+ int_inputs_["cfa_unsup_lags"] = lags;+ auto* methods = new QLineEdit(stack);+ methods->setText("pca,kmeans");+ methods->setPlaceholderText("comma-separated: pca,kmeans,agglomerative");+ methods->setStyleSheet(input_ss());+ text_inputs_["cfa_unsup_methods"] = methods;+ add_page({+ build_input_row("Lag features (n_lags)", lags, stack),+ build_input_row("Methods", methods, stack),+ });+ }+ // 6: model_evaluation — n_lags, model_type, cv_folds+ {+ auto* lags = new QSpinBox(stack);+ lags->setRange(1, 50);+ lags->setValue(5);+ lags->setStyleSheet(spinbox_ss());+ int_inputs_["cfa_eval_lags"] = lags;+ auto* mt = new QComboBox(stack);+ mt->addItems({"random_forest", "ridge", "lasso", "svr", "knn", "decision_tree"});+ mt->setStyleSheet(combo_ss());+ combo_inputs_["cfa_eval_model"] = mt;+ auto* cv = new QSpinBox(stack);+ cv->setRange(2, 20);+ cv->setValue(5);+ cv->setStyleSheet(spinbox_ss());+ int_inputs_["cfa_eval_cv"] = cv;+ add_page({+ build_input_row("Lag features (n_lags)", lags, stack),+ build_input_row("Model Type", mt, stack),+ build_input_row("CV Folds", cv, stack),+ });+ }+ // 7: resampling_methods — methods, n_resamples+ {+ auto* m = new QLineEdit(stack);+ m->setText("bootstrap,jackknife");+ m->setPlaceholderText("comma-separated: bootstrap,jackknife,permutation");+ m->setStyleSheet(input_ss());+ text_inputs_["cfa_resample_methods"] = m;+ auto* n = new QSpinBox(stack);+ n->setRange(50, 100000);+ n->setValue(1000);+ n->setStyleSheet(spinbox_ss());+ int_inputs_["cfa_resample_n"] = n;+ add_page({+ build_input_row("Methods", m, stack),+ build_input_row("Resamples", n, stack),+ });+ }+ // 8: sampling_techniques — sample_size, methods (population uses Symbol/Data)+ {+ auto* size = new QSpinBox(stack);+ size->setRange(10, 100000);+ size->setValue(100);+ size->setStyleSheet(spinbox_ss());+ int_inputs_["cfa_sampling_size"] = size;+ auto* m = new QLineEdit(stack);+ m->setText("simple,stratified,systematic");+ m->setStyleSheet(input_ss());+ text_inputs_["cfa_sampling_methods"] = m;+ add_page({+ build_input_row("Sample Size", size, stack),+ build_input_row("Methods", m, stack),+ });+ }+ // 9: central_limit_theorem — distribution, sample_sizes, n_samples+ {+ auto* dist = new QComboBox(stack);+ dist->addItems({"exponential", "uniform", "normal", "poisson", "binomial"});+ dist->setStyleSheet(combo_ss());+ combo_inputs_["cfa_clt_dist"] = dist;+ auto* sizes = new QLineEdit(stack);+ sizes->setText("5,10,30,100");+ sizes->setStyleSheet(input_ss());+ text_inputs_["cfa_clt_sizes"] = sizes;+ auto* n = new QSpinBox(stack);+ n->setRange(100, 100000);+ n->setValue(1000);+ n->setStyleSheet(spinbox_ss());+ int_inputs_["cfa_clt_n"] = n;+ add_page({+ build_input_row("Distribution", dist, stack),+ build_input_row("Sample Sizes", sizes, stack),+ build_input_row("Samples per size", n, stack),+ });+ }+ // 10: sampling_error_analysis — pop_mean, pop_std, sample_sizes, conf, n_sims+ {+ auto* mean = make_double_spin(-1e6, 1e6, 0.0, 4, "", stack);+ double_inputs_["cfa_serr_mean"] = mean;+ auto* sd = make_double_spin(0.0001, 1e6, 1.0, 4, "", stack);+ double_inputs_["cfa_serr_std"] = sd;+ auto* sizes = new QLineEdit(stack);+ sizes->setText("10,30,50,100,500");+ sizes->setStyleSheet(input_ss());+ text_inputs_["cfa_serr_sizes"] = sizes;+ auto* conf = make_double_spin(0.5, 0.999, 0.95, 3, "", stack);+ double_inputs_["cfa_serr_conf"] = conf;+ auto* sims = new QSpinBox(stack);+ sims->setRange(100, 100000);+ sims->setValue(1000);+ sims->setStyleSheet(spinbox_ss());+ int_inputs_["cfa_serr_sims"] = sims;+ add_page({+ build_input_row("Population Mean", mean, stack),+ build_input_row("Population Std", sd, stack),+ build_input_row("Sample Sizes", sizes, stack),+ build_input_row("Confidence Level", conf, stack),+ build_input_row("Simulations", sims, stack),+ });+ }+ // 11: validate_data — data_type, data_name+ {+ auto* dt = new QComboBox(stack);+ dt->addItems({"general", "returns", "prices", "rates"});+ dt->setStyleSheet(combo_ss());+ combo_inputs_["cfa_validate_type"] = dt;+ auto* dn = new QLineEdit(stack);+ dn->setText("data");+ dn->setStyleSheet(input_ss());+ text_inputs_["cfa_validate_name"] = dn;+ add_page({+ build_input_row("Data Type", dt, stack),+ build_input_row("Data Name", dn, stack),+ });+ }++ vl->addWidget(stack);++ // Switch stack page when analysis combo changes+ connect(analysis_type, qOverload<int>(&QComboBox::currentIndexChanged), stack,+ &QStackedWidget::setCurrentIndex);++ // ── Run button ──────────────────────────────────────────────────────────auto* run = make_run_button("RUN ANALYSIS", w);connect(run, &QPushButton::clicked, this, [this]() {status_label_->setText("Running...");+ const QString cmd = combo_inputs_["cfa_analysis"]->currentText();+ const QString raw = text_inputs_["cfa_symbol"]->text().trimmed();+QJsonObject params;- params["data"] = text_inputs_["cfa_symbol"]->text();- auto cmd = combo_inputs_["cfa_analysis"]->currentText();+ params["period"] = combo_inputs_["cfa_period"]->currentText();+ params["interval"] = combo_inputs_["cfa_interval"]->currentText();++ // Sample-error analysis is the only command that doesn't read from "data".+ // Everything else reads from "data" (or "population" for sampling_techniques).+ const bool needs_data = (cmd != "sampling_error_analysis" &&+ cmd != "central_limit_theorem");+ if (needs_data && raw.isEmpty()) {+ display_error("Please enter a ticker symbol or comma-separated values");+ status_label_->setText("Error");+ return;+ }+ if (cmd == "sampling_techniques")+ params["population"] = raw;+ else if (needs_data)+ params["data"] = raw;++ auto split_csv = [](const QString& s) {+ QJsonArray arr;+ for (const auto& part : s.split(',', Qt::SkipEmptyParts))+ arr.append(part.trimmed());+ return arr;+ };+ auto split_csv_int = [](const QString& s) {+ QJsonArray arr;+ for (const auto& part : s.split(',', Qt::SkipEmptyParts)) {+ bool ok = false;+ int v = part.trimmed().toInt(&ok);+ if (ok) arr.append(v);+ }+ return arr;+ };++ if (cmd == "trend_analysis") {+ params["trend_type"] = combo_inputs_["cfa_trend_type"]->currentText();+ } else if (cmd == "stationarity_test") {+ params["test_type"] = combo_inputs_["cfa_stationarity_test"]->currentText();+ } else if (cmd == "arima_model") {+ QJsonArray order;+ order.append(int_inputs_["cfa_arima_p"]->value());+ order.append(int_inputs_["cfa_arima_d"]->value());+ order.append(int_inputs_["cfa_arima_q"]->value());+ params["order"] = order;+ } else if (cmd == "forecasting") {+ params["horizon"] = int_inputs_["cfa_forecast_horizon"]->value();+ params["method"] = combo_inputs_["cfa_forecast_method"]->currentText();+ params["train_size"] = double_inputs_["cfa_forecast_train_size"]->value();+ } else if (cmd == "supervised_learning") {+ params["n_lags"] = int_inputs_["cfa_sup_lags"]->value();+ params["problem_type"] = combo_inputs_["cfa_sup_problem"]->currentText();+ params["algorithms"] = split_csv(text_inputs_["cfa_sup_algorithms"]->text());+ } else if (cmd == "unsupervised_learning") {+ params["n_lags"] = int_inputs_["cfa_unsup_lags"]->value();+ params["methods"] = split_csv(text_inputs_["cfa_unsup_methods"]->text());+ } else if (cmd == "model_evaluation") {+ params["n_lags"] = int_inputs_["cfa_eval_lags"]->value();+ params["model_type"] = combo_inputs_["cfa_eval_model"]->currentText();+ params["cv_folds"] = int_inputs_["cfa_eval_cv"]->value();+ } else if (cmd == "resampling_methods") {+ params["methods"] = split_csv(text_inputs_["cfa_resample_methods"]->text());+ params["n_resamples"] = int_inputs_["cfa_resample_n"]->value();+ } else if (cmd == "sampling_techniques") {+ params["sample_size"] = int_inputs_["cfa_sampling_size"]->value();+ params["sampling_methods"] = split_csv(text_inputs_["cfa_sampling_methods"]->text());+ } else if (cmd == "central_limit_theorem") {+ params["population_dist"] = combo_inputs_["cfa_clt_dist"]->currentText();+ params["sample_sizes"] = split_csv_int(text_inputs_["cfa_clt_sizes"]->text());+ params["n_samples"] = int_inputs_["cfa_clt_n"]->value();+ } else if (cmd == "sampling_error_analysis") {+ params["population_mean"] = double_inputs_["cfa_serr_mean"]->value();+ params["population_std"] = double_inputs_["cfa_serr_std"]->value();+ params["sample_sizes"] = split_csv_int(text_inputs_["cfa_serr_sizes"]->text());+ params["confidence_level"] = double_inputs_["cfa_serr_conf"]->value();+ params["n_simulations"] = int_inputs_["cfa_serr_sims"]->value();+ } else if (cmd == "validate_data") {+ params["data_type"] = combo_inputs_["cfa_validate_type"]->currentText();+ params["data_name"] = text_inputs_["cfa_validate_name"]->text();+ }+AIQuantLabService::instance().run_module("cfa_quant", cmd, params);});vl->addWidget(run);+ // ── Results container ───────────────────────────────────────────────────auto* rc = new QWidget(w);results_layout_ = new QVBoxLayout(rc);results_layout_->setContentsMargins(0, 8, 0, 0);@@ -1892,6 +2237,193 @@ void QuantModulePanel::display_backtest_result(const QJsonObject& payload) {.arg(sharpe, 0, 'f', 3));}+// ── CFA Quant Result Display ───────────────────────────────────────────────+//+// CFA Python returns a uniform shape:+// { success, analysis_type,+// result: { value, method, parameters, metadata, calculation_time, timestamp, calculator } }+//+// validate_data is the exception: result is a DataQualityReport.to_dict() with+// quality_score, issues, warnings, statistics, recommendations.+//+// We render flat scalars in result.value + result.metadata as a metrics table,+// surface the analysis method/calc-time as a header line, and keep the raw JSON+// + export button for inspection.++static void cfa_flatten_scalars(const QJsonObject& obj, const QString& prefix, QStringList& keys,+ QHash<QString, QJsonValue>& out) {+ for (auto it = obj.begin(); it != obj.end(); ++it) {+ const auto& v = it.value();+ const QString key = prefix.isEmpty() ? it.key() : prefix + "." + it.key();+ if (v.isObject()) {+ // Recurse one level deep so nested {slope, intercept} flattens nicely;+ // skip very deep / array-heavy fields (parameters.data, fitted_values).+ if (key.endsWith(".data") || key.endsWith(".fitted_values") ||+ key.endsWith(".residuals") || key.endsWith(".model_summary"))+ continue;+ cfa_flatten_scalars(v.toObject(), key, keys, out);+ } else if (!v.isArray()) {+ keys.append(key);+ out.insert(key, v);+ }+ }+}++void QuantModulePanel::display_cfa_result(const QString& command, const QJsonObject& payload) {+ clear_results();++ if (!payload.value("success").toBool()) {+ display_error(payload.value("error").toString("Unknown error"));+ return;+ }++ const QJsonObject result = payload.value("result").toObject();+ const QString method = result.value("method").toString();+ const double calc_time = result.value("calculation_time").toDouble();+ const QString analysis_type = payload.value("analysis_type").toString(command);++ // ── Header ──────────────────────────────────────────────────────────────+ auto* header = new QLabel(QString("%1 • %2 • %3 ms")+ .arg(analysis_type.toUpper())+ .arg(method)+ .arg(QString::number(calc_time * 1000.0, 'f', 1)));+ header->setStyleSheet(QString("color:%1; font-weight:700; font-family:%2; letter-spacing:1px;")+ .arg(module_.color.name())+ .arg(ui::fonts::DATA_FAMILY));+ results_layout_->addWidget(header);++ // ── validate_data has its own report shape ──────────────────────────────+ if (command == "validate_data") {+ const double score = result.value("quality_score").toDouble();+ auto* score_lbl = new QLabel(QString("Quality Score: %1 / 100").arg(score, 0, 'f', 1));+ score_lbl->setStyleSheet(QString("color:%1; font-size:16px; font-weight:700;")+ .arg(score >= 80 ? ui::colors::POSITIVE()+ : score >= 50 ? ui::colors::WARNING()+ : ui::colors::NEGATIVE()));+ results_layout_->addWidget(score_lbl);++ const auto issues = result.value("issues").toArray();+ const auto warnings = result.value("warnings").toArray();+ const auto recs = result.value("recommendations").toArray();++ auto add_section = [this](const QString& title, const QJsonArray& items, bool issue_shape) {+ if (items.isEmpty())+ return;+ auto* lbl = new QLabel(QString("%1 (%2)").arg(title).arg(items.size()));+ lbl->setStyleSheet(QString("color:%1; font-weight:700; margin-top:6px;")+ .arg(ui::colors::TEXT_PRIMARY()));+ results_layout_->addWidget(lbl);+ for (const auto& v : items) {+ QString text;+ if (issue_shape) {+ auto o = v.toObject();+ text = QString("[%1] %2: %3")+ .arg(o.value("severity").toString(),+ o.value("type").toString(),+ o.value("description").toString(o.value("message").toString()));+ } else {+ text = "• " + v.toString();+ }+ auto* item = new QLabel(text);+ item->setWordWrap(true);+ item->setStyleSheet(QString("color:%1; padding:2px 0;").arg(ui::colors::TEXT_SECONDARY()));+ results_layout_->addWidget(item);+ }+ };+ add_section("Issues", issues, true);+ add_section("Warnings", warnings, true);+ add_section("Recommendations", recs, false);+ } else {+ // ── Standard analyses: flatten value + metadata into a metrics table ──+ QStringList keys;+ QHash<QString, QJsonValue> kv;+ const QJsonObject value_obj = result.value("value").toObject();+ const QJsonObject meta_obj = result.value("metadata").toObject();++ // value can also be a scalar (e.g. forecasting → array, but value can be number)+ const QJsonValue value_raw = result.value("value");+ if (value_obj.isEmpty() && !value_raw.isNull() && !value_raw.isObject() && !value_raw.isArray()) {+ keys.append("value");+ kv.insert("value", value_raw);+ } else {+ cfa_flatten_scalars(value_obj, "value", keys, kv);+ }+ cfa_flatten_scalars(meta_obj, "metadata", keys, kv);++ if (!keys.isEmpty()) {+ auto* table = new QTableWidget(keys.size(), 2);+ table->setHorizontalHeaderLabels({"Metric", "Value"});+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);+ table->setAlternatingRowColors(true);+ table->horizontalHeader()->setStretchLastSection(true);+ table->verticalHeader()->setVisible(false);+ table->setMaximumHeight(qMin(keys.size() * 28 + 32, 480));+ table->setStyleSheet(table_ss());+ for (int r = 0; r < keys.size(); ++r) {+ QString label = keys[r];+ label.replace('_', ' ');+ table->setItem(r, 0, new QTableWidgetItem(label.toUpper()));+ auto* vi = new QTableWidgetItem(format_val(kv.value(keys[r])));+ vi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ table->setItem(r, 1, vi);+ }+ table->resizeColumnsToContents();+ results_layout_->addWidget(table);+ }++ // For forecasting the value is an array of forecast values — show inline+ if (value_raw.isArray()) {+ const auto arr = value_raw.toArray();+ QStringList parts;+ parts.reserve(arr.size());+ for (const auto& v : arr)+ parts << QString::number(v.toDouble(), 'f', 4);+ auto* fcst = new QLabel(QString("Forecast (%1 steps): %2").arg(arr.size()).arg(parts.join(", ")));+ fcst->setWordWrap(true);+ fcst->setStyleSheet(QString("color:%1; padding:6px 0;").arg(ui::colors::TEXT_PRIMARY()));+ results_layout_->addWidget(fcst);+ }+ }++ // ── Raw JSON viewer ─────────────────────────────────────────────────────+ auto* raw = new QTextEdit;+ raw->setReadOnly(true);+ raw->setMaximumHeight(220);+ raw->setPlainText(QJsonDocument(payload).toJson(QJsonDocument::Indented));+ raw->setStyleSheet(output_ss());+ results_layout_->addWidget(raw);++ // ── Export button ───────────────────────────────────────────────────────+ auto* export_btn = new QPushButton("EXPORT RESULTS");+ export_btn->setCursor(Qt::PointingHandCursor);+ export_btn->setFixedHeight(28);+ export_btn->setStyleSheet(QString("QPushButton { background:transparent; color:%1; border:1px solid %2; "+ "font-size:%3px; font-family:%4; padding:0 12px; }"+ "QPushButton:hover { color:%1; background:rgba(255,255,255,0.05); }")+ .arg(module_.color.name(), ui::colors::BORDER_DIM())+ .arg(ui::fonts::SMALL)+ .arg(ui::fonts::DATA_FAMILY));+ const QString json_str = QJsonDocument(payload).toJson(QJsonDocument::Indented);+ connect(export_btn, &QPushButton::clicked, this, [this, json_str, command]() {+ QString safe_name = module_.label + "_" + command;+ safe_name.replace(QRegularExpression("[^a-zA-Z0-9_\\-]"), "_");+ const QString stored_name = safe_name + "_" + QString::number(QDateTime::currentMSecsSinceEpoch()) + ".json";+ const QString dest = services::FileManagerService::instance().storage_dir() + "/" + stored_name;+ QFile f(dest);+ if (f.open(QIODevice::WriteOnly | QIODevice::Text)) {+ f.write(json_str.toUtf8());+ f.close();+ services::FileManagerService::instance().register_file(stored_name, module_.label + "_" + command + ".json",+ QFileInfo(dest).size(), "application/json",+ "ai_quant_lab");+ LOG_INFO("AIQuantLab", "Exported result: " + stored_name);+ }+ });+ results_layout_->addWidget(export_btn);++ status_label_->setText("Done");+}+void QuantModulePanel::display_result(const QJsonObject& payload) {clear_results();@@ -1983,6 +2515,12 @@ void QuantModulePanel::on_result(const QString& module_id, const QString& commanrl_progress_bar_->setValue(100);}+ // ── CFA Quant: uniform result shape across all analyses ──────────────────+ if (module_id == "cfa_quant") {+ display_cfa_result(command, payload);+ return;+ }+// ── LangGraph deep analysis result ───────────────────────────────────────if (command == "execute_task") {if (!payload["success"].toBool()) {diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.h b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.hindex 26156c825..7f9aa2717 100644--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.h+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.h@@ -66,6 +66,7 @@ class QuantModulePanel : public QWidget {QJsonObject llm_config_from_combo(QComboBox* combo) const;void display_result(const QJsonObject& data);void display_backtest_result(const QJsonObject& data);+ void display_cfa_result(const QString& command, const QJsonObject& data);void display_error(const QString& msg);void clear_results();diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp b/fincept-qt/src/screens/backtesting/BacktestingScreen.cppindex a2a7c0d80..0d6d8ad52 100644--- a/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp@@ -3,6 +3,8 @@#include "core/logging/Logger.h"#include "core/session/ScreenStateManager.h"+#include "core/symbol/SymbolContext.h"+#include "core/symbol/SymbolRef.h"#include "services/backtesting/BacktestingService.h"#include "services/file_manager/FileManagerService.h"#include "ui/theme/Theme.h"@@ -543,6 +545,9 @@ QWidget* BacktestingScreen::build_right_panel() {symbols_edit_->setPlaceholderText("SPY,AAPL,MSFT");symbols_edit_->setStyleSheet(input_style);vl->addWidget(symbols_edit_);+ // Publish the first symbol to the linked group when the user finishes editing.+ connect(symbols_edit_, &QLineEdit::editingFinished, this,+ [this]() { publish_first_symbol_to_group(); });auto* cap_lbl = new QLabel("INITIAL CAPITAL ($)", content);cap_lbl->setStyleSheet(label_style);@@ -1590,4 +1595,39 @@ void BacktestingScreen::restore_state(const QVariantMap& state) {on_command_changed(cmd);}+// ── IGroupLinked ─────────────────────────────────────────────────────────────++SymbolRef BacktestingScreen::current_symbol() const {+ if (!symbols_edit_)+ return {};+ const QString text = symbols_edit_->text().trimmed();+ if (text.isEmpty())+ return {};+ // First comma-separated token is the "active" symbol for group linking.+ const QString first = text.section(',', 0, 0).trimmed();+ if (first.isEmpty())+ return {};+ return SymbolRef::equity(first);+}++void BacktestingScreen::on_group_symbol_changed(const SymbolRef& ref) {+ if (!ref.is_valid() || !symbols_edit_)+ return;+ // Replace the entire field — adding to a comma list silently would+ // surprise users who have a multi-symbol backtest configured.+ if (symbols_edit_->text().trimmed() == ref.symbol)+ return;+ QSignalBlocker block(symbols_edit_); // avoid bouncing the publish back+ symbols_edit_->setText(ref.symbol);+}++void BacktestingScreen::publish_first_symbol_to_group() {+ if (link_group_ == SymbolGroup::None)+ return;+ const SymbolRef ref = current_symbol();+ if (!ref.is_valid())+ return;+ SymbolContext::instance().set_group_symbol(link_group_, ref, this);+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen.h b/fincept-qt/src/screens/backtesting/BacktestingScreen.hindex 692afb0ea..b50ae8f66 100644--- a/fincept-qt/src/screens/backtesting/BacktestingScreen.h+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen.h@@ -1,5 +1,6 @@// src/screens/backtesting/BacktestingScreen.h#pragma once+#include "core/symbol/IGroupLinked.h"#include "screens/IStatefulScreen.h"#include "services/backtesting/BacktestingTypes.h"@@ -25,8 +26,9 @@namespace fincept::screens {/// Multi-provider backtesting terminal with 6 providers, 9 commands, 50+ strategies.-class BacktestingScreen : public QWidget, public IStatefulScreen {+class BacktestingScreen : public QWidget, public IStatefulScreen, public IGroupLinked {Q_OBJECT+ Q_INTERFACES(fincept::IGroupLinked)public:explicit BacktestingScreen(QWidget* parent = nullptr);@@ -35,6 +37,15 @@ class BacktestingScreen : public QWidget, public IStatefulScreen {QString state_key() const override { return "backtesting"; }int state_version() const override { return 1; }+ // IGroupLinked — backtest is multi-symbol, but the *first* symbol in the+ // line edit acts as the active ticker for group linking. Receiving a+ // group symbol overwrites the entire field with that one symbol; users+ // who want a multi-symbol backtest add more after publishing.+ void set_group(SymbolGroup g) override { link_group_ = g; }+ SymbolGroup group() const override { return link_group_; }+ void on_group_symbol_changed(const SymbolRef& ref) override;+ SymbolRef current_symbol() const override;+protected:void showEvent(QShowEvent* event) override;void hideEvent(QHideEvent* event) override;@@ -140,6 +151,10 @@ class BacktestingScreen : public QWidget, public IStatefulScreen {bool first_show_ = true;bool is_running_ = false;++ // Symbol-group link (None when unlinked).+ SymbolGroup link_group_ = SymbolGroup::None;+ void publish_first_symbol_to_group();};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/CryptoCenterScreen.cpp b/fincept-qt/src/screens/crypto_center/CryptoCenterScreen.cppnew file mode 100644index 000000000..9911bb25e--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/CryptoCenterScreen.cpp@@ -0,0 +1,327 @@+#include "screens/crypto_center/CryptoCenterScreen.h"++#include "core/logging/Logger.h"+#include "screens/crypto_center/HoldingsBar.h"+#include "screens/crypto_center/tabs/ActivityTab.h"+#include "screens/crypto_center/tabs/ComingSoonTab.h"+#include "screens/crypto_center/tabs/HomeTab.h"+#include "screens/crypto_center/tabs/SettingsTab.h"+#include "screens/crypto_center/tabs/TradeTab.h"+#include "services/wallet/WalletService.h"+#include "ui/theme/Theme.h"++#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QPushButton>+#include <QStackedWidget>+#include <QStyle>+#include <QTabWidget>+#include <QVBoxLayout>++namespace fincept::screens {++namespace {++QString cc_font_stack() {+ return QStringLiteral(+ "'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");+}++} // namespace++CryptoCenterScreen::CryptoCenterScreen(QWidget* parent) : QWidget(parent) {+ setObjectName(QStringLiteral("cryptoCenterScreen"));+ build_ui();++ auto& svc = fincept::wallet::WalletService::instance();+ connect(&svc, &fincept::wallet::WalletService::wallet_connected, this,+ &CryptoCenterScreen::on_wallet_connected);+ connect(&svc, &fincept::wallet::WalletService::wallet_disconnected, this,+ &CryptoCenterScreen::on_wallet_disconnected);++ apply_theme();++ if (svc.is_connected()) {+ on_wallet_connected(svc.current_pubkey(), svc.state().label);+ } else {+ stack_->setCurrentWidget(empty_page_);+ }+}++CryptoCenterScreen::~CryptoCenterScreen() = default;++// ── Layout ─────────────────────────────────────────────────────────────────++void CryptoCenterScreen::build_ui() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // Header bar+ header_ = new QWidget(this);+ header_->setObjectName(QStringLiteral("cryptoCenterHeader"));+ header_->setFixedHeight(40);+ auto* hl = new QHBoxLayout(header_);+ hl->setContentsMargins(14, 0, 14, 0);+ hl->setSpacing(8);++ header_brand_ = new QLabel(QStringLiteral("FINCEPT"));+ header_brand_->setObjectName(QStringLiteral("cryptoCenterBrand"));+ header_separator_ = new QLabel(QStringLiteral("/"));+ header_separator_->setObjectName(QStringLiteral("cryptoCenterSep"));+ header_route_ = new QLabel(QStringLiteral("CRYPTO CENTER"));+ header_route_->setObjectName(QStringLiteral("cryptoCenterRoute"));+ header_status_ = new QLabel(QStringLiteral("● DISCONNECTED"));+ header_status_->setObjectName(QStringLiteral("cryptoCenterHeaderStatusOff"));++ hl->addWidget(header_brand_);+ hl->addWidget(header_separator_);+ hl->addWidget(header_route_);+ hl->addStretch();+ hl->addWidget(header_status_);+ root->addWidget(header_);++ stack_ = new QStackedWidget(this);+ stack_->setObjectName(QStringLiteral("cryptoCenterBody"));+ root->addWidget(stack_, 1);++ build_empty_page();+ build_connected_page();+}++void CryptoCenterScreen::build_empty_page() {+ empty_page_ = new QWidget(stack_);+ auto* layout = new QVBoxLayout(empty_page_);+ layout->setContentsMargins(14, 14, 14, 14);+ layout->setSpacing(0);+ layout->addStretch(1);++ auto* center_row = new QHBoxLayout;+ center_row->setSpacing(0);+ center_row->addStretch(1);++ empty_panel_ = new QFrame(empty_page_);+ empty_panel_->setObjectName(QStringLiteral("cryptoCenterEmptyPanel"));+ empty_panel_->setFixedWidth(520);+ auto* panel_l = new QVBoxLayout(empty_panel_);+ panel_l->setContentsMargins(0, 0, 0, 0);+ panel_l->setSpacing(0);++ auto* head = new QWidget(empty_panel_);+ head->setObjectName(QStringLiteral("cryptoCenterPanelHead"));+ head->setFixedHeight(34);+ auto* head_l = new QHBoxLayout(head);+ head_l->setContentsMargins(12, 0, 12, 0);+ head_l->setSpacing(0);+ auto* head_title = new QLabel(QStringLiteral("CONNECT WALLET"), head);+ head_title->setObjectName(QStringLiteral("cryptoCenterPanelTitle"));+ head_l->addWidget(head_title);+ head_l->addStretch();+ auto* head_status = new QLabel(QStringLiteral("READY"), head);+ head_status->setObjectName(QStringLiteral("cryptoCenterPanelStatus"));+ head_l->addWidget(head_status);+ panel_l->addWidget(head);++ auto* body = new QWidget(empty_panel_);+ auto* body_l = new QVBoxLayout(body);+ body_l->setContentsMargins(20, 18, 20, 20);+ body_l->setSpacing(10);++ empty_title_ = new QLabel(tr("No wallet connected"), body);+ empty_title_->setObjectName(QStringLiteral("cryptoCenterEmptyTitle"));+ body_l->addWidget(empty_title_);++ empty_lede_ = new QLabel(+ tr("Connect a Solana wallet to view your $FNCPT balance, SOL holdings, "+ "and live USD valuation. Your private keys never leave your wallet."),+ body);+ empty_lede_->setObjectName(QStringLiteral("cryptoCenterEmptyLede"));+ empty_lede_->setWordWrap(true);+ body_l->addWidget(empty_lede_);++ body_l->addSpacing(4);++ empty_security_label_ = new QLabel(QStringLiteral("SECURITY"), body);+ empty_security_label_->setObjectName(QStringLiteral("cryptoCenterCaptionAccent"));+ body_l->addWidget(empty_security_label_);++ empty_security_text_ = new QLabel(+ tr("· public address read-only\n"+ "· no private keys, no seed phrases\n"+ "· local handshake on 127.0.0.1, single-use token\n"+ "· cryptographic signature challenge before connect"),+ body);+ empty_security_text_->setObjectName(QStringLiteral("cryptoCenterSecurityText"));+ body_l->addWidget(empty_security_text_);++ body_l->addSpacing(6);++ connect_button_ = new QPushButton(tr("CONNECT WALLET"), body);+ connect_button_->setObjectName(QStringLiteral("cryptoCenterPrimaryButton"));+ connect_button_->setFixedHeight(28);+ connect_button_->setCursor(Qt::PointingHandCursor);+ body_l->addWidget(connect_button_);++ panel_l->addWidget(body);+ center_row->addWidget(empty_panel_);+ center_row->addStretch(1);+ layout->addLayout(center_row);+ layout->addStretch(2);++ connect(connect_button_, &QPushButton::clicked, this, [this]() {+ fincept::wallet::WalletService::instance().connect_with_dialog(this);+ });++ stack_->addWidget(empty_page_);+}++void CryptoCenterScreen::build_connected_page() {+ connected_page_ = new QWidget(stack_);+ connected_page_->setObjectName(QStringLiteral("cryptoCenterConnectedPage"));+ auto* root = new QVBoxLayout(connected_page_);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ holdings_bar_ = new HoldingsBar(connected_page_);+ root->addWidget(holdings_bar_);++ tab_widget_ = new QTabWidget(connected_page_);+ tab_widget_->setObjectName(QStringLiteral("cryptoCenterTabs"));+ tab_widget_->setDocumentMode(true);+ tab_widget_->setTabPosition(QTabWidget::North);+ tab_widget_->tabBar()->setExpanding(false);++ home_tab_ = new HomeTab(tab_widget_);+ trade_tab_ = new TradeTab(tab_widget_);+ activity_tab_ = new ActivityTab(tab_widget_);+ settings_tab_ = new SettingsTab(tab_widget_);++ stake_tab_ = new ComingSoonTab(+ QStringLiteral("STAKE"),+ QStringLiteral("PHASE 3"),+ tr("veFNCPT lock for 3 months – 4 years. Real-yield share of terminal "+ "revenue and tier badges (bronze / silver / gold) gating premium "+ "features across the terminal."),+ tab_widget_);+ markets_tab_ = new ComingSoonTab(+ QStringLiteral("MARKETS"),+ QStringLiteral("PHASE 4"),+ tr("Internal prediction markets settling in $FNCPT — Fed rate moves, "+ "CPI prints, S&P close, weather, crypto milestones. YES / NO order "+ "book with on-chain settlement."),+ tab_widget_);+ roadmap_tab_ = new ComingSoonTab(+ QStringLiteral("ROADMAP"),+ QStringLiteral("PHASE 5"),+ tr("Buyback & burn dashboard — live epoch buyback, cumulative burn, "+ "supply chart, and treasury runway. Replaces the static roadmap "+ "panel on HOME once Phase 5 ships."),+ tab_widget_);++ tab_widget_->addTab(home_tab_, tr("HOME"));+ tab_widget_->addTab(trade_tab_, tr("TRADE"));+ tab_widget_->addTab(activity_tab_, tr("ACTIVITY"));+ tab_widget_->addTab(settings_tab_, tr("SETTINGS"));+ tab_widget_->addTab(stake_tab_, tr("STAKE"));+ tab_widget_->addTab(markets_tab_, tr("MARKETS"));+ tab_widget_->addTab(roadmap_tab_, tr("ROADMAP"));++ root->addWidget(tab_widget_, 1);+ stack_->addWidget(connected_page_);+}++// ── Theme ──────────────────────────────────────────────────────────────────++void CryptoCenterScreen::apply_theme() {+ using namespace ui::colors;+ const QString font = cc_font_stack();++ const QString ss = QStringLiteral(+ // Root+ "QWidget#cryptoCenterScreen { background:%1; }"+ "QStackedWidget#cryptoCenterBody { background:%1; }"+ "QWidget#cryptoCenterConnectedPage { background:%1; }"++ // Header bar+ "QWidget#cryptoCenterHeader { background:%2; border-bottom:1px solid %3; }"+ "QLabel#cryptoCenterBrand { color:%4; font-family:%5; font-size:11px;"+ " font-weight:700; letter-spacing:1.5px; background:transparent; }"+ "QLabel#cryptoCenterSep { color:%6; font-family:%5; font-size:11px;"+ " background:transparent; }"+ "QLabel#cryptoCenterRoute { color:%7; font-family:%5; font-size:11px;"+ " font-weight:600; letter-spacing:1.2px; background:transparent; }"+ "QLabel#cryptoCenterHeaderStatusOff { color:%8; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QLabel#cryptoCenterHeaderStatusOn { color:%9; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"++ // Empty-state panel+ "QFrame#cryptoCenterEmptyPanel { background:%2; border:1px solid %3; }"+ "QWidget#cryptoCenterPanelHead { background:%10; border-bottom:1px solid %3; }"+ "QLabel#cryptoCenterPanelTitle { color:%4; font-family:%5; font-size:11px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QLabel#cryptoCenterPanelStatus { color:%8; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QLabel#cryptoCenterEmptyTitle { color:%7; font-family:%5; font-size:14px;"+ " font-weight:600; background:transparent; }"+ "QLabel#cryptoCenterEmptyLede { color:%11; font-family:%5; font-size:12px;"+ " background:transparent; }"+ "QLabel#cryptoCenterCaptionAccent { color:%4; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.5px; background:transparent; }"+ "QLabel#cryptoCenterSecurityText { color:%11; font-family:%5; font-size:11px;"+ " background:transparent; }"++ // Primary connect button+ "QPushButton#cryptoCenterPrimaryButton { background:rgba(217,119,6,0.10); color:%4;"+ " border:1px solid %12; font-family:%5; font-size:12px; font-weight:700;"+ " letter-spacing:1.5px; padding:0 16px; }"+ "QPushButton#cryptoCenterPrimaryButton:hover { background:%4; color:%1; }"++ // Tab bar — Bloomberg-flat with object-name styling (Phase 1.5 §1.5.3)+ "QTabWidget#cryptoCenterTabs::pane { background:%1; border:none;"+ " border-top:1px solid %3; }"+ "QTabWidget#cryptoCenterTabs QTabBar::tab { background:%2; color:%8;"+ " font-family:%5; font-size:10px; font-weight:700; letter-spacing:1.4px;"+ " padding:8px 14px; border-right:1px solid %3; }"+ "QTabWidget#cryptoCenterTabs QTabBar::tab:hover { background:%10; color:%7; }"+ "QTabWidget#cryptoCenterTabs QTabBar::tab:selected { background:%1; color:%4;"+ " border-bottom:2px solid %4; }"+ "QTabWidget#cryptoCenterTabs QTabBar { background:%2; border-bottom:1px solid %3; }"+ )+ .arg(BG_BASE(), // %1+ BG_SURFACE(), // %2+ BORDER_DIM(), // %3+ AMBER(), // %4+ font, // %5+ BORDER_BRIGHT(), // %6+ TEXT_PRIMARY(), // %7+ TEXT_TERTIARY(), // %8+ POSITIVE()) // %9+ .arg(BG_RAISED(), // %10+ TEXT_SECONDARY(), // %11+ QStringLiteral("#78350f")); // %12 darker amber++ setStyleSheet(ss);+}++// ── State handlers ─────────────────────────────────────────────────────────++void CryptoCenterScreen::on_wallet_connected(const QString& /*pubkey*/,+ const QString& /*label*/) {+ header_status_->setText(QStringLiteral("● CONNECTED"));+ header_status_->setObjectName(QStringLiteral("cryptoCenterHeaderStatusOn"));+ header_status_->style()->unpolish(header_status_);+ header_status_->style()->polish(header_status_);+ stack_->setCurrentWidget(connected_page_);+}++void CryptoCenterScreen::on_wallet_disconnected() {+ header_status_->setText(QStringLiteral("● DISCONNECTED"));+ header_status_->setObjectName(QStringLiteral("cryptoCenterHeaderStatusOff"));+ header_status_->style()->unpolish(header_status_);+ header_status_->style()->polish(header_status_);+ stack_->setCurrentWidget(empty_page_);+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/CryptoCenterScreen.h b/fincept-qt/src/screens/crypto_center/CryptoCenterScreen.hnew file mode 100644index 000000000..372603ce4--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/CryptoCenterScreen.h@@ -0,0 +1,83 @@+#pragma once++#include <QString>+#include <QWidget>++class QFrame;+class QHideEvent;+class QLabel;+class QPushButton;+class QShowEvent;+class QStackedWidget;+class QTabWidget;++namespace fincept::screens {++class ActivityTab;+class HoldingsBar;+class HomeTab;+class TradeTab;+class SettingsTab;+class ComingSoonTab;++/// Crypto Center — Obsidian-themed wallet hub.+///+/// Phase 2 layout: persistent HoldingsBar above a QTabWidget. Tabs:+/// HOME (Phase 1 panels)+/// TRADE (Stage 2.2)+/// ACTIVITY (Stage 2.4)+/// SETTINGS (mode toggle + Helius key + slippage)+/// STAKE / MARKETS / ROADMAP — placeholders shown via ComingSoonTab.+///+/// The screen itself owns no data subscriptions — those live in HoldingsBar+/// and the individual tabs. CryptoCenterScreen orchestrates the connect /+/// disconnect navigation between the empty page and the connected page only.+class CryptoCenterScreen : public QWidget {+ Q_OBJECT+ public:+ explicit CryptoCenterScreen(QWidget* parent = nullptr);+ ~CryptoCenterScreen() override;++ private:+ void build_ui();+ void build_empty_page();+ void build_connected_page();+ void apply_theme();++ void on_wallet_connected(const QString& pubkey, const QString& label);+ void on_wallet_disconnected();++ // Header+ QWidget* header_ = nullptr;+ QLabel* header_brand_ = nullptr;+ QLabel* header_route_ = nullptr;+ QLabel* header_separator_ = nullptr;+ QLabel* header_status_ = nullptr;++ // Stack+ QStackedWidget* stack_ = nullptr;++ // Empty state+ QWidget* empty_page_ = nullptr;+ QFrame* empty_panel_ = nullptr;+ QLabel* empty_title_ = nullptr;+ QLabel* empty_lede_ = nullptr;+ QLabel* empty_security_label_ = nullptr;+ QLabel* empty_security_text_ = nullptr;+ QPushButton* connect_button_ = nullptr;++ // Connected state+ QWidget* connected_page_ = nullptr;+ HoldingsBar* holdings_bar_ = nullptr;+ QTabWidget* tab_widget_ = nullptr;++ HomeTab* home_tab_ = nullptr;+ TradeTab* trade_tab_ = nullptr;+ ActivityTab* activity_tab_ = nullptr;+ SettingsTab* settings_tab_ = nullptr;+ ComingSoonTab* stake_tab_ = nullptr;+ ComingSoonTab* markets_tab_ = nullptr;+ ComingSoonTab* roadmap_tab_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/HoldingsBar.cpp b/fincept-qt/src/screens/crypto_center/HoldingsBar.cppnew file mode 100644index 000000000..a9f082602--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/HoldingsBar.cpp@@ -0,0 +1,479 @@+#include "screens/crypto_center/HoldingsBar.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "services/wallet/WalletService.h"+#include "services/wallet/WalletTypes.h"+#include "storage/secure/SecureStorage.h"+#include "ui/theme/Theme.h"++#include <QDateTime>+#include <QHBoxLayout>+#include <cmath>+#include <QHideEvent>+#include <QLabel>+#include <QLocale>+#include <QSet>+#include <QShowEvent>+#include <QStyle>+#include <QTimer>++namespace fincept::screens {++namespace {++constexpr qint64 kStaleThresholdMs = 90 * 1000;+constexpr int kStalenessTickMs = 5 * 1000;++QString font_stack() {+ return QStringLiteral(+ "'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");+}++QString format_token(double v, int max_dp = 4) {+ if (v <= 0.0) return QStringLiteral("0");+ return QLocale::system().toString(v, 'f', max_dp);+}++QString format_usd(double v) {+ if (v < 0.0) return QStringLiteral("—");+ if (v >= 1.0 || v == 0.0) {+ return QStringLiteral("$%1").arg(QLocale::system().toString(v, 'f', 2));+ }+ return QStringLiteral("$%1").arg(QLocale::system().toString(v, 'f', 6));+}++QString format_price(double v) {+ if (v <= 0.0) return QStringLiteral("—");+ if (v >= 1.0) {+ return QStringLiteral("$%1").arg(QLocale::system().toString(v, 'f', 4));+ }+ return QStringLiteral("$%1").arg(QLocale::system().toString(v, 'f', 8));+}++QString relative_time(qint64 ts_ms) {+ if (ts_ms == 0) return QStringLiteral("never");+ const auto delta = QDateTime::currentMSecsSinceEpoch() - ts_ms;+ if (delta < 0) return QStringLiteral("just now");+ const auto seconds = delta / 1000;+ if (seconds < 60) return QStringLiteral("%1s ago").arg(seconds);+ if (seconds < 3600) return QStringLiteral("%1m ago").arg(seconds / 60);+ if (seconds < 86400) return QStringLiteral("%1h ago").arg(seconds / 3600);+ return QStringLiteral("%1d ago").arg(seconds / 86400);+}++QString rpc_provider_label() {+ auto override_res =+ SecureStorage::instance().retrieve(QStringLiteral("solana.rpc_url"));+ if (override_res.is_ok() && !override_res.value().isEmpty()) {+ return QStringLiteral("CUSTOM");+ }+ auto helius_res =+ SecureStorage::instance().retrieve(QStringLiteral("solana.helius_api_key"));+ if (helius_res.is_ok() && !helius_res.value().isEmpty()) {+ return QStringLiteral("HELIUS");+ }+ return QStringLiteral("PUBLIC");+}++} // namespace++HoldingsBar::HoldingsBar(QWidget* parent) : QWidget(parent) {+ setObjectName(QStringLiteral("holdingsBar"));+ setFixedHeight(56);++ build_ui();+ apply_theme();++ auto& svc = fincept::wallet::WalletService::instance();+ connect(&svc, &fincept::wallet::WalletService::wallet_connected, this,+ &HoldingsBar::on_wallet_connected);+ connect(&svc, &fincept::wallet::WalletService::wallet_disconnected, this,+ &HoldingsBar::on_wallet_disconnected);+ connect(&svc, &fincept::wallet::WalletService::balance_mode_changed, this,+ &HoldingsBar::on_mode_changed);++ auto& hub = fincept::datahub::DataHub::instance();+ connect(&hub, &fincept::datahub::DataHub::topic_error, this,+ &HoldingsBar::on_topic_error);++ staleness_timer_ = new QTimer(this);+ staleness_timer_->setInterval(kStalenessTickMs);+ connect(staleness_timer_, &QTimer::timeout, this,+ &HoldingsBar::update_staleness);++ if (svc.is_connected()) {+ on_wallet_connected(svc.current_pubkey(), svc.state().label);+ } else {+ set_feed_status(FeedStatus::Idle);+ }+ update_rpc_indicator();+}++HoldingsBar::~HoldingsBar() = default;++void HoldingsBar::build_ui() {+ auto* root = new QHBoxLayout(this);+ root->setContentsMargins(14, 8, 14, 8);+ root->setSpacing(18);++ auto add_metric = [this, root](const QString& label_text, QLabel*& value_out,+ const QString& object_name) {+ auto* col = new QVBoxLayout;+ col->setContentsMargins(0, 0, 0, 0);+ col->setSpacing(2);+ auto* label = new QLabel(label_text, this);+ label->setObjectName(QStringLiteral("holdingsBarLabel"));+ value_out = new QLabel(QStringLiteral("—"), this);+ value_out->setObjectName(object_name);+ value_out->setTextInteractionFlags(Qt::TextSelectableByMouse);+ col->addWidget(label);+ col->addWidget(value_out);+ root->addLayout(col);+ };++ add_metric(QStringLiteral("SOL"), sol_value_,+ QStringLiteral("holdingsBarValue"));+ add_metric(QStringLiteral("$FNCPT"), fncpt_value_,+ QStringLiteral("holdingsBarValueAccent"));+ add_metric(QStringLiteral("TOTAL"), total_value_,+ QStringLiteral("holdingsBarValue"));+ add_metric(QStringLiteral("$FNCPT PRICE"), fncpt_price_value_,+ QStringLiteral("holdingsBarValueDim"));+ add_metric(QStringLiteral("UPDATED"), updated_value_,+ QStringLiteral("holdingsBarValueDim"));++ root->addStretch(1);++ discount_chip_ = new QLabel(QStringLiteral("30% OFF"), this);+ discount_chip_->setObjectName(QStringLiteral("holdingsBarDiscountChip"));+ discount_chip_->hide();+ root->addWidget(discount_chip_);++ feed_status_ = new QLabel(QStringLiteral("○ IDLE"), this);+ feed_status_->setObjectName(QStringLiteral("holdingsBarFeedIdle"));+ root->addWidget(feed_status_);++ rpc_indicator_ = new QLabel(rpc_provider_label(), this);+ rpc_indicator_->setObjectName(QStringLiteral("holdingsBarRpcChip"));+ root->addWidget(rpc_indicator_);+}++void HoldingsBar::apply_theme() {+ using namespace ui::colors;+ const QString font = font_stack();++ const QString ss = QStringLiteral(+ "QWidget#holdingsBar { background:%1; border-bottom:1px solid %2; }"++ // Metric labels+ "QLabel#holdingsBarLabel { color:%3; font-family:%4; font-size:9px;"+ " font-weight:700; letter-spacing:1.5px; background:transparent; }"+ "QLabel#holdingsBarValue { color:%5; font-family:%4; font-size:14px;"+ " font-weight:600; background:transparent; }"+ "QLabel#holdingsBarValueAccent { color:%6; font-family:%4; font-size:14px;"+ " font-weight:700; background:transparent; }"+ "QLabel#holdingsBarValueDim { color:%7; font-family:%4; font-size:12px;"+ " background:transparent; }"++ // Discount chip+ "QLabel#holdingsBarDiscountChip { color:%8; font-family:%4; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:rgba(34,197,94,0.10);"+ " border:1px solid %8; padding:2px 8px; }"++ // Feed status (5 variants)+ "QLabel#holdingsBarFeedIdle { color:%3; font-family:%4; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent;"+ " padding:2px 6px; }"+ "QLabel#holdingsBarFeedConnecting { color:%6; font-family:%4; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent;"+ " padding:2px 6px; }"+ "QLabel#holdingsBarFeedLive { color:%8; font-family:%4; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent;"+ " padding:2px 6px; }"+ "QLabel#holdingsBarFeedStale { color:%6; font-family:%4; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent;"+ " padding:2px 6px; }"+ "QLabel#holdingsBarFeedError { color:%9; font-family:%4; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent;"+ " padding:2px 6px; }"++ // RPC chip+ "QLabel#holdingsBarRpcChip { color:%3; font-family:%4; font-size:9px;"+ " font-weight:700; letter-spacing:1.2px; background:%10;"+ " border:1px solid %2; padding:2px 6px; }"+ )+ .arg(BG_SURFACE(), // %1+ BORDER_DIM(), // %2+ TEXT_TERTIARY(), // %3+ font, // %4+ TEXT_PRIMARY(), // %5+ AMBER(), // %6+ TEXT_SECONDARY(), // %7+ POSITIVE()) // %8+ .arg(NEGATIVE(), // %9+ BG_RAISED()); // %10++ setStyleSheet(ss);+}++void HoldingsBar::on_wallet_connected(const QString& pubkey, const QString& /*label*/) {+ current_pubkey_ = pubkey;+ sol_value_->setText(QStringLiteral("—"));+ fncpt_value_->setText(QStringLiteral("—"));+ total_value_->setText(QStringLiteral("—"));+ fncpt_price_value_->setText(QStringLiteral("—"));+ updated_value_->setText(QStringLiteral("waiting…"));+ last_balance_ts_ = 0;+ first_publish_received_ = false;+ update_rpc_indicator();+ set_feed_status(FeedStatus::Connecting);++ if (isVisible()) {+ refresh_subscription();+ if (!staleness_timer_->isActive()) staleness_timer_->start();+ }+}++void HoldingsBar::on_wallet_disconnected() {+ auto& hub = fincept::datahub::DataHub::instance();+ hub.unsubscribe(this);+ current_balance_topic_.clear();+ price_topic_.clear();+ price_usd_.clear();+ current_pubkey_.clear();+ latest_balance_ = {};+ last_balance_ts_ = 0;+ first_publish_received_ = false;+ sol_value_->setText(QStringLiteral("—"));+ fncpt_value_->setText(QStringLiteral("—"));+ total_value_->setText(QStringLiteral("—"));+ fncpt_price_value_->setText(QStringLiteral("—"));+ updated_value_->setText(QStringLiteral("—"));+ discount_chip_->hide();+ set_feed_status(FeedStatus::Idle);+ staleness_timer_->stop();+}++void HoldingsBar::on_mode_changed(bool /*is_stream*/) {+ if (current_pubkey_.isEmpty()) return;+ set_feed_status(FeedStatus::Connecting);+}++void HoldingsBar::refresh_subscription() {+ auto& hub = fincept::datahub::DataHub::instance();+ if (!current_balance_topic_.isEmpty()) {+ hub.unsubscribe(this, current_balance_topic_);+ current_balance_topic_.clear();+ }+ if (current_pubkey_.isEmpty()) return;+ current_balance_topic_ = QStringLiteral("wallet:balance:%1").arg(current_pubkey_);+ hub.subscribe(this, current_balance_topic_,+ [this](const QVariant& v) { on_balance_update(v); });+ hub.request(current_balance_topic_, /*force=*/true);++ // Phase 2 §2C: subscribe to fee-discount eligibility for this pubkey.+ const auto discount_topic =+ QStringLiteral("billing:fncpt_discount:%1").arg(current_pubkey_);+ hub.subscribe(this, discount_topic,+ [this](const QVariant& v) { on_discount_update(v); });+ hub.request(discount_topic, /*force=*/true);+}++void HoldingsBar::on_discount_update(const QVariant& v) {+ if (!v.canConvert<fincept::wallet::FncptDiscount>()) return;+ const auto d = v.value<fincept::wallet::FncptDiscount>();+ if (!discount_chip_) return;+ if (d.eligible) {+ discount_chip_->setText(QStringLiteral("%1% OFF").arg(d.discount_pct));+ discount_chip_->setToolTip(+ tr("Holding ≥ %1 $FNCPT — you qualify for the fee discount.")+ .arg(d.threshold_raw / std::pow(10.0, d.threshold_decimals), 0, 'f', 0));+ discount_chip_->show();+ } else {+ discount_chip_->hide();+ }+}++void HoldingsBar::resubscribe_prices() {+ auto& hub = fincept::datahub::DataHub::instance();++ // Always include SOL + FNCPT, plus every held token.+ QSet<QString> wanted;+ wanted.insert(QString::fromLatin1(fincept::wallet::kWrappedSolMint));+ wanted.insert(QString::fromLatin1(fincept::wallet::kFncptMint));+ for (const auto& t : latest_balance_.tokens) {+ if (!t.mint.isEmpty()) wanted.insert(t.mint);+ }++ // Drop stale subscriptions.+ for (auto it = price_topic_.begin(); it != price_topic_.end();) {+ if (!wanted.contains(it.key())) {+ hub.unsubscribe(this, it.value());+ price_usd_.remove(it.key());+ it = price_topic_.erase(it);+ } else {+ ++it;+ }+ }++ // Subscribe to anything new.+ for (const auto& mint : wanted) {+ if (price_topic_.contains(mint)) continue;+ const auto topic = QStringLiteral("market:price:token:%1").arg(mint);+ price_topic_.insert(mint, topic);+ hub.subscribe(this, topic, [this, mint](const QVariant& v) {+ on_price_update(mint, v);+ });+ hub.request(topic, /*force=*/true);+ }+}++void HoldingsBar::on_balance_update(const QVariant& v) {+ if (!v.canConvert<fincept::wallet::WalletBalance>()) return;+ latest_balance_ = v.value<fincept::wallet::WalletBalance>();+ sol_value_->setText(format_token(latest_balance_.sol(), 4));+ fncpt_value_->setText(format_token(latest_balance_.fncpt_ui(), 2));+ last_balance_ts_ = latest_balance_.ts_ms;+ first_publish_received_ = true;+ set_feed_status(FeedStatus::Live);+ resubscribe_prices();+ recompute_total();+ update_staleness();+}++void HoldingsBar::on_price_update(const QString& mint, const QVariant& v) {+ if (!v.canConvert<fincept::wallet::TokenPrice>()) return;+ const auto p = v.value<fincept::wallet::TokenPrice>();+ if (!p.valid) return;+ price_usd_[mint] = p.usd;+ // Update the dedicated $FNCPT price cell when that mint refreshes.+ if (mint == QString::fromLatin1(fincept::wallet::kFncptMint)) {+ fncpt_price_value_->setText(format_price(p.usd));+ }+ recompute_total();+}++void HoldingsBar::recompute_total() {+ double total = 0.0;+ int unpriced = 0;+ bool any_known = false;++ // SOL+ const auto sol_mint = QString::fromLatin1(fincept::wallet::kWrappedSolMint);+ const double sol_amt = latest_balance_.sol();+ const double sol_px = price_usd_.value(sol_mint, -1.0);+ if (sol_amt > 0.0) {+ if (sol_px >= 0.0) {+ total += sol_amt * sol_px;+ any_known = true;+ } else {+ ++unpriced;+ }+ }++ // Tokens+ for (const auto& t : latest_balance_.tokens) {+ const double amt = t.ui_amount();+ if (amt <= 0.0) continue;+ const double px = price_usd_.value(t.mint, -1.0);+ if (px >= 0.0) {+ total += amt * px;+ any_known = true;+ } else {+ ++unpriced;+ }+ }++ total_value_->setText(any_known ? format_usd(total) : QStringLiteral("—"));+ if (unpriced > 0) {+ total_value_->setToolTip(+ tr("%1 holding(s) excluded — no live price.").arg(unpriced));+ } else {+ total_value_->setToolTip(QString());+ }+}++void HoldingsBar::on_topic_error(const QString& topic, const QString& error) {+ if (topic == current_balance_topic_) {+ set_feed_status(FeedStatus::Error);+ LOG_DEBUG("HoldingsBar", "balance error: " + error);+ }+}++void HoldingsBar::set_feed_status(FeedStatus s) {+ if (s == feed_status_state_) return;+ feed_status_state_ = s;+ if (!feed_status_) return;+ QString text;+ QString object_name;+ switch (s) {+ case FeedStatus::Idle:+ text = QStringLiteral("○ IDLE");+ object_name = QStringLiteral("holdingsBarFeedIdle");+ break;+ case FeedStatus::Connecting:+ text = QStringLiteral("◌ CONNECTING");+ object_name = QStringLiteral("holdingsBarFeedConnecting");+ break;+ case FeedStatus::Live:+ text = QStringLiteral("● LIVE");+ object_name = QStringLiteral("holdingsBarFeedLive");+ break;+ case FeedStatus::Stale:+ text = QStringLiteral("◐ STALE");+ object_name = QStringLiteral("holdingsBarFeedStale");+ break;+ case FeedStatus::Error:+ text = QStringLiteral("✕ ERROR");+ object_name = QStringLiteral("holdingsBarFeedError");+ break;+ }+ feed_status_->setText(text);+ feed_status_->setObjectName(object_name);+ feed_status_->style()->unpolish(feed_status_);+ feed_status_->style()->polish(feed_status_);+}++void HoldingsBar::update_rpc_indicator() {+ if (!rpc_indicator_) return;+ const auto label = rpc_provider_label();+ rpc_indicator_->setText(label);+ if (label == QStringLiteral("PUBLIC")) {+ rpc_indicator_->setToolTip(+ tr("Public Solana RPC. STREAM may degrade — add a Helius API key "+ "in Settings for reliable WebSocket subscriptions."));+ } else if (label == QStringLiteral("HELIUS")) {+ rpc_indicator_->setToolTip(tr("Helius RPC — STREAM fully supported."));+ } else {+ rpc_indicator_->setToolTip(tr("Custom RPC override active."));+ }+}++void HoldingsBar::update_staleness() {+ if (!first_publish_received_ || last_balance_ts_ == 0) return;+ updated_value_->setText(relative_time(last_balance_ts_));+ const auto age = QDateTime::currentMSecsSinceEpoch() - last_balance_ts_;+ if (age > kStaleThresholdMs && feed_status_state_ == FeedStatus::Live) {+ set_feed_status(FeedStatus::Stale);+ }+}++void HoldingsBar::showEvent(QShowEvent* e) {+ QWidget::showEvent(e);+ if (!current_pubkey_.isEmpty()) {+ refresh_subscription();+ if (!staleness_timer_->isActive()) staleness_timer_->start();+ }+ update_rpc_indicator();+}++void HoldingsBar::hideEvent(QHideEvent* e) {+ QWidget::hideEvent(e);+ staleness_timer_->stop();+ fincept::datahub::DataHub::instance().unsubscribe(this);+ current_balance_topic_.clear();+ price_topic_.clear();+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/HoldingsBar.h b/fincept-qt/src/screens/crypto_center/HoldingsBar.hnew file mode 100644index 000000000..bcac715fb--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/HoldingsBar.h@@ -0,0 +1,80 @@+#pragma once++#include "services/wallet/WalletTypes.h"++#include <QHash>+#include <QString>+#include <QVariant>+#include <QWidget>++class QHideEvent;+class QLabel;+class QShowEvent;+class QTimer;++namespace fincept::screens {++/// Persistent identity bar at the top of CryptoCenterScreen, visible across+/// every tab. Renders SOL · $FNCPT · TOTAL (USD) · feed status · RPC chip.+///+/// Phase 2 §2A.5: TOTAL is the sum across SOL + every priced verified+/// holding. Tokens whose price hasn't arrived (or which Jupiter doesn't+/// price) are excluded with a tooltip footnote.+///+/// Subscriptions (visibility-driven, P3 + D3):+/// - `wallet:balance:<pubkey>` owned data feed+/// - `market:price:token:<mint>` (per held mint, dynamically subscribed)+/// - `billing:fncpt_discount:<pubkey>` (Phase 2 Stage 2C — wired then)+class HoldingsBar : public QWidget {+ Q_OBJECT+ public:+ explicit HoldingsBar(QWidget* parent = nullptr);+ ~HoldingsBar() override;++ protected:+ void showEvent(QShowEvent* e) override;+ void hideEvent(QHideEvent* e) override;++ private:+ enum class FeedStatus { Idle, Connecting, Live, Stale, Error };++ void build_ui();+ void apply_theme();++ void on_wallet_connected(const QString& pubkey, const QString& label);+ void on_wallet_disconnected();+ void on_balance_update(const QVariant& v);+ void on_price_update(const QString& mint, const QVariant& v);+ void on_discount_update(const QVariant& v);+ void on_topic_error(const QString& topic, const QString& error);+ void on_mode_changed(bool is_stream);++ void refresh_subscription();+ void resubscribe_prices();+ void recompute_total();+ void set_feed_status(FeedStatus s);+ void update_rpc_indicator();+ void update_staleness();++ QLabel* sol_value_ = nullptr;+ QLabel* fncpt_value_ = nullptr;+ QLabel* total_value_ = nullptr; ///< sum of all priced holdings+ QLabel* fncpt_price_value_ = nullptr; ///< $FNCPT spot for legacy display+ QLabel* updated_value_ = nullptr;+ QLabel* feed_status_ = nullptr;+ QLabel* rpc_indicator_ = nullptr;+ QLabel* discount_chip_ = nullptr; // hidden until Stage 2C wires it++ QTimer* staleness_timer_ = nullptr;++ QString current_pubkey_;+ QString current_balance_topic_;+ fincept::wallet::WalletBalance latest_balance_;+ QHash<QString, double> price_usd_; ///< mint → USD price+ QHash<QString, QString> price_topic_; ///< mint → topic for unsubscribe+ qint64 last_balance_ts_ = 0;+ FeedStatus feed_status_state_ = FeedStatus::Idle;+ bool first_publish_received_ = false;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/WalletActionConfirmDialog.cpp b/fincept-qt/src/screens/crypto_center/WalletActionConfirmDialog.cppnew file mode 100644index 000000000..a40a03185--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/WalletActionConfirmDialog.cpp@@ -0,0 +1,292 @@+#include "screens/crypto_center/WalletActionConfirmDialog.h"++#include "ui/theme/Theme.h"++#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QPushButton>+#include <QShowEvent>+#include <QTimer>+#include <QVBoxLayout>++namespace fincept::screens {++namespace {++constexpr int kArmTickMs = 100; // 10 Hz countdown tick — smooth-enough+constexpr int kMinDialogWidth = 480;+constexpr int kRowMinHeight = 28;++QString fontStack() {+ return QStringLiteral(+ "'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");+}++QString format_remaining(int ms) {+ // 1500 → "1.5s", 800 → "0.8s", <=0 → ""+ if (ms <= 0) return QString();+ const double secs = ms / 1000.0;+ return QStringLiteral("%1s").arg(secs, 0, 'f', 1);+}++} // namespace++WalletActionConfirmDialog::WalletActionConfirmDialog(WalletActionSummary summary,+ QWidget* parent)+ : QDialog(parent), summary_(std::move(summary)) {+ setObjectName(QStringLiteral("walletActionConfirmDialog"));+ setModal(true);+ setWindowTitle(summary_.title.isEmpty() ? tr("Confirm") : summary_.title);+ setMinimumWidth(kMinDialogWidth);++ arm_timer_ = new QTimer(this);+ arm_timer_->setInterval(kArmTickMs);+ connect(arm_timer_, &QTimer::timeout, this,+ &WalletActionConfirmDialog::on_arm_tick);++ build_ui();+ apply_theme();+}++WalletActionConfirmDialog::~WalletActionConfirmDialog() = default;++bool WalletActionConfirmDialog::prompt() {+ return exec() == QDialog::Accepted;+}++void WalletActionConfirmDialog::build_ui() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // Header bar — flat block colour, mirrors cryptoCenterPanelHead.+ auto* header = new QWidget(this);+ header->setObjectName(QStringLiteral("walletActionDialogHeader"));+ header->setFixedHeight(36);+ auto* hl = new QHBoxLayout(header);+ hl->setContentsMargins(14, 0, 14, 0);+ hl->setSpacing(0);+ title_label_ = new QLabel(summary_.title, header);+ title_label_->setObjectName(QStringLiteral("walletActionDialogTitle"));+ hl->addWidget(title_label_);+ hl->addStretch();+ auto* head_status = new QLabel(QStringLiteral("AWAITING CONFIRMATION"), header);+ head_status->setObjectName(QStringLiteral("walletActionDialogHeadStatus"));+ hl->addWidget(head_status);+ root->addWidget(header);++ // Body wrapper+ auto* body = new QWidget(this);+ body->setObjectName(QStringLiteral("walletActionDialogBody"));+ auto* bl = new QVBoxLayout(body);+ bl->setContentsMargins(18, 14, 18, 14);+ bl->setSpacing(10);++ if (!summary_.lede.isEmpty()) {+ lede_label_ = new QLabel(summary_.lede, body);+ lede_label_->setObjectName(QStringLiteral("walletActionDialogLede"));+ lede_label_->setWordWrap(true);+ bl->addWidget(lede_label_);+ }++ // Rows+ if (!summary_.rows.isEmpty()) {+ auto* rows_block = new QFrame(body);+ rows_block->setObjectName(QStringLiteral("walletActionDialogRowsBlock"));+ rows_layout_ = new QVBoxLayout(rows_block);+ rows_layout_->setContentsMargins(0, 0, 0, 0);+ rows_layout_->setSpacing(0);+ for (int i = 0; i < summary_.rows.size(); ++i) {+ const auto& r = summary_.rows.at(i);+ const bool last = (i + 1 == summary_.rows.size());++ auto* row_widget = new QWidget(rows_block);+ row_widget->setObjectName(QStringLiteral("walletActionDialogRow"));+ row_widget->setProperty("isLast", last);+ row_widget->setMinimumHeight(kRowMinHeight);+ auto* rl = new QHBoxLayout(row_widget);+ rl->setContentsMargins(12, 6, 12, 6);+ rl->setSpacing(8);+ auto* label = new QLabel(r.label, row_widget);+ label->setObjectName(QStringLiteral("walletActionDialogRowLabel"));+ auto* value = new QLabel(r.value, row_widget);+ value->setObjectName(r.monospace+ ? QStringLiteral("walletActionDialogRowValueMono")+ : QStringLiteral("walletActionDialogRowValue"));+ value->setWordWrap(!r.monospace);+ value->setTextInteractionFlags(Qt::TextSelectableByMouse);+ rl->addWidget(label);+ rl->addStretch(1);+ rl->addWidget(value);+ rows_layout_->addWidget(row_widget);+ }+ bl->addWidget(rows_block);+ }++ // Warnings+ if (!summary_.warnings.isEmpty()) {+ auto* warn_block = new QFrame(body);+ warn_block->setObjectName(QStringLiteral("walletActionDialogWarnBlock"));+ warnings_layout_ = new QVBoxLayout(warn_block);+ warnings_layout_->setContentsMargins(10, 8, 10, 8);+ warnings_layout_->setSpacing(4);+ for (const auto& w : summary_.warnings) {+ auto* line = new QLabel(QStringLiteral("· ") + w, warn_block);+ line->setObjectName(QStringLiteral("walletActionDialogWarnText"));+ line->setWordWrap(true);+ warnings_layout_->addWidget(line);+ }+ bl->addWidget(warn_block);+ }++ bl->addStretch(1);+ root->addWidget(body, 1);++ // Footer with buttons+ auto* footer = new QWidget(this);+ footer->setObjectName(QStringLiteral("walletActionDialogFooter"));+ footer->setFixedHeight(50);+ auto* fl = new QHBoxLayout(footer);+ fl->setContentsMargins(14, 8, 14, 8);+ fl->setSpacing(8);++ cancel_button_ = new QPushButton(tr("CANCEL"), footer);+ cancel_button_->setObjectName(QStringLiteral("walletActionDialogCancel"));+ cancel_button_->setFixedHeight(30);+ cancel_button_->setCursor(Qt::PointingHandCursor);++ primary_button_ = new QPushButton(summary_.primary_button_text, footer);+ primary_button_->setObjectName(+ summary_.primary_is_safe ? QStringLiteral("walletActionDialogPrimary")+ : QStringLiteral("walletActionDialogPrimaryDanger"));+ primary_button_->setFixedHeight(30);+ primary_button_->setCursor(Qt::PointingHandCursor);+ primary_button_->setEnabled(false); // armed by timer++ fl->addStretch(1);+ fl->addWidget(cancel_button_);+ fl->addWidget(primary_button_);+ root->addWidget(footer);++ connect(cancel_button_, &QPushButton::clicked, this, [this]() {+ emit cancelled();+ reject();+ });+ connect(primary_button_, &QPushButton::clicked, this, [this]() {+ emit confirmed();+ accept();+ });+}++void WalletActionConfirmDialog::apply_theme() {+ using namespace ui::colors;++ const QString font = fontStack();++ const QString ss = QStringLiteral(+ // Root+ "QDialog#walletActionConfirmDialog { background:%1; }"++ // Header+ "QWidget#walletActionDialogHeader { background:%2; border-bottom:1px solid %3; }"+ "QLabel#walletActionDialogTitle { color:%4; font-family:%5; font-size:12px;"+ " font-weight:700; letter-spacing:1.4px; background:transparent; }"+ "QLabel#walletActionDialogHeadStatus { color:%6; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"++ // Body+ "QWidget#walletActionDialogBody { background:%1; }"+ "QLabel#walletActionDialogLede { color:%7; font-family:%5; font-size:12px;"+ " background:transparent; }"++ // Row block+ "QFrame#walletActionDialogRowsBlock { background:%8; border:1px solid %3; }"+ "QWidget#walletActionDialogRow { background:transparent;"+ " border-bottom:1px solid %3; }"+ "QWidget#walletActionDialogRow[isLast=\"true\"] { border-bottom:none; }"+ "QLabel#walletActionDialogRowLabel { color:%6; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QLabel#walletActionDialogRowValue { color:%9; font-family:%5; font-size:12px;"+ " background:transparent; }"+ "QLabel#walletActionDialogRowValueMono { color:%9; font-family:%5; font-size:12px;"+ " background:transparent; }"++ // Warnings+ "QFrame#walletActionDialogWarnBlock { background:rgba(220,38,38,0.10);"+ " border:1px solid %10; }"+ "QLabel#walletActionDialogWarnText { color:%10; font-family:%5; font-size:11px;"+ " background:transparent; }"++ // Footer+ "QWidget#walletActionDialogFooter { background:%2; border-top:1px solid %3; }"++ // Cancel button+ "QPushButton#walletActionDialogCancel { background:%8; color:%7; border:1px solid %3;"+ " font-family:%5; font-size:11px; font-weight:700; letter-spacing:1px; padding:0 14px; }"+ "QPushButton#walletActionDialogCancel:hover { background:%11; color:%9;"+ " border-color:%12; }"++ // Primary (safe — amber)+ "QPushButton#walletActionDialogPrimary { background:rgba(217,119,6,0.10); color:%4;"+ " border:1px solid %13; font-family:%5; font-size:11px; font-weight:700;"+ " letter-spacing:1.2px; padding:0 16px; }"+ "QPushButton#walletActionDialogPrimary:hover { background:%4; color:%1; }"+ "QPushButton#walletActionDialogPrimary:disabled { background:%8; color:%6;"+ " border-color:%3; }"++ // Primary (danger — red)+ "QPushButton#walletActionDialogPrimaryDanger { background:rgba(220,38,38,0.10); color:%10;"+ " border:1px solid %14; font-family:%5; font-size:11px; font-weight:700;"+ " letter-spacing:1.2px; padding:0 16px; }"+ "QPushButton#walletActionDialogPrimaryDanger:hover { background:%10; color:%9; }"+ "QPushButton#walletActionDialogPrimaryDanger:disabled { background:%8; color:%6;"+ " border-color:%3; }"+ )+ .arg(BG_BASE(), // %1+ BG_SURFACE(), // %2+ BORDER_DIM(), // %3+ AMBER(), // %4+ font, // %5+ TEXT_TERTIARY(), // %6+ TEXT_SECONDARY(), // %7+ BG_RAISED(), // %8+ TEXT_PRIMARY()) // %9+ .arg(NEGATIVE(), // %10+ BG_HOVER(), // %11+ BORDER_BRIGHT(), // %12+ QStringLiteral("#78350f"), // %13 darker amber border+ QStringLiteral("#7f1d1d")); // %14 darker red border++ setStyleSheet(ss);+}++void WalletActionConfirmDialog::showEvent(QShowEvent* e) {+ QDialog::showEvent(e);+ arm_remaining_ms_ = summary_.arm_delay_ms;+ if (arm_remaining_ms_ <= 0) {+ primary_button_->setEnabled(true);+ primary_button_->setText(summary_.primary_button_text);+ return;+ }+ primary_button_->setEnabled(false);+ primary_button_->setText(QStringLiteral("%1 in %2")+ .arg(summary_.primary_button_text,+ format_remaining(arm_remaining_ms_)));+ arm_timer_->start();+}++void WalletActionConfirmDialog::on_arm_tick() {+ arm_remaining_ms_ -= kArmTickMs;+ if (arm_remaining_ms_ <= 0) {+ arm_timer_->stop();+ primary_button_->setEnabled(true);+ primary_button_->setText(summary_.primary_button_text);+ return;+ }+ primary_button_->setText(QStringLiteral("%1 in %2")+ .arg(summary_.primary_button_text,+ format_remaining(arm_remaining_ms_)));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/WalletActionConfirmDialog.h b/fincept-qt/src/screens/crypto_center/WalletActionConfirmDialog.hnew file mode 100644index 000000000..f27471bb2--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/WalletActionConfirmDialog.h@@ -0,0 +1,66 @@+#pragma once++#include "screens/crypto_center/WalletActionSummary.h"++#include <QDialog>++class QLabel;+class QPushButton;+class QTimer;+class QVBoxLayout;++namespace fincept::screens {++/// Modal "are you sure" dialog shown before any fund-moving wallet action.+///+/// Security-relevant behaviour:+/// - Renders every row of `WalletActionSummary` verbatim. The terminal+/// decodes the action **here**, not in the wallet — even users who blindly+/// approve in Phantom must see what they're signing first.+/// - The primary button is **disabled** for `summary.arm_delay_ms` after+/// show, with a visible countdown ("CONFIRM in 1.5s"). Resists muscle+/// memory and accidental double-clicks.+/// - Cancel always available. The cancel path emits `cancelled()` so the+/// caller can clean up any held-open bridge tokens.+///+/// UI compliance:+/// - Single global stylesheet keyed by `objectName` (Phase 1.5 §1.5.3 #1).+/// - No QTimer in constructor — `arm_timer_` only starts after `exec()`+/// fires `showEvent`.+class WalletActionConfirmDialog : public QDialog {+ Q_OBJECT+ public:+ explicit WalletActionConfirmDialog(WalletActionSummary summary,+ QWidget* parent = nullptr);+ ~WalletActionConfirmDialog() override;++ /// Convenience: show modally, return true on confirm, false on cancel /+ /// reject / close. Equivalent to `exec() == QDialog::Accepted`.+ bool prompt();++ signals:+ void confirmed();+ void cancelled();++ protected:+ void showEvent(QShowEvent* e) override;++ private:+ void build_ui();+ void apply_theme();+ void on_arm_tick();++ WalletActionSummary summary_;++ QLabel* title_label_ = nullptr;+ QLabel* lede_label_ = nullptr;+ QVBoxLayout* rows_layout_ = nullptr;+ QVBoxLayout* warnings_layout_ = nullptr;+ QPushButton* primary_button_ = nullptr;+ QPushButton* cancel_button_ = nullptr;++ QTimer* arm_timer_ = nullptr;+ int arm_remaining_ms_ = 0;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/WalletActionSummary.h b/fincept-qt/src/screens/crypto_center/WalletActionSummary.hnew file mode 100644index 000000000..d36f1e6ea--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/WalletActionSummary.h@@ -0,0 +1,50 @@+#pragma once++#include <QString>+#include <QVector>++namespace fincept::screens {++/// Plain-data description of a fund-moving wallet action, passed into+/// `WalletActionConfirmDialog`. Phase 2 covers swap + burn; later phases+/// (lock, prediction stake) reuse the same struct.+///+/// **Read carefully**: every row and warning here ends up in front of the+/// user before they sign anything, so each field is part of the security+/// contract — not just UI fluff. Don't omit a row "to keep the dialog small."+struct WalletActionSummary {+ /// Header line. Examples: "SWAP", "BURN $FNCPT", "LOCK $FNCPT".+ QString title;++ /// Short paragraph below the title, optional. One-liner is fine; longer+ /// strings wrap. Keep neutral and factual.+ QString lede;++ struct Row {+ QString label; ///< small-caps label, e.g. "ROUTE"+ QString value; ///< monospace value, e.g. "SOL → USDC → $FNCPT"+ bool monospace = true; ///< false if value should wrap as natural text+ };+ /// One key/value row per fact the user should verify before signing.+ /// Order matters — render top-to-bottom in the same sequence.+ QVector<Row> rows;++ /// Warnings rendered as a list of red-tinted bullets above the buttons.+ /// "Irreversible. Tokens cannot be recovered." goes here for burns.+ QVector<QString> warnings;++ /// Text on the confirm button. "SWAP", "BURN", "LOCK".+ QString primary_button_text = QStringLiteral("CONFIRM");++ /// Cosmetic — false renders the primary button in the danger color+ /// (red border / red hover); true uses the standard amber accent.+ /// Burns set `false`. Swaps set `true`.+ bool primary_is_safe = true;++ /// Anti-muscle-memory. The primary button is disabled for this many ms+ /// after the dialog appears, with a visible countdown. Per the Phase 2+ /// threat model: 1500 ms for swaps, 2500 ms for burns.+ int arm_delay_ms = 1500;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.cppnew file mode 100644index 000000000..c0d5bad06--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.cpp@@ -0,0 +1,329 @@+#include "screens/crypto_center/panels/FeeDiscountPanel.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "services/billing/FeeDiscountConfig.h"+#include "services/wallet/WalletService.h"+#include "services/wallet/WalletTypes.h"+#include "ui/theme/Theme.h"++#include <QHBoxLayout>+#include <QHideEvent>+#include <QLabel>+#include <QLocale>+#include <QProgressBar>+#include <QShowEvent>+#include <QVBoxLayout>++#include <cmath>++namespace fincept::screens::panels {++namespace {++QString font_stack() {+ return QStringLiteral(+ "'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");+}++QString format_token(double v, int dp = 2) {+ if (v <= 0.0) return QStringLiteral("0");+ return QLocale::system().toString(v, 'f', dp);+}++QString format_usd(double v) {+ if (v < 0.0) return QStringLiteral("—");+ return QStringLiteral("$%1").arg(QLocale::system().toString(v, 'f', 2));+}++double threshold_ui(const fincept::wallet::FncptDiscount& d) {+ if (d.threshold_decimals <= 0) return 0.0;+ return static_cast<double>(d.threshold_raw) / std::pow(10.0, d.threshold_decimals);+}++} // namespace++FeeDiscountPanel::FeeDiscountPanel(QWidget* parent) : QWidget(parent) {+ setObjectName(QStringLiteral("feeDiscountPanel"));+ build_ui();+ apply_theme();++ auto& svc = fincept::wallet::WalletService::instance();+ connect(&svc, &fincept::wallet::WalletService::wallet_connected, this,+ &FeeDiscountPanel::on_wallet_connected);+ connect(&svc, &fincept::wallet::WalletService::wallet_disconnected, this,+ &FeeDiscountPanel::on_wallet_disconnected);++ if (svc.is_connected()) {+ on_wallet_connected(svc.current_pubkey(), svc.state().label);+ }++ update_view();+}++FeeDiscountPanel::~FeeDiscountPanel() = default;++void FeeDiscountPanel::build_ui() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // Header bar+ auto* head = new QWidget(this);+ head->setObjectName(QStringLiteral("feeDiscountHead"));+ head->setFixedHeight(34);+ auto* hl = new QHBoxLayout(head);+ hl->setContentsMargins(12, 0, 12, 0);+ hl->setSpacing(8);+ auto* title = new QLabel(QStringLiteral("FEE DISCOUNT"), head);+ title->setObjectName(QStringLiteral("feeDiscountTitle"));+ heading_status_ = new QLabel(QStringLiteral("—"), head);+ heading_status_->setObjectName(QStringLiteral("feeDiscountHeadStatus"));+ hl->addWidget(title);+ hl->addStretch();+ hl->addWidget(heading_status_);+ root->addWidget(head);++ // Body+ auto* body = new QWidget(this);+ body->setObjectName(QStringLiteral("feeDiscountBody"));+ auto* bl = new QVBoxLayout(body);+ bl->setContentsMargins(14, 14, 14, 14);+ bl->setSpacing(10);++ // Threshold + balance row+ auto* row = new QWidget(body);+ auto* rl = new QHBoxLayout(row);+ rl->setContentsMargins(0, 0, 0, 0);+ rl->setSpacing(18);++ auto add_kv = [body, rl](const QString& cap, QLabel*& v_out,+ const QString& obj_name) {+ auto* col = new QVBoxLayout;+ col->setContentsMargins(0, 0, 0, 0);+ col->setSpacing(2);+ auto* k = new QLabel(cap, body);+ k->setObjectName(QStringLiteral("feeDiscountCaption"));+ v_out = new QLabel(QStringLiteral("—"), body);+ v_out->setObjectName(obj_name);+ col->addWidget(k);+ col->addWidget(v_out);+ rl->addLayout(col);+ };+ add_kv(QStringLiteral("HOLDING"), balance_value_,+ QStringLiteral("feeDiscountValue"));+ add_kv(QStringLiteral("THRESHOLD"), threshold_value_,+ QStringLiteral("feeDiscountValueDim"));+ rl->addStretch(1);+ bl->addWidget(row);++ progress_ = new QProgressBar(body);+ progress_->setObjectName(QStringLiteral("feeDiscountProgress"));+ progress_->setRange(0, 100);+ progress_->setValue(0);+ progress_->setTextVisible(false);+ progress_->setFixedHeight(8);+ bl->addWidget(progress_);++ auto* skus_caption = new QLabel(QStringLiteral("APPLIED TO"), body);+ skus_caption->setObjectName(QStringLiteral("feeDiscountCaption"));+ bl->addWidget(skus_caption);+ skus_value_ = new QLabel(QStringLiteral("—"), body);+ skus_value_->setObjectName(QStringLiteral("feeDiscountSkus"));+ skus_value_->setWordWrap(true);+ bl->addWidget(skus_value_);++ auto* save_caption = new QLabel(+ tr("PROJECTED SAVINGS · reference $%1 SKU")+ .arg(QLocale::system().toString(+ fincept::billing::FeeDiscountConfig::kReferencePriceUsd, 'f', 2)),+ body);+ save_caption->setObjectName(QStringLiteral("feeDiscountCaption"));+ bl->addWidget(save_caption);+ savings_value_ = new QLabel(QStringLiteral("—"), body);+ savings_value_->setObjectName(QStringLiteral("feeDiscountSavings"));+ bl->addWidget(savings_value_);++ hint_ = new QLabel(+ tr("Hold ≥ %1 $FNCPT to qualify for the discount on premium screens, "+ "AI reports, and deep backtests.")+ .arg(QLocale::system().toString(+ static_cast<double>(+ fincept::billing::FeeDiscountConfig::kThresholdRaw)+ / std::pow(10.0, fincept::billing::FeeDiscountConfig::kThresholdDecimals),+ 'f', 0)),+ body);+ hint_->setObjectName(QStringLiteral("feeDiscountHint"));+ hint_->setWordWrap(true);+ bl->addWidget(hint_);++ bl->addStretch(1);+ root->addWidget(body, 1);+}++void FeeDiscountPanel::apply_theme() {+ using namespace ui::colors;+ const QString font = font_stack();++ const QString ss = QStringLiteral(+ "QWidget#feeDiscountPanel { background:%1; }"+ "QWidget#feeDiscountHead { background:%2; border-bottom:1px solid %3; }"+ "QLabel#feeDiscountTitle { color:%4; font-family:%5; font-size:11px;"+ " font-weight:700; letter-spacing:1.4px; background:transparent; }"+ "QLabel#feeDiscountHeadStatus { color:%6; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QLabel#feeDiscountHeadStatusOk { color:%7; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QWidget#feeDiscountBody { background:%1; }"++ "QLabel#feeDiscountCaption { color:%6; font-family:%5; font-size:9px;"+ " font-weight:700; letter-spacing:1.4px; background:transparent; }"+ "QLabel#feeDiscountValue { color:%8; font-family:%5; font-size:14px;"+ " font-weight:600; background:transparent; }"+ "QLabel#feeDiscountValueDim { color:%9; font-family:%5; font-size:14px;"+ " background:transparent; }"+ "QLabel#feeDiscountSkus { color:%9; font-family:%5; font-size:12px;"+ " background:transparent; }"+ "QLabel#feeDiscountSavings { color:%4; font-family:%5; font-size:14px;"+ " font-weight:700; background:transparent; }"+ "QLabel#feeDiscountHint { color:%6; font-family:%5; font-size:11px;"+ " background:transparent; }"++ "QProgressBar#feeDiscountProgress { background:%2; border:1px solid %3;"+ " border-radius:0; }"+ "QProgressBar#feeDiscountProgress::chunk { background:%4; }"+ )+ .arg(BG_BASE(), // %1+ BG_RAISED(), // %2+ BORDER_DIM(), // %3+ AMBER(), // %4+ font, // %5+ TEXT_TERTIARY(), // %6+ POSITIVE(), // %7+ TEXT_PRIMARY(), // %8+ TEXT_SECONDARY()); // %9++ setStyleSheet(ss);+}++void FeeDiscountPanel::on_wallet_connected(const QString& pubkey, const QString& /*label*/) {+ current_pubkey_ = pubkey;+ if (isVisible()) refresh_subscriptions();+}++void FeeDiscountPanel::on_wallet_disconnected() {+ auto& hub = fincept::datahub::DataHub::instance();+ hub.unsubscribe(this);+ balance_topic_.clear();+ discount_topic_.clear();+ current_pubkey_.clear();+ fncpt_held_ = 0.0;+ have_discount_ = false;+ latest_ = {};+ update_view();+}++void FeeDiscountPanel::refresh_subscriptions() {+ auto& hub = fincept::datahub::DataHub::instance();+ if (!balance_topic_.isEmpty()) hub.unsubscribe(this, balance_topic_);+ if (!discount_topic_.isEmpty()) hub.unsubscribe(this, discount_topic_);+ balance_topic_.clear();+ discount_topic_.clear();+ if (current_pubkey_.isEmpty()) return;++ balance_topic_ = QStringLiteral("wallet:balance:%1").arg(current_pubkey_);+ discount_topic_ = QStringLiteral("billing:fncpt_discount:%1").arg(current_pubkey_);+ hub.subscribe(this, balance_topic_,+ [this](const QVariant& v) { on_balance_update(v); });+ hub.subscribe(this, discount_topic_,+ [this](const QVariant& v) { on_discount_update(v); });+ hub.request(balance_topic_, /*force=*/true);+ hub.request(discount_topic_, /*force=*/true);+}++void FeeDiscountPanel::on_balance_update(const QVariant& v) {+ if (!v.canConvert<fincept::wallet::WalletBalance>()) return;+ const auto bal = v.value<fincept::wallet::WalletBalance>();+ fncpt_held_ = bal.fncpt_ui();+ update_view();+}++void FeeDiscountPanel::on_discount_update(const QVariant& v) {+ if (!v.canConvert<fincept::wallet::FncptDiscount>()) return;+ latest_ = v.value<fincept::wallet::FncptDiscount>();+ have_discount_ = true;+ update_view();+}++void FeeDiscountPanel::update_view() {+ using fincept::billing::FeeDiscountConfig;++ const double threshold = have_discount_+ ? threshold_ui(latest_)+ : static_cast<double>(FeeDiscountConfig::kThresholdRaw)+ / std::pow(10.0, FeeDiscountConfig::kThresholdDecimals);+ const int discount_pct = have_discount_ ? latest_.discount_pct+ : FeeDiscountConfig::kDiscountPct;++ balance_value_->setText(+ current_pubkey_.isEmpty()+ ? QStringLiteral("—")+ : QStringLiteral("%1 $FNCPT").arg(format_token(fncpt_held_, 2)));+ threshold_value_->setText(+ QStringLiteral("%1 $FNCPT").arg(format_token(threshold, 0)));++ int pct = 0;+ if (threshold > 0.0) {+ const double frac = std::min(1.0, fncpt_held_ / threshold);+ pct = static_cast<int>(frac * 100.0);+ }+ progress_->setValue(pct);++ // SKUs as bullets+ QStringList sku_lines;+ const auto skus = have_discount_ ? latest_.applied_skus+ : FeeDiscountConfig::applied_skus();+ for (const auto& s : skus) {+ sku_lines.append(QStringLiteral("· ") + FeeDiscountConfig::display_label(s));+ }+ skus_value_->setText(sku_lines.join(QStringLiteral("\n")));++ // Eligibility chip + savings+ const bool eligible = have_discount_ ? latest_.eligible+ : (fncpt_held_ >= threshold);+ if (eligible) {+ heading_status_->setText(QStringLiteral("● %1% OFF ACTIVE").arg(discount_pct));+ heading_status_->setObjectName(QStringLiteral("feeDiscountHeadStatusOk"));+ const double save = FeeDiscountConfig::kReferencePriceUsd * discount_pct / 100.0;+ const double net = FeeDiscountConfig::kReferencePriceUsd - save;+ savings_value_->setText(+ QStringLiteral("%1 → %2 (you save %3)")+ .arg(format_usd(FeeDiscountConfig::kReferencePriceUsd))+ .arg(format_usd(net))+ .arg(format_usd(save)));+ } else {+ heading_status_->setText(QStringLiteral("LOCKED"));+ heading_status_->setObjectName(QStringLiteral("feeDiscountHeadStatus"));+ const double need = std::max(0.0, threshold - fncpt_held_);+ savings_value_->setText(+ tr("Acquire %1 more $FNCPT to unlock %2% off.")+ .arg(format_token(need, 0))+ .arg(discount_pct));+ }+ heading_status_->style()->unpolish(heading_status_);+ heading_status_->style()->polish(heading_status_);+}++void FeeDiscountPanel::showEvent(QShowEvent* e) {+ QWidget::showEvent(e);+ if (!current_pubkey_.isEmpty()) refresh_subscriptions();+}++void FeeDiscountPanel::hideEvent(QHideEvent* e) {+ QWidget::hideEvent(e);+ fincept::datahub::DataHub::instance().unsubscribe(this);+ balance_topic_.clear();+ discount_topic_.clear();+}++} // namespace fincept::screens::panelsdiff --git a/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.h b/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.hnew file mode 100644index 000000000..009c1be8c--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.h@@ -0,0 +1,64 @@+#pragma once++#include "services/wallet/WalletTypes.h"++#include <QString>+#include <QVariant>+#include <QWidget>++class QHideEvent;+class QLabel;+class QProgressBar;+class QShowEvent;++namespace fincept::screens::panels {++/// FeeDiscountPanel — sits on TradeTab; shows the user's eligibility for the+/// $FNCPT fee discount and the projected savings on a reference SKU.+///+/// Subscribes to two topics (visibility-driven, P3 + D3):+/// - `wallet:balance:<pubkey>` for the held FNCPT amount+/// - `billing:fncpt_discount:<pubkey>` for the eligibility flag + threshold+///+/// The two are decoupled so the panel can render the progress bar even+/// before the discount producer's first publish: balance → bar fill,+/// discount → eligibility chip + applied-SKU list.+class FeeDiscountPanel : public QWidget {+ Q_OBJECT+ public:+ explicit FeeDiscountPanel(QWidget* parent = nullptr);+ ~FeeDiscountPanel() override;++ protected:+ void showEvent(QShowEvent* e) override;+ void hideEvent(QHideEvent* e) override;++ private:+ void build_ui();+ void apply_theme();++ void on_wallet_connected(const QString& pubkey, const QString& label);+ void on_wallet_disconnected();+ void on_balance_update(const QVariant& v);+ void on_discount_update(const QVariant& v);++ void refresh_subscriptions();+ void update_view();++ QLabel* heading_status_ = nullptr;+ QLabel* balance_value_ = nullptr;+ QLabel* threshold_value_ = nullptr;+ QProgressBar* progress_ = nullptr;+ QLabel* skus_value_ = nullptr;+ QLabel* savings_value_ = nullptr;+ QLabel* hint_ = nullptr;++ QString current_pubkey_;+ QString balance_topic_;+ QString discount_topic_;+ double fncpt_held_ = 0.0;+ fincept::wallet::FncptDiscount latest_;+ bool have_discount_ = false;+};++} // namespace fincept::screens::panelsdiff --git a/fincept-qt/src/screens/crypto_center/panels/HoldingsTable.cpp b/fincept-qt/src/screens/crypto_center/panels/HoldingsTable.cppnew file mode 100644index 000000000..6af1981a9--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/panels/HoldingsTable.cpp@@ -0,0 +1,388 @@+#include "screens/crypto_center/panels/HoldingsTable.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "services/wallet/TokenMetadataService.h"+#include "services/wallet/WalletService.h"+#include "services/wallet/WalletTypes.h"+#include "storage/secure/SecureStorage.h"+#include "ui/theme/Theme.h"++#include <QHBoxLayout>+#include <QHeaderView>+#include <QHideEvent>+#include <QLabel>+#include <QLocale>+#include <QPushButton>+#include <QShowEvent>+#include <QTableWidget>+#include <QTableWidgetItem>+#include <QVBoxLayout>++namespace fincept::screens::panels {++namespace {++QString font_stack() {+ return QStringLiteral(+ "'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");+}++QString format_amount(double v, int max_dp = 4) {+ if (v == 0.0) return QStringLiteral("0");+ if (v < 0.0001) return QLocale::system().toString(v, 'g', 4);+ return QLocale::system().toString(v, 'f', max_dp);+}++QString format_usd(double v) {+ if (v < 0.0) return QStringLiteral("—");+ if (v >= 1.0 || v == 0.0) {+ return QStringLiteral("$%1").arg(QLocale::system().toString(v, 'f', 2));+ }+ return QStringLiteral("$%1").arg(QLocale::system().toString(v, 'f', 6));+}++QString format_price(double v) {+ if (v <= 0.0) return QStringLiteral("—");+ if (v >= 1.0) {+ return QStringLiteral("$%1").arg(QLocale::system().toString(v, 'f', 4));+ }+ return QStringLiteral("$%1").arg(QLocale::system().toString(v, 'f', 8));+}++QString format_pct(double v) {+ return QStringLiteral("%1%").arg(QLocale::system().toString(v, 'f', 1));+}++} // namespace++HoldingsTable::HoldingsTable(QWidget* parent) : QWidget(parent) {+ setObjectName(QStringLiteral("holdingsTable"));++ // Read persisted "show unverified" flag.+ auto r = SecureStorage::instance().retrieve(+ QStringLiteral("wallet.show_unverified_tokens"));+ if (r.is_ok()) {+ show_unverified_ =+ r.value().compare(QStringLiteral("true"), Qt::CaseInsensitive) == 0;+ }++ build_ui();+ apply_theme();++ auto& svc = fincept::wallet::WalletService::instance();+ connect(&svc, &fincept::wallet::WalletService::wallet_connected, this,+ &HoldingsTable::on_wallet_connected);+ connect(&svc, &fincept::wallet::WalletService::wallet_disconnected, this,+ &HoldingsTable::on_wallet_disconnected);++ connect(&fincept::wallet::TokenMetadataService::instance(),+ &fincept::wallet::TokenMetadataService::metadata_changed, this,+ &HoldingsTable::on_metadata_changed);++ if (svc.is_connected()) {+ on_wallet_connected(svc.current_pubkey(), svc.state().label);+ }+}++HoldingsTable::~HoldingsTable() = default;++void HoldingsTable::build_ui() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ table_ = new QTableWidget(this);+ table_->setObjectName(QStringLiteral("holdingsTableView"));+ table_->setColumnCount(5);+ table_->setHorizontalHeaderLabels(+ {QStringLiteral("TOKEN"), QStringLiteral("BALANCE"),+ QStringLiteral("PRICE"), QStringLiteral("USD VALUE"),+ QStringLiteral("% OF PORT")});+ table_->verticalHeader()->setVisible(false);+ table_->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);+ table_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);+ table_->setSelectionBehavior(QAbstractItemView::SelectRows);+ table_->setSelectionMode(QAbstractItemView::SingleSelection);+ table_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ table_->setShowGrid(false);+ table_->setAlternatingRowColors(false);+ table_->setSortingEnabled(false); // we sort manually at refresh+ root->addWidget(table_, 1);++ auto* footer_row = new QWidget(this);+ footer_row->setObjectName(QStringLiteral("holdingsTableFooter"));+ footer_row->setFixedHeight(30);+ auto* fl = new QHBoxLayout(footer_row);+ fl->setContentsMargins(12, 0, 12, 0);+ fl->setSpacing(8);+ footer_ = new QLabel(QStringLiteral("—"), footer_row);+ footer_->setObjectName(QStringLiteral("holdingsTableFooterText"));+ show_all_button_ = new QPushButton(+ show_unverified_ ? tr("Hide unverified") : tr("Show all"), footer_row);+ show_all_button_->setObjectName(QStringLiteral("holdingsTableShowAll"));+ show_all_button_->setFixedHeight(22);+ show_all_button_->setCursor(Qt::PointingHandCursor);+ fl->addWidget(footer_);+ fl->addStretch(1);+ fl->addWidget(show_all_button_);+ root->addWidget(footer_row);++ connect(table_, &QTableWidget::cellClicked, this, [this](int row, int) {+ auto* it = table_->item(row, 0);+ if (!it) return;+ const auto mint = it->data(Qt::UserRole).toString();+ if (!mint.isEmpty()) emit select_token(mint);+ });+ connect(show_all_button_, &QPushButton::clicked, this,+ &HoldingsTable::on_show_all_clicked);+}++void HoldingsTable::apply_theme() {+ using namespace ui::colors;+ const QString font = font_stack();+ const QString ss = QStringLiteral(+ "QWidget#holdingsTable { background:%1; }"+ "QTableWidget#holdingsTableView { background:%1; color:%2; gridline-color:%3;"+ " border:none; selection-background-color:%4; selection-color:%2;"+ " font-family:%5; font-size:11px; }"+ "QTableWidget#holdingsTableView::item { padding:6px 10px; border-bottom:1px solid %3; }"+ "QHeaderView::section { background:%6; color:%7; padding:6px 10px;"+ " border:none; border-bottom:1px solid %3; font-family:%5;"+ " font-size:9px; font-weight:700; letter-spacing:1.4px; }"+ "QWidget#holdingsTableFooter { background:%6; border-top:1px solid %3; }"+ "QLabel#holdingsTableFooterText { color:%7; font-family:%5; font-size:10px;"+ " background:transparent; }"+ "QPushButton#holdingsTableShowAll { background:transparent; color:%8;"+ " border:1px solid %3; font-family:%5; font-size:10px; font-weight:700;"+ " letter-spacing:1.2px; padding:0 10px; }"+ "QPushButton#holdingsTableShowAll:hover { color:%2; border-color:%9; }"+ )+ .arg(BG_BASE(), // %1+ TEXT_PRIMARY(), // %2+ BORDER_DIM(), // %3+ BG_HOVER(), // %4+ font, // %5+ BG_RAISED(), // %6+ TEXT_TERTIARY(), // %7+ AMBER(), // %8+ BORDER_BRIGHT()); // %9+ setStyleSheet(ss);+}++void HoldingsTable::on_wallet_connected(const QString& pubkey, const QString& /*label*/) {+ current_pubkey_ = pubkey;+ if (isVisible()) {+ refresh_subscription();+ }+}++void HoldingsTable::on_wallet_disconnected() {+ auto& hub = fincept::datahub::DataHub::instance();+ hub.unsubscribe(this);+ current_balance_topic_.clear();+ price_topic_.clear();+ price_usd_.clear();+ current_pubkey_.clear();+ latest_balance_ = {};+ rebuild_table();+}++void HoldingsTable::refresh_subscription() {+ auto& hub = fincept::datahub::DataHub::instance();+ if (!current_balance_topic_.isEmpty()) {+ hub.unsubscribe(this, current_balance_topic_);+ current_balance_topic_.clear();+ }+ if (current_pubkey_.isEmpty()) return;+ current_balance_topic_ = QStringLiteral("wallet:balance:%1").arg(current_pubkey_);+ hub.subscribe(this, current_balance_topic_,+ [this](const QVariant& v) { on_balance_update(v); });+ hub.request(current_balance_topic_, /*force=*/true);+}++void HoldingsTable::on_balance_update(const QVariant& v) {+ if (!v.canConvert<fincept::wallet::WalletBalance>()) return;+ latest_balance_ = v.value<fincept::wallet::WalletBalance>();+ resubscribe_prices();+ rebuild_table();+}++void HoldingsTable::resubscribe_prices() {+ auto& hub = fincept::datahub::DataHub::instance();++ // Build the desired set of mints (SOL + every held token).+ QSet<QString> wanted;+ wanted.insert(QString::fromLatin1(fincept::wallet::kWrappedSolMint));+ for (const auto& t : latest_balance_.tokens) {+ if (!t.mint.isEmpty()) wanted.insert(t.mint);+ }++ // Unsubscribe from mints we no longer hold.+ for (auto it = price_topic_.begin(); it != price_topic_.end();) {+ if (!wanted.contains(it.key())) {+ hub.unsubscribe(this, it.value());+ price_usd_.remove(it.key());+ it = price_topic_.erase(it);+ } else {+ ++it;+ }+ }++ // Subscribe to anything new.+ for (const auto& mint : wanted) {+ if (price_topic_.contains(mint)) continue;+ const auto topic = QStringLiteral("market:price:token:%1").arg(mint);+ price_topic_.insert(mint, topic);+ hub.subscribe(this, topic, [this, mint](const QVariant& v) {+ on_price_update(mint, v);+ });+ hub.request(topic, /*force=*/true);+ }+}++void HoldingsTable::on_price_update(const QString& mint, const QVariant& v) {+ if (!v.canConvert<fincept::wallet::TokenPrice>()) return;+ const auto p = v.value<fincept::wallet::TokenPrice>();+ if (!p.valid) return;+ price_usd_[mint] = p.usd;+ rebuild_table();+}++void HoldingsTable::on_metadata_changed() {+ // Symbols/icons may have flipped from truncated-mint to canonical;+ // rebuild so the cells show the right labels.+ rebuild_table();+}++void HoldingsTable::on_show_all_clicked() {+ show_unverified_ = !show_unverified_;+ SecureStorage::instance().store(+ QStringLiteral("wallet.show_unverified_tokens"),+ show_unverified_ ? QStringLiteral("true") : QStringLiteral("false"));+ show_all_button_->setText(show_unverified_ ? tr("Hide unverified")+ : tr("Show all"));+ rebuild_table();+}++void HoldingsTable::rebuild_table() {+ // Build the unified rows list: one synthetic SOL row + each TokenHolding,+ // optionally filtered by verified + sorted by USD value desc.+ struct Row {+ QString mint;+ QString symbol;+ double ui_amount;+ double usd_price;+ double usd_value;+ bool verified;+ };+ QVector<Row> rows;+ rows.reserve(latest_balance_.tokens.size() + 1);++ if (latest_balance_.sol_lamports > 0) {+ Row r;+ r.mint = QString::fromLatin1(fincept::wallet::kWrappedSolMint);+ r.symbol = QStringLiteral("SOL");+ r.ui_amount = latest_balance_.sol();+ r.usd_price = price_usd_.value(r.mint, -1.0);+ r.usd_value = (r.usd_price >= 0.0) ? r.ui_amount * r.usd_price : -1.0;+ r.verified = true;+ rows.append(std::move(r));+ }+ for (const auto& t : latest_balance_.tokens) {+ if (!show_unverified_ && !t.verified) continue;+ Row r;+ r.mint = t.mint;+ r.symbol = t.symbol.isEmpty() ? t.mint.left(10) : t.symbol;+ r.ui_amount = t.ui_amount();+ r.usd_price = price_usd_.value(t.mint, -1.0);+ r.usd_value = (r.usd_price >= 0.0) ? r.ui_amount * r.usd_price : -1.0;+ r.verified = t.verified;+ rows.append(std::move(r));+ }++ // Sort: known USD value desc; unknown to bottom alphabetically by symbol.+ std::sort(rows.begin(), rows.end(), [](const Row& a, const Row& b) {+ if ((a.usd_value < 0.0) != (b.usd_value < 0.0)) return a.usd_value >= 0.0;+ if (a.usd_value != b.usd_value) return a.usd_value > b.usd_value;+ return a.symbol < b.symbol;+ });++ // Total = sum of priced rows only.+ double total = 0.0;+ int unpriced = 0;+ for (const auto& r : rows) {+ if (r.usd_value >= 0.0) total += r.usd_value;+ else ++unpriced;+ }++ table_->setRowCount(rows.size());+ for (int i = 0; i < rows.size(); ++i) {+ const auto& r = rows[i];+ // Column 0: TOKEN — symbol + verified-or-not hint+ auto* sym = new QTableWidgetItem(r.symbol);+ sym->setData(Qt::UserRole, r.mint);+ if (!r.verified) {+ sym->setToolTip(tr("Unverified mint: %1").arg(r.mint));+ }+ table_->setItem(i, 0, sym);+ // Column 1: BALANCE+ auto* bal = new QTableWidgetItem(format_amount(r.ui_amount, 4));+ bal->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ table_->setItem(i, 1, bal);+ // Column 2: PRICE+ auto* prc = new QTableWidgetItem(+ r.usd_price >= 0.0 ? format_price(r.usd_price) : QStringLiteral("—"));+ prc->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ table_->setItem(i, 2, prc);+ // Column 3: USD VALUE+ auto* val = new QTableWidgetItem(+ r.usd_value >= 0.0 ? format_usd(r.usd_value) : QStringLiteral("—"));+ val->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ table_->setItem(i, 3, val);+ // Column 4: % OF PORT+ const double pct = (total > 0.0 && r.usd_value >= 0.0)+ ? (100.0 * r.usd_value / total)+ : 0.0;+ auto* pctc = new QTableWidgetItem(+ r.usd_value >= 0.0 ? format_pct(pct) : QStringLiteral("—"));+ pctc->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ table_->setItem(i, 4, pctc);+ }++ // Footer summary: total + counts.+ int verified = 0, unverified_total = 0;+ for (const auto& t : latest_balance_.tokens) {+ if (t.verified) ++verified;+ else ++unverified_total;+ }+ if (latest_balance_.sol_lamports > 0) ++verified; // SOL is always verified+ QString footer_text = tr("TOTAL %1 · %2 verified")+ .arg(format_usd(total))+ .arg(verified);+ if (unverified_total > 0) {+ footer_text += tr(" · %1 unverified%2")+ .arg(unverified_total)+ .arg(show_unverified_ ? QString() : tr(" hidden"));+ }+ if (unpriced > 0) {+ footer_text += tr(" · %1 without price").arg(unpriced);+ }+ footer_->setText(footer_text);+}++void HoldingsTable::showEvent(QShowEvent* e) {+ QWidget::showEvent(e);+ if (!current_pubkey_.isEmpty()) {+ refresh_subscription();+ }+}++void HoldingsTable::hideEvent(QHideEvent* e) {+ QWidget::hideEvent(e);+ fincept::datahub::DataHub::instance().unsubscribe(this);+ current_balance_topic_.clear();+ price_topic_.clear();+}++} // namespace fincept::screens::panelsdiff --git a/fincept-qt/src/screens/crypto_center/panels/HoldingsTable.h b/fincept-qt/src/screens/crypto_center/panels/HoldingsTable.hnew file mode 100644index 000000000..39cd93557--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/panels/HoldingsTable.h@@ -0,0 +1,78 @@+#pragma once++#include "services/wallet/WalletTypes.h"++#include <QHash>+#include <QString>+#include <QVariant>+#include <QVector>+#include <QWidget>++class QHideEvent;+class QLabel;+class QPushButton;+class QShowEvent;+class QTableWidget;+class QTableWidgetItem;++namespace fincept::screens::panels {++/// Holdings table — replaces HomeTab's three stat boxes (Stage 2A.5).+///+/// Renders one row per asset the wallet holds:+/// TOKEN · BALANCE · PRICE · USD VALUE · % OF PORTFOLIO+///+/// Subscriptions (visibility-driven):+/// - wallet:balance:<pubkey> for the holdings list+/// - market:price:token:<mint> one per held mint, refreshed when+/// the holdings list changes+///+/// Spam-token policy (Phase 2 §2A.5 D.5.4): unverified tokens are hidden by+/// default. The "Show all" button toggles them in for the current session;+/// the persistent setting lives in SettingsTab.+class HoldingsTable : public QWidget {+ Q_OBJECT+ public:+ explicit HoldingsTable(QWidget* parent = nullptr);+ ~HoldingsTable() override;++ signals:+ /// Emitted when the user clicks a row. Payload is the SPL mint of the+ /// selected asset (or the wrapped-SOL mint for SOL). Wired to+ /// SwapPanel's FROM combo in 2A.5.10.+ void select_token(QString mint);++ protected:+ void showEvent(QShowEvent* e) override;+ void hideEvent(QHideEvent* e) override;++ private:+ void build_ui();+ void apply_theme();++ void on_wallet_connected(const QString& pubkey, const QString& label);+ void on_wallet_disconnected();+ void on_balance_update(const QVariant& v);+ void on_price_update(const QString& mint, const QVariant& v);+ void on_show_all_clicked();+ void on_metadata_changed();++ void resubscribe_prices();+ void refresh_subscription();+ void rebuild_table();++ // UI+ QTableWidget* table_ = nullptr;+ QLabel* footer_ = nullptr;+ QPushButton* show_all_button_ = nullptr;++ // State+ QString current_pubkey_;+ QString current_balance_topic_;+ fincept::wallet::WalletBalance latest_balance_;+ QHash<QString, double> price_usd_; ///< mint → USD price+ QHash<QString, QString> price_topic_; ///< mint → topic (so we can unsubscribe)+ bool show_unverified_ = false;+};++} // namespace fincept::screens::panelsdiff --git a/fincept-qt/src/screens/crypto_center/panels/SwapPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/SwapPanel.cppnew file mode 100644index 000000000..945c3d4cd--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/panels/SwapPanel.cpp@@ -0,0 +1,768 @@+#include "screens/crypto_center/panels/SwapPanel.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "screens/crypto_center/WalletActionConfirmDialog.h"+#include "screens/crypto_center/WalletActionSummary.h"+#include "services/wallet/PumpFunSwapService.h"+#include "services/wallet/SolanaRpcClient.h"+#include "services/wallet/WalletService.h"+#include "services/wallet/WalletTypes.h"+#include "storage/secure/SecureStorage.h"+#include "ui/theme/Theme.h"++#include <QComboBox>+#include <QDoubleValidator>+#include <QFrame>+#include <QHBoxLayout>+#include <QHideEvent>+#include <QLabel>+#include <QLineEdit>+#include <QLocale>+#include <QPointer>+#include <QPushButton>+#include <QShowEvent>+#include <QSignalBlocker>+#include <QTimer>+#include <QVBoxLayout>++namespace fincept::screens::panels {++namespace {++constexpr const char* kFncptMint = "9LUqJ5aQTjQiUCL93gi33LZcscUoSBJNhVCYpPzEpump";+constexpr int kDebounceMs = 250;+constexpr int kDefaultSlippageBps = 100;+constexpr int kMaxSlippageBps = 500;+constexpr double kDefaultPriorityFeeSol = 0.00005;+constexpr int kStatusPollMs = 1500;+constexpr int kStatusPollMaxAttempts = 40; // 60 s of polling++QString font_stack() {+ return QStringLiteral(+ "'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");+}++QString format_token(double v, int max_dp = 4) {+ if (v <= 0.0) return QStringLiteral("0");+ return QLocale::system().toString(v, 'f', max_dp);+}++QString format_bps(int bps) {+ return QStringLiteral("%1.%2%")+ .arg(bps / 100)+ .arg(bps % 100, 2, 10, QChar('0'));+}++} // namespace++SwapPanel::SwapPanel(QWidget* parent) : QWidget(parent) {+ setObjectName(QStringLiteral("swapPanel"));+ build_ui();+ apply_theme();++ debounce_timer_ = new QTimer(this);+ debounce_timer_->setSingleShot(true);+ debounce_timer_->setInterval(kDebounceMs);+ connect(debounce_timer_, &QTimer::timeout, this, &SwapPanel::recompute_estimate);++ auto& svc = fincept::wallet::WalletService::instance();+ connect(&svc, &fincept::wallet::WalletService::wallet_connected, this,+ &SwapPanel::on_wallet_connected);+ connect(&svc, &fincept::wallet::WalletService::wallet_disconnected, this,+ &SwapPanel::on_wallet_disconnected);++ auto& hub = fincept::datahub::DataHub::instance();+ connect(&hub, &fincept::datahub::DataHub::topic_error, this,+ &SwapPanel::on_topic_error);++ if (svc.is_connected()) {+ on_wallet_connected(svc.current_pubkey(), svc.state().label);+ } else {+ on_wallet_disconnected();+ }+}++SwapPanel::~SwapPanel() = default;++void SwapPanel::build_ui() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ auto* head = new QWidget(this);+ head->setObjectName(QStringLiteral("swapPanelHead"));+ head->setFixedHeight(34);+ auto* head_l = new QHBoxLayout(head);+ head_l->setContentsMargins(12, 0, 12, 0);+ head_l->setSpacing(8);+ auto* title = new QLabel(QStringLiteral("SWAP"), head);+ title->setObjectName(QStringLiteral("swapPanelTitle"));+ auto* head_status = new QLabel(QStringLiteral("via Jupiter"), head);+ head_status->setObjectName(QStringLiteral("swapPanelHeadStatus"));+ head_l->addWidget(title);+ head_l->addStretch();+ head_l->addWidget(head_status);+ root->addWidget(head);++ auto* body = new QWidget(this);+ body->setObjectName(QStringLiteral("swapPanelBody"));+ auto* bl = new QVBoxLayout(body);+ bl->setContentsMargins(14, 14, 14, 14);+ bl->setSpacing(10);++ // Mode (BUY $FNCPT / SELL $FNCPT)+ {+ auto* row = new QHBoxLayout;+ row->setSpacing(8);+ auto* lbl = new QLabel(QStringLiteral("DIRECTION"), body);+ lbl->setObjectName(QStringLiteral("swapPanelCaption"));+ mode_combo_ = new QComboBox(body);+ mode_combo_->setObjectName(QStringLiteral("swapPanelCombo"));+ mode_combo_->addItem(tr("BUY $FNCPT (SOL → $FNCPT)"));+ mode_combo_->addItem(tr("SELL $FNCPT ($FNCPT → SOL)"));+ mode_combo_->setFixedHeight(28);+ row->addWidget(lbl);+ row->addWidget(mode_combo_, 1);+ bl->addLayout(row);+ }++ // FROM amount+ {+ auto* row = new QHBoxLayout;+ row->setSpacing(6);+ auto* col_l = new QVBoxLayout;+ col_l->setSpacing(2);+ auto* cap = new QLabel(QStringLiteral("YOU PAY"), body);+ cap->setObjectName(QStringLiteral("swapPanelCaption"));+ col_l->addWidget(cap);+ amount_input_ = new QLineEdit(body);+ amount_input_->setObjectName(QStringLiteral("swapPanelInput"));+ amount_input_->setFixedHeight(34);+ amount_input_->setPlaceholderText(QStringLiteral("0.00"));+ auto* validator = new QDoubleValidator(0.0, 1e12, 9, this);+ validator->setNotation(QDoubleValidator::StandardNotation);+ amount_input_->setValidator(validator);+ col_l->addWidget(amount_input_);+ row->addLayout(col_l, 1);++ auto* col_t = new QVBoxLayout;+ col_t->setSpacing(2);+ auto* cap_t = new QLabel(QStringLiteral("TOKEN"), body);+ cap_t->setObjectName(QStringLiteral("swapPanelCaption"));+ col_t->addWidget(cap_t);+ in_token_label_ = new QLabel(QStringLiteral("SOL"), body);+ in_token_label_->setObjectName(QStringLiteral("swapPanelTokenChip"));+ in_token_label_->setFixedHeight(34);+ in_token_label_->setAlignment(Qt::AlignCenter);+ in_token_label_->setMinimumWidth(80);+ col_t->addWidget(in_token_label_);+ row->addLayout(col_t);++ max_button_ = new QPushButton(tr("MAX"), body);+ max_button_->setObjectName(QStringLiteral("swapPanelButton"));+ max_button_->setFixedHeight(34);+ max_button_->setCursor(Qt::PointingHandCursor);+ row->addWidget(max_button_);+ bl->addLayout(row);++ in_balance_label_ = new QLabel(tr("Balance: —"), body);+ in_balance_label_->setObjectName(QStringLiteral("swapPanelMeta"));+ bl->addWidget(in_balance_label_);+ }++ // TO (quoted)+ {+ auto* row = new QHBoxLayout;+ row->setSpacing(6);+ auto* col_l = new QVBoxLayout;+ col_l->setSpacing(2);+ auto* cap = new QLabel(QStringLiteral("YOU RECEIVE (EST.)"), body);+ cap->setObjectName(QStringLiteral("swapPanelCaption"));+ col_l->addWidget(cap);+ out_amount_label_ = new QLabel(QStringLiteral("—"), body);+ out_amount_label_->setObjectName(QStringLiteral("swapPanelOutAmount"));+ out_amount_label_->setFixedHeight(34);+ col_l->addWidget(out_amount_label_);+ row->addLayout(col_l, 1);++ auto* col_t = new QVBoxLayout;+ col_t->setSpacing(2);+ auto* cap_t = new QLabel(QStringLiteral("TOKEN"), body);+ cap_t->setObjectName(QStringLiteral("swapPanelCaption"));+ col_t->addWidget(cap_t);+ out_token_label_ = new QLabel(QStringLiteral("$FNCPT"), body);+ out_token_label_->setObjectName(QStringLiteral("swapPanelTokenChip"));+ out_token_label_->setFixedHeight(34);+ out_token_label_->setAlignment(Qt::AlignCenter);+ out_token_label_->setMinimumWidth(80);+ col_t->addWidget(out_token_label_);+ row->addLayout(col_t);+ bl->addLayout(row);+ }++ // Quote details (route, impact, slippage)+ {+ auto* details = new QFrame(body);+ details->setObjectName(QStringLiteral("swapPanelDetailsBlock"));+ auto* dl = new QVBoxLayout(details);+ dl->setContentsMargins(10, 8, 10, 8);+ dl->setSpacing(4);++ auto add_kv = [details, dl](const QString& cap, QLabel*& v) {+ auto* row = new QHBoxLayout;+ row->setSpacing(8);+ auto* k = new QLabel(cap, details);+ k->setObjectName(QStringLiteral("swapPanelCaption"));+ v = new QLabel(QStringLiteral("—"), details);+ v->setObjectName(QStringLiteral("swapPanelDetailValue"));+ row->addWidget(k);+ row->addStretch(1);+ row->addWidget(v);+ dl->addLayout(row);+ };+ add_kv(QStringLiteral("ROUTE"), route_label_);+ add_kv(QStringLiteral("PRICE IMPACT"), impact_label_);+ add_kv(QStringLiteral("MAX SLIPPAGE"), slippage_label_);+ bl->addWidget(details);+ }++ // Error strip+ error_strip_ = new QFrame(body);+ error_strip_->setObjectName(QStringLiteral("swapPanelErrorStrip"));+ auto* es_l = new QHBoxLayout(error_strip_);+ es_l->setContentsMargins(10, 6, 10, 6);+ es_l->setSpacing(8);+ auto* es_icon = new QLabel(QStringLiteral("!"), error_strip_);+ es_icon->setObjectName(QStringLiteral("swapPanelErrorIcon"));+ error_text_ = new QLabel(QString(), error_strip_);+ error_text_->setObjectName(QStringLiteral("swapPanelErrorText"));+ error_text_->setWordWrap(true);+ es_l->addWidget(es_icon);+ es_l->addWidget(error_text_, 1);+ error_strip_->hide();+ bl->addWidget(error_strip_);++ // Submit row+ {+ auto* row = new QHBoxLayout;+ row->setSpacing(8);+ status_label_ = new QLabel(tr("Quotes refresh as you type."), body);+ status_label_->setObjectName(QStringLiteral("swapPanelMeta"));+ swap_button_ = new QPushButton(tr("SWAP"), body);+ swap_button_->setObjectName(QStringLiteral("swapPanelPrimaryButton"));+ swap_button_->setFixedHeight(34);+ swap_button_->setCursor(Qt::PointingHandCursor);+ swap_button_->setEnabled(false);+ row->addWidget(status_label_, 1);+ row->addWidget(swap_button_);+ bl->addLayout(row);+ }++ bl->addStretch(1);+ root->addWidget(body, 1);++ connect(mode_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,+ &SwapPanel::on_mode_changed);+ connect(amount_input_, &QLineEdit::textEdited, this, &SwapPanel::on_amount_changed);+ connect(max_button_, &QPushButton::clicked, this, &SwapPanel::on_max_clicked);+ connect(swap_button_, &QPushButton::clicked, this, &SwapPanel::on_swap_clicked);+}++void SwapPanel::apply_theme() {+ using namespace ui::colors;+ const QString font = font_stack();++ const QString ss = QStringLiteral(+ "QWidget#swapPanel { background:%1; }"+ "QWidget#swapPanelHead { background:%2; border-bottom:1px solid %3; }"+ "QLabel#swapPanelTitle { color:%4; font-family:%5; font-size:11px;"+ " font-weight:700; letter-spacing:1.4px; background:transparent; }"+ "QLabel#swapPanelHeadStatus { color:%6; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QWidget#swapPanelBody { background:%1; }"+ "QLabel#swapPanelCaption { color:%6; font-family:%5; font-size:9px;"+ " font-weight:700; letter-spacing:1.4px; background:transparent; }"+ "QLabel#swapPanelMeta { color:%6; font-family:%5; font-size:10px;"+ " background:transparent; }"++ // Inputs+ "QLineEdit#swapPanelInput { background:%2; color:%7; border:1px solid %3;"+ " font-family:%5; font-size:16px; padding:0 8px; }"+ "QLineEdit#swapPanelInput:focus { border-color:%4; }"+ "QComboBox#swapPanelCombo { background:%2; color:%7; border:1px solid %3;"+ " font-family:%5; font-size:11px; padding:0 8px; }"+ "QComboBox#swapPanelCombo::drop-down { border:none; width:18px; }"++ // Token chip (read-only, looks like an inert pill)+ "QLabel#swapPanelTokenChip { background:%8; color:%4; border:1px solid %3;"+ " font-family:%5; font-size:13px; font-weight:700; letter-spacing:1.2px; }"++ // Out amount+ "QLabel#swapPanelOutAmount { background:%8; color:%7; border:1px solid %3;"+ " font-family:%5; font-size:16px; padding:0 8px; }"++ // Details block+ "QFrame#swapPanelDetailsBlock { background:%8; border:1px solid %3; }"+ "QLabel#swapPanelDetailValue { color:%7; font-family:%5; font-size:11px;"+ " background:transparent; }"++ // Error strip+ "QFrame#swapPanelErrorStrip { background:rgba(220,38,38,0.10);"+ " border:1px solid %9; }"+ "QLabel#swapPanelErrorIcon { color:%9; font-family:%5; font-size:13px;"+ " font-weight:700; background:transparent; }"+ "QLabel#swapPanelErrorText { color:%9; font-family:%5; font-size:11px;"+ " background:transparent; }"++ // Buttons+ "QPushButton#swapPanelButton { background:%8; color:%6; border:1px solid %3;"+ " font-family:%5; font-size:11px; font-weight:700; letter-spacing:1px;"+ " padding:0 14px; }"+ "QPushButton#swapPanelButton:hover { background:%10; color:%7; border-color:%11; }"+ "QPushButton#swapPanelPrimaryButton { background:rgba(217,119,6,0.10); color:%4;"+ " border:1px solid %12; font-family:%5; font-size:12px; font-weight:700;"+ " letter-spacing:1.5px; padding:0 18px; }"+ "QPushButton#swapPanelPrimaryButton:hover { background:%4; color:%1; }"+ "QPushButton#swapPanelPrimaryButton:disabled { background:%8; color:%6;"+ " border-color:%3; }"+ )+ .arg(BG_BASE(), // %1+ BG_SURFACE(), // %2+ BORDER_DIM(), // %3+ AMBER(), // %4+ font, // %5+ TEXT_TERTIARY(), // %6+ TEXT_PRIMARY(), // %7+ BG_RAISED(), // %8+ NEGATIVE()) // %9+ .arg(BG_HOVER(), // %10+ BORDER_BRIGHT(), // %11+ QStringLiteral("#78350f")); // %12 darker amber++ setStyleSheet(ss);+}++// ── Lifecycle ──────────────────────────────────────────────────────────────++void SwapPanel::on_wallet_connected(const QString& pubkey, const QString& /*label*/) {+ current_pubkey_ = pubkey;+ if (isVisible()) {+ auto& hub = fincept::datahub::DataHub::instance();+ if (current_balance_topic_.isEmpty()) {+ current_balance_topic_ = QStringLiteral("wallet:balance:%1").arg(pubkey);+ hub.subscribe(this, current_balance_topic_,+ [this](const QVariant& v) { on_balance_update(v); });+ hub.request(current_balance_topic_, /*force=*/true);+ }+ hub.subscribe(this, QStringLiteral("market:price:fncpt"),+ [this](const QVariant& v) { on_price_update(v); });+ hub.request(QStringLiteral("market:price:fncpt"), /*force=*/true);+ }+ set_busy(false);+ swap_button_->setEnabled(can_submit());+ update_inputs_from_balance();+}++void SwapPanel::on_wallet_disconnected() {+ auto& hub = fincept::datahub::DataHub::instance();+ hub.unsubscribe(this);+ current_balance_topic_.clear();+ current_pubkey_.clear();+ sol_balance_ = 0.0;+ fncpt_balance_ = 0.0;+ last_fncpt_usd_price_ = 0.0;+ in_balance_label_->setText(tr("Balance: —"));+ out_amount_label_->setText(QStringLiteral("—"));+ route_label_->setText(QStringLiteral("—"));+ impact_label_->setText(QStringLiteral("—"));+ swap_button_->setEnabled(false);+ status_label_->setText(tr("Connect a wallet to swap."));+ clear_error_strip();+ set_busy(false);+}++void SwapPanel::showEvent(QShowEvent* e) {+ QWidget::showEvent(e);+ auto& hub = fincept::datahub::DataHub::instance();+ if (!current_pubkey_.isEmpty() && current_balance_topic_.isEmpty()) {+ current_balance_topic_ = QStringLiteral("wallet:balance:%1").arg(current_pubkey_);+ hub.subscribe(this, current_balance_topic_,+ [this](const QVariant& v) { on_balance_update(v); });+ }+ hub.subscribe(this, QStringLiteral("market:price:fncpt"),+ [this](const QVariant& v) { on_price_update(v); });+ slippage_label_->setText(format_bps(slippage_bps()));+ route_label_->setText(QStringLiteral("PumpSwap (auto)"));+}++void SwapPanel::hideEvent(QHideEvent* e) {+ QWidget::hideEvent(e);+ auto& hub = fincept::datahub::DataHub::instance();+ // unsubscribe(this) detaches us from every topic in one call —+ // covers both the balance topic and market:price:fncpt.+ hub.unsubscribe(this);+ current_balance_topic_.clear();+ debounce_timer_->stop();+}++// ── State updates ──────────────────────────────────────────────────────────++void SwapPanel::on_balance_update(const QVariant& v) {+ if (!v.canConvert<fincept::wallet::WalletBalance>()) return;+ const auto bal = v.value<fincept::wallet::WalletBalance>();+ sol_balance_ = bal.sol();+ fncpt_balance_ = bal.fncpt_ui();+ fncpt_decimals_ = bal.fncpt_decimals();+ update_inputs_from_balance();+}++void SwapPanel::update_inputs_from_balance() {+ if (mode_ == Mode::BuyFncpt) {+ in_token_label_->setText(QStringLiteral("SOL"));+ out_token_label_->setText(QStringLiteral("$FNCPT"));+ in_balance_label_->setText(tr("Balance: %1 SOL").arg(format_token(sol_balance_, 4)));+ } else {+ in_token_label_->setText(QStringLiteral("$FNCPT"));+ out_token_label_->setText(QStringLiteral("SOL"));+ in_balance_label_->setText(+ tr("Balance: %1 $FNCPT").arg(format_token(fncpt_balance_, 2)));+ }+}++void SwapPanel::on_price_update(const QVariant& v) {+ if (!v.canConvert<fincept::wallet::FncptPrice>()) return;+ const auto p = v.value<fincept::wallet::FncptPrice>();+ if (!p.valid) return;+ last_fncpt_usd_price_ = p.usd;+ last_fncpt_sol_price_ = p.sol; // FNCPT denominated in SOL+ recompute_estimate();+}++void SwapPanel::on_topic_error(const QString& topic, const QString& error) {+ if (topic == QStringLiteral("market:price:fncpt")) {+ // Without a price we can't estimate output — disable submit and warn.+ show_error_strip(tr("Spot price unavailable: %1. Try again in a moment.")+ .arg(error));+ swap_button_->setEnabled(false);+ }+ // Balance errors handled by HoldingsBar / HomeTab; ignore here.+}++void SwapPanel::on_amount_changed(const QString& /*s*/) {+ // Debounce the local estimate recompute so we don't thrash on every+ // keystroke (mostly cosmetic — the math is cheap, but it gives the+ // user a chance to finish typing before we paint the output).+ debounce_timer_->start();+ out_amount_label_->setText(QStringLiteral("…"));+ swap_button_->setEnabled(false);+ clear_error_strip();+}++void SwapPanel::on_mode_changed(int idx) {+ mode_ = (idx == 0) ? Mode::BuyFncpt : Mode::SellFncpt;+ update_inputs_from_balance();+ debounce_timer_->start();+}++void SwapPanel::on_max_clicked() {+ const double bal = (mode_ == Mode::BuyFncpt) ? sol_balance_ : fncpt_balance_;+ if (bal <= 0.0) return;+ // Leave a small SOL reserve for fees. 0.005 SOL covers a swap + rent.+ const double safe = (mode_ == Mode::BuyFncpt) ? std::max(0.0, bal - 0.005) : bal;+ QSignalBlocker b(amount_input_);+ amount_input_->setText(format_token(safe, 6));+ on_amount_changed(amount_input_->text());+}++void SwapPanel::recompute_estimate() {+ bool ok = false;+ const double ui_amount = QLocale::system().toDouble(amount_input_->text(), &ok);+ if (!ok || ui_amount <= 0.0) {+ out_amount_label_->setText(QStringLiteral("—"));+ swap_button_->setEnabled(false);+ return;+ }+ if (last_fncpt_sol_price_ <= 0.0 || last_fncpt_usd_price_ <= 0.0) {+ out_amount_label_->setText(QStringLiteral("…"));+ status_label_->setText(tr("Waiting for spot price…"));+ swap_button_->setEnabled(false);+ return;+ }++ // Local estimate from spot. PumpPortal returns the exact output at+ // build_swap time; this is just the user-facing preview.+ //+ // Spot inputs:+ // last_fncpt_usd_price_ = USD per 1 FNCPT+ // last_fncpt_sol_price_ = SOL per 1 FNCPT+ //+ // BUY (SOL → FNCPT): user types SOL_in+ // est_fncpt_out = SOL_in / SOL_per_FNCPT+ // SELL (FNCPT → SOL): user types FNCPT_in+ // est_sol_out = FNCPT_in * SOL_per_FNCPT+ //+ // Slippage is the user-set lower bound on what they'll accept; show the+ // worst-case to set expectations correctly.+ const double slippage_factor = 1.0 - (slippage_pct() / 100.0);+ QString out_text;+ if (mode_ == Mode::BuyFncpt) {+ const double est_fncpt = (ui_amount / last_fncpt_sol_price_) * slippage_factor;+ const double est_usd = ui_amount * last_fncpt_usd_price_ / last_fncpt_sol_price_;+ out_text = QStringLiteral("≈ %1 $FNCPT (~$%2)")+ .arg(format_token(est_fncpt, 2))+ .arg(format_token(est_usd, 2));+ } else {+ const double est_sol = ui_amount * last_fncpt_sol_price_ * slippage_factor;+ const double est_usd = ui_amount * last_fncpt_usd_price_;+ out_text = QStringLiteral("≈ %1 SOL (~$%2)")+ .arg(format_token(est_sol, 6))+ .arg(format_token(est_usd, 2));+ }+ out_amount_label_->setText(out_text);+ route_label_->setText(QStringLiteral("PumpSwap (auto)"));+ impact_label_->setText(tr("set by PumpSwap; capped by slippage"));+ slippage_label_->setText(format_bps(slippage_bps()));+ status_label_->setText(tr("Ready. Click SWAP to build the transaction."));+ clear_error_strip();+ swap_button_->setEnabled(can_submit());+}++void SwapPanel::show_error_strip(const QString& msg) {+ if (!error_strip_) return;+ error_text_->setText(msg);+ error_strip_->show();+}++void SwapPanel::clear_error_strip() {+ if (error_strip_ && error_strip_->isVisible()) {+ error_strip_->hide();+ error_text_->clear();+ }+}++void SwapPanel::set_busy(bool busy) {+ busy_ = busy;+ amount_input_->setEnabled(!busy);+ mode_combo_->setEnabled(!busy);+ max_button_->setEnabled(!busy);+ swap_button_->setEnabled(!busy && can_submit());+}++bool SwapPanel::can_submit() const {+ if (busy_) return false;+ if (current_pubkey_.isEmpty()) return false;+ if (last_fncpt_sol_price_ <= 0.0) return false;+ if (last_fncpt_usd_price_ <= 0.0) return false;+ bool ok = false;+ const double ui_amount = QLocale::system().toDouble(amount_input_->text(), &ok);+ if (!ok || ui_amount <= 0.0) return false;+ // Don't let the user buy/sell more than they have. PumpPortal would+ // reject the tx anyway; this is the friendlier early-exit.+ const double bal = (mode_ == Mode::BuyFncpt) ? sol_balance_ : fncpt_balance_;+ if (ui_amount > bal) return false;+ return true;+}++int SwapPanel::slippage_bps() const {+ auto r = SecureStorage::instance().retrieve(QStringLiteral("wallet.default_slippage_bps"));+ if (r.is_ok()) {+ bool ok = false;+ const auto v = r.value().toInt(&ok);+ if (ok && v >= 10 && v <= kMaxSlippageBps) return v;+ }+ return kDefaultSlippageBps;+}++int SwapPanel::slippage_pct() const {+ // PumpPortal expects integer percent; round up so we never under-tolerate.+ const int bps = slippage_bps();+ int pct = (bps + 99) / 100;+ if (pct < 1) pct = 1;+ if (pct > 5) pct = 5;+ return pct;+}++// ── Submit flow ────────────────────────────────────────────────────────────++void SwapPanel::on_swap_clicked() {+ if (!can_submit()) return;+ auto* svc = fincept::wallet::WalletService::instance().swap_service();+ if (!svc) {+ show_error_strip(tr("Swap service unavailable."));+ return;+ }+ bool ok = false;+ const double ui_amount = QLocale::system().toDouble(amount_input_->text(), &ok);+ if (!ok || ui_amount <= 0.0) return;++ const auto pubkey = current_pubkey_;+ const int slip_pct = slippage_pct();+ const int slip_bps_for_display = slippage_bps();+ const auto action = (mode_ == Mode::BuyFncpt)+ ? fincept::wallet::PumpFunSwapService::Action::Buy+ : fincept::wallet::PumpFunSwapService::Action::Sell;+ // BUY: amount is in SOL (denominatedInSol=true).+ // SELL: amount is in FNCPT (denominatedInSol=false).+ const bool denom_in_sol = (mode_ == Mode::BuyFncpt);++ // Build the user-facing summary from local estimate. PumpPortal will+ // produce the canonical numbers when build_swap returns; the wallet+ // shows the decoded transaction independently. Confirm dialog values+ // here are the panel's expectation; mismatches with PumpPortal's+ // result would be visible in the wallet popup.+ WalletActionSummary summary;+ summary.title = QStringLiteral("SWAP");+ summary.lede = tr("Approve in your wallet to forward this transaction "+ "to the network. The terminal does not hold any funds.");+ if (mode_ == Mode::BuyFncpt) {+ const double est_fncpt = ui_amount / last_fncpt_sol_price_;+ summary.rows.append({QStringLiteral("ROUTE"),+ QStringLiteral("PumpSwap (pool=auto)"), true});+ summary.rows.append({QStringLiteral("YOU PAY"),+ QStringLiteral("%1 SOL").arg(format_token(ui_amount, 6)),+ true});+ summary.rows.append({QStringLiteral("YOU RECEIVE"),+ tr("≈ %1 $FNCPT (PumpSwap fills at execution)")+ .arg(format_token(est_fncpt, 2)),+ true});+ } else {+ const double est_sol = ui_amount * last_fncpt_sol_price_;+ summary.rows.append({QStringLiteral("ROUTE"),+ QStringLiteral("PumpSwap (pool=auto)"), true});+ summary.rows.append({QStringLiteral("YOU PAY"),+ QStringLiteral("%1 $FNCPT").arg(format_token(ui_amount, 2)),+ true});+ summary.rows.append({QStringLiteral("YOU RECEIVE"),+ tr("≈ %1 SOL (PumpSwap fills at execution)")+ .arg(format_token(est_sol, 6)),+ true});+ }+ summary.rows.append({QStringLiteral("MAX SLIPPAGE"),+ format_bps(slip_bps_for_display), true});+ summary.rows.append({QStringLiteral("PRIORITY FEE"),+ QStringLiteral("%1 SOL")+ .arg(format_token(kDefaultPriorityFeeSol, 6)),+ true});+ summary.warnings.append(+ tr("PumpSwap will reject the trade if execution drifts more than "+ "the slippage tolerance above. Your funds stay in your wallet."));+ summary.primary_button_text = QStringLiteral("SWAP");+ summary.primary_is_safe = true;+ summary.arm_delay_ms = 1500;++ auto* dlg = new WalletActionConfirmDialog(summary, this);+ QPointer<SwapPanel> self = this;+ connect(dlg, &WalletActionConfirmDialog::confirmed, this,+ [self, svc, pubkey, ui_amount, action, denom_in_sol, slip_pct]() {+ if (!self) return;+ self->set_busy(true);+ self->status_label_->setText(self->tr("Building swap transaction…"));++ QPointer<SwapPanel> guard = self;+ svc->build_swap(action,+ QString::fromLatin1(kFncptMint),+ ui_amount,+ denom_in_sol,+ pubkey,+ slip_pct,+ kDefaultPriorityFeeSol,+ [guard](Result<fincept::wallet::PumpFunSwapService::SwapTransaction> r) {+ if (!guard) return;+ if (r.is_err()) {+ guard->set_busy(false);+ guard->show_error_strip(+ QObject::tr("build_swap failed: %1")+ .arg(QString::fromStdString(r.error())));+ guard->status_label_->setText(QObject::tr("Failed."));+ return;+ }+ const auto tx = r.value();+ guard->status_label_->setText(QObject::tr("Awaiting wallet signature…"));+ fincept::wallet::WalletService::instance().sign_and_send(+ tx.tx_base64,+ QObject::tr("Sign swap"),+ QObject::tr("Approve the swap in your wallet to complete the trade."),+ guard,+ [guard](Result<QString> sr) {+ if (!guard) return;+ if (sr.is_err()) {+ guard->set_busy(false);+ guard->show_error_strip(+ QObject::tr("Signing failed: %1")+ .arg(QString::fromStdString(sr.error())));+ guard->status_label_->setText(QObject::tr("Cancelled."));+ return;+ }+ const auto sig = sr.value();+ guard->status_label_->setText(+ QObject::tr("Sent. Waiting for confirmation…"));+ LOG_INFO("SwapPanel", "submitted: " + sig);++ // Poll getSignatureStatuses until confirmed (or give up).+ auto* rpc = new fincept::wallet::SolanaRpcClient(guard);+ rpc->reload_endpoint();+ auto attempts = std::make_shared<int>(0);+ auto* poll_timer = new QTimer(guard);+ poll_timer->setInterval(kStatusPollMs);+ QPointer<SwapPanel> poll_guard = guard;+ QObject::connect(poll_timer, &QTimer::timeout, guard,+ [poll_guard, rpc, sig, attempts, poll_timer]() {+ if (!poll_guard) {+ poll_timer->stop();+ poll_timer->deleteLater();+ return;+ }+ if (++(*attempts) > kStatusPollMaxAttempts) {+ poll_timer->stop();+ poll_timer->deleteLater();+ poll_guard->set_busy(false);+ poll_guard->show_error_strip(+ QObject::tr("No confirmation after 60 s. Check Solscan."));+ poll_guard->status_label_->setText(QObject::tr("Timed out."));+ return;+ }+ rpc->get_signature_statuses(QStringList{sig},+ [poll_guard, sig, poll_timer](+ Result<std::vector<fincept::wallet::SolanaRpcClient::SignatureStatus>> r) {+ if (!poll_guard) return;+ if (r.is_err()) return; // transient — keep polling+ const auto& vec = r.value();+ if (vec.empty() || !vec[0].found) return;+ const auto& s = vec[0];+ if (!s.err.isEmpty()) {+ poll_timer->stop();+ poll_timer->deleteLater();+ poll_guard->set_busy(false);+ poll_guard->show_error_strip(+ QObject::tr("Tx failed on-chain: %1").arg(s.err));+ poll_guard->status_label_->setText(QObject::tr("Reverted."));+ return;+ }+ if (s.confirmation_status == QStringLiteral("confirmed")+ || s.confirmation_status == QStringLiteral("finalized")) {+ poll_timer->stop();+ poll_timer->deleteLater();+ poll_guard->set_busy(false);+ poll_guard->amount_input_->clear();+ poll_guard->out_amount_label_->setText(QStringLiteral("—"));+ poll_guard->status_label_->setText(+ QObject::tr("Confirmed: %1…").arg(sig.left(12)));+ fincept::wallet::WalletService::instance()+ .force_balance_refresh();+ }+ });+ });+ poll_timer->start();+ });+ });+ });+ connect(dlg, &WalletActionConfirmDialog::cancelled, this, [self]() {+ if (!self) return;+ self->status_label_->setText(self->tr("Cancelled."));+ });+ dlg->setAttribute(Qt::WA_DeleteOnClose);+ dlg->open();+}++} // namespace fincept::screens::panelsdiff --git a/fincept-qt/src/screens/crypto_center/panels/SwapPanel.h b/fincept-qt/src/screens/crypto_center/panels/SwapPanel.hnew file mode 100644index 000000000..90370e1c3--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/panels/SwapPanel.h@@ -0,0 +1,103 @@+#pragma once++#include "core/result/Result.h"++#include <QString>+#include <QVariant>+#include <QWidget>++class QComboBox;+class QFrame;+class QHideEvent;+class QLabel;+class QLineEdit;+class QPushButton;+class QShowEvent;+class QTimer;++namespace fincept::screens::panels {++/// SWAP panel inside the TRADE tab. Phase 2 rev 2 — PumpPortal-backed.+///+/// Flow:+/// 1. User edits the YOU PAY amount. The panel computes the **estimated+/// output** locally from the live `market:price:fncpt` spot times the+/// slippage budget. There is no quote-API round-trip — PumpPortal has+/// no quote endpoint, only "build me a tx now."+/// 2. User clicks SWAP → SwapPanel calls+/// `PumpFunSwapService::build_swap(action, mint, amount, …)` to+/// materialise the unsigned versioned tx body, then constructs a+/// `WalletActionConfirmDialog`. On Confirm, it forwards to+/// `WalletService::sign_and_send` and polls `getSignatureStatuses`+/// until `confirmed`.+///+/// Refuses to enable SWAP if there's no spot price yet or no wallet is+/// connected. All visual error reporting goes through the panel's own+/// error strip, not stderr or LOG_*.+class SwapPanel : public QWidget {+ Q_OBJECT+ public:+ explicit SwapPanel(QWidget* parent = nullptr);+ ~SwapPanel() override;++ protected:+ void showEvent(QShowEvent* e) override;+ void hideEvent(QHideEvent* e) override;++ private:+ enum class Mode { BuyFncpt, SellFncpt };++ void build_ui();+ void apply_theme();++ void on_wallet_connected(const QString& pubkey, const QString& label);+ void on_wallet_disconnected();+ void on_balance_update(const QVariant& v);+ void on_price_update(const QVariant& v);+ void on_topic_error(const QString& topic, const QString& error);+ void on_amount_changed(const QString& s);+ void on_mode_changed(int idx);+ void on_max_clicked();+ void on_swap_clicked();++ void update_inputs_from_balance();+ void recompute_estimate();+ void show_error_strip(const QString& msg);+ void clear_error_strip();+ void set_busy(bool busy);+ bool can_submit() const;+ int slippage_pct() const;+ int slippage_bps() const;++ // UI+ QComboBox* mode_combo_ = nullptr; // BUY $FNCPT / SELL $FNCPT+ QLineEdit* amount_input_ = nullptr;+ QPushButton* max_button_ = nullptr;+ QLabel* in_token_label_ = nullptr;+ QLabel* in_balance_label_ = nullptr;+ QLabel* out_amount_label_ = nullptr;+ QLabel* out_token_label_ = nullptr;+ QLabel* route_label_ = nullptr;+ QLabel* impact_label_ = nullptr;+ QLabel* slippage_label_ = nullptr;+ QFrame* error_strip_ = nullptr;+ QLabel* error_text_ = nullptr;+ QPushButton* swap_button_ = nullptr;+ QLabel* status_label_ = nullptr;++ // Debounce timer for amount input → quote topic switch.+ QTimer* debounce_timer_ = nullptr;++ // State+ QString current_pubkey_;+ QString current_balance_topic_;+ Mode mode_ = Mode::BuyFncpt;+ double sol_balance_ = 0.0;+ double fncpt_balance_ = 0.0;+ int fncpt_decimals_ = 6; // pump.fun default; refreshed on balance publish+ double last_fncpt_usd_price_ = 0.0; // refreshed on market:price:fncpt publish+ double last_fncpt_sol_price_ = 0.0; // FNCPT priced in SOL+ bool busy_ = false;+};++} // namespace fincept::screens::panelsdiff --git a/fincept-qt/src/screens/crypto_center/tabs/ActivityTab.cpp b/fincept-qt/src/screens/crypto_center/tabs/ActivityTab.cppnew file mode 100644index 000000000..02f8b5c36--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/tabs/ActivityTab.cpp@@ -0,0 +1,312 @@+#include "screens/crypto_center/tabs/ActivityTab.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "services/wallet/WalletService.h"+#include "services/wallet/WalletTypes.h"+#include "storage/secure/SecureStorage.h"+#include "ui/theme/Theme.h"++#include <QButtonGroup>+#include <QDateTime>+#include <QDesktopServices>+#include <QHBoxLayout>+#include <QHeaderView>+#include <QHideEvent>+#include <QLabel>+#include <QPushButton>+#include <QShowEvent>+#include <QTableWidget>+#include <QTableWidgetItem>+#include <QUrl>+#include <QVBoxLayout>++namespace fincept::screens {++namespace {++QString font_stack() {+ return QStringLiteral(+ "'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");+}++QString format_time(qint64 ts_ms) {+ if (ts_ms <= 0) return QStringLiteral("—");+ return QDateTime::fromMSecsSinceEpoch(ts_ms)+ .toString(QStringLiteral("yyyy-MM-dd HH:mm:ss"));+}++QString kind_label(fincept::wallet::ParsedActivity::Kind k) {+ using K = fincept::wallet::ParsedActivity::Kind;+ switch (k) {+ case K::Swap: return QStringLiteral("SWAP");+ case K::Receive: return QStringLiteral("RECEIVE");+ case K::Send: return QStringLiteral("SEND");+ case K::Other: return QStringLiteral("OTHER");+ }+ return QStringLiteral("OTHER");+}++QString shorten_sig(const QString& sig) {+ if (sig.size() < 14) return sig;+ return sig.left(8) + QStringLiteral("…") + sig.right(4);+}++} // namespace++ActivityTab::ActivityTab(QWidget* parent) : QWidget(parent) {+ setObjectName(QStringLiteral("activityTab"));+ build_ui();+ apply_theme();++ auto& svc = fincept::wallet::WalletService::instance();+ connect(&svc, &fincept::wallet::WalletService::wallet_connected, this,+ &ActivityTab::on_wallet_connected);+ connect(&svc, &fincept::wallet::WalletService::wallet_disconnected, this,+ &ActivityTab::on_wallet_disconnected);++ auto& hub = fincept::datahub::DataHub::instance();+ connect(&hub, &fincept::datahub::DataHub::topic_error, this,+ &ActivityTab::on_topic_error);++ if (svc.is_connected()) {+ on_wallet_connected(svc.current_pubkey(), svc.state().label);+ }+}++ActivityTab::~ActivityTab() = default;++void ActivityTab::build_ui() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(14, 14, 14, 14);+ root->setSpacing(10);++ // Filter chips row+ auto* chips_row = new QHBoxLayout;+ chips_row->setSpacing(6);+ auto make_chip = [this](const QString& text, bool checked = false) {+ auto* b = new QPushButton(text, this);+ b->setObjectName(QStringLiteral("activityTabChip"));+ b->setCheckable(true);+ b->setChecked(checked);+ b->setFixedHeight(24);+ b->setCursor(Qt::PointingHandCursor);+ return b;+ };+ filter_all_ = make_chip(tr("ALL"), true);+ filter_swap_ = make_chip(tr("SWAP"));+ filter_send_ = make_chip(tr("SEND"));+ filter_receive_ = make_chip(tr("RECEIVE"));+ filter_other_ = make_chip(tr("OTHER"));++ auto* group = new QButtonGroup(this);+ group->setExclusive(true);+ group->addButton(filter_all_);+ group->addButton(filter_swap_);+ group->addButton(filter_send_);+ group->addButton(filter_receive_);+ group->addButton(filter_other_);++ chips_row->addWidget(filter_all_);+ chips_row->addWidget(filter_swap_);+ chips_row->addWidget(filter_send_);+ chips_row->addWidget(filter_receive_);+ chips_row->addWidget(filter_other_);+ chips_row->addStretch(1);+ root->addLayout(chips_row);++ // Table+ table_ = new QTableWidget(this);+ table_->setObjectName(QStringLiteral("activityTabTable"));+ table_->setColumnCount(6);+ table_->setHorizontalHeaderLabels(+ {QStringLiteral("TIMESTAMP"), QStringLiteral("EVENT"),+ QStringLiteral("ASSET"), QStringLiteral("AMOUNT"),+ QStringLiteral("STATUS"), QStringLiteral("SIGNATURE")});+ table_->verticalHeader()->setVisible(false);+ table_->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);+ table_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);+ table_->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);+ table_->setSelectionBehavior(QAbstractItemView::SelectRows);+ table_->setSelectionMode(QAbstractItemView::SingleSelection);+ table_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ table_->setShowGrid(false);+ table_->setAlternatingRowColors(false);+ table_->setSortingEnabled(false);+ root->addWidget(table_, 1);++ // Footer hint+ footer_ = new QLabel(tr("No transactions yet."), this);+ footer_->setObjectName(QStringLiteral("activityTabFooter"));+ footer_->setWordWrap(true);+ root->addWidget(footer_);++ connect(filter_all_, &QPushButton::clicked, this, &ActivityTab::on_filter_changed);+ connect(filter_swap_, &QPushButton::clicked, this, &ActivityTab::on_filter_changed);+ connect(filter_send_, &QPushButton::clicked, this, &ActivityTab::on_filter_changed);+ connect(filter_receive_, &QPushButton::clicked, this, &ActivityTab::on_filter_changed);+ connect(filter_other_, &QPushButton::clicked, this, &ActivityTab::on_filter_changed);+ connect(table_, &QTableWidget::cellClicked, this, &ActivityTab::on_row_clicked);+}++void ActivityTab::apply_theme() {+ using namespace ui::colors;+ const QString font = font_stack();++ const QString ss = QStringLiteral(+ "QWidget#activityTab { background:%1; }"++ "QPushButton#activityTabChip { background:transparent; color:%2; border:1px solid %3;"+ " font-family:%4; font-size:10px; font-weight:700; letter-spacing:1.2px;"+ " padding:0 12px; }"+ "QPushButton#activityTabChip:hover { color:%5; border-color:%6; }"+ "QPushButton#activityTabChip:checked { background:rgba(217,119,6,0.12); color:%7;"+ " border-color:%7; }"++ "QTableWidget#activityTabTable { background:%1; color:%5; gridline-color:%3;"+ " border:1px solid %3; selection-background-color:%8; selection-color:%5;"+ " font-family:%4; font-size:11px; }"+ "QTableWidget#activityTabTable::item { padding:6px 10px; border-bottom:1px solid %3; }"+ "QHeaderView::section { background:%9; color:%2; padding:6px 10px;"+ " border:none; border-bottom:1px solid %3; font-family:%4;"+ " font-size:9px; font-weight:700; letter-spacing:1.4px; }"++ "QLabel#activityTabFooter { color:%2; font-family:%4; font-size:10px;"+ " background:transparent; }"+ )+ .arg(BG_BASE(), // %1+ TEXT_TERTIARY(), // %2+ BORDER_DIM(), // %3+ font, // %4+ TEXT_PRIMARY(), // %5+ BORDER_BRIGHT(), // %6+ AMBER(), // %7+ BG_HOVER(), // %8+ BG_RAISED()); // %9++ setStyleSheet(ss);+}++bool ActivityTab::helius_key_present() const {+ auto r = SecureStorage::instance().retrieve(+ QStringLiteral("solana.helius_api_key"));+ return r.is_ok() && !r.value().isEmpty();+}++void ActivityTab::on_wallet_connected(const QString& pubkey, const QString& /*label*/) {+ current_pubkey_ = pubkey;+ if (isVisible()) refresh_subscription();+}++void ActivityTab::on_wallet_disconnected() {+ auto& hub = fincept::datahub::DataHub::instance();+ hub.unsubscribe(this);+ current_topic_.clear();+ current_pubkey_.clear();+ latest_.clear();+ rebuild_table();+}++void ActivityTab::refresh_subscription() {+ auto& hub = fincept::datahub::DataHub::instance();+ if (!current_topic_.isEmpty()) {+ hub.unsubscribe(this, current_topic_);+ current_topic_.clear();+ }+ if (current_pubkey_.isEmpty()) return;+ current_topic_ = QStringLiteral("wallet:activity:%1").arg(current_pubkey_);+ hub.subscribe(this, current_topic_,+ [this](const QVariant& v) { on_activity_update(v); });+ hub.request(current_topic_, /*force=*/true);+}++void ActivityTab::on_activity_update(const QVariant& v) {+ if (v.canConvert<QVector<fincept::wallet::ParsedActivity>>()) {+ latest_ = v.value<QVector<fincept::wallet::ParsedActivity>>();+ rebuild_table();+ }+}++void ActivityTab::on_topic_error(const QString& topic, const QString& error) {+ if (topic == current_topic_) {+ footer_->setText(tr("Activity fetch failed: %1").arg(error));+ }+}++void ActivityTab::on_filter_changed() {+ rebuild_table();+}++void ActivityTab::on_row_clicked(int row, int /*column*/) {+ auto* it = table_->item(row, 0);+ if (!it) return;+ const auto sig = it->data(Qt::UserRole).toString();+ if (sig.isEmpty()) return;+ QDesktopServices::openUrl(QUrl(+ QStringLiteral("https://solscan.io/tx/%1").arg(sig)));+}++void ActivityTab::rebuild_table() {+ // Determine the active filter from which chip is checked.+ auto filter_ok = [this](Kind k) {+ if (filter_all_ && filter_all_->isChecked()) return true;+ if (k == Kind::Swap && filter_swap_->isChecked()) return true;+ if (k == Kind::Send && filter_send_->isChecked()) return true;+ if (k == Kind::Receive && filter_receive_->isChecked()) return true;+ if (k == Kind::Other && filter_other_->isChecked()) return true;+ return false;+ };++ QVector<Activity> filtered;+ filtered.reserve(latest_.size());+ for (const auto& a : latest_) {+ if (filter_ok(a.kind)) filtered.append(a);+ }++ table_->setRowCount(filtered.size());+ for (int i = 0; i < filtered.size(); ++i) {+ const auto& a = filtered[i];+ auto* ts = new QTableWidgetItem(format_time(a.ts_ms));+ ts->setData(Qt::UserRole, a.signature);+ table_->setItem(i, 0, ts);++ table_->setItem(i, 1, new QTableWidgetItem(kind_label(a.kind)));+ table_->setItem(i, 2, new QTableWidgetItem(+ a.asset.isEmpty() ? QStringLiteral("—") : a.asset));+ table_->setItem(i, 3, new QTableWidgetItem(+ a.amount_ui.isEmpty() ? QStringLiteral("—") : a.amount_ui));+ auto* status = new QTableWidgetItem(+ a.status.isEmpty() ? QStringLiteral("—") : a.status);+ table_->setItem(i, 4, status);+ auto* sig = new QTableWidgetItem(shorten_sig(a.signature));+ sig->setToolTip(a.signature);+ table_->setItem(i, 5, sig);+ }++ // Footer status — count + Helius hint when fallback path is in use.+ if (current_pubkey_.isEmpty()) {+ footer_->setText(tr("Connect a wallet to view activity."));+ } else if (latest_.isEmpty()) {+ footer_->setText(tr("No transactions yet."));+ } else {+ QString text = tr("%1 of %2 events").arg(filtered.size()).arg(latest_.size());+ if (!helius_key_present()) {+ text += tr(" · Add a Helius API key in Settings for parsed swap "+ "and transfer details.");+ }+ footer_->setText(text);+ }+}++void ActivityTab::showEvent(QShowEvent* e) {+ QWidget::showEvent(e);+ if (!current_pubkey_.isEmpty()) refresh_subscription();+}++void ActivityTab::hideEvent(QHideEvent* e) {+ QWidget::hideEvent(e);+ fincept::datahub::DataHub::instance().unsubscribe(this);+ current_topic_.clear();+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/tabs/ActivityTab.h b/fincept-qt/src/screens/crypto_center/tabs/ActivityTab.hnew file mode 100644index 000000000..29ff4b376--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/tabs/ActivityTab.h@@ -0,0 +1,75 @@+#pragma once++#include "services/wallet/WalletTypes.h"++#include <QString>+#include <QVariant>+#include <QVector>+#include <QWidget>++class QHideEvent;+class QLabel;+class QPushButton;+class QShowEvent;+class QTableWidget;++namespace fincept::screens {++/// ACTIVITY tab — last 50 parsed wallet operations (Phase 2 §2B).+///+/// Subscribes to `wallet:activity:<pubkey>` (visibility-driven, P3 + D3).+/// Renders a table with TIMESTAMP / EVENT / ASSET / AMOUNT / STATUS+/// columns. Filter chips (ALL / SWAP / SEND / RECEIVE / OTHER) narrow the+/// view client-side.+///+/// Whole-row click opens the transaction's signature in Solscan via the+/// system browser. No in-app explorer.+///+/// When no Helius API key is configured, the producer falls back to raw+/// signatures from the standard RPC and rows show only TIMESTAMP ++/// SIGNATURE + STATUS. The footer hints "Add a Helius key in Settings for+/// parsed activity".+class ActivityTab : public QWidget {+ Q_OBJECT+ public:+ explicit ActivityTab(QWidget* parent = nullptr);+ ~ActivityTab() override;++ protected:+ void showEvent(QShowEvent* e) override;+ void hideEvent(QHideEvent* e) override;++ private:+ using Activity = fincept::wallet::ParsedActivity;+ using Kind = Activity::Kind;++ void build_ui();+ void apply_theme();++ void on_wallet_connected(const QString& pubkey, const QString& label);+ void on_wallet_disconnected();+ void on_activity_update(const QVariant& v);+ void on_topic_error(const QString& topic, const QString& error);+ void on_filter_changed();+ void on_row_clicked(int row, int column);++ void refresh_subscription();+ void rebuild_table();+ bool helius_key_present() const;++ QTableWidget* table_ = nullptr;+ QLabel* footer_ = nullptr;+ QPushButton* filter_all_ = nullptr;+ QPushButton* filter_swap_ = nullptr;+ QPushButton* filter_send_ = nullptr;+ QPushButton* filter_receive_ = nullptr;+ QPushButton* filter_other_ = nullptr;++ QString current_pubkey_;+ QString current_topic_;+ QVector<Activity> latest_;+ Kind active_filter_kind_ = Kind::Other; // sentinel — `filter_all_` checked = no filter+ bool show_all_ = true;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/tabs/ComingSoonTab.cpp b/fincept-qt/src/screens/crypto_center/tabs/ComingSoonTab.cppnew file mode 100644index 000000000..89c97b3b5--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/tabs/ComingSoonTab.cpp@@ -0,0 +1,100 @@+#include "screens/crypto_center/tabs/ComingSoonTab.h"++#include "ui/theme/Theme.h"++#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QVBoxLayout>++namespace fincept::screens {++namespace {++QString cs_font_stack() {+ return QStringLiteral(+ "'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");+}++} // namespace++ComingSoonTab::ComingSoonTab(const QString& tab_name,+ const QString& phase_label,+ const QString& description,+ QWidget* parent)+ : QWidget(parent) {+ setObjectName(QStringLiteral("comingSoonTab"));++ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(14, 14, 14, 14);+ root->setSpacing(0);+ root->addStretch(1);++ auto* center_row = new QHBoxLayout;+ center_row->setSpacing(0);+ center_row->addStretch(1);++ auto* card = new QFrame(this);+ card->setObjectName(QStringLiteral("comingSoonCard"));+ card->setFixedWidth(460);+ auto* cl = new QVBoxLayout(card);+ cl->setContentsMargins(24, 22, 24, 22);+ cl->setSpacing(8);++ phase_label_ = new QLabel(phase_label.toUpper(), card);+ phase_label_->setObjectName(QStringLiteral("comingSoonPhase"));+ cl->addWidget(phase_label_);++ tab_name_label_ = new QLabel(tab_name.toUpper(), card);+ tab_name_label_->setObjectName(QStringLiteral("comingSoonTitle"));+ cl->addWidget(tab_name_label_);++ description_label_ = new QLabel(description, card);+ description_label_->setObjectName(QStringLiteral("comingSoonDescription"));+ description_label_->setWordWrap(true);+ cl->addWidget(description_label_);++ auto* status = new QLabel(QStringLiteral("STATUS · COMING SOON"), card);+ status->setObjectName(QStringLiteral("comingSoonStatus"));+ cl->addSpacing(6);+ cl->addWidget(status);++ center_row->addWidget(card);+ center_row->addStretch(1);+ root->addLayout(center_row);+ root->addStretch(2);++ apply_theme();+}++ComingSoonTab::~ComingSoonTab() = default;++void ComingSoonTab::apply_theme() {+ using namespace ui::colors;+ const QString font = cs_font_stack();++ const QString ss = QStringLiteral(+ "QWidget#comingSoonTab { background:%1; }"+ "QFrame#comingSoonCard { background:%2; border:1px solid %3; }"+ "QLabel#comingSoonPhase { color:%4; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.5px; background:transparent; }"+ "QLabel#comingSoonTitle { color:%6; font-family:%5; font-size:18px;"+ " font-weight:700; letter-spacing:1.4px; background:transparent; }"+ "QLabel#comingSoonDescription { color:%7; font-family:%5; font-size:12px;"+ " background:transparent; }"+ "QLabel#comingSoonStatus { color:%8; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ )+ .arg(BG_BASE(), // %1+ BG_SURFACE(), // %2+ BORDER_DIM(), // %3+ AMBER(), // %4+ font, // %5+ TEXT_PRIMARY(), // %6+ TEXT_SECONDARY(), // %7+ TEXT_TERTIARY()); // %8++ setStyleSheet(ss);+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/tabs/ComingSoonTab.h b/fincept-qt/src/screens/crypto_center/tabs/ComingSoonTab.hnew file mode 100644index 000000000..e6caf10cf--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/tabs/ComingSoonTab.h@@ -0,0 +1,33 @@+#pragma once++#include <QString>+#include <QWidget>++class QLabel;++namespace fincept::screens {++/// Lightweight placeholder tab — used for STAKE / MARKETS / ROADMAP slots+/// that ship in later phases. Renders the tab name, the phase label, and a+/// one-line description so users know what's coming and when.+///+/// Has no data subscriptions and no timers, so it's safe to construct+/// eagerly inside the tab widget.+class ComingSoonTab : public QWidget {+ Q_OBJECT+ public:+ explicit ComingSoonTab(const QString& tab_name,+ const QString& phase_label,+ const QString& description,+ QWidget* parent = nullptr);+ ~ComingSoonTab() override;++ private:+ void apply_theme();++ QLabel* tab_name_label_ = nullptr;+ QLabel* phase_label_ = nullptr;+ QLabel* description_label_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/tabs/HomeTab.cpp b/fincept-qt/src/screens/crypto_center/tabs/HomeTab.cppnew file mode 100644index 000000000..72c31e31a--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/tabs/HomeTab.cpp@@ -0,0 +1,428 @@+#include "screens/crypto_center/tabs/HomeTab.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "screens/crypto_center/panels/HoldingsTable.h"+#include "services/wallet/WalletService.h"+#include "services/wallet/WalletTypes.h"+#include "ui/theme/Theme.h"++#include <QApplication>+#include <QButtonGroup>+#include <QClipboard>+#include <QDateTime>+#include <QFrame>+#include <QHBoxLayout>+#include <QHideEvent>+#include <QLabel>+#include <QPushButton>+#include <QShowEvent>+#include <QSignalBlocker>+#include <QTimer>+#include <QVBoxLayout>++namespace fincept::screens {++namespace {++QString home_font_stack() {+ return QStringLiteral(+ "'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");+}++QString shorten_pubkey(const QString& pk) {+ if (pk.size() < 16) return pk;+ return pk.left(8) + QStringLiteral("…") + pk.right(8);+}++QString relative_time(qint64 ts_ms) {+ if (ts_ms == 0) return QStringLiteral("never");+ const auto delta = QDateTime::currentMSecsSinceEpoch() - ts_ms;+ if (delta < 0) return QStringLiteral("just now");+ const auto seconds = delta / 1000;+ if (seconds < 60) return QStringLiteral("%1s ago").arg(seconds);+ if (seconds < 3600) return QStringLiteral("%1m ago").arg(seconds / 60);+ if (seconds < 86400) return QStringLiteral("%1h ago").arg(seconds / 3600);+ return QStringLiteral("%1d ago").arg(seconds / 86400);+}++} // namespace++HomeTab::HomeTab(QWidget* parent) : QWidget(parent) {+ setObjectName(QStringLiteral("homeTab"));+ build_ui();+ apply_theme();++ auto& svc = fincept::wallet::WalletService::instance();+ connect(&svc, &fincept::wallet::WalletService::wallet_connected, this,+ &HomeTab::on_wallet_connected);+ connect(&svc, &fincept::wallet::WalletService::wallet_disconnected, this,+ &HomeTab::on_wallet_disconnected);+ connect(&svc, &fincept::wallet::WalletService::balance_mode_changed, this,+ &HomeTab::on_mode_changed);++ auto& hub = fincept::datahub::DataHub::instance();+ connect(&hub, &fincept::datahub::DataHub::topic_error, this,+ &HomeTab::on_topic_error);++ apply_mode_to_buttons(svc.balance_mode_is_stream());+ if (svc.is_connected()) {+ on_wallet_connected(svc.current_pubkey(), svc.state().label);+ }+}++HomeTab::~HomeTab() = default;++void HomeTab::build_ui() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(14, 14, 14, 14);+ root->setSpacing(10);++ auto* top_row = new QHBoxLayout;+ top_row->setSpacing(10);++ // ── Wallet panel ──────────────────────────────────────────────────────+ {+ wallet_panel_ = new QFrame(this);+ wallet_panel_->setObjectName(QStringLiteral("homeTabPanel"));+ auto* outer = new QVBoxLayout(wallet_panel_);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(0);++ auto* head = new QWidget(wallet_panel_);+ head->setObjectName(QStringLiteral("homeTabPanelHead"));+ head->setFixedHeight(34);+ auto* head_l = new QHBoxLayout(head);+ head_l->setContentsMargins(12, 0, 12, 0);+ head_l->setSpacing(0);+ auto* title = new QLabel(QStringLiteral("WALLET"), head);+ title->setObjectName(QStringLiteral("homeTabPanelTitle"));+ auto* status = new QLabel(QStringLiteral("● CONNECTED"), head);+ status->setObjectName(QStringLiteral("homeTabPanelStatusOk"));+ head_l->addWidget(title);+ head_l->addStretch();+ head_l->addWidget(status);+ outer->addWidget(head);++ auto* body = new QWidget(wallet_panel_);+ auto* body_l = new QVBoxLayout(body);+ body_l->setContentsMargins(0, 0, 0, 0);+ body_l->setSpacing(0);++ auto add_row = [body_l, body](const QString& caption, QLabel*& val_out,+ bool last) {+ auto* row = new QWidget(body);+ row->setObjectName(QStringLiteral("homeTabRow"));+ row->setProperty("isLast", last);+ row->setFixedHeight(32);+ auto* rl = new QHBoxLayout(row);+ rl->setContentsMargins(12, 0, 12, 0);+ rl->setSpacing(8);+ auto* cap = new QLabel(caption, row);+ cap->setObjectName(QStringLiteral("homeTabCaption"));+ val_out = new QLabel(QStringLiteral("—"), row);+ val_out->setObjectName(QStringLiteral("homeTabRowValue"));+ val_out->setTextInteractionFlags(Qt::TextSelectableByMouse);+ rl->addWidget(cap);+ rl->addStretch(1);+ rl->addWidget(val_out);+ body_l->addWidget(row);+ };+ add_row(QStringLiteral("PROVIDER"), row_label_value_, false);+ add_row(QStringLiteral("ADDRESS"), row_pubkey_value_, false);+ add_row(QStringLiteral("CONNECTED"), row_connected_value_, true);+ outer->addWidget(body);++ auto* btn_row = new QWidget(wallet_panel_);+ btn_row->setObjectName(QStringLiteral("homeTabPanelFoot"));+ btn_row->setFixedHeight(40);+ auto* br_l = new QHBoxLayout(btn_row);+ br_l->setContentsMargins(10, 6, 10, 6);+ br_l->setSpacing(6);+ copy_button_ = new QPushButton(tr("COPY ADDRESS"), btn_row);+ copy_button_->setObjectName(QStringLiteral("homeTabButton"));+ copy_button_->setFixedHeight(26);+ copy_button_->setCursor(Qt::PointingHandCursor);+ disconnect_button_ = new QPushButton(tr("DISCONNECT"), btn_row);+ disconnect_button_->setObjectName(QStringLiteral("homeTabDangerButton"));+ disconnect_button_->setFixedHeight(26);+ disconnect_button_->setCursor(Qt::PointingHandCursor);+ br_l->addWidget(copy_button_);+ br_l->addStretch(1);+ br_l->addWidget(disconnect_button_);+ outer->addWidget(btn_row);++ top_row->addWidget(wallet_panel_, 1);+ }++ // ── Holdings panel (replaces three stat boxes per Stage 2A.5) ─────────+ {+ balance_panel_ = new QFrame(this);+ balance_panel_->setObjectName(QStringLiteral("homeTabPanel"));+ auto* outer = new QVBoxLayout(balance_panel_);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(0);++ auto* head = new QWidget(balance_panel_);+ head->setObjectName(QStringLiteral("homeTabPanelHead"));+ head->setFixedHeight(34);+ auto* head_l = new QHBoxLayout(head);+ head_l->setContentsMargins(12, 0, 12, 0);+ head_l->setSpacing(8);+ auto* title = new QLabel(QStringLiteral("HOLDINGS"), head);+ title->setObjectName(QStringLiteral("homeTabPanelTitle"));++ // Mode toggle — mirrored from Settings.+ mode_poll_button_ = new QPushButton(QStringLiteral("POLL"), head);+ mode_poll_button_->setObjectName(QStringLiteral("homeTabToggle"));+ mode_poll_button_->setCheckable(true);+ mode_poll_button_->setFixedHeight(22);+ mode_poll_button_->setCursor(Qt::PointingHandCursor);+ mode_stream_button_ = new QPushButton(QStringLiteral("STREAM"), head);+ mode_stream_button_->setObjectName(QStringLiteral("homeTabToggle"));+ mode_stream_button_->setCheckable(true);+ mode_stream_button_->setFixedHeight(22);+ mode_stream_button_->setCursor(Qt::PointingHandCursor);+ mode_group_ = new QButtonGroup(this);+ mode_group_->setExclusive(true);+ mode_group_->addButton(mode_poll_button_);+ mode_group_->addButton(mode_stream_button_);++ auto* mode_label = new QLabel(QStringLiteral("MAINNET"), head);+ mode_label->setObjectName(QStringLiteral("homeTabPanelStatus"));++ head_l->addWidget(title);+ head_l->addStretch();+ head_l->addWidget(mode_poll_button_);+ head_l->addWidget(mode_stream_button_);+ head_l->addSpacing(6);+ head_l->addWidget(mode_label);+ outer->addWidget(head);++ // Body wraps the embedded HoldingsTable + an error strip.+ auto* body = new QWidget(balance_panel_);+ auto* body_l = new QVBoxLayout(body);+ body_l->setContentsMargins(0, 0, 0, 0);+ body_l->setSpacing(0);++ holdings_table_ = new panels::HoldingsTable(body);+ holdings_table_->setMinimumHeight(220);+ connect(holdings_table_, &panels::HoldingsTable::select_token, this,+ [this](const QString& mint) { emit select_token(mint); });+ body_l->addWidget(holdings_table_, 1);++ // Tab-local error strip (hidden by default).+ error_strip_ = new QFrame(body);+ error_strip_->setObjectName(QStringLiteral("homeTabErrorStrip"));+ auto* es_l = new QHBoxLayout(error_strip_);+ es_l->setContentsMargins(10, 6, 10, 6);+ es_l->setSpacing(8);+ auto* es_icon = new QLabel(QStringLiteral("!"), error_strip_);+ es_icon->setObjectName(QStringLiteral("homeTabErrorIcon"));+ error_strip_text_ = new QLabel(QString(), error_strip_);+ error_strip_text_->setObjectName(QStringLiteral("homeTabErrorText"));+ error_strip_text_->setWordWrap(true);+ es_l->addWidget(es_icon);+ es_l->addWidget(error_strip_text_, 1);+ error_strip_->hide();+ body_l->addWidget(error_strip_);+ outer->addWidget(body, 1);++ // Foot: REFRESH button.+ auto* foot = new QWidget(balance_panel_);+ foot->setObjectName(QStringLiteral("homeTabPanelFoot"));+ foot->setFixedHeight(40);+ auto* fl = new QHBoxLayout(foot);+ fl->setContentsMargins(10, 6, 10, 6);+ fl->setSpacing(6);+ fl->addStretch(1);+ refresh_button_ = new QPushButton(tr("REFRESH"), foot);+ refresh_button_->setObjectName(QStringLiteral("homeTabButton"));+ refresh_button_->setFixedHeight(26);+ refresh_button_->setCursor(Qt::PointingHandCursor);+ fl->addWidget(refresh_button_);+ outer->addWidget(foot);++ top_row->addWidget(balance_panel_, 2);+ }++ root->addLayout(top_row);++ // ── Roadmap panel ─────────────────────────────────────────────────────+ {+ roadmap_panel_ = new QFrame(this);+ roadmap_panel_->setObjectName(QStringLiteral("homeTabPanel"));+ auto* outer = new QVBoxLayout(roadmap_panel_);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(0);++ auto* head = new QWidget(roadmap_panel_);+ head->setObjectName(QStringLiteral("homeTabPanelHead"));+ head->setFixedHeight(34);+ auto* head_l = new QHBoxLayout(head);+ head_l->setContentsMargins(12, 0, 12, 0);+ head_l->setSpacing(0);+ auto* title = new QLabel(QStringLiteral("$FNCPT ROADMAP"), head);+ title->setObjectName(QStringLiteral("homeTabPanelTitle"));+ auto* phase = new QLabel(QStringLiteral("PHASE 2"), head);+ phase->setObjectName(QStringLiteral("homeTabPanelStatus"));+ head_l->addWidget(title);+ head_l->addStretch();+ head_l->addWidget(phase);+ outer->addWidget(head);++ roadmap_body_ = new QLabel(+ QStringLiteral("PHASE 1 WALLET & BALANCE SHIPPED connect Solana wallet, view $FNCPT + SOL\n"+ "PHASE 2 SWAP & FEE DISCOUNT IN PROGRESS buy $FNCPT via PumpPortal, fee discount\n"+ "PHASE 3 STAKING & TIERS UPCOMING lock $FNCPT for bronze / silver / gold tiers\n"+ "PHASE 4 PREDICTION MARKETS UPCOMING earnings, fed, weather — settled in $FNCPT\n"+ "PHASE 5 BUYBACK & BURN UPCOMING terminal revenue auto-buys & burns $FNCPT"),+ roadmap_panel_);+ roadmap_body_->setObjectName(QStringLiteral("homeTabRoadmapBody"));+ roadmap_body_->setContentsMargins(14, 12, 14, 14);+ outer->addWidget(roadmap_body_);+ }+ root->addWidget(roadmap_panel_);+ root->addStretch(1);++ // Wiring+ connect(copy_button_, &QPushButton::clicked, this, [this]() {+ QApplication::clipboard()->setText(current_pubkey_);+ copy_button_->setText(tr("COPIED"));+ QTimer::singleShot(1200, this, [this]() {+ if (copy_button_) copy_button_->setText(tr("COPY ADDRESS"));+ });+ });+ connect(disconnect_button_, &QPushButton::clicked, this, []() {+ fincept::wallet::WalletService::instance().disconnect();+ });+ connect(refresh_button_, &QPushButton::clicked, this, [this]() {+ if (current_pubkey_.isEmpty()) return;+ clear_error_strip();+ fincept::wallet::WalletService::instance().force_balance_refresh();+ });+ connect(mode_poll_button_, &QPushButton::toggled, this, [](bool checked) {+ if (!checked) return;+ fincept::wallet::WalletService::instance().set_balance_mode(false);+ });+ connect(mode_stream_button_, &QPushButton::toggled, this, [](bool checked) {+ if (!checked) return;+ fincept::wallet::WalletService::instance().set_balance_mode(true);+ });+}++void HomeTab::apply_theme() {+ using namespace ui::colors;+ const QString font = home_font_stack();++ const QString ss = QStringLiteral(+ "QWidget#homeTab { background:%1; }"+ "QFrame#homeTabPanel { background:%2; border:1px solid %3; }"+ "QWidget#homeTabPanelHead { background:%10; border-bottom:1px solid %3; }"+ "QWidget#homeTabPanelFoot { background:%10; border-top:1px solid %3; }"+ "QLabel#homeTabPanelTitle { color:%4; font-family:%5; font-size:11px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QLabel#homeTabPanelStatus { color:%6; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QLabel#homeTabPanelStatusOk { color:%9; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QWidget#homeTabRow { background:transparent; border-bottom:1px solid %3; }"+ "QWidget#homeTabRow[isLast=\"true\"] { border-bottom:none; }"+ "QLabel#homeTabCaption { color:%7; font-family:%5; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QLabel#homeTabRowValue { color:%8; font-family:%5; font-size:12px;"+ " background:transparent; }"+ "QFrame#homeTabErrorStrip { background:rgba(220,38,38,0.10);"+ " border:1px solid %11; }"+ "QLabel#homeTabErrorIcon { color:%11; font-family:%5; font-size:13px;"+ " font-weight:700; background:transparent; }"+ "QLabel#homeTabErrorText { color:%11; font-family:%5; font-size:11px;"+ " background:transparent; }"+ "QPushButton#homeTabButton { background:%10; color:%7; border:1px solid %3;"+ " font-family:%5; font-size:11px; font-weight:700; letter-spacing:1px; padding:0 12px; }"+ "QPushButton#homeTabButton:hover { background:%12; color:%8; border-color:%13; }"+ "QPushButton#homeTabDangerButton { background:rgba(220,38,38,0.10); color:%11;"+ " border:1px solid %14; font-family:%5; font-size:11px; font-weight:700;"+ " letter-spacing:1px; padding:0 12px; }"+ "QPushButton#homeTabDangerButton:hover { background:%11; color:%8; }"+ "QPushButton#homeTabToggle { background:transparent; color:%6; border:1px solid %3;"+ " font-family:%5; font-size:10px; font-weight:700; letter-spacing:1.2px;"+ " padding:0 10px; }"+ "QPushButton#homeTabToggle:hover { color:%8; border-color:%13; }"+ "QPushButton#homeTabToggle:checked { background:rgba(217,119,6,0.12); color:%4;"+ " border-color:%4; }"+ "QLabel#homeTabRoadmapBody { color:%7; font-family:%5; font-size:11px;"+ " background:transparent; }"+ )+ .arg(BG_BASE(), BG_SURFACE(), BORDER_DIM(), AMBER(), font,+ TEXT_TERTIARY(), TEXT_SECONDARY(), TEXT_PRIMARY(), POSITIVE())+ .arg(BG_RAISED(), NEGATIVE(), BG_HOVER(), BORDER_BRIGHT(),+ QStringLiteral("#7f1d1d"));++ setStyleSheet(ss);+}++void HomeTab::on_wallet_connected(const QString& pubkey, const QString& label) {+ current_pubkey_ = pubkey;+ row_label_value_->setText(label.isEmpty() ? tr("Solana wallet") : label.toUpper());+ row_pubkey_value_->setText(shorten_pubkey(pubkey));+ row_pubkey_value_->setToolTip(pubkey);+ const auto& s = fincept::wallet::WalletService::instance().state();+ if (s.connected_at_ms > 0) {+ row_connected_value_->setText(relative_time(s.connected_at_ms));+ } else {+ row_connected_value_->setText(tr("restored from storage"));+ }+ clear_error_strip();+}++void HomeTab::on_wallet_disconnected() {+ current_pubkey_.clear();+ row_label_value_->setText(QStringLiteral("—"));+ row_pubkey_value_->setText(QStringLiteral("—"));+ row_connected_value_->setText(QStringLiteral("—"));+ clear_error_strip();+}++void HomeTab::on_mode_changed(bool is_stream) {+ apply_mode_to_buttons(is_stream);+ if (current_pubkey_.isEmpty()) return;+ clear_error_strip();+}++void HomeTab::on_topic_error(const QString& topic, const QString& error) {+ if (topic.startsWith(QStringLiteral("wallet:balance:"))) {+ show_error_strip(tr("Balance fetch failed: %1").arg(error));+ }+}++void HomeTab::clear_error_strip() {+ if (error_strip_ && error_strip_->isVisible()) {+ error_strip_->hide();+ error_strip_text_->clear();+ }+}++void HomeTab::show_error_strip(const QString& msg) {+ if (!error_strip_) return;+ error_strip_text_->setText(msg);+ error_strip_->show();+}++void HomeTab::apply_mode_to_buttons(bool is_stream) {+ QSignalBlocker b1(mode_poll_button_);+ QSignalBlocker b2(mode_stream_button_);+ mode_poll_button_->setChecked(!is_stream);+ mode_stream_button_->setChecked(is_stream);+}++void HomeTab::showEvent(QShowEvent* e) {+ QWidget::showEvent(e);+ // HoldingsTable manages its own subscriptions; nothing else to do here.+}++void HomeTab::hideEvent(QHideEvent* e) {+ QWidget::hideEvent(e);+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/tabs/HomeTab.h b/fincept-qt/src/screens/crypto_center/tabs/HomeTab.hnew file mode 100644index 000000000..51510e817--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/tabs/HomeTab.h@@ -0,0 +1,85 @@+#pragma once++#include <QString>+#include <QVariant>+#include <QWidget>++class QButtonGroup;+class QFrame;+class QHideEvent;+class QLabel;+class QPushButton;+class QShowEvent;++namespace fincept::screens::panels {+class HoldingsTable;+}++namespace fincept::screens {++/// HOME tab inside the Crypto Center workspace.+/// Phase 1's three panels (Wallet · Balance · Roadmap) repackaged into a+/// stand-alone tab. Subscribes to `wallet:balance:<pubkey>` and+/// `market:price:fncpt` independently of HoldingsBar — DataHub fans out a+/// single producer publish to both consumers, no double-fetch.+///+/// What lives here vs HoldingsBar:+/// - HoldingsBar — identity-level: SOL · $FNCPT · USD · feed pill+/// - HomeTab — panel-level detail, wallet identity rows, mode+/// toggle (mirrored from Settings), REFRESH button,+/// tab-local error strip, roadmap text.+class HomeTab : public QWidget {+ Q_OBJECT+ public:+ explicit HomeTab(QWidget* parent = nullptr);+ ~HomeTab() override;++ protected:+ void showEvent(QShowEvent* e) override;+ void hideEvent(QHideEvent* e) override;++ private:+ void build_ui();+ void apply_theme();++ void on_wallet_connected(const QString& pubkey, const QString& label);+ void on_wallet_disconnected();+ void on_topic_error(const QString& topic, const QString& error);+ void on_mode_changed(bool is_stream);++ void clear_error_strip();+ void show_error_strip(const QString& msg);+ void apply_mode_to_buttons(bool is_stream);++ signals:+ /// Forwarded from the embedded HoldingsTable when the user clicks a row.+ /// CryptoCenterScreen wires this to SwapPanel's FROM combo.+ void select_token(QString mint);++ private:+ // Wallet panel+ QFrame* wallet_panel_ = nullptr;+ QLabel* row_label_value_ = nullptr;+ QLabel* row_pubkey_value_ = nullptr;+ QLabel* row_connected_value_ = nullptr;+ QPushButton* copy_button_ = nullptr;+ QPushButton* disconnect_button_ = nullptr;++ // Holdings panel — replaces the three stat boxes (Stage 2A.5).+ QFrame* balance_panel_ = nullptr;+ QButtonGroup* mode_group_ = nullptr;+ QPushButton* mode_poll_button_ = nullptr;+ QPushButton* mode_stream_button_ = nullptr;+ QPushButton* refresh_button_ = nullptr;+ QFrame* error_strip_ = nullptr;+ QLabel* error_strip_text_ = nullptr;+ panels::HoldingsTable* holdings_table_ = nullptr;++ // Roadmap panel+ QFrame* roadmap_panel_ = nullptr;+ QLabel* roadmap_body_ = nullptr;++ QString current_pubkey_;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/tabs/SettingsTab.cpp b/fincept-qt/src/screens/crypto_center/tabs/SettingsTab.cppnew file mode 100644index 000000000..340c7d42c--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/tabs/SettingsTab.cpp@@ -0,0 +1,413 @@+#include "screens/crypto_center/tabs/SettingsTab.h"++#include "core/logging/Logger.h"+#include "services/wallet/WalletService.h"+#include "storage/secure/SecureStorage.h"+#include "ui/theme/Theme.h"++#include <QButtonGroup>+#include <QCheckBox>+#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QLineEdit>+#include <QPushButton>+#include <QSignalBlocker>+#include <QSlider>+#include <QVBoxLayout>++namespace fincept::screens {++namespace {++constexpr const char* kHeliusKey = "solana.helius_api_key";+constexpr const char* kSlippageKey = "wallet.default_slippage_bps";+constexpr int kDefaultSlippageBps = 100; // 1.00%+constexpr int kMaxSlippageBps = 500; // 5.00%++QString settings_font_stack() {+ return QStringLiteral(+ "'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");+}++QString format_bps(int bps) {+ return QStringLiteral("%1.%2%")+ .arg(bps / 100)+ .arg(bps % 100, 2, 10, QChar('0'));+}++} // namespace++SettingsTab::SettingsTab(QWidget* parent) : QWidget(parent) {+ setObjectName(QStringLiteral("settingsTab"));+ build_ui();+ apply_theme();+ load_initial_values();++ auto& svc = fincept::wallet::WalletService::instance();+ connect(&svc, &fincept::wallet::WalletService::balance_mode_changed, this,+ &SettingsTab::on_mode_changed);+}++SettingsTab::~SettingsTab() = default;++void SettingsTab::build_ui() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(14, 14, 14, 14);+ root->setSpacing(10);++ auto make_panel = [this](const QString& title_text,+ const QString& subtitle_text) -> std::pair<QFrame*, QVBoxLayout*> {+ auto* panel = new QFrame(this);+ panel->setObjectName(QStringLiteral("settingsTabPanel"));+ auto* outer = new QVBoxLayout(panel);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(0);++ auto* head = new QWidget(panel);+ head->setObjectName(QStringLiteral("settingsTabPanelHead"));+ head->setFixedHeight(34);+ auto* head_l = new QHBoxLayout(head);+ head_l->setContentsMargins(12, 0, 12, 0);+ head_l->setSpacing(0);+ auto* title = new QLabel(title_text, head);+ title->setObjectName(QStringLiteral("settingsTabPanelTitle"));+ head_l->addWidget(title);+ head_l->addStretch();+ if (!subtitle_text.isEmpty()) {+ auto* sub = new QLabel(subtitle_text, head);+ sub->setObjectName(QStringLiteral("settingsTabPanelStatus"));+ head_l->addWidget(sub);+ }+ outer->addWidget(head);++ auto* body = new QWidget(panel);+ auto* body_l = new QVBoxLayout(body);+ body_l->setContentsMargins(14, 12, 14, 14);+ body_l->setSpacing(8);+ outer->addWidget(body);+ return {panel, body_l};+ };++ // ── Balance refresh mode ──────────────────────────────────────────────+ {+ auto [panel, body] = make_panel(QStringLiteral("BALANCE REFRESH"),+ QStringLiteral("Mirrored on HOME"));+ auto* hint = new QLabel(+ tr("POLL refreshes balances on a TTL via the configured RPC. "+ "STREAM opens a WebSocket account subscription — requires Helius "+ "or a private RPC."),+ panel);+ hint->setObjectName(QStringLiteral("settingsTabHint"));+ hint->setWordWrap(true);+ body->addWidget(hint);++ auto* row = new QHBoxLayout;+ row->setSpacing(6);+ mode_poll_button_ = new QPushButton(QStringLiteral("POLL"), panel);+ mode_poll_button_->setObjectName(QStringLiteral("settingsTabToggle"));+ mode_poll_button_->setCheckable(true);+ mode_poll_button_->setFixedHeight(28);+ mode_poll_button_->setCursor(Qt::PointingHandCursor);+ mode_stream_button_ = new QPushButton(QStringLiteral("STREAM"), panel);+ mode_stream_button_->setObjectName(QStringLiteral("settingsTabToggle"));+ mode_stream_button_->setCheckable(true);+ mode_stream_button_->setFixedHeight(28);+ mode_stream_button_->setCursor(Qt::PointingHandCursor);+ mode_group_ = new QButtonGroup(this);+ mode_group_->setExclusive(true);+ mode_group_->addButton(mode_poll_button_);+ mode_group_->addButton(mode_stream_button_);+ row->addWidget(mode_poll_button_);+ row->addWidget(mode_stream_button_);+ row->addStretch(1);+ body->addLayout(row);++ connect(mode_poll_button_, &QPushButton::toggled, this, [](bool checked) {+ if (!checked) return;+ fincept::wallet::WalletService::instance().set_balance_mode(false);+ });+ connect(mode_stream_button_, &QPushButton::toggled, this, [](bool checked) {+ if (!checked) return;+ fincept::wallet::WalletService::instance().set_balance_mode(true);+ });++ root->addWidget(panel);+ }++ // ── Helius API key ────────────────────────────────────────────────────+ {+ auto [panel, body] = make_panel(QStringLiteral("HELIUS API KEY"),+ QStringLiteral("optional"));+ auto* hint = new QLabel(+ tr("Paste a Helius API key for reliable account-subscribe streaming "+ "and parsed transaction history. Stored in SecureStorage; never "+ "transmitted off-machine except in RPC requests to api.helius.xyz."),+ panel);+ hint->setObjectName(QStringLiteral("settingsTabHint"));+ hint->setWordWrap(true);+ body->addWidget(hint);++ auto* row = new QHBoxLayout;+ row->setSpacing(6);+ helius_input_ = new QLineEdit(panel);+ helius_input_->setObjectName(QStringLiteral("settingsTabInput"));+ helius_input_->setPlaceholderText(tr("paste API key…"));+ helius_input_->setEchoMode(QLineEdit::Password);+ helius_input_->setFixedHeight(28);+ row->addWidget(helius_input_, 1);++ helius_save_button_ = new QPushButton(tr("SAVE"), panel);+ helius_save_button_->setObjectName(QStringLiteral("settingsTabButton"));+ helius_save_button_->setFixedHeight(28);+ helius_save_button_->setCursor(Qt::PointingHandCursor);+ row->addWidget(helius_save_button_);++ helius_clear_button_ = new QPushButton(tr("CLEAR"), panel);+ helius_clear_button_->setObjectName(QStringLiteral("settingsTabDangerButton"));+ helius_clear_button_->setFixedHeight(28);+ helius_clear_button_->setCursor(Qt::PointingHandCursor);+ row->addWidget(helius_clear_button_);+ body->addLayout(row);++ helius_status_ = new QLabel(QStringLiteral("—"), panel);+ helius_status_->setObjectName(QStringLiteral("settingsTabHint"));+ body->addWidget(helius_status_);++ connect(helius_save_button_, &QPushButton::clicked, this,+ &SettingsTab::on_save_helius_key);+ connect(helius_clear_button_, &QPushButton::clicked, this,+ &SettingsTab::on_clear_helius_key);++ root->addWidget(panel);+ }++ // ── Default slippage ──────────────────────────────────────────────────+ {+ auto [panel, body] = make_panel(QStringLiteral("DEFAULT SLIPPAGE"),+ QStringLiteral("1% – 5%"));+ auto* hint = new QLabel(+ tr("Default slippage tolerance for swaps. Quotes whose route "+ "impact exceeds this value are blocked. Adjustable per-swap on "+ "the TRADE tab."),+ panel);+ hint->setObjectName(QStringLiteral("settingsTabHint"));+ hint->setWordWrap(true);+ body->addWidget(hint);++ auto* row = new QHBoxLayout;+ row->setSpacing(8);+ slippage_slider_ = new QSlider(Qt::Horizontal, panel);+ slippage_slider_->setObjectName(QStringLiteral("settingsTabSlider"));+ slippage_slider_->setMinimum(10); // 0.10%+ slippage_slider_->setMaximum(kMaxSlippageBps);+ slippage_slider_->setSingleStep(5);+ slippage_slider_->setTickInterval(50);+ slippage_slider_->setTickPosition(QSlider::TicksBelow);+ slippage_slider_->setValue(kDefaultSlippageBps);+ slippage_slider_->setFixedHeight(28);+ slippage_value_ = new QLabel(format_bps(kDefaultSlippageBps), panel);+ slippage_value_->setObjectName(QStringLiteral("settingsTabSliderValue"));+ slippage_value_->setFixedWidth(64);+ row->addWidget(slippage_slider_, 1);+ row->addWidget(slippage_value_);+ body->addLayout(row);++ connect(slippage_slider_, &QSlider::valueChanged, this,+ &SettingsTab::on_slippage_changed);++ root->addWidget(panel);+ }++ // ── Asset filters ─────────────────────────────────────────────────────+ {+ auto [panel, body] = make_panel(QStringLiteral("ASSET FILTERS"),+ QStringLiteral("affects holdings"));+ auto* hint = new QLabel(+ tr("Pump.fun-launched wallets accumulate airdropped junk over time. "+ "By default the holdings panel hides tokens that aren't in "+ "Jupiter's verified-tagged list. Toggle this on to see every "+ "SPL token account in the wallet."),+ panel);+ hint->setObjectName(QStringLiteral("settingsTabHint"));+ hint->setWordWrap(true);+ body->addWidget(hint);++ show_unverified_checkbox_ = new QCheckBox(+ tr("Show unverified tokens in the holdings panel"), panel);+ show_unverified_checkbox_->setObjectName(+ QStringLiteral("settingsTabCheckbox"));+ body->addWidget(show_unverified_checkbox_);++ connect(show_unverified_checkbox_, &QCheckBox::toggled, this,+ &SettingsTab::on_show_unverified_toggled);++ root->addWidget(panel);+ }++ root->addStretch(1);+}++void SettingsTab::apply_theme() {+ using namespace ui::colors;+ const QString font = settings_font_stack();++ const QString ss = QStringLiteral(+ "QWidget#settingsTab { background:%1; }"+ "QFrame#settingsTabPanel { background:%2; border:1px solid %3; }"+ "QWidget#settingsTabPanelHead { background:%4; border-bottom:1px solid %3; }"+ "QLabel#settingsTabPanelTitle { color:%5; font-family:%6; font-size:11px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QLabel#settingsTabPanelStatus { color:%7; font-family:%6; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QLabel#settingsTabHint { color:%8; font-family:%6; font-size:11px;"+ " background:transparent; }"++ // Inputs+ "QLineEdit#settingsTabInput { background:%4; color:%9; border:1px solid %3;"+ " font-family:%6; font-size:12px; padding:0 8px; }"+ "QLineEdit#settingsTabInput:focus { border-color:%5; }"++ // Buttons+ "QPushButton#settingsTabButton { background:%4; color:%8; border:1px solid %3;"+ " font-family:%6; font-size:11px; font-weight:700; letter-spacing:1px; padding:0 14px; }"+ "QPushButton#settingsTabButton:hover { background:%10; color:%9; border-color:%11; }"+ "QPushButton#settingsTabDangerButton { background:rgba(220,38,38,0.10); color:%12;"+ " border:1px solid %13; font-family:%6; font-size:11px; font-weight:700;"+ " letter-spacing:1px; padding:0 14px; }"+ "QPushButton#settingsTabDangerButton:hover { background:%12; color:%9; }"++ // Toggle+ "QPushButton#settingsTabToggle { background:transparent; color:%7; border:1px solid %3;"+ " font-family:%6; font-size:10px; font-weight:700; letter-spacing:1.2px;"+ " padding:0 14px; }"+ "QPushButton#settingsTabToggle:hover { color:%9; border-color:%11; }"+ "QPushButton#settingsTabToggle:checked { background:rgba(217,119,6,0.12);"+ " color:%5; border-color:%5; }"++ // Slider+ "QSlider#settingsTabSlider::groove:horizontal { background:%4; border:1px solid %3;"+ " height:6px; border-radius:0; }"+ "QSlider#settingsTabSlider::handle:horizontal { background:%5; border:1px solid %5;"+ " width:14px; margin:-6px 0; }"+ "QSlider#settingsTabSlider::sub-page:horizontal { background:rgba(217,119,6,0.30); }"+ "QLabel#settingsTabSliderValue { color:%5; font-family:%6; font-size:14px;"+ " font-weight:700; background:transparent; }"++ // Checkbox (asset filter)+ "QCheckBox#settingsTabCheckbox { color:%9; font-family:%6; font-size:12px;"+ " background:transparent; spacing:8px; }"+ "QCheckBox#settingsTabCheckbox::indicator { width:14px; height:14px;"+ " border:1px solid %3; background:%4; }"+ "QCheckBox#settingsTabCheckbox::indicator:checked { background:%5;"+ " border-color:%5; }"+ )+ .arg(BG_BASE(), // %1+ BG_SURFACE(), // %2+ BORDER_DIM(), // %3+ BG_RAISED(), // %4+ AMBER(), // %5+ font, // %6+ TEXT_TERTIARY(), // %7+ TEXT_SECONDARY(), // %8+ TEXT_PRIMARY()) // %9+ .arg(BG_HOVER(), // %10+ BORDER_BRIGHT(), // %11+ NEGATIVE(), // %12+ QStringLiteral("#7f1d1d"));// %13++ setStyleSheet(ss);+}++void SettingsTab::load_initial_values() {+ apply_mode_to_buttons(+ fincept::wallet::WalletService::instance().balance_mode_is_stream());++ auto helius_res =+ SecureStorage::instance().retrieve(QString::fromLatin1(kHeliusKey));+ if (helius_res.is_ok() && !helius_res.value().isEmpty()) {+ helius_status_->setText(tr("Stored — input is hidden. Type to replace."));+ } else {+ helius_status_->setText(tr("No key stored. Public RPC will be used."));+ }++ auto slip_res =+ SecureStorage::instance().retrieve(QString::fromLatin1(kSlippageKey));+ int bps = kDefaultSlippageBps;+ if (slip_res.is_ok()) {+ bool ok = false;+ const auto v = slip_res.value().toInt(&ok);+ if (ok && v >= 10 && v <= kMaxSlippageBps) bps = v;+ }+ QSignalBlocker b(slippage_slider_);+ slippage_slider_->setValue(bps);+ slippage_value_->setText(format_bps(bps));++ // Asset filters: show-unverified toggle.+ auto unv_res = SecureStorage::instance().retrieve(+ QStringLiteral("wallet.show_unverified_tokens"));+ const bool show_unverified =+ unv_res.is_ok() &&+ unv_res.value().compare(QStringLiteral("true"), Qt::CaseInsensitive) == 0;+ if (show_unverified_checkbox_) {+ QSignalBlocker cb(show_unverified_checkbox_);+ show_unverified_checkbox_->setChecked(show_unverified);+ }+}++void SettingsTab::on_mode_changed(bool is_stream) {+ apply_mode_to_buttons(is_stream);+}++void SettingsTab::on_show_unverified_toggled(bool checked) {+ SecureStorage::instance().store(+ QStringLiteral("wallet.show_unverified_tokens"),+ checked ? QStringLiteral("true") : QStringLiteral("false"));+ LOG_INFO("SettingsTab",+ QStringLiteral("show_unverified_tokens = %1")+ .arg(checked ? "true" : "false"));+}++void SettingsTab::on_save_helius_key() {+ const auto v = helius_input_->text().trimmed();+ if (v.isEmpty()) {+ helius_status_->setText(tr("Empty input — use CLEAR to remove a stored key."));+ return;+ }+ auto r = SecureStorage::instance().store(QString::fromLatin1(kHeliusKey), v);+ if (r.is_err()) {+ helius_status_->setText(+ tr("Failed: %1").arg(QString::fromStdString(r.error())));+ return;+ }+ helius_input_->clear();+ helius_status_->setText(tr("Saved. Restart streaming to use the new key."));+ LOG_INFO("SettingsTab", "Helius key stored");+}++void SettingsTab::on_clear_helius_key() {+ auto r = SecureStorage::instance().remove(QString::fromLatin1(kHeliusKey));+ if (r.is_err()) {+ helius_status_->setText(+ tr("Failed: %1").arg(QString::fromStdString(r.error())));+ return;+ }+ helius_input_->clear();+ helius_status_->setText(tr("Cleared. Public RPC will be used."));+ LOG_INFO("SettingsTab", "Helius key cleared");+}++void SettingsTab::on_slippage_changed(int bps) {+ slippage_value_->setText(format_bps(bps));+ SecureStorage::instance().store(QString::fromLatin1(kSlippageKey),+ QString::number(bps));+}++void SettingsTab::apply_mode_to_buttons(bool is_stream) {+ QSignalBlocker b1(mode_poll_button_);+ QSignalBlocker b2(mode_stream_button_);+ mode_poll_button_->setChecked(!is_stream);+ mode_stream_button_->setChecked(is_stream);+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/tabs/SettingsTab.h b/fincept-qt/src/screens/crypto_center/tabs/SettingsTab.hnew file mode 100644index 000000000..bfce90540--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/tabs/SettingsTab.h@@ -0,0 +1,60 @@+#pragma once++#include <QString>+#include <QWidget>++class QButtonGroup;+class QCheckBox;+class QFrame;+class QLabel;+class QLineEdit;+class QPushButton;+class QSlider;++namespace fincept::screens {++/// SETTINGS tab — Phase 2 lands the configuration that previously lived+/// inline on the HOME panel.+///+/// Sections:+/// - Balance refresh mode (POLL / STREAM, mirrored on HOME)+/// - Helius API key entry (writes to SecureStorage `solana.helius_api_key`)+/// - Default slippage (writes to SecureStorage `wallet.default_slippage_bps`)+///+/// No data subscriptions; all reads/writes go through SecureStorage and+/// WalletService. Safe to construct eagerly.+class SettingsTab : public QWidget {+ Q_OBJECT+ public:+ explicit SettingsTab(QWidget* parent = nullptr);+ ~SettingsTab() override;++ private:+ void build_ui();+ void apply_theme();++ void on_mode_changed(bool is_stream);+ void on_save_helius_key();+ void on_clear_helius_key();+ void on_slippage_changed(int bps);+ void on_show_unverified_toggled(bool checked);++ void apply_mode_to_buttons(bool is_stream);+ void load_initial_values();++ QButtonGroup* mode_group_ = nullptr;+ QPushButton* mode_poll_button_ = nullptr;+ QPushButton* mode_stream_button_ = nullptr;++ QLineEdit* helius_input_ = nullptr;+ QPushButton* helius_save_button_ = nullptr;+ QPushButton* helius_clear_button_ = nullptr;+ QLabel* helius_status_ = nullptr;++ QSlider* slippage_slider_ = nullptr;+ QLabel* slippage_value_ = nullptr;++ QCheckBox* show_unverified_checkbox_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/tabs/TradeTab.cpp b/fincept-qt/src/screens/crypto_center/tabs/TradeTab.cppnew file mode 100644index 000000000..5bb57c5d1--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/tabs/TradeTab.cpp@@ -0,0 +1,131 @@+#include "screens/crypto_center/tabs/TradeTab.h"++#include "screens/crypto_center/panels/FeeDiscountPanel.h"+#include "screens/crypto_center/panels/SwapPanel.h"+#include "ui/theme/Theme.h"++#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QVBoxLayout>++namespace fincept::screens {++namespace {++QString trade_font_stack() {+ return QStringLiteral(+ "'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");+}++} // namespace++TradeTab::TradeTab(QWidget* parent) : QWidget(parent) {+ setObjectName(QStringLiteral("tradeTab"));+ build_ui();+ apply_theme();+}++TradeTab::~TradeTab() = default;++void TradeTab::build_ui() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(14, 14, 14, 14);+ root->setSpacing(10);++ auto* top_row = new QHBoxLayout;+ top_row->setSpacing(10);++ // SwapPanel — host inside a styled outer frame so it matches the rest of+ // the screens' panel chrome.+ {+ auto* host = new QFrame(this);+ host->setObjectName(QStringLiteral("tradeTabPanelHost"));+ auto* hl = new QVBoxLayout(host);+ hl->setContentsMargins(0, 0, 0, 0);+ hl->setSpacing(0);+ swap_panel_ = new panels::SwapPanel(host);+ hl->addWidget(swap_panel_);+ top_row->addWidget(host, 2);+ }++ // FeeDiscount panel — Phase 2 §2C, replaces the earlier placeholder.+ {+ fee_discount_placeholder_ = new QFrame(this);+ fee_discount_placeholder_->setObjectName(QStringLiteral("tradeTabPanelHost"));+ auto* outer = new QVBoxLayout(fee_discount_placeholder_);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(0);+ fee_discount_panel_ = new panels::FeeDiscountPanel(fee_discount_placeholder_);+ outer->addWidget(fee_discount_panel_);+ top_row->addWidget(fee_discount_placeholder_, 1);+ }+ root->addLayout(top_row, 1);++ // Burn placeholder (Stage 2.3)+ {+ burn_placeholder_ = new QFrame(this);+ burn_placeholder_->setObjectName(QStringLiteral("tradeTabPanelHost"));+ auto* outer = new QVBoxLayout(burn_placeholder_);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(0);++ auto* head = new QWidget(burn_placeholder_);+ head->setObjectName(QStringLiteral("tradeTabPanelHead"));+ head->setFixedHeight(34);+ auto* head_l = new QHBoxLayout(head);+ head_l->setContentsMargins(12, 0, 12, 0);+ head_l->setSpacing(0);+ auto* title = new QLabel(QStringLiteral("BURN $FNCPT"), head);+ title->setObjectName(QStringLiteral("tradeTabPanelTitle"));+ auto* status = new QLabel(QStringLiteral("STAGE 2.3"), head);+ status->setObjectName(QStringLiteral("tradeTabPanelStatus"));+ head_l->addWidget(title);+ head_l->addStretch();+ head_l->addWidget(status);+ outer->addWidget(head);++ auto* body = new QLabel(+ tr("Permanently destroy $FNCPT through the on-chain fincept_burn program. "+ "The terminal builds the burn transaction, you sign in your wallet, "+ "and the receipt lands here. Lands with the Anchor program in Stage 2.3."),+ burn_placeholder_);+ body->setObjectName(QStringLiteral("tradeTabPlaceholderBody"));+ body->setWordWrap(true);+ body->setContentsMargins(14, 12, 14, 14);+ outer->addWidget(body);+ outer->addStretch(1);+ root->addWidget(burn_placeholder_);+ }++ root->addStretch(1);+}++void TradeTab::apply_theme() {+ using namespace ui::colors;+ const QString font = trade_font_stack();++ const QString ss = QStringLiteral(+ "QWidget#tradeTab { background:%1; }"+ "QFrame#tradeTabPanelHost { background:%2; border:1px solid %3; }"+ "QWidget#tradeTabPanelHead { background:%4; border-bottom:1px solid %3; }"+ "QLabel#tradeTabPanelTitle { color:%5; font-family:%6; font-size:11px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QLabel#tradeTabPanelStatus { color:%7; font-family:%6; font-size:10px;"+ " font-weight:700; letter-spacing:1.2px; background:transparent; }"+ "QLabel#tradeTabPlaceholderBody { color:%8; font-family:%6; font-size:11px;"+ " background:transparent; }"+ )+ .arg(BG_BASE(), // %1+ BG_SURFACE(), // %2+ BORDER_DIM(), // %3+ BG_RAISED(), // %4+ AMBER(), // %5+ font, // %6+ TEXT_TERTIARY(), // %7+ TEXT_SECONDARY()); // %8++ setStyleSheet(ss);+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_center/tabs/TradeTab.h b/fincept-qt/src/screens/crypto_center/tabs/TradeTab.hnew file mode 100644index 000000000..fb621ddc0--- /dev/null+++ b/fincept-qt/src/screens/crypto_center/tabs/TradeTab.h@@ -0,0 +1,38 @@+#pragma once++#include <QWidget>++class QFrame;+class QLabel;++namespace fincept::screens::panels {+class SwapPanel;+class FeeDiscountPanel;+}++namespace fincept::screens {++/// TRADE tab — buy/sell $FNCPT via Jupiter and burn $FNCPT.+///+/// Stage 2.2 ships SwapPanel; placeholder slots reserved for BurnPanel+/// (Stage 2.3) and FeeDiscountPanel (Stage 2.4). When those land they take+/// over the placeholder QFrames keyed by `objectName`.+class TradeTab : public QWidget {+ Q_OBJECT+ public:+ explicit TradeTab(QWidget* parent = nullptr);+ ~TradeTab() override;++ private:+ void build_ui();+ void apply_theme();++ panels::SwapPanel* swap_panel_ = nullptr;+ panels::FeeDiscountPanel* fee_discount_panel_ = nullptr;++ // Burn placeholder — burn deferred to Phase 5 (see plans/crypto-center-phase-2.md D6).+ QFrame* burn_placeholder_ = nullptr;+ QFrame* fee_discount_placeholder_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/news/NewsFeedPanel.cpp b/fincept-qt/src/screens/news/NewsFeedPanel.cppindex b5efb0f3d..c6ae7e1bc 100644--- a/fincept-qt/src/screens/news/NewsFeedPanel.cpp+++ b/fincept-qt/src/screens/news/NewsFeedPanel.cpp@@ -44,8 +44,31 @@ NewsFeedPanel::NewsFeedPanel(QWidget* parent) : QWidget(parent) {// Skeleton loading widgetbuild_skeleton();+ // Empty-state widget — shown when fetch yields zero articles+ empty_state_ = new QWidget(stack);+ empty_state_->setObjectName("newsEmptyState");+ {+ auto* layout = new QVBoxLayout(empty_state_);+ layout->setContentsMargins(24, 24, 24, 24);+ layout->setSpacing(8);+ layout->addStretch();+ auto* title = new QLabel(QStringLiteral("No articles available"), empty_state_);+ title->setObjectName("newsEmptyStateTitle");+ title->setAlignment(Qt::AlignCenter);+ auto* hint = new QLabel(+ QStringLiteral("Check your network connection and click Refresh to retry."),+ empty_state_);+ hint->setObjectName("newsEmptyStateHint");+ hint->setAlignment(Qt::AlignCenter);+ hint->setWordWrap(true);+ layout->addWidget(title);+ layout->addWidget(hint);+ layout->addStretch();+ }+stack->addWidget(list_view_); // index 0 = feedstack->addWidget(skeleton_overlay_); // index 1 = skeleton+ stack->addWidget(empty_state_); // index 2 = empty statestack->setCurrentIndex(0);stack_ = stack;@@ -209,6 +232,16 @@ void NewsFeedPanel::set_loading(bool loading) {}}+void NewsFeedPanel::set_empty_state(bool empty) {+ if (is_loading_)+ return; // skeleton wins until loading completes+ if (empty) {+ stack_->setCurrentWidget(empty_state_);+ } else if (stack_->currentWidget() == empty_state_) {+ stack_->setCurrentWidget(list_view_);+ }+}+void NewsFeedPanel::scroll_to(const QString& article_id) {auto idx = model_->index_for_article(article_id);if (idx.isValid())diff --git a/fincept-qt/src/screens/news/NewsFeedPanel.h b/fincept-qt/src/screens/news/NewsFeedPanel.hindex 942e33b6e..e32304dab 100644--- a/fincept-qt/src/screens/news/NewsFeedPanel.h+++ b/fincept-qt/src/screens/news/NewsFeedPanel.h@@ -24,6 +24,10 @@ class NewsFeedPanel : public QWidget {void show_breaking(const QVector<services::NewsCluster>& breaking_clusters);void clear_breaking();void set_loading(bool loading);+ /// When loading has finished but no articles arrived, show a non-blocking+ /// empty-state message ("No articles available — check connection").+ /// Calling with `false` (or any successful set_wire_articles) hides it.+ void set_empty_state(bool empty);void scroll_to(const QString& article_id);void set_selected(const QString& article_id);void select_next();@@ -72,6 +76,9 @@ class NewsFeedPanel : public QWidget {QTimer* skeleton_anim_timer_ = nullptr;int skeleton_phase_ = 0;bool is_loading_ = false;++ // Empty-state widget (shown when loading is done + no articles)+ QWidget* empty_state_ = nullptr;};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/news/NewsScreen.cpp b/fincept-qt/src/screens/news/NewsScreen.cppindex f5c8fb646..fbc164209 100644--- a/fincept-qt/src/screens/news/NewsScreen.cpp+++ b/fincept-qt/src/screens/news/NewsScreen.cpp@@ -527,6 +527,12 @@ void NewsScreen::refresh_data(bool force) {return;self->all_articles_ = std::move(articles);self->command_bar_->set_loading_progress(done, total);+ // Hide skeleton as soon as we have any articles to render —+ // otherwise the overlay traps progressive partials and the+ // user sees a blank list until the slowest feed times out.+ if (!self->all_articles_.isEmpty()) {+ self->feed_panel_->set_loading(false);+ }self->apply_filters_async();if (done == total)QObject::disconnect(*conn);@@ -540,9 +546,13 @@ void NewsScreen::refresh_data(bool force) {self->feed_panel_->set_loading(false);if (!ok) {LOG_ERROR("NewsScreen", "Failed to fetch news");+ self->feed_panel_->set_empty_state(true);return;}self->all_articles_ = std::move(articles);+ // Show empty state only when literally no articles came back across+ // every feed — otherwise apply_filters_async will populate the list.+ self->feed_panel_->set_empty_state(self->all_articles_.isEmpty());self->apply_filters_async();});}@@ -611,19 +621,32 @@ void NewsScreen::apply_filters_async() {QMap<QString, int> category_counts;int bullish = 0, bearish = 0, neutral = 0;+ // Per-stage rejection counters — surface the cause when we silently+ // filter the entire input down to zero (the single highest-impact+ // failure mode in this pipeline).+ int rejected_time = 0, rejected_variant = 0, rejected_category = 0, rejected_search = 0;+for (const auto& a : articles_copy) {- if (cutoff > 0 && a.sort_ts < cutoff)+ if (cutoff > 0 && a.sort_ts < cutoff) {+ ++rejected_time;continue;+ }// Variant filterif (variant == "FINANCE" && a.category != "MARKETS" && a.category != "EARNINGS" &&- a.category != "ECONOMIC" && a.category != "REGULATORY")+ a.category != "ECONOMIC" && a.category != "REGULATORY") {+ ++rejected_variant;continue;- if (variant == "CRYPTO" && a.category != "CRYPTO" && a.category != "TECH")+ }+ if (variant == "CRYPTO" && a.category != "CRYPTO" && a.category != "TECH") {+ ++rejected_variant;continue;+ }if (variant == "MACRO" && a.category != "ECONOMIC" && a.category != "REGULATORY" &&- a.category != "GEOPOLITICS" && a.category != "ENERGY")+ a.category != "GEOPOLITICS" && a.category != "ENERGY") {+ ++rejected_variant;continue;+ }// Category filterif (category != "ALL") {@@ -632,8 +655,10 @@ void NewsScreen::apply_filters_async() {{"NRG", "ENERGY"}, {"CRPT", "CRYPTO"}, {"GEO", "GEOPOLITICS"}, {"DEF", "DEFENSE"},};auto it = cat_map.find(category);- if (it != cat_map.end() && a.category != it.value())+ if (it != cat_map.end() && a.category != it.value()) {+ ++rejected_category;continue;+ }}// Search filter@@ -650,8 +675,10 @@ void NewsScreen::apply_filters_async() {}}}- if (!match)+ if (!match) {+ ++rejected_search;continue;+ }}filtered.append(a);@@ -679,6 +706,16 @@ void NewsScreen::apply_filters_async() {auto clusters = services::cluster_articles(filtered);+ // When the entire input is filtered to zero, surface why so the cause+ // is visible in logs without users digging into the source.+ if (!articles_copy.isEmpty() && filtered.isEmpty()) {+ LOG_WARN("NewsScreen",+ QString("Filter rejected ALL %1 articles "+ "(time=%2 variant=%3 category=%4 search=%5 range=%6)")+ .arg(articles_copy.size()).arg(rejected_time).arg(rejected_variant)+ .arg(rejected_category).arg(rejected_search).arg(time_range));+ }+QMetaObject::invokeMethod(self,[self, gen, filtered, clusters, category_counts, bullish, bearish, neutral]() {@@ -710,6 +747,14 @@ void NewsScreen::update_ui_from_filtered(int /*generation*/, const QVector<servifeed_panel_->model()->set_clusters(clusters);feed_panel_->model()->set_view_mode(view_mode_);+ // Empty-state toggle: only show "no articles" when we're not still loading+ // and the filter genuinely produced nothing. Hide it as soon as the user+ // has any rows to look at.+ if (!loading_)+ feed_panel_->set_empty_state(filtered.isEmpty());+ else if (!filtered.isEmpty())+ feed_panel_->set_empty_state(false);+// Command bar countscommand_bar_->set_article_count(filtered.size());int alert_count = static_cast<int>(services::get_breaking_clusters(clusters).size());@@ -945,9 +990,13 @@ int64_t NewsScreen::time_window_seconds() const {// ── IStatefulScreen ─────────────────────────────────────────────────────────QVariantMap NewsScreen::save_state() const {+ // search_query_ is intentionally NOT persisted — it's a transient+ // typed-in filter, and restoring it would silently filter the feed+ // on next launch (the search input widget doesn't display restored+ // queries, so users can't see what's hiding articles).return {- {"category", active_category_}, {"time_range", time_range_}, {"sort_mode", sort_mode_},- {"view_mode", view_mode_}, {"search_query", search_query_}, {"variant", active_variant_},+ {"category", active_category_}, {"time_range", time_range_}, {"sort_mode", sort_mode_},+ {"view_mode", view_mode_}, {"variant", active_variant_},};}@@ -956,7 +1005,8 @@ void NewsScreen::restore_state(const QVariantMap& state) {time_range_ = state.value("time_range", "24H").toString();sort_mode_ = state.value("sort_mode", "RELEVANCE").toString();view_mode_ = state.value("view_mode", "WIRE").toString();- search_query_ = state.value("search_query").toString();+ // Drop any legacy "search_query" stored by an older build — see save_state().+ search_query_.clear();active_variant_ = state.value("variant", "FULL").toString();if (command_bar_)diff --git a/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp b/fincept-qt/src/screens/portfolio/PortfolioScreen.cppindex 4c7d36735..2aae68245 100644--- a/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp+++ b/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp@@ -2,6 +2,8 @@#include "screens/portfolio/PortfolioScreen.h"#include "core/session/ScreenStateManager.h"+#include "core/symbol/SymbolContext.h"+#include "core/symbol/SymbolRef.h"#include "screens/portfolio/PortfolioInsightsPanel.h"#include "screens/portfolio/PortfolioBlotter.h"#include "screens/portfolio/PortfolioCommandBar.h"@@ -1045,6 +1047,13 @@ void PortfolioScreen::on_symbol_selected(const QString& symbol) {blotter_->set_selected_symbol(symbol);if (order_panel_)order_panel_->set_holding(find_holding(symbol));++ // Publish to the linked group so other panels (Equity Research, Watchlist+ // …) follow the selection. Only when actually linked.+ if (link_group_ != SymbolGroup::None && !symbol.isEmpty()) {+ SymbolContext::instance().set_group_symbol(+ link_group_, SymbolRef::equity(symbol), this);+ }}void PortfolioScreen::on_buy_requested() {@@ -1184,4 +1193,31 @@ void PortfolioScreen::restore_state(const QVariantMap& state) {selected_symbol_ = sym;}+// ── IGroupLinked ─────────────────────────────────────────────────────────────++SymbolRef PortfolioScreen::current_symbol() const {+ if (selected_symbol_.isEmpty())+ return {};+ return SymbolRef::equity(selected_symbol_);+}++void PortfolioScreen::on_group_symbol_changed(const SymbolRef& ref) {+ if (!ref.is_valid())+ return;+ // Only react if the symbol is actually held — otherwise the group is+ // pointing at a ticker the user can't act on here, and silently+ // selecting a phantom would be misleading.+ if (!find_holding(ref.symbol))+ return;+ if (selected_symbol_ == ref.symbol)+ return;+ selected_symbol_ = ref.symbol;+ if (heatmap_)+ heatmap_->set_selected_symbol(ref.symbol);+ if (blotter_)+ blotter_->set_selected_symbol(ref.symbol);+ if (order_panel_)+ order_panel_->set_holding(find_holding(ref.symbol));+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/portfolio/PortfolioScreen.h b/fincept-qt/src/screens/portfolio/PortfolioScreen.hindex 41791233c..2e29d6bb2 100644--- a/fincept-qt/src/screens/portfolio/PortfolioScreen.h+++ b/fincept-qt/src/screens/portfolio/PortfolioScreen.h@@ -1,5 +1,6 @@// src/screens/portfolio/PortfolioScreen.h#pragma once+#include "core/symbol/IGroupLinked.h"#include "screens/IStatefulScreen.h"#include "screens/portfolio/PortfolioTypes.h"@@ -28,8 +29,9 @@ class PortfolioDetailWrapper;class PortfolioFFNView;class PortfolioInsightsPanel;-class PortfolioScreen : public QWidget, public IStatefulScreen {+class PortfolioScreen : public QWidget, public IStatefulScreen, public IGroupLinked {Q_OBJECT+ Q_INTERFACES(fincept::IGroupLinked)public:explicit PortfolioScreen(QWidget* parent = nullptr);@@ -37,6 +39,15 @@ class PortfolioScreen : public QWidget, public IStatefulScreen {QVariantMap save_state() const override;QString state_key() const override { return "portfolio"; }+ // IGroupLinked — active symbol = currently selected holding. Receiving+ // a group symbol scrolls/selects that holding if it exists in the+ // current portfolio; symbols not held are silently ignored (no synthetic+ // "phantom" selection).+ void set_group(SymbolGroup g) override { link_group_ = g; }+ SymbolGroup group() const override { return link_group_; }+ void on_group_symbol_changed(const SymbolRef& ref) override;+ SymbolRef current_symbol() const override;+protected:void showEvent(QShowEvent* event) override;void hideEvent(QHideEvent* event) override;@@ -118,6 +129,9 @@ class PortfolioScreen : public QWidget, public IStatefulScreen {// Positions section header — count badge updates with holdingsQLabel* positions_count_label_ = nullptr;++ // Symbol-group link (None when unlinked).+ SymbolGroup link_group_ = SymbolGroup::None;};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/report_builder/ComponentToolbar.cpp b/fincept-qt/src/screens/report_builder/ComponentToolbar.cppindex 179c4111d..3b841e29e 100644--- a/fincept-qt/src/screens/report_builder/ComponentToolbar.cpp+++ b/fincept-qt/src/screens/report_builder/ComponentToolbar.cpp@@ -10,7 +10,10 @@namespace fincept::screens {ComponentToolbar::ComponentToolbar(QWidget* parent) : QWidget(parent) {- setFixedWidth(240);+ // Use min/max width pair (not setFixedWidth) so the parent splitter can+ // drive resize and the collapse animation can drive maximumWidth → 0.+ setMinimumWidth(0);+ setMaximumWidth(240);setStyleSheet(QString("background: %1; border-right: 1px solid %2;").arg(ui::colors::PANEL(), ui::colors::BORDER()));// Wrap content in a scroll area so it doesn't clip on small displaysdiff --git a/fincept-qt/src/screens/report_builder/DocumentCanvas.cpp b/fincept-qt/src/screens/report_builder/DocumentCanvas.cppindex 5b809503f..003520f27 100644--- a/fincept-qt/src/screens/report_builder/DocumentCanvas.cpp+++ b/fincept-qt/src/screens/report_builder/DocumentCanvas.cpp@@ -356,29 +356,40 @@ void DocumentCanvas::render(const QVector<ReportComponent>& components, const ReQTextCursor cursor = current_page->textCursor();// ── Metadata header ───────────────────────────────────────────────────────+ // Title: large, accent-coloured, with a thicker rule under the meta line+ // so the cover area reads as a proper report header.+ QTextBlockFormat title_bf;+ title_bf.setBottomMargin(2);+ cursor.setBlockFormat(title_bf);QTextCharFormat title_fmt;- title_fmt.setFontPointSize(20);+ title_fmt.setFontPointSize(24);title_fmt.setFontWeight(QFont::Bold);title_fmt.setForeground(QColor(theme.heading_color));- cursor.insertText(metadata.title + "\n", title_fmt);+ cursor.insertText(metadata.title, title_fmt);+ cursor.insertBlock();+ QTextBlockFormat meta_bf;+ meta_bf.setTopMargin(2);+ meta_bf.setBottomMargin(8);+ cursor.setBlockFormat(meta_bf);QTextCharFormat meta_fmt;meta_fmt.setFontPointSize(10);meta_fmt.setForeground(QColor(theme.meta_color));- QString meta_line = metadata.author;- if (!metadata.company.isEmpty())- meta_line += " | " + metadata.company;- if (!metadata.date.isEmpty())- meta_line += " | " + metadata.date;- cursor.insertText(meta_line + "\n\n", meta_fmt);-- // Divider+ QStringList meta_parts;+ if (!metadata.author.trimmed().isEmpty()) meta_parts << metadata.author;+ if (!metadata.company.trimmed().isEmpty()) meta_parts << metadata.company;+ if (!metadata.date.trimmed().isEmpty()) meta_parts << metadata.date;+ cursor.insertText(meta_parts.join(" · "), meta_fmt);++ // Accent-coloured rule under the cover meta — visually separates the+ // report header from the body.+ cursor.insertBlock();QTextBlockFormat line_block;- line_block.setTopMargin(4);- line_block.setBottomMargin(12);- cursor.insertBlock(line_block);+ line_block.setTopMargin(6);+ line_block.setBottomMargin(16);+ cursor.setBlockFormat(line_block);QTextCharFormat line_fmt;- line_fmt.setForeground(QColor(theme.divider_color));+ line_fmt.setForeground(QColor(theme.accent_color));line_fmt.setFontPointSize(8);cursor.insertText(QString(80, QChar(0x2500)), line_fmt);@@ -404,71 +415,166 @@ void DocumentCanvas::render(const QVector<ReportComponent>& components, const Re}if (comp.type == "heading") {+ // Visual hierarchy: large size, accent-colour rule before, generous+ // top margin so sections don't run together.+ QTextBlockFormat hbf;+ hbf.setTopMargin(20);+ hbf.setBottomMargin(8);+ if (i == selected_index)+ hbf.setBackground(QColor("#fffbe6"));+ cursor.setBlockFormat(hbf);+QTextCharFormat fmt;- fmt.setFontPointSize(16);+ fmt.setFontPointSize(18);fmt.setFontWeight(QFont::Bold);fmt.setForeground(QColor(theme.heading_color));cursor.insertText(comp.content.isEmpty() ? "Heading" : comp.content, fmt);- cursor.insertText("\n");++ // Thin accent rule under the heading for institutional polish.+ cursor.insertBlock();+ QTextBlockFormat rule_bf;+ rule_bf.setTopMargin(2);+ rule_bf.setBottomMargin(10);+ cursor.setBlockFormat(rule_bf);+ QTextCharFormat rule_fmt;+ rule_fmt.setForeground(QColor(theme.accent_color));+ rule_fmt.setFontPointSize(8);+ cursor.insertText(QString(80, QChar(0x2500)), rule_fmt);} else if (comp.type == "text") {+ // Use markdown rendering so **bold**, *italic*, links, etc.+ // come through. Also gives the LLM a familiar formatting target.QTextBlockFormat bf;bf.setLineHeight(140, QTextBlockFormat::ProportionalHeight);+ bf.setTopMargin(4);+ bf.setBottomMargin(8);if (i == selected_index)bf.setBackground(QColor("#fffbe6"));cursor.setBlockFormat(bf);++ // Set default char format so insertMarkdown picks up the right+ // body colour. Markdown headers/emphasis override per-run as needed.QTextCharFormat fmt;fmt.setFontPointSize(12);fmt.setForeground(QColor(theme.text_color));- cursor.insertText(comp.content.isEmpty() ? "Enter text here..." : comp.content, fmt);+ cursor.setCharFormat(fmt);++ const QString body = comp.content.isEmpty() ? "Enter text here..." : comp.content;+ // Heuristic: if content contains common markdown markers, render+ // as markdown; else fall back to plain text. Avoids spurious+ // re-interpretation of ad-hoc punctuation in plain copy.+ const bool looks_markdown = body.contains("**") || body.contains("__") ||+ body.contains("\n- ") || body.contains("\n* ") ||+ body.contains("\n#");+ if (looks_markdown)+ cursor.insertMarkdown(body);+ else+ cursor.insertText(body, fmt);cursor.insertText("\n");} else if (comp.type == "table") {- int rows = comp.config.value("rows", "3").toInt();- int cols = comp.config.value("cols", "3").toInt();+ // Cell data sources, in priority order:+ // 1. config["csv"] — pipe-separated rows, comma-separated cells:+ // "Metric,FY22,FY23|Revenue,81462,96773|Net Income,12556,14997"+ // This is the LLM-friendly format the MCP tool description+ // recommends.+ // 2. config["data"] — JSON map {"r_c":"value"} (legacy).+ // 3. fallback to "Header N" placeholders so the table at least+ // shows where data should go rather than empty cells.+ QVector<QStringList> rows_data;+ QString csv = comp.config.value("csv");+ if (!csv.isEmpty()) {+ for (const QString& row_str : csv.split('|', Qt::SkipEmptyParts)) {+ QStringList row;+ for (const QString& cell : row_str.split(',')) // keep empty cells+ row << cell.trimmed();+ rows_data.append(row);+ }+ }++ QJsonObject cell_data;+ if (rows_data.isEmpty() && comp.config.contains("data")) {+ QJsonDocument doc = QJsonDocument::fromJson(comp.config.value("data").toUtf8());+ if (doc.isObject())+ cell_data = doc.object();+ }++ // Determine grid dimensions: prefer csv shape, then config rows/cols,+ // then a 3x3 default. Cap to keep one massive table from blowing the page.+ int rows;+ int cols;+ if (!rows_data.isEmpty()) {+ rows = rows_data.size();+ cols = 0;+ for (const auto& r : rows_data)+ cols = qMax(cols, r.size());+ } else {+ rows = comp.config.value("rows", "3").toInt();+ cols = comp.config.value("cols", "3").toInt();+ }+ rows = qBound(1, rows, 100);+ cols = qBound(1, cols, 12);QTextTableFormat tf;tf.setBorderBrush(QColor(theme.divider_color));tf.setBorder(1);+ tf.setBorderStyle(QTextFrameFormat::BorderStyle_Solid);tf.setCellPadding(6);tf.setCellSpacing(0);QVector<QTextLength> widths(cols, QTextLength(QTextLength::PercentageLength, 100.0 / cols));tf.setColumnWidthConstraints(widths);- // Parse cell data from JSON stored in config["data"]- QJsonObject cell_data;- if (comp.config.contains("data")) {- QJsonDocument doc = QJsonDocument::fromJson(comp.config.value("data").toUtf8());- if (doc.isObject())- cell_data = doc.object();- }+ // Push a top margin block so tables don't touch the prior heading rule.+ QTextBlockFormat tbf;+ tbf.setTopMargin(6);+ tbf.setBottomMargin(6);+ cursor.setBlockFormat(tbf);auto* table = cursor.insertTable(rows, cols, tf);for (int r = 0; r < rows; ++r) {for (int c = 0; c < cols; ++c) {- QString cell_key = QString("%1_%2").arg(r).arg(c);QString cell_text;-- if (cell_data.contains(cell_key)) {- cell_text = cell_data.value(cell_key).toString();- } else if (r == 0) {- cell_text = QString("Header %1").arg(c + 1);+ if (!rows_data.isEmpty()) {+ if (r < rows_data.size() && c < rows_data[r].size())+ cell_text = rows_data[r][c];+ } else {+ QString cell_key = QString("%1_%2").arg(r).arg(c);+ if (cell_data.contains(cell_key))+ cell_text = cell_data.value(cell_key).toString();+ else if (r == 0)+ cell_text = QString("Header %1").arg(c + 1);}QTextCharFormat cell_fmt;+ QTextBlockFormat cell_block;if (r == 0) {cell_fmt.setFontWeight(QFont::Bold);+ cell_fmt.setFontPointSize(11);cell_fmt.setForeground(QColor(theme.table_header_fg));- QTextBlockFormat hdr_block;- hdr_block.setBackground(QColor(theme.table_header_bg));- auto cell_cursor = table->cellAt(r, c).firstCursorPosition();- cell_cursor.setBlockFormat(hdr_block);- cell_cursor.insertText(cell_text, cell_fmt);+ cell_block.setBackground(QColor(theme.table_header_bg));+ cell_block.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);} else {+ cell_fmt.setFontPointSize(11);cell_fmt.setForeground(QColor(theme.text_color));- table->cellAt(r, c).firstCursorPosition().insertText(cell_text, cell_fmt);+ // Right-align numeric-looking cells (helps financials read).+ bool is_numeric = !cell_text.isEmpty();+ for (QChar ch : cell_text) {+ if (!ch.isDigit() && ch != QChar('.') && ch != QChar(',') &&+ ch != QChar('-') && ch != QChar('+') && ch != QChar('%') &&+ ch != QChar('$') && ch != QChar(' ') && ch != QChar('(') &&+ ch != QChar(')') && ch != QChar('B') && ch != QChar('M') &&+ ch != QChar('K') && ch != QChar('T') && ch != QChar('x')) {+ is_numeric = false;+ break;+ }+ }+ if (c > 0 && is_numeric)+ cell_block.setAlignment(Qt::AlignRight | Qt::AlignVCenter);}+ auto cc = table->cellAt(r, c).firstCursorPosition();+ cc.setBlockFormat(cell_block);+ cc.insertText(cell_text, cell_fmt);}}cursor.movePosition(QTextCursor::End);@@ -499,6 +605,9 @@ void DocumentCanvas::render(const QVector<ReportComponent>& components, const Re} else if (comp.type == "quote") {QTextBlockFormat bf;bf.setLeftMargin(24);+ bf.setRightMargin(8);+ bf.setTopMargin(8);+ bf.setBottomMargin(8);bf.setBackground(QColor(theme.quote_bg));if (i == selected_index)bf.setBackground(QColor("#fffbe6"));@@ -507,29 +616,56 @@ void DocumentCanvas::render(const QVector<ReportComponent>& components, const Refmt.setFontItalic(true);fmt.setForeground(QColor(theme.meta_color));fmt.setFontPointSize(12);- cursor.insertText(comp.content.isEmpty() ? "Block quote..." : comp.content, fmt);+ cursor.setCharFormat(fmt);+ const QString body = comp.content.isEmpty() ? "Block quote..." : comp.content;+ if (body.contains("**") || body.contains("__"))+ cursor.insertMarkdown(body);+ else+ cursor.insertText(body, fmt);cursor.insertText("\n");} else if (comp.type == "list") {- QTextListFormat lf;- lf.setStyle(QTextListFormat::ListDisc);- lf.setIndent(1);QStringList items = comp.content.split("\n", Qt::SkipEmptyParts);if (items.isEmpty())items << "Item 1" << "Item 2";- QTextList* list = nullptr;++ QTextBlockFormat outer_bf;+ outer_bf.setTopMargin(4);+ outer_bf.setBottomMargin(8);+ if (i == selected_index)+ outer_bf.setBackground(QColor("#fffbe6"));+ cursor.setBlockFormat(outer_bf);++ QTextListFormat lf;+ lf.setStyle(QTextListFormat::ListDisc);+ lf.setIndent(1);+QTextCharFormat item_fmt;+ item_fmt.setFontPointSize(12);item_fmt.setForeground(QColor(theme.text_color));+ cursor.setCharFormat(item_fmt);++ QTextList* list = nullptr;for (const auto& item : items) {if (!list) {list = cursor.insertList(lf);} else {cursor.insertBlock();+ list->add(cursor.block());}- cursor.insertText(item, item_fmt);+ // Render each item's content as markdown so **bold** and+ // emphasis inside list items work.+ if (item.contains("**") || item.contains("__") || item.contains("*"))+ cursor.insertMarkdown(item);+ else+ cursor.insertText(item, item_fmt);}++ // Terminate the list cleanly: open a fresh non-list block so the+ // next component doesn't accidentally become a list item.cursor.insertBlock();- cursor.setBlockFormat(QTextBlockFormat{});+ QTextBlockFormat reset_bf;+ cursor.setBlockFormat(reset_bf);} else if (comp.type == "chart") {QString chart_type = comp.config.value("chart_type", "line");@@ -715,27 +851,47 @@ void DocumentCanvas::render(const QVector<ReportComponent>& components, const Recursor = current_page->textCursor();} else if (comp.type == "toc") {+ QTextBlockFormat toc_hdr_bf;+ toc_hdr_bf.setTopMargin(8);+ toc_hdr_bf.setBottomMargin(6);+ cursor.setBlockFormat(toc_hdr_bf);QTextCharFormat hdr_fmt;hdr_fmt.setFontPointSize(14);hdr_fmt.setFontWeight(QFont::Bold);hdr_fmt.setForeground(QColor(theme.heading_color));- cursor.insertText("Table of Contents\n", hdr_fmt);+ cursor.insertText("Table of Contents", hdr_fmt);if (toc_headings.isEmpty()) {+ cursor.insertBlock();QTextCharFormat empty_fmt;empty_fmt.setForeground(QColor(theme.meta_color));empty_fmt.setFontPointSize(11);- cursor.insertText(" (No headings found in document)\n", empty_fmt);+ cursor.insertText(" (No headings found in document)", empty_fmt);+ cursor.insertText("\n");} else {int num = 1;for (const auto& heading : toc_headings) {cursor.insertBlock();+ QTextBlockFormat entry_bf;+ entry_bf.setLeftMargin(12);+ entry_bf.setTopMargin(2);+ entry_bf.setBottomMargin(2);+ cursor.setBlockFormat(entry_bf);++ QTextCharFormat num_fmt;+ num_fmt.setFontPointSize(11);+ num_fmt.setFontWeight(QFont::Bold);+ num_fmt.setForeground(QColor(theme.accent_color));+ cursor.insertText(QString("%1. ").arg(num++), num_fmt);+QTextCharFormat entry_fmt;entry_fmt.setFontPointSize(11);entry_fmt.setForeground(QColor(theme.text_color));- cursor.insertText(QString(" %1. %2").arg(num++).arg(heading), entry_fmt);+ cursor.insertText(heading, entry_fmt);}- cursor.insertText("\n");+ // Reset block formatting so the next component starts fresh.+ cursor.insertBlock();+ cursor.setBlockFormat(QTextBlockFormat{});}} else if (comp.type == "stats_block") {@@ -872,7 +1028,12 @@ void DocumentCanvas::render(const QVector<ReportComponent>& components, const ReQTextCharFormat body_fmt;body_fmt.setFontPointSize(11);body_fmt.setForeground(QColor(theme.text_color));- cursor.insertText(comp.content.isEmpty() ? "Enter callout text..." : comp.content, body_fmt);+ cursor.setCharFormat(body_fmt);+ const QString cbody = comp.content.isEmpty() ? "Enter callout text..." : comp.content;+ if (cbody.contains("**") || cbody.contains("__") || cbody.contains("\n- "))+ cursor.insertMarkdown(cbody);+ else+ cursor.insertText(cbody, body_fmt);cursor.insertText("\n");} else if (comp.type == "sparkline") {diff --git a/fincept-qt/src/screens/report_builder/DocumentCanvas.h b/fincept-qt/src/screens/report_builder/DocumentCanvas.hindex 48ec1dc1f..80ceeed8e 100644--- a/fincept-qt/src/screens/report_builder/DocumentCanvas.h+++ b/fincept-qt/src/screens/report_builder/DocumentCanvas.h@@ -1,4 +1,6 @@#pragma once+#include "core/report/ReportDocument.h"+#include <QScrollArea>#include <QTextEdit>#include <QVBoxLayout>@@ -6,9 +8,12 @@namespace fincept::screens {-struct ReportComponent;-struct ReportMetadata;-struct ReportTheme;+// Re-export the canonical types under the screens namespace so existing+// implementation code (which qualifies them as fincept::screens::Report*)+// keeps compiling unchanged.+using ReportComponent = ::fincept::report::ReportComponent;+using ReportMetadata = ::fincept::report::ReportMetadata;+using ReportTheme = ::fincept::report::ReportTheme;/// Center panel — paginated A4 document canvas./// Each page is a separate QTextEdit with visible gap between pages,diff --git a/fincept-qt/src/screens/report_builder/PropertiesPanel.cpp b/fincept-qt/src/screens/report_builder/PropertiesPanel.cppindex e989d7b0b..80e231676 100644--- a/fincept-qt/src/screens/report_builder/PropertiesPanel.cpp+++ b/fincept-qt/src/screens/report_builder/PropertiesPanel.cpp@@ -28,7 +28,10 @@namespace fincept::screens {PropertiesPanel::PropertiesPanel(QWidget* parent) : QWidget(parent) {- setFixedWidth(280);+ // Use min/max width pair (not setFixedWidth) so the parent splitter can+ // drive resize and the collapse animation can drive maximumWidth → 0.+ setMinimumWidth(0);+ setMaximumWidth(280);setStyleSheet(QString("background: %1; border-left: 1px solid %2;").arg(ui::colors::PANEL(), ui::colors::BORDER()));auto* vl = new QVBoxLayout(this);diff --git a/fincept-qt/src/screens/report_builder/PropertiesPanel.h b/fincept-qt/src/screens/report_builder/PropertiesPanel.hindex 826df75b0..c6d12f0bb 100644--- a/fincept-qt/src/screens/report_builder/PropertiesPanel.h+++ b/fincept-qt/src/screens/report_builder/PropertiesPanel.h@@ -1,11 +1,16 @@#pragma once+#include "core/report/ReportDocument.h"+#include <QStackedWidget>#include <QVBoxLayout>#include <QWidget>namespace fincept::screens {-struct ReportComponent;+// ReportComponent comes from core/report/ReportDocument.h. PropertiesPanel+// historically used the screens-namespace forward declaration; with the+// model migrated to fincept::report we refer to the concrete type directly.+using ReportComponent = ::fincept::report::ReportComponent;/// Right panel — context-sensitive property editor for selected component.class PropertiesPanel : public QWidget {diff --git a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cppindex 123762db7..0b48d06f3 100644--- a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp+++ b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp@@ -1,3 +1,10 @@+// ReportBuilderScreen.cpp — view onto ReportBuilderService.+//+// All document state (components, metadata, theme, undo, autosave, recent+// files) lives in the service. The screen renders that state, forwards user+// gestures to the service, and observes service signals so LLM/MCP-driven+// mutations appear live on the canvas.+#include "screens/report_builder/ReportBuilderScreen.h"#include "core/session/ScreenStateManager.h"@@ -5,25 +12,21 @@#include "datahub/DataHubMetaTypes.h"#include "services/file_manager/FileManagerService.h"#include "services/markets/MarketDataService.h"+#include "services/report_builder/ReportBuilderService.h"#include "ui/theme/Theme.h"-#include <QApplication>#include <QComboBox>-#include <QDateEdit>#include <QDateTime>#include <QDialog>#include <QDialogButtonBox>-#include <QFile>#include <QFileDialog>#include <QFormLayout>#include <QFrame>#include <QHBoxLayout>-#include <QJsonArray>-#include <QJsonDocument>-#include <QJsonObject>#include <QLabel>#include <QLineEdit>#include <QListWidget>+#include <QListWidgetItem>#include <QMessageBox>#include <QPageLayout>#include <QPageSize>@@ -32,139 +35,19 @@#include <QPrintPreviewDialog>#include <QPrinter>#include <QPushButton>-#include <QSettings>-#include <QStandardPaths>-#include <QTextDocumentWriter>+#include <QTextDocument>#include <QTextFrame>#include <QVBoxLayout>namespace fincept::screens {-// ── Undo Commands ──────────────────────────────────────────────────────────────--AddComponentCommand::AddComponentCommand(ReportBuilderScreen* screen, const ReportComponent& comp, int insert_at)- : QUndoCommand("Add " + comp.type), screen_(screen), comp_(comp), insert_at_(insert_at) {}--void AddComponentCommand::redo() {- screen_->add_component_direct(comp_, insert_at_);-}--void AddComponentCommand::undo() {- screen_->remove_component_direct(insert_at_);-}--RemoveComponentCommand::RemoveComponentCommand(ReportBuilderScreen* screen, int index)- : QUndoCommand("Remove component"), screen_(screen), index_(index) {- if (index >= 0 && index < screen->components().size()) {- saved_ = screen->components()[index];- }-}--void RemoveComponentCommand::redo() {- screen_->remove_component_direct(index_);-}--void RemoveComponentCommand::undo() {- screen_->add_component_direct(saved_, index_);-}--UpdateComponentCommand::UpdateComponentCommand(ReportBuilderScreen* screen, int index, const QString& old_content,- const QMap<QString, QString>& old_config, const QString& new_content,- const QMap<QString, QString>& new_config)- : QUndoCommand("Edit component"),- screen_(screen),- index_(index),- old_content_(old_content),- new_content_(new_content),- old_config_(old_config),- new_config_(new_config) {}--void UpdateComponentCommand::redo() {- screen_->update_component_direct(index_, new_content_, new_config_);-}--void UpdateComponentCommand::undo() {- screen_->update_component_direct(index_, old_content_, old_config_);-}--bool UpdateComponentCommand::mergeWith(const QUndoCommand* other) {- if (other->id() != id())- return false;- auto* cmd = static_cast<const UpdateComponentCommand*>(other);- if (cmd->index_ != index_)- return false;- new_content_ = cmd->new_content_;- new_config_ = cmd->new_config_;- return true;-}--MoveComponentCommand::MoveComponentCommand(ReportBuilderScreen* screen, int from, int to)- : QUndoCommand("Move component"), screen_(screen), from_(from), to_(to) {}--void MoveComponentCommand::redo() {- screen_->swap_components(from_, to_);- screen_->selected() = to_;- screen_->refresh_canvas();- screen_->refresh_structure();-}+namespace rep = ::fincept::report;+using Service = ::fincept::services::ReportBuilderService;-void MoveComponentCommand::undo() {- screen_->swap_components(to_, from_);- screen_->selected() = from_;- screen_->refresh_canvas();- screen_->refresh_structure();-}--// ── Direct (no-undo-push) operations ──────────────────────────────────────────--void ReportBuilderScreen::add_component_direct(const ReportComponent& comp, int at) {- if (at >= 0 && at <= components_.size()) {- components_.insert(at, comp);- } else {- components_.append(comp);- }- refresh_canvas();- refresh_structure();- ScreenStateManager::instance().notify_changed(this);-}--void ReportBuilderScreen::remove_component_direct(int index) {- if (index >= 0 && index < components_.size()) {- components_.removeAt(index);- if (selected_ >= components_.size())- selected_ = components_.size() - 1;- refresh_canvas();- refresh_structure();- select_component(selected_);- ScreenStateManager::instance().notify_changed(this);- }-}--void ReportBuilderScreen::update_component_direct(int index, const QString& content,- const QMap<QString, QString>& config) {- if (index >= 0 && index < components_.size()) {- components_[index].content = content;- for (auto it = config.cbegin(); it != config.cend(); ++it) {- components_[index].config[it.key()] = it.value();- }- refresh_canvas();- }-}--void ReportBuilderScreen::swap_components(int a, int b) {- if (a >= 0 && b >= 0 && a < components_.size() && b < components_.size()) {- components_.swapItemsAt(a, b);- }-}--// ── Constructor ───────────────────────────────────────────────────────────────+// ── Constructor / Destructor ─────────────────────────────────────────────────ReportBuilderScreen::ReportBuilderScreen(QWidget* parent) : QWidget(parent) {setStyleSheet(QString("background: %1;").arg(ui::colors::DARK()));- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");-- // Create undo stack first — build_toolbar() connects to it- undo_stack_ = new QUndoStack(this);auto* vl = new QVBoxLayout(this);vl->setContentsMargins(0, 0, 0, 0);@@ -194,19 +77,15 @@ ReportBuilderScreen::ReportBuilderScreen(QWidget* parent) : QWidget(parent) {vl->addWidget(splitter_, 1);- autosave_ = new QTimer(this);- autosave_->setInterval(60000);- connect(autosave_, &QTimer::timeout, this, &ReportBuilderScreen::on_auto_save);-- // ── Toolbar file/doc actions ──────────────────────────────────────────────+ // ── Component toolbar wiring ─────────────────────────────────────────connect(comp_toolbar_, &ComponentToolbar::new_report_requested, this, &ReportBuilderScreen::on_new);connect(comp_toolbar_, &ComponentToolbar::open_report_requested, this, &ReportBuilderScreen::on_open);- connect(comp_toolbar_, &ComponentToolbar::recent_reports_requested, this, &ReportBuilderScreen::show_recent_dialog);+ connect(comp_toolbar_, &ComponentToolbar::recent_reports_requested, this,+ &ReportBuilderScreen::show_recent_dialog);connect(comp_toolbar_, &ComponentToolbar::templates_requested, this, &ReportBuilderScreen::show_template_dialog);connect(comp_toolbar_, &ComponentToolbar::theme_requested, this, &ReportBuilderScreen::show_theme_dialog);connect(comp_toolbar_, &ComponentToolbar::metadata_requested, this, &ReportBuilderScreen::show_metadata_dialog);- // ── Font signal ───────────────────────────────────────────────────────────connect(comp_toolbar_, &ComponentToolbar::font_changed, this,[this](const QString& family, int size, bool bold, bool italic) {QTextCharFormat fmt;@@ -214,66 +93,58 @@ ReportBuilderScreen::ReportBuilderScreen(QWidget* parent) : QWidget(parent) {fmt.setFontPointSize(size);fmt.setFontWeight(bold ? QFont::Bold : QFont::Normal);fmt.setFontItalic(italic);- canvas_->text_edit()->mergeCurrentCharFormat(fmt);+ if (canvas_->text_edit())+ canvas_->text_edit()->mergeCurrentCharFormat(fmt);});- // ── Component signals ─────────────────────────────────────────────────────connect(comp_toolbar_, &ComponentToolbar::add_component, this, &ReportBuilderScreen::add_component);connect(comp_toolbar_, &ComponentToolbar::structure_selected, this, &ReportBuilderScreen::select_component);- connect(comp_toolbar_, &ComponentToolbar::delete_item, this, &ReportBuilderScreen::remove_component);+ connect(comp_toolbar_, &ComponentToolbar::delete_item, this, &ReportBuilderScreen::remove_component_at);+ connect(comp_toolbar_, &ComponentToolbar::duplicate, this, &ReportBuilderScreen::duplicate_at);+ connect(comp_toolbar_, &ComponentToolbar::move_up, this, &ReportBuilderScreen::move_up_at);+ connect(comp_toolbar_, &ComponentToolbar::move_down, this, &ReportBuilderScreen::move_down_at);- connect(comp_toolbar_, &ComponentToolbar::duplicate, this, [this](int idx) {- if (idx >= 0 && idx < components_.size()) {- ReportComponent copy = components_[idx];- copy.id = next_id_++;- undo_stack_->push(new AddComponentCommand(this, copy, idx + 1));- }- });- connect(comp_toolbar_, &ComponentToolbar::move_up, this, [this](int idx) {- if (idx > 0)- undo_stack_->push(new MoveComponentCommand(this, idx, idx - 1));- });- connect(comp_toolbar_, &ComponentToolbar::move_down, this, [this](int idx) {- if (idx >= 0 && idx < components_.size() - 1)- undo_stack_->push(new MoveComponentCommand(this, idx, idx + 1));- });-- // ── Properties signals ────────────────────────────────────────────────────+ // ── Properties panel wiring ───────────────────────────────────────────connect(properties_, &PropertiesPanel::content_changed, this, [this](int idx, const QString& content) {- if (idx < 0 || idx >= components_.size())+ const auto comps = Service::instance().components();+ if (idx < 0 || idx >= comps.size())return;- auto old_content = components_[idx].content;- auto old_config = components_[idx].config;- auto new_config = old_config;- undo_stack_->push(new UpdateComponentCommand(this, idx, old_content, old_config, content, new_config));+ Service::instance().update_component(comps[idx].id, content, comps[idx].config);});- connect(- properties_, &PropertiesPanel::config_changed, this, [this](int idx, const QString& key, const QString& val) {- if (idx < 0 || idx >= components_.size())- return;-- // ── stats_block: fetch real fundamentals via get_info ─────────- if (components_[idx].type == "stats_block" && key == "fetch_ticker") {- QString sym = val;- components_[idx].config["fetch_ticker"] = "";- components_[idx].config["data"] = "(Loading " + sym + "...)";- refresh_canvas();- QPointer<ReportBuilderScreen> self = this;- fincept::services::MarketDataService::instance().fetch_info(- sym, [self, idx, sym](bool ok, fincept::services::InfoData info) {- if (!self)- return;- QMetaObject::invokeMethod(- self,- [self, idx, sym, ok, info]() {- if (!self || idx >= self->components_.size())- return;- QStringList lines;- if (!ok) {- lines << "Error: Could not fetch data for " + sym;- } else {- // Format helper: show "—" for zero/missing values+ connect(properties_, &PropertiesPanel::config_changed, this,+ [this](int idx, const QString& key, const QString& val) {+ auto& svc = Service::instance();+ auto comps = svc.components();+ if (idx < 0 || idx >= comps.size())+ return;+ const int comp_id = comps[idx].id;+ const QString comp_type = comps[idx].type;++ // ── stats_block: fetch real fundamentals via get_info ─────+ if (comp_type == "stats_block" && key == "fetch_ticker") {+ QString sym = val;+ auto loading_cfg = comps[idx].config;+ loading_cfg["fetch_ticker"] = "";+ loading_cfg["data"] = "(Loading " + sym + "...)";+ svc.update_component(comp_id, comps[idx].content, loading_cfg);++ QPointer<ReportBuilderScreen> self = this;+ fincept::services::MarketDataService::instance().fetch_info(+ sym, [self, comp_id, sym](bool ok, fincept::services::InfoData info) {+ if (!self)+ return;+ QMetaObject::invokeMethod(+ self,+ [self, comp_id, sym, ok, info]() {+ if (!self)+ return;+ auto& s = Service::instance();+ int idx2 = s.index_of(comp_id);+ if (idx2 < 0)+ return;+ auto comps2 = s.components();+ QStringList lines;auto fmt_dbl = [](double v, int dec = 2) -> QString {return v != 0 ? QString::number(v, 'f', dec) : "—";};@@ -281,236 +152,219 @@ ReportBuilderScreen::ReportBuilderScreen(QWidget* parent) : QWidget(parent) {return v != 0 ? QString::number(v * 100, 'f', 2) + "%" : "—";};auto fmt_mcap = [](double v) -> QString {- if (v <= 0)- return "—";- if (v >= 1e12)- return QString::number(v / 1e12, 'f', 2) + "T";- if (v >= 1e9)- return QString::number(v / 1e9, 'f', 2) + "B";- if (v >= 1e6)- return QString::number(v / 1e6, 'f', 2) + "M";+ if (v <= 0) return QString("—");+ if (v >= 1e12) return QString::number(v / 1e12, 'f', 2) + "T";+ if (v >= 1e9) return QString::number(v / 1e9, 'f', 2) + "B";+ if (v >= 1e6) return QString::number(v / 1e6, 'f', 2) + "M";return QString::number(v, 'f', 0);};auto fmt_vol = [](double v) -> QString {- if (v <= 0)- return "—";- if (v >= 1e9)- return QString::number(v / 1e9, 'f', 2) + "B";- if (v >= 1e6)- return QString::number(v / 1e6, 'f', 2) + "M";- if (v >= 1e3)- return QString::number(v / 1e3, 'f', 1) + "K";+ if (v <= 0) return QString("—");+ if (v >= 1e9) return QString::number(v / 1e9, 'f', 2) + "B";+ if (v >= 1e6) return QString::number(v / 1e6, 'f', 2) + "M";+ if (v >= 1e3) return QString::number(v / 1e3, 'f', 1) + "K";return QString::number(v, 'f', 0);};- if (!info.name.isEmpty())- lines << "Company: " + info.name;- if (!info.sector.isEmpty())- lines << "Sector: " + info.sector;- if (!info.industry.isEmpty())- lines << "Industry: " + info.industry;- if (!info.country.isEmpty())- lines << "Country: " + info.country;- lines << "Market Cap: " + fmt_mcap(info.market_cap);- lines << "P/E Ratio: " + fmt_dbl(info.pe_ratio);- lines << "Forward P/E: " + fmt_dbl(info.forward_pe);- lines << "Price/Book: " + fmt_dbl(info.price_to_book);- lines << "Dividend Yield: " + fmt_pct(info.dividend_yield);- lines << "Beta: " + fmt_dbl(info.beta);- lines << "52W High: " + fmt_dbl(info.week52_high);- lines << "52W Low: " + fmt_dbl(info.week52_low);- lines << "Avg Volume: " + fmt_vol(info.avg_volume);- lines << "ROE: " + fmt_pct(info.roe);- lines << "Profit Margin: " + fmt_pct(info.profit_margin);- if (info.debt_to_equity != 0)- lines << "Debt/Equity: " + fmt_dbl(info.debt_to_equity);- if (info.current_ratio != 0)- lines << "Current Ratio: " + fmt_dbl(info.current_ratio);- if (info.eps != 0)- lines << "Rev/Share: " + fmt_dbl(info.eps);- }- self->components_[idx].config["data"] = lines.join("\n");- self->components_[idx].config["fetch_ticker"] = "";- self->refresh_canvas();- if (self->selected_ == idx)- self->properties_->show_properties(&self->components_[idx], idx);- },- Qt::QueuedConnection);- });- return;- }-- // ── chart: hub-driven 6mo/1d history fetch ─────────────────────- if (components_[idx].type == "chart" && key == "fetch_history") {- QString sym = val;- components_[idx].config["fetch_history"] = "";- components_[idx].config["data"] = ""; // clear stale data- refresh_canvas();-- // Use 6-month daily history by default. Topic format:- // market:history:<sym>:<period>:<interval>- const QString topic =- QStringLiteral("market:history:") + sym + QStringLiteral(":6mo:1d");- auto& hub = fincept::datahub::DataHub::instance();-- // Rendering helper — writes the chart data into components_[idx]- // from a HistoryPoint vector.- QPointer<ReportBuilderScreen> self = this;- auto apply = [self, idx, sym](const QVector<fincept::services::HistoryPoint>& history) {- if (!self || idx >= self->components_.size())- return;- if (history.isEmpty()) {- self->components_[idx].config["data"] = "";- self->refresh_canvas();- return;- }- QStringList pts, lbls;- int step = qMax(1, history.size() / 20); // max ~20 points- for (int i = 0; i < history.size(); i += step) {- const auto& pt = history[i];- pts << QString::number(pt.close, 'f', 2);- QDateTime dt = QDateTime::fromSecsSinceEpoch(pt.timestamp);- lbls << dt.toString("MMM d");- }- if ((history.size() - 1) % step != 0) {- pts << QString::number(history.last().close, 'f', 2);- lbls << QDateTime::fromSecsSinceEpoch(history.last().timestamp)- .toString("MMM d");- }- self->components_[idx].config["data"] = pts.join(",");- self->components_[idx].config["labels"] = lbls.join(",");- if (self->components_[idx].config.value("title").isEmpty() ||- self->components_[idx].config.value("title") == "Chart")- self->components_[idx].config["title"] = sym + " (6mo)";- self->refresh_canvas();- if (self->selected_ == idx)- self->properties_->show_properties(&self->components_[idx], idx);- };-- // Cached snapshot first (instant render if data is fresh on the hub).- QVariant cached = hub.peek(topic);- if (cached.isValid() && cached.canConvert<QVector<fincept::services::HistoryPoint>>()) {- apply(cached.value<QVector<fincept::services::HistoryPoint>>());+ if (!ok) {+ lines << "Error: Could not fetch data for " + sym;+ } else {+ if (!info.name.isEmpty()) lines << "Company: " + info.name;+ if (!info.sector.isEmpty()) lines << "Sector: " + info.sector;+ if (!info.industry.isEmpty()) lines << "Industry: " + info.industry;+ if (!info.country.isEmpty()) lines << "Country: " + info.country;+ lines << "Market Cap: " + fmt_mcap(info.market_cap);+ lines << "P/E Ratio: " + fmt_dbl(info.pe_ratio);+ lines << "Forward P/E: " + fmt_dbl(info.forward_pe);+ lines << "Price/Book: " + fmt_dbl(info.price_to_book);+ lines << "Dividend Yield: " + fmt_pct(info.dividend_yield);+ lines << "Beta: " + fmt_dbl(info.beta);+ lines << "52W High: " + fmt_dbl(info.week52_high);+ lines << "52W Low: " + fmt_dbl(info.week52_low);+ lines << "Avg Volume: " + fmt_vol(info.avg_volume);+ lines << "ROE: " + fmt_pct(info.roe);+ lines << "Profit Margin: " + fmt_pct(info.profit_margin);+ if (info.debt_to_equity != 0)+ lines << "Debt/Equity: " + fmt_dbl(info.debt_to_equity);+ if (info.current_ratio != 0)+ lines << "Current Ratio: " + fmt_dbl(info.current_ratio);+ if (info.eps != 0) lines << "Rev/Share: " + fmt_dbl(info.eps);+ }+ auto cfg = comps2[idx2].config;+ cfg["data"] = lines.join("\n");+ cfg["fetch_ticker"] = "";+ s.update_component(comp_id, comps2[idx2].content, cfg);+ },+ Qt::QueuedConnection);+ });return;}- // Otherwise: subscribe-once, force-kick the producer. The first- // delivery renders then tears down the subscription so the- // report-builder doesn't keep receiving updates it doesn't want.- hub.subscribe<QVector<fincept::services::HistoryPoint>>(- this, topic,- [self, topic, apply](const QVector<fincept::services::HistoryPoint>& history) {- if (!self)- return;- apply(history);- fincept::datahub::DataHub::instance().unsubscribe(self, topic);- });- hub.request(topic, /*force=*/true);- return;- }-- // For market_data "status=loading", trigger a hub-driven quote fetch.- if (components_[idx].type == "market_data" && key == "status" && val == "loading") {- QString sym = components_[idx].config.value("symbol", "");- if (sym.isEmpty()) {- return; // don't push undo for status change- }- components_[idx].config["status"] = "loading";- refresh_canvas();+ // ── chart: hub-driven 6mo/1d history fetch ─────────────────+ if (comp_type == "chart" && key == "fetch_history") {+ QString sym = val;+ auto cfg = comps[idx].config;+ cfg["fetch_history"] = "";+ cfg["data"] = "";+ svc.update_component(comp_id, comps[idx].content, cfg);- const QString topic = QStringLiteral("market:quote:") + sym;- auto& hub = fincept::datahub::DataHub::instance();- QPointer<ReportBuilderScreen> self = this;+ const QString topic = QStringLiteral("market:history:") + sym + QStringLiteral(":6mo:1d");+ auto& hub = fincept::datahub::DataHub::instance();+ QPointer<ReportBuilderScreen> self = this;- auto apply = [self, idx](const fincept::services::QuoteData& q) {- if (!self || idx >= self->components_.size())+ auto apply = [self, comp_id, sym](const QVector<fincept::services::HistoryPoint>& history) {+ if (!self)+ return;+ auto& s = Service::instance();+ int idx2 = s.index_of(comp_id);+ if (idx2 < 0)+ return;+ auto comps2 = s.components();+ if (history.isEmpty()) {+ auto cfg2 = comps2[idx2].config;+ cfg2["data"] = "";+ s.update_component(comp_id, comps2[idx2].content, cfg2);+ return;+ }+ QStringList pts, lbls;+ int step = qMax(1, history.size() / 20);+ for (int i = 0; i < history.size(); i += step) {+ const auto& pt = history[i];+ pts << QString::number(pt.close, 'f', 2);+ QDateTime dt = QDateTime::fromSecsSinceEpoch(pt.timestamp);+ lbls << dt.toString("MMM d");+ }+ if ((history.size() - 1) % step != 0) {+ pts << QString::number(history.last().close, 'f', 2);+ lbls << QDateTime::fromSecsSinceEpoch(history.last().timestamp).toString("MMM d");+ }+ auto cfg2 = comps2[idx2].config;+ cfg2["data"] = pts.join(",");+ cfg2["labels"] = lbls.join(",");+ if (cfg2.value("title").isEmpty() || cfg2.value("title") == "Chart")+ cfg2["title"] = sym + " (6mo)";+ s.update_component(comp_id, comps2[idx2].content, cfg2);+ };++ QVariant cached = hub.peek(topic);+ if (cached.isValid() && cached.canConvert<QVector<fincept::services::HistoryPoint>>()) {+ apply(cached.value<QVector<fincept::services::HistoryPoint>>());return;- self->components_[idx].config["price"] = QString::number(q.price, 'f', 2);- self->components_[idx].config["change"] = QString::number(q.change, 'f', 2);- self->components_[idx].config["change_pct"] =- QString::number(q.change_pct, 'f', 2);- self->components_[idx].config["name"] = q.name;- self->components_[idx].config["high"] =- q.high > 0 ? QString::number(q.high, 'f', 2) : "";- self->components_[idx].config["low"] =- q.low > 0 ? QString::number(q.low, 'f', 2) : "";- self->components_[idx].config["volume"] =- q.volume > 0 ? QString::number(q.volume, 'f', 0) : "";- self->components_[idx].config["status"] = "ok";- self->refresh_canvas();- if (self->selected_ == idx) {- self->properties_->show_properties(&self->components_[idx], idx);}- };- // Fast path: render from cached quote if fresh on the hub.- QVariant cached = hub.peek(topic);- if (cached.isValid() && cached.canConvert<fincept::services::QuoteData>()) {- apply(cached.value<fincept::services::QuoteData>());- return; // don't push undo for status change+ hub.subscribe<QVector<fincept::services::HistoryPoint>>(+ this, topic,+ [self, topic, apply](const QVector<fincept::services::HistoryPoint>& history) {+ if (!self)+ return;+ apply(history);+ fincept::datahub::DataHub::instance().unsubscribe(self, topic);+ });+ hub.request(topic, /*force=*/true);+ return;}- // Otherwise: subscribe-once then tear down — this is a- // one-shot user refresh, not a live ticker.- hub.subscribe<fincept::services::QuoteData>(- this, topic,- [self, topic, apply](const fincept::services::QuoteData& q) {+ // ── market_data: hub-driven quote fetch ───────────────────+ if (comp_type == "market_data" && key == "status" && val == "loading") {+ auto cfg = comps[idx].config;+ QString sym = cfg.value("symbol", "");+ if (sym.isEmpty())+ return;+ cfg["status"] = "loading";+ svc.update_component(comp_id, comps[idx].content, cfg);++ const QString topic = QStringLiteral("market:quote:") + sym;+ auto& hub = fincept::datahub::DataHub::instance();+ QPointer<ReportBuilderScreen> self = this;++ auto apply = [self, comp_id](const fincept::services::QuoteData& q) {if (!self)return;- apply(q);- fincept::datahub::DataHub::instance().unsubscribe(self, topic);- });- hub.request(topic, /*force=*/true);- return; // don't push undo for status change- }-- auto old_content = components_[idx].content;- auto old_config = components_[idx].config;- auto new_config = old_config;- new_config[key] = val;- undo_stack_->push(new UpdateComponentCommand(this, idx, old_content, old_config, old_content, new_config));- });-- connect(properties_, &PropertiesPanel::duplicate_requested, this, [this](int idx) {- if (idx >= 0 && idx < components_.size()) {- ReportComponent copy = components_[idx];- copy.id = next_id_++;- undo_stack_->push(new AddComponentCommand(this, copy, idx + 1));- }- });- connect(properties_, &PropertiesPanel::delete_requested, this, &ReportBuilderScreen::remove_component);+ auto& s = Service::instance();+ int idx2 = s.index_of(comp_id);+ if (idx2 < 0)+ return;+ auto comps2 = s.components();+ auto cfg2 = comps2[idx2].config;+ cfg2["price"] = QString::number(q.price, 'f', 2);+ cfg2["change"] = QString::number(q.change, 'f', 2);+ cfg2["change_pct"] = QString::number(q.change_pct, 'f', 2);+ cfg2["name"] = q.name;+ cfg2["high"] = q.high > 0 ? QString::number(q.high, 'f', 2) : "";+ cfg2["low"] = q.low > 0 ? QString::number(q.low, 'f', 2) : "";+ cfg2["volume"] = q.volume > 0 ? QString::number(q.volume, 'f', 0) : "";+ cfg2["status"] = "ok";+ s.update_component(comp_id, comps2[idx2].content, cfg2);+ };++ QVariant cached = hub.peek(topic);+ if (cached.isValid() && cached.canConvert<fincept::services::QuoteData>()) {+ apply(cached.value<fincept::services::QuoteData>());+ return;+ }+ hub.subscribe<fincept::services::QuoteData>(+ this, topic,+ [self, topic, apply](const fincept::services::QuoteData& q) {+ if (!self)+ return;+ apply(q);+ fincept::datahub::DataHub::instance().unsubscribe(self, topic);+ });+ hub.request(topic, /*force=*/true);+ return;+ }++ // Generic single-key config patch.+ QMap<QString, QString> patch;+ patch[key] = val;+ svc.patch_component(comp_id, nullptr, patch);+ });++ connect(properties_, &PropertiesPanel::duplicate_requested, this, &ReportBuilderScreen::duplicate_at);+ connect(properties_, &PropertiesPanel::delete_requested, this, &ReportBuilderScreen::remove_component_at);- // ── Canvas drag-and-drop ──────────────────────────────────────────────────+ // ── Canvas drag-and-drop ──────────────────────────────────────────────connect(canvas_, &DocumentCanvas::image_dropped, this, [this](const QString& path) {- // If selected component is an image, update its path- if (selected_ >= 0 && selected_ < components_.size() && components_[selected_].type == "image") {- auto old_content = components_[selected_].content;- auto old_config = components_[selected_].config;- auto new_config = old_config;- new_config["path"] = path;- new_config["clipboard"] = "";- undo_stack_->push(- new UpdateComponentCommand(this, selected_, old_content, old_config, old_content, new_config));- select_component(selected_);+ auto& svc = Service::instance();+ auto comps = svc.components();+ // If selected component is an image, update its path.+ int sel_idx = (selected_id_ > 0) ? svc.index_of(selected_id_) : -1;+ if (sel_idx >= 0 && comps[sel_idx].type == "image") {+ auto cfg = comps[sel_idx].config;+ cfg["path"] = path;+ cfg["clipboard"] = "";+ svc.update_component(comps[sel_idx].id, comps[sel_idx].content, cfg);} else {- // Insert a new image component- ReportComponent comp;- comp.id = next_id_++;+ rep::ReportComponent comp;comp.type = "image";comp.config["path"] = path;comp.config["width"] = "400";comp.config["align"] = "left";- int at = (selected_ >= 0 && selected_ < components_.size()) ? selected_ + 1 : components_.size();- undo_stack_->push(new AddComponentCommand(this, comp, at));- selected_ = at;- select_component(selected_);+ int at = (sel_idx >= 0) ? sel_idx + 1 : -1;+ int new_id = svc.add_component(comp, at);+ selected_id_ = new_id;+ select_component(svc.index_of(new_id));}});- refresh_canvas();+ // ── Service signals → screen ──────────────────────────────────────────+ connect(&Service::instance(), &Service::component_added, this, &ReportBuilderScreen::on_component_added);+ connect(&Service::instance(), &Service::component_updated, this, &ReportBuilderScreen::on_component_updated);+ connect(&Service::instance(), &Service::component_removed, this, &ReportBuilderScreen::on_component_removed);+ connect(&Service::instance(), &Service::component_moved, this, &ReportBuilderScreen::on_component_moved);+ connect(&Service::instance(), &Service::metadata_changed, this, &ReportBuilderScreen::on_metadata_changed);+ connect(&Service::instance(), &Service::theme_changed, this, &ReportBuilderScreen::on_theme_changed);+ connect(&Service::instance(), &Service::document_changed, this, &ReportBuilderScreen::on_document_changed);+ connect(&Service::instance(), &Service::document_loaded, this, &ReportBuilderScreen::on_document_loaded);++ // First render — pull whatever the service already holds (autosave restore,+ // earlier LLM mutations while the screen wasn't open, etc.).+ rebind_from_service();}-// ── Top Toolbar ───────────────────────────────────────────────────────────────+ReportBuilderScreen::~ReportBuilderScreen() = default;++// ── Top toolbar ──────────────────────────────────────────────────────────────QWidget* ReportBuilderScreen::build_toolbar() {auto* bar = new QWidget(this);@@ -521,6 +375,25 @@ QWidget* ReportBuilderScreen::build_toolbar() {hl->setContentsMargins(8, 0, 8, 0);hl->setSpacing(6);+ auto make_panel_toggle = [&](const char* glyph, const char* tooltip, const char* shortcut) {+ auto* b = new QPushButton(glyph);+ b->setFixedSize(26, 26);+ b->setCursor(Qt::PointingHandCursor);+ b->setToolTip(tooltip);+ if (shortcut)+ b->setShortcut(QKeySequence(shortcut));+ b->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"+ "border-radius:0px;font-size:14px;font-weight:700;padding:0;}"+ "QPushButton:hover{background:%3;color:%4;border-color:%4;}")+ .arg(ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_DIM(), ui::colors::BG_HOVER(),+ ui::colors::AMBER()));+ hl->addWidget(b);+ return b;+ };++ left_toggle_btn_ = make_panel_toggle("‹", "Collapse components panel (Ctrl+B)", "Ctrl+B");+ connect(left_toggle_btn_, &QPushButton::clicked, this, &ReportBuilderScreen::on_toggle_left);+auto* title = new QLabel("REPORT BUILDER");title->setStyleSheet(QString("color: %1; font-size: 14px; font-weight: bold; background: transparent;").arg(ui::colors::AMBER()));@@ -535,15 +408,17 @@ QWidget* ReportBuilderScreen::build_toolbar() {return b;};+ auto* undo_stack = Service::instance().undo_stack();+auto* undo_btn = make_btn("Undo");- undo_btn->setEnabled(false);- connect(undo_stack_, &QUndoStack::canUndoChanged, undo_btn, &QPushButton::setEnabled);- connect(undo_btn, &QPushButton::clicked, undo_stack_, &QUndoStack::undo);+ undo_btn->setEnabled(undo_stack->canUndo());+ connect(undo_stack, &QUndoStack::canUndoChanged, undo_btn, &QPushButton::setEnabled);+ connect(undo_btn, &QPushButton::clicked, undo_stack, &QUndoStack::undo);auto* redo_btn = make_btn("Redo");- redo_btn->setEnabled(false);- connect(undo_stack_, &QUndoStack::canRedoChanged, redo_btn, &QPushButton::setEnabled);- connect(redo_btn, &QPushButton::clicked, undo_stack_, &QUndoStack::redo);+ redo_btn->setEnabled(undo_stack->canRedo());+ connect(undo_stack, &QUndoStack::canRedoChanged, redo_btn, &QPushButton::setEnabled);+ connect(redo_btn, &QPushButton::clicked, undo_stack, &QUndoStack::redo);make_btn("|")->setEnabled(false);@@ -560,60 +435,225 @@ QWidget* ReportBuilderScreen::build_toolbar() {auto* preview_btn = make_btn("Preview");connect(preview_btn, &QPushButton::clicked, this, &ReportBuilderScreen::on_preview);+ right_toggle_btn_ = make_panel_toggle("›", "Collapse properties panel (Ctrl+Shift+B)", "Ctrl+Shift+B");+ connect(right_toggle_btn_, &QPushButton::clicked, this, &ReportBuilderScreen::on_toggle_right);+return bar;}-// ── Component operations (push to undo stack) ─────────────────────────────────+// ── Side-panel collapse ──────────────────────────────────────────────────────++void ReportBuilderScreen::on_toggle_left() { apply_left_collapsed(!left_collapsed_, /*animate=*/true); }+void ReportBuilderScreen::on_toggle_right() { apply_right_collapsed(!right_collapsed_, /*animate=*/true); }++void ReportBuilderScreen::apply_left_collapsed(bool collapsed, bool animate) {+ left_collapsed_ = collapsed;+ if (!comp_toolbar_)+ return;+ const int target = collapsed ? 0 : kLeftPanelWidth;+ if (!left_anim_) {+ left_anim_ = new QPropertyAnimation(comp_toolbar_, "maximumWidth", this);+ left_anim_->setDuration(180);+ left_anim_->setEasingCurve(QEasingCurve::OutCubic);+ }+ left_anim_->stop();+ if (animate) {+ left_anim_->setStartValue(comp_toolbar_->maximumWidth());+ left_anim_->setEndValue(target);+ left_anim_->start();+ } else {+ comp_toolbar_->setMaximumWidth(target);+ }+ if (left_toggle_btn_) {+ left_toggle_btn_->setText(collapsed ? "›" : "‹");+ left_toggle_btn_->setToolTip(collapsed ? "Expand components panel (Ctrl+B)"+ : "Collapse components panel (Ctrl+B)");+ }+}++void ReportBuilderScreen::apply_right_collapsed(bool collapsed, bool animate) {+ right_collapsed_ = collapsed;+ if (!properties_)+ return;+ const int target = collapsed ? 0 : kRightPanelWidth;+ if (!right_anim_) {+ right_anim_ = new QPropertyAnimation(properties_, "maximumWidth", this);+ right_anim_->setDuration(180);+ right_anim_->setEasingCurve(QEasingCurve::OutCubic);+ }+ right_anim_->stop();+ if (animate) {+ right_anim_->setStartValue(properties_->maximumWidth());+ right_anim_->setEndValue(target);+ right_anim_->start();+ } else {+ properties_->setMaximumWidth(target);+ }+ if (right_toggle_btn_) {+ right_toggle_btn_->setText(collapsed ? "‹" : "›");+ right_toggle_btn_->setToolTip(collapsed ? "Expand properties panel (Ctrl+Shift+B)"+ : "Collapse properties panel (Ctrl+Shift+B)");+ }+}++// ── User-driven mutations (delegate to service) ──────────────────────────────void ReportBuilderScreen::add_component(const QString& type) {- ReportComponent comp;- comp.id = next_id_++;+ rep::ReportComponent comp;comp.type = type;-if (type == "table") {comp.config["rows"] = "3";comp.config["cols"] = "3";}-- int at = (selected_ >= 0 && selected_ < components_.size()) ? selected_ + 1 : components_.size();- undo_stack_->push(new AddComponentCommand(this, comp, at));- selected_ = at;- select_component(selected_);+ auto& svc = Service::instance();+ int sel_idx = (selected_id_ > 0) ? svc.index_of(selected_id_) : -1;+ int at = (sel_idx >= 0) ? sel_idx + 1 : -1;+ int new_id = svc.add_component(comp, at);+ selected_id_ = new_id;+ select_component(svc.index_of(new_id));}void ReportBuilderScreen::select_component(int index) {- selected_ = index;- if (index >= 0 && index < components_.size()) {- properties_->show_properties(&components_[index], index);+ auto comps = Service::instance().components();+ if (index >= 0 && index < comps.size()) {+ selected_id_ = comps[index].id;+ properties_->show_properties(&comps[index], index);} else {+ selected_id_ = 0;properties_->show_empty();}refresh_canvas();+ refresh_structure();+}++void ReportBuilderScreen::remove_component_at(int index) {+ auto comps = Service::instance().components();+ if (index < 0 || index >= comps.size())+ return;+ Service::instance().remove_component(comps[index].id);+}++void ReportBuilderScreen::duplicate_at(int index) {+ auto comps = Service::instance().components();+ if (index < 0 || index >= comps.size())+ return;+ rep::ReportComponent copy = comps[index];+ copy.id = 0; // service allocates a fresh id+ int new_id = Service::instance().add_component(copy, index + 1);+ selected_id_ = new_id;+}++void ReportBuilderScreen::move_up_at(int index) {+ auto comps = Service::instance().components();+ if (index <= 0 || index >= comps.size())+ return;+ Service::instance().move_component(comps[index].id, index - 1);+}++void ReportBuilderScreen::move_down_at(int index) {+ auto comps = Service::instance().components();+ if (index < 0 || index >= comps.size() - 1)+ return;+ Service::instance().move_component(comps[index].id, index + 1);+}++// ── Service signal handlers ──────────────────────────────────────────────────++void ReportBuilderScreen::rebind_from_service() {+ auto& svc = Service::instance();+ auto comps = svc.components();+ if (selected_id_ > 0 && svc.index_of(selected_id_) < 0)+ selected_id_ = 0;+ if (selected_id_ == 0 && !comps.isEmpty())+ selected_id_ = comps.first().id;+ refresh_canvas();+ refresh_structure();+ int sel_idx = (selected_id_ > 0) ? svc.index_of(selected_id_) : -1;+ if (sel_idx >= 0)+ properties_->show_properties(&svc.components()[sel_idx], sel_idx);+ else+ properties_->show_empty();}-void ReportBuilderScreen::remove_component(int index) {- if (index >= 0 && index < components_.size()) {- undo_stack_->push(new RemoveComponentCommand(this, index));+void ReportBuilderScreen::on_component_added(int id, int /*index*/) {+ selected_id_ = id;+ auto& svc = Service::instance();+ int sel_idx = svc.index_of(id);+ refresh_canvas();+ refresh_structure();+ if (sel_idx >= 0)+ properties_->show_properties(&svc.components()[sel_idx], sel_idx);+ ScreenStateManager::instance().notify_changed(this);+}++void ReportBuilderScreen::on_component_updated(int id) {+ refresh_canvas();+ refresh_structure();+ if (id == selected_id_) {+ auto& svc = Service::instance();+ int sel_idx = svc.index_of(id);+ if (sel_idx >= 0)+ properties_->show_properties(&svc.components()[sel_idx], sel_idx);}+ ScreenStateManager::instance().notify_changed(this);}-void ReportBuilderScreen::update_component(int index, const QString& content, const QMap<QString, QString>& config) {- if (index >= 0 && index < components_.size()) {- auto old_content = components_[index].content;- auto old_config = components_[index].config;- undo_stack_->push(new UpdateComponentCommand(this, index, old_content, old_config, content, config));+void ReportBuilderScreen::on_component_removed(int id, int /*prior_index*/) {+ if (id == selected_id_) {+ // Pick a sensible neighbour as the new selection.+ auto comps = Service::instance().components();+ selected_id_ = comps.isEmpty() ? 0 : comps.first().id;}+ refresh_canvas();+ refresh_structure();+ int sel_idx = (selected_id_ > 0) ? Service::instance().index_of(selected_id_) : -1;+ if (sel_idx >= 0)+ properties_->show_properties(&Service::instance().components()[sel_idx], sel_idx);+ else+ properties_->show_empty();+ ScreenStateManager::instance().notify_changed(this);}-// ── Refresh ───────────────────────────────────────────────────────────────────+void ReportBuilderScreen::on_component_moved(int /*id*/, int /*from*/, int /*to*/) {+ refresh_canvas();+ refresh_structure();+ ScreenStateManager::instance().notify_changed(this);+}++void ReportBuilderScreen::on_metadata_changed() {+ refresh_canvas();+ ScreenStateManager::instance().notify_changed(this);+}++void ReportBuilderScreen::on_theme_changed() {+ refresh_canvas();+ ScreenStateManager::instance().notify_changed(this);+}++void ReportBuilderScreen::on_document_changed() {+ // Coarse signal — only refresh structure (canvas is repainted by the+ // fine-grained handlers that fire alongside).+ refresh_structure();+}++void ReportBuilderScreen::on_document_loaded(const QString& /*path*/) {+ selected_id_ = 0;+ rebind_from_service();+}++// ── Refresh ──────────────────────────────────────────────────────────────────void ReportBuilderScreen::refresh_canvas() {- canvas_->render(components_, metadata_, theme_, selected_);+ auto& svc = Service::instance();+ auto comps = svc.components();+ int sel_idx = (selected_id_ > 0) ? svc.index_of(selected_id_) : -1;+ canvas_->render(comps, svc.metadata(), svc.theme(), sel_idx);}void ReportBuilderScreen::refresh_structure() {+ auto comps = Service::instance().components();QStringList items;- for (const auto& c : components_) {+ for (const auto& c : comps) {QString label = c.type.toUpper();if (!c.content.isEmpty())label += ": " + c.content.left(28);@@ -629,134 +669,14 @@ void ReportBuilderScreen::refresh_structure() {label += " [" + c.config.value("style", "info") + "]";items << label;}- comp_toolbar_->update_structure(items, selected_);+ int sel_idx = (selected_id_ > 0) ? Service::instance().index_of(selected_id_) : -1;+ comp_toolbar_->update_structure(items, sel_idx);}-// ── Serialization ─────────────────────────────────────────────────────────────--QString ReportBuilderScreen::serialize_to_json() const {- QJsonObject root;-- // Metadata- QJsonObject meta;- meta["title"] = metadata_.title;- meta["author"] = metadata_.author;- meta["company"] = metadata_.company;- meta["date"] = metadata_.date;- meta["header_left"] = metadata_.header_left;- meta["header_center"] = metadata_.header_center;- meta["header_right"] = metadata_.header_right;- meta["footer_left"] = metadata_.footer_left;- meta["footer_center"] = metadata_.footer_center;- meta["footer_right"] = metadata_.footer_right;- meta["show_page_numbers"] = metadata_.show_page_numbers;- root["metadata"] = meta;-- // Theme- root["theme"] = theme_.name;-- // Components- QJsonArray comps;- for (const auto& c : components_) {- QJsonObject obj;- obj["id"] = c.id;- obj["type"] = c.type;- obj["content"] = c.content;- QJsonObject cfg;- for (auto it = c.config.cbegin(); it != c.config.cend(); ++it) {- cfg[it.key()] = it.value();- }- obj["config"] = cfg;- comps.append(obj);- }- root["components"] = comps;- root["next_id"] = next_id_;-- return QString::fromUtf8(QJsonDocument(root).toJson(QJsonDocument::Indented));-}--bool ReportBuilderScreen::deserialize_from_json(const QString& json) {- QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());- if (!doc.isObject())- return false;- QJsonObject root = doc.object();-- // Metadata- if (root.contains("metadata")) {- QJsonObject m = root["metadata"].toObject();- metadata_.title = m.value("title").toString("Untitled Report");- metadata_.author = m.value("author").toString("Analyst");- metadata_.company = m.value("company").toString("Fincept Corporation");- metadata_.date = m.value("date").toString();- metadata_.header_left = m.value("header_left").toString();- metadata_.header_center = m.value("header_center").toString();- metadata_.header_right = m.value("header_right").toString();- metadata_.footer_left = m.value("footer_left").toString();- metadata_.footer_center = m.value("footer_center").toString("Page {page}");- metadata_.footer_right = m.value("footer_right").toString();- metadata_.show_page_numbers = m.value("show_page_numbers").toBool(true);- }-- // Theme- if (root.contains("theme")) {- QString tname = root["theme"].toString();- if (tname == "Dark Corporate")- theme_ = report_themes::dark_corporate();- else if (tname == "Bloomberg Terminal")- theme_ = report_themes::bloomberg();- else if (tname == "Midnight Blue")- theme_ = report_themes::midnight_blue();- else- theme_ = report_themes::light_professional();- }-- // Components- components_.clear();- next_id_ = 1;- if (root.contains("components")) {- for (const auto& val : root["components"].toArray()) {- QJsonObject obj = val.toObject();- ReportComponent c;- c.id = obj["id"].toInt(next_id_);- c.type = obj["type"].toString();- c.content = obj["content"].toString();- for (const auto& k : obj["config"].toObject().keys()) {- c.config[k] = obj["config"].toObject()[k].toString();- }- components_.append(c);- if (c.id >= next_id_)- next_id_ = c.id + 1;- }- }- if (root.contains("next_id"))- next_id_ = root["next_id"].toInt(next_id_);-- selected_ = components_.isEmpty() ? -1 : 0;- undo_stack_->clear();- return true;-}--// ── Recent files ──────────────────────────────────────────────────────────────--void ReportBuilderScreen::update_recent(const QString& path) {- QSettings s("Fincept", "FinceptTerminal");- QStringList recent = s.value("report_builder/recent").toStringList();- recent.removeAll(path);- recent.prepend(path);- if (recent.size() > 10)- recent = recent.mid(0, 10);- s.setValue("report_builder/recent", recent);-}--QStringList ReportBuilderScreen::load_recent() const {- QSettings s("Fincept", "FinceptTerminal");- return s.value("report_builder/recent").toStringList();-}--// ── Dialogs ───────────────────────────────────────────────────────────────────+// ── Dialogs ──────────────────────────────────────────────────────────────────void ReportBuilderScreen::show_recent_dialog() {- QStringList recent = load_recent();+ QStringList recent = Service::instance().recent_files();auto* dlg = new QDialog(this);dlg->setWindowTitle("Recent Reports");@@ -768,7 +688,8 @@ void ReportBuilderScreen::show_recent_dialog() {"QListWidget::item:selected { background: %5; }""QPushButton { background: %3; color: %2; border: 1px solid %4; padding: 6px 16px; }""QPushButton:hover { background: %5; }")- .arg(ui::colors::DARK(), ui::colors::WHITE(), ui::colors::PANEL(), ui::colors::BORDER(), ui::colors::BG_RAISED()));+ .arg(ui::colors::DARK(), ui::colors::WHITE(), ui::colors::PANEL(), ui::colors::BORDER(),+ ui::colors::BG_RAISED()));auto* vl = new QVBoxLayout(dlg);auto* lbl = new QLabel("Select a report to open:");@@ -786,28 +707,27 @@ void ReportBuilderScreen::show_recent_dialog() {auto* bb = new QDialogButtonBox(QDialogButtonBox::Open | QDialogButtonBox::Cancel);vl->addWidget(bb);- connect(bb, &QDialogButtonBox::accepted, dlg, [this, list, recent, dlg]() {+ auto open_selected = [list, recent, dlg, this]() {int row = list->currentRow();if (row >= 0 && row < recent.size()) {- load_report(recent[row]);+ auto r = Service::instance().load_from(recent[row]);+ if (r.is_err())+ QMessageBox::warning(this, "Open Report",+ "Could not open file:\n" + recent[row] + "\n\n" ++ QString::fromStdString(r.error()));}dlg->accept();- });+ };++ connect(bb, &QDialogButtonBox::accepted, dlg, open_selected);connect(bb, &QDialogButtonBox::rejected, dlg, &QDialog::reject);- connect(list, &QListWidget::itemDoubleClicked, dlg, [this, list, recent, dlg](QListWidgetItem*) {- int row = list->currentRow();- if (row >= 0 && row < recent.size()) {- load_report(recent[row]);- }- dlg->accept();- });+ connect(list, &QListWidget::itemDoubleClicked, dlg, [open_selected](QListWidgetItem*) { open_selected(); });dlg->exec();dlg->deleteLater();}void ReportBuilderScreen::show_template_dialog() {- // category → list of {name, description}struct TemplateEntry {QString name;QString description;@@ -819,60 +739,42 @@ void ReportBuilderScreen::show_template_dialog() {const QVector<Category> categories = {{"General Purpose",- {- {"Blank Report", "Empty document with title and date — start from scratch."},- {"Meeting Notes", "Agenda, attendees, discussion points, action items, next steps."},- {"Investment Memo", "Executive summary, thesis, opportunity, risks, recommendation."},- }},+ {{"Blank Report", "Empty document with title and date — start from scratch."},+ {"Meeting Notes", "Agenda, attendees, discussion points, action items, next steps."},+ {"Investment Memo", "Executive summary, thesis, opportunity, risks, recommendation."}}},{"Retail Investor",- {- {"Stock Research", "Company overview, financials, valuation, thesis, and risks."},- {"Portfolio Review", "Holdings, performance, allocation pie, risk metrics, notes."},- {"Watchlist Report", "Tracked tickers with price, change, target, and notes columns."},- {"Dividend Income Report", "Dividend stocks table, yield chart, income projection, calendar."},- }},+ {{"Stock Research", "Company overview, financials, valuation, thesis, and risks."},+ {"Portfolio Review", "Holdings, performance, allocation pie, risk metrics, notes."},+ {"Watchlist Report", "Tracked tickers with price, change, target, and notes columns."},+ {"Dividend Income Report", "Dividend stocks table, yield chart, income projection, calendar."}}},{"Trader",- {- {"Daily Market Brief", "Indices snapshot, top movers, news highlights, watchlist."},- {"Trade Journal", "Trade log table, P&L chart, win rate stats, lessons learned."},- {"Technical Analysis", "Price chart placeholder, indicators table, S/R levels, setup."},- {"Pre-Market Checklist", "Macro events, key levels, planned trades, risk per trade."},- }},+ {{"Daily Market Brief", "Indices snapshot, top movers, news highlights, watchlist."},+ {"Trade Journal", "Trade log table, P&L chart, win rate stats, lessons learned."},+ {"Technical Analysis", "Price chart placeholder, indicators table, S/R levels, setup."},+ {"Pre-Market Checklist", "Macro events, key levels, planned trades, risk per trade."}}},{"Institutional / Analyst",- {- {"Equity Research Report", "Full buy-side template: overview, financials, DCF, comparables."},- {"Earnings Review", "Revenue/EPS vs estimates, guidance, segment breakdown, outlook."},- {"M&A Deal Summary", "Deal overview, rationale, comparables, synergies, valuation."},- {"Sector Deep Dive", "Sector overview, sub-industries, key players, trends, risks."},- }},+ {{"Equity Research Report", "Full buy-side template: overview, financials, DCF, comparables."},+ {"Earnings Review", "Revenue/EPS vs estimates, guidance, segment breakdown, outlook."},+ {"M&A Deal Summary", "Deal overview, rationale, comparables, synergies, valuation."},+ {"Sector Deep Dive", "Sector overview, sub-industries, key players, trends, risks."}}},{"Economist / Macro",- {- {"Macro Economic Summary", "GDP, inflation, unemployment, central bank policy, outlook."},- {"Country Risk Report", "Political, economic, financial, market risk tables and charts."},- {"Central Bank Monitor", "Rate decisions, forward guidance, balance sheet, implications."},- }},+ {{"Macro Economic Summary", "GDP, inflation, unemployment, central bank policy, outlook."},+ {"Country Risk Report", "Political, economic, financial, market risk tables and charts."},+ {"Central Bank Monitor", "Rate decisions, forward guidance, balance sheet, implications."}}},{"Crypto / Digital Assets",- {- {"Crypto Research Report", "Project overview, tokenomics, on-chain metrics, price chart."},- {"DeFi Protocol Analysis", "Protocol overview, TVL, revenue, risks, token valuation."},- {"Crypto Portfolio Review", "Holdings, allocation, cost basis table, P&L, risk exposure."},- }},+ {{"Crypto Research Report", "Project overview, tokenomics, on-chain metrics, price chart."},+ {"DeFi Protocol Analysis", "Protocol overview, TVL, revenue, risks, token valuation."},+ {"Crypto Portfolio Review", "Holdings, allocation, cost basis table, P&L, risk exposure."}}},{"Fixed Income",- {- {"Bond Research Report", "Issuer overview, credit profile, yield analysis, recommendation."},- {"Yield Curve Analysis", "Curve chart, spread table, duration/convexity, macro drivers."},- }},+ {{"Bond Research Report", "Issuer overview, credit profile, yield analysis, recommendation."},+ {"Yield Curve Analysis", "Curve chart, spread table, duration/convexity, macro drivers."}}},{"Quant / Risk",- {- {"Quant Strategy Report", "Strategy description, backtest results, stats, drawdown chart."},- {"Risk Management Report", "VaR, CVaR, stress tests, correlation matrix, recommendations."},- }},+ {{"Quant Strategy Report", "Strategy description, backtest results, stats, drawdown chart."},+ {"Risk Management Report", "VaR, CVaR, stress tests, correlation matrix, recommendations."}}},{"Corporate / Business",- {- {"Business Performance", "KPI dashboard, revenue chart, cost breakdown, targets vs actual."},- {"Project Status Report", "Objectives, milestones table, status, risks, next actions."},- {"Financial Statement", "Income statement, balance sheet, cash flow tables."},- }},+ {{"Business Performance", "KPI dashboard, revenue chart, cost breakdown, targets vs actual."},+ {"Project Status Report", "Objectives, milestones table, status, risks, next actions."},+ {"Financial Statement", "Income statement, balance sheet, cash flow tables."}}},};auto* dlg = new QDialog(this);@@ -882,20 +784,16 @@ void ReportBuilderScreen::show_template_dialog() {"QListWidget { background: %3; color: %2; border: 1px solid %4; }""QListWidget::item { padding: 6px 8px; font-size: 12px; }""QListWidget::item:selected { background: %5; color: %6; }"- "QListWidget::item[category=true] { color: %6; font-weight: bold; "- " background: %7; padding: 4px 8px; font-size: 11px; }""QPushButton { background: %3; color: %2; border: 1px solid %4; padding: 6px 16px; }""QPushButton:hover { background: %5; }"- "QLabel { background: transparent; }"- "QSplitter::handle { background: %4; }")+ "QLabel { background: transparent; }").arg(ui::colors::DARK(), ui::colors::WHITE(), ui::colors::PANEL(), ui::colors::BORDER(),- ui::colors::AMBER_DIM(), ui::colors::AMBER(), ui::colors::BG_RAISED()));+ ui::colors::AMBER_DIM(), ui::colors::AMBER()));auto* hl = new QHBoxLayout(dlg);hl->setSpacing(0);hl->setContentsMargins(0, 0, 0, 0);- // Left: category + template listauto* left = new QWidget(this);left->setMinimumWidth(280);auto* lvl = new QVBoxLayout(left);@@ -908,11 +806,9 @@ void ReportBuilderScreen::show_template_dialog() {auto* list = new QListWidget;list->setSpacing(1);-- // Populate: category header items + template itemsfor (const auto& cat : categories) {auto* cat_item = new QListWidgetItem(" " + cat.label.toUpper());- cat_item->setFlags(Qt::NoItemFlags); // not selectable+ cat_item->setFlags(Qt::NoItemFlags);cat_item->setForeground(QColor(ui::colors::AMBER()));QFont f = cat_item->font();f.setBold(true);@@ -920,7 +816,6 @@ void ReportBuilderScreen::show_template_dialog() {cat_item->setFont(f);cat_item->setBackground(QColor(ui::colors::BG_RAISED()));list->addItem(cat_item);-for (const auto& tmpl : cat.entries) {auto* item = new QListWidgetItem(" " + tmpl.name);item->setData(Qt::UserRole, tmpl.name);@@ -931,13 +826,11 @@ void ReportBuilderScreen::show_template_dialog() {lvl->addWidget(list, 1);hl->addWidget(left);- // Separatorauto* sep = new QFrame;sep->setFixedWidth(1);sep->setStyleSheet(QString("background: %1;").arg(ui::colors::BORDER()));hl->addWidget(sep);- // Right: description + previewauto* right = new QWidget(this);right->setMinimumWidth(280);auto* rvl = new QVBoxLayout(right);@@ -959,7 +852,6 @@ void ReportBuilderScreen::show_template_dialog() {rvl->addWidget(bb);hl->addWidget(right);- // Update description panel on selectionconnect(list, &QListWidget::currentItemChanged, this,[tmpl_name_lbl, desc_lbl](QListWidgetItem* cur, QListWidgetItem*) {if (!cur || !(cur->flags() & Qt::ItemIsSelectable))@@ -968,26 +860,18 @@ void ReportBuilderScreen::show_template_dialog() {desc_lbl->setText(cur->data(Qt::UserRole + 1).toString());});- // Double-click accepts- connect(list, &QListWidget::itemDoubleClicked, dlg, [this, dlg](QListWidgetItem* item) {- if (!item || !(item->flags() & Qt::ItemIsSelectable))- return;- QString tname = item->data(Qt::UserRole).toString();- if (!tname.isEmpty()) {- apply_template(tname);- dlg->accept();- }- });-- connect(bb, &QDialogButtonBox::accepted, dlg, [this, list, dlg]() {+ auto apply_selected = [list, dlg]() {auto* cur = list->currentItem();- if (cur && (cur->flags() & Qt::ItemIsSelectable)) {- QString tname = cur->data(Qt::UserRole).toString();- if (!tname.isEmpty())- apply_template(tname);- }+ if (!cur || !(cur->flags() & Qt::ItemIsSelectable))+ return;+ QString tname = cur->data(Qt::UserRole).toString();+ if (!tname.isEmpty())+ Service::instance().apply_template(tname);dlg->accept();- });+ };++ connect(list, &QListWidget::itemDoubleClicked, dlg, [apply_selected](QListWidgetItem*) { apply_selected(); });+ connect(bb, &QDialogButtonBox::accepted, dlg, apply_selected);connect(bb, &QDialogButtonBox::rejected, dlg, &QDialog::reject);dlg->exec();@@ -995,12 +879,7 @@ void ReportBuilderScreen::show_template_dialog() {}void ReportBuilderScreen::show_theme_dialog() {- const QList<ReportTheme> themes = {- report_themes::light_professional(),- report_themes::dark_corporate(),- report_themes::bloomberg(),- report_themes::midnight_blue(),- };+ const QStringList theme_names = rep::themes::all_names();auto* dlg = new QDialog(this);dlg->setWindowTitle("Report Theme");@@ -1015,22 +894,19 @@ void ReportBuilderScreen::show_theme_dialog() {vl->addWidget(new QLabel("Select a color theme for your report:"));auto* combo = new QComboBox;- for (const auto& t : themes)- combo->addItem(t.name);- // Select current theme- for (int i = 0; i < themes.size(); ++i) {- if (themes[i].name == theme_.name) {- combo->setCurrentIndex(i);- break;- }- }+ for (const auto& n : theme_names)+ combo->addItem(n);+ const QString current = Service::instance().theme().name;+ int cur_idx = theme_names.indexOf(current);+ if (cur_idx >= 0)+ combo->setCurrentIndex(cur_idx);vl->addWidget(combo);auto* preview_lbl = new QLabel;preview_lbl->setFixedHeight(40);preview_lbl->setAlignment(Qt::AlignCenter);- auto update_preview = [themes, preview_lbl](int idx) {- const auto& t = themes[idx];+ auto update_preview = [preview_lbl, theme_names](int idx) {+ const auto t = rep::themes::by_name(theme_names.value(idx));preview_lbl->setStyleSheet(QString("background: %1; color: %2; border: 2px solid %3; font-weight: bold;").arg(t.page_bg, t.heading_color, t.accent_color));preview_lbl->setText(t.name + " — Sample Text");@@ -1042,9 +918,8 @@ void ReportBuilderScreen::show_theme_dialog() {auto* bb = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);vl->addWidget(bb);- connect(bb, &QDialogButtonBox::accepted, dlg, [this, combo, themes, dlg]() {- theme_ = themes[combo->currentIndex()];- refresh_canvas();+ connect(bb, &QDialogButtonBox::accepted, dlg, [combo, theme_names, dlg]() {+ Service::instance().set_theme(rep::themes::by_name(theme_names.value(combo->currentIndex())));dlg->accept();});connect(bb, &QDialogButtonBox::rejected, dlg, &QDialog::reject);@@ -1054,6 +929,8 @@ void ReportBuilderScreen::show_theme_dialog() {}void ReportBuilderScreen::show_metadata_dialog() {+ auto m = Service::instance().metadata();+auto* dlg = new QDialog(this);dlg->setWindowTitle("Report Metadata");dlg->setMinimumWidth(420);@@ -1063,35 +940,31 @@ void ReportBuilderScreen::show_metadata_dialog() {"QLabel { background: transparent; color: %2; }""QPushButton { background: %3; color: %2; border: 1px solid %4; padding: 6px 16px; }""QPushButton:hover { background: %5; }")- .arg(ui::colors::DARK(), ui::colors::WHITE(), ui::colors::PANEL(), ui::colors::BORDER(), ui::colors::BG_RAISED()));+ .arg(ui::colors::DARK(), ui::colors::WHITE(), ui::colors::PANEL(), ui::colors::BORDER(),+ ui::colors::BG_RAISED()));auto* vl = new QVBoxLayout(dlg);auto* form = new QFormLayout;form->setSpacing(8);- auto* title_edit = new QLineEdit(metadata_.title);- auto* author_edit = new QLineEdit(metadata_.author);- auto* company_edit = new QLineEdit(metadata_.company);- auto* date_edit = new QLineEdit(metadata_.date);+ auto* title_edit = new QLineEdit(m.title);+ auto* author_edit = new QLineEdit(m.author);+ auto* company_edit = new QLineEdit(m.company);+ auto* date_edit = new QLineEdit(m.date);date_edit->setPlaceholderText("yyyy-MM-dd");auto lbl_style = QString("color: %1;").arg(ui::colors::GRAY());- auto* tl = new QLabel("Title:");- tl->setStyleSheet(lbl_style);- auto* al = new QLabel("Author:");- al->setStyleSheet(lbl_style);- auto* cl = new QLabel("Company:");- cl->setStyleSheet(lbl_style);- auto* dl = new QLabel("Date:");- dl->setStyleSheet(lbl_style);-- form->addRow(tl, title_edit);- form->addRow(al, author_edit);- form->addRow(cl, company_edit);- form->addRow(dl, date_edit);+ auto add_row = [&](const char* text, QLineEdit* edit) {+ auto* lbl = new QLabel(text);+ lbl->setStyleSheet(lbl_style);+ form->addRow(lbl, edit);+ };+ add_row("Title:", title_edit);+ add_row("Author:", author_edit);+ add_row("Company:", company_edit);+ add_row("Date:", date_edit);vl->addLayout(form);- // Header/Footer sectionauto* hf_lbl = new QLabel("HEADER / FOOTER");hf_lbl->setStyleSheet(QString("color: %1; font-size: 11px; font-weight: bold; padding-top: 10px;").arg(ui::colors::MUTED()));@@ -1100,12 +973,12 @@ void ReportBuilderScreen::show_metadata_dialog() {auto* hf_form = new QFormLayout;hf_form->setSpacing(8);- auto* hl_edit = new QLineEdit(metadata_.header_left);- auto* hc_edit = new QLineEdit(metadata_.header_center);- auto* hr_edit = new QLineEdit(metadata_.header_right);- auto* fl_edit = new QLineEdit(metadata_.footer_left);- auto* fc_edit = new QLineEdit(metadata_.footer_center);- auto* fr_edit = new QLineEdit(metadata_.footer_right);+ auto* hl_edit = new QLineEdit(m.header_left);+ auto* hc_edit = new QLineEdit(m.header_center);+ auto* hr_edit = new QLineEdit(m.header_right);+ auto* fl_edit = new QLineEdit(m.footer_left);+ auto* fc_edit = new QLineEdit(m.footer_center);+ auto* fr_edit = new QLineEdit(m.footer_right);hl_edit->setPlaceholderText("Left");hc_edit->setPlaceholderText("Center");@@ -1133,18 +1006,19 @@ void ReportBuilderScreen::show_metadata_dialog() {auto* bb = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);vl->addWidget(bb);- connect(bb, &QDialogButtonBox::accepted, dlg, [=, this]() {- metadata_.title = title_edit->text();- metadata_.author = author_edit->text();- metadata_.company = company_edit->text();- metadata_.date = date_edit->text();- metadata_.header_left = hl_edit->text();- metadata_.header_center = hc_edit->text();- metadata_.header_right = hr_edit->text();- metadata_.footer_left = fl_edit->text();- metadata_.footer_center = fc_edit->text();- metadata_.footer_right = fr_edit->text();- refresh_canvas();+ connect(bb, &QDialogButtonBox::accepted, dlg, [=]() {+ rep::ReportMetadata nm = m;+ nm.title = title_edit->text();+ nm.author = author_edit->text();+ nm.company = company_edit->text();+ nm.date = date_edit->text();+ nm.header_left = hl_edit->text();+ nm.header_center = hc_edit->text();+ nm.header_right = hr_edit->text();+ nm.footer_left = fl_edit->text();+ nm.footer_center = fc_edit->text();+ nm.footer_right = fr_edit->text();+ Service::instance().set_metadata(nm);dlg->accept();});connect(bb, &QDialogButtonBox::rejected, dlg, &QDialog::reject);@@ -1153,794 +1027,50 @@ void ReportBuilderScreen::show_metadata_dialog() {dlg->deleteLater();}-// ── Templates ─────────────────────────────────────────────────────────────────--void ReportBuilderScreen::apply_template(const QString& name) {- components_.clear();- undo_stack_->clear();- selected_ = -1;- next_id_ = 1;- metadata_ = ReportMetadata{};- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");-- auto add = [&](const QString& type, const QString& content = {}, const QMap<QString, QString>& cfg = {}) {- ReportComponent c;- c.id = next_id_++;- c.type = type;- c.content = content;- c.config = cfg;- components_.append(c);- };-- // ── General Purpose ───────────────────────────────────────────────────────-- if (name == "Blank Report") {- metadata_.title = "Untitled Report";- add("heading", "Title");- add("text", "Start writing here...");-- } else if (name == "Meeting Notes") {- metadata_.title = "Meeting Notes";- add("toc");- add("heading", "Meeting Details");- add("table", {}, {{"rows", "4"}, {"cols", "2"}}); // Date, Time, Location, Chair- add("heading", "Attendees");- add("list", "Name — Role\nName — Role\nName — Role");- add("heading", "Agenda");- add("list", "Item 1\nItem 2\nItem 3");- add("divider");- add("heading", "Discussion Points");- add("text", "Summarise key discussion points here.");- add("heading", "Decisions Made");- add("list", "Decision 1\nDecision 2");- add("heading", "Action Items");- add("table", {}, {{"rows", "5"}, {"cols", "3"}}); // Action | Owner | Due Date- add("heading", "Next Meeting");- add("text", "Date / time / agenda for next meeting.");-- } else if (name == "Investment Memo") {- metadata_.title = "Investment Memo";- add("toc");- add("heading", "Executive Summary");- add("text", "One-paragraph summary of the investment opportunity and recommendation.");- add("heading", "Opportunity");- add("text", "Describe the investment opportunity, market context, and why now.");- add("heading", "Investment Thesis");- add("list", "Thesis point 1\nThesis point 2\nThesis point 3");- add("heading", "Financial Snapshot");- add("table", {}, {{"rows", "5"}, {"cols", "3"}});- add("heading", "Valuation");- add("chart", {},- {{"chart_type", "bar"},- {"title", "Valuation Scenarios"},- {"data", "80,100,130"},- {"labels", "Bear,Base,Bull"}});- add("heading", "Key Risks");- add("list", "Risk 1\nRisk 2\nRisk 3");- add("heading", "Recommendation");- add("text", "State your recommendation and conviction level.");- add("divider");- add("quote", "This memo is for internal use only. Not investment advice.");-- // ── Retail Investor ───────────────────────────────────────────────────────-- } else if (name == "Stock Research") {- metadata_.title = "Stock Research";- add("toc");- add("heading", "Company Overview");- add("text", "Describe the company, its business model, products/services, and competitive position.");- add("market_data", {}, {{"symbol", "AAPL"}});- add("heading", "Financial Highlights");- add("table", {}, {{"rows", "6"}, {"cols", "4"}}); // Metric | FY-2 | FY-1 | TTM- add("heading", "Earnings History");- add("chart", {},- {{"chart_type", "bar"},- {"title", "Revenue vs Net Income"},- {"data", "120,130,145,160"},- {"labels", "FY21,FY22,FY23,FY24"}});- add("heading", "Valuation Metrics");- add("table", {}, {{"rows", "5"}, {"cols", "3"}}); // Metric | Company | Sector Avg- add("heading", "Investment Thesis");- add("text", "Why you are considering this stock.");- add("heading", "Risks");- add("list", "Regulatory\nCompetition\nMacro headwinds\nExecution risk");- add("heading", "Price Target");- add("text", "Your price target and timeline.");- add("divider");- add("quote", "For personal research purposes only. Not financial advice.");-- } else if (name == "Portfolio Review") {- metadata_.title = "Portfolio Review";- add("toc");- add("heading", "Holdings Summary");- add("table", {}, {{"rows", "8"}, {"cols", "6"}}); // Ticker | Name | Qty | Cost | Price | P&L%- add("heading", "Portfolio Performance");- add("chart", {},- {{"chart_type", "line"},- {"title", "Portfolio Value"},- {"data", "10000,10500,9800,11200,12000,11500,13000"}});- add("heading", "Asset Allocation");- add("chart", {},- {{"chart_type", "pie"},- {"title", "Allocation"},- {"data", "40,30,20,10"},- {"labels", "Equities,Fixed Income,Crypto,Cash"}});- add("heading", "Top Performers");- add("table", {}, {{"rows", "4"}, {"cols", "3"}});- add("heading", "Underperformers");- add("table", {}, {{"rows", "4"}, {"cols", "3"}});- add("heading", "Risk Metrics");- add("table", {}, {{"rows", "5"}, {"cols", "2"}}); // Beta, Sharpe, Max DD, Volatility, VaR- add("heading", "Notes & Next Steps");- add("text", "Commentary on portfolio health and planned changes.");-- } else if (name == "Watchlist Report") {- metadata_.title = "Watchlist Report";- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");- add("heading", "Watchlist Snapshot");- add("market_data", {}, {{"symbol", "AAPL"}});- add("market_data", {}, {{"symbol", "MSFT"}});- add("market_data", {}, {{"symbol", "GOOGL"}});- add("market_data", {}, {{"symbol", "AMZN"}});- add("market_data", {}, {{"symbol", "TSLA"}});- add("divider");- add("heading", "Watchlist Detail");- add("table", {}, {{"rows", "8"}, {"cols", "6"}}); // Ticker | Price | Chg% | Target | Stop | Notes- add("heading", "Observations");- add("text", "Key observations and setup notes for tracked names.");-- } else if (name == "Dividend Income Report") {- metadata_.title = "Dividend Income Report";- add("toc");- add("heading", "Dividend Holdings");- add("table", {}, {{"rows", "8"}, {"cols", "6"}}); // Ticker | Shares | Div/Share | Freq | Yield | Annual $- add("heading", "Annual Income Projection");- add("chart", {},- {{"chart_type", "bar"},- {"title", "Monthly Dividend Income"},- {"data", "200,180,220,210,195,230,215,240,200,220,210,250"},- {"labels", "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"}});- add("heading", "Yield by Holding");- add("chart", {},- {{"chart_type", "pie"},- {"title", "Income Contribution"},- {"data", "30,25,20,15,10"},- {"labels", "VZ,T,PFE,KO,MO"}});- add("heading", "Dividend Calendar");- add("table", {}, {{"rows", "8"}, {"cols", "4"}}); // Ticker | Ex-Date | Pay Date | Amount- add("heading", "Growth Targets");- add("text", "Target yield, DRIP strategy, and reinvestment notes.");-- // ── Trader ────────────────────────────────────────────────────────────────-- } else if (name == "Daily Market Brief") {- metadata_.title = "Daily Market Brief";- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");- add("heading", "Market Overview");- add("market_data", {}, {{"symbol", "^GSPC"}});- add("market_data", {}, {{"symbol", "^DJI"}});- add("market_data", {}, {{"symbol", "^IXIC"}});- add("market_data", {}, {{"symbol", "^VIX"}});- add("market_data", {}, {{"symbol", "DX-Y.NYB"}});- add("divider");- add("heading", "Sector Performance");- add("chart", {},- {{"chart_type", "bar"},- {"title", "Sector Returns Today"},- {"data", "0.5,-0.3,1.2,-0.8,0.4,0.9,-0.2,1.1,0.3,-0.5,0.7"},- {"labels", "XLK,XLF,XLV,XLE,XLI,XLY,XLP,XLC,XLB,XLU,XLRE"}});- add("heading", "Top Movers");- add("table", {}, {{"rows", "7"}, {"cols", "4"}}); // Ticker | Price | Chg% | Volume- add("heading", "Key Events & News");- add("text", "Enter today's key market events, earnings, and macro news.");- add("heading", "Watchlist Levels");- add("table", {}, {{"rows", "6"}, {"cols", "5"}}); // Ticker | Price | Support | Resistance | Bias- add("heading", "Commentary");- add("text", "Market tone, breadth observations, and outlook.");-- } else if (name == "Trade Journal") {- metadata_.title = "Trade Journal";- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");- add("toc");- add("heading", "Trade Log");- add("table", {}, {{"rows", "10"}, {"cols", "8"}}); // Date | Symbol | Dir | Entry | Exit | Size | P&L | Notes- add("heading", "P&L Summary");- add("chart", {},- {{"chart_type", "line"}, {"title", "Cumulative P&L"}, {"data", "0,150,-80,320,210,480,390,620"}});- add("heading", "Statistics");- add("table", {},- {{"rows", "7"}, {"cols", "2"}}); // Win Rate, Avg Win, Avg Loss, R:R, Max DD, Profit Factor, Trades- add("heading", "Win/Loss Breakdown");- add("chart", {},- {{"chart_type", "pie"}, {"title", "Win vs Loss"}, {"data", "62,38"}, {"labels", "Wins,Losses"}});- add("heading", "Best Trades");- add("table", {}, {{"rows", "4"}, {"cols", "5"}});- add("heading", "Worst Trades");- add("table", {}, {{"rows", "4"}, {"cols", "5"}});- add("heading", "Lessons Learned");- add("text", "What worked, what didn't, and adjustments for next session.");- add("heading", "Rules Checklist");- add("list", "Followed entry rules\nRespected stop loss\nDid not revenge trade\nPositioned sized "- "correctly\nLogged all trades");-- } else if (name == "Technical Analysis") {- metadata_.title = "Technical Analysis";- add("heading", "Instrument");- add("market_data", {}, {{"symbol", "AAPL"}});- add("heading", "Price Chart");- add("image", {}, {{"width", "700"}, {"caption", "Daily chart — add screenshot here"}, {"align", "center"}});- add("heading", "Key Levels");- add("table", {}, {{"rows", "6"}, {"cols", "3"}}); // Level Type | Price | Notes- add("heading", "Indicators");- add("table", {}, {{"rows", "6"}, {"cols", "3"}}); // Indicator | Value | Signal- add("heading", "Pattern / Setup");- add("text", "Describe the chart pattern or setup and the rationale.");- add("heading", "Trade Plan");- add("table", {}, {{"rows", "4"}, {"cols", "3"}}); // Scenario | Entry | Target | Stop- add("heading", "Bias");- add("quote", "Bullish / Bearish / Neutral — state your directional bias and timeframe.");-- } else if (name == "Pre-Market Checklist") {- metadata_.title = "Pre-Market Checklist";- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");- add("heading", "Overnight Summary");- add("market_data", {}, {{"symbol", "ES=F"}});- add("market_data", {}, {{"symbol", "NQ=F"}});- add("market_data", {}, {{"symbol", "CL=F"}});- add("market_data", {}, {{"symbol", "GC=F"}});- add("divider");- add("heading", "Economic Calendar");- add("table", {}, {{"rows", "5"}, {"cols", "4"}}); // Time | Event | Forecast | Previous- add("heading", "Earnings Today");- add("table", {}, {{"rows", "5"}, {"cols", "3"}}); // Symbol | Time | EPS Est- add("heading", "Key Levels to Watch");- add("table", {}, {{"rows", "5"}, {"cols", "4"}}); // Symbol | Support | Resistance | Pivot- add("heading", "Planned Trades");- add("table", {}, {{"rows", "4"}, {"cols", "5"}}); // Symbol | Direction | Entry | Stop | Target- add("heading", "Risk Parameters");- add("table", {}, {{"rows", "4"}, {"cols", "2"}}); // Max daily loss | Per-trade risk | Max positions | etc.- add("heading", "Mental Checklist");- add("list",- "Reviewed overnight news\nIdentified key levels\nSet max daily loss\nNo FOMO trades\nLog every trade");-- // ── Institutional / Analyst ───────────────────────────────────────────────-- } else if (name == "Equity Research Report") {- metadata_.title = "Equity Research Report";- add("toc");- add("heading", "Company Overview");- add("text", "Business description, history, products/services, and competitive moat.");- add("market_data", {}, {{"symbol", "AAPL"}});- add("heading", "Industry & Market");- add("text", "Industry dynamics, total addressable market, and competitive landscape.");- add("heading", "Financial Analysis");- add("table", {}, {{"rows", "8"}, {"cols", "5"}}); // Income statement summary- add("chart", {},- {{"chart_type", "bar"},- {"title", "Revenue & EPS Growth"},- {"data", "100,115,130,148,169"},- {"labels", "FY20,FY21,FY22,FY23,FY24"}});- add("heading", "Valuation");- add("table", {}, {{"rows", "5"}, {"cols", "4"}}); // DCF, P/E, EV/EBITDA, comparables- add("chart", {},- {{"chart_type", "bar"},- {"title", "Valuation vs Peers"},- {"data", "22,18,25,19,28"},- {"labels", "AAPL,MSFT,GOOGL,META,AMZN"}});- add("heading", "Investment Thesis");- add("list", "Catalyst 1\nCatalyst 2\nCatalyst 3");- add("heading", "Risks");- add("list", "Regulatory risk\nCompetitive pressure\nMacro sensitivity\nExecution risk");- add("heading", "Rating & Price Target");- add("table", {}, {{"rows", "3"}, {"cols", "3"}}); // Rating | Target | Timeframe- add("divider");- add("quote", "This report is for informational purposes only. Not investment advice.");-- } else if (name == "Earnings Review") {- metadata_.title = "Earnings Review";- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");- add("market_data", {}, {{"symbol", "AAPL"}});- add("heading", "Results vs Estimates");- add("table", {}, {{"rows", "5"}, {"cols", "4"}}); // Metric | Actual | Estimate | Surprise%- add("heading", "Revenue Breakdown");- add("chart", {},- {{"chart_type", "bar"},- {"title", "Revenue by Segment"},- {"data", "42,18,10,8,6"},- {"labels", "iPhone,Services,Mac,iPad,Wearables"}});- add("heading", "Margin Analysis");- add("table", {}, {{"rows", "4"}, {"cols", "3"}}); // Metric | This Q | Last Q- add("heading", "Guidance");- add("table", {}, {{"rows", "4"}, {"cols", "4"}}); // Metric | Q+1 Guide | Q+1 Est | Delta- add("heading", "Management Commentary");- add("text", "Key quotes and commentary from the earnings call.");- add("heading", "Our Take");- add("text", "Analysis of results relative to expectations and impact on thesis.");- add("heading", "Revised Estimates");- add("table", {}, {{"rows", "4"}, {"cols", "3"}});-- } else if (name == "M&A Deal Summary") {- metadata_.title = "M&A Deal Summary";- add("toc");- add("heading", "Deal Overview");- add("table", {}, {{"rows", "6"}, {"cols", "2"}}); // Acquirer, Target, Value, Structure, Close Date, Advisors- add("heading", "Strategic Rationale");- add("list", "Strategic fit\nMarket expansion\nSynergy opportunity\nDefensive rationale");- add("heading", "Comparable Transactions");- add("table", {}, {{"rows", "7"}, {"cols", "5"}}); // Date | Acquirer | Target | Value | EV/EBITDA- add("heading", "Synergy Analysis");- add("chart", {},- {{"chart_type", "bar"},- {"title", "Synergy Build-Up ($M)"},- {"data", "50,120,200,250"},- {"labels", "Yr1,Yr2,Yr3,Yr4"}});- add("heading", "Valuation Bridge");- add("table", {}, {{"rows", "5"}, {"cols", "3"}});- add("heading", "Key Risks");- add("list", "Integration risk\nRegulatory clearance\nCulture clash\nPremium paid\nFinancing risk");- add("heading", "Timeline");- add("table", {}, {{"rows", "5"}, {"cols", "3"}}); // Milestone | Expected Date | Status- add("quote", "Deal subject to regulatory approval and shareholder vote.");-- } else if (name == "Sector Deep Dive") {- metadata_.title = "Sector Deep Dive";- add("toc");- add("heading", "Sector Overview");- add("text", "Define the sector, key sub-industries, and economic significance.");- add("heading", "Market Size & Growth");- add("chart", {},- {{"chart_type", "bar"},- {"title", "Market Size ($B)"},- {"data", "800,900,1020,1160,1320"},- {"labels", "2020,2021,2022,2023,2024E"}});- add("heading", "Key Players");- add("table", {}, {{"rows", "8"}, {"cols", "4"}}); // Company | Mkt Cap | Rev | Market Share%- add("heading", "Competitive Dynamics");- add("text", "Porter's five forces or similar competitive analysis framework.");- add("heading", "Structural Trends");- add("list", "Trend 1\nTrend 2\nTrend 3\nTrend 4");- add("heading", "Valuation Comparison");- add("chart", {},- {{"chart_type", "bar"},- {"title", "P/E Ratio by Company"},- {"data", "22,19,25,17,30"},- {"labels", "Co1,Co2,Co3,Co4,Co5"}});- add("heading", "Risks & Headwinds");- add("list", "Regulatory pressure\nTechnology disruption\nCyclicality\nGeopolitical exposure");- add("heading", "Investment Opportunities");- add("text", "Best positioned names and sub-themes to play.");-- // ── Economist / Macro ─────────────────────────────────────────────────────-- } else if (name == "Macro Economic Summary") {- metadata_.title = "Macro Economic Summary";- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");- add("toc");- add("heading", "Global Snapshot");- add("table", {}, {{"rows", "6"}, {"cols", "4"}}); // Country | GDP | Inflation | Rates- add("heading", "GDP Growth");- add("chart", {},- {{"chart_type", "line"},- {"title", "GDP Growth Rate (%)"},- {"data", "2.1,2.3,1.8,2.5,2.2,1.9,2.4"},- {"labels", "Q1 23,Q2 23,Q3 23,Q4 23,Q1 24,Q2 24,Q3 24"}});- add("heading", "Inflation");- add("chart", {},- {{"chart_type", "line"},- {"title", "CPI YoY (%)"},- {"data", "6.0,5.2,4.3,3.7,3.2,2.9,2.6"},- {"labels", "Q1 23,Q2 23,Q3 23,Q4 23,Q1 24,Q2 24,Q3 24"}});- add("heading", "Labour Market");- add("table", {}, {{"rows", "4"}, {"cols", "3"}}); // Unemployment | NFP | Wages- add("heading", "Central Bank Policy");- add("table", {}, {{"rows", "6"}, {"cols", "4"}}); // Central Bank | Rate | Next Meeting | Bias- add("heading", "Key Risks to Outlook");- add("list",- "Geopolitical escalation\nCredit tightening\nChina slowdown\nEnergy price shock\nElection uncertainty");- add("heading", "Outlook");- add("text", "Macro outlook summary and base-case scenario for the next 6–12 months.");-- } else if (name == "Country Risk Report") {- metadata_.title = "Country Risk Report";- add("toc");- add("heading", "Country Overview");- add("table", {}, {{"rows", "6"}, {"cols", "2"}}); // GDP, Population, Currency, Rating, HDI, etc.- add("heading", "Political Risk");- add("text", "Government stability, rule of law, corruption index, and geopolitical exposure.");- add("heading", "Economic Risk");- add("table", {}, {{"rows", "6"}, {"cols", "3"}}); // Indicator | Value | Trend- add("chart", {},- {{"chart_type", "line"},- {"title", "GDP Growth vs Inflation"},- {"data", "3.0,3.4,2.8,1.9,2.5"},- {"labels", "2020,2021,2022,2023,2024E"}});- add("heading", "Financial Risk");- add("table", {}, {{"rows", "5"}, {"cols", "3"}}); // Debt/GDP, CA Balance, FX Reserves, etc.- add("heading", "Market Risk");- add("table", {}, {{"rows", "4"}, {"cols", "3"}}); // Equity Market | Bond Yields | Currency- add("heading", "Overall Risk Rating");- add("table", {}, {{"rows", "5"}, {"cols", "3"}}); // Risk Category | Score | Weight- add("heading", "Outlook");- add("text", "Summary of country risk outlook and key watchpoints.");-- } else if (name == "Central Bank Monitor") {- metadata_.title = "Central Bank Monitor";- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");- add("heading", "Rate Decisions");- add("table", {}, {{"rows", "7"}, {"cols", "4"}}); // Central Bank | Current Rate | Last Change | Next Meeting- add("heading", "Rate Path");- add("chart", {},- {{"chart_type", "line"},- {"title", "Policy Rate (%)"},- {"data", "0.25,0.5,1.0,2.0,3.5,4.5,5.25,5.25,5.0"},- {"labels", "Jan22,Mar22,Jun22,Sep22,Dec22,Mar23,Jun23,Sep23,Dec23"}});- add("heading", "Forward Guidance Summary");- add("text", "Summarise the forward guidance from major central banks.");- add("heading", "Balance Sheet");- add("chart", {},- {{"chart_type", "bar"},- {"title", "Balance Sheet Size ($T)"},- {"data", "8.9,8.5,8.1,7.8,7.4"},- {"labels", "Q4 22,Q1 23,Q2 23,Q3 23,Q4 23"}});- add("heading", "Market Implications");- add("text", "Impact on equities, bonds, FX, and commodities.");- add("heading", "Key Upcoming Events");- add("table", {}, {{"rows", "5"}, {"cols", "3"}}); // Date | Event | Expected-- // ── Crypto / Digital Assets ───────────────────────────────────────────────-- } else if (name == "Crypto Research Report") {- metadata_.title = "Crypto Research Report";- add("toc");- add("heading", "Project Overview");- add("text", "Describe the project, its purpose, technology, and value proposition.");- add("market_data", {}, {{"symbol", "BTC-USD"}});- add("heading", "Tokenomics");- add("table", {}, {{"rows", "7"}, {"cols", "2"}}); // Total Supply, Circulating, Market Cap, FDV, etc.- add("chart", {},- {{"chart_type", "pie"},- {"title", "Token Distribution"},- {"data", "20,15,30,25,10"},- {"labels", "Team,Investors,Community,Treasury,Public"}});- add("heading", "On-Chain Metrics");- add("table", {}, {{"rows", "6"}, {"cols", "3"}}); // Metric | Value | Trend- add("heading", "Price History");- add("chart", {},- {{"chart_type", "line"},- {"title", "Price (USD)"},- {"data", "16000,20000,25000,30000,28000,42000,38000,52000"}});- add("heading", "Competitive Landscape");- add("text", "Key competitors and differentiation.");- add("heading", "Risks");- add("list",- "Regulatory risk\nSmart contract bugs\nCompetitor displacement\nLiquidity risk\nTeam/execution risk");- add("heading", "Investment Thesis");- add("text", "Thesis, catalysts, and price targets.");- add("quote", "Crypto assets are highly volatile. This is not financial advice.");-- } else if (name == "DeFi Protocol Analysis") {- metadata_.title = "DeFi Protocol Analysis";- add("toc");- add("heading", "Protocol Overview");- add("text", "What the protocol does, how it works, and what problem it solves.");- add("heading", "Key Metrics");- add("table", {}, {{"rows", "7"}, {"cols", "3"}}); // TVL | Revenue | Users | Fees | Token Price | MC | FDV- add("heading", "TVL History");- add("chart", {},- {{"chart_type", "line"},- {"title", "Total Value Locked ($M)"},- {"data", "500,800,1200,900,1500,2000,1800,2400"}});- add("heading", "Revenue & Fees");- add("chart", {},- {{"chart_type", "bar"},- {"title", "Monthly Protocol Revenue ($K)"},- {"data", "120,150,180,140,200,230,210,250"}});- add("heading", "Governance & Token");- add("text", "Token utility, governance rights, staking mechanics, and emission schedule.");- add("heading", "Risks");- add("list", "Smart contract exploit\nOracle manipulation\nRegulatory action\nLiquidity "- "fragmentation\nFork/governance risk");- add("heading", "Valuation");- add("text", "P/S, P/TVL, or other relevant DeFi valuation metrics and comparables.");-- } else if (name == "Crypto Portfolio Review") {- metadata_.title = "Crypto Portfolio Review";- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");- add("heading", "Holdings");- add("table", {}, {{"rows", "8"}, {"cols", "6"}}); // Asset | Qty | Cost | Price | Value | P&L%- add("heading", "Current Prices");- add("market_data", {}, {{"symbol", "BTC-USD"}});- add("market_data", {}, {{"symbol", "ETH-USD"}});- add("market_data", {}, {{"symbol", "SOL-USD"}});- add("heading", "Allocation");- add("chart", {},- {{"chart_type", "pie"},- {"title", "Portfolio Allocation"},- {"data", "50,25,15,10"},- {"labels", "BTC,ETH,SOL,Other"}});- add("heading", "Performance");- add("chart", {},- {{"chart_type", "line"},- {"title", "Portfolio Value (USD)"},- {"data", "10000,9500,12000,11000,15000,13000,18000"}});- add("heading", "Notes");- add("text", "Rebalancing notes, conviction levels, and next moves.");-- // ── Fixed Income ──────────────────────────────────────────────────────────-- } else if (name == "Bond Research Report") {- metadata_.title = "Bond Research Report";- add("toc");- add("heading", "Issuer Overview");- add("text", "Issuer description, business profile, and credit history.");- add("heading", "Bond Details");- add("table", {}, {{"rows", "8"}, {"cols", "2"}}); // ISIN, Coupon, Maturity, Rating, Face Value, etc.- add("heading", "Credit Profile");- add("table", {}, {{"rows", "5"}, {"cols", "4"}}); // Metric | FY-2 | FY-1 | TTM- add("heading", "Yield Analysis");- add("chart", {},- {{"chart_type", "line"},- {"title", "Yield vs Benchmark"},- {"data", "3.0,3.2,3.5,3.8,4.1,4.3,4.0"},- {"labels", "Jan,Feb,Mar,Apr,May,Jun,Jul"}});- add("heading", "Duration & Convexity");- add("table", {}, {{"rows", "4"}, {"cols", "2"}});- add("heading", "Comparable Bonds");- add("table", {}, {{"rows", "5"}, {"cols", "5"}}); // Issuer | Rating | Coupon | Maturity | YTM- add("heading", "Recommendation");- add("text", "Buy / Hold / Sell with rationale and target spread.");-- } else if (name == "Yield Curve Analysis") {- metadata_.title = "Yield Curve Analysis";- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");- add("heading", "Yield Curve Shape");- add("chart", {},- {{"chart_type", "line"},- {"title", "US Treasury Yield Curve"},- {"data", "5.3,5.1,4.9,4.7,4.6,4.5,4.4,4.3"},- {"labels", "3M,6M,1Y,2Y,3Y,5Y,10Y,30Y"}});- add("heading", "Key Spreads");- add("table", {}, {{"rows", "5"}, {"cols", "3"}}); // Spread | Current | 1M Ago- add("heading", "Historical Comparison");- add("chart", {},- {{"chart_type", "bar"},- {"title", "10Y-2Y Spread (bps)"},- {"data", "-80,-60,-40,-20,5,15,30"},- {"labels", "Oct23,Nov23,Dec23,Jan24,Feb24,Mar24,Apr24"}});- add("heading", "Duration & Convexity");- add("table", {}, {{"rows", "4"}, {"cols", "3"}});- add("heading", "Macro Drivers");- add("text", "Explain the key macro factors driving current curve shape.");- add("heading", "Implications");- add("list",- "Recession signal interpretation\nFed policy implications\nSector rotation impact\nCurrency effects");-- // ── Quant / Risk ──────────────────────────────────────────────────────────-- } else if (name == "Quant Strategy Report") {- metadata_.title = "Quant Strategy Report";- add("toc");- add("heading", "Strategy Description");- add("text", "Describe the strategy, signal generation logic, universe, and execution rules.");- add("heading", "Backtest Parameters");- add("table", {}, {{"rows", "6"}, {"cols", "2"}}); // Start Date, End Date, Universe, Frequency, etc.- add("heading", "Performance Summary");- add("table", {}, {{"rows", "8"}, {"cols", "2"}}); // CAGR, Sharpe, Sortino, Max DD, Win Rate, etc.- add("heading", "Equity Curve");- add("chart", {},- {{"chart_type", "line"},- {"title", "Strategy vs Benchmark"},- {"data", "100,108,115,112,124,131,128,142,150"},- {"labels", "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep"}});- add("heading", "Drawdown Analysis");- add("chart", {},- {{"chart_type", "bar"},- {"title", "Monthly Drawdowns (%)"},- {"data", "0,-2.1,-0.5,-3.2,-1.1,0,-1.8,-0.4,0"}});- add("heading", "Factor Exposure");- add("table", {}, {{"rows", "6"}, {"cols", "3"}}); // Factor | Beta | t-stat- add("heading", "Stress Tests");- add("table", {}, {{"rows", "5"}, {"cols", "3"}}); // Scenario | P&L | Max DD- add("heading", "Limitations & Risks");- add("list",- "Overfitting risk\nTransaction cost sensitivity\nRegime change\nCapacity constraints\nData snooping bias");-- } else if (name == "Risk Management Report") {- metadata_.title = "Risk Management Report";- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");- add("toc");- add("heading", "Portfolio Risk Summary");- add("table", {}, {{"rows", "6"}, {"cols", "2"}}); // VaR, CVaR, Beta, Volatility, Sharpe, Max DD- add("heading", "VaR Analysis");- add("chart", {},- {{"chart_type", "bar"},- {"title", "VaR by Confidence Level"},- {"data", "1.2,1.8,2.5,3.1"},- {"labels", "90%,95%,99%,99.9%"}});- add("heading", "Stress Test Results");- add("table", {}, {{"rows", "7"}, {"cols", "3"}}); // Scenario | P&L Impact | % Portfolio- add("heading", "Correlation Matrix");- add("text", "Paste or describe key pairwise correlations between holdings.");- add("heading", "Concentration Risk");- add("chart", {},- {{"chart_type", "pie"},- {"title", "Position Concentration"},- {"data", "25,20,18,15,12,10"},- {"labels", "Pos1,Pos2,Pos3,Pos4,Pos5,Other"}});- add("heading", "Liquidity Risk");- add("table", {}, {{"rows", "5"}, {"cols", "3"}}); // Position | ADV | Days to Liquidate- add("heading", "Recommendations");- add("list", "Reduce concentration in top 3 positions\nAdd hedges for macro exposure\nReview stop-loss "- "levels\nRebalance sector exposure");-- // ── Corporate / Business ──────────────────────────────────────────────────-- } else if (name == "Business Performance") {- metadata_.title = "Business Performance Report";- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");- add("toc");- add("heading", "Executive Summary");- add("text", "One-paragraph summary of business performance this period.");- add("heading", "Key Performance Indicators");- add("table", {}, {{"rows", "8"}, {"cols", "4"}}); // KPI | Target | Actual | Variance- add("heading", "Revenue");- add("chart", {},- {{"chart_type", "bar"},- {"title", "Revenue ($M)"},- {"data", "42,45,48,44,51,53,50,55"},- {"labels", "Q1 22,Q2 22,Q3 22,Q4 22,Q1 23,Q2 23,Q3 23,Q4 23"}});- add("heading", "Cost Breakdown");- add("chart", {},- {{"chart_type", "pie"},- {"title", "Cost Structure"},- {"data", "40,25,20,15"},- {"labels", "COGS,R&D,S&M,G&A"}});- add("heading", "Department Performance");- add("table", {}, {{"rows", "6"}, {"cols", "4"}});- add("heading", "Targets vs Actuals");- add("chart", {},- {{"chart_type", "bar"},- {"title", "Target vs Actual"},- {"data", "100,95,100,102,100,88"},- {"labels", "Jan,Feb,Mar,Apr,May,Jun"}});- add("heading", "Issues & Risks");- add("list", "Issue 1\nIssue 2\nIssue 3");- add("heading", "Next Period Targets");- add("table", {}, {{"rows", "5"}, {"cols", "3"}});-- } else if (name == "Project Status Report") {- metadata_.title = "Project Status Report";- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");- add("heading", "Project Overview");- add("table", {}, {{"rows", "5"}, {"cols", "2"}}); // Name, Owner, Start, End, Budget- add("heading", "Overall Status");- add("table", {}, {{"rows", "4"}, {"cols", "3"}}); // Dimension | Status | Notes (Scope/Time/Cost/Quality)- add("heading", "Milestones");- add("table", {}, {{"rows", "7"}, {"cols", "4"}}); // Milestone | Due Date | Status | Owner- add("heading", "Progress This Period");- add("text", "Summarise completed work and progress against plan.");- add("heading", "Issues & Blockers");- add("table", {}, {{"rows", "5"}, {"cols", "4"}}); // Issue | Impact | Owner | Resolution Date- add("heading", "Risks");- add("table", {}, {{"rows", "5"}, {"cols", "4"}}); // Risk | Likelihood | Impact | Mitigation- add("heading", "Next Steps");- add("list", "Action 1 — Owner — Due date\nAction 2 — Owner — Due date\nAction 3 — Owner — Due date");-- } else if (name == "Financial Statement") {- metadata_.title = "Financial Statement";- add("toc");- add("heading", "Income Statement");- add("table", {}, {{"rows", "12"}, {"cols", "4"}}); // Item | FY-2 | FY-1 | FY Current- add("chart", {},- {{"chart_type", "bar"},- {"title", "Revenue & Net Income"},- {"data", "400,450,500,420,480,530"},- {"labels", "H1 22,H2 22,H1 23,H2 23,H1 24,H2 24"}});- add("page_break");- add("heading", "Balance Sheet");- add("table", {}, {{"rows", "14"}, {"cols", "3"}}); // Item | Prior Year | Current Year- add("page_break");- add("heading", "Cash Flow Statement");- add("table", {}, {{"rows", "12"}, {"cols", "3"}});- add("heading", "Key Ratios");- add("table", {}, {{"rows", "8"}, {"cols", "3"}}); // Ratio | Prior Year | Current Year- add("divider");- add("quote", "Prepared in accordance with applicable accounting standards.");- }-- selected_ = components_.isEmpty() ? -1 : 0;- refresh_canvas();- refresh_structure();- if (!components_.isEmpty())- select_component(0);-}--// ── File I/O ──────────────────────────────────────────────────────────────────--void ReportBuilderScreen::load_report(const QString& path) {- QFile f(path);- if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {- QMessageBox::warning(this, "Open Report", "Could not open file:\n" + path);- return;- }- QString json = QString::fromUtf8(f.readAll());- f.close();-- if (!deserialize_from_json(json)) {- QMessageBox::warning(this, "Open Report", "Could not parse report file:\n" + path);- return;- }-- current_file_ = path;- update_recent(path);- refresh_canvas();- refresh_structure();- if (!components_.isEmpty())- select_component(0);-}+// ── File operations ──────────────────────────────────────────────────────────void ReportBuilderScreen::on_new() {auto answer = QMessageBox::question(this, "New Report", "Create a new report? Unsaved changes will be lost.",QMessageBox::Yes | QMessageBox::No);if (answer != QMessageBox::Yes)return;-- components_.clear();- undo_stack_->clear();- selected_ = -1;- next_id_ = 1;- current_file_ = {};- metadata_ = ReportMetadata{};- metadata_.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");-+ Service::instance().clear_document();+ selected_id_ = 0;properties_->show_empty();- refresh_canvas();- refresh_structure();}void ReportBuilderScreen::on_open() {- QString path = QFileDialog::getOpenFileName(this, "Open Report", "", "Fincept Report (*.fincept);;JSON (*.json)");+ QString path =+ QFileDialog::getOpenFileName(this, "Open Report", "", "Fincept Report (*.fincept);;JSON (*.json)");if (path.isEmpty())return;- load_report(path);+ auto r = Service::instance().load_from(path);+ if (r.is_err())+ QMessageBox::warning(this, "Open Report", "Could not open file:\n" + path + "\n\n" ++ QString::fromStdString(r.error()));}void ReportBuilderScreen::on_save() {- QString path = current_file_;+ auto& svc = Service::instance();+ QString path = svc.current_file();if (path.isEmpty()) {- path = QFileDialog::getSaveFileName(this, "Save Report", metadata_.title,+ path = QFileDialog::getSaveFileName(this, "Save Report", svc.metadata().title,"Fincept Report (*.fincept);;JSON (*.json)");if (path.isEmpty())return;- current_file_ = path;}-- QFile f(path);- if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) {- QMessageBox::warning(this, "Save Report", "Could not save to:\n" + path);+ auto r = svc.save_to(path);+ if (r.is_err()) {+ QMessageBox::warning(this, "Save Report", "Could not save to:\n" + path + "\n\n" ++ QString::fromStdString(r.error()));return;}- f.write(serialize_to_json().toUtf8());- f.close();- update_recent(path);-- // Register with File Manager so it appears in the Files tabservices::FileManagerService::instance().import_file(path, "report_builder");}-void ReportBuilderScreen::on_auto_save() {- if (autosave_path_.isEmpty()) {- autosave_path_ =- QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/fincept_report_autosave.fincept";- }- QFile f(autosave_path_);- if (f.open(QIODevice::WriteOnly | QIODevice::Text)) {- f.write(serialize_to_json().toUtf8());- }-}-void ReportBuilderScreen::on_export_pdf() {- QString path = QFileDialog::getSaveFileName(this, "Export PDF", metadata_.title, "PDF (*.pdf)");+ auto m = Service::instance().metadata();+ QString path = QFileDialog::getSaveFileName(this, "Export PDF", m.title, "PDF (*.pdf)");if (path.isEmpty())return;@@ -1950,20 +1080,15 @@ void ReportBuilderScreen::on_export_pdf() {printer.setPageSize(QPageSize(QPageSize::A4));printer.setPageMargins(QMarginsF(15, 20, 15, 20), QPageLayout::Millimeter);- // Determine if we need header/footer rendering- bool has_header =- !metadata_.header_left.isEmpty() || !metadata_.header_center.isEmpty() || !metadata_.header_right.isEmpty();- bool has_footer = !metadata_.footer_left.isEmpty() || !metadata_.footer_center.isEmpty() ||- !metadata_.footer_right.isEmpty() || metadata_.show_page_numbers;+ bool has_header = !m.header_left.isEmpty() || !m.header_center.isEmpty() || !m.header_right.isEmpty();+ bool has_footer = !m.footer_left.isEmpty() || !m.footer_center.isEmpty() || !m.footer_right.isEmpty() ||+ m.show_page_numbers;if (!has_header && !has_footer) {- // Simple path — let Qt handle itcanvas_->text_edit()->document()->print(&printer);} else {- // Manual render with header/footer via QPainterQTextDocument* doc = canvas_->text_edit()->document()->clone(this);- // Shrink document margins to leave room for header/footerQTextFrameFormat root_fmt = doc->rootFrame()->frameFormat();root_fmt.setTopMargin(has_header ? 24 : root_fmt.topMargin());root_fmt.setBottomMargin(has_footer ? 24 : root_fmt.bottomMargin());@@ -1978,15 +1103,13 @@ void ReportBuilderScreen::on_export_pdf() {QRectF page_rect = printer.pageRect(QPrinter::DevicePixel);doc->setPageSize(page_rect.size());-int total_pages = doc->pageCount();auto draw_hf_line = [&](int page, bool is_header) {- QString left = is_header ? metadata_.header_left : metadata_.footer_left;- QString center = is_header ? metadata_.header_center : metadata_.footer_center;- QString right = is_header ? metadata_.header_right : metadata_.footer_right;+ QString left = is_header ? m.header_left : m.footer_left;+ QString center = is_header ? m.header_center : m.footer_center;+ QString right = is_header ? m.header_right : m.footer_right;- // Replace {page} and {total}auto replace_tokens = [&](QString s) {s.replace("{page}", QString::number(page));s.replace("{total}", QString::number(total_pages));@@ -2010,7 +1133,6 @@ void ReportBuilderScreen::on_export_pdf() {if (!right.isEmpty())painter.drawText(r, Qt::AlignRight | Qt::AlignVCenter, right);- // Thin rule under header / above footerpainter.setPen(QPen(QColor("#cccccc"), 0.5));double rule_y = is_header ? y + 14 : y - 2;painter.drawLine(QPointF(page_rect.left() + 8, rule_y), QPointF(page_rect.right() - 8, rule_y));@@ -2019,18 +1141,14 @@ void ReportBuilderScreen::on_export_pdf() {for (int page = 1; page <= total_pages; ++page) {if (page > 1)printer.newPage();-painter.save();- // Clip to content area (leave header/footer bands)double content_top = has_header ? 20 : 0;double content_bottom = has_footer ? page_rect.height() - 20 : page_rect.height();- painter.setClipRect(QRectF(page_rect.left(), content_top, page_rect.width(), content_bottom - content_top));-- // Paint the page content+ painter.setClipRect(+ QRectF(page_rect.left(), content_top, page_rect.width(), content_bottom - content_top));painter.translate(0, -(page - 1) * page_rect.height() + content_top);doc->drawContents(&painter);painter.restore();-if (has_header)draw_hf_line(page, true);if (has_footer)@@ -2042,43 +1160,47 @@ void ReportBuilderScreen::on_export_pdf() {}QMessageBox::information(this, "Export PDF", "Report exported successfully to:\n" + path);-- // Register exported PDF with File Managerservices::FileManagerService::instance().import_file(path, "report_builder");}void ReportBuilderScreen::on_preview() {QPrinter printer(QPrinter::HighResolution);printer.setPageSize(QPageSize(QPageSize::A4));-QPrintPreviewDialog preview(&printer, this);connect(&preview, &QPrintPreviewDialog::paintRequested, this,[this](QPrinter* p) { canvas_->text_edit()->document()->print(p); });preview.exec();}+// ── Show / Hide ──────────────────────────────────────────────────────────────+void ReportBuilderScreen::showEvent(QShowEvent* e) {QWidget::showEvent(e);- autosave_->start();+ // The service runs autosave continuously. We just rebind from current+ // service state in case mutations happened while the screen was hidden.+ rebind_from_service();}-void ReportBuilderScreen::hideEvent(QHideEvent* e) {- QWidget::hideEvent(e);- autosave_->stop();-}+void ReportBuilderScreen::hideEvent(QHideEvent* e) { QWidget::hideEvent(e); }-// ── IStatefulScreen ───────────────────────────────────────────────────────────+// ── IStatefulScreen ──────────────────────────────────────────────────────────QVariantMap ReportBuilderScreen::save_state() const {- return {{"current_file", current_file_}};+ return {+ {"selected_id", selected_id_},+ {"left_collapsed", left_collapsed_},+ {"right_collapsed", right_collapsed_},+ };}void ReportBuilderScreen::restore_state(const QVariantMap& state) {- // current_file_ is only a reference path — the actual content lives in- // the undo stack and components_ vector. Just restore the title display.- const QString file = state.value("current_file").toString();- if (!file.isEmpty())- current_file_ = file;+ if (state.contains("selected_id"))+ selected_id_ = state.value("selected_id").toInt(0);+ if (state.contains("left_collapsed"))+ apply_left_collapsed(state.value("left_collapsed").toBool(), /*animate=*/false);+ if (state.contains("right_collapsed"))+ apply_right_collapsed(state.value("right_collapsed").toBool(), /*animate=*/false);+ rebind_from_service();}} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.h b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.hindex d1e1cea23..b21818a8b 100644--- a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.h+++ b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.h@@ -1,217 +1,113 @@#pragma once+// ReportBuilderScreen — view onto ReportBuilderService.+//+// All document state (components, metadata, theme, undo stack, autosave,+// recent files) lives in fincept::services::ReportBuilderService. This+// screen renders that state and forwards user gestures to the service.+// LLM/MCP tools mutate the same service on a different thread; the screen+// observes service signals and re-renders live.++#include "core/report/ReportDocument.h"#include "screens/IStatefulScreen.h"#include "screens/report_builder/ComponentToolbar.h"#include "screens/report_builder/DocumentCanvas.h"#include "screens/report_builder/PropertiesPanel.h"+#include <QPropertyAnimation>+#include <QPushButton>#include <QSplitter>-#include <QTimer>-#include <QUndoCommand>#include <QUndoStack>#include <QWidget>namespace fincept::screens {-struct ReportComponent {- int id = 0;- // Types: heading, text, table, image, chart, sparkline, stats_block,- // callout, code, divider, quote, list, market_data, page_break, toc- QString type;- QString content;- QMap<QString, QString> config;-};--struct ReportMetadata {- QString title = "Untitled Report";- QString author = "Analyst";- QString company = "Fincept Corporation";- QString date;- QString header_left;- QString header_center;- QString header_right;- QString footer_left;- QString footer_center = "Page {page}";- QString footer_right;- bool show_page_numbers = true;-};--// Report color theme-struct ReportTheme {- QString name;- QString heading_color;- QString accent_color;- QString page_bg;- QString text_color;- QString table_header_bg;- QString table_header_fg;- QString code_bg;- QString quote_bg;- QString meta_color;- QString divider_color;-};--namespace report_themes {-inline ReportTheme light_professional() {- return {"Light Professional",- "#1a1a1a",- "#d97706",- "#ffffff",- "#333333",- "#f0f0f0",- "#1a1a1a",- "#f5f5f5",- "#f9f9f9",- "#666666",- "#cccccc"};-}-inline ReportTheme dark_corporate() {- return {"Dark Corporate", "#e5e5e5", "#d97706", "#1e1e1e", "#cccccc", "#2a2a2a",- "#e5e5e5", "#111111", "#1a1a1a", "#808080", "#444444"};-}-inline ReportTheme bloomberg() {- return {"Bloomberg Terminal",- "#ff8c00",- "#ff8c00",- "#0a0a0a",- "#d4d4d4",- "#1a0a00",- "#ff8c00",- "#050505",- "#0f0f0f",- "#888888",- "#333300"};-}-inline ReportTheme midnight_blue() {- return {"Midnight Blue", "#e2e8f0", "#3b82f6", "#0f172a", "#cbd5e1", "#1e3a5f",- "#e2e8f0", "#0d1b2e", "#132033", "#64748b", "#1e3a5f"};-}-} // namespace report_themes--// ── Undo Commands ──────────────────────────────────────────────────────────────--class ReportBuilderScreen;--class AddComponentCommand : public QUndoCommand {- public:- AddComponentCommand(ReportBuilderScreen* screen, const ReportComponent& comp, int insert_at);- void undo() override;- void redo() override;-- private:- ReportBuilderScreen* screen_;- ReportComponent comp_;- int insert_at_;-};--class RemoveComponentCommand : public QUndoCommand {- public:- RemoveComponentCommand(ReportBuilderScreen* screen, int index);- void undo() override;- void redo() override;-- private:- ReportBuilderScreen* screen_;- ReportComponent saved_;- int index_;-};--class UpdateComponentCommand : public QUndoCommand {- public:- UpdateComponentCommand(ReportBuilderScreen* screen, int index, const QString& old_content,- const QMap<QString, QString>& old_config, const QString& new_content,- const QMap<QString, QString>& new_config);- void undo() override;- void redo() override;- int id() const override { return 1001; }- bool mergeWith(const QUndoCommand* other) override;-- private:- ReportBuilderScreen* screen_;- int index_;- QString old_content_, new_content_;- QMap<QString, QString> old_config_, new_config_;-};--class MoveComponentCommand : public QUndoCommand {- public:- MoveComponentCommand(ReportBuilderScreen* screen, int from, int to);- void undo() override;- void redo() override;-- private:- ReportBuilderScreen* screen_;- int from_, to_;-};--// ── Main Screen ────────────────────────────────────────────────────────────────+// Type aliases — ComponentToolbar / DocumentCanvas / PropertiesPanel were+// originally written against types declared inside fincept::screens. After+// the model moved into core/report we keep those aliases so the existing+// callers (and forward declarations like `struct ReportComponent` in+// PropertiesPanel.h) keep resolving.+using ReportComponent = ::fincept::report::ReportComponent;+using ReportMetadata = ::fincept::report::ReportMetadata;+using ReportTheme = ::fincept::report::ReportTheme;class ReportBuilderScreen : public QWidget, public IStatefulScreen {Q_OBJECTpublic:explicit ReportBuilderScreen(QWidget* parent = nullptr);+ ~ReportBuilderScreen() override;void restore_state(const QVariantMap& state) override;QVariantMap save_state() const override;QString state_key() const override { return "report_builder"; }- int state_version() const override { return 1; }-- // Called by undo commands — do NOT push to undo stack inside these- void add_component_direct(const ReportComponent& comp, int at);- void remove_component_direct(int index);- void update_component_direct(int index, const QString& content, const QMap<QString, QString>& config);- void swap_components(int a, int b);-- QVector<ReportComponent>& components() { return components_; }- const QVector<ReportComponent>& components() const { return components_; }- int& selected() { return selected_; }-- void refresh_canvas();- void refresh_structure();+ // v2 adds: left_collapsed, right_collapsed.+ // v3 = ServiceMigration — selected_id (stable id, not index).+ int state_version() const override { return 3; }private:QWidget* build_toolbar();- void apply_template(const QString& name);- void load_report(const QString& path);- QString serialize_to_json() const;- bool deserialize_from_json(const QString& json);- void update_recent(const QString& path);- QStringList load_recent() const;++ // Dialogs (UI shells; service does the actual work)void show_recent_dialog();void show_template_dialog();void show_theme_dialog();void show_metadata_dialog();- // Public-facing operations that push to undo stack+ // User-driven operations — all go through the servicevoid add_component(const QString& type);void select_component(int index);- void remove_component(int index);- void update_component(int index, const QString& content, const QMap<QString, QString>& config);+ void remove_component_at(int index);+ void duplicate_at(int index);+ void move_up_at(int index);+ void move_down_at(int index);++ // Service → screen+ void rebind_from_service();+ void on_component_added(int id, int index);+ void on_component_updated(int id);+ void on_component_removed(int id, int prior_index);+ void on_component_moved(int id, int from, int to);+ void on_metadata_changed();+ void on_theme_changed();+ void on_document_changed();+ void on_document_loaded(const QString& path);+ void refresh_canvas();+ void refresh_structure();++ // ChildrenComponentToolbar* comp_toolbar_ = nullptr;DocumentCanvas* canvas_ = nullptr;PropertiesPanel* properties_ = nullptr;QSplitter* splitter_ = nullptr;- QUndoStack* undo_stack_ = nullptr;- QTimer* autosave_ = nullptr;-- QVector<ReportComponent> components_;- ReportMetadata metadata_;- ReportTheme theme_ = report_themes::light_professional();- int selected_ = -1;- int next_id_ = 1;- QString current_file_;- QString autosave_path_;- void showEvent(QShowEvent* e) override;- void hideEvent(QHideEvent* e) override;+ // Selection — tracked by stable id so it survives mutations from the+ // LLM that shift indices. -1 / 0 = nothing selected.+ int selected_id_ = 0;++ // ── Side-panel collapse state ───────────────────────────────────────+ QPushButton* left_toggle_btn_ = nullptr;+ QPushButton* right_toggle_btn_ = nullptr;+ QPropertyAnimation* left_anim_ = nullptr;+ QPropertyAnimation* right_anim_ = nullptr;+ bool left_collapsed_ = false;+ bool right_collapsed_ = false;+ static constexpr int kLeftPanelWidth = 240;+ static constexpr int kRightPanelWidth = 280;+ void apply_left_collapsed(bool collapsed, bool animate);+ void apply_right_collapsed(bool collapsed, bool animate);private slots:+ void on_toggle_left();+ void on_toggle_right();void on_save();void on_open();void on_new();- void on_auto_save();void on_export_pdf();void on_preview();++ protected:+ void showEvent(QShowEvent* e) override;+ void hideEvent(QHideEvent* e) override;};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/surface_analytics/Surface3DWidget.cpp b/fincept-qt/src/screens/surface_analytics/Surface3DWidget.cppindex 743260b5c..d0acc2c8e 100644--- a/fincept-qt/src/screens/surface_analytics/Surface3DWidget.cpp+++ b/fincept-qt/src/screens/surface_analytics/Surface3DWidget.cpp@@ -49,6 +49,13 @@ void Surface3DWidget::clear() {update();}+void Surface3DWidget::set_supported(bool supported) {+ if (supported_ == supported)+ return;+ supported_ = supported;+ update();+}+// ---- Color mapping ----QColor Surface3DWidget::lerp_color(const QColor& a, const QColor& b, float t) {return QColor((int)(a.red() + (b.red() - a.red()) * t), (int)(a.green() + (b.green() - a.green()) * t),@@ -111,6 +118,20 @@ void Surface3DWidget::paintEvent(QPaintEvent*) {// Obsidian background — pure dark basepainter.fillRect(rect(), QColor(8, 8, 8));+ if (!supported_) {+ painter.setPen(QColor(217, 119, 6));+ painter.setFont(QFont("Consolas", 13, QFont::Bold));+ painter.drawText(QRect(0, H / 2 - 28, W, 24), Qt::AlignCenter,+ "3D NOT APPLICABLE");+ painter.setPen(QColor(140, 140, 140));+ painter.setFont(QFont("Consolas", 10));+ painter.drawText(QRect(0, H / 2, W, 22), Qt::AlignCenter,+ "This surface is 1-D or categorical.");+ painter.drawText(QRect(0, H / 2 + 18, W, 22), Qt::AlignCenter,+ "Switch to TABLE or LINE view.");+ return;+ }+if (grid_.empty() || grid_[0].empty()) {painter.setPen(QColor(80, 80, 80));painter.setFont(QFont("Consolas", 11));diff --git a/fincept-qt/src/screens/surface_analytics/Surface3DWidget.h b/fincept-qt/src/screens/surface_analytics/Surface3DWidget.hindex 9d4a5068e..1fc631b16 100644--- a/fincept-qt/src/screens/surface_analytics/Surface3DWidget.h+++ b/fincept-qt/src/screens/surface_analytics/Surface3DWidget.h@@ -19,6 +19,10 @@ class Surface3DWidget : public QWidget {bool diverging = false, const std::vector<std::string>* col_labels = nullptr,const std::vector<std::string>* row_labels = nullptr);+ // When false the widget paints an overlay telling the user the active+ // chart type cannot be shown in 3D and to switch to TABLE / LINE view.+ void set_supported(bool supported);+void clear();protected:@@ -58,6 +62,8 @@ class Surface3DWidget : public QWidget {bool dragging_ = false;QPoint drag_start_;float drag_start_yaw_ = 0, drag_start_pitch_ = 0;++ bool supported_ = true;};} // namespace fincept::surfacediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.cppindex 8f04d9a4b..78695b71b 100644--- a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.cpp+++ b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.cpp@@ -1,14 +1,20 @@#include "SurfaceAnalyticsScreen.h"#include "Surface3DWidget.h"+#include "SurfaceCapabilities.h"+#include "SurfaceControlPanel.h"#include "SurfaceCsvImporter.h"-#include "SurfaceDatabentoPanel.h"-#include "SurfaceMetricsPanel.h"+#include "SurfaceDataInspector.h"+#include "SurfaceDefaults.h"+#include "SurfaceLineWidget.h"#include "SurfaceTableWidget.h"+#include "core/logging/Logger.h"#include "core/session/ScreenStateManager.h"+#include "datahub/DataHub.h"+#include "datahub/DataHubMetaTypes.h"+#include "services/markets/MarketDataService.h"#include "ui/theme/Theme.h"-#include <QComboBox>#include <QFileDialog>#include <QFrame>#include <QHBoxLayout>@@ -17,6 +23,8 @@#include <QScrollArea>#include <QSplitter>#include <QStackedWidget>+#include <QStringList>+#include <QVariant>#include <QVBoxLayout>#include <cstdlib>@@ -68,24 +76,47 @@ static QString btn_inactive() {.arg(colors::BORDER_BRIGHT());}-static QString btn_active_amber() {- return QString("QPushButton { background:rgba(217,119,6,0.12); border:1px solid %1; color:%2;"- " font-size:11px; font-weight:bold; font-family:%3;"- " padding:0 10px; }"- "QPushButton:hover { background:%2; color:%4; }")- .arg(colors::AMBER_DIM())- .arg(colors::AMBER())- .arg(MONO)- .arg(colors::BG_BASE());-}-// ── Constructor ──────────────────────────────────────────────────────────────SurfaceAnalyticsScreen::SurfaceAnalyticsScreen(QWidget* parent) : QWidget(parent) {srand((unsigned)time(nullptr));setup_ui();+ // Default to the seeded equity underlyings on first open so demo data fills.+ if (!control_panel_->state().basket.isEmpty())+ control_panel_->set_capability(active_chart_);load_demo_data();update_chart();update_metrics();+ update_inspector_lineage();+}++QString SurfaceAnalyticsScreen::current_symbol_or_default() const {+ QString s = control_panel_ ? control_panel_->state().symbol : QString();+ if (s.isEmpty())+ s = QString::fromUtf8(defaults::EQUITY_UNDERLYINGS[0]);+ return s;+}++float SurfaceAnalyticsScreen::spot_for(const QString& sym) const {+ if (sym.isEmpty())+ return 100.0f;+ auto it = spot_cache_.constFind(sym);+ if (it != spot_cache_.constEnd())+ return it.value();+ // Best-effort hub lookup; if no quote published yet, returns invalid QVariant.+ auto& hub = fincept::datahub::DataHub::instance();+ QVariant v = hub.peek(QString("market:quote:%1").arg(sym));+ if (v.isValid()) {+ if (v.canConvert<fincept::services::QuoteData>()) {+ auto q = v.value<fincept::services::QuoteData>();+ if (q.price > 0.0)+ return (float)q.price;+ }+ bool ok = false;+ double d = v.toDouble(&ok);+ if (ok && d > 0.0)+ return (float)d;+ }+ return 100.0f;}// ── Layout ───────────────────────────────────────────────────────────────────@@ -107,16 +138,19 @@ void SurfaceAnalyticsScreen::setup_ui() {surface_bar_ = build_surface_bar();root->addWidget(surface_bar_);- // Content — metrics panel | chart area- auto* splitter = new QSplitter(Qt::Horizontal, this);- splitter->setHandleWidth(1);- splitter->setStyleSheet(QString("QSplitter::handle { background:%1; }").arg(colors::BORDER_DIM()));+ // Vertical split: top = horizontal split (control panel | view stack), bottom = data inspector+ auto* outer = new QSplitter(Qt::Vertical, this);+ outer->setHandleWidth(1);+ outer->setStyleSheet(QString("QSplitter::handle { background:%1; }").arg(colors::BORDER_DIM()));++ auto* hsplit = new QSplitter(Qt::Horizontal, outer);+ hsplit->setHandleWidth(1);+ hsplit->setStyleSheet(QString("QSplitter::handle { background:%1; }").arg(colors::BORDER_DIM()));- metrics_panel_ = new SurfaceMetricsPanel(splitter);- splitter->addWidget(metrics_panel_);+ control_panel_ = new SurfaceControlPanel(hsplit);+ hsplit->addWidget(control_panel_);- // Right: view stack + databento panel- auto* right = new QWidget(splitter);+ auto* right = new QWidget(hsplit);right->setStyleSheet(QString("background:%1;").arg(colors::BG_BASE()));auto* rvl = new QVBoxLayout(right);rvl->setContentsMargins(0, 0, 0, 0);@@ -125,19 +159,35 @@ void SurfaceAnalyticsScreen::setup_ui() {view_stack_ = new QStackedWidget(right);surface_3d_ = new Surface3DWidget(view_stack_);surface_table_ = new SurfaceTableWidget(view_stack_);+ surface_line_ = new SurfaceLineWidget(view_stack_);view_stack_->addWidget(surface_3d_); // 0view_stack_->addWidget(surface_table_); // 1+ view_stack_->addWidget(surface_line_); // 2rvl->addWidget(view_stack_, 1);- databento_panel_ = new SurfaceDatabentoPanel(right);- databento_panel_->setFixedHeight(200);- rvl->addWidget(databento_panel_);-- splitter->addWidget(right);- splitter->setStretchFactor(0, 0);- splitter->setStretchFactor(1, 1);-- root->addWidget(splitter, 1);+ hsplit->addWidget(right);+ hsplit->setStretchFactor(0, 0);+ hsplit->setStretchFactor(1, 1);+ outer->addWidget(hsplit);++ data_inspector_ = new SurfaceDataInspector(outer);+ outer->addWidget(data_inspector_);+ outer->setStretchFactor(0, 1);+ outer->setStretchFactor(1, 0);+ outer->setSizes({600, 220});++ root->addWidget(outer, 1);++ // Wire control panel signals+ connect(control_panel_, &SurfaceControlPanel::controls_changed, this,+ &SurfaceAnalyticsScreen::on_controls_changed);+ connect(control_panel_, &SurfaceControlPanel::symbol_changed, this,+ &SurfaceAnalyticsScreen::on_control_symbol_changed);+ connect(control_panel_, &SurfaceControlPanel::fetch_requested, this,+ &SurfaceAnalyticsScreen::on_fetch_requested);++ // Default visibility / capability for active surface+ control_panel_->set_capability(active_chart_);}// ── Category bar (32px, Obsidian tab style) ──────────────────────────────────@@ -198,20 +248,25 @@ QWidget* SurfaceAnalyticsScreen::build_category_bar() {btn_3d_ = new QPushButton("3D", bar);btn_table_ = new QPushButton("TABLE", bar);+ btn_line_ = new QPushButton("LINE", bar);btn_3d_->setFixedHeight(20);btn_table_->setFixedHeight(20);+ btn_line_->setFixedHeight(20);btn_3d_->setCheckable(true);btn_table_->setCheckable(true);- btn_3d_->setChecked(true);+ btn_line_->setCheckable(true);+ btn_3d_->setChecked(view_mode_ == ViewMode::Surface3D);+ btn_table_->setChecked(view_mode_ == ViewMode::Table);+ btn_line_->setChecked(view_mode_ == ViewMode::Line);- auto tab_style = [&](bool checked) { return checked ? btn_active_amber() : btn_inactive(); };- btn_3d_->setStyleSheet(tab_style(true));- btn_table_->setStyleSheet(tab_style(false));+ apply_view_mode_buttons();connect(btn_3d_, &QPushButton::clicked, this, &SurfaceAnalyticsScreen::on_view_3d);connect(btn_table_, &QPushButton::clicked, this, &SurfaceAnalyticsScreen::on_view_table);+ connect(btn_line_, &QPushButton::clicked, this, &SurfaceAnalyticsScreen::on_view_line);hl->addWidget(btn_3d_);hl->addWidget(btn_table_);+ hl->addWidget(btn_line_);hl->addSpacing(4);hl->addWidget(make_sep(bar));@@ -284,35 +339,6 @@ QWidget* SurfaceAnalyticsScreen::build_surface_bar() {}hl->addStretch();-- // Symbol selector — equity derivatives only- if (active_category_ == 0) {- auto* sym_lbl = new QLabel("SYM:", bar);- sym_lbl->setStyleSheet(QString("color:%1; font-size:11px; background:transparent; font-family:%2;")- .arg(colors::TEXT_SECONDARY())- .arg(MONO));- hl->addWidget(sym_lbl);-- symbol_combo_ = new QComboBox(bar);- for (int s = 0; s < N_SYMBOLS; s++)- symbol_combo_->addItem(VOL_SYMBOLS[s]);- symbol_combo_->setCurrentIndex(selected_symbol_);- symbol_combo_->setFixedHeight(18);- symbol_combo_->setStyleSheet(QString("QComboBox { background:%1; color:%2; border:1px solid %3;"- " padding:0 6px; font-size:11px; font-family:%4; }"- "QComboBox::drop-down { border:none; }"- "QComboBox QAbstractItemView { background:%1; color:%2;"- " border:1px solid %3; selection-background-color:%5; }")- .arg(colors::BG_RAISED())- .arg(colors::TEXT_PRIMARY())- .arg(colors::BORDER_DIM())- .arg(MONO)- .arg(colors::BG_HOVER()));- connect(symbol_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,- &SurfaceAnalyticsScreen::on_symbol_changed);- hl->addWidget(symbol_combo_);- }-return bar;}@@ -331,16 +357,28 @@ void SurfaceAnalyticsScreen::refresh_surface_bar() {// ── Data loading ─────────────────────────────────────────────────────────────void SurfaceAnalyticsScreen::load_demo_data() {- const char* sym = VOL_SYMBOLS[selected_symbol_];- float spot = VOL_SPOTS[selected_symbol_];+ QString qsym = current_symbol_or_default();+ std::string sym = qsym.toStdString();+ float spot = spot_for(qsym);++ // Build a basket vector<string> from the control-panel state for risk surfaces.+ std::vector<std::string> basket;+ if (control_panel_) {+ for (const QString& s : control_panel_->state().basket)+ basket.push_back(s.toStdString());+ }+ if (basket.empty()) {+ for (auto* s : defaults::RISK_BASKET)+ basket.emplace_back(s);+ }- vol_data_ = generate_vol_surface(sym, spot);- delta_data_ = generate_delta_surface(sym, spot);- gamma_data_ = generate_gamma_surface(sym, spot);- vega_data_ = generate_vega_surface(sym, spot);- theta_data_ = generate_theta_surface(sym, spot);- skew_data_ = generate_skew_surface(sym);- local_vol_data_ = generate_local_vol(sym, spot);+ vol_data_ = generate_vol_surface(sym.c_str(), spot);+ delta_data_ = generate_delta_surface(sym.c_str(), spot);+ gamma_data_ = generate_gamma_surface(sym.c_str(), spot);+ vega_data_ = generate_vega_surface(sym.c_str(), spot);+ theta_data_ = generate_theta_surface(sym.c_str(), spot);+ skew_data_ = generate_skew_surface(sym.c_str());+ local_vol_data_ = generate_local_vol(sym.c_str(), spot);yield_data_ = generate_yield_curve();swaption_data_ = generate_swaption_vol();@@ -363,15 +401,15 @@ void SurfaceAnalyticsScreen::load_demo_data() {crack_data_ = generate_crack_spread();contango_data_ = generate_contango();- corr_data_ = generate_correlation(corr_assets_);- pca_data_ = generate_pca(corr_assets_);+ corr_data_ = generate_correlation(basket);+ pca_data_ = generate_pca(basket);var_data_ = generate_var();stress_data_ = generate_stress_test();- factor_data_ = generate_factor_exposure(corr_assets_);- liquidity_data_ = generate_liquidity(sym, spot);- drawdown_data_ = generate_drawdown(corr_assets_);- beta_data_ = generate_beta(corr_assets_);- impl_div_data_ = generate_implied_dividend(sym, spot);+ factor_data_ = generate_factor_exposure(basket);+ liquidity_data_ = generate_liquidity(sym.c_str(), spot);+ drawdown_data_ = generate_drawdown(basket);+ beta_data_ = generate_beta(basket);+ impl_div_data_ = generate_implied_dividend(sym.c_str(), spot);inflation_data_ = generate_inflation_expectations();monetary_data_ = generate_monetary_policy();@@ -419,7 +457,27 @@ void SurfaceAnalyticsScreen::update_chart() {float mn, mx;- if (show_table_) {+ // ── Capability-driven view-mode coercion ───────────────────────────────+ // A surface declares which views it supports. If the active view_mode_ is+ // not supported, fall back to the first one that is.+ const auto& cap = capability_for(active_chart_);+ ViewMode mode = view_mode_;+ if (mode == ViewMode::Surface3D && !cap.supports_3d)+ mode = cap.supports_table ? ViewMode::Table : ViewMode::Line;+ if (mode == ViewMode::Line && !cap.supports_line)+ mode = cap.supports_table ? ViewMode::Table : ViewMode::Surface3D;+ if (mode == ViewMode::Table && !cap.supports_table)+ mode = cap.supports_3d ? ViewMode::Surface3D : ViewMode::Line;++ surface_3d_->set_supported(cap.supports_3d);++ if (mode == ViewMode::Line) {+ view_stack_->setCurrentIndex(2);+ update_line_view();+ return;+ }++ if (mode == ViewMode::Table) {view_stack_->setCurrentIndex(1);switch (active_chart_) {@@ -829,14 +887,276 @@ void SurfaceAnalyticsScreen::update_chart() {}}-// ── Metrics routing ───────────────────────────────────────────────────────────+// ── Metrics routing — now hands the active surface's z grid to the control panel+// which computes summary stats locally (count/min/max/mean/median/std/skew/kurt).void SurfaceAnalyticsScreen::update_metrics() {- metrics_panel_->update_metrics(- active_chart_, vol_data_, delta_data_, gamma_data_, vega_data_, theta_data_, skew_data_, local_vol_data_,- yield_data_, swaption_data_, capfloor_data_, bond_spread_data_, ois_data_, real_yield_data_, fwd_rate_data_,- fx_vol_data_, fx_fwd_data_, xccy_data_, cds_data_, credit_trans_data_, recovery_data_, cmdty_fwd_data_,- cmdty_vol_data_, crack_data_, contango_data_, corr_data_, pca_data_, var_data_, stress_data_, factor_data_,- liquidity_data_, drawdown_data_, beta_data_, impl_div_data_, inflation_data_, monetary_data_);+ if (!control_panel_)+ return;+ if (const auto* z = active_z_grid())+ control_panel_->update_metrics(*z);+ else+ control_panel_->update_metrics({});+}++const std::vector<std::vector<float>>* SurfaceAnalyticsScreen::active_z_grid() const {+ switch (active_chart_) {+ case ChartType::Volatility: return &vol_data_.z;+ case ChartType::DeltaSurface: return &delta_data_.z;+ case ChartType::GammaSurface: return &gamma_data_.z;+ case ChartType::VegaSurface: return &vega_data_.z;+ case ChartType::ThetaSurface: return &theta_data_.z;+ case ChartType::SkewSurface: return &skew_data_.z;+ case ChartType::LocalVolSurface: return &local_vol_data_.z;+ case ChartType::YieldCurve: return &yield_data_.z;+ case ChartType::SwaptionVol: return &swaption_data_.z;+ case ChartType::CapFloorVol: return &capfloor_data_.z;+ case ChartType::BondSpread: return &bond_spread_data_.z;+ case ChartType::OISBasis: return &ois_data_.z;+ case ChartType::RealYield: return &real_yield_data_.z;+ case ChartType::ForwardRate: return &fwd_rate_data_.z;+ case ChartType::FXVol: return &fx_vol_data_.z;+ case ChartType::FXForwardPoints: return &fx_fwd_data_.z;+ case ChartType::CrossCurrencyBasis: return &xccy_data_.z;+ case ChartType::CDSSpread: return &cds_data_.z;+ case ChartType::CreditTransition: return &credit_trans_data_.z;+ case ChartType::RecoveryRate: return &recovery_data_.z;+ case ChartType::CommodityForward: return &cmdty_fwd_data_.z;+ case ChartType::CommodityVol: return &cmdty_vol_data_.z;+ case ChartType::CrackSpread: return &crack_data_.z;+ case ChartType::ContangoBackwardation: return &contango_data_.z;+ case ChartType::Correlation: return &corr_data_.z;+ case ChartType::PCA: return &pca_data_.z;+ case ChartType::VaR: return &var_data_.z;+ case ChartType::StressTestPnL: return &stress_data_.z;+ case ChartType::FactorExposure: return &factor_data_.z;+ case ChartType::LiquidityHeatmap: return &liquidity_data_.z;+ case ChartType::Drawdown: return &drawdown_data_.z;+ case ChartType::BetaSurface: return &beta_data_.z;+ case ChartType::ImpliedDividend: return &impl_div_data_.z;+ case ChartType::InflationExpectations: return &inflation_data_.z;+ case ChartType::MonetaryPolicyPath: return &monetary_data_.z;+ }+ return nullptr;+}++void SurfaceAnalyticsScreen::update_inspector_lineage() {+ if (!data_inspector_)+ return;+ const auto& cap = capability_for(active_chart_);+ QString date_range;+ if (control_panel_) {+ const auto& s = control_panel_->state();+ if (s.start_date.isValid() && s.end_date.isValid())+ date_range = QString("%1 → %2")+ .arg(s.start_date.toString("yyyy-MM-dd"))+ .arg(s.end_date.toString("yyyy-MM-dd"));+ }+ QString sym = current_symbol_or_default();+ if (cap.tier == SurfaceTier::EQUITIES && control_panel_)+ sym = control_panel_->state().basket.join(",");+ qint64 count = 0;+ if (const auto* z = active_z_grid())+ for (const auto& row : *z)+ count += (qint64)row.size();+ data_inspector_->set_lineage(QString::fromUtf8(cap.dataset),+ QString::fromUtf8(cap.schema),+ QString::fromUtf8(cap.symbology),+ sym, date_range, count, 0.0);++ // Fire-and-forget cost lookup. Skip for DEMO (no dataset) and for+ // capabilities whose schema is a composite ("definition+cbbo-1s") since+ // metadata.get_cost takes a single schema. Use the first listed.+ if (cap.tier == SurfaceTier::DEMO || !control_panel_)+ return;+ auto& svc = DatabentoService::instance();+ if (!svc.has_api_key())+ return;+ const auto& s = control_panel_->state();+ if (!s.start_date.isValid() || !s.end_date.isValid())+ return;+ QString schema = QString::fromUtf8(cap.schema);+ int plus = schema.indexOf('+');+ if (plus >= 0)+ schema = schema.left(plus);+ DbCostQuery q;+ q.dataset = QString::fromUtf8(cap.dataset);+ q.schema = schema;+ q.start = s.start_date;+ q.end = s.end_date;+ q.stype_in = QString::fromUtf8(cap.symbology);+ if (cap.tier == SurfaceTier::EQUITIES)+ q.symbols = s.basket.isEmpty() ? QStringList{s.symbol} : s.basket;+ else if (QString::fromUtf8(cap.symbology) == "parent")+ q.symbols = QStringList{s.symbol + ".OPT"};+ else+ q.symbols = QStringList{s.symbol};++ QPointer<SurfaceAnalyticsScreen> self = this;+ QString ds = q.dataset;+ QString sch = QString::fromUtf8(cap.schema);+ QString symb = QString::fromUtf8(cap.symbology);+ QString sym_text = sym;+ QString dr = date_range;+ qint64 row_ct = count;+ svc.get_cost(q, [self, ds, sch, symb, sym_text, dr, row_ct](DbCostResult r) {+ if (!self || !self->data_inspector_)+ return;+ if (!r.success)+ return;+ self->data_inspector_->set_lineage(ds, sch, symb, sym_text, dr,+ row_ct > 0 ? row_ct : r.record_count,+ r.cost_usd);+ });+}++void SurfaceAnalyticsScreen::update_line_view() {+ if (!surface_line_)+ return;+ auto fmt_months_str = [](const std::vector<int>& v) {+ QStringList out;+ for (int i : v) out << QString("%1M").arg(i);+ return out;+ };++ switch (active_chart_) {+ case ChartType::YieldCurve: {+ // Show the latest column of the yield matrix as a single curve+ if (yield_data_.z.empty() || yield_data_.maturities.empty())+ break;+ std::vector<float> xs, ys;+ for (size_t i = 0; i < yield_data_.maturities.size(); ++i) {+ xs.push_back((float)yield_data_.maturities[i]);+ ys.push_back(yield_data_.z[0].size() > i ? yield_data_.z[0][i] : 0.0f);+ }+ surface_line_->set_curve("YIELD CURVE", xs, ys, fmt_months_str(yield_data_.maturities),+ "Maturity (months)", "Yield %", QColor(63, 185, 80));+ return;+ }+ case ChartType::ContangoBackwardation: {+ std::vector<SurfaceLineWidget::Series> series;+ for (size_t i = 0; i < contango_data_.commodities.size() && i < contango_data_.z.size(); ++i) {+ SurfaceLineWidget::Series s;+ s.name = QString::fromStdString(contango_data_.commodities[i]);+ for (size_t k = 0; k < contango_data_.contract_months.size(); ++k)+ s.x_values.push_back((float)contango_data_.contract_months[k]);+ s.y_values.assign(contango_data_.z[i].begin(), contango_data_.z[i].end());+ static const QColor palette[] = {+ QColor(217, 119, 6), QColor(88, 166, 255), QColor(63, 185, 80),+ QColor(220, 80, 80), QColor(155, 114, 255), QColor(89, 196, 217)};+ s.color = palette[i % 6];+ series.push_back(s);+ }+ surface_line_->set_series("CONTANGO / BACKWARDATION", series, "Contract month", "Roll %");+ return;+ }+ case ChartType::CommodityForward: {+ std::vector<SurfaceLineWidget::Series> series;+ for (size_t i = 0; i < cmdty_fwd_data_.commodities.size() && i < cmdty_fwd_data_.z.size(); ++i) {+ SurfaceLineWidget::Series s;+ s.name = QString::fromStdString(cmdty_fwd_data_.commodities[i]);+ for (size_t k = 0; k < cmdty_fwd_data_.contract_months.size(); ++k)+ s.x_values.push_back((float)cmdty_fwd_data_.contract_months[k]);+ s.y_values.assign(cmdty_fwd_data_.z[i].begin(), cmdty_fwd_data_.z[i].end());+ static const QColor palette[] = {+ QColor(217, 119, 6), QColor(88, 166, 255), QColor(63, 185, 80),+ QColor(220, 80, 80), QColor(155, 114, 255), QColor(89, 196, 217)};+ s.color = palette[i % 6];+ series.push_back(s);+ }+ surface_line_->set_series("FUTURES TERM STRUCTURE", series, "Contract month", "Price");+ return;+ }+ case ChartType::CrackSpread: {+ std::vector<SurfaceLineWidget::Series> series;+ for (size_t i = 0; i < crack_data_.spread_types.size() && i < crack_data_.z.size(); ++i) {+ SurfaceLineWidget::Series s;+ s.name = QString::fromStdString(crack_data_.spread_types[i]);+ for (size_t k = 0; k < crack_data_.contract_months.size(); ++k)+ s.x_values.push_back((float)crack_data_.contract_months[k]);+ s.y_values.assign(crack_data_.z[i].begin(), crack_data_.z[i].end());+ static const QColor palette[] = {QColor(217, 119, 6), QColor(88, 166, 255),+ QColor(63, 185, 80), QColor(220, 80, 80)};+ s.color = palette[i % 4];+ series.push_back(s);+ }+ surface_line_->set_series("CRACK / CRUSH SPREAD", series, "Contract month", "Spread $/bbl");+ return;+ }+ case ChartType::FXForwardPoints: {+ std::vector<SurfaceLineWidget::Series> series;+ for (size_t i = 0; i < fx_fwd_data_.pairs.size() && i < fx_fwd_data_.z.size(); ++i) {+ SurfaceLineWidget::Series s;+ s.name = QString::fromStdString(fx_fwd_data_.pairs[i]);+ for (size_t k = 0; k < fx_fwd_data_.tenors.size(); ++k)+ s.x_values.push_back((float)fx_fwd_data_.tenors[k]);+ s.y_values.assign(fx_fwd_data_.z[i].begin(), fx_fwd_data_.z[i].end());+ static const QColor palette[] = {QColor(217, 119, 6), QColor(88, 166, 255),+ QColor(63, 185, 80), QColor(220, 80, 80)};+ s.color = palette[i % 4];+ series.push_back(s);+ }+ surface_line_->set_series("FX FORWARD POINTS", series, "Tenor (months)", "Fwd points");+ return;+ }+ case ChartType::InflationExpectations: {+ if (inflation_data_.z.empty() || inflation_data_.horizons.empty())+ break;+ std::vector<float> xs, ys;+ for (size_t i = 0; i < inflation_data_.horizons.size(); ++i) {+ xs.push_back((float)inflation_data_.horizons[i]);+ ys.push_back(inflation_data_.z[0].size() > i ? inflation_data_.z[0][i] : 0.0f);+ }+ QStringList xl;+ for (int h : inflation_data_.horizons) xl << QString("%1Y").arg(h);+ surface_line_->set_curve("INFLATION EXPECTATIONS", xs, ys, xl,+ "Horizon (years)", "Breakeven %",+ QColor(89, 196, 217));+ return;+ }+ case ChartType::MonetaryPolicyPath: {+ std::vector<SurfaceLineWidget::Series> series;+ for (size_t i = 0; i < monetary_data_.central_banks.size() && i < monetary_data_.z.size(); ++i) {+ SurfaceLineWidget::Series s;+ s.name = QString::fromStdString(monetary_data_.central_banks[i]);+ for (size_t k = 0; k < monetary_data_.meetings_ahead.size(); ++k)+ s.x_values.push_back((float)monetary_data_.meetings_ahead[k]);+ s.y_values.assign(monetary_data_.z[i].begin(), monetary_data_.z[i].end());+ static const QColor palette[] = {QColor(217, 119, 6), QColor(88, 166, 255),+ QColor(63, 185, 80), QColor(220, 80, 80)};+ s.color = palette[i % 4];+ series.push_back(s);+ }+ surface_line_->set_series("RATE PATH", series, "Meetings ahead", "Rate %");+ return;+ }+ default:+ break;+ }+ // Fallback — clear if the current chart has no line representation.+ surface_line_->clear();+}++void SurfaceAnalyticsScreen::apply_view_mode_buttons() {+ auto active = [&]() {+ return QString("QPushButton { background:rgba(217,119,6,0.18); color:%1; "+ "border:1px solid %2; padding:0 10px; font-size:11px; "+ "font-weight:bold; font-family:%3; }")+ .arg(colors::AMBER())+ .arg(colors::AMBER_DIM())+ .arg(MONO);+ };+ if (btn_3d_) {+ btn_3d_->setChecked(view_mode_ == ViewMode::Surface3D);+ btn_3d_->setStyleSheet(view_mode_ == ViewMode::Surface3D ? active() : btn_inactive());+ }+ if (btn_table_) {+ btn_table_->setChecked(view_mode_ == ViewMode::Table);+ btn_table_->setStyleSheet(view_mode_ == ViewMode::Table ? active() : btn_inactive());+ }+ if (btn_line_) {+ btn_line_->setChecked(view_mode_ == ViewMode::Line);+ btn_line_->setStyleSheet(view_mode_ == ViewMode::Line ? active() : btn_inactive());+ }}// ── Slots ─────────────────────────────────────────────────────────────────────@@ -865,9 +1185,12 @@ void SurfaceAnalyticsScreen::on_category_clicked(int index) {}}- databento_panel_->set_active_chart(active_chart_, VOL_SYMBOLS[selected_symbol_], VOL_SPOTS[selected_symbol_]);+ if (control_panel_)+ control_panel_->set_capability(active_chart_);+ load_dataset_range_for_active_capability();update_chart();update_metrics();+ update_inspector_lineage();fincept::ScreenStateManager::instance().notify_changed(this);}@@ -876,22 +1199,29 @@ void SurfaceAnalyticsScreen::on_surface_clicked(int cat, int surf_index) {if (cat < (int)cats.size() && surf_index < (int)cats[cat].types.size())active_chart_ = cats[cat].types[surf_index];refresh_surface_bar();- databento_panel_->set_active_chart(active_chart_, VOL_SYMBOLS[selected_symbol_], VOL_SPOTS[selected_symbol_]);+ if (control_panel_)+ control_panel_->set_capability(active_chart_);+ load_dataset_range_for_active_capability();update_chart();update_metrics();+ update_inspector_lineage();}void SurfaceAnalyticsScreen::on_view_3d() {- show_table_ = false;- btn_3d_->setStyleSheet(btn_active_amber());- btn_table_->setStyleSheet(btn_inactive());+ view_mode_ = ViewMode::Surface3D;+ apply_view_mode_buttons();update_chart();}void SurfaceAnalyticsScreen::on_view_table() {- show_table_ = true;- btn_3d_->setStyleSheet(btn_inactive());- btn_table_->setStyleSheet(btn_active_amber());+ view_mode_ = ViewMode::Table;+ apply_view_mode_buttons();+ update_chart();+}++void SurfaceAnalyticsScreen::on_view_line() {+ view_mode_ = ViewMode::Line;+ apply_view_mode_buttons();update_chart();}@@ -905,14 +1235,68 @@ void SurfaceAnalyticsScreen::on_refresh() {load_demo_data();update_chart();update_metrics();+ update_inspector_lineage();}-void SurfaceAnalyticsScreen::on_symbol_changed(int index) {- selected_symbol_ = index;+void SurfaceAnalyticsScreen::on_controls_changed() {+ update_inspector_lineage();+}++void SurfaceAnalyticsScreen::on_control_symbol_changed(const QString& /*sym*/) {+ // Rebuild demo surfaces with the new underlying so the chart isn't stale.load_demo_data();update_chart();update_metrics();- databento_panel_->set_active_chart(active_chart_, VOL_SYMBOLS[selected_symbol_], VOL_SPOTS[selected_symbol_]);+ update_inspector_lineage();+}++void SurfaceAnalyticsScreen::on_fetch_requested() {+ if (!control_panel_)+ return;+ const auto& cap = capability_for(active_chart_);+ if (cap.tier == SurfaceTier::DEMO)+ return; // Button should be disabled, but guard anyway++ auto& svc = DatabentoService::instance();+ if (!svc.has_api_key()) {+ if (data_inspector_) {+ data_inspector_->set_status("No Databento API key configured", false);+ data_inspector_->set_error("Add a key in Settings → Credentials → Databento.");+ }+ return;+ }++ DatabentoFetchParams p;+ static const char* CT_NAMES[] = {+ "Volatility", "DeltaSurface", "GammaSurface", "VegaSurface", "ThetaSurface",+ "SkewSurface", "LocalVolSurface", "YieldCurve", "SwaptionVol", "CapFloorVol",+ "BondSpread", "OISBasis", "RealYield", "ForwardRate", "FXVol",+ "FXForwardPoints", "CrossCurrencyBasis", "CDSSpread", "CreditTransition",+ "RecoveryRate", "CommodityForward", "CommodityVol", "CrackSpread",+ "ContangoBackwardation", "Correlation", "PCA", "VaR", "StressTestPnL",+ "FactorExposure", "LiquidityHeatmap", "Drawdown", "BetaSurface",+ "ImpliedDividend", "InflationExpectations", "MonetaryPolicyPath",+ };+ int idx = (int)active_chart_;+ if (idx >= 0 && idx < (int)(sizeof(CT_NAMES) / sizeof(CT_NAMES[0])))+ p.chart_type = QString::fromUtf8(CT_NAMES[idx]);++ const auto& s = control_panel_->state();+ p.symbol = s.symbol;+ p.basket = s.basket;+ p.dataset = s.dataset.isEmpty() ? QString::fromUtf8(cap.dataset) : s.dataset;+ p.start_date = s.start_date;+ p.end_date = s.end_date;+ p.strike_window_pct = s.strike_window_pct;+ p.dte_min = s.dte_min;+ p.dte_max = s.dte_max;+ p.iv_method = s.iv_method;+ p.spot_override = spot_for(p.symbol);++ if (data_inspector_)+ data_inspector_->set_status(+ QString("Fetching %1 …").arg(QString::fromUtf8(chart_type_name(active_chart_))), true);+ svc.fetch_with_params(p);}void SurfaceAnalyticsScreen::dispatch_csv(const QString& path) {@@ -958,49 +1342,102 @@ void SurfaceAnalyticsScreen::dispatch_csv(const QString& path) {// ── Databento slots ───────────────────────────────────────────────────────────void SurfaceAnalyticsScreen::on_vol_surface_received(const fincept::DatabentoVolSurfaceResult& r) {- if (r.success) {- const char* sym = VOL_SYMBOLS[selected_symbol_];- float spot = VOL_SPOTS[selected_symbol_];- if (!r.vol.z.empty()) {- vol_data_ = r.vol;- vol_data_.underlying = sym;- vol_data_.spot_price = spot;- }- if (!r.delta.z.empty()) {- delta_data_ = r.delta;- delta_data_.underlying = sym;- delta_data_.spot_price = spot;- }- if (!r.gamma.z.empty()) {- gamma_data_ = r.gamma;- gamma_data_.underlying = sym;- gamma_data_.spot_price = spot;- }- if (!r.vega.z.empty()) {- vega_data_ = r.vega;- vega_data_.underlying = sym;- vega_data_.spot_price = spot;- }- if (!r.theta.z.empty()) {- theta_data_ = r.theta;- theta_data_.underlying = sym;- theta_data_.spot_price = spot;- }- if (!r.skew.z.empty()) {- skew_data_ = r.skew;- skew_data_.underlying = sym;+ if (data_inspector_)+ data_inspector_->set_status(r.success ? "Vol surface loaded" : "Vol fetch failed", r.success);+ if (!r.success) {+ if (data_inspector_)+ data_inspector_->set_error(r.error);+ update_chart();+ return;+ }++ QString sym = current_symbol_or_default();+ std::string sym_std = sym.toStdString();+ float spot = spot_for(sym);++ if (!r.vol.z.empty()) {+ vol_data_ = r.vol;+ vol_data_.underlying = sym_std;+ vol_data_.spot_price = spot;+ }+ if (!r.delta.z.empty()) {+ delta_data_ = r.delta;+ delta_data_.underlying = sym_std;+ delta_data_.spot_price = spot;+ }+ if (!r.gamma.z.empty()) {+ gamma_data_ = r.gamma;+ gamma_data_.underlying = sym_std;+ gamma_data_.spot_price = spot;+ }+ if (!r.vega.z.empty()) {+ vega_data_ = r.vega;+ vega_data_.underlying = sym_std;+ vega_data_.spot_price = spot;+ }+ if (!r.theta.z.empty()) {+ theta_data_ = r.theta;+ theta_data_.underlying = sym_std;+ theta_data_.spot_price = spot;+ }+ if (!r.skew.z.empty()) {+ skew_data_ = r.skew;+ skew_data_.underlying = sym_std;+ }++ if (data_inspector_) {+ QStringList headers = {"strike", "expiration", "iv"};+ QVector<QStringList> rows;+ for (size_t i = 0; i < vol_data_.strikes.size(); ++i) {+ for (size_t j = 0; j < vol_data_.expirations.size(); ++j) {+ if (i < vol_data_.z.size() && j < vol_data_.z[i].size()) {+ rows.push_back({QString::number(vol_data_.strikes[i], 'f', 2),+ QString::number(vol_data_.expirations[j]),+ QString::number(vol_data_.z[i][j], 'f', 4)});+ }+ }}+ data_inspector_->show_table("vol_surface", headers, rows);}+update_chart();update_metrics();+ update_inspector_lineage();}-void SurfaceAnalyticsScreen::on_ohlcv_received(const fincept::DatabentoOhlcvResult&) {+void SurfaceAnalyticsScreen::on_ohlcv_received(const fincept::DatabentoOhlcvResult& r) {+ if (data_inspector_) {+ data_inspector_->set_status(r.success ? "OHLCV loaded" : "OHLCV fetch failed", r.success);+ if (!r.success)+ data_inspector_->set_error(r.error);+ else {+ QStringList headers = {"symbol", "date", "open", "high", "low", "close", "volume"};+ QVector<QStringList> rows;+ for (auto it = r.data.constBegin(); it != r.data.constEnd(); ++it) {+ for (const QJsonObject& bar : it.value()) {+ rows.push_back({it.key(),+ bar.value("date").toString(),+ QString::number(bar.value("open").toDouble(), 'f', 2),+ QString::number(bar.value("high").toDouble(), 'f', 2),+ QString::number(bar.value("low").toDouble(), 'f', 2),+ QString::number(bar.value("close").toDouble(), 'f', 2),+ QString::number(bar.value("volume").toDouble(), 'f', 0)});+ }+ }+ data_inspector_->show_table("ohlcv-1d", headers, rows);+ }+ }update_chart();update_metrics();+ update_inspector_lineage();}void SurfaceAnalyticsScreen::on_futures_received(const fincept::DatabentoFuturesResult& r) {+ if (data_inspector_) {+ data_inspector_->set_status(r.success ? "Futures curve loaded" : "Futures fetch failed", r.success);+ if (!r.success)+ data_inspector_->set_error(r.error);+ }if (r.success) {if (!r.forward.z.empty())cmdty_fwd_data_ = r.forward;@@ -1009,36 +1446,45 @@ void SurfaceAnalyticsScreen::on_futures_received(const fincept::DatabentoFutures}update_chart();update_metrics();+ update_inspector_lineage();}void SurfaceAnalyticsScreen::on_surface_received(const fincept::DatabentoSurfaceResult& r) {+ if (data_inspector_) {+ data_inspector_->set_status(r.success ? "Surface loaded" : "Surface fetch failed", r.success);+ if (!r.success)+ data_inspector_->set_error(r.error);+ }if (!r.success) {update_chart();return;}const auto& type = r.type;+ QString sym = current_symbol_or_default();+ std::string sym_std = sym.toStdString();+ float spot = spot_for(sym);if (type == "local_vol" && !r.z.empty()) {local_vol_data_.strikes.assign(r.x_axis.begin(), r.x_axis.end());local_vol_data_.expirations.assign(r.y_axis.begin(), r.y_axis.end());local_vol_data_.z = r.z;- local_vol_data_.underlying = VOL_SYMBOLS[selected_symbol_];- local_vol_data_.spot_price = VOL_SPOTS[selected_symbol_];+ local_vol_data_.underlying = sym_std;+ local_vol_data_.spot_price = spot;} else if (type == "implied_dividend" && !r.z.empty()) {impl_div_data_.strikes.assign(r.x_axis.begin(), r.x_axis.end());impl_div_data_.expirations.assign(r.y_axis.begin(), r.y_axis.end());impl_div_data_.z = r.z;- impl_div_data_.underlying = VOL_SYMBOLS[selected_symbol_];+ impl_div_data_.underlying = sym_std;} else if (type == "liquidity" && !r.z.empty()) {liquidity_data_.strikes.assign(r.x_axis.begin(), r.x_axis.end());liquidity_data_.expirations.assign(r.y_axis.begin(), r.y_axis.end());liquidity_data_.z = r.z;- liquidity_data_.underlying = VOL_SYMBOLS[selected_symbol_];+ liquidity_data_.underlying = sym_std;} else if (type == "commodity_vol" && !r.z.empty()) {cmdty_vol_data_.strikes.assign(r.x_axis.begin(), r.x_axis.end());cmdty_vol_data_.expirations.assign(r.y_axis.begin(), r.y_axis.end());cmdty_vol_data_.z = r.z;- cmdty_vol_data_.commodity = "CL";+ cmdty_vol_data_.commodity = sym_std;} else if (type == "crack_spread" && !r.z.empty()) {crack_data_.spread_types = r.x_labels;crack_data_.contract_months.assign(r.y_axis.begin(), r.y_axis.end());@@ -1047,86 +1493,171 @@ void SurfaceAnalyticsScreen::on_surface_received(const fincept::DatabentoSurfacestress_data_.scenarios = r.x_labels;stress_data_.portfolios = r.y_labels;stress_data_.z = r.z;- } else if (type == "yield_curve" && !r.z.empty()) {- yield_data_.maturities.clear();- for (float f : r.x_axis)- yield_data_.maturities.push_back((int)f);- yield_data_.time_points.assign(r.y_axis.begin(), r.y_axis.end());- yield_data_.z = r.z;- } else if (type == "forward_rate" && !r.z.empty()) {- fwd_rate_data_.start_tenors.clear();- for (float f : r.x_axis)- fwd_rate_data_.start_tenors.push_back((int)f);- fwd_rate_data_.forward_periods.assign(r.y_axis.begin(), r.y_axis.end());- fwd_rate_data_.z = r.z;- } else if (type == "rate_path" && !r.z.empty()) {- monetary_data_.central_banks = r.x_labels;- monetary_data_.meetings_ahead.assign(r.y_axis.begin(), r.y_axis.end());- monetary_data_.z = r.z;- } else if (type == "fx_forward_points" && !r.z.empty()) {- fx_fwd_data_.pairs = r.x_labels;- fx_fwd_data_.tenors.assign(r.y_axis.begin(), r.y_axis.end());- fx_fwd_data_.z = r.z;}update_chart();update_metrics();+ update_inspector_lineage();+}++void SurfaceAnalyticsScreen::on_db_fetch_started(const QString& desc) {+ if (data_inspector_)+ data_inspector_->set_status(desc, true);+}++void SurfaceAnalyticsScreen::on_db_fetch_failed(const QString& err) {+ if (data_inspector_) {+ data_inspector_->set_status("Fetch failed", false);+ data_inspector_->set_error(err);+ }+}++void SurfaceAnalyticsScreen::on_db_connection_tested(bool ok, const QString& msg) {+ if (!control_panel_)+ return;+ control_panel_->set_provider_status("databento",+ ok ? "connected" : "error",+ ok ? QString() : msg);+}++void SurfaceAnalyticsScreen::on_db_raw_response(const QString& cmd, const QString& raw_stdout) {+ if (!data_inspector_)+ return;+ QString header = QString("=== %1 ===\n").arg(cmd);+ data_inspector_->set_raw_output(header + raw_stdout);+}++void SurfaceAnalyticsScreen::refresh_provider_status() {+ if (!control_panel_)+ return;+ auto& svc = DatabentoService::instance();+ control_panel_->set_provider_status(+ "databento",+ svc.has_api_key() ? "configured" : "not configured",+ svc.has_api_key() ? "key set" : "Settings → Credentials");+}++void SurfaceAnalyticsScreen::load_dataset_range_for_active_capability() {+ if (!control_panel_)+ return;+ const auto& cap = capability_for(active_chart_);+ QString ds = QString::fromUtf8(cap.dataset);+ if (ds.isEmpty())+ return; // DEMO surface — no Databento dataset to query+ auto& svc = DatabentoService::instance();+ if (!svc.has_api_key())+ return;+ QPointer<SurfaceAnalyticsScreen> self = this;+ svc.get_dataset_range(ds, [self](DbDatasetRange r) {+ if (!self || !self->control_panel_)+ return;+ self->control_panel_->apply_dataset_range(r.start, r.end);+ });}// ── Show/hide event — P3 compliance ──────────────────────────────────────────void SurfaceAnalyticsScreen::showEvent(QShowEvent* e) {QWidget::showEvent(e);- connect(databento_panel_, &SurfaceDatabentoPanel::vol_surface_received, this,+ auto& svc = DatabentoService::instance();+ connect(&svc, &DatabentoService::vol_surface_ready, this,&SurfaceAnalyticsScreen::on_vol_surface_received, Qt::UniqueConnection);- connect(databento_panel_, &SurfaceDatabentoPanel::ohlcv_received, this, &SurfaceAnalyticsScreen::on_ohlcv_received,- Qt::UniqueConnection);- connect(databento_panel_, &SurfaceDatabentoPanel::futures_received, this,+ connect(&svc, &DatabentoService::ohlcv_ready, this,+ &SurfaceAnalyticsScreen::on_ohlcv_received, Qt::UniqueConnection);+ connect(&svc, &DatabentoService::futures_ready, this,&SurfaceAnalyticsScreen::on_futures_received, Qt::UniqueConnection);- connect(databento_panel_, &SurfaceDatabentoPanel::surface_received, this,+ connect(&svc, &DatabentoService::surface_ready, this,&SurfaceAnalyticsScreen::on_surface_received, Qt::UniqueConnection);+ connect(&svc, &DatabentoService::fetch_started, this,+ &SurfaceAnalyticsScreen::on_db_fetch_started, Qt::UniqueConnection);+ connect(&svc, &DatabentoService::fetch_failed, this,+ &SurfaceAnalyticsScreen::on_db_fetch_failed, Qt::UniqueConnection);+ connect(&svc, &DatabentoService::connection_tested, this,+ &SurfaceAnalyticsScreen::on_db_connection_tested, Qt::UniqueConnection);+ connect(&svc, &DatabentoService::raw_response, this,+ &SurfaceAnalyticsScreen::on_db_raw_response, Qt::UniqueConnection);+ refresh_provider_status();+ load_dataset_range_for_active_capability();}void SurfaceAnalyticsScreen::hideEvent(QHideEvent* e) {QWidget::hideEvent(e);- disconnect(databento_panel_, nullptr, this, nullptr);+ auto& svc = DatabentoService::instance();+ disconnect(&svc, nullptr, this, nullptr);}// ── IStatefulScreen ───────────────────────────────────────────────────────────QVariantMap SurfaceAnalyticsScreen::save_state() const {- return {+ QVariantMap s{{"category", active_category_},{"chart", static_cast<int>(active_chart_)},+ {"view_mode", static_cast<int>(view_mode_)},};+ if (control_panel_) {+ const auto& cs = control_panel_->state();+ s["symbol"] = cs.symbol;+ s["dataset"] = cs.dataset;+ s["start_date"] = cs.start_date.toString(Qt::ISODate);+ s["end_date"] = cs.end_date.toString(Qt::ISODate);+ s["strike_window_pct"] = cs.strike_window_pct;+ s["dte_min"] = cs.dte_min;+ s["dte_max"] = cs.dte_max;+ s["iv_method"] = cs.iv_method;+ s["basket"] = cs.basket;+ }+ return s;}void SurfaceAnalyticsScreen::restore_state(const QVariantMap& state) {const int cat = state.value("category", 0).toInt();if (cat != active_category_)on_category_clicked(cat);+ if (state.contains("view_mode")) {+ view_mode_ = static_cast<ViewMode>(state.value("view_mode", 0).toInt());+ apply_view_mode_buttons();+ }+ if (control_panel_) {+ SurfaceControlsState cs = control_panel_->state();+ cs.symbol = state.value("symbol", cs.symbol).toString();+ cs.dataset = state.value("dataset", cs.dataset).toString();+ QString sd = state.value("start_date").toString();+ QString ed = state.value("end_date").toString();+ if (!sd.isEmpty()) cs.start_date = QDate::fromString(sd, Qt::ISODate);+ if (!ed.isEmpty()) cs.end_date = QDate::fromString(ed, Qt::ISODate);+ cs.strike_window_pct = state.value("strike_window_pct", cs.strike_window_pct).toInt();+ cs.dte_min = state.value("dte_min", cs.dte_min).toInt();+ cs.dte_max = state.value("dte_max", cs.dte_max).toInt();+ cs.iv_method = state.value("iv_method", cs.iv_method).toString();+ cs.basket = state.value("basket", cs.basket).toStringList();+ control_panel_->apply_state(cs);+ load_demo_data();+ update_chart();+ update_metrics();+ }}// ── IGroupLinked ─────────────────────────────────────────────────────────────void SurfaceAnalyticsScreen::on_group_symbol_changed(const fincept::SymbolRef& ref) {- if (!ref.is_valid() || !symbol_combo_)+ if (!ref.is_valid() || !control_panel_)return;- // Only act when the incoming symbol matches one of our supported tickers- // (VOL_SYMBOLS). For anything else the screen has no data surface, so- // silently ignore rather than clearing the current view.- for (int i = 0; i < N_SYMBOLS; ++i) {- if (ref.symbol.compare(QString::fromLatin1(VOL_SYMBOLS[i]), Qt::CaseInsensitive) == 0) {- if (symbol_combo_->currentIndex() != i)- symbol_combo_->setCurrentIndex(i); // triggers on_symbol_changed- return;- }- }+ // Push the linked symbol into the control panel; demo data + chart rebuild+ // happen via on_control_symbol_changed.+ SurfaceControlsState cs = control_panel_->state();+ if (cs.symbol.compare(ref.symbol, Qt::CaseInsensitive) == 0)+ return;+ cs.symbol = ref.symbol.toUpper();+ control_panel_->apply_state(cs);+ on_control_symbol_changed(cs.symbol);}fincept::SymbolRef SurfaceAnalyticsScreen::current_symbol() const {- if (selected_symbol_ < 0 || selected_symbol_ >= N_SYMBOLS)+ if (!control_panel_)+ return {};+ QString s = control_panel_->state().symbol;+ if (s.isEmpty())return {};- return fincept::SymbolRef::equity(QString::fromLatin1(VOL_SYMBOLS[selected_symbol_]));+ return fincept::SymbolRef::equity(s);}} // namespace fincept::surfacediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.h b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.hindex 6cd925c29..c571bb2f5 100644--- a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.h+++ b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.h@@ -2,18 +2,20 @@// SurfaceAnalyticsScreen — 35 financial surface visualizations// Equity derivatives, fixed income, FX, credit, commodities, risk, macro+#include "SurfaceCapabilities.h"#include "SurfaceDemoData.h"#include "SurfaceTypes.h"#include "core/symbol/IGroupLinked.h"#include "screens/IStatefulScreen.h"#include "services/databento/DatabentoService.h"-#include <QComboBox>+#include <QHash>#include <QLabel>#include <QPushButton>#include <QScrollArea>#include <QSplitter>#include <QStackedWidget>+#include <QString>#include <QVBoxLayout>#include <QWidget>@@ -21,8 +23,9 @@ namespace fincept::surface {class Surface3DWidget;class SurfaceTableWidget;-class SurfaceMetricsPanel;-class SurfaceDatabentoPanel;+class SurfaceLineWidget;+class SurfaceControlPanel;+class SurfaceDataInspector;class SurfaceAnalyticsScreen : public QWidget,public fincept::screens::IStatefulScreen,@@ -37,8 +40,9 @@ class SurfaceAnalyticsScreen : public QWidget,QString state_key() const override { return "surface_analytics"; }int state_version() const override { return 1; }- // IGroupLinked — subscribe-only. Only equity group changes are honoured,- // and only if the symbol is in VOL_SYMBOLS (the screen's supported list).+ // IGroupLinked — subscribe-only. Equity group changes are forwarded to+ // the SurfaceControlPanel which becomes the new symbol of record; demo data+ // and chart re-render via on_control_symbol_changed.void set_group(fincept::SymbolGroup g) override { link_group_ = g; }fincept::SymbolGroup group() const override { return link_group_; }void on_group_symbol_changed(const fincept::SymbolRef& ref) override;@@ -49,57 +53,66 @@ class SurfaceAnalyticsScreen : public QWidget,void on_surface_clicked(int cat, int surf_index);void on_view_3d();void on_view_table();+ void on_view_line();void on_import_csv();void on_refresh();- void on_symbol_changed(int index);+ void on_controls_changed();+ void on_control_symbol_changed(const QString& sym);+ void on_fetch_requested();// Databento data slotsvoid on_vol_surface_received(const fincept::DatabentoVolSurfaceResult& r);void on_ohlcv_received(const fincept::DatabentoOhlcvResult& r);void on_futures_received(const fincept::DatabentoFuturesResult& r);void on_surface_received(const fincept::DatabentoSurfaceResult& r);+ void on_db_fetch_started(const QString& desc);+ void on_db_fetch_failed(const QString& err);+ void on_db_connection_tested(bool ok, const QString& msg);+ void on_db_raw_response(const QString& cmd, const QString& raw_stdout);protected:void showEvent(QShowEvent* e) override;void hideEvent(QHideEvent* e) override;private:+ enum class ViewMode { Surface3D = 0, Table = 1, Line = 2 };+void setup_ui();- QWidget* build_control_bar();QWidget* build_category_bar();QWidget* build_surface_bar();void refresh_surface_bar();void load_demo_data();void update_chart();void update_metrics();+ void update_inspector_lineage();void dispatch_csv(const QString& path);+ void apply_view_mode_buttons();+ void update_line_view();+ void refresh_provider_status();+ void load_dataset_range_for_active_capability();++ QString current_symbol_or_default() const;+ float spot_for(const QString& sym) const;+ const std::vector<std::vector<float>>* active_z_grid() const;// Control bar widgets (kept for dynamic rebuild)QWidget* category_bar_ = nullptr;QWidget* surface_bar_ = nullptr;- QComboBox* symbol_combo_ = nullptr;QPushButton* btn_3d_ = nullptr;QPushButton* btn_table_ = nullptr;+ QPushButton* btn_line_ = nullptr;// Main panels- SurfaceDatabentoPanel* databento_panel_ = nullptr;- SurfaceMetricsPanel* metrics_panel_ = nullptr;+ SurfaceControlPanel* control_panel_ = nullptr;+ SurfaceDataInspector* data_inspector_ = nullptr;Surface3DWidget* surface_3d_ = nullptr;SurfaceTableWidget* surface_table_ = nullptr;+ SurfaceLineWidget* surface_line_ = nullptr;QStackedWidget* view_stack_ = nullptr;// Stateint active_category_ = 0;ChartType active_chart_ = ChartType::Volatility;- bool show_table_ = false;-- // Equity symbol list- static constexpr const char* VOL_SYMBOLS[] = {"SPY", "QQQ", "IWM", "AAPL", "TSLA", "NVDA", "AMZN"};- static constexpr float VOL_SPOTS[] = {450, 380, 200, 175, 250, 120, 180};- static constexpr int N_SYMBOLS = 7;- int selected_symbol_ = 0;-- // Correlation assets- std::vector<std::string> corr_assets_ = {"SPY", "QQQ", "IWM", "DIA", "GLD", "TLT", "IEF", "HYG"};+ ViewMode view_mode_ = ViewMode::Surface3D;// ---- Data for all 35 surfaces ----VolatilitySurfaceData vol_data_;@@ -138,6 +151,10 @@ class SurfaceAnalyticsScreen : public QWidget,// Symbol group link — SymbolGroup::None when unlinked.fincept::SymbolGroup link_group_ = fincept::SymbolGroup::None;+ // Spot cache, populated from DataHub::peek("market:quote:<sym>") on demand.+ // Falls back to a constant if the hub has no quote for the symbol.+ QHash<QString, float> spot_cache_;+// Category accent colors (R,G,B)static constexpr int CAT_COLORS[][3] = {{51, 153, 255}, // EQUITY DERIV — bluediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceCapabilities.h b/fincept-qt/src/screens/surface_analytics/SurfaceCapabilities.hnew file mode 100644index 000000000..c67162669--- /dev/null+++ b/fincept-qt/src/screens/surface_analytics/SurfaceCapabilities.h@@ -0,0 +1,187 @@+#pragma once+// Surface Analytics — capability matrix.+// Source of truth mapping every ChartType to: Databento support tier,+// dataset/schema/symbology lineage, and the set of input controls the surface needs.+//+// The control panel reads this to decide which sections to render. The data+// inspector reads it to display lineage. The screen reads it to dispatch the+// right DatabentoService method. No hardcoded knowledge anywhere else.++#include "SurfaceTypes.h"++#include <array>++namespace fincept::surface {++enum class SurfaceTier {+ LIVE, // Direct Databento fetch+ COMPUTED, // Python-derived from a Databento input+ EQUITIES, // Equities OHLCV-driven+ DEMO, // No Databento source — synthetic data+};++inline const char* tier_name(SurfaceTier t) {+ switch (t) {+ case SurfaceTier::LIVE:+ return "LIVE";+ case SurfaceTier::COMPUTED:+ return "COMPUTED";+ case SurfaceTier::EQUITIES:+ return "EQUITIES";+ case SurfaceTier::DEMO:+ return "DEMO";+ }+ return "UNKNOWN";+}++// View modes a surface can be rendered in. The capability declares which apply.+enum class ViewMode { Surface3D, Table, Line };++struct SurfaceCapability {+ ChartType type;+ SurfaceTier tier;+ const char* dataset; // e.g. "OPRA.PILLAR" — empty for DEMO+ const char* schema; // e.g. "cbbo-1s" — empty for DEMO+ const char* symbology; // e.g. "parent" — what stype_in resolves to+ const char* description; // human-readable lineage line+ bool needs_underlying;+ bool needs_date_range;+ bool needs_strike_window;+ bool needs_expiry_filter;+ bool needs_correlation_basket;+ bool supports_3d;+ bool supports_table;+ bool supports_line;+};++// 35 entries — must remain in 1:1 correspondence with ChartType.+inline constexpr std::array<SurfaceCapability, 35> SURFACE_CAPABILITIES = {{+ // ── Equity Derivatives ─────────────────────────────────────────────────+ {ChartType::Volatility, SurfaceTier::COMPUTED, "OPRA.PILLAR", "definition+cbbo-1s", "parent",+ "OPRA options definitions joined to CBBO snapshot, BS-implied vol",+ true, true, true, true, false, true, true, false},+ {ChartType::DeltaSurface, SurfaceTier::COMPUTED, "OPRA.PILLAR", "definition+cbbo-1s", "parent",+ "Black-Scholes delta from CBBO mid",+ true, true, true, true, false, true, true, false},+ {ChartType::GammaSurface, SurfaceTier::COMPUTED, "OPRA.PILLAR", "definition+cbbo-1s", "parent",+ "Black-Scholes gamma from CBBO mid",+ true, true, true, true, false, true, true, false},+ {ChartType::VegaSurface, SurfaceTier::COMPUTED, "OPRA.PILLAR", "definition+cbbo-1s", "parent",+ "Black-Scholes vega from CBBO mid",+ true, true, true, true, false, true, true, false},+ {ChartType::ThetaSurface, SurfaceTier::COMPUTED, "OPRA.PILLAR", "definition+cbbo-1s", "parent",+ "Black-Scholes theta from CBBO mid",+ true, true, true, true, false, true, true, false},+ {ChartType::SkewSurface, SurfaceTier::COMPUTED, "OPRA.PILLAR", "definition+cbbo-1s", "parent",+ "IV skew across delta buckets and tenors",+ true, true, true, true, false, true, true, false},+ {ChartType::LocalVolSurface, SurfaceTier::COMPUTED, "OPRA.PILLAR", "definition+cbbo-1s", "parent",+ "Dupire local vol from BS implied vol surface",+ true, true, true, true, false, true, true, false},+ // ── Fixed Income (DEMO) ─────────────────────────────────────────────────+ {ChartType::YieldCurve, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, true},+ {ChartType::SwaptionVol, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, false},+ {ChartType::CapFloorVol, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, false},+ {ChartType::BondSpread, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, false},+ {ChartType::OISBasis, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, false},+ {ChartType::RealYield, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, false},+ {ChartType::ForwardRate, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, false},+ // ── FX (DEMO) ───────────────────────────────────────────────────────────+ {ChartType::FXVol, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, false},+ {ChartType::FXForwardPoints, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, true},+ {ChartType::CrossCurrencyBasis, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, false},+ // ── Credit (DEMO) ───────────────────────────────────────────────────────+ {ChartType::CDSSpread, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, false},+ {ChartType::CreditTransition, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, false},+ {ChartType::RecoveryRate, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, false},+ // ── Commodities ─────────────────────────────────────────────────────────+ {ChartType::CommodityForward, SurfaceTier::LIVE, "GLBX.MDP3", "definition+ohlcv-1d", "parent",+ "CME futures definitions and daily settlements",+ true, true, false, false, false, true, true, true},+ {ChartType::CommodityVol, SurfaceTier::COMPUTED, "GLBX.MDP3", "definition+ohlcv-1d", "parent",+ "Daily realised vol from futures settlements",+ true, true, false, false, false, true, true, false},+ {ChartType::CrackSpread, SurfaceTier::COMPUTED, "GLBX.MDP3", "ohlcv-1d", "parent",+ "Crack/crush spreads computed from related futures",+ true, true, false, false, false, true, true, true},+ {ChartType::ContangoBackwardation, SurfaceTier::LIVE, "GLBX.MDP3", "definition+ohlcv-1d", "parent",+ "Term-structure shape from daily settlement curve",+ true, true, false, false, false, true, true, true},+ // ── Risk & Portfolio ────────────────────────────────────────────────────+ {ChartType::Correlation, SurfaceTier::EQUITIES, "EQUS.MINI", "ohlcv-1d", "raw_symbol",+ "Pairwise correlation from equities daily returns",+ false, true, false, false, true, true, true, false},+ {ChartType::PCA, SurfaceTier::EQUITIES, "EQUS.MINI", "ohlcv-1d", "raw_symbol",+ "Principal components of basket returns",+ false, true, false, false, true, true, true, false},+ {ChartType::VaR, SurfaceTier::EQUITIES, "EQUS.MINI", "ohlcv-1d", "raw_symbol",+ "Value-at-Risk by confidence and horizon",+ false, true, false, false, true, true, true, false},+ {ChartType::StressTestPnL, SurfaceTier::EQUITIES, "EQUS.MINI", "ohlcv-1d", "raw_symbol",+ "Scenario PnL from user-defined shock vectors",+ false, true, false, false, true, true, true, false},+ {ChartType::FactorExposure, SurfaceTier::EQUITIES, "EQUS.MINI", "ohlcv-1d", "raw_symbol",+ "Factor loadings via OLS on basket returns",+ false, true, false, false, true, true, true, false},+ {ChartType::LiquidityHeatmap, SurfaceTier::COMPUTED, "OPRA.PILLAR", "cbbo-1s+statistics", "parent",+ "Open interest / volume across strike×expiry",+ true, true, true, true, false, true, true, false},+ {ChartType::Drawdown, SurfaceTier::EQUITIES, "EQUS.MINI", "ohlcv-1d", "raw_symbol",+ "Rolling drawdown across windows",+ false, true, false, false, true, true, true, false},+ {ChartType::BetaSurface, SurfaceTier::EQUITIES, "EQUS.MINI", "ohlcv-1d", "raw_symbol",+ "Rolling beta vs SPY across horizons",+ false, true, false, false, true, true, true, false},+ {ChartType::ImpliedDividend, SurfaceTier::COMPUTED, "OPRA.PILLAR", "definition+cbbo-1s", "parent",+ "Implied dividend yield from put-call parity",+ true, true, true, true, false, true, true, false},+ // ── Macro (DEMO) ────────────────────────────────────────────────────────+ {ChartType::InflationExpectations, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, true},+ {ChartType::MonetaryPolicyPath, SurfaceTier::DEMO, "", "", "",+ "No Databento source — synthetic data",+ false, false, false, false, false, true, true, true},+}};++inline const SurfaceCapability& capability_for(ChartType t) {+ for (const auto& cap : SURFACE_CAPABILITIES) {+ if (cap.type == t)+ return cap;+ }+ // Cannot happen — every ChartType is in the table. Fall back to first entry.+ return SURFACE_CAPABILITIES[0];+}++inline bool is_live(ChartType t) {+ auto tier = capability_for(t).tier;+ return tier != SurfaceTier::DEMO;+}++} // namespace fincept::surfacediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.cppnew file mode 100644index 000000000..ee3f69d1f--- /dev/null+++ b/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.cpp@@ -0,0 +1,790 @@+#include "SurfaceControlPanel.h"++#include "SurfaceDefaults.h"+#include "services/databento/DatabentoService.h"+#include "ui/theme/Theme.h"++#include <QComboBox>+#include <QCompleter>+#include <QDateEdit>+#include <QFrame>+#include <QGroupBox>+#include <QHBoxLayout>+#include <QLabel>+#include <QLineEdit>+#include <QListWidget>+#include <QPointer>+#include <QPushButton>+#include <QScrollArea>+#include <QSpinBox>+#include <QStringListModel>+#include <QTimer>+#include <QToolButton>+#include <QVBoxLayout>++#include <algorithm>+#include <cmath>++namespace fincept::surface {++using namespace fincept::ui;++namespace {++QString section_title_qss() {+ return QString("QGroupBox { background:%1; border:1px solid %2; border-radius:3px; "+ "margin-top:10px; padding:10px 8px 8px 8px; color:%3; font-size:9px; "+ "font-weight:bold; }"+ "QGroupBox::title { subcontrol-origin:margin; subcontrol-position:top left; "+ "left:10px; padding:0 4px; color:%4; }")+ .arg(colors::BG_SURFACE())+ .arg(colors::BORDER_DIM())+ .arg(colors::TEXT_PRIMARY())+ .arg(colors::TEXT_SECONDARY());+}++QString line_edit_qss() {+ return QString("QLineEdit { background:%1; color:%2; border:1px solid %3; "+ "padding:4px 6px; font-size:10px; border-radius:2px; }"+ "QLineEdit:focus { border-color:%4; }")+ .arg(colors::BG_HOVER())+ .arg(colors::TEXT_PRIMARY())+ .arg(colors::BORDER_MED())+ .arg(colors::INFO());+}++QString combo_qss() {+ return QString("QComboBox { background:%1; color:%2; border:1px solid %3; "+ "padding:3px 6px; font-size:10px; border-radius:2px; }"+ "QComboBox::drop-down { border:none; width:18px; }"+ "QComboBox QAbstractItemView { background:%1; color:%2; "+ "selection-background-color:%4; }")+ .arg(colors::BG_HOVER())+ .arg(colors::TEXT_PRIMARY())+ .arg(colors::BORDER_MED())+ .arg(colors::BG_RAISED());+}++QString small_btn_qss() {+ return QString("QToolButton, QPushButton { background:%1; color:%2; border:1px solid %3; "+ "padding:3px 8px; font-size:9px; border-radius:2px; }"+ "QToolButton:hover, QPushButton:hover { background:%3; color:%4; }"+ "QPushButton:disabled { background:%1; color:%5; border-color:%1; }")+ .arg(colors::BG_RAISED())+ .arg(colors::TEXT_SECONDARY())+ .arg(colors::BORDER_MED())+ .arg(colors::TEXT_PRIMARY())+ .arg(colors::TEXT_DIM());+}++QString fetch_btn_qss(bool enabled) {+ if (!enabled) {+ return QString("QPushButton { background:%1; color:%2; border:1px solid %3; "+ "padding:8px 12px; font-size:10px; font-weight:bold; border-radius:2px; }")+ .arg(colors::BG_HOVER())+ .arg(colors::TEXT_DIM())+ .arg(colors::BORDER_DIM());+ }+ return QString("QPushButton { background:rgba(31,77,153,255); color:%1; "+ "border:1px solid rgba(64,140,255,140); padding:8px 12px; "+ "font-size:10px; font-weight:bold; border-radius:2px; }"+ "QPushButton:hover { background:rgba(46,102,191,255); }")+ .arg(colors::INFO());+}++QColor tier_color(SurfaceTier t) {+ switch (t) {+ case SurfaceTier::LIVE:+ return QColor(63, 185, 80);+ case SurfaceTier::COMPUTED:+ return QColor(88, 166, 255);+ case SurfaceTier::EQUITIES:+ return QColor(217, 164, 6);+ case SurfaceTier::DEMO:+ return QColor(140, 140, 140);+ }+ return QColor(140, 140, 140);+}++void set_metric(QLabel* lbl, const QString& v) {+ if (lbl)+ lbl->setText(v);+}++} // anonymous namespace++SurfaceControlPanel::SurfaceControlPanel(QWidget* parent) : QWidget(parent) {+ // Databento publishes most schemas with a multi-hour lag, so "today" is+ // almost always after the dataset's available end. Default end to+ // *yesterday*; the screen refines via metadata.get_dataset_range when the+ // active capability has a known dataset.+ QDate yesterday = QDate::currentDate().addDays(-1);+ state_.start_date = yesterday.addDays(-defaults::LOOKBACK_DAYS);+ state_.end_date = yesterday;+ state_.strike_window_pct = defaults::STRIKE_WINDOW_PCT;+ state_.dte_min = defaults::DTE_MIN;+ state_.dte_max = defaults::DTE_MAX;+ for (auto* s : defaults::RISK_BASKET)+ state_.basket << QString::fromUtf8(s);+ setup_ui();+ apply_capability_visibility();+}++void SurfaceControlPanel::setup_ui() {+ setStyleSheet(QString("background:%1; color:%2;")+ .arg(colors::BG_BASE())+ .arg(colors::TEXT_PRIMARY()));+ setMinimumWidth(300);+ setMaximumWidth(360);++ auto* outer = new QVBoxLayout(this);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(0);++ // ── Header ─────────────────────────────────────────────────────────────+ auto* header = new QLabel("CONTROL PANEL", this);+ header->setStyleSheet(QString("background:%1; color:%2; font-size:10px; font-weight:bold; "+ "padding:8px 10px; border-bottom:1px solid %3;")+ .arg(colors::BG_SURFACE())+ .arg(colors::TEXT_PRIMARY())+ .arg(colors::BORDER_DIM()));+ outer->addWidget(header);++ // ── Provider status strip (one row per provider; just Databento for now) ─+ providers_box_ = new QWidget(this);+ providers_box_->setStyleSheet(QString("background:%1; border-bottom:1px solid %2;")+ .arg(colors::BG_SURFACE())+ .arg(colors::BORDER_DIM()));+ auto* prov_layout = new QVBoxLayout(providers_box_);+ prov_layout->setContentsMargins(8, 6, 8, 6);+ prov_layout->setSpacing(3);++ auto* prov_title = new QLabel("DATA PROVIDERS", providers_box_);+ prov_title->setStyleSheet(+ QString("color:%1; font-size:9px; font-weight:bold; letter-spacing:0.5px;")+ .arg(colors::TEXT_DIM()));+ prov_layout->addWidget(prov_title);++ auto add_provider_row = [&](const QString& key, const QString& label) {+ auto* row = new QHBoxLayout();+ row->setSpacing(5);+ auto* dot = new QLabel("●", providers_box_);+ dot->setStyleSheet(QString("color:%1; font-size:11px;").arg(colors::TEXT_DIM()));+ dot->setFixedWidth(10);+ row->addWidget(dot);+ auto* name_lbl = new QLabel(label, providers_box_);+ name_lbl->setStyleSheet(QString("color:%1; font-size:10px; font-family:Consolas;")+ .arg(colors::TEXT_PRIMARY()));+ name_lbl->setMinimumWidth(80);+ row->addWidget(name_lbl);+ auto* state_lbl = new QLabel("not configured", providers_box_);+ state_lbl->setStyleSheet(QString("color:%1; font-size:9px;").arg(colors::TEXT_DIM()));+ row->addWidget(state_lbl, 1);+ auto* detail_lbl = new QLabel("", providers_box_);+ detail_lbl->setStyleSheet(QString("color:%1; font-size:9px; font-family:Consolas;")+ .arg(colors::TEXT_DIM()));+ row->addWidget(detail_lbl);+ prov_layout->addLayout(row);+ provider_dot_[key] = dot;+ provider_state_[key] = state_lbl;+ provider_detail_[key] = detail_lbl;+ };+ add_provider_row("databento", "Databento");+ // Future: add_provider_row("polygon", "Polygon");+ // Future: add_provider_row("tradier", "Tradier");++ outer->addWidget(providers_box_);++ // ── Scroll body ────────────────────────────────────────────────────────+ auto* scroll = new QScrollArea(this);+ scroll->setWidgetResizable(true);+ scroll->setFrameShape(QFrame::NoFrame);+ scroll->setStyleSheet(QString("background:%1;").arg(colors::BG_BASE()));+ auto* body = new QWidget(scroll);+ auto* body_layout = new QVBoxLayout(body);+ body_layout->setContentsMargins(8, 8, 8, 8);+ body_layout->setSpacing(8);++ body_layout->addWidget((asset_box_ = build_asset_section()));+ body_layout->addWidget((dates_box_ = build_dates_section()));+ body_layout->addWidget((options_box_ = build_options_section()));+ body_layout->addWidget((basket_box_ = build_basket_section()));+ body_layout->addWidget((metrics_box_ = build_metrics_section()));+ body_layout->addWidget((lineage_box_ = build_lineage_section()));+ body_layout->addStretch();++ scroll->setWidget(body);+ outer->addWidget(scroll, 1);++ // ── Footer (sticky) — FETCH ────────────────────────────────────────────+ auto* footer = new QWidget(this);+ footer->setStyleSheet(QString("background:%1; border-top:1px solid %2;")+ .arg(colors::BG_SURFACE())+ .arg(colors::BORDER_DIM()));+ auto* footer_layout = new QVBoxLayout(footer);+ footer_layout->setContentsMargins(8, 8, 8, 8);+ fetch_btn_ = new QPushButton("FETCH", footer);+ fetch_btn_->setStyleSheet(fetch_btn_qss(true));+ fetch_btn_->setMinimumHeight(34);+ connect(fetch_btn_, &QPushButton::clicked, this, &SurfaceControlPanel::on_fetch_clicked);+ footer_layout->addWidget(fetch_btn_);+ outer->addWidget(footer);++ prefill_datasets();+}++QGroupBox* SurfaceControlPanel::build_asset_section() {+ auto* gb = new QGroupBox("ASSET", this);+ gb->setStyleSheet(section_title_qss());+ auto* l = new QVBoxLayout(gb);+ l->setContentsMargins(8, 12, 8, 8);+ l->setSpacing(6);++ symbol_edit_ = new QLineEdit(gb);+ symbol_edit_->setPlaceholderText("Underlying / parent symbol");+ symbol_edit_->setText(state_.symbol);+ symbol_edit_->setStyleSheet(line_edit_qss());+ connect(symbol_edit_, &QLineEdit::editingFinished, this, &SurfaceControlPanel::on_symbol_edited);+ connect(symbol_edit_, &QLineEdit::textEdited, this, &SurfaceControlPanel::on_symbol_text_changed);+ l->addWidget(symbol_edit_);++ // ── Autocomplete model + completer (populated by Databento symbol_search) ─+ symbol_completer_model_ = new QStringListModel(this);+ symbol_completer_ = new QCompleter(symbol_completer_model_, this);+ symbol_completer_->setCaseSensitivity(Qt::CaseInsensitive);+ symbol_completer_->setFilterMode(Qt::MatchContains);+ symbol_completer_->setCompletionMode(QCompleter::PopupCompletion);+ symbol_completer_->setMaxVisibleItems(10);+ symbol_edit_->setCompleter(symbol_completer_);++ // 300 ms debounce — avoids hammering the Databento API on every keypress.+ symbol_search_timer_ = new QTimer(this);+ symbol_search_timer_->setSingleShot(true);+ symbol_search_timer_->setInterval(300);+ connect(symbol_search_timer_, &QTimer::timeout, this,+ &SurfaceControlPanel::on_search_debounce_fired);++ auto* row = new QHBoxLayout();+ row->setSpacing(6);+ auto* ds_lbl = new QLabel("Dataset:", gb);+ ds_lbl->setStyleSheet(QString("color:%1; font-size:9px;").arg(colors::TEXT_SECONDARY()));+ row->addWidget(ds_lbl);+ dataset_combo_ = new QComboBox(gb);+ dataset_combo_->setStyleSheet(combo_qss());+ connect(dataset_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,+ &SurfaceControlPanel::on_dataset_changed);+ row->addWidget(dataset_combo_, 1);+ l->addLayout(row);++ spot_label_ = new QLabel("Spot: —", gb);+ spot_label_->setStyleSheet(QString("color:%1; font-size:9px;").arg(colors::TEXT_DIM()));+ l->addWidget(spot_label_);++ tier_badge_ = new QLabel("DEMO", gb);+ tier_badge_->setAlignment(Qt::AlignCenter);+ tier_badge_->setStyleSheet(+ QString("background:%1; color:#000; font-size:9px; font-weight:bold; "+ "padding:2px 6px; border-radius:2px; max-width:80px;")+ .arg(colors::TEXT_DIM()));+ l->addWidget(tier_badge_, 0, Qt::AlignLeft);++ return gb;+}++QGroupBox* SurfaceControlPanel::build_dates_section() {+ auto* gb = new QGroupBox("DATE RANGE", this);+ gb->setStyleSheet(section_title_qss());+ auto* l = new QVBoxLayout(gb);+ l->setContentsMargins(8, 12, 8, 8);+ l->setSpacing(6);++ // Default acceptable range — capped at yesterday since Databento data is+ // never published instantaneously. Widened/narrowed dynamically when the+ // screen calls apply_dataset_range() with concrete metadata.+ QDate default_min(2013, 1, 1);+ QDate default_max = QDate::currentDate().addDays(-1);++ auto build_date_row = [&](const QString& title, QDateEdit*& target, const QDate& def) {+ auto* row = new QHBoxLayout();+ row->setSpacing(6);+ auto* lbl = new QLabel(title, gb);+ lbl->setStyleSheet(QString("color:%1; font-size:9px;").arg(colors::TEXT_SECONDARY()));+ lbl->setMinimumWidth(40);+ row->addWidget(lbl);+ target = new QDateEdit(def, gb);+ target->setCalendarPopup(true);+ target->setDisplayFormat("yyyy-MM-dd");+ target->setMinimumDate(default_min);+ target->setMaximumDate(default_max);+ target->setStyleSheet(combo_qss());+ connect(target, &QDateEdit::dateChanged, this, &SurfaceControlPanel::on_dates_changed);+ row->addWidget(target, 1);+ l->addLayout(row);+ };+ build_date_row("Start:", start_edit_, state_.start_date);+ build_date_row("End:", end_edit_, state_.end_date);++ // Lookback presets+ auto* presets = new QHBoxLayout();+ presets->setSpacing(4);+ auto add_preset = [&](const QString& text, int days, QToolButton*& target) {+ target = new QToolButton(gb);+ target->setText(text);+ target->setStyleSheet(small_btn_qss());+ connect(target, &QToolButton::clicked, this, [this, days]() { on_lookback_preset(days); });+ presets->addWidget(target);+ };+ add_preset("1D", 1, lb_1d_);+ add_preset("5D", 5, lb_5d_);+ add_preset("1M", 30, lb_1m_);+ add_preset("3M", 90, lb_3m_);+ add_preset("1Y", 365, lb_1y_);+ presets->addStretch();+ l->addLayout(presets);++ return gb;+}++QGroupBox* SurfaceControlPanel::build_options_section() {+ auto* gb = new QGroupBox("OPTION FILTERS", this);+ gb->setStyleSheet(section_title_qss());+ auto* l = new QVBoxLayout(gb);+ l->setContentsMargins(8, 12, 8, 8);+ l->setSpacing(6);++ auto build_spin_row = [&](const QString& title, int min_v, int max_v, int initial,+ QSpinBox*& target, const QString& suffix = QString()) {+ auto* row = new QHBoxLayout();+ row->setSpacing(6);+ auto* lbl = new QLabel(title, gb);+ lbl->setStyleSheet(QString("color:%1; font-size:9px;").arg(colors::TEXT_SECONDARY()));+ lbl->setMinimumWidth(110);+ row->addWidget(lbl);+ target = new QSpinBox(gb);+ target->setRange(min_v, max_v);+ target->setValue(initial);+ if (!suffix.isEmpty())+ target->setSuffix(suffix);+ target->setStyleSheet(combo_qss());+ row->addWidget(target, 1);+ l->addLayout(row);+ };++ build_spin_row("Strike window:", 1, 100, state_.strike_window_pct, strike_window_spin_, "%");+ connect(strike_window_spin_, QOverload<int>::of(&QSpinBox::valueChanged), this,+ &SurfaceControlPanel::on_strike_window_changed);++ build_spin_row("DTE min (days):", 0, 3650, state_.dte_min, dte_min_spin_);+ build_spin_row("DTE max (days):", 1, 3650, state_.dte_max, dte_max_spin_);+ connect(dte_min_spin_, QOverload<int>::of(&QSpinBox::valueChanged), this, &SurfaceControlPanel::on_dte_changed);+ connect(dte_max_spin_, QOverload<int>::of(&QSpinBox::valueChanged), this, &SurfaceControlPanel::on_dte_changed);++ auto* iv_row = new QHBoxLayout();+ iv_row->setSpacing(6);+ auto* iv_lbl = new QLabel("IV method:", gb);+ iv_lbl->setStyleSheet(QString("color:%1; font-size:9px;").arg(colors::TEXT_SECONDARY()));+ iv_lbl->setMinimumWidth(110);+ iv_row->addWidget(iv_lbl);+ iv_method_combo_ = new QComboBox(gb);+ iv_method_combo_->addItems({"Brent", "Bisection", "Newton-Raphson"});+ iv_method_combo_->setStyleSheet(combo_qss());+ connect(iv_method_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,+ &SurfaceControlPanel::on_iv_method_changed);+ iv_row->addWidget(iv_method_combo_, 1);+ l->addLayout(iv_row);++ return gb;+}++QGroupBox* SurfaceControlPanel::build_basket_section() {+ auto* gb = new QGroupBox("BASKET", this);+ gb->setStyleSheet(section_title_qss());+ auto* l = new QVBoxLayout(gb);+ l->setContentsMargins(8, 12, 8, 8);+ l->setSpacing(6);++ auto* input_row = new QHBoxLayout();+ input_row->setSpacing(4);+ basket_input_ = new QLineEdit(gb);+ basket_input_->setPlaceholderText("Add ticker");+ basket_input_->setStyleSheet(line_edit_qss());+ input_row->addWidget(basket_input_, 1);+ basket_add_btn_ = new QPushButton("+", gb);+ basket_add_btn_->setStyleSheet(small_btn_qss());+ basket_add_btn_->setFixedWidth(26);+ connect(basket_add_btn_, &QPushButton::clicked, this, &SurfaceControlPanel::on_basket_add);+ connect(basket_input_, &QLineEdit::returnPressed, this, &SurfaceControlPanel::on_basket_add);+ input_row->addWidget(basket_add_btn_);+ basket_remove_btn_ = new QPushButton("–", gb);+ basket_remove_btn_->setStyleSheet(small_btn_qss());+ basket_remove_btn_->setFixedWidth(26);+ connect(basket_remove_btn_, &QPushButton::clicked, this, &SurfaceControlPanel::on_basket_remove);+ input_row->addWidget(basket_remove_btn_);+ l->addLayout(input_row);++ basket_list_ = new QListWidget(gb);+ basket_list_->setStyleSheet(QString("QListWidget { background:%1; color:%2; "+ "border:1px solid %3; font-size:10px; }"+ "QListWidget::item:selected { background:%4; color:%5; }")+ .arg(colors::BG_HOVER())+ .arg(colors::TEXT_PRIMARY())+ .arg(colors::BORDER_MED())+ .arg(colors::BG_RAISED())+ .arg(colors::TEXT_PRIMARY()));+ basket_list_->setMinimumHeight(110);+ for (const QString& t : state_.basket)+ basket_list_->addItem(t);+ l->addWidget(basket_list_);++ return gb;+}++QGroupBox* SurfaceControlPanel::build_metrics_section() {+ auto* gb = new QGroupBox("METRICS", this);+ gb->setStyleSheet(section_title_qss());+ auto* l = new QVBoxLayout(gb);+ l->setContentsMargins(8, 12, 8, 8);+ l->setSpacing(2);++ auto add_row = [&](const QString& label, QLabel*& target) {+ auto* row = new QHBoxLayout();+ row->setSpacing(6);+ auto* lbl = new QLabel(label, gb);+ lbl->setStyleSheet(QString("color:%1; font-size:9px; font-family:Consolas;")+ .arg(colors::TEXT_SECONDARY()));+ lbl->setMinimumWidth(80);+ row->addWidget(lbl);+ target = new QLabel("—", gb);+ target->setStyleSheet(QString("color:%1; font-size:10px; font-family:Consolas; font-weight:bold;")+ .arg(colors::TEXT_PRIMARY()));+ row->addWidget(target, 1, Qt::AlignRight);+ l->addLayout(row);+ };++ add_row("count", metrics_count_);+ add_row("min", metrics_min_);+ add_row("max", metrics_max_);+ add_row("mean", metrics_mean_);+ add_row("median", metrics_median_);+ add_row("std", metrics_std_);+ add_row("skew", metrics_skew_);+ add_row("kurt", metrics_kurt_);++ return gb;+}++QGroupBox* SurfaceControlPanel::build_lineage_section() {+ auto* gb = new QGroupBox("LINEAGE", this);+ gb->setStyleSheet(section_title_qss());+ auto* l = new QVBoxLayout(gb);+ l->setContentsMargins(8, 12, 8, 8);+ lineage_label_ = new QLabel("—", gb);+ lineage_label_->setWordWrap(true);+ lineage_label_->setStyleSheet(+ QString("color:%1; font-size:9px; font-family:Consolas;").arg(colors::TEXT_SECONDARY()));+ l->addWidget(lineage_label_);+ return gb;+}++void SurfaceControlPanel::prefill_datasets() {+ // Static seed list — the screen calls list_datasets() asynchronously and+ // updates this combo when results arrive (see SurfaceAnalyticsScreen).+ QStringList seed = {"OPRA.PILLAR", "GLBX.MDP3", "EQUS.MINI", "XNAS.ITCH", "XNYS.PILLAR",+ "IFEU.IMPACT", "IFUS.IMPACT"};+ dataset_combo_->blockSignals(true);+ dataset_combo_->clear();+ for (const QString& s : seed)+ dataset_combo_->addItem(s);+ dataset_combo_->blockSignals(false);+}++void SurfaceControlPanel::set_capability(ChartType type) {+ active_type_ = type;+ const auto& cap = capability_for(type);++ // Tier badge+ QColor bg = tier_color(cap.tier);+ tier_badge_->setText(tier_name(cap.tier));+ tier_badge_->setStyleSheet(+ QString("background:%1; color:#000; font-size:9px; font-weight:bold; "+ "padding:2px 6px; border-radius:2px; max-width:80px;")+ .arg(bg.name()));++ // Default dataset for this surface+ if (!QString(cap.dataset).isEmpty()) {+ int idx = dataset_combo_->findText(cap.dataset);+ if (idx < 0) {+ dataset_combo_->addItem(cap.dataset);+ idx = dataset_combo_->findText(cap.dataset);+ }+ dataset_combo_->blockSignals(true);+ dataset_combo_->setCurrentIndex(idx);+ dataset_combo_->blockSignals(false);+ state_.dataset = cap.dataset;+ }++ apply_capability_visibility();++ // FETCH button enable state+ bool can_fetch = cap.tier != SurfaceTier::DEMO;+ fetch_btn_->setEnabled(can_fetch);+ fetch_btn_->setStyleSheet(fetch_btn_qss(can_fetch));+ fetch_btn_->setToolTip(can_fetch ? QString()+ : "No Databento source for this surface — "+ "viewing synthetic data");++ update_lineage(QString::fromUtf8(cap.description));+}++void SurfaceControlPanel::apply_capability_visibility() {+ const auto& cap = capability_for(active_type_);+ asset_box_->setVisible(cap.needs_underlying || cap.needs_correlation_basket ||+ cap.tier != SurfaceTier::DEMO);+ dates_box_->setVisible(cap.needs_date_range);+ options_box_->setVisible(cap.needs_strike_window || cap.needs_expiry_filter);+ basket_box_->setVisible(cap.needs_correlation_basket);+}++void SurfaceControlPanel::update_metrics(const std::vector<std::vector<float>>& z, const QString& units) {+ std::vector<float> flat;+ flat.reserve(64);+ for (const auto& row : z)+ for (float v : row)+ if (std::isfinite(v))+ flat.push_back(v);+ if (flat.empty()) {+ for (auto* l : {metrics_count_, metrics_min_, metrics_max_, metrics_mean_,+ metrics_median_, metrics_std_, metrics_skew_, metrics_kurt_})+ set_metric(l, "—");+ return;+ }+ std::sort(flat.begin(), flat.end());+ double n = (double)flat.size();+ double sum = 0;+ for (float v : flat)+ sum += v;+ double mean = sum / n;+ double var = 0, m3 = 0, m4 = 0;+ for (float v : flat) {+ double d = v - mean;+ var += d * d;+ m3 += d * d * d;+ m4 += d * d * d * d;+ }+ var /= n;+ double std_dev = std::sqrt(var);+ double skew = (std_dev > 0) ? (m3 / n) / std::pow(std_dev, 3) : 0.0;+ double kurt = (std_dev > 0) ? (m4 / n) / std::pow(std_dev, 4) - 3.0 : 0.0;+ double median = flat[flat.size() / 2];++ QString suffix = units.isEmpty() ? QString() : QStringLiteral(" ") + units;+ set_metric(metrics_count_, QString::number((qint64)n));+ set_metric(metrics_min_, QString::number(flat.front(), 'f', 4) + suffix);+ set_metric(metrics_max_, QString::number(flat.back(), 'f', 4) + suffix);+ set_metric(metrics_mean_, QString::number(mean, 'f', 4) + suffix);+ set_metric(metrics_median_, QString::number(median, 'f', 4) + suffix);+ set_metric(metrics_std_, QString::number(std_dev, 'f', 4) + suffix);+ set_metric(metrics_skew_, QString::number(skew, 'f', 3));+ set_metric(metrics_kurt_, QString::number(kurt, 'f', 3));+}++void SurfaceControlPanel::update_lineage(const QString& line) {+ if (lineage_label_)+ lineage_label_->setText(line.isEmpty() ? "—" : line);+}++void SurfaceControlPanel::apply_state(const SurfaceControlsState& s) {+ state_ = s;+ if (symbol_edit_)+ symbol_edit_->setText(s.symbol);+ if (start_edit_ && s.start_date.isValid())+ start_edit_->setDate(s.start_date);+ if (end_edit_ && s.end_date.isValid())+ end_edit_->setDate(s.end_date);+ if (strike_window_spin_)+ strike_window_spin_->setValue(s.strike_window_pct);+ if (dte_min_spin_)+ dte_min_spin_->setValue(s.dte_min);+ if (dte_max_spin_)+ dte_max_spin_->setValue(s.dte_max);+ if (iv_method_combo_) {+ int idx = iv_method_combo_->findText(s.iv_method);+ if (idx >= 0)+ iv_method_combo_->setCurrentIndex(idx);+ }+ if (basket_list_) {+ basket_list_->clear();+ for (const QString& t : s.basket)+ basket_list_->addItem(t);+ }+}++// ── Slots ──────────────────────────────────────────────────────────────────+void SurfaceControlPanel::on_symbol_edited() {+ QString s = symbol_edit_->text().trimmed().toUpper();+ if (s == state_.symbol)+ return;+ state_.symbol = s;+ emit symbol_changed(s);+ emit controls_changed();+}++void SurfaceControlPanel::on_symbol_text_changed(const QString& text) {+ QString q = text.trimmed();+ if (q.size() < 1) {+ if (symbol_completer_model_)+ symbol_completer_model_->setStringList({});+ return;+ }+ pending_search_query_ = q;+ if (symbol_search_timer_)+ symbol_search_timer_->start();+}++void SurfaceControlPanel::on_search_debounce_fired() {+ if (pending_search_query_.isEmpty())+ return;+ QString query = pending_search_query_;+ QString dataset = dataset_combo_ ? dataset_combo_->currentText() : QString();+ QPointer<SurfaceControlPanel> self = this;+ DatabentoService::instance().search_symbols(+ query, dataset, [self, query](QStringList matches) {+ if (!self || !self->symbol_completer_model_)+ return;+ // Only apply if the query is still the freshest pending one.+ if (self->pending_search_query_ != query)+ return;+ self->symbol_completer_model_->setStringList(matches);+ if (self->symbol_completer_ && self->symbol_edit_ &&+ self->symbol_edit_->hasFocus() && !matches.isEmpty()) {+ self->symbol_completer_->complete();+ }+ });+}++void SurfaceControlPanel::on_dataset_changed() {+ state_.dataset = dataset_combo_->currentText();+ emit controls_changed();+}++void SurfaceControlPanel::on_dates_changed() {+ state_.start_date = start_edit_->date();+ state_.end_date = end_edit_->date();+ emit controls_changed();+}++void SurfaceControlPanel::on_lookback_preset(int days) {+ QDate end = QDate::currentDate();+ QDate start = end.addDays(-days);+ end_edit_->setDate(end);+ start_edit_->setDate(start);+ // dates_changed slot will fire and emit controls_changed+}++void SurfaceControlPanel::on_strike_window_changed(int v) {+ state_.strike_window_pct = v;+ emit controls_changed();+}++void SurfaceControlPanel::on_dte_changed() {+ state_.dte_min = dte_min_spin_->value();+ state_.dte_max = dte_max_spin_->value();+ if (state_.dte_max < state_.dte_min) {+ state_.dte_max = state_.dte_min;+ dte_max_spin_->blockSignals(true);+ dte_max_spin_->setValue(state_.dte_max);+ dte_max_spin_->blockSignals(false);+ }+ emit controls_changed();+}++void SurfaceControlPanel::on_iv_method_changed() {+ state_.iv_method = iv_method_combo_->currentText();+ emit controls_changed();+}++void SurfaceControlPanel::on_basket_add() {+ QString s = basket_input_->text().trimmed().toUpper();+ if (s.isEmpty())+ return;+ if (!state_.basket.contains(s)) {+ state_.basket << s;+ basket_list_->addItem(s);+ emit controls_changed();+ }+ basket_input_->clear();+}++void SurfaceControlPanel::on_basket_remove() {+ auto items = basket_list_->selectedItems();+ if (items.isEmpty())+ return;+ for (auto* it : items) {+ state_.basket.removeAll(it->text());+ delete basket_list_->takeItem(basket_list_->row(it));+ }+ emit controls_changed();+}++void SurfaceControlPanel::on_fetch_clicked() {+ emit fetch_requested();+}++void SurfaceControlPanel::apply_dataset_range(const QDate& available_start,+ const QDate& available_end) {+ if (!start_edit_ || !end_edit_)+ return;+ // Cap end at *yesterday* even if Databento says today, since intraday+ // schemas finalise hours after the close.+ QDate ui_max = available_end.isValid() ? std::min(available_end, QDate::currentDate().addDays(-1))+ : QDate::currentDate().addDays(-1);+ QDate ui_min = available_start.isValid() ? available_start : QDate(2013, 1, 1);++ start_edit_->blockSignals(true);+ end_edit_->blockSignals(true);+ start_edit_->setMinimumDate(ui_min);+ start_edit_->setMaximumDate(ui_max);+ end_edit_->setMinimumDate(ui_min);+ end_edit_->setMaximumDate(ui_max);++ // Clamp current values into the new range+ if (state_.end_date > ui_max) {+ state_.end_date = ui_max;+ end_edit_->setDate(state_.end_date);+ }+ if (state_.start_date < ui_min) {+ state_.start_date = ui_min;+ start_edit_->setDate(state_.start_date);+ }+ if (state_.start_date > ui_max) {+ state_.start_date = ui_max.addDays(-defaults::LOOKBACK_DAYS);+ start_edit_->setDate(state_.start_date);+ }+ start_edit_->blockSignals(false);+ end_edit_->blockSignals(false);+}++void SurfaceControlPanel::set_provider_status(const QString& provider_name,+ const QString& provider_state,+ const QString& detail) {+ auto* dot = provider_dot_.value(provider_name, nullptr);+ auto* lbl = provider_state_.value(provider_name, nullptr);+ auto* dt = provider_detail_.value(provider_name, nullptr);+ if (!dot || !lbl)+ return;+ QString color = colors::TEXT_DIM();+ QString text = provider_state;+ if (provider_state == "connected")+ color = colors::POSITIVE();+ else if (provider_state == "disconnected" || provider_state == "error")+ color = colors::NEGATIVE();+ else if (provider_state == "configured")+ color = QString("rgb(217,164,6)"); // amber, key set but not yet tested+ dot->setStyleSheet(QString("color:%1; font-size:11px;").arg(color));+ lbl->setText(text);+ lbl->setStyleSheet(QString("color:%1; font-size:9px;").arg(color));+ if (dt)+ dt->setText(detail);+}++} // namespace fincept::surfacediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.h b/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.hnew file mode 100644index 000000000..8b929ff68--- /dev/null+++ b/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.h@@ -0,0 +1,176 @@+#pragma once+// SurfaceControlPanel — left-side control surface for Surface Analytics.+// Replaces the old SurfaceMetricsPanel + the bottom-strip Databento panel's+// asset/parameter inputs. Reads the SurfaceCapabilities matrix to decide+// which sections to render for the active ChartType.+//+// Owns the SurfaceControlsState and emits controls_changed + fetch_requested+// for the screen to translate into DatabentoFetchParams.++#include "SurfaceCapabilities.h"+#include "SurfaceTypes.h"++#include <QDate>+#include <QHash>+#include <QString>+#include <QStringList>+#include <QWidget>++class QComboBox;+class QCompleter;+class QDateEdit;+class QGroupBox;+class QLabel;+class QLineEdit;+class QListWidget;+class QPushButton;+class QSpinBox;+class QStringListModel;+class QTimer;+class QToolButton;+class QVBoxLayout;++namespace fincept::surface {++struct SurfaceControlsState {+ QString symbol = "SPY";+ QString dataset; // empty = use capability default+ QDate start_date;+ QDate end_date;+ int strike_window_pct = 20;+ int dte_min = 7;+ int dte_max = 365;+ QString iv_method = "Brent";+ QStringList basket;+ QStringList venues;+};++class SurfaceControlPanel : public QWidget {+ Q_OBJECT+ public:+ explicit SurfaceControlPanel(QWidget* parent = nullptr);++ // Re-render sections to match the active surface's capability profile.+ // Called by the screen on every chip click.+ void set_capability(ChartType type);++ // Push min/max/mean/median/std/skew/kurt of the active surface's z matrix.+ void update_metrics(const std::vector<std::vector<float>>& z, const QString& units = "");++ // Show a one-line lineage string from the active capability + state.+ void update_lineage(const QString& line);++ SurfaceControlsState state() const { return state_; }++ void apply_state(const SurfaceControlsState& s);++ // Tighten the QDateEdits' min/max bounds (and clamp current values into+ // them) when the screen receives dataset_range metadata. Called once per+ // dataset; subsequent calls are cheap.+ void apply_dataset_range(const QDate& available_start, const QDate& available_end);++ // Update the provider status pill (header). dataset is shown alongside+ // the dot. State is one of "connected", "disconnected", "not configured".+ void set_provider_status(const QString& provider_name, const QString& state,+ const QString& detail = QString());++ signals:+ void controls_changed();+ void fetch_requested();+ void symbol_changed(const QString& symbol);++ private slots:+ void on_symbol_edited();+ void on_symbol_text_changed(const QString& text);+ void on_search_debounce_fired();+ void on_dataset_changed();+ void on_dates_changed();+ void on_lookback_preset(int days);+ void on_strike_window_changed(int v);+ void on_dte_changed();+ void on_iv_method_changed();+ void on_basket_add();+ void on_basket_remove();+ void on_fetch_clicked();++ private:+ void setup_ui();+ QGroupBox* build_asset_section();+ QGroupBox* build_dates_section();+ QGroupBox* build_options_section();+ QGroupBox* build_basket_section();+ QGroupBox* build_metrics_section();+ QGroupBox* build_lineage_section();+ void apply_capability_visibility();+ void prefill_datasets();++ // ── Sections ───────────────────────────────────────────────────────────+ QGroupBox* asset_box_ = nullptr;+ QGroupBox* dates_box_ = nullptr;+ QGroupBox* options_box_ = nullptr;+ QGroupBox* basket_box_ = nullptr;+ QGroupBox* metrics_box_ = nullptr;+ QGroupBox* lineage_box_ = nullptr;++ // ── Asset section ──────────────────────────────────────────────────────+ QLineEdit* symbol_edit_ = nullptr;+ QComboBox* dataset_combo_ = nullptr;+ QLabel* spot_label_ = nullptr;+ QLabel* tier_badge_ = nullptr;+ // Symbol search autocomplete (Databento)+ QCompleter* symbol_completer_ = nullptr;+ QStringListModel* symbol_completer_model_ = nullptr;+ QTimer* symbol_search_timer_ = nullptr;+ QString pending_search_query_;++ // ── Date range section ─────────────────────────────────────────────────+ QDateEdit* start_edit_ = nullptr;+ QDateEdit* end_edit_ = nullptr;+ // Lookback preset row buttons; clicked -> on_lookback_preset+ QToolButton* lb_1d_ = nullptr;+ QToolButton* lb_5d_ = nullptr;+ QToolButton* lb_1m_ = nullptr;+ QToolButton* lb_3m_ = nullptr;+ QToolButton* lb_1y_ = nullptr;++ // ── Option filters section ─────────────────────────────────────────────+ QSpinBox* strike_window_spin_ = nullptr;+ QSpinBox* dte_min_spin_ = nullptr;+ QSpinBox* dte_max_spin_ = nullptr;+ QComboBox* iv_method_combo_ = nullptr;++ // ── Basket section ─────────────────────────────────────────────────────+ QLineEdit* basket_input_ = nullptr;+ QListWidget* basket_list_ = nullptr;+ QPushButton* basket_add_btn_ = nullptr;+ QPushButton* basket_remove_btn_ = nullptr;++ // ── Metrics section ────────────────────────────────────────────────────+ QLabel* metrics_min_ = nullptr;+ QLabel* metrics_max_ = nullptr;+ QLabel* metrics_mean_ = nullptr;+ QLabel* metrics_median_ = nullptr;+ QLabel* metrics_std_ = nullptr;+ QLabel* metrics_skew_ = nullptr;+ QLabel* metrics_kurt_ = nullptr;+ QLabel* metrics_count_ = nullptr;++ // ── Lineage section ────────────────────────────────────────────────────+ QLabel* lineage_label_ = nullptr;++ // ── Provider status pills (top of panel) ───────────────────────────────+ // QWidget container, populated by set_provider_status(). Future providers+ // (Polygon, Tradier, FRED, etc) will append rows here without layout churn.+ QWidget* providers_box_ = nullptr;+ QHash<QString, QLabel*> provider_dot_;+ QHash<QString, QLabel*> provider_state_;+ QHash<QString, QLabel*> provider_detail_;++ // ── Footer ─────────────────────────────────────────────────────────────+ QPushButton* fetch_btn_ = nullptr;++ ChartType active_type_ = ChartType::Volatility;+ SurfaceControlsState state_;+};++} // namespace fincept::surfacediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceDataInspector.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceDataInspector.cppnew file mode 100644index 000000000..0a7a1a8d3--- /dev/null+++ b/fincept-qt/src/screens/surface_analytics/SurfaceDataInspector.cpp@@ -0,0 +1,346 @@+#include "SurfaceDataInspector.h"++#include "ui/theme/Theme.h"++#include <QAbstractItemView>+#include <QDateTime>+#include <QDialog>+#include <QFileDialog>+#include <QFrame>+#include <QHBoxLayout>+#include <QHeaderView>+#include <QLabel>+#include <QPlainTextEdit>+#include <QPushButton>+#include <QStandardItemModel>+#include <QTabBar>+#include <QTableView>+#include <QTextStream>+#include <QVBoxLayout>++namespace fincept::surface {++using namespace fincept::ui;++namespace {++QString section_header_qss() {+ return QString("background:%1; color:%2; font-size:9px; font-weight:bold; "+ "padding:4px 8px; border-bottom:1px solid %3;")+ .arg(colors::BG_SURFACE())+ .arg(colors::TEXT_SECONDARY())+ .arg(colors::BORDER_DIM());+}++QString table_qss() {+ return QString("QTableView { background:%1; color:%2; gridline-color:%3; "+ "border:none; font-size:10px; font-family:Consolas; "+ "selection-background-color:%4; selection-color:%5; }"+ "QHeaderView::section { background:%6; color:%7; padding:3px 6px; "+ "border:none; border-right:1px solid %3; border-bottom:1px solid %3; "+ "font-size:9px; font-weight:bold; }")+ .arg(colors::BG_BASE())+ .arg(colors::TEXT_PRIMARY())+ .arg(colors::BORDER_DIM())+ .arg(colors::BG_RAISED())+ .arg(colors::TEXT_PRIMARY())+ .arg(colors::BG_SURFACE())+ .arg(colors::TEXT_SECONDARY());+}++QString tab_qss() {+ return QString("QTabBar::tab { background:%1; color:%2; padding:4px 12px; "+ "border:1px solid %3; border-bottom:none; font-size:9px; }"+ "QTabBar::tab:selected { background:%4; color:%5; }")+ .arg(colors::BG_BASE())+ .arg(colors::TEXT_DIM())+ .arg(colors::BORDER_DIM())+ .arg(colors::BG_SURFACE())+ .arg(colors::TEXT_PRIMARY());+}++QString small_btn_qss() {+ return QString("QPushButton { background:%1; color:%2; border:1px solid %3; "+ "padding:3px 10px; font-size:9px; border-radius:2px; }"+ "QPushButton:hover { background:%3; color:%4; }")+ .arg(colors::BG_RAISED())+ .arg(colors::TEXT_SECONDARY())+ .arg(colors::BORDER_MED())+ .arg(colors::TEXT_PRIMARY());+}++} // namespace++SurfaceDataInspector::SurfaceDataInspector(QWidget* parent) : QWidget(parent) {+ setup_ui();+}++void SurfaceDataInspector::setup_ui() {+ setStyleSheet(QString("background:%1; color:%2;")+ .arg(colors::BG_BASE())+ .arg(colors::TEXT_PRIMARY()));+ setMinimumHeight(190);++ auto* outer = new QHBoxLayout(this);+ outer->setContentsMargins(0, 0, 0, 0);+ outer->setSpacing(0);++ // ── COLUMN 1: Raw data tabs + table ────────────────────────────────────+ auto* col1 = new QWidget(this);+ col1->setStyleSheet(QString("background:%1;").arg(colors::BG_BASE()));+ auto* col1_layout = new QVBoxLayout(col1);+ col1_layout->setContentsMargins(0, 0, 0, 0);+ col1_layout->setSpacing(0);++ auto* col1_header_row = new QHBoxLayout();+ col1_header_row->setContentsMargins(0, 0, 0, 0);+ col1_header_row->setSpacing(0);+ auto* col1_header = new QLabel("RAW DATA", col1);+ col1_header->setStyleSheet(section_header_qss());+ col1_header->setMinimumHeight(22);+ col1_header_row->addWidget(col1_header, 1);+ export_btn_ = new QPushButton("EXPORT CSV", col1);+ export_btn_->setStyleSheet(small_btn_qss());+ connect(export_btn_, &QPushButton::clicked, this, &SurfaceDataInspector::on_export_csv_clicked);+ col1_header_row->addWidget(export_btn_);+ col1_layout->addLayout(col1_header_row);++ tab_bar_ = new QTabBar(col1);+ tab_bar_->setStyleSheet(tab_qss());+ tab_bar_->setExpanding(false);+ connect(tab_bar_, &QTabBar::currentChanged, this, &SurfaceDataInspector::on_tab_changed);+ col1_layout->addWidget(tab_bar_);++ table_view_ = new QTableView(col1);+ table_model_ = new QStandardItemModel(this);+ table_view_->setModel(table_model_);+ table_view_->setStyleSheet(table_qss());+ table_view_->setAlternatingRowColors(false);+ table_view_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ table_view_->setSortingEnabled(true);+ table_view_->verticalHeader()->setVisible(false);+ table_view_->verticalHeader()->setDefaultSectionSize(18);+ col1_layout->addWidget(table_view_, 1);++ outer->addWidget(col1, 6);++ // ── COLUMN 2: Lineage ──────────────────────────────────────────────────+ auto* col2 = new QWidget(this);+ col2->setStyleSheet(QString("background:%1; border-left:1px solid %2;")+ .arg(colors::BG_BASE())+ .arg(colors::BORDER_DIM()));+ auto* col2_layout = new QVBoxLayout(col2);+ col2_layout->setContentsMargins(0, 0, 0, 0);+ col2_layout->setSpacing(0);++ auto* col2_header = new QLabel("LINEAGE", col2);+ col2_header->setStyleSheet(section_header_qss());+ col2_header->setMinimumHeight(22);+ col2_layout->addWidget(col2_header);++ auto* lin_body = new QWidget(col2);+ auto* lin_l = new QVBoxLayout(lin_body);+ lin_l->setContentsMargins(8, 8, 8, 8);+ lin_l->setSpacing(4);++ auto add_row = [&](const QString& key, QLabel*& target) {+ auto* row = new QHBoxLayout();+ row->setSpacing(6);+ auto* k = new QLabel(key, lin_body);+ k->setStyleSheet(QString("color:%1; font-size:9px; font-family:Consolas;")+ .arg(colors::TEXT_DIM()));+ k->setMinimumWidth(72);+ row->addWidget(k);+ target = new QLabel("—", lin_body);+ target->setStyleSheet(QString("color:%1; font-size:10px; font-family:Consolas;")+ .arg(colors::TEXT_PRIMARY()));+ target->setWordWrap(true);+ row->addWidget(target, 1);+ lin_l->addLayout(row);+ };+ add_row("dataset", lin_dataset_);+ add_row("schema", lin_schema_);+ add_row("symbology", lin_symbology_);+ add_row("symbols", lin_symbols_);+ add_row("range", lin_dates_);+ add_row("rows", lin_count_);+ add_row("cost", lin_cost_);+ lin_l->addStretch();+ col2_layout->addWidget(lin_body, 1);++ outer->addWidget(col2, 3);++ // ── COLUMN 3: Status / errors ──────────────────────────────────────────+ auto* col3 = new QWidget(this);+ col3->setStyleSheet(QString("background:%1; border-left:1px solid %2;")+ .arg(colors::BG_BASE())+ .arg(colors::BORDER_DIM()));+ auto* col3_layout = new QVBoxLayout(col3);+ col3_layout->setContentsMargins(0, 0, 0, 0);+ col3_layout->setSpacing(0);++ auto* col3_header = new QLabel("STATUS / ERRORS", col3);+ col3_header->setStyleSheet(section_header_qss());+ col3_header->setMinimumHeight(22);+ col3_layout->addWidget(col3_header);++ auto* status_body = new QWidget(col3);+ auto* status_l = new QVBoxLayout(status_body);+ status_l->setContentsMargins(8, 8, 8, 8);+ status_l->setSpacing(6);++ auto* dot_row = new QHBoxLayout();+ dot_row->setSpacing(6);+ status_dot_ = new QLabel("●", status_body);+ status_dot_->setStyleSheet(QString("color:%1; font-size:14px;").arg(colors::TEXT_DIM()));+ dot_row->addWidget(status_dot_);+ status_label_ = new QLabel("Idle", status_body);+ status_label_->setWordWrap(true);+ status_label_->setStyleSheet(QString("color:%1; font-size:10px;").arg(colors::TEXT_PRIMARY()));+ dot_row->addWidget(status_label_, 1);+ status_l->addLayout(dot_row);++ error_label_ = new QLabel("", status_body);+ error_label_->setWordWrap(true);+ error_label_->setStyleSheet(QString("color:%1; font-size:9px; font-family:Consolas;")+ .arg(colors::NEGATIVE()));+ status_l->addWidget(error_label_);++ view_raw_btn_ = new QPushButton("VIEW RAW RESPONSE", status_body);+ view_raw_btn_->setStyleSheet(small_btn_qss());+ connect(view_raw_btn_, &QPushButton::clicked, this, &SurfaceDataInspector::on_view_raw_clicked);+ status_l->addWidget(view_raw_btn_);+ status_l->addStretch();+ col3_layout->addWidget(status_body, 1);++ outer->addWidget(col3, 2);+}++void SurfaceDataInspector::clear() {+ snapshots_.clear();+ while (tab_bar_->count() > 0)+ tab_bar_->removeTab(0);+ table_model_->clear();+ set_lineage("", "", "", "", "", 0, 0.0);+ error_label_->setText("");+ set_status("Idle", true);+ raw_output_.clear();+}++void SurfaceDataInspector::show_table(const QString& tab_name, const QStringList& headers,+ const QVector<QStringList>& rows) {+ // Append (or replace if same name already exists) and select.+ int existing = -1;+ for (int i = 0; i < snapshots_.size(); ++i) {+ if (snapshots_[i].name == tab_name) {+ existing = i;+ break;+ }+ }+ TableSnapshot snap{tab_name, headers, rows};+ if (existing >= 0) {+ snapshots_[existing] = snap;+ tab_bar_->blockSignals(true);+ tab_bar_->setCurrentIndex(existing);+ tab_bar_->blockSignals(false);+ on_tab_changed(existing);+ } else {+ snapshots_.push_back(snap);+ tab_bar_->blockSignals(true);+ int idx = tab_bar_->addTab(tab_name);+ tab_bar_->setCurrentIndex(idx);+ tab_bar_->blockSignals(false);+ on_tab_changed(idx);+ }+}++void SurfaceDataInspector::on_tab_changed(int index) {+ if (index < 0 || index >= snapshots_.size())+ return;+ const auto& s = snapshots_[index];+ table_model_->clear();+ table_model_->setHorizontalHeaderLabels(s.headers);+ for (const auto& r : s.rows) {+ QList<QStandardItem*> items;+ for (const QString& cell : r)+ items.push_back(new QStandardItem(cell));+ table_model_->appendRow(items);+ }+ table_view_->resizeColumnsToContents();+}++void SurfaceDataInspector::set_lineage(const QString& dataset, const QString& schema,+ const QString& symbology, const QString& symbols,+ const QString& date_range, qint64 row_count,+ double cost_usd) {+ lin_dataset_->setText(dataset.isEmpty() ? "—" : dataset);+ lin_schema_->setText(schema.isEmpty() ? "—" : schema);+ lin_symbology_->setText(symbology.isEmpty() ? "—" : symbology);+ lin_symbols_->setText(symbols.isEmpty() ? "—" : symbols);+ lin_dates_->setText(date_range.isEmpty() ? "—" : date_range);+ lin_count_->setText(row_count > 0 ? QString::number(row_count) : "—");+ lin_cost_->setText(cost_usd > 0.0 ? QString("$%1").arg(cost_usd, 0, 'f', 4) : "—");+}++void SurfaceDataInspector::set_status(const QString& message, bool ok) {+ QString stamp = QDateTime::currentDateTime().toString("hh:mm:ss");+ status_label_->setText(QString("[%1] %2").arg(stamp).arg(message));+ status_dot_->setStyleSheet(QString("color:%1; font-size:14px;")+ .arg(ok ? colors::POSITIVE() : colors::NEGATIVE()));+ if (ok)+ error_label_->setText("");+}++void SurfaceDataInspector::set_error(const QString& error) {+ error_label_->setText(error);+ if (!error.isEmpty()) {+ status_dot_->setStyleSheet(QString("color:%1; font-size:14px;").arg(colors::NEGATIVE()));+ }+}++void SurfaceDataInspector::set_raw_output(const QString& raw_stdout) {+ raw_output_ = raw_stdout;+}++void SurfaceDataInspector::on_view_raw_clicked() {+ QDialog dlg(this);+ dlg.setWindowTitle("Raw Databento response");+ dlg.resize(720, 480);+ auto* lay = new QVBoxLayout(&dlg);+ auto* edit = new QPlainTextEdit(&dlg);+ edit->setReadOnly(true);+ edit->setStyleSheet(QString("background:%1; color:%2; font-family:Consolas; font-size:10px;")+ .arg(colors::BG_BASE())+ .arg(colors::TEXT_PRIMARY()));+ edit->setPlainText(raw_output_.isEmpty() ? "(no response captured yet)" : raw_output_);+ lay->addWidget(edit);+ auto* close_btn = new QPushButton("CLOSE", &dlg);+ close_btn->setStyleSheet(small_btn_qss());+ connect(close_btn, &QPushButton::clicked, &dlg, &QDialog::accept);+ lay->addWidget(close_btn, 0, Qt::AlignRight);+ dlg.exec();+}++void SurfaceDataInspector::on_export_csv_clicked() {+ if (snapshots_.isEmpty())+ return;+ int idx = tab_bar_->currentIndex();+ if (idx < 0 || idx >= snapshots_.size())+ return;+ const auto& snap = snapshots_[idx];++ QString suggested = QString("%1.csv").arg(snap.name);+ QString path = QFileDialog::getSaveFileName(this, "Export CSV", suggested,+ "CSV files (*.csv)");+ if (path.isEmpty())+ return;+ QFile f(path);+ if (!f.open(QIODevice::WriteOnly | QIODevice::Text))+ return;+ QTextStream out(&f);+ out << snap.headers.join(",") << "\n";+ for (const auto& r : snap.rows)+ out << r.join(",") << "\n";+}++} // namespace fincept::surfacediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceDataInspector.h b/fincept-qt/src/screens/surface_analytics/SurfaceDataInspector.hnew file mode 100644index 000000000..30dc74a2c--- /dev/null+++ b/fincept-qt/src/screens/surface_analytics/SurfaceDataInspector.h@@ -0,0 +1,82 @@+#pragma once+// SurfaceDataInspector — bottom strip of Surface Analytics.+// Replaces the old API-key + status SurfaceDatabentoPanel. Three columns:+//+// ┌──────────────────────────┬─────────────────┬──────────────┐+// │ RAW DATA TABLE (tabs: │ LINEAGE │ STATUS / │+// │ definition, cbbo-1s, …) │ dataset / … │ ERRORS │+// └──────────────────────────┴─────────────────┴──────────────┘++#include <QString>+#include <QStringList>+#include <QVector>+#include <QWidget>++class QHBoxLayout;+class QLabel;+class QPushButton;+class QStandardItemModel;+class QTabBar;+class QTableView;++namespace fincept::surface {++class SurfaceDataInspector : public QWidget {+ Q_OBJECT+ public:+ explicit SurfaceDataInspector(QWidget* parent = nullptr);++ // Push a tabular schema view (definition / ohlcv / statistics / ...).+ // Each name is shown as a tab. Headers seed the columns, rows seed cells.+ void show_table(const QString& tab_name, const QStringList& headers,+ const QVector<QStringList>& rows);++ // Set the lineage block (dataset / schema / symbology / symbols / dates / count / cost).+ void set_lineage(const QString& dataset, const QString& schema,+ const QString& symbology, const QString& symbols,+ const QString& date_range, qint64 row_count, double cost_usd);++ // Status / errors area+ void set_status(const QString& message, bool ok);+ void set_error(const QString& error);+ void set_raw_output(const QString& raw_stdout); // full Python stdout for the modal++ void clear();++ private slots:+ void on_tab_changed(int index);+ void on_view_raw_clicked();+ void on_export_csv_clicked();++ private:+ void setup_ui();++ struct TableSnapshot {+ QString name;+ QStringList headers;+ QVector<QStringList> rows;+ };++ QTabBar* tab_bar_ = nullptr;+ QTableView* table_view_ = nullptr;+ QStandardItemModel* table_model_ = nullptr;+ QPushButton* export_btn_ = nullptr;++ QLabel* lin_dataset_ = nullptr;+ QLabel* lin_schema_ = nullptr;+ QLabel* lin_symbology_ = nullptr;+ QLabel* lin_symbols_ = nullptr;+ QLabel* lin_dates_ = nullptr;+ QLabel* lin_count_ = nullptr;+ QLabel* lin_cost_ = nullptr;++ QLabel* status_label_ = nullptr;+ QLabel* status_dot_ = nullptr;+ QLabel* error_label_ = nullptr;+ QPushButton* view_raw_btn_ = nullptr;+ QString raw_output_;++ QVector<TableSnapshot> snapshots_;+};++} // namespace fincept::surfacediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceDatabentoPanel.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceDatabentoPanel.cppdeleted file mode 100644index d7e94da39..000000000--- a/fincept-qt/src/screens/surface_analytics/SurfaceDatabentoPanel.cpp+++ /dev/null@@ -1,387 +0,0 @@-#include "SurfaceDatabentoPanel.h"--#include "core/logging/Logger.h"-#include "ui/theme/Theme.h"--#include <QDateTime>-#include <QFrame>-#include <QHBoxLayout>--namespace fincept::surface {--using namespace fincept::ui;--SurfaceDatabentoPanel::SurfaceDatabentoPanel(QWidget* parent) : QWidget(parent) {- setup_ui();- update_key_status();-}--void SurfaceDatabentoPanel::setup_ui() {- setStyleSheet(QString("background:%1; color:%2;").arg(colors::BG_BASE()).arg(colors::TEXT_PRIMARY()));- auto* layout = new QVBoxLayout(this);- layout->setContentsMargins(8, 8, 8, 8);- layout->setSpacing(6);-- // ── Section title ─────────────────────────────────────────────────────- auto* title = new QLabel("DATABENTO DATA SOURCE", this);- title->setStyleSheet(QString("color:%1; font-size:10px; font-weight:bold;"- "border-bottom:1px solid %2; padding-bottom:4px;")- .arg(colors::INFO())- .arg(colors::BORDER_DIM()));- layout->addWidget(title);-- // ── API Key row ───────────────────────────────────────────────────────- auto* key_row = new QWidget(this);- auto* key_hl = new QHBoxLayout(key_row);- key_hl->setContentsMargins(0, 0, 0, 0);- key_hl->setSpacing(4);-- api_key_input_ = new QLineEdit(key_row);- api_key_input_->setPlaceholderText("Databento API key (db-...)");- api_key_input_->setEchoMode(QLineEdit::Password);- api_key_input_->setStyleSheet(QString("QLineEdit { background:%1; color:%2; border:1px solid %3;"- " padding:4px 8px; font-size:10px; border-radius:2px; }"- "QLineEdit:focus { border-color:%4; }")- .arg(colors::BG_HOVER())- .arg(colors::TEXT_PRIMARY())- .arg(colors::BORDER_MED())- .arg(colors::INFO()));- key_hl->addWidget(api_key_input_, 1);-- save_key_btn_ = new QPushButton("SAVE", key_row);- save_key_btn_->setStyleSheet(QString("QPushButton { background:%1; color:%2; border:1px solid %3;"- " padding:4px 8px; font-size:10px; border-radius:2px; }"- "QPushButton:hover { background:%3; color:%4; }")- .arg(colors::BG_RAISED())- .arg(colors::TEXT_SECONDARY())- .arg(colors::BORDER_MED())- .arg(colors::TEXT_PRIMARY()));- connect(save_key_btn_, &QPushButton::clicked, this, &SurfaceDatabentoPanel::on_save_key_clicked);- key_hl->addWidget(save_key_btn_);-- test_btn_ = new QPushButton("TEST", key_row);- test_btn_->setStyleSheet(QString("QPushButton { background:%1; color:%2; border:1px solid %3;"- " padding:4px 8px; font-size:10px; border-radius:2px; }"- "QPushButton:hover { background:%3; color:%4; }")- .arg(colors::BG_RAISED())- .arg(colors::TEXT_SECONDARY())- .arg(colors::BORDER_MED())- .arg(colors::TEXT_PRIMARY()));- connect(test_btn_, &QPushButton::clicked, &DatabentoService::instance(), &DatabentoService::test_connection);- key_hl->addWidget(test_btn_);-- layout->addWidget(key_row);-- // ── Key status ────────────────────────────────────────────────────────- key_status_lbl_ = new QLabel(this);- key_status_lbl_->setStyleSheet(QString("font-size:9px; color:%1;").arg(colors::TEXT_SECONDARY()));- layout->addWidget(key_status_lbl_);-- // ── Divider ───────────────────────────────────────────────────────────- auto* line = new QFrame(this);- line->setFrameShape(QFrame::HLine);- line->setStyleSheet(QString("border:none; border-top:1px solid %1;").arg(colors::BORDER_DIM()));- layout->addWidget(line);-- // ── Fetch button ──────────────────────────────────────────────────────- fetch_btn_ = new QPushButton("FETCH LIVE DATA", this);- fetch_btn_->setStyleSheet(QString("QPushButton { background:rgba(31,77,153,255); color:%1;"- " border:1px solid rgba(64,140,255,100); padding:6px 12px;"- " font-size:10px; font-weight:bold; border-radius:2px; }"- "QPushButton:hover { background:rgba(46,102,191,255); }"- "QPushButton:disabled { background:%2; color:%3; border-color:%4; }")- .arg(colors::INFO())- .arg(colors::BG_HOVER())- .arg(colors::TEXT_DIM())- .arg(colors::BORDER_DIM()));- connect(fetch_btn_, &QPushButton::clicked, this, &SurfaceDatabentoPanel::on_fetch_clicked);- layout->addWidget(fetch_btn_);-- // ── Status label ──────────────────────────────────────────────────────- status_lbl_ = new QLabel(this);- status_lbl_->setWordWrap(true);- status_lbl_->setStyleSheet(QString("font-size:9px; color:%1;").arg(colors::TEXT_SECONDARY()));- layout->addWidget(status_lbl_);-- // ── Last fetch timestamp ──────────────────────────────────────────────- last_fetch_lbl_ = new QLabel(this);- last_fetch_lbl_->setStyleSheet(QString("font-size:9px; color:%1;").arg(colors::TEXT_DIM()));- layout->addWidget(last_fetch_lbl_);-- layout->addStretch();-- // ── Info note ─────────────────────────────────────────────────────────- auto* note = new QLabel("Databento is a paid institutional data service.\n"- "Fetches options chains, OHLCV, and futures curves.",- this);- note->setWordWrap(true);- note->setStyleSheet(QString("font-size:9px; color:%1; font-style:italic;").arg(colors::TEXT_DIM()));- layout->addWidget(note);-}--void SurfaceDatabentoPanel::update_key_status() {- auto& svc = DatabentoService::instance();- if (svc.has_api_key()) {- key_status_lbl_->setText("API key stored");- key_status_lbl_->setStyleSheet(QString("font-size:9px; color:%1;").arg(colors::POSITIVE()));- fetch_btn_->setEnabled(true);- test_btn_->setEnabled(true);- } else {- key_status_lbl_->setText("No API key — enter key above");- key_status_lbl_->setStyleSheet(QString("font-size:9px; color:%1;").arg(colors::NEGATIVE()));- fetch_btn_->setEnabled(false);- test_btn_->setEnabled(false);- }-- QDateTime last = svc.last_fetch_time();- if (last.isValid())- last_fetch_lbl_->setText("Last fetch: " + last.toString("hh:mm:ss"));- else- last_fetch_lbl_->setText("No data fetched yet");-}--void SurfaceDatabentoPanel::set_active_chart(ChartType type, const QString& symbol, float spot) {- active_chart_ = type;- active_symbol_ = symbol;- active_spot_ = spot;-- // Update fetch button label based on what data we'll request- if (needs_vol_surface())- fetch_btn_->setText("FETCH OPTIONS CHAIN");- else if (needs_local_vol())- fetch_btn_->setText("FETCH LOCAL VOL");- else if (needs_implied_dividend())- fetch_btn_->setText("FETCH IMPLIED DIV");- else if (needs_liquidity())- fetch_btn_->setText("FETCH LIQUIDITY");- else if (needs_futures())- fetch_btn_->setText("FETCH FUTURES CURVE");- else if (needs_commodity_vol())- fetch_btn_->setText("FETCH COMMODITY VOL");- else if (needs_crack_spread())- fetch_btn_->setText("FETCH CRACK SPREAD");- else if (needs_stress_test())- fetch_btn_->setText("FETCH STRESS TEST");- else if (needs_yield_curve())- fetch_btn_->setText("FETCH YIELD CURVE");- else if (needs_forward_rate())- fetch_btn_->setText("FETCH FORWARD RATE");- else if (needs_rate_path())- fetch_btn_->setText("FETCH RATE PATH");- else if (needs_fx_forward_points())- fetch_btn_->setText("FETCH FX FORWARDS");- else if (needs_ohlcv())- fetch_btn_->setText("FETCH OHLCV DATA");- else- fetch_btn_->setText("FETCH LIVE DATA");-}--bool SurfaceDatabentoPanel::needs_vol_surface() const {- return active_chart_ == ChartType::Volatility || active_chart_ == ChartType::DeltaSurface ||- active_chart_ == ChartType::GammaSurface || active_chart_ == ChartType::VegaSurface ||- active_chart_ == ChartType::ThetaSurface || active_chart_ == ChartType::SkewSurface ||- active_chart_ == ChartType::LocalVolSurface || active_chart_ == ChartType::LiquidityHeatmap ||- active_chart_ == ChartType::ImpliedDividend;-}--bool SurfaceDatabentoPanel::needs_ohlcv() const {- return active_chart_ == ChartType::Correlation || active_chart_ == ChartType::PCA ||- active_chart_ == ChartType::Drawdown || active_chart_ == ChartType::BetaSurface ||- active_chart_ == ChartType::VaR || active_chart_ == ChartType::FactorExposure;-}--bool SurfaceDatabentoPanel::needs_futures() const {- return active_chart_ == ChartType::CommodityForward || active_chart_ == ChartType::ContangoBackwardation;-}--bool SurfaceDatabentoPanel::needs_local_vol() const {- return active_chart_ == ChartType::LocalVolSurface;-}--bool SurfaceDatabentoPanel::needs_implied_dividend() const {- return active_chart_ == ChartType::ImpliedDividend;-}--bool SurfaceDatabentoPanel::needs_liquidity() const {- return active_chart_ == ChartType::LiquidityHeatmap;-}--bool SurfaceDatabentoPanel::needs_commodity_vol() const {- return active_chart_ == ChartType::CommodityVol;-}--bool SurfaceDatabentoPanel::needs_crack_spread() const {- return active_chart_ == ChartType::CrackSpread;-}--bool SurfaceDatabentoPanel::needs_stress_test() const {- return active_chart_ == ChartType::StressTestPnL;-}--bool SurfaceDatabentoPanel::needs_yield_curve() const {- return active_chart_ == ChartType::YieldCurve;-}--bool SurfaceDatabentoPanel::needs_forward_rate() const {- return active_chart_ == ChartType::ForwardRate;-}--bool SurfaceDatabentoPanel::needs_rate_path() const {- return active_chart_ == ChartType::MonetaryPolicyPath;-}--bool SurfaceDatabentoPanel::needs_fx_forward_points() const {- return active_chart_ == ChartType::FXForwardPoints;-}--void SurfaceDatabentoPanel::set_status(const QString& msg, bool is_error) {- status_lbl_->setText(msg);- status_lbl_->setStyleSheet(- QString("font-size:9px; color:%1;").arg(is_error ? colors::NEGATIVE() : colors::TEXT_SECONDARY()));-}--// ── Show/Hide — P3 compliance (no timers here, but connect/disconnect signals) ─-void SurfaceDatabentoPanel::showEvent(QShowEvent* e) {- QWidget::showEvent(e);- auto& svc = DatabentoService::instance();- connect(&svc, &DatabentoService::connection_tested, this, &SurfaceDatabentoPanel::on_connection_tested,- Qt::UniqueConnection);- connect(&svc, &DatabentoService::fetch_started, this, &SurfaceDatabentoPanel::on_fetch_started,- Qt::UniqueConnection);- connect(&svc, &DatabentoService::fetch_failed, this, &SurfaceDatabentoPanel::on_fetch_failed, Qt::UniqueConnection);- connect(&svc, &DatabentoService::ohlcv_ready, this, &SurfaceDatabentoPanel::on_ohlcv_ready, Qt::UniqueConnection);- connect(&svc, &DatabentoService::vol_surface_ready, this, &SurfaceDatabentoPanel::on_vol_ready,- Qt::UniqueConnection);- connect(&svc, &DatabentoService::futures_ready, this, &SurfaceDatabentoPanel::on_futures_ready,- Qt::UniqueConnection);- connect(&svc, &DatabentoService::surface_ready, this, &SurfaceDatabentoPanel::on_surface_ready,- Qt::UniqueConnection);- update_key_status();-}--void SurfaceDatabentoPanel::hideEvent(QHideEvent* e) {- QWidget::hideEvent(e);- auto& svc = DatabentoService::instance();- disconnect(&svc, nullptr, this, nullptr);-}--// ── Slots ──────────────────────────────────────────────────────────────────-void SurfaceDatabentoPanel::on_save_key_clicked() {- QString key = api_key_input_->text().trimmed();- if (key.isEmpty()) {- set_status("Enter a valid API key", true);- return;- }- DatabentoService::instance().set_api_key(key);- api_key_input_->clear();- update_key_status();- set_status("API key saved");-}--void SurfaceDatabentoPanel::on_fetch_clicked() {- set_status("Fetching...");- fetch_btn_->setEnabled(false);- auto& svc = DatabentoService::instance();-- if (needs_vol_surface()) {- svc.fetch_options_surface(active_symbol_, active_spot_);- } else if (needs_local_vol()) {- svc.fetch_local_vol(active_symbol_, active_spot_);- } else if (needs_implied_dividend()) {- svc.fetch_implied_dividend(active_symbol_, active_spot_);- } else if (needs_liquidity()) {- svc.fetch_liquidity(active_symbol_, active_spot_);- } else if (needs_futures()) {- QStringList commodities = {"CL", "NG", "GC", "SI", "HG", "ZC"};- svc.fetch_futures_term_structure(commodities);- } else if (needs_commodity_vol()) {- svc.fetch_commodity_vol("CL");- } else if (needs_crack_spread()) {- svc.fetch_crack_spread();- } else if (needs_stress_test()) {- QStringList syms = {"SPY", "QQQ", "IWM", "GLD", "TLT"};- svc.fetch_stress_test(syms);- } else if (needs_yield_curve()) {- svc.fetch_yield_curve();- } else if (needs_forward_rate()) {- svc.fetch_forward_rate();- } else if (needs_rate_path()) {- svc.fetch_rate_path();- } else if (needs_fx_forward_points()) {- svc.fetch_fx_forward_points();- } else if (needs_ohlcv()) {- QStringList syms = {"SPY", "QQQ", "IWM", "DIA", "GLD", "TLT", "IEF", "HYG"};- svc.fetch_ohlcv(syms, 60);- } else {- // Fallback: OHLCV- QStringList syms = {"SPY", "QQQ", "IWM", "DIA", "GLD", "TLT", "IEF", "HYG"};- svc.fetch_ohlcv(syms, 60);- }-}--void SurfaceDatabentoPanel::on_connection_tested(bool ok, const QString& msg) {- connected_ = ok;- set_status(ok ? "Connected: " + msg : "Failed: " + msg, !ok);- if (ok) {- key_status_lbl_->setText("API key valid");- key_status_lbl_->setStyleSheet(QString("font-size:9px; color:%1;").arg(colors::POSITIVE()));- }-}--void SurfaceDatabentoPanel::on_fetch_started(const QString& desc) {- set_status(desc);- fetch_btn_->setEnabled(false);-}--void SurfaceDatabentoPanel::on_fetch_failed(const QString& err) {- set_status(err, true);- fetch_btn_->setEnabled(true);-}--void SurfaceDatabentoPanel::on_ohlcv_ready(const fincept::DatabentoOhlcvResult& r) {- fetch_btn_->setEnabled(true);- if (!r.success) {- set_status(r.error, true);- return;- }- set_status(QString("OHLCV ready: %1 symbols").arg(r.data.size()));- last_fetch_lbl_->setText("Last fetch: " + DatabentoService::instance().last_fetch_time().toString("hh:mm:ss"));- emit ohlcv_received(r);-}--void SurfaceDatabentoPanel::on_vol_ready(const fincept::DatabentoVolSurfaceResult& r) {- fetch_btn_->setEnabled(true);- if (!r.success) {- set_status(r.error, true);- return;- }- set_status(QString("Options chain ready: %1 strikes x %2 expiries")- .arg(r.vol.strikes.size())- .arg(r.vol.expirations.size()));- last_fetch_lbl_->setText("Last fetch: " + DatabentoService::instance().last_fetch_time().toString("hh:mm:ss"));- emit vol_surface_received(r);-}--void SurfaceDatabentoPanel::on_futures_ready(const fincept::DatabentoFuturesResult& r) {- fetch_btn_->setEnabled(true);- if (!r.success) {- set_status(r.error, true);- return;- }- set_status(QString("Futures ready: %1 contracts").arg(r.forward.commodities.size()));- last_fetch_lbl_->setText("Last fetch: " + DatabentoService::instance().last_fetch_time().toString("hh:mm:ss"));- emit futures_received(r);-}--void SurfaceDatabentoPanel::on_surface_ready(const fincept::DatabentoSurfaceResult& r) {- fetch_btn_->setEnabled(true);- if (!r.success) {- set_status(r.error, true);- return;- }- set_status(QString("%1 ready: %2 rows").arg(r.type).arg(r.z.size()));- last_fetch_lbl_->setText("Last fetch: " + DatabentoService::instance().last_fetch_time().toString("hh:mm:ss"));- emit surface_received(r);-}--} // namespace fincept::surfacediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceDatabentoPanel.h b/fincept-qt/src/screens/surface_analytics/SurfaceDatabentoPanel.hdeleted file mode 100644index 48e21f1de..000000000--- a/fincept-qt/src/screens/surface_analytics/SurfaceDatabentoPanel.h+++ /dev/null@@ -1,81 +0,0 @@-#pragma once-// SurfaceDatabentoPanel — Databento data source controls for Surface Analytics-// Follows P3 (show/hideEvent timers), P6 (connects to DatabentoService signals only)--#include "SurfaceTypes.h"-#include "services/databento/DatabentoService.h"--#include <QComboBox>-#include <QLabel>-#include <QLineEdit>-#include <QPushButton>-#include <QVBoxLayout>-#include <QWidget>--namespace fincept::surface {--class SurfaceDatabentoPanel : public QWidget {- Q_OBJECT- public:- explicit SurfaceDatabentoPanel(QWidget* parent = nullptr);-- // Called by SurfaceAnalyticsScreen to wire up which surface is active- void set_active_chart(ChartType type, const QString& symbol, float spot);-- signals:- // Emitted when Databento data arrives — screen connects to update surfaces- void vol_surface_received(const fincept::DatabentoVolSurfaceResult& result);- void ohlcv_received(const fincept::DatabentoOhlcvResult& result);- void futures_received(const fincept::DatabentoFuturesResult& result);- void surface_received(const fincept::DatabentoSurfaceResult& result);-- protected:- void showEvent(QShowEvent* e) override;- void hideEvent(QHideEvent* e) override;-- private slots:- void on_fetch_clicked();- void on_save_key_clicked();- void on_connection_tested(bool ok, const QString& msg);- void on_fetch_started(const QString& desc);- void on_fetch_failed(const QString& err);- void on_ohlcv_ready(const fincept::DatabentoOhlcvResult& r);- void on_vol_ready(const fincept::DatabentoVolSurfaceResult& r);- void on_futures_ready(const fincept::DatabentoFuturesResult& r);- void on_surface_ready(const fincept::DatabentoSurfaceResult& r);-- private:- void setup_ui();- void update_key_status();- void set_status(const QString& msg, bool is_error = false);- bool needs_ohlcv() const;- bool needs_vol_surface() const;- bool needs_futures() const;- bool needs_local_vol() const;- bool needs_implied_dividend() const;- bool needs_liquidity() const;- bool needs_commodity_vol() const;- bool needs_crack_spread() const;- bool needs_stress_test() const;- bool needs_yield_curve() const;- bool needs_forward_rate() const;- bool needs_rate_path() const;- bool needs_fx_forward_points() const;-- // Widgets- QLineEdit* api_key_input_ = nullptr;- QPushButton* save_key_btn_ = nullptr;- QPushButton* test_btn_ = nullptr;- QPushButton* fetch_btn_ = nullptr;- QLabel* key_status_lbl_ = nullptr;- QLabel* status_lbl_ = nullptr;- QLabel* last_fetch_lbl_ = nullptr;-- // State- ChartType active_chart_ = ChartType::Volatility;- QString active_symbol_ = "SPY";- float active_spot_ = 450.0f;- bool connected_ = false;-};--} // namespace fincept::surfacediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceDefaults.h b/fincept-qt/src/screens/surface_analytics/SurfaceDefaults.hnew file mode 100644index 000000000..ca50d4cb0--- /dev/null+++ b/fincept-qt/src/screens/surface_analytics/SurfaceDefaults.h@@ -0,0 +1,35 @@+#pragma once+// Surface Analytics — single home for legitimate constexpr defaults used+// to seed control-panel state on first run / reset. Anything here is a+// fall-back, never an authoritative value baked into business logic.++#include <array>++namespace fincept::surface::defaults {++// Starter equity options underlyings — used to seed the asset search field+// when the user first opens an OPRA-backed surface.+inline constexpr std::array<const char*, 7> EQUITY_UNDERLYINGS = {+ "SPY", "QQQ", "IWM", "AAPL", "TSLA", "NVDA", "AMZN"};++// Default correlation / PCA / risk basket — user can edit and persist their own+// via SurfaceControlPanel state.+inline constexpr std::array<const char*, 8> RISK_BASKET = {+ "SPY", "QQQ", "IWM", "DIA", "GLD", "TLT", "IEF", "HYG"};++// Default commodity roots used for futures-curve surfaces. The control panel+// shows these in the asset combo when the active surface is commodity-backed.+inline constexpr std::array<const char*, 5> COMMODITY_ROOTS = {+ "CL", "NG", "GC", "ZC", "ZS"};++// Default historical lookback (days) for equities OHLCV-driven surfaces.+inline constexpr int LOOKBACK_DAYS = 60;++// Default strike window for OPRA option-surface fetches, % of spot.+inline constexpr int STRIKE_WINDOW_PCT = 20;++// Default DTE filter for option surfaces (days-to-expiry).+inline constexpr int DTE_MIN = 7;+inline constexpr int DTE_MAX = 365;++} // namespace fincept::surface::defaultsdiff --git a/fincept-qt/src/screens/surface_analytics/SurfaceLineWidget.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceLineWidget.cppnew file mode 100644index 000000000..9eb32a03d--- /dev/null+++ b/fincept-qt/src/screens/surface_analytics/SurfaceLineWidget.cpp@@ -0,0 +1,207 @@+#include "SurfaceLineWidget.h"++#include "ui/theme/Theme.h"++#include <QPaintEvent>+#include <QPainter>+#include <QPainterPath>+#include <QPen>++#include <algorithm>+#include <cmath>+#include <limits>++namespace fincept::surface {++using namespace fincept::ui;++SurfaceLineWidget::SurfaceLineWidget(QWidget* parent) : QWidget(parent) {+ setMinimumSize(320, 240);+ setAttribute(Qt::WA_OpaquePaintEvent);+}++void SurfaceLineWidget::clear() {+ series_.clear();+ x_labels_.clear();+ title_.clear();+ update();+}++void SurfaceLineWidget::set_curve(const QString& title,+ const std::vector<float>& x_values,+ const std::vector<float>& y_values,+ const QStringList& x_labels,+ const QString& x_axis_title,+ const QString& y_axis_title,+ const QColor& line_color) {+ Series s;+ s.name = title;+ s.x_values = x_values;+ s.y_values = y_values;+ s.color = line_color;+ title_ = title;+ x_labels_ = x_labels;+ x_axis_title_ = x_axis_title;+ y_axis_title_ = y_axis_title;+ series_ = {s};+ recompute_bounds();+ update();+}++void SurfaceLineWidget::set_series(const QString& title,+ const std::vector<Series>& series,+ const QString& x_axis_title,+ const QString& y_axis_title) {+ title_ = title;+ series_ = series;+ x_axis_title_ = x_axis_title;+ y_axis_title_ = y_axis_title;+ x_labels_.clear();+ recompute_bounds();+ update();+}++void SurfaceLineWidget::recompute_bounds() {+ x_min_ = std::numeric_limits<float>::infinity();+ x_max_ = -std::numeric_limits<float>::infinity();+ y_min_ = std::numeric_limits<float>::infinity();+ y_max_ = -std::numeric_limits<float>::infinity();+ for (const auto& s : series_) {+ for (float v : s.x_values) {+ x_min_ = std::min(x_min_, v);+ x_max_ = std::max(x_max_, v);+ }+ for (float v : s.y_values) {+ y_min_ = std::min(y_min_, v);+ y_max_ = std::max(y_max_, v);+ }+ }+ if (!std::isfinite(x_min_) || x_min_ == x_max_) {+ x_min_ = 0;+ x_max_ = 1;+ }+ if (!std::isfinite(y_min_) || y_min_ == y_max_) {+ y_min_ = 0;+ y_max_ = 1;+ }+ // Add ~5% headroom on the y-axis so the curve doesn't kiss the frame+ float pad = (y_max_ - y_min_) * 0.05f;+ y_min_ -= pad;+ y_max_ += pad;+}++QPointF SurfaceLineWidget::data_to_pixel(float x, float y, const QRectF& plot) const {+ float fx = (x - x_min_) / (x_max_ - x_min_);+ float fy = (y - y_min_) / (y_max_ - y_min_);+ return QPointF(plot.left() + fx * plot.width(), plot.bottom() - fy * plot.height());+}++void SurfaceLineWidget::paintEvent(QPaintEvent* /*event*/) {+ QPainter p(this);+ p.setRenderHint(QPainter::Antialiasing, true);+ p.fillRect(rect(), QColor(colors::BG_BASE()));++ if (series_.empty()) {+ p.setPen(QColor(colors::TEXT_DIM()));+ p.drawText(rect(), Qt::AlignCenter, "No data");+ return;+ }++ QRectF plot(60, 30, width() - 80, height() - 70);++ // ── Frame ───────────────────────────────────────────────────────────────+ p.setPen(QPen(QColor(colors::BORDER_DIM()), 1));+ p.drawRect(plot);++ // ── Y gridlines + tick labels (5 ticks) ─────────────────────────────────+ p.setPen(QColor(colors::TEXT_DIM()));+ for (int i = 0; i <= 4; ++i) {+ float frac = i / 4.0f;+ float v = y_min_ + frac * (y_max_ - y_min_);+ float py = plot.bottom() - frac * plot.height();+ QPen grid(QColor(colors::BORDER_DIM()), 1, Qt::DotLine);+ p.setPen(grid);+ p.drawLine(QPointF(plot.left(), py), QPointF(plot.right(), py));+ p.setPen(QColor(colors::TEXT_DIM()));+ p.drawText(QRectF(0, py - 8, 55, 16), Qt::AlignRight | Qt::AlignVCenter,+ QString::number(v, 'f', 2));+ }++ // ── X tick labels ───────────────────────────────────────────────────────+ int n_ticks = std::min(8, !x_labels_.isEmpty() ? (int)x_labels_.size() : 6);+ for (int i = 0; i < n_ticks; ++i) {+ float frac = (n_ticks <= 1) ? 0.5f : (float)i / (n_ticks - 1);+ float px = plot.left() + frac * plot.width();+ QString label;+ if (!x_labels_.isEmpty()) {+ int idx = std::min((int)x_labels_.size() - 1, i * ((int)x_labels_.size() - 1) /+ std::max(1, n_ticks - 1));+ label = x_labels_.at(idx);+ } else {+ float v = x_min_ + frac * (x_max_ - x_min_);+ label = QString::number(v, 'f', 1);+ }+ p.setPen(QColor(colors::TEXT_DIM()));+ p.drawText(QRectF(px - 40, plot.bottom() + 4, 80, 16), Qt::AlignCenter, label);+ }++ // ── Curve(s) ────────────────────────────────────────────────────────────+ for (const auto& s : series_) {+ if (s.x_values.empty() || s.y_values.size() != s.x_values.size())+ continue;+ QPainterPath path;+ for (size_t i = 0; i < s.x_values.size(); ++i) {+ QPointF pt = data_to_pixel(s.x_values[i], s.y_values[i], plot);+ if (i == 0)+ path.moveTo(pt);+ else+ path.lineTo(pt);+ }+ p.setPen(QPen(s.color, 2));+ p.drawPath(path);++ // Markers at each point+ p.setBrush(s.color);+ for (size_t i = 0; i < s.x_values.size(); ++i) {+ QPointF pt = data_to_pixel(s.x_values[i], s.y_values[i], plot);+ p.drawEllipse(pt, 2.5, 2.5);+ }+ p.setBrush(Qt::NoBrush);+ }++ // ── Title + axis labels ─────────────────────────────────────────────────+ p.setPen(QColor(colors::TEXT_PRIMARY()));+ QFont f = p.font();+ f.setBold(true);+ p.setFont(f);+ p.drawText(QRectF(0, 4, width(), 22), Qt::AlignCenter, title_);+ f.setBold(false);+ p.setFont(f);++ p.setPen(QColor(colors::TEXT_SECONDARY()));+ if (!x_axis_title_.isEmpty())+ p.drawText(QRectF(plot.left(), plot.bottom() + 22, plot.width(), 16),+ Qt::AlignCenter, x_axis_title_);+ if (!y_axis_title_.isEmpty()) {+ p.save();+ p.translate(14, plot.center().y());+ p.rotate(-90);+ p.drawText(QRectF(-100, -8, 200, 16), Qt::AlignCenter, y_axis_title_);+ p.restore();+ }++ // ── Legend (only if >1 series) ──────────────────────────────────────────+ if (series_.size() > 1) {+ int y = (int)plot.top() + 4;+ for (const auto& s : series_) {+ p.setPen(QPen(s.color, 2));+ p.drawLine(QPointF(plot.right() - 110, y + 6), QPointF(plot.right() - 95, y + 6));+ p.setPen(QColor(colors::TEXT_SECONDARY()));+ p.drawText(QRectF(plot.right() - 90, y, 90, 14), Qt::AlignLeft | Qt::AlignVCenter,+ s.name);+ y += 16;+ }+ }+}++} // namespace fincept::surfacediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceLineWidget.h b/fincept-qt/src/screens/surface_analytics/SurfaceLineWidget.hnew file mode 100644index 000000000..67a523c38--- /dev/null+++ b/fincept-qt/src/screens/surface_analytics/SurfaceLineWidget.h@@ -0,0 +1,64 @@+#pragma once+// SurfaceLineWidget — 1-D curve renderer for surfaces that flatten to a single+// line: yield curves, contango/backwardation, FX forwards, crack spreads,+// monetary policy paths, inflation expectations.+//+// Built on QPainter (matches the rest of the screen) so we don't pull in+// Qt6 Charts as a dependency for a chart that is fundamentally a polyline.++#include <QColor>+#include <QString>+#include <QStringList>+#include <QWidget>++#include <vector>++namespace fincept::surface {++class SurfaceLineWidget : public QWidget {+ Q_OBJECT+ public:+ explicit SurfaceLineWidget(QWidget* parent = nullptr);++ // Render a single named curve.+ // Optional categorical x-labels are rendered as tick labels under the axis;+ // if empty, numeric x_values are formatted directly.+ void set_curve(const QString& title,+ const std::vector<float>& x_values,+ const std::vector<float>& y_values,+ const QStringList& x_labels = {},+ const QString& x_axis_title = QString(),+ const QString& y_axis_title = QString(),+ const QColor& line_color = QColor(88, 166, 255));++ // Render multiple curves on the same axes (e.g. one per commodity for contango).+ struct Series {+ QString name;+ std::vector<float> x_values;+ std::vector<float> y_values;+ QColor color;+ };+ void set_series(const QString& title,+ const std::vector<Series>& series,+ const QString& x_axis_title = QString(),+ const QString& y_axis_title = QString());++ void clear();++ protected:+ void paintEvent(QPaintEvent* event) override;++ private:+ QString title_;+ QString x_axis_title_;+ QString y_axis_title_;+ QStringList x_labels_;+ std::vector<Series> series_;+ float x_min_ = 0, x_max_ = 1;+ float y_min_ = 0, y_max_ = 1;++ void recompute_bounds();+ QPointF data_to_pixel(float x, float y, const QRectF& plot_area) const;+};++} // namespace fincept::surfacediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceMetricsPanel.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceMetricsPanel.cppdeleted file mode 100644index 55b9c128a..000000000--- a/fincept-qt/src/screens/surface_analytics/SurfaceMetricsPanel.cpp+++ /dev/null@@ -1,500 +0,0 @@-#include "SurfaceMetricsPanel.h"--#include "ui/theme/Theme.h"--#include <algorithm>-#include <cmath>--namespace fincept::surface {--using namespace fincept::ui;--static const char* MONO = "'Consolas','Courier New',monospace";--SurfaceMetricsPanel::SurfaceMetricsPanel(QWidget* parent) : QWidget(parent) {- setFixedWidth(190);- setStyleSheet(QString("QWidget { background:%1; border-right:1px solid %2; }")- .arg(colors::BG_SURFACE())- .arg(colors::BORDER_DIM()));- layout_ = new QVBoxLayout(this);- layout_->setContentsMargins(0, 0, 0, 0);- layout_->setSpacing(0);- layout_->addStretch();-}--void SurfaceMetricsPanel::clear_rows() {- QLayoutItem* item;- while ((item = layout_->takeAt(0))) {- if (item->widget())- item->widget()->deleteLater();- delete item;- }-}--void SurfaceMetricsPanel::add_section(const QString& title, const char* color) {- auto* lbl = new QLabel(title, this);- lbl->setFixedHeight(26);- lbl->setStyleSheet(QString("color:%1; font-size:11px; font-weight:bold; letter-spacing:0.5px;"- " background:%2; padding:0 10px;"- " border-bottom:1px solid %3;"- " font-family:%4;")- .arg(color)- .arg(colors::BG_RAISED())- .arg(colors::BORDER_DIM())- .arg(MONO));- layout_->addWidget(lbl);-}--void SurfaceMetricsPanel::add_row(const QString& label, const QString& value, const char* value_color) {- const char* vc = value_color ? value_color : colors::TEXT_PRIMARY();- auto* row = new QWidget(this);- row->setFixedHeight(22);- row->setStyleSheet(- QString("QWidget { background:transparent; border-bottom:1px solid %1; }").arg(colors::BG_RAISED()));- auto* hl = new QHBoxLayout(row);- hl->setContentsMargins(10, 0, 10, 0);- hl->setSpacing(4);-- auto* lbl = new QLabel(label, row);- lbl->setStyleSheet(QString("color:%1; font-size:11px; background:transparent;"- " font-family:%2; border:none;")- .arg(colors::TEXT_SECONDARY())- .arg(MONO));-- auto* val = new QLabel(value, row);- val->setStyleSheet(QString("color:%1; font-size:11px; font-weight:bold; background:transparent;"- " font-family:%2; border:none;")- .arg(vc)- .arg(MONO));- val->setAlignment(Qt::AlignRight | Qt::AlignVCenter);-- hl->addWidget(lbl, 1);- hl->addWidget(val, 1);- layout_->addWidget(row);-}--// ── update_metrics ────────────────────────────────────────────────────────────-void SurfaceMetricsPanel::update_metrics(- ChartType type, const VolatilitySurfaceData& vol, const GreeksSurfaceData& delta, const GreeksSurfaceData& gamma,- const GreeksSurfaceData& vega, const GreeksSurfaceData& theta, const SkewSurfaceData& skew,- const LocalVolData& local_vol, const YieldCurveData& yield, const SwaptionVolData& swaption,- const CapFloorVolData& capfloor, const BondSpreadData& bond_spread, const OISBasisData& ois,- const RealYieldData& real_yield, const ForwardRateData& fwd_rate, const FXVolData& fx_vol,- const FXForwardPointsData& fx_fwd, const CrossCurrencyBasisData& xccy, const CDSSpreadData& cds,- const CreditTransitionData& credit_trans, const RecoveryRateData& recovery, const CommodityForwardData& cmdty_fwd,- const CommodityVolData& cmdty_vol, const CrackSpreadData& crack, const ContangoData& contango,- const CorrelationMatrixData& corr, const PCAData& pca, const VaRData& var_data, const StressTestData& stress,- const FactorExposureData& factor, const LiquidityData& liquidity, const DrawdownData& drawdown,- const BetaData& beta, const ImpliedDividendData& impl_div, const InflationExpData& inflation,- const MonetaryPolicyData& monetary) {- clear_rows();-- auto fmt = [](float v, int dec = 2) { return QString::number((double)v, 'f', dec); };- auto minmax_z = [](const std::vector<std::vector<float>>& z, float& mn, float& mx) {- mn = 9999;- mx = -9999;- for (const auto& r : z)- for (float v : r) {- mn = std::min(mn, v);- mx = std::max(mx, v);- }- };-- const char* POS = colors::POSITIVE();- const char* NEG = colors::NEGATIVE();- const char* PRI = colors::TEXT_PRIMARY();- const char* SEC = colors::TEXT_SECONDARY();- const char* AMB = colors::AMBER();- const char* CYN = colors::CYAN();-- switch (type) {- // ── EQUITY DERIVATIVES ────────────────────────────────────────────────────- case ChartType::Volatility: {- if (vol.z.empty())- break;- add_section("■ VOL SURFACE", AMB);- add_row("SYMBOL", QString::fromStdString(vol.underlying), AMB);- add_row("SPOT", "$" + fmt(vol.spot_price, 2), PRI);- int me = (int)vol.z.size() / 2, ms = (int)vol.z[me].size() / 2;- add_row("ATM IV", fmt(vol.z[me][ms], 1) + "%", POS);- float mn, mx;- minmax_z(vol.z, mn, mx);- add_row("IV RANGE", fmt(mn, 1) + "-" + fmt(mx, 1) + "%", SEC);- add_row("STRIKES", QString::number(vol.strikes.size()), SEC);- add_row("EXPIRIES", QString::number(vol.expirations.size()), SEC);- break;- }- case ChartType::DeltaSurface:- case ChartType::GammaSurface:- case ChartType::VegaSurface:- case ChartType::ThetaSurface: {- const GreeksSurfaceData* gd = (type == ChartType::DeltaSurface) ? &delta- : (type == ChartType::GammaSurface) ? &gamma- : (type == ChartType::VegaSurface) ? &vega- : θ- if (gd->z.empty())- break;- add_section(QString("■ %1").arg(QString::fromStdString(gd->greek_name).toUpper()), AMB);- add_row("SYMBOL", QString::fromStdString(gd->underlying), AMB);- add_row("SPOT", "$" + fmt(gd->spot_price, 2), PRI);- int me = (int)gd->z.size() / 2, ms = (int)gd->z[me].size() / 2;- add_row("ATM", fmt(gd->z[me][ms], 4), POS);- add_row("RANGE", fmt(gd->strikes.front(), 0) + "-" + fmt(gd->strikes.back(), 0), SEC);- add_row("GRID", QString::number(gd->strikes.size()) + "x" + QString::number(gd->expirations.size()), SEC);- break;- }- case ChartType::SkewSurface: {- if (skew.z.empty())- break;- add_section("■ SKEW SURFACE", AMB);- add_row("SYMBOL", QString::fromStdString(skew.underlying), AMB);- add_row("TYPE", "25D RISK REV", SEC);- if (!skew.z.empty() && skew.z[0].size() > 2)- add_row("1W 25D", fmt(skew.z[0][2], 2) + "%", skew.z[0][2] > 0 ? POS : NEG);- add_row("TENORS", QString::number(skew.expirations.size()), SEC);- break;- }- case ChartType::LocalVolSurface: {- if (local_vol.z.empty())- break;- add_section("■ LOCAL VOL", AMB);- add_row("SYMBOL", QString::fromStdString(local_vol.underlying), AMB);- add_row("SPOT", "$" + fmt(local_vol.spot_price, 2), PRI);- add_row("MODEL", "DUPIRE", SEC);- int me = (int)local_vol.z.size() / 2, ms = (int)local_vol.z[me].size() / 2;- add_row("ATM LV", fmt(local_vol.z[me][ms], 1) + "%", POS);- break;- }- case ChartType::ImpliedDividend: {- if (impl_div.z.empty())- break;- add_section("■ IMPLIED DIV", AMB);- add_row("SYMBOL", QString::fromStdString(impl_div.underlying), AMB);- add_row("EXPIRIES", QString::number(impl_div.expirations.size()), SEC);- if (!impl_div.z.empty() && !impl_div.z[0].empty())- add_row("NEAR DIV", "$" + fmt(impl_div.z[0][0], 2), PRI);- break;- }-- // ── FIXED INCOME ──────────────────────────────────────────────────────────- case ChartType::YieldCurve: {- if (yield.z.empty())- break;- add_section("■ YIELD CURVE", POS);- const auto& last = yield.z.back();- if (!last.empty()) {- add_row("2Y", fmt(last[1], 2) + "%", PRI);- add_row("5Y", fmt(last[3], 2) + "%", PRI);- add_row("10Y", fmt(last[5], 2) + "%", PRI);- float slope = last.back() - last[3];- add_row("2s10s", fmt(slope, 1) + "bp", slope > 0 ? POS : NEG);- }- add_row("MATURITIES", QString::number(yield.maturities.size()), SEC);- break;- }- case ChartType::SwaptionVol: {- if (swaption.z.empty())- break;- add_section("■ SWAPTION VOL", POS);- int me = (int)swaption.z.size() / 2, ms = (int)swaption.z[me].size() / 2;- add_row("BELLY ATM", fmt(swaption.z[me][ms], 1) + "bp", CYN);- float mn, mx;- minmax_z(swaption.z, mn, mx);- add_row("RANGE", fmt(mn, 0) + "-" + fmt(mx, 0) + "bp", SEC);- add_row("GRID",- QString::number(swaption.option_expiries.size()) + "x" +- QString::number(swaption.swap_tenors.size()),- SEC);- break;- }- case ChartType::CapFloorVol: {- if (capfloor.z.empty())- break;- add_section("■ CAP/FLOOR VOL", POS);- float mn, mx;- minmax_z(capfloor.z, mn, mx);- add_row("RANGE", fmt(mn, 0) + "-" + fmt(mx, 0) + "bp", SEC);- add_row("MATURITIES", QString::number(capfloor.maturities.size()), SEC);- break;- }- case ChartType::BondSpread: {- if (bond_spread.z.empty())- break;- add_section("■ BOND SPREADS", POS);- if (bond_spread.z.size() > 3)- add_row("BBB 5Y", fmt(bond_spread.z[3][4], 0) + "bp", PRI);- if (bond_spread.z.size() > 4)- add_row("BB 5Y", fmt(bond_spread.z[4][4], 0) + "bp", NEG);- add_row("RATINGS", QString::number(bond_spread.ratings.size()), SEC);- break;- }- case ChartType::OISBasis: {- if (ois.z.empty())- break;- add_section("■ OIS BASIS", POS);- float mn, mx;- minmax_z(ois.z, mn, mx);- add_row("RANGE", fmt(mn, 1) + "-" + fmt(mx, 1) + "bp", SEC);- add_row("TENORS", QString::number(ois.tenors.size()), SEC);- break;- }- case ChartType::RealYield: {- if (real_yield.z.empty())- break;- add_section("■ REAL YIELD", POS);- const auto& last = real_yield.z.back();- if (!last.empty()) {- add_row("5Y REAL", fmt(last[2], 2) + "%", last[2] > 0 ? POS : NEG);- add_row("10Y REAL", fmt(last[4], 2) + "%", last[4] > 0 ? POS : NEG);- }- break;- }- case ChartType::ForwardRate: {- if (fwd_rate.z.empty())- break;- add_section("■ FORWARD RATE", POS);- float mn, mx;- minmax_z(fwd_rate.z, mn, mx);- add_row("MIN", fmt(mn, 2) + "%", PRI);- add_row("MAX", fmt(mx, 2) + "%", PRI);- add_row("TENORS", QString::number(fwd_rate.start_tenors.size()), SEC);- break;- }-- // ── FX ────────────────────────────────────────────────────────────────────- case ChartType::FXVol: {- if (fx_vol.z.empty())- break;- add_section("■ FX VOL", colors::WARNING());- add_row("PAIR", QString::fromStdString(fx_vol.pair), AMB);- if (fx_vol.z.size() > 2)- add_row("1M ATM", fmt(fx_vol.z[2][2], 2) + "%", PRI);- float mn, mx;- minmax_z(fx_vol.z, mn, mx);- add_row("RANGE", fmt(mn, 1) + "-" + fmt(mx, 1) + "%", SEC);- break;- }- case ChartType::FXForwardPoints: {- if (fx_fwd.z.empty())- break;- add_section("■ FX FWD PTS", colors::WARNING());- add_row("PAIRS", QString::number(fx_fwd.z.size()), SEC);- add_row("TENORS", QString::number(fx_fwd.tenors.size()), SEC);- break;- }- case ChartType::CrossCurrencyBasis: {- if (xccy.z.empty())- break;- add_section("■ XCCY BASIS", colors::WARNING());- float mn, mx;- minmax_z(xccy.z, mn, mx);- add_row("RANGE", fmt(mn, 1) + "-" + fmt(mx, 1) + "bp", SEC);- add_row("PAIRS", QString::number(xccy.z.size()), SEC);- break;- }-- // ── CREDIT ────────────────────────────────────────────────────────────────- case ChartType::CDSSpread: {- if (cds.z.empty())- break;- add_section("■ CDS SPREADS", NEG);- if (!cds.entities.empty())- add_row(QString::fromStdString(cds.entities[0]) + " 5Y", fmt(cds.z[0][4], 0) + "bp", NEG);- if (cds.z.size() > 1)- add_row(QString::fromStdString(cds.entities[1]) + " 5Y", fmt(cds.z[1][4], 0) + "bp", NEG);- add_row("ENTITIES", QString::number(cds.entities.size()), SEC);- break;- }- case ChartType::CreditTransition: {- if (credit_trans.z.empty())- break;- add_section("■ TRANSITION", NEG);- add_row("AAA→AAA", fmt(credit_trans.z[0][0], 1) + "%", POS);- if (credit_trans.z.size() > 6)- add_row("CCC→D", fmt(credit_trans.z[6][7], 1) + "%", NEG);- add_row("RATINGS", QString::number(credit_trans.ratings.size()), SEC);- break;- }- case ChartType::RecoveryRate: {- if (recovery.z.empty())- break;- add_section("■ RECOVERY RATE", NEG);- float mn, mx;- minmax_z(recovery.z, mn, mx);- add_row("RANGE", fmt(mn, 1) + "-" + fmt(mx, 1) + "%", SEC);- break;- }-- // ── COMMODITIES ───────────────────────────────────────────────────────────- case ChartType::CommodityForward: {- if (cmdty_fwd.z.empty())- break;- add_section("■ CMDTY FORWARD", "#9b72ff");- if (!cmdty_fwd.commodities.empty())- add_row(QString::fromStdString(cmdty_fwd.commodities[0]).toUpper() + " SPOT",- "$" + fmt(cmdty_fwd.z[0][0], 2), PRI);- add_row("COMMODITIES", QString::number(cmdty_fwd.commodities.size()), SEC);- add_row("CONTRACTS", QString::number(cmdty_fwd.contract_months.size()), SEC);- break;- }- case ChartType::CommodityVol: {- if (cmdty_vol.z.empty())- break;- add_section("■ CMDTY VOL", "#9b72ff");- float mn, mx;- minmax_z(cmdty_vol.z, mn, mx);- add_row("RANGE", fmt(mn, 1) + "-" + fmt(mx, 1) + "%", SEC);- add_row("COMMODITIES", QString::number(cmdty_vol.z.size()), SEC);- break;- }- case ChartType::CrackSpread: {- if (crack.z.empty())- break;- add_section("■ CRACK SPREAD", "#9b72ff");- float mn, mx;- minmax_z(crack.z, mn, mx);- add_row("RANGE", fmt(mn, 1) + "-" + fmt(mx, 1) + " $/bbl", SEC);- add_row("PRODUCTS", QString::number(crack.z.size()), SEC);- break;- }- case ChartType::ContangoBackwardation: {- if (contango.z.empty())- break;- add_section("■ CONTANGO", "#9b72ff");- float mn, mx;- minmax_z(contango.z, mn, mx);- add_row("RANGE", fmt(mn, 2) + "-" + fmt(mx, 2) + "%", SEC);- add_row("COMMODITIES", QString::number(contango.z.size()), SEC);- break;- }-- // ── RISK ──────────────────────────────────────────────────────────────────- case ChartType::Correlation: {- if (corr.z.empty())- break;- add_section("■ CORRELATION", AMB);- add_row("ASSETS", QString::number(corr.assets.size()), SEC);- add_row("WINDOW", QString::number(corr.window) + "D", SEC);- float mn, mx;- minmax_z(corr.z, mn, mx);- add_row("RANGE", fmt(mn, 2) + " / " + fmt(mx, 2), SEC);- break;- }- case ChartType::PCA: {- if (pca.z.empty())- break;- add_section("■ PCA", AMB);- if (!pca.variance_explained.empty()) {- add_row("PC1 VAR%", fmt(pca.variance_explained[0] * 100, 1) + "%", CYN);- if (pca.variance_explained.size() > 1)- add_row("PC2 VAR%", fmt(pca.variance_explained[1] * 100, 1) + "%", SEC);- }- add_row("FACTORS", QString::number(pca.factors.size()), SEC);- add_row("ASSETS", QString::number(pca.assets.size()), SEC);- break;- }- case ChartType::VaR: {- if (var_data.z.empty())- break;- add_section("■ VALUE AT RISK", NEG);- if (var_data.z.size() > 1)- add_row("95% 1D", fmt(var_data.z[1][0], 2) + "%", NEG);- if (var_data.z.size() > 2)- add_row("99% 10D", fmt(var_data.z[2][2], 2) + "%", NEG);- add_row("CONF LEVELS", QString::number(var_data.z.size()), SEC);- break;- }- case ChartType::StressTestPnL: {- if (stress.z.empty())- break;- add_section("■ STRESS TEST", NEG);- float worst = 0;- for (const auto& r : stress.z)- for (float v : r)- worst = std::min(worst, v);- add_row("WORST P&L", fmt(worst, 1) + "%", NEG);- add_row("SCENARIOS", QString::number(stress.scenarios.size()), SEC);- add_row("PORTFOLIOS", QString::number(stress.portfolios.size()), SEC);- break;- }- case ChartType::FactorExposure: {- if (factor.z.empty())- break;- add_section("■ FACTOR EXPOSURE", AMB);- add_row("FACTORS", QString::number(factor.factors.size()), SEC);- add_row("ASSETS", QString::number(factor.assets.size()), SEC);- break;- }- case ChartType::LiquidityHeatmap: {- if (liquidity.z.empty())- break;- add_section("■ LIQUIDITY", AMB);- float mn, mx;- minmax_z(liquidity.z, mn, mx);- add_row("MIN BID-ASK", fmt(mn, 1) + "bp", POS);- add_row("MAX BID-ASK", fmt(mx, 1) + "bp", NEG);- break;- }- case ChartType::Drawdown: {- if (drawdown.z.empty())- break;- add_section("■ DRAWDOWN", NEG);- float mn, mx;- minmax_z(drawdown.z, mn, mx);- add_row("MAX DD", fmt(mn, 1) + "%", NEG);- add_row("ASSETS", QString::number(drawdown.assets.size()), SEC);- add_row("WINDOWS", QString::number(drawdown.windows.size()), SEC);- break;- }- case ChartType::BetaSurface: {- if (beta.z.empty())- break;- add_section("■ BETA SURFACE", AMB);- float mn, mx;- minmax_z(beta.z, mn, mx);- add_row("RANGE", fmt(mn, 2) + " / " + fmt(mx, 2), SEC);- add_row("ASSETS", QString::number(beta.assets.size()), SEC);- add_row("HORIZONS", QString::number(beta.horizons.size()), SEC);- break;- }-- // ── MACRO ─────────────────────────────────────────────────────────────────- case ChartType::InflationExpectations: {- if (inflation.z.empty())- break;- add_section("■ INFLATION EXP", CYN);- const auto& last = inflation.z.back();- if (!last.empty())- add_row("1Y BE", fmt(last[0], 2) + "%", PRI);- if (last.size() > 3)- add_row("5Y BE", fmt(last[3], 2) + "%", PRI);- if (last.size() > 5)- add_row("10Y BE", fmt(last[5], 2) + "%", PRI);- add_row("HORIZONS", QString::number(inflation.horizons.size()), SEC);- break;- }- case ChartType::MonetaryPolicyPath: {- if (monetary.z.empty())- break;- add_section("■ POLICY PATH", CYN);- if (!monetary.central_banks.empty())- add_row(QString::fromStdString(monetary.central_banks[0]).toUpper(), fmt(monetary.z[0][0], 2) + "%",- PRI);- if (monetary.z.size() > 1)- add_row(QString::fromStdString(monetary.central_banks[1]).toUpper(), fmt(monetary.z[1][0], 2) + "%",- PRI);- add_row("BANKS", QString::number(monetary.central_banks.size()), SEC);- add_row("MEETINGS", QString::number(monetary.meetings_ahead.size()), SEC);- break;- }-- default:- add_section("■ METRICS", colors::TEXT_TERTIARY());- add_row("SELECT", "A SURFACE", colors::TEXT_TERTIARY());- break;- }-- layout_->addStretch();-}--} // namespace fincept::surfacediff --git a/fincept-qt/src/screens/surface_analytics/SurfaceMetricsPanel.h b/fincept-qt/src/screens/surface_analytics/SurfaceMetricsPanel.hdeleted file mode 100644index 37497a821..000000000--- a/fincept-qt/src/screens/surface_analytics/SurfaceMetricsPanel.h+++ /dev/null@@ -1,41 +0,0 @@-#pragma once-#include "SurfaceTypes.h"-#include "ui/theme/Theme.h"--#include <QLabel>-#include <QVBoxLayout>-#include <QWidget>--namespace fincept::surface {--// Left-side metrics panel — shows key stats for the active surface-class SurfaceMetricsPanel : public QWidget {- Q_OBJECT- public:- explicit SurfaceMetricsPanel(QWidget* parent = nullptr);-- void update_metrics(ChartType type,- // All data pointers — panel selects the right one- const VolatilitySurfaceData& vol, const GreeksSurfaceData& delta,- const GreeksSurfaceData& gamma, const GreeksSurfaceData& vega, const GreeksSurfaceData& theta,- const SkewSurfaceData& skew, const LocalVolData& local_vol, const YieldCurveData& yield,- const SwaptionVolData& swaption, const CapFloorVolData& capfloor,- const BondSpreadData& bond_spread, const OISBasisData& ois, const RealYieldData& real_yield,- const ForwardRateData& fwd_rate, const FXVolData& fx_vol, const FXForwardPointsData& fx_fwd,- const CrossCurrencyBasisData& xccy, const CDSSpreadData& cds,- const CreditTransitionData& credit_trans, const RecoveryRateData& recovery,- const CommodityForwardData& cmdty_fwd, const CommodityVolData& cmdty_vol,- const CrackSpreadData& crack, const ContangoData& contango, const CorrelationMatrixData& corr,- const PCAData& pca, const VaRData& var_data, const StressTestData& stress,- const FactorExposureData& factor, const LiquidityData& liquidity, const DrawdownData& drawdown,- const BetaData& beta, const ImpliedDividendData& impl_div, const InflationExpData& inflation,- const MonetaryPolicyData& monetary);-- private:- QVBoxLayout* layout_;- void clear_rows();- void add_row(const QString& label, const QString& value, const char* value_color = nullptr);- void add_section(const QString& title, const char* color);-};--} // namespace fincept::surfacediff --git a/fincept-qt/src/services/backtesting/BacktestingService.cpp b/fincept-qt/src/services/backtesting/BacktestingService.cppindex 7b0af4be1..a77a6039a 100644--- a/fincept-qt/src/services/backtesting/BacktestingService.cpp+++ b/fincept-qt/src/services/backtesting/BacktestingService.cpp@@ -5,6 +5,7 @@#include "python/PythonRunner.h"#include "storage/cache/CacheManager.h"+#include <QHash>#include <QJsonDocument>#include <QPointer>@@ -25,11 +26,25 @@ void BacktestingService::execute(const QString& provider, const QString& commandauto script = QString("Analytics/backtesting/%1/%1_provider.py").arg(provider);auto json_str = QJsonDocument(args).toJson(QJsonDocument::Compact);+ // The UI uses short command ids (matching fincept-qt/src/services/backtesting/+ // BacktestingTypes.h::all_commands()); every Python provider's main() dispatches+ // on the canonical, longer names. Translate at the boundary so screen/types+ // code keeps the short ids while the subprocess sees what its dispatcher expects.+ static const QHash<QString, QString> kPyCommandMap{+ {"backtest", "run_backtest"},+ {"indicator", "calculate_indicator"},+ {"signals", "generate_signals"},+ {"labels", "generate_labels"},+ {"splits", "generate_splits"},+ {"returns", "analyze_returns"},+ };+ const QString py_command = kPyCommandMap.value(command, command);+QPointer<BacktestingService> self = this;auto ctx = QString("%1/%2").arg(provider, command);python::PythonRunner::instance().run(- script, {command, json_str}, [self, provider, command, ctx](python::PythonResult result) {+ script, {py_command, json_str}, [self, provider, command, ctx](python::PythonResult result) {if (!self)return;if (!result.success) {@@ -114,9 +129,12 @@ void BacktestingService::load_command_options(const QString& provider) {}void BacktestingService::list_strategies() {+ // fincept_provider.py exposes the catalog under "get_strategies" and requires+ // a JSON args payload (sys.argv[2]) — pass an empty object.QPointer<BacktestingService> self = this;python::PythonRunner::instance().run(- "Analytics/backtesting/fincept/fincept_provider.py", {"list_strategies"}, [self](python::PythonResult result) {+ "Analytics/backtesting/fincept/fincept_provider.py", {"get_strategies", "{}"},+ [self](python::PythonResult result) {if (!self)return;if (!result.success) {diff --git a/fincept-qt/src/services/billing/FeeDiscountConfig.h b/fincept-qt/src/services/billing/FeeDiscountConfig.hnew file mode 100644index 000000000..d2f35c9f0--- /dev/null+++ b/fincept-qt/src/services/billing/FeeDiscountConfig.h@@ -0,0 +1,52 @@+#pragma once++#include <QString>+#include <QStringList>++namespace fincept::billing {++/// Static configuration for the $FNCPT fee-discount tier (Phase 2 §2C).+///+/// Header-only by design — these are compile-time constants that both+/// `FeeDiscountService` and `FeeDiscountPanel` read. Phase 3's TierService+/// will introduce a richer per-user override path; this stays as the+/// fallback / Phase 2 baseline.+struct FeeDiscountConfig {+ /// Eligibility threshold in raw $FNCPT atomic units (decimals = 6).+ /// 1,000 $FNCPT = 1,000 × 10^6 = 1,000,000,000 raw.+ static constexpr quint64 kThresholdRaw = 1000ULL * 1000000ULL;++ /// $FNCPT mint decimals — pump.fun standard. Used to convert raw → UI+ /// when rendering "1,000 $FNCPT" instead of the atomic count.+ static constexpr int kThresholdDecimals = 6;++ /// Discount percentage on every applied SKU.+ static constexpr int kDiscountPct = 30;++ /// SKUs that honor the discount when eligible. The strings are stable+ /// IDs the billing pipeline will eventually key on; the panel renders+ /// human labels via `display_label()`.+ static QStringList applied_skus() {+ return QStringList{+ QStringLiteral("ai-report"),+ QStringLiteral("deep-backtest"),+ QStringLiteral("premium-screen"),+ };+ }++ /// Human-readable label for a SKU id. Unknown ids fall back to the+ /// raw id (so a future SKU added on the backend at least renders).+ static QString display_label(const QString& sku) {+ if (sku == QStringLiteral("ai-report")) return QStringLiteral("AI Reports");+ if (sku == QStringLiteral("deep-backtest")) return QStringLiteral("Deep Backtests");+ if (sku == QStringLiteral("premium-screen")) return QStringLiteral("Premium Screens");+ return sku;+ }++ /// Indicative reference price for the savings preview on the+ /// FeeDiscountPanel. Not a real billed amount — purely a UX hint.+ /// The savings = (reference × kDiscountPct / 100).+ static constexpr double kReferencePriceUsd = 9.99;+};++} // namespace fincept::billingdiff --git a/fincept-qt/src/services/billing/FeeDiscountService.cpp b/fincept-qt/src/services/billing/FeeDiscountService.cppnew file mode 100644index 000000000..5462d1555--- /dev/null+++ b/fincept-qt/src/services/billing/FeeDiscountService.cpp@@ -0,0 +1,101 @@+#include "services/billing/FeeDiscountService.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "services/billing/FeeDiscountConfig.h"+#include "services/wallet/WalletTypes.h"++#include <QDateTime>+#include <QVariant>++namespace fincept::billing {++namespace {++constexpr const char* kFamilyPrefix = "billing:fncpt_discount:";++quint64 fncpt_raw_amount(const fincept::wallet::WalletBalance& bal) {+ if (auto* h = bal.fncpt_holding()) {+ bool ok = false;+ const auto raw = h->amount_raw.toULongLong(&ok);+ return ok ? raw : 0;+ }+ return 0;+}++} // namespace++FeeDiscountService::FeeDiscountService(QObject* parent) : QObject(parent) {}++FeeDiscountService::~FeeDiscountService() = default;++QStringList FeeDiscountService::topic_patterns() const {+ return QStringList{QStringLiteral("billing:fncpt_discount:*")};+}++QString FeeDiscountService::pubkey_from_topic(const QString& topic) {+ return topic.mid(static_cast<int>(qstrlen(kFamilyPrefix)));+}++QString FeeDiscountService::balance_topic_for(const QString& pubkey) {+ return QStringLiteral("wallet:balance:") + pubkey;+}++void FeeDiscountService::refresh(const QStringList& topics) {+ wire_balance_listener();+ for (const auto& topic : topics) {+ const auto pubkey = pubkey_from_topic(topic);+ if (pubkey.isEmpty()) continue;+ publish_for(topic, pubkey);+ }+}++void FeeDiscountService::publish_for(const QString& topic, const QString& pubkey) {+ auto& hub = fincept::datahub::DataHub::instance();+ const auto bal_topic = balance_topic_for(pubkey);+ const auto v = hub.peek(bal_topic);++ fincept::wallet::FncptDiscount d;+ d.pubkey_b58 = pubkey;+ d.threshold_raw = FeeDiscountConfig::kThresholdRaw;+ d.threshold_decimals = FeeDiscountConfig::kThresholdDecimals;+ d.discount_pct = FeeDiscountConfig::kDiscountPct;+ d.applied_skus = FeeDiscountConfig::applied_skus();+ d.ts_ms = QDateTime::currentMSecsSinceEpoch();++ if (v.canConvert<fincept::wallet::WalletBalance>()) {+ const auto bal = v.value<fincept::wallet::WalletBalance>();+ d.eligible = fncpt_raw_amount(bal) >= FeeDiscountConfig::kThresholdRaw;+ } else {+ // No balance cached yet. Subscribe so the next publish flips us.+ // Stay on `eligible=false` until we have data — the chip on the+ // HoldingsBar starts hidden, no UX glitch.+ d.eligible = false;+ }++ hub.publish(topic, QVariant::fromValue(d));+}++void FeeDiscountService::wire_balance_listener() {+ if (listener_wired_) return;+ auto& hub = fincept::datahub::DataHub::instance();+ // Listen for *every* wallet:balance:* publish and re-emit any active+ // discount topic that matches. We use the topic_changed signal because+ // it fires once per publish across the family.+ QObject::connect(&hub, &fincept::datahub::DataHub::topic_updated, this,+ [this](const QString& topic, const QVariant& /*value*/) {+ const QString prefix = QStringLiteral("wallet:balance:");+ if (!topic.startsWith(prefix)) return;+ const auto pubkey = topic.mid(prefix.size());+ if (pubkey.isEmpty()) return;+ const auto out_topic = QString::fromLatin1(kFamilyPrefix) + pubkey;+ // Only republish if someone is actually listening (cheap check —+ // if nobody subscribed, the hub will skip the publish anyway,+ // but we save the QVariant copy).+ publish_for(out_topic, pubkey);+ });+ listener_wired_ = true;+ LOG_INFO("FeeDiscount", "balance listener wired");+}++} // namespace fincept::billingdiff --git a/fincept-qt/src/services/billing/FeeDiscountService.h b/fincept-qt/src/services/billing/FeeDiscountService.hnew file mode 100644index 000000000..37993e41a--- /dev/null+++ b/fincept-qt/src/services/billing/FeeDiscountService.h@@ -0,0 +1,50 @@+#pragma once++#include "datahub/Producer.h"++#include <QObject>+#include <QString>++namespace fincept::billing {++/// Producer for `billing:fncpt_discount:<pubkey>`.+///+/// Phase 2 §2C — derives eligibility from `wallet:balance:<pubkey>` rather+/// than fetching anything external. When the hub asks us to refresh a topic,+/// we peek the corresponding balance topic, compute `eligible = fncpt_ui >=+/// threshold`, and publish a `FncptDiscount`. The service also subscribes+/// to balance updates so eligibility flips re-publish immediately, not+/// only on hub TTL ticks.+///+/// Per CLAUDE.md D2 this is a real Producer because it owns a topic family.+/// The "no external fetch" property just means `refresh()` is cheap — no+/// HTTP, no cadence pacing required.+class FeeDiscountService : public QObject, public fincept::datahub::Producer {+ Q_OBJECT+ public:+ explicit FeeDiscountService(QObject* parent = nullptr);+ ~FeeDiscountService() override;++ QStringList topic_patterns() const override;+ void refresh(const QStringList& topics) override;+ int max_requests_per_sec() const override { return 0; }++ private:+ /// `billing:fncpt_discount:<pubkey>` → pubkey, or "" if invalid.+ static QString pubkey_from_topic(const QString& topic);++ /// `wallet:balance:<pubkey>` for the given pubkey.+ static QString balance_topic_for(const QString& pubkey);++ /// Compute + publish the FncptDiscount payload by peeking the latest+ /// balance from the hub. Idempotent — safe to call repeatedly.+ void publish_for(const QString& topic, const QString& pubkey);++ /// Set up cross-subscriptions so balance changes re-emit eligibility+ /// immediately rather than waiting on the hub TTL tick.+ void wire_balance_listener();++ bool listener_wired_ = false;+};++} // namespace fincept::billingdiff --git a/fincept-qt/src/services/databento/DatabentoService.cpp b/fincept-qt/src/services/databento/DatabentoService.cppindex acf7ba4ba..2e406189e 100644--- a/fincept-qt/src/services/databento/DatabentoService.cpp+++ b/fincept-qt/src/services/databento/DatabentoService.cpp@@ -53,23 +53,38 @@ DatabentoService& DatabentoService::instance() {DatabentoService::DatabentoService() {}// ── API key ────────────────────────────────────────────────────────────────+// We accept both the legacy SECURE_KEY ("databento.api_key") and the canonical+// env-style key ("DATABENTO_API_KEY") used by Settings + PythonRunner env+// injection. Reads check both; writes mirror to both so the two paths stay+// in sync regardless of which screen entered the key.+static constexpr const char* DATABENTO_ENV_KEY = "DATABENTO_API_KEY";+bool DatabentoService::has_api_key() const {auto r = SecureStorage::instance().retrieve(SECURE_KEY);- return r.is_ok() && !r.value().isEmpty();+ if (r.is_ok() && !r.value().isEmpty())+ return true;+ auto r2 = SecureStorage::instance().retrieve(DATABENTO_ENV_KEY);+ return r2.is_ok() && !r2.value().isEmpty();}void DatabentoService::set_api_key(const QString& key) {- SecureStorage::instance().store(SECURE_KEY, key.trimmed());+ QString trimmed = key.trimmed();+ SecureStorage::instance().store(SECURE_KEY, trimmed);+ SecureStorage::instance().store(DATABENTO_ENV_KEY, trimmed);LOG_INFO("Databento", "API key stored");}QString DatabentoService::api_key() const {auto r = SecureStorage::instance().retrieve(SECURE_KEY);- return r.is_ok() ? r.value() : QString{};+ if (r.is_ok() && !r.value().isEmpty())+ return r.value();+ auto r2 = SecureStorage::instance().retrieve(DATABENTO_ENV_KEY);+ return r2.is_ok() ? r2.value() : QString{};}void DatabentoService::clear_api_key() {SecureStorage::instance().remove(SECURE_KEY);+ SecureStorage::instance().remove(DATABENTO_ENV_KEY);}// ── Core runner — wraps PythonRunner per P4 ────────────────────────────────@@ -105,9 +120,13 @@ void DatabentoService::run_script(const QStringList& args, std::function<void(boQPointer<DatabentoService> self = this;- PythonRunner::instance().run(SCRIPT, script_args, [self, cb](PythonResult result) {+ QString cmd_label = command;+ PythonRunner::instance().run(SCRIPT, script_args, [self, cb, cmd_label](PythonResult result) {if (!self)return;+ // Surface the full stdout (includes warnings + JSON) so the inspector's+ // "View raw response" modal has something useful to show.+ emit self->raw_response(cmd_label, result.output);if (!result.success) {LOG_ERROR("Databento", "Script error: " + result.error);cb(false, {{"error", result.error}});@@ -706,6 +725,195 @@ surface::CommodityForwardData DatabentoService::parse_commodity_forward(const QJreturn data;}+// ── Metadata: list datasets ────────────────────────────────────────────────+void DatabentoService::list_datasets(std::function<void(QStringList)> cb) {+ if (!cached_datasets_.isEmpty()) {+ cb(cached_datasets_);+ return;+ }+ QPointer<DatabentoService> self = this;+ run_script({"list_datasets"}, [self, cb](bool ok, const QJsonObject& j) {+ QStringList out;+ if (self && ok && !j["error"].toBool(false)) {+ for (const auto& v : j["datasets"].toArray()) {+ QString id = v.toObject()["id"].toString();+ if (!id.isEmpty())+ out << id;+ }+ self->cached_datasets_ = out;+ }+ cb(out);+ });+}++// ── Metadata: list schemas for a dataset ───────────────────────────────────+void DatabentoService::list_schemas(const QString& dataset, std::function<void(QStringList)> cb) {+ if (cached_schemas_.contains(dataset)) {+ cb(cached_schemas_.value(dataset));+ return;+ }+ QPointer<DatabentoService> self = this;+ QString ds = dataset;+ run_script({"list_schemas", "dataset", dataset}, [self, ds, cb](bool ok, const QJsonObject& j) {+ QStringList out;+ if (self && ok && !j["error"].toBool(false)) {+ for (const auto& v : j["schemas"].toArray()) {+ QString id = v.toObject()["id"].toString();+ if (!id.isEmpty())+ out << id;+ }+ self->cached_schemas_[ds] = out;+ }+ cb(out);+ });+}++// ── Metadata: list publishers (optionally filtered to one dataset) ─────────+void DatabentoService::list_publishers(const QString& dataset, std::function<void(QList<DbPublisher>)> cb) {+ QString cache_key = dataset.isEmpty() ? "*" : dataset;+ if (cached_publishers_.contains(cache_key)) {+ cb(cached_publishers_.value(cache_key));+ return;+ }+ QPointer<DatabentoService> self = this;+ QStringList args = {"list_publishers"};+ if (!dataset.isEmpty()) {+ args << "dataset" << dataset;+ }+ run_script(args, [self, cache_key, cb](bool ok, const QJsonObject& j) {+ QList<DbPublisher> out;+ if (self && ok && !j["error"].toBool(false)) {+ for (const auto& v : j["publishers"].toArray()) {+ QJsonObject o = v.toObject();+ DbPublisher p;+ p.publisher_id = o["publisher_id"].toInt();+ p.dataset = o["dataset"].toString();+ p.venue = o["venue"].toString();+ p.description = o["description"].toString();+ out.push_back(p);+ }+ self->cached_publishers_[cache_key] = out;+ }+ cb(out);+ });+}++// ── Metadata: dataset date range ───────────────────────────────────────────+void DatabentoService::get_dataset_range(const QString& dataset, std::function<void(DbDatasetRange)> cb) {+ if (cached_ranges_.contains(dataset)) {+ cb(cached_ranges_.value(dataset));+ return;+ }+ QPointer<DatabentoService> self = this;+ run_script({"dataset_range", "dataset", dataset}, [self, dataset, cb](bool ok, const QJsonObject& j) {+ DbDatasetRange out;+ out.dataset = dataset;+ if (self && ok && !j["error"].toBool(false)) {+ QString s = j["start"].toString();+ QString e = j["end"].toString();+ // Accept "YYYY-MM-DD..." or full ISO with 'T'+ if (!s.isEmpty())+ out.start = QDate::fromString(s.left(10), "yyyy-MM-dd");+ if (!e.isEmpty())+ out.end = QDate::fromString(e.left(10), "yyyy-MM-dd");+ self->cached_ranges_[dataset] = out;+ }+ cb(out);+ });+}++// ── Metadata: cost estimate ────────────────────────────────────────────────+void DatabentoService::get_cost(const DbCostQuery& q, std::function<void(DbCostResult)> cb) {+ QStringList args = {"get_cost_estimate",+ "dataset", q.dataset,+ "symbols", q.symbols.join(","),+ "schema", q.schema,+ "start_date", q.start.toString("yyyy-MM-dd"),+ "end_date", q.end.toString("yyyy-MM-dd")};+ run_script(args, [cb](bool ok, const QJsonObject& j) {+ DbCostResult res;+ if (!ok || j["error"].toBool(false)) {+ res.success = false;+ res.error = ok ? j["message"].toString("Unknown error") : j["error"].toString();+ } else {+ res.success = true;+ res.record_count = (qint64)j["record_count"].toDouble(0);+ res.cost_usd = j["cost_usd"].toDouble(0);+ }+ cb(res);+ });+}++// ── Metadata: symbol search ────────────────────────────────────────────────+void DatabentoService::search_symbols(const QString& query, const QString& dataset,+ std::function<void(QStringList)> cb) {+ QStringList args = {"symbol_search", "query", query};+ if (!dataset.isEmpty()) {+ args << "dataset" << dataset;+ }+ run_script(args, [cb](bool ok, const QJsonObject& j) {+ QStringList out;+ if (ok && !j["error"].toBool(false)) {+ for (const auto& v : j["matches"].toArray()) {+ QString rs = v.toObject()["raw_symbol"].toString();+ if (!rs.isEmpty())+ out << rs;+ }+ }+ cb(out);+ });+}++// ── Unified surface fetch dispatcher ───────────────────────────────────────+// Takes a DatabentoFetchParams produced by the SurfaceControlPanel and routes+// to the correct underlying fetch, which still emits the appropriate+// vol_surface_ready / ohlcv_ready / futures_ready / surface_ready signal.+void DatabentoService::fetch_with_params(const DatabentoFetchParams& params) {+ const QString& chart = params.chart_type;++ // Resolve spot for option-surface fetches. If the caller provided one,+ // honour it; otherwise default to a placeholder; the screen can later+ // consult DataHub for a live quote.+ float spot = params.spot_override > 0.0f ? params.spot_override : 100.0f;++ if (chart == "Volatility" || chart == "DeltaSurface" || chart == "GammaSurface" ||+ chart == "VegaSurface" || chart == "ThetaSurface" || chart == "SkewSurface") {+ fetch_options_surface(params.symbol, spot);+ } else if (chart == "LocalVolSurface") {+ fetch_local_vol(params.symbol, spot);+ } else if (chart == "ImpliedDividend") {+ fetch_implied_dividend(params.symbol, spot);+ } else if (chart == "LiquidityHeatmap") {+ fetch_liquidity(params.symbol, spot);+ } else if (chart == "CommodityForward" || chart == "ContangoBackwardation") {+ QStringList roots = params.basket;+ if (roots.isEmpty() && !params.symbol.isEmpty())+ roots << params.symbol;+ fetch_futures_term_structure(roots);+ } else if (chart == "CommodityVol") {+ fetch_commodity_vol(params.symbol);+ } else if (chart == "CrackSpread") {+ fetch_crack_spread();+ } else if (chart == "Correlation" || chart == "PCA" || chart == "Drawdown" ||+ chart == "BetaSurface" || chart == "VaR" || chart == "FactorExposure") {+ QDate start = params.start_date.isValid() ? params.start_date+ : QDate::currentDate().addDays(-60);+ QDate end = params.end_date.isValid() ? params.end_date : QDate::currentDate();+ int days = std::max(1, (int)start.daysTo(end));+ QStringList syms = params.basket.isEmpty() ? QStringList{params.symbol} : params.basket;+ fetch_ohlcv(syms, days);+ } else if (chart == "StressTestPnL") {+ fetch_stress_test(params.basket.isEmpty() ? QStringList{params.symbol} : params.basket);+ } else {+ // Surfaces with no Databento source — emit failure so UI shows DEMO state+ DatabentoSurfaceResult res;+ res.success = false;+ res.type = chart;+ res.error = "No Databento source for this surface";+ emit surface_ready(res);+ }+}+surface::ContangoData DatabentoService::parse_contango(const QJsonObject& j) {surface::ContangoData data;QJsonObject term = j["term_structure"].toObject();diff --git a/fincept-qt/src/services/databento/DatabentoService.h b/fincept-qt/src/services/databento/DatabentoService.hindex 368124879..53906c9c2 100644--- a/fincept-qt/src/services/databento/DatabentoService.h+++ b/fincept-qt/src/services/databento/DatabentoService.h@@ -4,17 +4,69 @@#include "screens/surface_analytics/SurfaceTypes.h"+#include <QDate>#include <QDateTime>#include <QHash>#include <QJsonObject>#include <QObject>#include <QString>+#include <QStringList>+#include <functional>#include <string>#include <vector>namespace fincept {+// Metadata types for the Surface Analytics control panel+struct DbPublisher {+ int publisher_id = 0;+ QString dataset;+ QString venue;+ QString description;+};++struct DbDatasetRange {+ QString dataset;+ QDate start;+ QDate end;+};++struct DbCostQuery {+ QString dataset;+ QStringList symbols;+ QString schema;+ QDate start;+ QDate end;+ QString stype_in = "raw_symbol";+};++struct DbCostResult {+ bool success = false;+ QString error;+ qint64 record_count = 0;+ double cost_usd = 0.0;+};++// Unified parameters for surface fetches. Replaces the per-method+// (symbol, spot, days, root_symbol, ...) overloads. The screen builds one+// of these from the SurfaceControlPanel state and passes it to fetch_with_params().+struct DatabentoFetchParams {+ QString chart_type; // String form of ChartType, e.g. "Volatility"+ QString symbol; // Underlying for option/futures surfaces+ QStringList basket; // Multi-symbol basket for risk surfaces+ QString dataset; // Optional override; capability default if empty+ QString schema; // Optional override; capability default if empty+ QDate start_date;+ QDate end_date;+ int strike_window_pct = 20;+ int dte_min = 7;+ int dte_max = 365;+ QStringList venues; // Optional OPRA-venue filter+ QString iv_method = "Brent";+ float spot_override = 0.0f; // 0 = lookup via DataHub::peek+};+// Result of a Databento fetch — emitted via signalsstruct DatabentoOhlcvResult {bool success = false;@@ -64,6 +116,25 @@ class DatabentoService : public QObject {// Test connectionvoid test_connection(); // emits connection_tested(bool ok, QString msg)+ // ── Metadata (callback-based; results cached in-memory) ─────────────────+ // The control panel uses these to populate dataset/schema/publisher pickers+ // and to suggest sane default date ranges before a fetch is dispatched.+ void list_datasets(std::function<void(QStringList)> cb);+ void list_schemas(const QString& dataset, std::function<void(QStringList)> cb);+ void list_publishers(const QString& dataset, std::function<void(QList<DbPublisher>)> cb);+ void get_dataset_range(const QString& dataset, std::function<void(DbDatasetRange)> cb);+ void get_cost(const DbCostQuery& q, std::function<void(DbCostResult)> cb);+ void search_symbols(const QString& query, const QString& dataset,+ std::function<void(QStringList)> cb);++ // ── Unified surface fetch ───────────────────────────────────────────────+ // Routes to the right Python command based on params.chart_type.+ // Spot for option surfaces is read from DataHub::peek("market:quote:<sym>")+ // unless params.spot_override > 0. Result arrives through the existing+ // vol_surface_ready / ohlcv_ready / futures_ready / surface_ready signals+ // matching the request's chart family.+ void fetch_with_params(const DatabentoFetchParams& params);+// Fetch historical OHLCV for a list of symbols (used for correlation, PCA, drawdown, beta)void fetch_ohlcv(const QStringList& symbols, int days = 60);@@ -99,6 +170,9 @@ class DatabentoService : public QObject {void surface_ready(const DatabentoSurfaceResult& result);void fetch_started(const QString& description);void fetch_failed(const QString& error);+ // Emits the raw Python stdout for the most recent fetch so the data+ // inspector can show it in the "View raw response" modal.+ void raw_response(const QString& script_command, const QString& raw_stdout);private:DatabentoService();@@ -117,6 +191,12 @@ class DatabentoService : public QObject {DatabentoFuturesResult cached_futures_;QDateTime last_fetch_time_;+ // Metadata caches — populated lazily on first request, valid for app session+ QStringList cached_datasets_;+ QHash<QString, QStringList> cached_schemas_; // dataset → schemas+ QHash<QString, QList<DbPublisher>> cached_publishers_;+ QHash<QString, DbDatasetRange> cached_ranges_;+static constexpr const char* SECURE_KEY = "databento.api_key";static constexpr const char* SCRIPT = "databento_provider.py";};diff --git a/fincept-qt/src/services/news/NewsService.cpp b/fincept-qt/src/services/news/NewsService.cppindex 156230ba4..70d77cf8f 100644--- a/fincept-qt/src/services/news/NewsService.cpp+++ b/fincept-qt/src/services/news/NewsService.cpp@@ -26,10 +26,17 @@namespace fincept::services {-static constexpr int kFeedTransferTimeoutMs = 5000; // 5s per RSS feed request+static constexpr int kFeedTransferTimeoutMs = 8000; // 8s per RSS feed requeststatic constexpr int kWsReconnectDelayMs = 10000; // 10s before WebSocket reconnectstatic constexpr int kSummaryMaxChars = 300; // max chars for article summary+// Use a real browser User-Agent — Bloomberg, WSJ, FT and other major+// publishers reject "FinceptTerminal/4.0" as scraper traffic. Browser UA+// gets us 200s on the same endpoints.+static constexpr const char* kBrowserUserAgent =+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "+ "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";+// ── Singleton ───────────────────────────────────────────────────────────────NewsService& NewsService::instance() {@@ -100,8 +107,10 @@ void NewsService::fetch_all_news(bool force, ArticlesCallback cb) {for (const auto& feed : feeds) {QNetworkRequest req(QUrl(feed.url));- req.setHeader(QNetworkRequest::UserAgentHeader, "FinceptTerminal/4.0");+ req.setHeader(QNetworkRequest::UserAgentHeader, kBrowserUserAgent);req.setRawHeader("Accept", "application/rss+xml, application/xml, text/xml, */*");+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,+ QNetworkRequest::NoLessSafeRedirectPolicy);req.setTransferTimeout(kFeedTransferTimeoutMs);auto* reply = nam_->get(req);@@ -109,11 +118,31 @@ void NewsService::fetch_all_news(bool force, ArticlesCallback cb) {reply->deleteLater();QVector<NewsArticle> articles;+ const int http_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();if (reply->error() == QNetworkReply::NoError) {QByteArray data = reply->readAll();- if (data.trimmed().startsWith('<')) {+ const QByteArray trimmed = data.trimmed();+ // Cheap shape check: real RSS/Atom starts with <?xml or <rss or+ // <feed. HTML error pages (Akamai access-denied, Cloudflare+ // captcha) start with <html / <!doctype and would pass through+ // the parser silently producing 0 articles — flag them clearly.+ const bool looks_like_html =+ trimmed.left(20).toLower().contains("<html") ||+ trimmed.left(20).toLower().contains("<!doctype html");+ if (looks_like_html) {+ LOG_WARN("NewsService",+ QString("Feed %1 (%2) returned HTML (likely access-denied), %3 bytes")+ .arg(feed.id, feed.source).arg(data.size()));+ } else if (trimmed.startsWith('<')) {articles = parse_rss_xml(data, feed);}+ if (articles.isEmpty() && !looks_like_html) {+ LOG_WARN("NewsService", QString("Feed %1 (%2) returned %3 bytes but no parsed articles")+ .arg(feed.id, feed.source).arg(data.size()));+ }+ } else {+ LOG_WARN("NewsService", QString("Feed %1 (%2) failed: HTTP %3, err=%4")+ .arg(feed.id, feed.source).arg(http_code).arg(reply->errorString()));}{@@ -230,8 +259,10 @@ void NewsService::fetch_all_news_progressive(bool force, ArticlesCallback final_for (const auto& feed : feeds) {QNetworkRequest req(QUrl(feed.url));- req.setHeader(QNetworkRequest::UserAgentHeader, "FinceptTerminal/4.0");+ req.setHeader(QNetworkRequest::UserAgentHeader, kBrowserUserAgent);req.setRawHeader("Accept", "application/rss+xml, application/xml, text/xml, */*");+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,+ QNetworkRequest::NoLessSafeRedirectPolicy);req.setTransferTimeout(kFeedTransferTimeoutMs);auto* reply = nam_->get(req);@@ -239,10 +270,27 @@ void NewsService::fetch_all_news_progressive(bool force, ArticlesCallback final_reply->deleteLater();QVector<NewsArticle> batch;+ const int http_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();if (reply->error() == QNetworkReply::NoError) {QByteArray data = reply->readAll();- if (data.trimmed().startsWith('<'))+ const QByteArray trimmed = data.trimmed();+ const bool looks_like_html =+ trimmed.left(20).toLower().contains("<html") ||+ trimmed.left(20).toLower().contains("<!doctype html");+ if (looks_like_html) {+ LOG_WARN("NewsService",+ QString("Feed %1 (%2) returned HTML (likely access-denied), %3 bytes")+ .arg(feed.id, feed.source).arg(data.size()));+ } else if (trimmed.startsWith('<')) {batch = parse_rss_xml(data, feed);+ }+ if (batch.isEmpty() && !looks_like_html) {+ LOG_WARN("NewsService", QString("Feed %1 (%2) returned %3 bytes but no parsed articles")+ .arg(feed.id, feed.source).arg(data.size()));+ }+ } else {+ LOG_WARN("NewsService", QString("Feed %1 (%2) failed: HTTP %3, err=%4")+ .arg(feed.id, feed.source).arg(http_code).arg(reply->errorString()));}QVector<NewsArticle> snapshot;@@ -942,19 +990,17 @@ QString NewsService::source_flag_label(SourceFlag flag) {QVector<RSSFeed> NewsService::default_feeds() {return {// Tier 1 — Wire Services & Regulators- {"reuters-world", "Reuters World", "https://feeds.reuters.com/Reuters/worldNews", "GEOPOLITICS", "GLOBAL",- "REUTERS", 1},- {"reuters-biz", "Reuters Business", "https://feeds.reuters.com/reuters/businessNews", "MARKETS", "GLOBAL",- "REUTERS", 1},- {"reuters-mkts", "Reuters Markets", "https://feeds.reuters.com/reuters/financialsNews", "MARKETS", "GLOBAL",- "REUTERS", 1},+ // Reuters discontinued public RSS in 2020 (feeds.reuters.com is dead).+ // We keep tier-1 coverage via AP, BBC, FT, Bloomberg, WSJ instead.{"ap-top", "AP Top News", "https://rsshub.app/apnews/topics/ap-top-news", "GEOPOLITICS", "GLOBAL", "AP", 1},{"sec-press", "SEC Press Releases", "https://www.sec.gov/news/pressreleases.rss", "REGULATORY", "US", "SEC", 1},{"fed-press", "Federal Reserve", "https://www.federalreserve.gov/feeds/press_all.xml", "REGULATORY", "US","FEDERAL RESERVE", 1},{"un-news", "UN News", "https://news.un.org/feed/subscribe/en/news/all/rss.xml", "GEOPOLITICS", "GLOBAL", "UN",1},- {"imf-news", "IMF News", "https://www.imf.org/en/News/rss?language=eng", "ECONOMIC", "GLOBAL", "IMF", 1},+ // (IMF News removed — endpoint serves an Akamai access-denied HTML page,+ // not RSS. Fincept's macro coverage is already provided by Bloomberg /+ // WSJ / Economist / IMF press is reachable via UN feeds.)// Tier 2 — Major Financial Media{"bloomberg-mkts", "Bloomberg Markets", "https://feeds.bloomberg.com/markets/news.rss", "MARKETS", "GLOBAL",@@ -984,11 +1030,11 @@ QVector<RSSFeed> NewsService::default_feeds() {// Tier 2 — Geopolitics & Defense{"foreignpolicy", "Foreign Policy", "https://foreignpolicy.com/feed/", "GEOPOLITICS", "GLOBAL","FOREIGN POLICY", 2},- {"defensenews", "Defense News", "https://www.defensenews.com/rss/", "GEOPOLITICS", "GLOBAL", "DEFENSE NEWS", 2},+ // (defensenews.com/rss/ returns 404 — endpoint discontinued.)// Tier 2 — Energy & Commodities{"oilprice", "OilPrice.com", "https://oilprice.com/rss/main", "ENERGY", "GLOBAL", "OILPRICE", 2},- {"kitco", "Kitco Gold", "https://www.kitco.com/rss/news/", "MARKETS", "GLOBAL", "KITCO", 2},+ // (Kitco RSS endpoint removed — kitco.com no longer publishes RSS.)// Tier 2 — Tech{"techcrunch", "TechCrunch", "https://techcrunch.com/feed/", "TECH", "GLOBAL", "TECHCRUNCH", 2},@@ -1010,8 +1056,7 @@ QVector<RSSFeed> NewsService::default_feeds() {// ── Additional feeds (29→80+) ──────────────────────────────────────// Tier 1 — Wire (additional)- {"reuters-tech", "Reuters Technology", "https://feeds.reuters.com/reuters/technologyNews", "TECH", "GLOBAL",- "REUTERS", 1},+ // (Reuters tech RSS removed — feed discontinued.)// Tier 2 — Major Financial (additional){"cnbc-world", "CNBC World",@@ -1063,7 +1108,7 @@ QVector<RSSFeed> NewsService::default_feeds() {{"wolfstreet", "Wolf Street", "https://wolfstreet.com/feed/", "ECONOMIC", "US", "WOLF STREET", 3},// Tier 3 — Defense & Security- {"defense-one", "Defense One", "https://www.defenseone.com/rss/", "DEFENSE", "US", "DEFENSE ONE", 3},+ // (defenseone.com/rss/ returns 404 — endpoint discontinued.){"bellingcat", "Bellingcat", "https://www.bellingcat.com/feed/", "GEOPOLITICS", "GLOBAL", "BELLINGCAT", 3},// Tier 3 — Tech (additional)diff --git a/fincept-qt/src/services/report_builder/ReportBuilderService.cpp b/fincept-qt/src/services/report_builder/ReportBuilderService.cppnew file mode 100644index 000000000..cebf91c9a--- /dev/null+++ b/fincept-qt/src/services/report_builder/ReportBuilderService.cpp@@ -0,0 +1,654 @@+// ReportBuilderService.cpp — see header for design rationale.++#include "services/report_builder/ReportBuilderService.h"++#include "core/events/EventBus.h"+#include "core/logging/Logger.h"++#include <QDateTime>+#include <QFile>+#include <QFileInfo>+#include <QSettings>+#include <QStandardPaths>+#include <QUndoCommand>++#include <utility>++namespace fincept::services {++static constexpr const char* RB_SVC_TAG = "ReportBuilderService";+static constexpr int kAutosaveIntervalMs = 60'000;+static constexpr int kLlmWindowMs = 400;+static constexpr int kRecentMax = 10;+static constexpr const char* kRecentKey = "report_builder/recent";+static constexpr const char* kCurrentFileKey = "report_builder/current_file";++namespace rep = report;++// ── Undo commands ────────────────────────────────────────────────────────────+//+// Owned by the service (formerly owned by the screen). They mutate the doc+// directly without re-entering the public mutators (which would push another+// command onto the stack — infinite loop). The service exposes private direct-+// mutators via friend access.++namespace {++class AddCmd : public QUndoCommand {+ public:+ AddCmd(ReportBuilderService* svc, rep::ReportComponent comp, int at)+ : QUndoCommand("Add " + comp.type), svc_(svc), comp_(std::move(comp)), at_(at) {}+ void redo() override;+ void undo() override;++ private:+ ReportBuilderService* svc_;+ rep::ReportComponent comp_;+ int at_;+};++class RemoveCmd : public QUndoCommand {+ public:+ RemoveCmd(ReportBuilderService* svc, int index)+ : QUndoCommand("Remove component"), svc_(svc), index_(index) {}+ void redo() override;+ void undo() override;+ void set_saved(rep::ReportComponent c) { saved_ = std::move(c); }++ private:+ ReportBuilderService* svc_;+ rep::ReportComponent saved_;+ int index_;+};++class UpdateCmd : public QUndoCommand {+ public:+ UpdateCmd(ReportBuilderService* svc, int id, QString old_content, QMap<QString, QString> old_config,+ QString new_content, QMap<QString, QString> new_config)+ : QUndoCommand("Edit component"),+ svc_(svc),+ id_(id),+ old_content_(std::move(old_content)),+ new_content_(std::move(new_content)),+ old_config_(std::move(old_config)),+ new_config_(std::move(new_config)) {}+ void redo() override;+ void undo() override;+ int id() const override { return 1001; }+ bool mergeWith(const QUndoCommand* other) override;++ private:+ ReportBuilderService* svc_;+ int id_;+ QString old_content_, new_content_;+ QMap<QString, QString> old_config_, new_config_;+};++class MoveCmd : public QUndoCommand {+ public:+ MoveCmd(ReportBuilderService* svc, int id, int from, int to)+ : QUndoCommand("Move component"), svc_(svc), id_(id), from_(from), to_(to) {}+ void redo() override;+ void undo() override;++ private:+ ReportBuilderService* svc_;+ int id_;+ int from_, to_;+};++class MetadataCmd : public QUndoCommand {+ public:+ MetadataCmd(ReportBuilderService* svc, rep::ReportMetadata old_m, rep::ReportMetadata new_m)+ : QUndoCommand("Edit metadata"),+ svc_(svc),+ old_(std::move(old_m)),+ new_(std::move(new_m)) {}+ void redo() override;+ void undo() override;++ private:+ ReportBuilderService* svc_;+ rep::ReportMetadata old_, new_;+};++class ThemeCmd : public QUndoCommand {+ public:+ ThemeCmd(ReportBuilderService* svc, rep::ReportTheme old_t, rep::ReportTheme new_t)+ : QUndoCommand("Change theme"),+ svc_(svc),+ old_(std::move(old_t)),+ new_(std::move(new_t)) {}+ void redo() override;+ void undo() override;++ private:+ ReportBuilderService* svc_;+ rep::ReportTheme old_, new_;+};++} // namespace++// Direct (no-undo) mutators — used by the undo commands. They take the mutex,+// modify doc_, drop the mutex, then emit signals. Signals fire on the owning+// thread of the service (main thread).++namespace detail {++class ServiceFriend {+ public:+ static void direct_insert(ReportBuilderService* svc, rep::ReportComponent c, int at);+ static rep::ReportComponent direct_remove(ReportBuilderService* svc, int index);+ static void direct_update_by_id(ReportBuilderService* svc, int id, const QString& content,+ const QMap<QString, QString>& config);+ static void direct_move_by_id(ReportBuilderService* svc, int id, int new_index);+ static void direct_set_metadata(ReportBuilderService* svc, rep::ReportMetadata m);+ static void direct_set_theme(ReportBuilderService* svc, rep::ReportTheme t);++ // Read helpers used by the undo commands. They hold the service mutex+ // briefly and return a snapshot — undo command bodies must not access+ // svc_->mutex_ / svc_->doc_ directly (those members are private).+ static int locked_index_of(ReportBuilderService* svc, int id);+ static rep::ReportComponent locked_get_at(ReportBuilderService* svc, int index);+};++void ServiceFriend::direct_insert(ReportBuilderService* svc, rep::ReportComponent c, int at) {+ int index;+ {+ QMutexLocker lock(&svc->mutex_);+ if (at < 0 || at > svc->doc_.components.size())+ at = svc->doc_.components.size();+ if (c.id <= 0)+ c.id = svc->doc_.allocate_id();+ else if (c.id >= svc->doc_.next_id)+ svc->doc_.next_id = c.id + 1;+ svc->doc_.components.insert(at, c);+ index = at;+ }+ emit svc->component_added(c.id, index);+ emit svc->document_changed();+}++rep::ReportComponent ServiceFriend::direct_remove(ReportBuilderService* svc, int index) {+ rep::ReportComponent removed;+ int id = -1;+ {+ QMutexLocker lock(&svc->mutex_);+ if (index < 0 || index >= svc->doc_.components.size())+ return removed;+ removed = svc->doc_.components.takeAt(index);+ id = removed.id;+ }+ if (id != -1) {+ emit svc->component_removed(id, index);+ emit svc->document_changed();+ }+ return removed;+}++void ServiceFriend::direct_update_by_id(ReportBuilderService* svc, int id, const QString& content,+ const QMap<QString, QString>& config) {+ bool found = false;+ {+ QMutexLocker lock(&svc->mutex_);+ int idx = svc->doc_.index_of(id);+ if (idx >= 0) {+ svc->doc_.components[idx].content = content;+ svc->doc_.components[idx].config = config;+ found = true;+ }+ }+ if (found) {+ emit svc->component_updated(id);+ emit svc->document_changed();+ }+}++void ServiceFriend::direct_move_by_id(ReportBuilderService* svc, int id, int new_index) {+ int from = -1, to = -1;+ {+ QMutexLocker lock(&svc->mutex_);+ from = svc->doc_.index_of(id);+ if (from < 0)+ return;+ to = new_index;+ if (to < 0)+ to = 0;+ if (to >= svc->doc_.components.size())+ to = svc->doc_.components.size() - 1;+ if (from == to)+ return;+ rep::ReportComponent c = svc->doc_.components.takeAt(from);+ svc->doc_.components.insert(to, std::move(c));+ }+ emit svc->component_moved(id, from, to);+ emit svc->document_changed();+}++void ServiceFriend::direct_set_metadata(ReportBuilderService* svc, rep::ReportMetadata m) {+ {+ QMutexLocker lock(&svc->mutex_);+ svc->doc_.metadata = std::move(m);+ }+ emit svc->metadata_changed();+ emit svc->document_changed();+}++void ServiceFriend::direct_set_theme(ReportBuilderService* svc, rep::ReportTheme t) {+ {+ QMutexLocker lock(&svc->mutex_);+ svc->doc_.theme = std::move(t);+ }+ emit svc->theme_changed();+ emit svc->document_changed();+}++int ServiceFriend::locked_index_of(ReportBuilderService* svc, int id) {+ QMutexLocker lock(&svc->mutex_);+ return svc->doc_.index_of(id);+}++rep::ReportComponent ServiceFriend::locked_get_at(ReportBuilderService* svc, int index) {+ QMutexLocker lock(&svc->mutex_);+ if (index < 0 || index >= svc->doc_.components.size())+ return rep::ReportComponent{};+ return svc->doc_.components[index];+}++} // namespace detail++// ── Undo command bodies ──────────────────────────────────────────────────────++void AddCmd::redo() { detail::ServiceFriend::direct_insert(svc_, comp_, at_); }+void AddCmd::undo() {+ // Find by id rather than index — concurrent mutations may have shifted+ // positions since the original add. (Within a macro this is unlikely+ // but the bookkeeping cost is trivial.)+ int idx = detail::ServiceFriend::locked_index_of(svc_, comp_.id);+ if (idx >= 0)+ detail::ServiceFriend::direct_remove(svc_, idx);+}++void RemoveCmd::redo() {+ if (saved_.id == 0) {+ // First execution: capture before removing so undo can restore.+ saved_ = detail::ServiceFriend::locked_get_at(svc_, index_);+ }+ detail::ServiceFriend::direct_remove(svc_, index_);+}+void RemoveCmd::undo() {+ if (saved_.id != 0)+ detail::ServiceFriend::direct_insert(svc_, saved_, index_);+}++void UpdateCmd::redo() {+ detail::ServiceFriend::direct_update_by_id(svc_, id_, new_content_, new_config_);+}+void UpdateCmd::undo() {+ detail::ServiceFriend::direct_update_by_id(svc_, id_, old_content_, old_config_);+}+bool UpdateCmd::mergeWith(const QUndoCommand* other) {+ if (other->id() != id())+ return false;+ auto* o = static_cast<const UpdateCmd*>(other);+ if (o->id_ != id_)+ return false;+ new_content_ = o->new_content_;+ new_config_ = o->new_config_;+ return true;+}++void MoveCmd::redo() { detail::ServiceFriend::direct_move_by_id(svc_, id_, to_); }+void MoveCmd::undo() { detail::ServiceFriend::direct_move_by_id(svc_, id_, from_); }++void MetadataCmd::redo() { detail::ServiceFriend::direct_set_metadata(svc_, new_); }+void MetadataCmd::undo() { detail::ServiceFriend::direct_set_metadata(svc_, old_); }++void ThemeCmd::redo() { detail::ServiceFriend::direct_set_theme(svc_, new_); }+void ThemeCmd::undo() { detail::ServiceFriend::direct_set_theme(svc_, old_); }++// ── Service ──────────────────────────────────────────────────────────────────++ReportBuilderService& ReportBuilderService::instance() {+ static ReportBuilderService s;+ return s;+}++ReportBuilderService::ReportBuilderService() {+ doc_.metadata.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");+ undo_stack_ = new QUndoStack(this);++ autosave_timer_ = new QTimer(this);+ autosave_timer_->setInterval(kAutosaveIntervalMs);+ connect(autosave_timer_, &QTimer::timeout, this, &ReportBuilderService::trigger_autosave);+ autosave_timer_->start();++ llm_window_timer_ = new QTimer(this);+ llm_window_timer_->setSingleShot(true);+ llm_window_timer_->setInterval(kLlmWindowMs);+ connect(llm_window_timer_, &QTimer::timeout, this, [this]() {+ // Close the macro we opened in note_llm_mutation().+ if (macro_depth_ > 0) {+ macro_depth_ = 0;+ undo_stack_->endMacro();+ LOG_INFO(RB_SVC_TAG, "LLM macro window closed");+ }+ });++ autosave_path_ =+ QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/fincept_report_autosave.fincept";++ // Restore current_file_ from settings so the title bar shows the right+ // path on relaunch. (The doc itself comes from autosave below.)+ QSettings s("Fincept", "FinceptTerminal");+ current_file_ = s.value(kCurrentFileKey).toString();++ // Try to restore from autosave on construction. Failures are silent —+ // an empty doc is the correct fallback.+ QFile f(autosave_path_);+ if (f.exists() && f.open(QIODevice::ReadOnly | QIODevice::Text)) {+ QString json = QString::fromUtf8(f.readAll());+ f.close();+ auto r = rep::ReportDocument::from_json(json);+ if (r.is_ok()) {+ doc_ = r.value();+ LOG_INFO(RB_SVC_TAG, "Restored from autosave: " + autosave_path_);+ }+ }+}++// ── Read API ────────────────────────────────────────────────────────────────++QVector<rep::ReportComponent> ReportBuilderService::components() const {+ QMutexLocker lock(&mutex_);+ return doc_.components;+}+rep::ReportMetadata ReportBuilderService::metadata() const {+ QMutexLocker lock(&mutex_);+ return doc_.metadata;+}+rep::ReportTheme ReportBuilderService::theme() const {+ QMutexLocker lock(&mutex_);+ return doc_.theme;+}+int ReportBuilderService::next_id() const {+ QMutexLocker lock(&mutex_);+ return doc_.next_id;+}+int ReportBuilderService::index_of(int id) const {+ QMutexLocker lock(&mutex_);+ return doc_.index_of(id);+}+QString ReportBuilderService::current_file() const {+ QMutexLocker lock(&mutex_);+ return current_file_;+}+QStringList ReportBuilderService::recent_files() const {+ if (!recent_loaded_)+ load_recent();+ return recent_cache_;+}+rep::ReportDocument ReportBuilderService::snapshot() const {+ QMutexLocker lock(&mutex_);+ return doc_;+}++// ── Write API ────────────────────────────────────────────────────────────────++int ReportBuilderService::add_component(const rep::ReportComponent& comp, int insert_at) {+ rep::ReportComponent c = comp;+ if (c.id <= 0) {+ QMutexLocker lock(&mutex_);+ c.id = doc_.allocate_id();+ }+ int at = insert_at;+ {+ QMutexLocker lock(&mutex_);+ if (at < 0 || at > doc_.components.size())+ at = doc_.components.size();+ }+ LOG_INFO(RB_SVC_TAG, QString("add_component: type=%1 id=%2 at=%3").arg(c.type).arg(c.id).arg(at));+ push_undo(new AddCmd(this, c, at));+ return c.id;+}++bool ReportBuilderService::update_component(int id, const QString& content, const QMap<QString, QString>& config) {+ QString old_content;+ QMap<QString, QString> old_config;+ {+ QMutexLocker lock(&mutex_);+ int idx = doc_.index_of(id);+ if (idx < 0)+ return false;+ old_content = doc_.components[idx].content;+ old_config = doc_.components[idx].config;+ }+ push_undo(new UpdateCmd(this, id, old_content, old_config, content, config));+ return true;+}++bool ReportBuilderService::patch_component(int id, const QString* content_or_null,+ const QMap<QString, QString>& partial_config) {+ QString old_content, new_content;+ QMap<QString, QString> old_config, new_config;+ {+ QMutexLocker lock(&mutex_);+ int idx = doc_.index_of(id);+ if (idx < 0)+ return false;+ old_content = doc_.components[idx].content;+ old_config = doc_.components[idx].config;+ new_content = content_or_null ? *content_or_null : old_content;+ new_config = old_config;+ for (auto it = partial_config.cbegin(); it != partial_config.cend(); ++it)+ new_config[it.key()] = it.value();+ }+ push_undo(new UpdateCmd(this, id, old_content, old_config, new_content, new_config));+ return true;+}++bool ReportBuilderService::remove_component(int id) {+ int idx;+ {+ QMutexLocker lock(&mutex_);+ idx = doc_.index_of(id);+ }+ if (idx < 0)+ return false;+ push_undo(new RemoveCmd(this, idx));+ return true;+}++bool ReportBuilderService::move_component(int id, int new_index) {+ int from;+ {+ QMutexLocker lock(&mutex_);+ from = doc_.index_of(id);+ if (from < 0)+ return false;+ if (new_index < 0)+ new_index = 0;+ if (new_index >= doc_.components.size())+ new_index = doc_.components.size() - 1;+ if (from == new_index)+ return true;+ }+ push_undo(new MoveCmd(this, id, from, new_index));+ return true;+}++void ReportBuilderService::set_metadata(const rep::ReportMetadata& meta) {+ rep::ReportMetadata old;+ {+ QMutexLocker lock(&mutex_);+ old = doc_.metadata;+ }+ push_undo(new MetadataCmd(this, old, meta));+}++void ReportBuilderService::set_theme(const rep::ReportTheme& th) {+ rep::ReportTheme old;+ {+ QMutexLocker lock(&mutex_);+ old = doc_.theme;+ }+ push_undo(new ThemeCmd(this, old, th));+}++void ReportBuilderService::clear_document() {+ begin_macro("Clear report");+ auto comps = components();+ for (auto it = comps.crbegin(); it != comps.crend(); ++it)+ remove_component(it->id);+ set_metadata(rep::ReportMetadata{});+ end_macro();+ {+ QMutexLocker lock(&mutex_);+ doc_.metadata.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");+ current_file_.clear();+ }+ persist_current_file();+ emit document_cleared();+ emit current_file_changed({});+}++void ReportBuilderService::replace_document(const rep::ReportDocument& doc) {+ {+ QMutexLocker lock(&mutex_);+ doc_ = doc;+ }+ undo_stack_->clear();+ emit document_changed();+}++// ── Undo helpers ────────────────────────────────────────────────────────────++QUndoStack* ReportBuilderService::undo_stack() { return undo_stack_; }++void ReportBuilderService::begin_macro(const QString& description) {+ if (macro_depth_++ == 0)+ undo_stack_->beginMacro(description);+}++void ReportBuilderService::end_macro() {+ if (macro_depth_ == 0)+ return;+ if (--macro_depth_ == 0)+ undo_stack_->endMacro();+}++void ReportBuilderService::note_llm_mutation() {+ if (macro_depth_ == 0) {+ macro_depth_ = 1;+ undo_stack_->beginMacro("AI: report changes");+ LOG_INFO(RB_SVC_TAG, "LLM macro window opened (400ms)");+ }+ // (Re)start the window timer — extend as long as mutations keep arriving.+ llm_window_timer_->start();+}++void ReportBuilderService::push_undo(QUndoCommand* cmd) { undo_stack_->push(cmd); }++// ── File ops ────────────────────────────────────────────────────────────────++Result<void> ReportBuilderService::save_to(const QString& path) {+ QString json;+ {+ QMutexLocker lock(&mutex_);+ json = doc_.to_json();+ }+ QFile f(path);+ if (!f.open(QIODevice::WriteOnly | QIODevice::Text))+ return Result<void>::err("Could not open file for writing: " + f.errorString().toStdString());+ f.write(json.toUtf8());+ f.close();+ set_current_file(path);+ return Result<void>::ok();+}++Result<void> ReportBuilderService::load_from(const QString& path) {+ QFile f(path);+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text))+ return Result<void>::err("Could not open file: " + f.errorString().toStdString());+ QString json = QString::fromUtf8(f.readAll());+ f.close();+ auto r = rep::ReportDocument::from_json(json);+ if (r.is_err())+ return Result<void>::err("Parse error: " + r.error());+ {+ QMutexLocker lock(&mutex_);+ doc_ = r.value();+ }+ undo_stack_->clear();+ set_current_file(path);+ emit document_loaded(path);+ emit document_changed();+ return Result<void>::ok();+}++void ReportBuilderService::set_current_file(const QString& path) {+ {+ QMutexLocker lock(&mutex_);+ current_file_ = path;+ }+ persist_current_file();+ if (!path.isEmpty()) {+ if (!recent_loaded_)+ load_recent();+ recent_cache_.removeAll(path);+ recent_cache_.prepend(path);+ if (recent_cache_.size() > kRecentMax)+ recent_cache_ = recent_cache_.mid(0, kRecentMax);+ save_recent();+ }+ emit current_file_changed(path);+}++void ReportBuilderService::persist_current_file() {+ QSettings s("Fincept", "FinceptTerminal");+ s.setValue(kCurrentFileKey, current_file_);+}++QString ReportBuilderService::autosave_path() const { return autosave_path_; }++void ReportBuilderService::trigger_autosave() {+ QString json;+ {+ QMutexLocker lock(&mutex_);+ // Skip writing an empty doc — avoids clobbering a useful autosave+ // with nothing if the user just bumped the timer with no content.+ if (doc_.components.isEmpty() && doc_.metadata.title == "Untitled Report")+ return;+ json = doc_.to_json();+ }+ QFile f(autosave_path_);+ if (f.open(QIODevice::WriteOnly | QIODevice::Text))+ f.write(json.toUtf8());+}++void ReportBuilderService::load_recent() const {+ QSettings s("Fincept", "FinceptTerminal");+ recent_cache_ = s.value(kRecentKey).toStringList();+ recent_loaded_ = true;+}++void ReportBuilderService::save_recent() const {+ QSettings s("Fincept", "FinceptTerminal");+ s.setValue(kRecentKey, recent_cache_);+}++// ── apply_template ──────────────────────────────────────────────────────────+//+// Templates are large literal data — keeping the table of templates here+// (out of the screen) means the LLM and manual UI both build the same+// content. The template body lives in ReportBuilderTemplates.cpp so this+// file stays focused.++extern void apply_template_to_service(ReportBuilderService* svc, const QString& name);++void ReportBuilderService::apply_template(const QString& name) {+ LOG_INFO(RB_SVC_TAG, "apply_template: " + name);+ apply_template_to_service(this, name);+}++} // namespace fincept::servicesdiff --git a/fincept-qt/src/services/report_builder/ReportBuilderService.h b/fincept-qt/src/services/report_builder/ReportBuilderService.hnew file mode 100644index 000000000..23bf84314--- /dev/null+++ b/fincept-qt/src/services/report_builder/ReportBuilderService.h@@ -0,0 +1,169 @@+#pragma once+// ReportBuilderService — Single source of truth for the active report document.+//+// Why a service: per CLAUDE.md §P6 (Service Layer Separation), screens render+// UI only. The report document state must live outside the screen so:+// • LLM/MCP tools can mutate the document even when the screen isn't open.+// • State survives screen open/close (factory-registered screen recreates).+// • Manual edits and LLM-driven edits go through the same undo stack.+// • Autosave runs regardless of UI visibility.+//+// Threading: the service object lives on the main thread. All public mutators+// must be invoked there. Workers (e.g. LLM tool handlers running on+// QtConcurrent::run threads) post via QMetaObject::invokeMethod with+// Qt::BlockingQueuedConnection, which is what the dispatch helper does+// internally. Reads (components()/metadata()/theme()) are guarded by a mutex+// and are safe from any thread.++#include "core/report/ReportDocument.h"+#include "core/result/Result.h"++#include <QMutex>+#include <QObject>+#include <QString>+#include <QStringList>+#include <QTimer>+#include <QUndoStack>+#include <QVector>++namespace fincept::services {++namespace detail {+class ServiceFriend; // defined in ReportBuilderService.cpp+}++class ReportBuilderService : public QObject {+ Q_OBJECT+ public:+ static ReportBuilderService& instance();++ // ── Read API (thread-safe) ────────────────────────────────────────────────++ QVector<report::ReportComponent> components() const;+ report::ReportMetadata metadata() const;+ report::ReportTheme theme() const;+ int next_id() const;++ // Find by stable id; -1 if not found.+ int index_of(int id) const;++ QString current_file() const;+ QStringList recent_files() const;++ // Snapshot the entire doc. Useful for serialization, MCP get_state,+ // PDF export.+ report::ReportDocument snapshot() const;++ // ── Write API (main thread) ──────────────────────────────────────────────+ //+ // All mutators push onto undo_stack_ (so manual undo covers LLM edits).+ // They emit the appropriate fine-grained signal AND document_changed.+ //+ // Workers should call dispatch_blocking(...) (see helpers below) rather+ // than these directly.++ /// Insert a component. insert_at: -1 = end, otherwise clamped to [0,size].+ /// Returns the assigned stable id.+ int add_component(const report::ReportComponent& comp, int insert_at = -1);++ /// Update content/config by stable id. config replaces (not merges).+ /// Returns true if the id was found.+ bool update_component(int id, const QString& content, const QMap<QString, QString>& config);++ /// Patch update — updates content if non-null, merges config (only the+ /// keys present in `partial_config` are touched).+ bool patch_component(int id, const QString* content_or_null, const QMap<QString, QString>& partial_config);++ /// Remove by stable id. Returns true if removed.+ bool remove_component(int id);++ /// Move by stable id to new index. new_index clamped to [0,size-1].+ bool move_component(int id, int new_index);++ void set_metadata(const report::ReportMetadata& meta);+ void set_theme(const report::ReportTheme& theme);++ /// Apply a built-in template by name (e.g. "Investment Memo"). Clears+ /// the doc, sets metadata, populates components. Pushes a single+ /// macro onto the undo stack.+ void apply_template(const QString& name);++ /// Reset to an empty document.+ void clear_document();++ /// Replace the entire document state (used by load).+ void replace_document(const report::ReportDocument& doc);++ // ── Undo ──────────────────────────────────────────────────────────────────++ QUndoStack* undo_stack();++ /// Open a macro that groups all subsequent mutations under one Ctrl+Z+ /// until end_macro() (or the LLM window timer fires). Re-entrant safe:+ /// nested begin_macro calls just bump a counter.+ void begin_macro(const QString& description);+ void end_macro();++ /// LLM-burst window: tool handlers call note_llm_mutation() which opens+ /// a macro on first call and (re)starts a 400ms timer; on timer expiry+ /// the macro is closed. Result: a chain of LLM mutations within ~400ms+ /// is one Ctrl+Z.+ void note_llm_mutation();++ // ── File ops ──────────────────────────────────────────────────────────────++ Result<void> save_to(const QString& path);+ Result<void> load_from(const QString& path);+ void set_current_file(const QString& path); // updates current_file_ + recent++ // ── Autosave ─────────────────────────────────────────────────────────────++ QString autosave_path() const;+ void trigger_autosave();++ signals:+ // Coarse — fires after any mutation. Screens can hook this for a full+ // re-render. Per-mutation signals fire alongside for incremental updates.+ void document_changed();++ void component_added(int id, int index);+ void component_updated(int id);+ void component_removed(int id, int prior_index);+ void component_moved(int id, int from_index, int to_index);+ void metadata_changed();+ void theme_changed();+ void document_loaded(const QString& path);+ void document_cleared();+ void current_file_changed(const QString& path);++ // Emitted when an LLM-driven mutation is about to happen and the report+ // builder is not currently visible. Listeners (NavigationBar) can react+ // to bring the tab into view.+ void navigate_requested();++ private:+ ReportBuilderService();++ // detail::ServiceFriend bypasses the public mutators (which would push+ // onto undo_stack_ recursively) and writes doc_ directly. It is used+ // exclusively by the QUndoCommand subclasses defined in the .cpp.+ friend class detail::ServiceFriend;++ void push_undo(QUndoCommand* cmd);+ void load_recent() const;+ void save_recent() const;+ void persist_current_file();++ mutable QMutex mutex_;+ report::ReportDocument doc_;+ QUndoStack* undo_stack_;+ QTimer* autosave_timer_;+ QTimer* llm_window_timer_; // single-shot, 400ms; closes the LLM macro+ int macro_depth_ = 0;+ QString current_file_;+ QString autosave_path_;+ mutable QStringList recent_cache_;+ mutable bool recent_loaded_ = false;+};++} // namespace fincept::servicesdiff --git a/fincept-qt/src/services/report_builder/ReportBuilderTemplates.cpp b/fincept-qt/src/services/report_builder/ReportBuilderTemplates.cppnew file mode 100644index 000000000..4b6576fa3--- /dev/null+++ b/fincept-qt/src/services/report_builder/ReportBuilderTemplates.cpp@@ -0,0 +1,637 @@+// ReportBuilderTemplates.cpp — body of ReportBuilderService::apply_template().+//+// Kept in a separate translation unit because the template catalog is+// ~600 lines of literal data and would dominate the service file.++#include "core/report/ReportDocument.h"+#include "services/report_builder/ReportBuilderService.h"++#include <QDateTime>++namespace fincept::services {++namespace rep = report;++void apply_template_to_service(ReportBuilderService* svc, const QString& name) {+ // Build the new document offline, then atomically swap it onto the+ // service via replace_document(). This avoids a flurry of fine-grained+ // signals during template application — the screen just gets one+ // document_changed and re-renders once.++ rep::ReportDocument doc;+ doc.metadata.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");++ auto add = [&](const QString& type, const QString& content = {}, const QMap<QString, QString>& cfg = {}) {+ rep::ReportComponent c;+ c.id = doc.allocate_id();+ c.type = type;+ c.content = content;+ c.config = cfg;+ doc.components.append(c);+ };++ // ── General Purpose ───────────────────────────────────────────────────────++ if (name == "Blank Report") {+ doc.metadata.title = "Untitled Report";+ add("heading", "Title");+ add("text", "Start writing here...");++ } else if (name == "Meeting Notes") {+ doc.metadata.title = "Meeting Notes";+ add("toc");+ add("heading", "Meeting Details");+ add("table", {}, {{"rows", "4"}, {"cols", "2"}});+ add("heading", "Attendees");+ add("list", "Name — Role\nName — Role\nName — Role");+ add("heading", "Agenda");+ add("list", "Item 1\nItem 2\nItem 3");+ add("divider");+ add("heading", "Discussion Points");+ add("text", "Summarise key discussion points here.");+ add("heading", "Decisions Made");+ add("list", "Decision 1\nDecision 2");+ add("heading", "Action Items");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});+ add("heading", "Next Meeting");+ add("text", "Date / time / agenda for next meeting.");++ } else if (name == "Investment Memo") {+ doc.metadata.title = "Investment Memo";+ add("toc");+ add("heading", "Executive Summary");+ add("text", "One-paragraph summary of the investment opportunity and recommendation.");+ add("heading", "Opportunity");+ add("text", "Describe the investment opportunity, market context, and why now.");+ add("heading", "Investment Thesis");+ add("list", "Thesis point 1\nThesis point 2\nThesis point 3");+ add("heading", "Financial Snapshot");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});+ add("heading", "Valuation");+ add("chart", {},+ {{"chart_type", "bar"},+ {"title", "Valuation Scenarios"},+ {"data", "80,100,130"},+ {"labels", "Bear,Base,Bull"}});+ add("heading", "Key Risks");+ add("list", "Risk 1\nRisk 2\nRisk 3");+ add("heading", "Recommendation");+ add("text", "State your recommendation and conviction level.");+ add("divider");+ add("quote", "This memo is for internal use only. Not investment advice.");++ } else if (name == "Stock Research") {+ doc.metadata.title = "Stock Research";+ add("toc");+ add("heading", "Company Overview");+ add("text", "Describe the company, its business model, products/services, and competitive position.");+ add("market_data", {}, {{"symbol", "AAPL"}});+ add("heading", "Financial Highlights");+ add("table", {}, {{"rows", "6"}, {"cols", "4"}});+ add("heading", "Earnings History");+ add("chart", {},+ {{"chart_type", "bar"},+ {"title", "Revenue vs Net Income"},+ {"data", "120,130,145,160"},+ {"labels", "FY21,FY22,FY23,FY24"}});+ add("heading", "Valuation Metrics");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});+ add("heading", "Investment Thesis");+ add("text", "Why you are considering this stock.");+ add("heading", "Risks");+ add("list", "Regulatory\nCompetition\nMacro headwinds\nExecution risk");+ add("heading", "Price Target");+ add("text", "Your price target and timeline.");+ add("divider");+ add("quote", "For personal research purposes only. Not financial advice.");++ } else if (name == "Portfolio Review") {+ doc.metadata.title = "Portfolio Review";+ add("toc");+ add("heading", "Holdings Summary");+ add("table", {}, {{"rows", "8"}, {"cols", "6"}});+ add("heading", "Portfolio Performance");+ add("chart", {},+ {{"chart_type", "line"}, {"title", "Portfolio Value"},+ {"data", "10000,10500,9800,11200,12000,11500,13000"}});+ add("heading", "Asset Allocation");+ add("chart", {},+ {{"chart_type", "pie"}, {"title", "Allocation"},+ {"data", "40,30,20,10"}, {"labels", "Equities,Fixed Income,Crypto,Cash"}});+ add("heading", "Top Performers");+ add("table", {}, {{"rows", "4"}, {"cols", "3"}});+ add("heading", "Underperformers");+ add("table", {}, {{"rows", "4"}, {"cols", "3"}});+ add("heading", "Risk Metrics");+ add("table", {}, {{"rows", "5"}, {"cols", "2"}});+ add("heading", "Notes & Next Steps");+ add("text", "Commentary on portfolio health and planned changes.");++ } else if (name == "Watchlist Report") {+ doc.metadata.title = "Watchlist Report";+ add("heading", "Watchlist Snapshot");+ add("market_data", {}, {{"symbol", "AAPL"}});+ add("market_data", {}, {{"symbol", "MSFT"}});+ add("market_data", {}, {{"symbol", "GOOGL"}});+ add("market_data", {}, {{"symbol", "AMZN"}});+ add("market_data", {}, {{"symbol", "TSLA"}});+ add("divider");+ add("heading", "Watchlist Detail");+ add("table", {}, {{"rows", "8"}, {"cols", "6"}});+ add("heading", "Observations");+ add("text", "Key observations and setup notes for tracked names.");++ } else if (name == "Dividend Income Report") {+ doc.metadata.title = "Dividend Income Report";+ add("toc");+ add("heading", "Dividend Holdings");+ add("table", {}, {{"rows", "8"}, {"cols", "6"}});+ add("heading", "Annual Income Projection");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Monthly Dividend Income"},+ {"data", "200,180,220,210,195,230,215,240,200,220,210,250"},+ {"labels", "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"}});+ add("heading", "Yield by Holding");+ add("chart", {},+ {{"chart_type", "pie"}, {"title", "Income Contribution"},+ {"data", "30,25,20,15,10"}, {"labels", "VZ,T,PFE,KO,MO"}});+ add("heading", "Dividend Calendar");+ add("table", {}, {{"rows", "8"}, {"cols", "4"}});+ add("heading", "Growth Targets");+ add("text", "Target yield, DRIP strategy, and reinvestment notes.");++ } else if (name == "Daily Market Brief") {+ doc.metadata.title = "Daily Market Brief";+ add("heading", "Market Overview");+ add("market_data", {}, {{"symbol", "^GSPC"}});+ add("market_data", {}, {{"symbol", "^DJI"}});+ add("market_data", {}, {{"symbol", "^IXIC"}});+ add("market_data", {}, {{"symbol", "^VIX"}});+ add("market_data", {}, {{"symbol", "DX-Y.NYB"}});+ add("divider");+ add("heading", "Sector Performance");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Sector Returns Today"},+ {"data", "0.5,-0.3,1.2,-0.8,0.4,0.9,-0.2,1.1,0.3,-0.5,0.7"},+ {"labels", "XLK,XLF,XLV,XLE,XLI,XLY,XLP,XLC,XLB,XLU,XLRE"}});+ add("heading", "Top Movers");+ add("table", {}, {{"rows", "7"}, {"cols", "4"}});+ add("heading", "Key Events & News");+ add("text", "Enter today's key market events, earnings, and macro news.");+ add("heading", "Watchlist Levels");+ add("table", {}, {{"rows", "6"}, {"cols", "5"}});+ add("heading", "Commentary");+ add("text", "Market tone, breadth observations, and outlook.");++ } else if (name == "Trade Journal") {+ doc.metadata.title = "Trade Journal";+ add("toc");+ add("heading", "Trade Log");+ add("table", {}, {{"rows", "10"}, {"cols", "8"}});+ add("heading", "P&L Summary");+ add("chart", {},+ {{"chart_type", "line"}, {"title", "Cumulative P&L"},+ {"data", "0,150,-80,320,210,480,390,620"}});+ add("heading", "Statistics");+ add("table", {}, {{"rows", "7"}, {"cols", "2"}});+ add("heading", "Win/Loss Breakdown");+ add("chart", {},+ {{"chart_type", "pie"}, {"title", "Win vs Loss"},+ {"data", "62,38"}, {"labels", "Wins,Losses"}});+ add("heading", "Best Trades");+ add("table", {}, {{"rows", "4"}, {"cols", "5"}});+ add("heading", "Worst Trades");+ add("table", {}, {{"rows", "4"}, {"cols", "5"}});+ add("heading", "Lessons Learned");+ add("text", "What worked, what didn't, and adjustments for next session.");+ add("heading", "Rules Checklist");+ add("list", "Followed entry rules\nRespected stop loss\nDid not revenge trade\nPositioned sized "+ "correctly\nLogged all trades");++ } else if (name == "Technical Analysis") {+ doc.metadata.title = "Technical Analysis";+ add("heading", "Instrument");+ add("market_data", {}, {{"symbol", "AAPL"}});+ add("heading", "Price Chart");+ add("image", {}, {{"width", "700"}, {"caption", "Daily chart — add screenshot here"}, {"align", "center"}});+ add("heading", "Key Levels");+ add("table", {}, {{"rows", "6"}, {"cols", "3"}});+ add("heading", "Indicators");+ add("table", {}, {{"rows", "6"}, {"cols", "3"}});+ add("heading", "Pattern / Setup");+ add("text", "Describe the chart pattern or setup and the rationale.");+ add("heading", "Trade Plan");+ add("table", {}, {{"rows", "4"}, {"cols", "3"}});+ add("heading", "Bias");+ add("quote", "Bullish / Bearish / Neutral — state your directional bias and timeframe.");++ } else if (name == "Pre-Market Checklist") {+ doc.metadata.title = "Pre-Market Checklist";+ add("heading", "Overnight Summary");+ add("market_data", {}, {{"symbol", "ES=F"}});+ add("market_data", {}, {{"symbol", "NQ=F"}});+ add("market_data", {}, {{"symbol", "CL=F"}});+ add("market_data", {}, {{"symbol", "GC=F"}});+ add("divider");+ add("heading", "Economic Calendar");+ add("table", {}, {{"rows", "5"}, {"cols", "4"}});+ add("heading", "Earnings Today");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});+ add("heading", "Key Levels to Watch");+ add("table", {}, {{"rows", "5"}, {"cols", "4"}});+ add("heading", "Planned Trades");+ add("table", {}, {{"rows", "4"}, {"cols", "5"}});+ add("heading", "Risk Parameters");+ add("table", {}, {{"rows", "4"}, {"cols", "2"}});+ add("heading", "Mental Checklist");+ add("list",+ "Reviewed overnight news\nIdentified key levels\nSet max daily loss\nNo FOMO trades\nLog every trade");++ } else if (name == "Equity Research Report") {+ doc.metadata.title = "Equity Research Report";+ add("toc");+ add("heading", "Company Overview");+ add("text", "Business description, history, products/services, and competitive moat.");+ add("market_data", {}, {{"symbol", "AAPL"}});+ add("heading", "Industry & Market");+ add("text", "Industry dynamics, total addressable market, and competitive landscape.");+ add("heading", "Financial Analysis");+ add("table", {}, {{"rows", "8"}, {"cols", "5"}});+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Revenue & EPS Growth"},+ {"data", "100,115,130,148,169"}, {"labels", "FY20,FY21,FY22,FY23,FY24"}});+ add("heading", "Valuation");+ add("table", {}, {{"rows", "5"}, {"cols", "4"}});+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Valuation vs Peers"},+ {"data", "22,18,25,19,28"}, {"labels", "AAPL,MSFT,GOOGL,META,AMZN"}});+ add("heading", "Investment Thesis");+ add("list", "Catalyst 1\nCatalyst 2\nCatalyst 3");+ add("heading", "Risks");+ add("list", "Regulatory risk\nCompetitive pressure\nMacro sensitivity\nExecution risk");+ add("heading", "Rating & Price Target");+ add("table", {}, {{"rows", "3"}, {"cols", "3"}});+ add("divider");+ add("quote", "This report is for informational purposes only. Not investment advice.");++ } else if (name == "Earnings Review") {+ doc.metadata.title = "Earnings Review";+ add("market_data", {}, {{"symbol", "AAPL"}});+ add("heading", "Results vs Estimates");+ add("table", {}, {{"rows", "5"}, {"cols", "4"}});+ add("heading", "Revenue Breakdown");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Revenue by Segment"},+ {"data", "42,18,10,8,6"}, {"labels", "iPhone,Services,Mac,iPad,Wearables"}});+ add("heading", "Margin Analysis");+ add("table", {}, {{"rows", "4"}, {"cols", "3"}});+ add("heading", "Guidance");+ add("table", {}, {{"rows", "4"}, {"cols", "4"}});+ add("heading", "Management Commentary");+ add("text", "Key quotes and commentary from the earnings call.");+ add("heading", "Our Take");+ add("text", "Analysis of results relative to expectations and impact on thesis.");+ add("heading", "Revised Estimates");+ add("table", {}, {{"rows", "4"}, {"cols", "3"}});++ } else if (name == "M&A Deal Summary") {+ doc.metadata.title = "M&A Deal Summary";+ add("toc");+ add("heading", "Deal Overview");+ add("table", {}, {{"rows", "6"}, {"cols", "2"}});+ add("heading", "Strategic Rationale");+ add("list", "Strategic fit\nMarket expansion\nSynergy opportunity\nDefensive rationale");+ add("heading", "Comparable Transactions");+ add("table", {}, {{"rows", "7"}, {"cols", "5"}});+ add("heading", "Synergy Analysis");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Synergy Build-Up ($M)"},+ {"data", "50,120,200,250"}, {"labels", "Yr1,Yr2,Yr3,Yr4"}});+ add("heading", "Valuation Bridge");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});+ add("heading", "Key Risks");+ add("list", "Integration risk\nRegulatory clearance\nCulture clash\nPremium paid\nFinancing risk");+ add("heading", "Timeline");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});+ add("quote", "Deal subject to regulatory approval and shareholder vote.");++ } else if (name == "Sector Deep Dive") {+ doc.metadata.title = "Sector Deep Dive";+ add("toc");+ add("heading", "Sector Overview");+ add("text", "Define the sector, key sub-industries, and economic significance.");+ add("heading", "Market Size & Growth");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Market Size ($B)"},+ {"data", "800,900,1020,1160,1320"}, {"labels", "2020,2021,2022,2023,2024E"}});+ add("heading", "Key Players");+ add("table", {}, {{"rows", "8"}, {"cols", "4"}});+ add("heading", "Competitive Dynamics");+ add("text", "Porter's five forces or similar competitive analysis framework.");+ add("heading", "Structural Trends");+ add("list", "Trend 1\nTrend 2\nTrend 3\nTrend 4");+ add("heading", "Valuation Comparison");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "P/E Ratio by Company"},+ {"data", "22,19,25,17,30"}, {"labels", "Co1,Co2,Co3,Co4,Co5"}});+ add("heading", "Risks & Headwinds");+ add("list", "Regulatory pressure\nTechnology disruption\nCyclicality\nGeopolitical exposure");+ add("heading", "Investment Opportunities");+ add("text", "Best positioned names and sub-themes to play.");++ } else if (name == "Macro Economic Summary") {+ doc.metadata.title = "Macro Economic Summary";+ add("toc");+ add("heading", "Global Snapshot");+ add("table", {}, {{"rows", "6"}, {"cols", "4"}});+ add("heading", "GDP Growth");+ add("chart", {},+ {{"chart_type", "line"}, {"title", "GDP Growth Rate (%)"},+ {"data", "2.1,2.3,1.8,2.5,2.2,1.9,2.4"},+ {"labels", "Q1 23,Q2 23,Q3 23,Q4 23,Q1 24,Q2 24,Q3 24"}});+ add("heading", "Inflation");+ add("chart", {},+ {{"chart_type", "line"}, {"title", "CPI YoY (%)"},+ {"data", "6.0,5.2,4.3,3.7,3.2,2.9,2.6"},+ {"labels", "Q1 23,Q2 23,Q3 23,Q4 23,Q1 24,Q2 24,Q3 24"}});+ add("heading", "Labour Market");+ add("table", {}, {{"rows", "4"}, {"cols", "3"}});+ add("heading", "Central Bank Policy");+ add("table", {}, {{"rows", "6"}, {"cols", "4"}});+ add("heading", "Key Risks to Outlook");+ add("list", "Geopolitical escalation\nCredit tightening\nChina slowdown\nEnergy price shock\nElection uncertainty");+ add("heading", "Outlook");+ add("text", "Macro outlook summary and base-case scenario for the next 6–12 months.");++ } else if (name == "Country Risk Report") {+ doc.metadata.title = "Country Risk Report";+ add("toc");+ add("heading", "Country Overview");+ add("table", {}, {{"rows", "6"}, {"cols", "2"}});+ add("heading", "Political Risk");+ add("text", "Government stability, rule of law, corruption index, and geopolitical exposure.");+ add("heading", "Economic Risk");+ add("table", {}, {{"rows", "6"}, {"cols", "3"}});+ add("chart", {},+ {{"chart_type", "line"}, {"title", "GDP Growth vs Inflation"},+ {"data", "3.0,3.4,2.8,1.9,2.5"}, {"labels", "2020,2021,2022,2023,2024E"}});+ add("heading", "Financial Risk");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});+ add("heading", "Market Risk");+ add("table", {}, {{"rows", "4"}, {"cols", "3"}});+ add("heading", "Overall Risk Rating");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});+ add("heading", "Outlook");+ add("text", "Summary of country risk outlook and key watchpoints.");++ } else if (name == "Central Bank Monitor") {+ doc.metadata.title = "Central Bank Monitor";+ add("heading", "Rate Decisions");+ add("table", {}, {{"rows", "7"}, {"cols", "4"}});+ add("heading", "Rate Path");+ add("chart", {},+ {{"chart_type", "line"}, {"title", "Policy Rate (%)"},+ {"data", "0.25,0.5,1.0,2.0,3.5,4.5,5.25,5.25,5.0"},+ {"labels", "Jan22,Mar22,Jun22,Sep22,Dec22,Mar23,Jun23,Sep23,Dec23"}});+ add("heading", "Forward Guidance Summary");+ add("text", "Summarise the forward guidance from major central banks.");+ add("heading", "Balance Sheet");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Balance Sheet Size ($T)"},+ {"data", "8.9,8.5,8.1,7.8,7.4"},+ {"labels", "Q4 22,Q1 23,Q2 23,Q3 23,Q4 23"}});+ add("heading", "Market Implications");+ add("text", "Impact on equities, bonds, FX, and commodities.");+ add("heading", "Key Upcoming Events");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});++ } else if (name == "Crypto Research Report") {+ doc.metadata.title = "Crypto Research Report";+ add("toc");+ add("heading", "Project Overview");+ add("text", "Describe the project, its purpose, technology, and value proposition.");+ add("market_data", {}, {{"symbol", "BTC-USD"}});+ add("heading", "Tokenomics");+ add("table", {}, {{"rows", "7"}, {"cols", "2"}});+ add("chart", {},+ {{"chart_type", "pie"}, {"title", "Token Distribution"},+ {"data", "20,15,30,25,10"}, {"labels", "Team,Investors,Community,Treasury,Public"}});+ add("heading", "On-Chain Metrics");+ add("table", {}, {{"rows", "6"}, {"cols", "3"}});+ add("heading", "Price History");+ add("chart", {},+ {{"chart_type", "line"}, {"title", "Price (USD)"},+ {"data", "16000,20000,25000,30000,28000,42000,38000,52000"}});+ add("heading", "Competitive Landscape");+ add("text", "Key competitors and differentiation.");+ add("heading", "Risks");+ add("list", "Regulatory risk\nSmart contract bugs\nCompetitor displacement\nLiquidity risk\nTeam/execution risk");+ add("heading", "Investment Thesis");+ add("text", "Thesis, catalysts, and price targets.");+ add("quote", "Crypto assets are highly volatile. This is not financial advice.");++ } else if (name == "DeFi Protocol Analysis") {+ doc.metadata.title = "DeFi Protocol Analysis";+ add("toc");+ add("heading", "Protocol Overview");+ add("text", "What the protocol does, how it works, and what problem it solves.");+ add("heading", "Key Metrics");+ add("table", {}, {{"rows", "7"}, {"cols", "3"}});+ add("heading", "TVL History");+ add("chart", {},+ {{"chart_type", "line"}, {"title", "Total Value Locked ($M)"},+ {"data", "500,800,1200,900,1500,2000,1800,2400"}});+ add("heading", "Revenue & Fees");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Monthly Protocol Revenue ($K)"},+ {"data", "120,150,180,140,200,230,210,250"}});+ add("heading", "Governance & Token");+ add("text", "Token utility, governance rights, staking mechanics, and emission schedule.");+ add("heading", "Risks");+ add("list", "Smart contract exploit\nOracle manipulation\nRegulatory action\nLiquidity "+ "fragmentation\nFork/governance risk");+ add("heading", "Valuation");+ add("text", "P/S, P/TVL, or other relevant DeFi valuation metrics and comparables.");++ } else if (name == "Crypto Portfolio Review") {+ doc.metadata.title = "Crypto Portfolio Review";+ add("heading", "Holdings");+ add("table", {}, {{"rows", "8"}, {"cols", "6"}});+ add("heading", "Current Prices");+ add("market_data", {}, {{"symbol", "BTC-USD"}});+ add("market_data", {}, {{"symbol", "ETH-USD"}});+ add("market_data", {}, {{"symbol", "SOL-USD"}});+ add("heading", "Allocation");+ add("chart", {},+ {{"chart_type", "pie"}, {"title", "Portfolio Allocation"},+ {"data", "50,25,15,10"}, {"labels", "BTC,ETH,SOL,Other"}});+ add("heading", "Performance");+ add("chart", {},+ {{"chart_type", "line"}, {"title", "Portfolio Value (USD)"},+ {"data", "10000,9500,12000,11000,15000,13000,18000"}});+ add("heading", "Notes");+ add("text", "Rebalancing notes, conviction levels, and next moves.");++ } else if (name == "Bond Research Report") {+ doc.metadata.title = "Bond Research Report";+ add("toc");+ add("heading", "Issuer Overview");+ add("text", "Issuer description, business profile, and credit history.");+ add("heading", "Bond Details");+ add("table", {}, {{"rows", "8"}, {"cols", "2"}});+ add("heading", "Credit Profile");+ add("table", {}, {{"rows", "5"}, {"cols", "4"}});+ add("heading", "Yield Analysis");+ add("chart", {},+ {{"chart_type", "line"}, {"title", "Yield vs Benchmark"},+ {"data", "3.0,3.2,3.5,3.8,4.1,4.3,4.0"},+ {"labels", "Jan,Feb,Mar,Apr,May,Jun,Jul"}});+ add("heading", "Duration & Convexity");+ add("table", {}, {{"rows", "4"}, {"cols", "2"}});+ add("heading", "Comparable Bonds");+ add("table", {}, {{"rows", "5"}, {"cols", "5"}});+ add("heading", "Recommendation");+ add("text", "Buy / Hold / Sell with rationale and target spread.");++ } else if (name == "Yield Curve Analysis") {+ doc.metadata.title = "Yield Curve Analysis";+ add("heading", "Yield Curve Shape");+ add("chart", {},+ {{"chart_type", "line"}, {"title", "US Treasury Yield Curve"},+ {"data", "5.3,5.1,4.9,4.7,4.6,4.5,4.4,4.3"},+ {"labels", "3M,6M,1Y,2Y,3Y,5Y,10Y,30Y"}});+ add("heading", "Key Spreads");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});+ add("heading", "Historical Comparison");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "10Y-2Y Spread (bps)"},+ {"data", "-80,-60,-40,-20,5,15,30"},+ {"labels", "Oct23,Nov23,Dec23,Jan24,Feb24,Mar24,Apr24"}});+ add("heading", "Duration & Convexity");+ add("table", {}, {{"rows", "4"}, {"cols", "3"}});+ add("heading", "Macro Drivers");+ add("text", "Explain the key macro factors driving current curve shape.");+ add("heading", "Implications");+ add("list",+ "Recession signal interpretation\nFed policy implications\nSector rotation impact\nCurrency effects");++ } else if (name == "Quant Strategy Report") {+ doc.metadata.title = "Quant Strategy Report";+ add("toc");+ add("heading", "Strategy Description");+ add("text", "Describe the strategy, signal generation logic, universe, and execution rules.");+ add("heading", "Backtest Parameters");+ add("table", {}, {{"rows", "6"}, {"cols", "2"}});+ add("heading", "Performance Summary");+ add("table", {}, {{"rows", "8"}, {"cols", "2"}});+ add("heading", "Equity Curve");+ add("chart", {},+ {{"chart_type", "line"}, {"title", "Strategy vs Benchmark"},+ {"data", "100,108,115,112,124,131,128,142,150"},+ {"labels", "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep"}});+ add("heading", "Drawdown Analysis");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Monthly Drawdowns (%)"},+ {"data", "0,-2.1,-0.5,-3.2,-1.1,0,-1.8,-0.4,0"}});+ add("heading", "Factor Exposure");+ add("table", {}, {{"rows", "6"}, {"cols", "3"}});+ add("heading", "Stress Tests");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});+ add("heading", "Limitations & Risks");+ add("list",+ "Overfitting risk\nTransaction cost sensitivity\nRegime change\nCapacity constraints\nData snooping bias");++ } else if (name == "Risk Management Report") {+ doc.metadata.title = "Risk Management Report";+ add("toc");+ add("heading", "Portfolio Risk Summary");+ add("table", {}, {{"rows", "6"}, {"cols", "2"}});+ add("heading", "VaR Analysis");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "VaR by Confidence Level"},+ {"data", "1.2,1.8,2.5,3.1"}, {"labels", "90%,95%,99%,99.9%"}});+ add("heading", "Stress Test Results");+ add("table", {}, {{"rows", "7"}, {"cols", "3"}});+ add("heading", "Correlation Matrix");+ add("text", "Paste or describe key pairwise correlations between holdings.");+ add("heading", "Concentration Risk");+ add("chart", {},+ {{"chart_type", "pie"}, {"title", "Position Concentration"},+ {"data", "25,20,18,15,12,10"},+ {"labels", "Pos1,Pos2,Pos3,Pos4,Pos5,Other"}});+ add("heading", "Liquidity Risk");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});+ add("heading", "Recommendations");+ add("list", "Reduce concentration in top 3 positions\nAdd hedges for macro exposure\nReview stop-loss "+ "levels\nRebalance sector exposure");++ } else if (name == "Business Performance") {+ doc.metadata.title = "Business Performance Report";+ add("toc");+ add("heading", "Executive Summary");+ add("text", "One-paragraph summary of business performance this period.");+ add("heading", "Key Performance Indicators");+ add("table", {}, {{"rows", "8"}, {"cols", "4"}});+ add("heading", "Revenue");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Revenue ($M)"},+ {"data", "42,45,48,44,51,53,50,55"},+ {"labels", "Q1 22,Q2 22,Q3 22,Q4 22,Q1 23,Q2 23,Q3 23,Q4 23"}});+ add("heading", "Cost Breakdown");+ add("chart", {},+ {{"chart_type", "pie"}, {"title", "Cost Structure"},+ {"data", "40,25,20,15"}, {"labels", "COGS,R&D,S&M,G&A"}});+ add("heading", "Department Performance");+ add("table", {}, {{"rows", "6"}, {"cols", "4"}});+ add("heading", "Targets vs Actuals");+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Target vs Actual"},+ {"data", "100,95,100,102,100,88"},+ {"labels", "Jan,Feb,Mar,Apr,May,Jun"}});+ add("heading", "Issues & Risks");+ add("list", "Issue 1\nIssue 2\nIssue 3");+ add("heading", "Next Period Targets");+ add("table", {}, {{"rows", "5"}, {"cols", "3"}});++ } else if (name == "Project Status Report") {+ doc.metadata.title = "Project Status Report";+ add("heading", "Project Overview");+ add("table", {}, {{"rows", "5"}, {"cols", "2"}});+ add("heading", "Overall Status");+ add("table", {}, {{"rows", "4"}, {"cols", "3"}});+ add("heading", "Milestones");+ add("table", {}, {{"rows", "7"}, {"cols", "4"}});+ add("heading", "Progress This Period");+ add("text", "Summarise completed work and progress against plan.");+ add("heading", "Issues & Blockers");+ add("table", {}, {{"rows", "5"}, {"cols", "4"}});+ add("heading", "Risks");+ add("table", {}, {{"rows", "5"}, {"cols", "4"}});+ add("heading", "Next Steps");+ add("list", "Action 1 — Owner — Due date\nAction 2 — Owner — Due date\nAction 3 — Owner — Due date");++ } else if (name == "Financial Statement") {+ doc.metadata.title = "Financial Statement";+ add("toc");+ add("heading", "Income Statement");+ add("table", {}, {{"rows", "12"}, {"cols", "4"}});+ add("chart", {},+ {{"chart_type", "bar"}, {"title", "Revenue & Net Income"},+ {"data", "400,450,500,420,480,530"},+ {"labels", "H1 22,H2 22,H1 23,H2 23,H1 24,H2 24"}});+ add("page_break");+ add("heading", "Balance Sheet");+ add("table", {}, {{"rows", "14"}, {"cols", "3"}});+ add("page_break");+ add("heading", "Cash Flow Statement");+ add("table", {}, {{"rows", "12"}, {"cols", "3"}});+ add("heading", "Key Ratios");+ add("table", {}, {{"rows", "8"}, {"cols", "3"}});+ add("divider");+ add("quote", "Prepared in accordance with applicable accounting standards.");+ }++ svc->replace_document(doc);+}++} // namespace fincept::servicesdiff --git a/fincept-qt/src/services/wallet/ConnectWalletDialog.cpp b/fincept-qt/src/services/wallet/ConnectWalletDialog.cppnew file mode 100644index 000000000..d4a662359--- /dev/null+++ b/fincept-qt/src/services/wallet/ConnectWalletDialog.cpp@@ -0,0 +1,164 @@+#include "services/wallet/ConnectWalletDialog.h"++#include "core/logging/Logger.h"+#include "services/wallet/Ed25519Verifier.h"+#include "services/wallet/LocalWalletBridge.h"++#include <QByteArray>+#include <QCloseEvent>+#include <QDesktopServices>+#include <QHBoxLayout>+#include <QLabel>+#include <QPushButton>+#include <QRandomGenerator>+#include <QShowEvent>+#include <QUrl>+#include <QVBoxLayout>++namespace fincept::wallet {++namespace {++QByteArray make_random_nonce() {+ QByteArray buf;+ buf.resize(32);+ QRandomGenerator::system()->generate(reinterpret_cast<quint32*>(buf.data()),+ reinterpret_cast<quint32*>(buf.data() + buf.size()));+ return buf.toHex();+}++} // namespace++ConnectWalletDialog::ConnectWalletDialog(QWidget* parent) : QDialog(parent) {+ setWindowTitle(tr("Connect Wallet"));+ setModal(true);+ resize(440, 220);++ auto* layout = new QVBoxLayout(this);+ layout->setContentsMargins(24, 20, 24, 20);+ layout->setSpacing(12);++ auto* title = new QLabel(tr("Connect your Solana wallet"), this);+ title->setObjectName(QStringLiteral("walletDialogTitle"));+ layout->addWidget(title);++ status_label_ = new QLabel(this);+ status_label_->setObjectName(QStringLiteral("walletDialogStatus"));+ status_label_->setWordWrap(true);+ status_label_->setText(tr("Opening your browser to complete the handshake…"));+ layout->addWidget(status_label_);++ layout->addStretch(1);++ auto* row = new QHBoxLayout;+ row->setSpacing(8);+ reopen_button_ = new QPushButton(tr("Reopen browser"), this);+ cancel_button_ = new QPushButton(tr("Cancel"), this);+ cancel_button_->setObjectName(QStringLiteral("walletDialogCancel"));+ row->addStretch(1);+ row->addWidget(reopen_button_);+ row->addWidget(cancel_button_);+ layout->addLayout(row);++ connect(cancel_button_, &QPushButton::clicked, this, [this]() {+ fail_and_close(tr("cancelled by user"));+ });+ connect(reopen_button_, &QPushButton::clicked, this, [this]() {+ if (!last_open_url_.isEmpty()) {+ QDesktopServices::openUrl(QUrl(last_open_url_));+ }+ });+}++ConnectWalletDialog::~ConnectWalletDialog() = default;++void ConnectWalletDialog::showEvent(QShowEvent* e) {+ QDialog::showEvent(e);+ if (!bridge_) {+ start_handshake();+ }+}++void ConnectWalletDialog::closeEvent(QCloseEvent* e) {+ if (bridge_) {+ bridge_->stop();+ }+ QDialog::closeEvent(e);+}++void ConnectWalletDialog::start_handshake() {+ nonce_hex_ = make_random_nonce();+ expected_message_ = QByteArrayLiteral(+ "Fincept Terminal wallet-connect challenge. Nonce: ") + nonce_hex_;++ bridge_ = new LocalWalletBridge(this);+ connect(bridge_, &LocalWalletBridge::connect_payload, this,+ &ConnectWalletDialog::on_payload);+ connect(bridge_, &LocalWalletBridge::timed_out, this,+ &ConnectWalletDialog::on_timed_out);+ connect(bridge_, &LocalWalletBridge::bridge_error, this,+ &ConnectWalletDialog::on_bridge_error);++ last_open_url_ = bridge_->start(nonce_hex_, /*timeout_seconds=*/120);+ if (last_open_url_.isEmpty()) {+ fail_and_close(tr("could not start local bridge server"));+ return;+ }+ QDesktopServices::openUrl(QUrl(last_open_url_));+ status_label_->setText(+ tr("Browser opened. Approve the connection and the signature in your wallet."));+}++void ConnectWalletDialog::on_payload(QString pubkey, QString signature, QString label) {+ LOG_INFO("ConnectWalletDialog",+ QStringLiteral("on_payload: pubkey=%1 sig_chars=%2 label=%3 msg_len=%4")+ .arg(pubkey)+ .arg(signature.size())+ .arg(label)+ .arg(expected_message_.size()));+ if (handshake_done_) {+ LOG_WARN("ConnectWalletDialog", "ignoring late payload (handshake already done)");+ return;+ }+ if (!Ed25519Verifier::verify(pubkey, expected_message_, signature)) {+ LOG_WARN("ConnectWalletDialog",+ QStringLiteral("signature verification FAILED. pubkey=%1 sig=%2 msg_first40='%3'")+ .arg(pubkey)+ .arg(signature)+ .arg(QString::fromUtf8(expected_message_.left(40))));+ fail_and_close(tr("signature verification failed"));+ return;+ }+ handshake_done_ = true;+ if (bridge_) {+ bridge_->stop();+ }+ LOG_INFO("ConnectWalletDialog", "Handshake verified for " + pubkey + " (" + label + ")");+ emit connected(pubkey, label);+ accept();+}++void ConnectWalletDialog::on_timed_out() {+ if (handshake_done_) {+ return;+ }+ fail_and_close(tr("timed out waiting for browser callback"));+}++void ConnectWalletDialog::on_bridge_error(QString message) {+ fail_and_close(tr("bridge error: %1").arg(message));+}++void ConnectWalletDialog::fail_and_close(const QString& reason) {+ if (handshake_done_) {+ return;+ }+ handshake_done_ = true;+ if (bridge_) {+ bridge_->stop();+ }+ emit failed(reason);+ reject();+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/ConnectWalletDialog.h b/fincept-qt/src/services/wallet/ConnectWalletDialog.hnew file mode 100644index 000000000..2145939e4--- /dev/null+++ b/fincept-qt/src/services/wallet/ConnectWalletDialog.h@@ -0,0 +1,47 @@+#pragma once++#include <QDialog>+#include <QString>++class QLabel;+class QPushButton;++namespace fincept::wallet {++class LocalWalletBridge;++/// Modal dialog that owns a LocalWalletBridge, opens the user's default+/// browser to the bridge URL, and emits `connected(pubkey, label)` once a+/// valid signed-message handshake completes.+class ConnectWalletDialog : public QDialog {+ Q_OBJECT+ public:+ explicit ConnectWalletDialog(QWidget* parent = nullptr);+ ~ConnectWalletDialog() override;++ signals:+ void connected(QString pubkey_b58, QString label);+ void failed(QString reason);++ protected:+ void showEvent(QShowEvent* e) override;+ void closeEvent(QCloseEvent* e) override;++ private:+ void start_handshake();+ void on_payload(QString pubkey, QString signature, QString label);+ void on_timed_out();+ void on_bridge_error(QString message);+ void fail_and_close(const QString& reason);++ LocalWalletBridge* bridge_ = nullptr;+ QByteArray nonce_hex_;+ QByteArray expected_message_;+ QLabel* status_label_ = nullptr;+ QPushButton* cancel_button_ = nullptr;+ QPushButton* reopen_button_ = nullptr;+ QString last_open_url_;+ bool handshake_done_ = false;+};++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/Ed25519Verifier.cpp b/fincept-qt/src/services/wallet/Ed25519Verifier.cppnew file mode 100644index 000000000..941574580--- /dev/null+++ b/fincept-qt/src/services/wallet/Ed25519Verifier.cpp@@ -0,0 +1,147 @@+#include "services/wallet/Ed25519Verifier.h"++#include "core/logging/Logger.h"++#include <QByteArray>++extern "C" {+#include "ed25519.h"+}++#include <array>+#include <cstring>++namespace fincept::wallet {++namespace {++constexpr const char* kBase58Alphabet =+ "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";++// Build a reverse-lookup table once. -1 indicates an invalid character.+std::array<int8_t, 256> build_b58_table() {+ std::array<int8_t, 256> table{};+ table.fill(-1);+ for (int i = 0; i < 58; ++i) {+ table[static_cast<unsigned char>(kBase58Alphabet[i])] = static_cast<int8_t>(i);+ }+ return table;+}++const std::array<int8_t, 256>& b58_table() {+ static const std::array<int8_t, 256> table = build_b58_table();+ return table;+}++} // namespace++QByteArray Ed25519Verifier::decode_base58(const QString& s) noexcept {+ if (s.isEmpty()) {+ return {};+ }+ const QByteArray ascii = s.toLatin1();+ const auto& table = b58_table();++ // Count leading '1's — each represents a leading zero byte.+ int zeros = 0;+ while (zeros < ascii.size() && ascii[zeros] == '1') {+ ++zeros;+ }++ // Allocate enough room for the worst-case decode: ceil(N * log(58) / log(256)).+ std::vector<unsigned char> b256(static_cast<size_t>(ascii.size() * 733 / 1000 + 1), 0);+ int b256_len = 0;++ for (int i = zeros; i < ascii.size(); ++i) {+ const int8_t carry_seed = table[static_cast<unsigned char>(ascii[i])];+ if (carry_seed < 0) {+ return {}; // invalid character+ }+ int carry = carry_seed;+ for (int j = 0; j < b256_len || carry; ++j) {+ if (j == static_cast<int>(b256.size())) {+ return {}; // overflow guard+ }+ carry += 58 * b256[b256.size() - 1 - j];+ b256[b256.size() - 1 - j] = static_cast<unsigned char>(carry & 0xff);+ carry >>= 8;+ if (j >= b256_len) {+ b256_len = j + 1;+ }+ }+ }++ QByteArray out;+ out.reserve(zeros + b256_len);+ for (int i = 0; i < zeros; ++i) {+ out.append('\0');+ }+ out.append(reinterpret_cast<const char*>(b256.data() + b256.size() - b256_len),+ b256_len);+ return out;+}++QString Ed25519Verifier::encode_base58(const QByteArray& bytes) {+ if (bytes.isEmpty()) {+ return {};+ }+ int zeros = 0;+ while (zeros < bytes.size() && bytes[zeros] == '\0') {+ ++zeros;+ }++ std::vector<unsigned char> b58(static_cast<size_t>(bytes.size() * 138 / 100 + 1), 0);+ int b58_len = 0;++ for (int i = zeros; i < bytes.size(); ++i) {+ int carry = static_cast<unsigned char>(bytes[i]);+ for (int j = 0; j < b58_len || carry; ++j) {+ if (j == static_cast<int>(b58.size())) {+ b58.push_back(0);+ }+ carry += 256 * b58[b58.size() - 1 - j];+ b58[b58.size() - 1 - j] = static_cast<unsigned char>(carry % 58);+ carry /= 58;+ if (j >= b58_len) {+ b58_len = j + 1;+ }+ }+ }++ QString out;+ out.reserve(zeros + b58_len);+ for (int i = 0; i < zeros; ++i) {+ out.append(QLatin1Char('1'));+ }+ for (int i = static_cast<int>(b58.size()) - b58_len; i < static_cast<int>(b58.size()); ++i) {+ out.append(QLatin1Char(kBase58Alphabet[b58[i]]));+ }+ return out;+}++bool Ed25519Verifier::verify(const QString& pubkey_b58,+ const QByteArray& message,+ const QString& signature_b58) noexcept {+ const QByteArray pubkey = decode_base58(pubkey_b58);+ if (pubkey.size() != 32) {+ LOG_WARN("WalletVerify", "Invalid pubkey length: " + QString::number(pubkey.size()));+ return false;+ }+ const QByteArray signature = decode_base58(signature_b58);+ if (signature.size() != 64) {+ LOG_WARN("WalletVerify", "Invalid signature length: " + QString::number(signature.size()));+ return false;+ }+ if (message.isEmpty()) {+ return false;+ }++ const int ok = ::ed25519_verify(+ reinterpret_cast<const unsigned char*>(signature.constData()),+ reinterpret_cast<const unsigned char*>(message.constData()),+ static_cast<size_t>(message.size()),+ reinterpret_cast<const unsigned char*>(pubkey.constData()));+ return ok == 1;+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/Ed25519Verifier.h b/fincept-qt/src/services/wallet/Ed25519Verifier.hnew file mode 100644index 000000000..d53344e3a--- /dev/null+++ b/fincept-qt/src/services/wallet/Ed25519Verifier.h@@ -0,0 +1,33 @@+#pragma once++#include <QByteArray>+#include <QString>++namespace fincept::wallet {++/// Verifies an Ed25519 signature against a message and a Solana public key.+///+/// All inputs are base58-encoded as Solana wallets emit them. The implementation+/// decodes base58 and delegates to the orlp/ed25519 reference implementation.+///+/// This is consulted **only** during the wallet-connect handshake to prove that+/// the user controls the private key behind the claimed public key. We never+/// store, transmit, or accept private keys.+class Ed25519Verifier {+ public:+ /// Returns true iff `signature_b58` is a valid Ed25519 signature of+ /// `message` produced by the private key paired with `pubkey_b58`.+ /// Returns false on any decode error or verification failure — never throws.+ static bool verify(const QString& pubkey_b58,+ const QByteArray& message,+ const QString& signature_b58) noexcept;++ /// Decodes a base58 string. Returns empty QByteArray on invalid input.+ /// Exposed for tests and for SolanaRpcClient (mint addresses are b58).+ static QByteArray decode_base58(const QString& s) noexcept;++ /// Encodes a byte array as base58. Used to log/display pubkeys.+ static QString encode_base58(const QByteArray& bytes);+};++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/LocalWalletBridge.cpp b/fincept-qt/src/services/wallet/LocalWalletBridge.cppnew file mode 100644index 000000000..ed21cce1b--- /dev/null+++ b/fincept-qt/src/services/wallet/LocalWalletBridge.cpp@@ -0,0 +1,318 @@+#include "services/wallet/LocalWalletBridge.h"++#include "core/logging/Logger.h"++#include <QByteArray>+#include <QCoreApplication>+#include <QFile>+#include <QHostAddress>+#include <QJsonDocument>+#include <QJsonObject>+#include <QRandomGenerator>+#include <QTcpServer>+#include <QTcpSocket>+#include <QTimerEvent>+#include <QUrl>+#include <QUrlQuery>++namespace fincept::wallet {++namespace {++QByteArray random_token_hex(int n_bytes) {+ QByteArray buf;+ buf.resize(n_bytes);+ QRandomGenerator::system()->generate(reinterpret_cast<quint32*>(buf.data()),+ reinterpret_cast<quint32*>(buf.data() + n_bytes));+ return buf.toHex();+}++QByteArray load_connect_html() {+ // Resources are copied beside the executable at build time:+ // $<TARGET_FILE_DIR:FinceptTerminal>/resources/wallet/connect.html+ const QString path =+ QCoreApplication::applicationDirPath() + QStringLiteral("/resources/wallet/connect.html");+ QFile f(path);+ if (!f.open(QIODevice::ReadOnly)) {+ LOG_WARN("WalletBridge", "connect.html not found at " + path);+ return {};+ }+ return f.readAll();+}++bool path_starts_with(const QByteArray& path, const char* prefix) {+ return path.startsWith(QByteArray::fromRawData(prefix, qstrlen(prefix)));+}++QByteArray query_param(const QByteArray& path, const char* key) {+ const auto idx = path.indexOf('?');+ if (idx < 0) {+ return {};+ }+ QUrlQuery q(QString::fromLatin1(path.mid(idx + 1)));+ return q.queryItemValue(QString::fromLatin1(key)).toLatin1();+}++} // namespace++LocalWalletBridge::LocalWalletBridge(QObject* parent) : QObject(parent) {}++LocalWalletBridge::~LocalWalletBridge() {+ stop();+}++QString LocalWalletBridge::start(const QByteArray& nonce_hex, int timeout_seconds) {+ stop();+ nonce_hex_ = nonce_hex;+ connect_token_ = random_token_hex(16);++ server_ = new QTcpServer(this);+ connect(server_, &QTcpServer::newConnection, this, &LocalWalletBridge::on_new_connection);++ if (!server_->listen(QHostAddress::LocalHost, 0)) {+ const QString err = server_->errorString();+ LOG_ERROR("WalletBridge", "listen() failed: " + err);+ emit bridge_error(err);+ stop();+ return {};+ }+ const quint16 port = server_->serverPort();+ LOG_INFO("WalletBridge",+ QStringLiteral("listening on 127.0.0.1:%1 (timeout %2s)")+ .arg(port)+ .arg(timeout_seconds));++ if (timer_id_ != 0) {+ killTimer(timer_id_);+ }+ timer_id_ = startTimer(timeout_seconds * 1000);++ return QStringLiteral("http://127.0.0.1:%1/connect?token=%2")+ .arg(port)+ .arg(QString::fromLatin1(connect_token_));+}++void LocalWalletBridge::stop() {+ if (timer_id_ != 0) {+ killTimer(timer_id_);+ timer_id_ = 0;+ }+ if (server_) {+ server_->close();+ server_->deleteLater();+ server_ = nullptr;+ }+ connect_token_.clear();+ nonce_hex_.clear();+}++bool LocalWalletBridge::is_listening() const noexcept {+ return server_ != nullptr && server_->isListening();+}++void LocalWalletBridge::timerEvent(QTimerEvent* e) {+ if (e->timerId() == timer_id_) {+ LOG_WARN("WalletBridge", "timed out before callback");+ emit timed_out();+ stop();+ }+}++void LocalWalletBridge::on_new_connection() {+ if (!server_) {+ return;+ }+ while (auto* socket = server_->nextPendingConnection()) {+ connect(socket, &QTcpSocket::disconnected, socket, &QObject::deleteLater);+ connect(socket, &QTcpSocket::readyRead, this, [this, socket]() {+ // Read full request: headers terminated by \r\n\r\n, body length from+ // Content-Length. Solana wallet POSTs are small (< 4KB) so a 32KB+ // cap is plenty and protects against runaway uploads.+ static constexpr int kMaxRequestBytes = 32 * 1024;+ const QByteArray buf = socket->peek(kMaxRequestBytes);+ const int header_end = buf.indexOf("\r\n\r\n");+ if (header_end < 0) {+ if (buf.size() >= kMaxRequestBytes) {+ write_response(socket, 413, "text/plain", "request too large");+ socket->disconnectFromHost();+ }+ return; // wait for more bytes+ }+ const QByteArray header_block = buf.left(header_end);+ int content_length = 0;+ for (const auto& line : header_block.split('\n')) {+ const auto trimmed = line.trimmed();+ if (trimmed.toLower().startsWith("content-length:")) {+ content_length = trimmed.mid(15).trimmed().toInt();+ break;+ }+ }+ const int total_required = header_end + 4 + content_length;+ if (buf.size() < total_required) {+ return; // wait for body+ }+ socket->read(total_required); // drain peek window from buffer++ const auto first_line = header_block.split('\n').value(0).trimmed();+ const auto parts = first_line.split(' ');+ if (parts.size() < 2) {+ write_response(socket, 400, "text/plain", "bad request");+ socket->disconnectFromHost();+ return;+ }+ const QByteArray method = parts.value(0);+ const QByteArray path = parts.value(1);+ const QByteArray body = buf.mid(header_end + 4, content_length);+ handle_request(socket, first_line, body, path, method);+ });+ }+}++void LocalWalletBridge::handle_request(QTcpSocket* socket,+ const QByteArray& /*request_line*/,+ const QByteArray& body,+ const QByteArray& path,+ const QByteArray& method) {+ LOG_INFO("WalletBridge",+ QStringLiteral("request %1 %2 (body=%3 bytes)")+ .arg(QString::fromLatin1(method))+ .arg(QString::fromLatin1(path))+ .arg(body.size()));++ // CORS preflight: respond 204 without checking token (token is in the+ // query string of the actual POST, which the browser hasn't yet sent).+ if (method == "OPTIONS") {+ write_response(socket, 204, "text/plain", QByteArray());+ socket->disconnectFromHost();+ return;+ }++ // Browser auto-requests /favicon.ico without our token; respond cleanly+ // so it doesn't pollute logs with token-mismatch warnings.+ if (method == "GET" && path == "/favicon.ico") {+ write_response(socket, 204, "image/x-icon", QByteArray());+ socket->disconnectFromHost();+ return;+ }++ const auto token_in_query = query_param(path, "token");+ if (token_in_query != connect_token_) {+ LOG_WARN("WalletBridge",+ QStringLiteral("token mismatch on %1 (got %2 chars)")+ .arg(QString::fromLatin1(path))+ .arg(token_in_query.size()));+ write_response(socket, 403, "text/plain", "forbidden");+ socket->disconnectFromHost();+ return;+ }++ if (method == "GET" && path_starts_with(path, "/connect")) {+ const auto html = render_connect_page();+ LOG_INFO("WalletBridge",+ QStringLiteral("served connect.html (%1 bytes)").arg(html.size()));+ write_response(socket, 200, "text/html; charset=utf-8", html);+ socket->disconnectFromHost();+ return;+ }++ if (method == "POST" && path_starts_with(path, "/log")) {+ // Browser-side diagnostics — JS can POST {"level":"info","msg":"..."} here.+ QJsonParseError pe;+ const auto doc = QJsonDocument::fromJson(body, &pe);+ if (pe.error == QJsonParseError::NoError && doc.isObject()) {+ const auto obj = doc.object();+ const auto level = obj.value(QStringLiteral("level")).toString();+ const auto msg = obj.value(QStringLiteral("msg")).toString();+ if (level == QStringLiteral("error")) {+ LOG_ERROR("WalletPage", msg);+ } else if (level == QStringLiteral("warn")) {+ LOG_WARN("WalletPage", msg);+ } else {+ LOG_INFO("WalletPage", msg);+ }+ }+ write_response(socket, 200, "application/json", QByteArrayLiteral("{\"ok\":true}"));+ socket->disconnectFromHost();+ return;+ }++ if (method == "POST" && path_starts_with(path, "/callback")) {+ QJsonParseError pe;+ const auto doc = QJsonDocument::fromJson(body, &pe);+ if (pe.error != QJsonParseError::NoError || !doc.isObject()) {+ write_response(socket, 400, "text/plain", "invalid json");+ socket->disconnectFromHost();+ return;+ }+ const auto obj = doc.object();+ const auto pubkey = obj.value(QStringLiteral("pubkey")).toString();+ const auto sig = obj.value(QStringLiteral("signature")).toString();+ const auto label = obj.value(QStringLiteral("label")).toString();+ if (pubkey.isEmpty() || sig.isEmpty()) {+ write_response(socket, 400, "text/plain", "missing fields");+ socket->disconnectFromHost();+ return;+ }+ LOG_INFO("WalletBridge",+ QStringLiteral("callback received: pubkey=%1 sig_len=%2 label=%3")+ .arg(pubkey.left(8) + QStringLiteral("…"))+ .arg(sig.size())+ .arg(label));+ write_response(socket, 200, "application/json", QByteArrayLiteral("{\"ok\":true}"));+ socket->disconnectFromHost();++ emit connect_payload(pubkey, sig, label.isEmpty() ? QStringLiteral("wallet") : label);+ // The dialog will call stop() once it has consumed the payload.+ return;+ }++ write_response(socket, 404, "text/plain", "not found");+ socket->disconnectFromHost();+}++QByteArray LocalWalletBridge::render_connect_page() const {+ QByteArray html = load_connect_html();+ if (html.isEmpty()) {+ // Fall back to a minimal inline page if the resource isn't bundled.+ html =+ "<!doctype html><html><body><h2>connect.html missing in resources</h2>"+ "</body></html>";+ }+ html.replace("__NONCE_HEX__", nonce_hex_);+ html.replace("__CALLBACK_TOKEN__", connect_token_);+ return html;+}++void LocalWalletBridge::write_response(QTcpSocket* socket, int status,+ const QByteArray& content_type,+ const QByteArray& body) {+ QByteArray status_text;+ switch (status) {+ case 200: status_text = "OK"; break;+ case 400: status_text = "Bad Request"; break;+ case 403: status_text = "Forbidden"; break;+ case 404: status_text = "Not Found"; break;+ case 413: status_text = "Payload Too Large"; break;+ default: status_text = "Error"; break;+ }+ QByteArray response;+ response.append("HTTP/1.1 " + QByteArray::number(status) + " " + status_text + "\r\n");+ response.append("Content-Type: " + content_type + "\r\n");+ response.append("Content-Length: " + QByteArray::number(body.size()) + "\r\n");+ response.append("Connection: close\r\n");+ response.append("Cache-Control: no-store\r\n");+ response.append("X-Content-Type-Options: nosniff\r\n");+ response.append("Referrer-Policy: no-referrer\r\n");+ // Same-origin in practice (page + fetch both served by us), but some+ // browsers (and some Phantom builds) trip on missing CORS for any+ // localhost POST. Echoing the page's own origin keeps it safe.+ response.append("Access-Control-Allow-Origin: *\r\n");+ response.append("Access-Control-Allow-Headers: Content-Type\r\n");+ response.append("Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n");+ response.append("\r\n");+ response.append(body);+ socket->write(response);+ socket->flush();+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/LocalWalletBridge.h b/fincept-qt/src/services/wallet/LocalWalletBridge.hnew file mode 100644index 000000000..0fa5e1d76--- /dev/null+++ b/fincept-qt/src/services/wallet/LocalWalletBridge.h@@ -0,0 +1,75 @@+#pragma once++#include <QByteArray>+#include <QObject>+#include <QString>++class QTcpServer;+class QTcpSocket;++namespace fincept::wallet {++/// Tiny single-purpose HTTP server bound to 127.0.0.1 used during wallet-connect.+///+/// Lifecycle:+/// 1. start(nonce) — picks a random ephemeral port, listens on loopback only,+/// generates a single-use connect_token, returns the URL the user's+/// browser should open.+/// 2. The browser hits GET /connect?token=... → we serve connect.html.+/// 3. Browser-side JS prompts the wallet, signs the nonce, then POSTs the+/// payload {pubkey, signature, label} to /callback?token=....+/// 4. The bridge fires `connect_payload(...)`, replies 200 to the browser,+/// and stops listening.+/// 5. After timeout_seconds with no callback, the server stops and emits+/// `timed_out()`.+///+/// Security:+/// - listens only on QHostAddress::LocalHost (no LAN, no public).+/// - random port, random connect_token (32 bytes hex) bound to one connect.+/// - any request with a missing/wrong token is rejected with 403.+/// - server self-destructs after success or timeout.+/// - never speaks HTTP/2, never allows CORS, never serves anything besides+/// the embedded connect page and a tiny 200 OK on /callback.+class LocalWalletBridge : public QObject {+ Q_OBJECT+ public:+ explicit LocalWalletBridge(QObject* parent = nullptr);+ ~LocalWalletBridge() override;++ /// Spins up the server. Returns the URL to open in the user's browser, or+ /// an empty string if listen() failed.+ QString start(const QByteArray& nonce_hex, int timeout_seconds = 120);++ /// Stops the server immediately. Idempotent.+ void stop();++ /// True if the server is currently listening for the callback.+ bool is_listening() const noexcept;++ signals:+ /// Fired once when /callback receives a valid POST payload.+ void connect_payload(QString pubkey_b58, QString signature_b58, QString wallet_label);+ /// Fired if no callback arrived within timeout_seconds.+ void timed_out();+ /// Fired on internal errors (port bind failure, parse error, etc.)+ void bridge_error(QString message);++ private:+ void on_new_connection();+ void handle_request(QTcpSocket* socket, const QByteArray& request_line,+ const QByteArray& body, const QByteArray& path,+ const QByteArray& method);+ QByteArray render_connect_page() const;+ void write_response(QTcpSocket* socket, int status, const QByteArray& content_type,+ const QByteArray& body);++ QTcpServer* server_ = nullptr;+ QByteArray nonce_hex_;+ QByteArray connect_token_;+ int timer_id_ = 0;++ protected:+ void timerEvent(QTimerEvent* e) override;+};++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/PumpFunSwapService.cpp b/fincept-qt/src/services/wallet/PumpFunSwapService.cppnew file mode 100644index 000000000..7644f3fed--- /dev/null+++ b/fincept-qt/src/services/wallet/PumpFunSwapService.cpp@@ -0,0 +1,183 @@+#include "services/wallet/PumpFunSwapService.h"++#include "core/logging/Logger.h"++#include <QByteArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QPointer>+#include <QUrl>++namespace fincept::wallet {++namespace {++constexpr const char* kTradeLocalUrl = "https://pumpportal.fun/api/trade-local";++constexpr int kSlippageMin = 1;+constexpr int kSlippageMax = 5;+constexpr double kPriorityFeeMin = 0.00001;+constexpr double kPriorityFeeMax = 0.005;++QString action_to_str(PumpFunSwapService::Action a) {+ return (a == PumpFunSwapService::Action::Buy)+ ? QStringLiteral("buy")+ : QStringLiteral("sell");+}++int clamp_slippage(int pct) {+ if (pct < kSlippageMin) return kSlippageMin;+ if (pct > kSlippageMax) return kSlippageMax;+ return pct;+}++double clamp_priority_fee(double sol) {+ if (sol < kPriorityFeeMin) return kPriorityFeeMin;+ if (sol > kPriorityFeeMax) return kPriorityFeeMax;+ return sol;+}++} // namespace++PumpFunSwapService::PumpFunSwapService(QObject* parent) : QObject(parent) {+ nam_ = new QNetworkAccessManager(this);+}++PumpFunSwapService::~PumpFunSwapService() = default;++void PumpFunSwapService::build_swap(Action action,+ const QString& mint,+ double amount,+ bool denominated_in_sol,+ const QString& user_pubkey,+ int slippage_pct,+ double priority_fee_sol,+ SwapBuildCallback cb) {+ if (mint.isEmpty()) {+ if (cb) cb(Result<SwapTransaction>::err("missing_mint"));+ return;+ }+ if (user_pubkey.isEmpty()) {+ if (cb) cb(Result<SwapTransaction>::err("missing_pubkey"));+ return;+ }+ if (amount <= 0.0) {+ if (cb) cb(Result<SwapTransaction>::err("amount_must_be_positive"));+ return;+ }++ const int slippage = clamp_slippage(slippage_pct);+ const double prio_fee = clamp_priority_fee(priority_fee_sol);++ // PumpPortal expects:+ // publicKey, action, mint, amount,+ // denominatedInSol ("true"/"false" — string!),+ // slippage (integer percent),+ // priorityFee (number, SOL),+ // pool ("auto" — pump.fun bonding curve before graduation, PumpSwap after)+ QJsonObject body;+ body[QStringLiteral("publicKey")] = user_pubkey;+ body[QStringLiteral("action")] = action_to_str(action);+ body[QStringLiteral("mint")] = mint;+ body[QStringLiteral("amount")] = amount;+ body[QStringLiteral("denominatedInSol")] =+ denominated_in_sol ? QStringLiteral("true") : QStringLiteral("false");+ body[QStringLiteral("slippage")] = slippage;+ body[QStringLiteral("priorityFee")] = prio_fee;+ body[QStringLiteral("pool")] = QStringLiteral("auto");++ const QByteArray payload = QJsonDocument(body).toJson(QJsonDocument::Compact);++ QNetworkRequest req{QUrl(QString::fromLatin1(kTradeLocalUrl))};+ req.setHeader(QNetworkRequest::ContentTypeHeader,+ QStringLiteral("application/json"));+ req.setRawHeader(QByteArrayLiteral("Accept"),+ QByteArrayLiteral("application/octet-stream"));+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,+ QNetworkRequest::NoLessSafeRedirectPolicy);++ auto* reply = nam_->post(req, payload);+ QPointer<PumpFunSwapService> self = this;+ connect(reply, &QNetworkReply::finished, this,+ [self, reply, cb = std::move(cb)]() {+ reply->deleteLater();+ if (!self) return;++ if (reply->error() != QNetworkReply::NoError) {+ const auto err_str = reply->errorString();+ // PumpPortal's error responses are JSON in the body; surface+ // both the HTTP error and the body text so the panel can show+ // something useful.+ const auto body_bytes = reply->readAll();+ QString detail;+ if (!body_bytes.isEmpty()) {+ QJsonParseError pe;+ const auto doc = QJsonDocument::fromJson(body_bytes, &pe);+ if (pe.error == QJsonParseError::NoError && doc.isObject()) {+ const auto root = doc.object();+ detail = root.value(QStringLiteral("error")).toString();+ if (detail.isEmpty()) {+ detail = root.value(QStringLiteral("message")).toString();+ }+ }+ if (detail.isEmpty()) {+ detail = QString::fromUtf8(body_bytes.left(180));+ }+ }+ const QString combined =+ detail.isEmpty() ? err_str : (err_str + ": " + detail);+ LOG_WARN("PumpFunSwap", "trade-local failed: " + combined);+ if (cb) cb(Result<SwapTransaction>::err(combined.toStdString()));+ return;+ }++ const QByteArray body_bytes = reply->readAll();+ if (body_bytes.isEmpty()) {+ if (cb) cb(Result<SwapTransaction>::err("empty_response"));+ return;+ }++ // Sanity check: a Solana versioned tx always begins with a+ // signatures-count varint of 1 (0x01) followed by 64 zero bytes+ // (signature placeholder). Reject anything that doesn't look+ // remotely like a tx — protects against a server returning JSON+ // unexpectedly with a 200 status.+ if (static_cast<unsigned char>(body_bytes.at(0)) > 16+ || body_bytes.size() < 80) {+ // Likely JSON or HTML error page slipping through. Try to parse+ // it as JSON and surface the message; otherwise return the+ // first slice as-is.+ QJsonParseError pe;+ const auto doc = QJsonDocument::fromJson(body_bytes, &pe);+ if (pe.error == QJsonParseError::NoError && doc.isObject()) {+ const auto root = doc.object();+ auto msg = root.value(QStringLiteral("error")).toString();+ if (msg.isEmpty()) {+ msg = root.value(QStringLiteral("message")).toString();+ }+ if (msg.isEmpty()) msg = QStringLiteral("unexpected_response");+ if (cb) cb(Result<SwapTransaction>::err(msg.toStdString()));+ return;+ }+ if (cb) cb(Result<SwapTransaction>::err(+ "unexpected_response: " ++ std::string(body_bytes.left(80).constData(),+ std::min<int>(80, body_bytes.size()))));+ return;+ }++ SwapTransaction out;+ out.tx_base64 = QString::fromLatin1(body_bytes.toBase64());+ // last_valid_block_height left at 0 — wallet/RPC will reject stale txs.+ LOG_INFO("PumpFunSwap",+ QStringLiteral("trade-local ok (%1 raw bytes, %2 b64 chars)")+ .arg(body_bytes.size())+ .arg(out.tx_base64.size()));+ if (cb) cb(Result<SwapTransaction>::ok(std::move(out)));+ });+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/PumpFunSwapService.h b/fincept-qt/src/services/wallet/PumpFunSwapService.hnew file mode 100644index 000000000..fc2769f36--- /dev/null+++ b/fincept-qt/src/services/wallet/PumpFunSwapService.h@@ -0,0 +1,84 @@+#pragma once++#include "core/result/Result.h"++#include <QObject>+#include <QString>++#include <functional>++class QNetworkAccessManager;++namespace fincept::wallet {++/// One-shot service that produces a signable Solana transaction for a+/// user-initiated $FNCPT swap. Phase 2 rev 2 — replaces the earlier+/// Jupiter-based `JupiterSwapService`.+///+/// Why this is **not** a `fincept::datahub::Producer`:+/// - Each call has a unique input (action + amount) bound to a single+/// user click; nothing benefits from caching or coalescing.+/// - The output (`tx_base64`) is consumed exactly once by+/// `WalletService::sign_and_send` and never republished.+/// - Per CLAUDE.md D2 (exception clause), one-shot user-initiated+/// services don't have to be Producers.+///+/// The HTTP transport is `pumpportal.fun/api/trade-local`. PumpPortal+/// returns a fully-built unsigned versioned transaction in raw binary+/// (about 1 KB); we base64-encode it and hand it to the wallet via the+/// existing `WalletTxBridge` → `swap.html` pipeline.+class PumpFunSwapService : public QObject {+ Q_OBJECT+ public:+ enum class Action { Buy, Sell };++ /// Result returned by `build_swap()`. Mirrors the shape of+ /// `JupiterSwapService::SwapTransaction` so `SwapPanel` can swap+ /// service implementations without touching its submit-flow.+ struct SwapTransaction {+ QString tx_base64;+ /// PumpPortal does not expose `lastValidBlockHeight` directly. The+ /// field stays in the struct for forward-compatibility (the wallet+ /// adapter reads it from the deserialised tx itself); set to 0 for+ /// "unknown — let the wallet/RPC reject if stale".+ quint64 last_valid_block_height = 0;+ };+ using SwapBuildCallback = std::function<void(Result<SwapTransaction>)>;++ explicit PumpFunSwapService(QObject* parent = nullptr);+ ~PumpFunSwapService() override;++ PumpFunSwapService(const PumpFunSwapService&) = delete;+ PumpFunSwapService& operator=(const PumpFunSwapService&) = delete;++ /// Build an unsigned swap transaction. All parameters are required.+ ///+ /// `mint` — base58 SPL mint of the token being bought / sold+ /// (the **non-SOL** side; SOL is implied as the+ /// counter-asset).+ /// `amount` — number, interpreted per `denominated_in_sol`.+ /// `denominated_in_sol` — `true` means `amount` is in SOL (e.g. "buy+ /// 0.5 SOL worth of $FNCPT"); `false` means+ /// `amount` is in the token (e.g. "sell 1000+ /// $FNCPT for SOL"). PumpPortal also accepts+ /// `"100%"` as a string when `false`, but this API+ /// surfaces a clean numeric path only — clients+ /// that need MAX should compute it from balance.+ /// `user_pubkey` — base58 of the connected wallet.+ /// `slippage_pct` — integer percent, 1..5. Clamped server-side.+ /// `priority_fee_sol` — SOL prio-fee, e.g. 0.00005. Clamped to a+ /// sensible range internally.+ void build_swap(Action action,+ const QString& mint,+ double amount,+ bool denominated_in_sol,+ const QString& user_pubkey,+ int slippage_pct,+ double priority_fee_sol,+ SwapBuildCallback cb);++ private:+ QNetworkAccessManager* nam_ = nullptr;+};++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/SignTransactionDialog.cpp b/fincept-qt/src/services/wallet/SignTransactionDialog.cppnew file mode 100644index 000000000..bf64f38e8--- /dev/null+++ b/fincept-qt/src/services/wallet/SignTransactionDialog.cpp@@ -0,0 +1,130 @@+#include "services/wallet/SignTransactionDialog.h"++#include "core/logging/Logger.h"+#include "services/wallet/WalletTxBridge.h"++#include <QCloseEvent>+#include <QDesktopServices>+#include <QHBoxLayout>+#include <QLabel>+#include <QPointer>+#include <QPushButton>+#include <QShowEvent>+#include <QUrl>+#include <QVBoxLayout>++namespace fincept::wallet {++SignTransactionDialog::SignTransactionDialog(const QString& tx_base64,+ const QString& title,+ const QString& lede,+ QWidget* parent)+ : QDialog(parent), tx_base64_(tx_base64), lede_(lede) {+ setWindowTitle(title.isEmpty() ? tr("Sign transaction") : title);+ setModal(true);+ resize(440, 220);++ auto* layout = new QVBoxLayout(this);+ layout->setContentsMargins(24, 20, 24, 20);+ layout->setSpacing(12);++ auto* heading = new QLabel(title.isEmpty() ? tr("Sign transaction") : title, this);+ heading->setObjectName(QStringLiteral("walletDialogTitle"));+ layout->addWidget(heading);++ auto* lede_label = new QLabel(+ lede_.isEmpty()+ ? tr("Approve the transaction in your wallet to complete this action.")+ : lede_,+ this);+ lede_label->setWordWrap(true);+ layout->addWidget(lede_label);++ status_label_ = new QLabel(this);+ status_label_->setObjectName(QStringLiteral("walletDialogStatus"));+ status_label_->setWordWrap(true);+ status_label_->setText(tr("Opening your browser to relay the transaction…"));+ layout->addWidget(status_label_);++ layout->addStretch(1);++ auto* row = new QHBoxLayout;+ row->setSpacing(8);+ reopen_button_ = new QPushButton(tr("Reopen browser"), this);+ cancel_button_ = new QPushButton(tr("Cancel"), this);+ cancel_button_->setObjectName(QStringLiteral("walletDialogCancel"));+ row->addStretch(1);+ row->addWidget(reopen_button_);+ row->addWidget(cancel_button_);+ layout->addLayout(row);++ connect(cancel_button_, &QPushButton::clicked, this, [this]() {+ if (resolved_) return;+ on_signature_resolved(Result<QString>::err("user_cancelled"));+ });+ connect(reopen_button_, &QPushButton::clicked, this, [this]() {+ if (!last_open_url_.isEmpty()) {+ QDesktopServices::openUrl(QUrl(last_open_url_));+ }+ });+}++SignTransactionDialog::~SignTransactionDialog() = default;++void SignTransactionDialog::showEvent(QShowEvent* e) {+ QDialog::showEvent(e);+ if (!bridge_) {+ start_signing();+ }+}++void SignTransactionDialog::closeEvent(QCloseEvent* e) {+ if (!resolved_) {+ // Window-close X behaves like cancel — resolve the bridge first so the+ // upstream callback fires with a clear reason, then let Qt close us.+ on_signature_resolved(Result<QString>::err("user_cancelled"));+ }+ QDialog::closeEvent(e);+}++void SignTransactionDialog::start_signing() {+ bridge_ = new WalletTxBridge(this);++ QPointer<SignTransactionDialog> self = this;+ auto url_res = bridge_->request_signature(+ tx_base64_,+ [self](Result<QString> r) {+ if (!self) return;+ self->on_signature_resolved(std::move(r));+ },+ /*timeout_seconds=*/180); // give the user 3 min to approve++ if (url_res.is_err()) {+ on_signature_resolved(+ Result<QString>::err("bridge_failed: " + url_res.error()));+ return;+ }+ last_open_url_ = url_res.value();+ QDesktopServices::openUrl(QUrl(last_open_url_));+ status_label_->setText(+ tr("Browser opened. Approve the transaction in your wallet. The terminal "+ "is waiting on a single-use loopback bridge — this dialog will close "+ "automatically when the wallet returns the signature."));+}++void SignTransactionDialog::on_signature_resolved(Result<QString> r) {+ if (resolved_) return;+ resolved_ = true;++ if (r.is_ok()) {+ signature_ = r.value();+ LOG_INFO("SignTxDialog", "signature received");+ accept();+ return;+ }+ failure_reason_ = QString::fromStdString(r.error());+ LOG_WARN("SignTxDialog", "rejected: " + failure_reason_);+ reject();+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/SignTransactionDialog.h b/fincept-qt/src/services/wallet/SignTransactionDialog.hnew file mode 100644index 000000000..6f4375733--- /dev/null+++ b/fincept-qt/src/services/wallet/SignTransactionDialog.h@@ -0,0 +1,80 @@+#pragma once++#include "core/result/Result.h"++#include <QByteArray>+#include <QDialog>+#include <QString>++class QCloseEvent;+class QLabel;+class QPushButton;+class QShowEvent;++namespace fincept::wallet {++class WalletTxBridge;++/// Modal "browser is open, please sign in your wallet" dialog used for any+/// fund-moving operation (Phase 2 swap + burn, Phase 3 lock, Phase 4 stake).+///+/// Mirrors `ConnectWalletDialog`'s shape:+/// - Owns a `WalletTxBridge` (per-dialog instance — single-use).+/// - On show, registers the tx with the bridge, opens the resulting URL in+/// the system browser via `QDesktopServices::openUrl`.+/// - User signs in their installed wallet extension (Phantom/Solflare/etc).+/// - On `/result` POST, the bridge resolves and the dialog accepts.+/// - On cancel / timeout / error, the dialog rejects.+///+/// The dialog is intentionally minimal — it does not render the action+/// summary. That's `WalletActionConfirmDialog`'s job, which runs *before*+/// this dialog opens. The trip from confirm to sign is:+/// WalletActionConfirmDialog (Accept)+/// → WalletService::sign_and_send(tx_b64, cb)+/// → SignTransactionDialog (owns WalletTxBridge)+/// → system browser → wallet ext → POST /result+/// → cb(Result<sig_b58>)+class SignTransactionDialog : public QDialog {+ Q_OBJECT+ public:+ /// `tx_base64`: the unsigned (or partially-signed) transaction body to+ /// forward to the wallet for `signAndSendTransaction`.+ /// `title`: dialog window title, e.g. "Sign swap" / "Sign burn".+ /// `lede`: one-liner shown above the status message, e.g.+ /// "Sign the swap in Phantom to complete the trade."+ SignTransactionDialog(const QString& tx_base64,+ const QString& title,+ const QString& lede,+ QWidget* parent = nullptr);+ ~SignTransactionDialog() override;++ /// Available after the dialog closes with `Accepted` — the base58+ /// signature returned by the wallet. Empty if the dialog was rejected.+ QString signature() const noexcept { return signature_; }++ /// If the dialog rejected, this carries the reason: "user_cancelled",+ /// "timeout", or whatever the bridge / wallet reported.+ QString failure_reason() const noexcept { return failure_reason_; }++ protected:+ void showEvent(QShowEvent* e) override;+ void closeEvent(QCloseEvent* e) override;++ private:+ void start_signing();+ void on_signature_resolved(Result<QString> r);++ WalletTxBridge* bridge_ = nullptr;+ QLabel* status_label_ = nullptr;+ QPushButton* reopen_button_ = nullptr;+ QPushButton* cancel_button_ = nullptr;++ QString tx_base64_;+ QString lede_;+ QString last_open_url_;+ QString signature_;+ QString failure_reason_;+ bool resolved_ = false;+};++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/SolanaRpcClient.cpp b/fincept-qt/src/services/wallet/SolanaRpcClient.cppnew file mode 100644index 000000000..26b7079b5--- /dev/null+++ b/fincept-qt/src/services/wallet/SolanaRpcClient.cpp@@ -0,0 +1,411 @@+#include "services/wallet/SolanaRpcClient.h"++#include "core/logging/Logger.h"+#include "storage/secure/SecureStorage.h"++#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QPointer>+#include <QUuid>++#include <cmath>++namespace fincept::wallet {++namespace {++constexpr const char* kPublicMainnetRpc = "https://api.mainnet-beta.solana.com";+constexpr const char* kHeliusMainnetTpl = "https://mainnet.helius-rpc.com/?api-key=%1";++constexpr const char* kHeliusKey = "solana.helius_api_key";+constexpr const char* kRpcOverrideKey = "solana.rpc_url";++QString stable_request_id() {+ return QUuid::createUuid().toString(QUuid::WithoutBraces);+}++} // namespace++double SplTokenBalance::ui_amount() const noexcept {+ if (amount_raw.isEmpty()) {+ return 0.0;+ }+ bool ok = false;+ const auto raw = amount_raw.toLongLong(&ok);+ if (!ok) {+ return 0.0;+ }+ return static_cast<double>(raw) / std::pow(10.0, decimals);+}++SolanaRpcClient::SolanaRpcClient(QObject* parent) : QObject(parent) {+ nam_ = new QNetworkAccessManager(this);+ endpoint_ = resolve_endpoint();+ LOG_INFO("SolanaRpc",+ QStringLiteral("Endpoint configured (%1)")+ .arg(endpoint_.startsWith(QStringLiteral("https://api.mainnet-beta"))+ ? QStringLiteral("public")+ : QStringLiteral("private")));+}++SolanaRpcClient::~SolanaRpcClient() = default;++void SolanaRpcClient::reload_endpoint() {+ endpoint_ = resolve_endpoint();+}++QString SolanaRpcClient::ws_endpoint() const {+ QString ws = endpoint_;+ if (ws.startsWith(QStringLiteral("https://"))) {+ ws.replace(0, 8, QStringLiteral("wss://"));+ } else if (ws.startsWith(QStringLiteral("http://"))) {+ ws.replace(0, 7, QStringLiteral("ws://"));+ }+ return ws;+}++QString SolanaRpcClient::resolve_endpoint() const {+ auto override_res = SecureStorage::instance().retrieve(QString::fromLatin1(kRpcOverrideKey));+ if (override_res.is_ok() && !override_res.value().isEmpty()) {+ return override_res.value();+ }+ auto helius_res = SecureStorage::instance().retrieve(QString::fromLatin1(kHeliusKey));+ if (helius_res.is_ok() && !helius_res.value().isEmpty()) {+ return QString::fromLatin1(kHeliusMainnetTpl).arg(helius_res.value());+ }+ return QString::fromLatin1(kPublicMainnetRpc);+}++void SolanaRpcClient::post_rpc(const QString& method,+ const QJsonObject& params_obj,+ std::function<void(Result<QJsonObject>)> callback) {+ QJsonObject envelope;+ envelope[QStringLiteral("jsonrpc")] = QStringLiteral("2.0");+ envelope[QStringLiteral("id")] = stable_request_id();+ envelope[QStringLiteral("method")] = method;+ if (params_obj.contains(QStringLiteral("__array"))) {+ // Allow callers to request positional params by passing { "__array": [ ... ] }.+ envelope[QStringLiteral("params")] = params_obj.value(QStringLiteral("__array")).toArray();+ } else {+ envelope[QStringLiteral("params")] = params_obj;+ }++ QNetworkRequest req{QUrl(endpoint_)};+ req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json"));+ req.setRawHeader(QByteArrayLiteral("Accept"), QByteArrayLiteral("application/json"));+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,+ QNetworkRequest::NoLessSafeRedirectPolicy);++ const QByteArray body = QJsonDocument(envelope).toJson(QJsonDocument::Compact);+ auto* reply = nam_->post(req, body);++ QPointer<SolanaRpcClient> self = this;+ connect(reply, &QNetworkReply::finished, this, [reply, callback = std::move(callback), self, method]() {+ reply->deleteLater();+ if (!self) {+ return;+ }+ if (reply->error() != QNetworkReply::NoError) {+ const QString err = reply->errorString();+ LOG_WARN("SolanaRpc", method + " failed: " + err);+ callback(Result<QJsonObject>::err(err.toStdString()));+ return;+ }+ const QByteArray payload = reply->readAll();+ QJsonParseError pe;+ const auto doc = QJsonDocument::fromJson(payload, &pe);+ if (pe.error != QJsonParseError::NoError || !doc.isObject()) {+ callback(Result<QJsonObject>::err("invalid JSON"));+ return;+ }+ const auto root = doc.object();+ if (root.contains(QStringLiteral("error"))) {+ const auto err_obj = root.value(QStringLiteral("error")).toObject();+ const auto err_msg = err_obj.value(QStringLiteral("message")).toString(+ QStringLiteral("rpc error"));+ callback(Result<QJsonObject>::err(err_msg.toStdString()));+ return;+ }+ callback(Result<QJsonObject>::ok(root));+ });+}++void SolanaRpcClient::get_sol_balance(const QString& pubkey_b58, BalanceCallback callback) {+ QJsonObject params;+ params[QStringLiteral("__array")] = QJsonArray{pubkey_b58};+ post_rpc(QStringLiteral("getBalance"), params,+ [cb = std::move(callback)](Result<QJsonObject> r) {+ if (r.is_err()) {+ cb(Result<quint64>::err(r.error()));+ return;+ }+ const auto result = r.value().value(QStringLiteral("result")).toObject();+ const auto value = result.value(QStringLiteral("value"));+ if (!value.isDouble()) {+ cb(Result<quint64>::err("missing value"));+ return;+ }+ cb(Result<quint64>::ok(static_cast<quint64>(value.toDouble())));+ });+}++namespace {+// Standard SPL Token Program. Token-2022 is a separate program (TokenzQ…).+// We only fetch from the classic program here; token-2022 holdings are rare+// for retail wallets and can be added in a follow-up if it matters.+constexpr const char* kSplTokenProgramId =+ "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";+} // namespace++void SolanaRpcClient::get_token_balance(const QString& owner_b58,+ const QString& mint_b58,+ TokenBalancesCallback callback) {+ QJsonObject mint_filter;+ mint_filter[QStringLiteral("mint")] = mint_b58;+ QJsonObject opts;+ opts[QStringLiteral("encoding")] = QStringLiteral("jsonParsed");++ QJsonArray params_array{owner_b58, mint_filter, opts};+ QJsonObject params;+ params[QStringLiteral("__array")] = params_array;++ post_rpc(QStringLiteral("getTokenAccountsByOwner"), params,+ [cb = std::move(callback)](Result<QJsonObject> r) {+ if (r.is_err()) {+ cb(Result<std::vector<SplTokenBalance>>::err(r.error()));+ return;+ }+ std::vector<SplTokenBalance> out;+ const auto result = r.value().value(QStringLiteral("result")).toObject();+ const auto accounts = result.value(QStringLiteral("value")).toArray();+ for (const auto& entry : accounts) {+ const auto acct = entry.toObject()+ .value(QStringLiteral("account"))+ .toObject();+ const auto data = acct.value(QStringLiteral("data")).toObject();+ const auto parsed = data.value(QStringLiteral("parsed")).toObject();+ const auto info = parsed.value(QStringLiteral("info")).toObject();+ const auto token_amount =+ info.value(QStringLiteral("tokenAmount")).toObject();+ SplTokenBalance bal;+ bal.mint = info.value(QStringLiteral("mint")).toString();+ bal.amount_raw = token_amount.value(QStringLiteral("amount")).toString();+ bal.decimals = token_amount.value(QStringLiteral("decimals")).toInt();+ out.push_back(std::move(bal));+ }+ cb(Result<std::vector<SplTokenBalance>>::ok(std::move(out)));+ });+}++void SolanaRpcClient::get_all_token_balances(const QString& owner_b58,+ TokenBalancesCallback callback) {+ // Same response shape as `get_token_balance`, just no mint filter:+ // we filter by programId instead, returning every SPL token account.+ QJsonObject program_filter;+ program_filter[QStringLiteral("programId")] = QString::fromLatin1(kSplTokenProgramId);+ QJsonObject opts;+ opts[QStringLiteral("encoding")] = QStringLiteral("jsonParsed");++ QJsonObject params;+ params[QStringLiteral("__array")] = QJsonArray{owner_b58, program_filter, opts};++ post_rpc(QStringLiteral("getTokenAccountsByOwner"), params,+ [cb = std::move(callback)](Result<QJsonObject> r) {+ if (r.is_err()) {+ cb(Result<std::vector<SplTokenBalance>>::err(r.error()));+ return;+ }+ std::vector<SplTokenBalance> out;+ const auto result = r.value().value(QStringLiteral("result")).toObject();+ const auto accounts = result.value(QStringLiteral("value")).toArray();+ out.reserve(accounts.size());+ for (const auto& entry : accounts) {+ const auto acct = entry.toObject()+ .value(QStringLiteral("account"))+ .toObject();+ const auto data = acct.value(QStringLiteral("data")).toObject();+ const auto parsed = data.value(QStringLiteral("parsed")).toObject();+ const auto info = parsed.value(QStringLiteral("info")).toObject();+ const auto token_amount =+ info.value(QStringLiteral("tokenAmount")).toObject();+ SplTokenBalance bal;+ bal.mint = info.value(QStringLiteral("mint")).toString();+ bal.amount_raw = token_amount.value(QStringLiteral("amount")).toString();+ bal.decimals = token_amount.value(QStringLiteral("decimals")).toInt();+ // Skip zero-amount accounts to keep the list tight; the+ // wallet may have orphan accounts from past holdings.+ if (bal.amount_raw.isEmpty() || bal.amount_raw == QStringLiteral("0")) {+ continue;+ }+ out.push_back(std::move(bal));+ }+ cb(Result<std::vector<SplTokenBalance>>::ok(std::move(out)));+ });+}++// ── Phase 2 RPC additions ──────────────────────────────────────────────────++void SolanaRpcClient::get_latest_blockhash(LatestBlockhashCallback callback) {+ QJsonObject opts;+ opts[QStringLiteral("commitment")] = QStringLiteral("confirmed");+ QJsonObject params;+ params[QStringLiteral("__array")] = QJsonArray{opts};++ post_rpc(QStringLiteral("getLatestBlockhash"), params,+ [cb = std::move(callback)](Result<QJsonObject> r) {+ if (r.is_err()) {+ cb(Result<LatestBlockhash>::err(r.error()));+ return;+ }+ const auto result = r.value().value(QStringLiteral("result")).toObject();+ const auto value = result.value(QStringLiteral("value")).toObject();+ const auto bh = value.value(QStringLiteral("blockhash")).toString();+ if (bh.isEmpty()) {+ cb(Result<LatestBlockhash>::err("missing blockhash"));+ return;+ }+ LatestBlockhash out;+ out.blockhash = bh;+ out.last_valid_block_height = static_cast<quint64>(+ value.value(QStringLiteral("lastValidBlockHeight")).toDouble());+ cb(Result<LatestBlockhash>::ok(std::move(out)));+ });+}++void SolanaRpcClient::send_transaction(const QString& tx_base64,+ std::function<void(Result<QString>)> callback) {+ // Solana's sendTransaction takes the encoded tx as a positional arg, with+ // an options object as the second positional arg (encoding="base64",+ // skipPreflight=false, preflightCommitment="confirmed").+ QJsonObject opts;+ opts[QStringLiteral("encoding")] = QStringLiteral("base64");+ opts[QStringLiteral("skipPreflight")] = false;+ opts[QStringLiteral("preflightCommitment")] = QStringLiteral("confirmed");+ opts[QStringLiteral("maxRetries")] = 3;++ QJsonObject params;+ params[QStringLiteral("__array")] = QJsonArray{tx_base64, opts};++ post_rpc(QStringLiteral("sendTransaction"), params,+ [cb = std::move(callback)](Result<QJsonObject> r) {+ if (r.is_err()) {+ cb(Result<QString>::err(r.error()));+ return;+ }+ const auto result = r.value().value(QStringLiteral("result"));+ if (!result.isString()) {+ cb(Result<QString>::err("missing signature"));+ return;+ }+ cb(Result<QString>::ok(result.toString()));+ });+}++void SolanaRpcClient::get_signature_statuses(const QStringList& signatures,+ SignatureStatusesCallback callback) {+ if (signatures.isEmpty()) {+ callback(Result<std::vector<SignatureStatus>>::ok({}));+ return;+ }+ QJsonArray sigs_arr;+ for (const auto& s : signatures) {+ sigs_arr.append(s);+ }+ QJsonObject opts;+ opts[QStringLiteral("searchTransactionHistory")] = true;++ QJsonObject params;+ params[QStringLiteral("__array")] = QJsonArray{sigs_arr, opts};++ // Capture the input order so we can align result rows even if some are null.+ auto input_sigs = std::make_shared<QStringList>(signatures);+ post_rpc(QStringLiteral("getSignatureStatuses"), params,+ [cb = std::move(callback), input_sigs](Result<QJsonObject> r) {+ if (r.is_err()) {+ cb(Result<std::vector<SignatureStatus>>::err(r.error()));+ return;+ }+ const auto result = r.value().value(QStringLiteral("result")).toObject();+ const auto value = result.value(QStringLiteral("value")).toArray();+ std::vector<SignatureStatus> out;+ out.reserve(static_cast<std::size_t>(input_sigs->size()));+ for (int i = 0; i < input_sigs->size(); ++i) {+ SignatureStatus s;+ s.signature = input_sigs->at(i);+ if (i >= value.size() || value.at(i).isNull()) {+ s.found = false;+ out.push_back(std::move(s));+ continue;+ }+ const auto entry = value.at(i).toObject();+ s.found = true;+ s.slot = static_cast<quint64>(+ entry.value(QStringLiteral("slot")).toDouble());+ s.confirmation_status =+ entry.value(QStringLiteral("confirmationStatus")).toString();+ const auto err_v = entry.value(QStringLiteral("err"));+ if (!err_v.isNull()) {+ // err may be an object or a string; stringify either way.+ s.err = QString::fromUtf8(+ QJsonDocument::fromVariant(err_v.toVariant())+ .toJson(QJsonDocument::Compact));+ }+ out.push_back(std::move(s));+ }+ cb(Result<std::vector<SignatureStatus>>::ok(std::move(out)));+ });+}++void SolanaRpcClient::get_signatures_for_address(const QString& address_b58,+ int limit,+ const QString& before_signature,+ SignaturesForAddressCallback callback) {+ if (limit < 1) limit = 1;+ if (limit > 1000) limit = 1000;+ QJsonObject opts;+ opts[QStringLiteral("limit")] = limit;+ if (!before_signature.isEmpty()) {+ opts[QStringLiteral("before")] = before_signature;+ }+ opts[QStringLiteral("commitment")] = QStringLiteral("confirmed");++ QJsonObject params;+ params[QStringLiteral("__array")] = QJsonArray{address_b58, opts};++ post_rpc(QStringLiteral("getSignaturesForAddress"), params,+ [cb = std::move(callback)](Result<QJsonObject> r) {+ if (r.is_err()) {+ cb(Result<std::vector<SignatureRow>>::err(r.error()));+ return;+ }+ const auto rows = r.value().value(QStringLiteral("result")).toArray();+ std::vector<SignatureRow> out;+ out.reserve(static_cast<std::size_t>(rows.size()));+ for (const auto& v : rows) {+ const auto e = v.toObject();+ SignatureRow row;+ row.signature = e.value(QStringLiteral("signature")).toString();+ row.slot = static_cast<quint64>(+ e.value(QStringLiteral("slot")).toDouble());+ const auto bt = e.value(QStringLiteral("blockTime"));+ if (bt.isDouble()) {+ row.block_time = static_cast<qint64>(bt.toDouble());+ }+ const auto err_v = e.value(QStringLiteral("err"));+ if (!err_v.isNull() && !err_v.isUndefined()) {+ row.err = QString::fromUtf8(+ QJsonDocument::fromVariant(err_v.toVariant())+ .toJson(QJsonDocument::Compact));+ }+ row.memo = e.value(QStringLiteral("memo")).toString();+ out.push_back(std::move(row));+ }+ cb(Result<std::vector<SignatureRow>>::ok(std::move(out)));+ });+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/SolanaRpcClient.h b/fincept-qt/src/services/wallet/SolanaRpcClient.hnew file mode 100644index 000000000..4ff8f0599--- /dev/null+++ b/fincept-qt/src/services/wallet/SolanaRpcClient.h@@ -0,0 +1,133 @@+#pragma once++#include "core/result/Result.h"++#include <QJsonObject>+#include <QObject>+#include <QString>++#include <functional>++class QNetworkAccessManager;+class QNetworkReply;++namespace fincept::wallet {++/// Token balance for a single SPL mint owned by some wallet.+struct SplTokenBalance {+ QString mint; ///< base58 mint address+ QString amount_raw; ///< integer string (token units, not decimal-shifted)+ int decimals = 0;+ double ui_amount() const noexcept;+};++/// Thin async wrapper over Solana JSON-RPC.+///+/// One QNetworkAccessManager per service (P10). All callbacks run on the+/// originating QObject's thread.+///+/// Endpoint resolution order:+/// 1. KeyConfigManager key "solana/rpc_url" (full URL, takes precedence)+/// 2. KeyConfigManager key "solana/helius_api_key" → Helius mainnet URL+/// 3. Fallback: https://api.mainnet-beta.solana.com (rate-limited, dev only)+class SolanaRpcClient : public QObject {+ Q_OBJECT+ public:+ explicit SolanaRpcClient(QObject* parent = nullptr);+ ~SolanaRpcClient() override;++ SolanaRpcClient(const SolanaRpcClient&) = delete;+ SolanaRpcClient& operator=(const SolanaRpcClient&) = delete;++ using BalanceCallback = std::function<void(Result<quint64>)>;+ using TokenBalancesCallback =+ std::function<void(Result<std::vector<SplTokenBalance>>)>;++ /// `getLatestBlockhash` result. `last_valid_block_height` is the slot at+ /// which a transaction signed against `blockhash` becomes invalid.+ struct LatestBlockhash {+ QString blockhash;+ quint64 last_valid_block_height = 0;+ };+ using LatestBlockhashCallback = std::function<void(Result<LatestBlockhash>)>;++ /// One row of `getSignatureStatuses`.+ struct SignatureStatus {+ QString signature;+ bool found = false;+ QString confirmation_status; ///< "processed" | "confirmed" | "finalized"+ QString err; ///< empty if no error+ quint64 slot = 0;+ };+ using SignatureStatusesCallback =+ std::function<void(Result<std::vector<SignatureStatus>>)>;++ /// One row of `getSignaturesForAddress`.+ struct SignatureRow {+ QString signature;+ quint64 slot = 0;+ qint64 block_time = 0; ///< unix seconds, 0 if unknown+ QString err; ///< empty if confirmed+ QString memo;+ };+ using SignaturesForAddressCallback =+ std::function<void(Result<std::vector<SignatureRow>>)>;++ /// `getBalance` — returns lamports (1 SOL = 1e9 lamports).+ void get_sol_balance(const QString& pubkey_b58, BalanceCallback callback);++ /// `getTokenAccountsByOwner` filtered by mint, parsed for amount + decimals.+ void get_token_balance(const QString& owner_b58,+ const QString& mint_b58,+ TokenBalancesCallback callback);++ /// `getTokenAccountsByOwner` with no mint filter — returns every SPL+ /// token account the wallet owns under the standard SPL Token Program+ /// (TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA). One RPC call per+ /// wallet; cheap. Used by the multi-token holdings path (Phase 2 §2A.5).+ void get_all_token_balances(const QString& owner_b58,+ TokenBalancesCallback callback);++ /// `getLatestBlockhash` (commitment = `confirmed`).+ /// Used by transaction-building paths to stamp a fresh recent blockhash+ /// before forwarding to the wallet for signing.+ void get_latest_blockhash(LatestBlockhashCallback callback);++ /// `sendTransaction` with a base64-encoded signed transaction.+ /// Returns the transaction signature (base58). The caller is responsible+ /// for polling `get_signature_statuses` to confirm landing.+ void send_transaction(const QString& tx_base64,+ std::function<void(Result<QString>)> callback);++ /// `getSignatureStatuses` — batched. Order of `out` matches `signatures`.+ void get_signature_statuses(const QStringList& signatures,+ SignatureStatusesCallback callback);++ /// `getSignaturesForAddress` — paged. `before` is optional (empty = newest).+ /// `limit` is clamped to [1, 1000].+ void get_signatures_for_address(const QString& address_b58,+ int limit,+ const QString& before_signature,+ SignaturesForAddressCallback callback);++ /// Refresh the resolved endpoint from KeyConfigManager. Cheap; safe to call.+ void reload_endpoint();++ /// Currently-resolved HTTP endpoint (for diagnostics / WS-URL derivation).+ QString http_endpoint() const { return endpoint_; }++ /// Derive the WebSocket endpoint from the HTTP endpoint (Helius and the+ /// public mainnet RPC both use the same hostname for `wss://`).+ QString ws_endpoint() const;++ private:+ QString resolve_endpoint() const;+ void post_rpc(const QString& method,+ const QJsonObject& params,+ std::function<void(Result<QJsonObject>)> callback);++ QNetworkAccessManager* nam_ = nullptr;+ QString endpoint_;+};++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/TokenMetadataService.cpp b/fincept-qt/src/services/wallet/TokenMetadataService.cppnew file mode 100644index 000000000..bd6010fd7--- /dev/null+++ b/fincept-qt/src/services/wallet/TokenMetadataService.cpp@@ -0,0 +1,210 @@+#include "services/wallet/TokenMetadataService.h"++#include "core/logging/Logger.h"+#include "storage/secure/SecureStorage.h"++#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QPointer>+#include <QReadLocker>+#include <QUrl>+#include <QWriteLocker>++namespace fincept::wallet {++namespace {++constexpr const char* kStorageKey = "token_metadata.cache_v1";+constexpr const char* kJupiterTokensUrl =+ "https://api.jup.ag/tokens/v2/tagged/verified";+constexpr qint64 kStaleAfterMs = 24LL * 60 * 60 * 1000; // 24h++} // namespace++TokenMetadataService& TokenMetadataService::instance() {+ static TokenMetadataService s;+ return s;+}++TokenMetadataService::TokenMetadataService(QObject* parent) : QObject(parent) {+ nam_ = new QNetworkAccessManager(this);+}++TokenMetadataService::~TokenMetadataService() = default;++bool TokenMetadataService::cache_is_stale() const {+ QReadLocker rl(&lock_);+ if (last_refreshed_ms_ == 0) return true;+ return (QDateTime::currentMSecsSinceEpoch() - last_refreshed_ms_) > kStaleAfterMs;+}++std::optional<TokenMetadata> TokenMetadataService::lookup(const QString& mint) const {+ QReadLocker rl(&lock_);+ auto it = cache_.constFind(mint);+ if (it == cache_.constEnd()) return std::nullopt;+ return it.value();+}++bool TokenMetadataService::is_verified(const QString& mint) const {+ QReadLocker rl(&lock_);+ auto it = cache_.constFind(mint);+ return it != cache_.constEnd() && it.value().verified;+}++int TokenMetadataService::size() const {+ QReadLocker rl(&lock_);+ return cache_.size();+}++void TokenMetadataService::load_from_storage() {+ auto r = SecureStorage::instance().retrieve(QString::fromLatin1(kStorageKey));+ if (r.is_err() || r.value().isEmpty()) {+ LOG_INFO("TokenMetadata", "no cached token list — will fetch from Jupiter");+ return;+ }+ QJsonParseError pe;+ const auto doc = QJsonDocument::fromJson(r.value().toUtf8(), &pe);+ if (pe.error != QJsonParseError::NoError || !doc.isObject()) {+ LOG_WARN("TokenMetadata", "cached token list is malformed; ignoring");+ return;+ }+ const auto root = doc.object();+ const auto entries = root.value(QStringLiteral("entries")).toArray();+ QHash<QString, TokenMetadata> next;+ next.reserve(entries.size());+ for (const auto& v : entries) {+ const auto obj = v.toObject();+ TokenMetadata m;+ m.mint = obj.value(QStringLiteral("mint")).toString();+ m.symbol = obj.value(QStringLiteral("symbol")).toString();+ m.name = obj.value(QStringLiteral("name")).toString();+ m.decimals = obj.value(QStringLiteral("decimals")).toInt();+ m.icon_url = obj.value(QStringLiteral("icon_url")).toString();+ m.verified = obj.value(QStringLiteral("verified")).toBool();+ if (!m.mint.isEmpty()) next.insert(m.mint, std::move(m));+ }+ {+ QWriteLocker wl(&lock_);+ cache_ = std::move(next);+ last_refreshed_ms_ = static_cast<qint64>(+ root.value(QStringLiteral("ts_ms")).toDouble());+ }+ LOG_INFO("TokenMetadata",+ QStringLiteral("loaded %1 tokens from cache (age %2 h)")+ .arg(size())+ .arg((QDateTime::currentMSecsSinceEpoch() - last_refreshed_ms_) / 3600000));+}++void TokenMetadataService::persist_to_storage() {+ QJsonArray entries;+ {+ QReadLocker rl(&lock_);+ for (auto it = cache_.constBegin(); it != cache_.constEnd(); ++it) {+ const auto& m = it.value();+ QJsonObject obj;+ obj[QStringLiteral("mint")] = m.mint;+ obj[QStringLiteral("symbol")] = m.symbol;+ obj[QStringLiteral("name")] = m.name;+ obj[QStringLiteral("decimals")] = m.decimals;+ obj[QStringLiteral("icon_url")] = m.icon_url;+ obj[QStringLiteral("verified")] = m.verified;+ entries.append(obj);+ }+ }+ QJsonObject root;+ root[QStringLiteral("ts_ms")] = static_cast<double>(last_refreshed_ms_);+ root[QStringLiteral("entries")] = entries;+ const auto blob = QString::fromUtf8(+ QJsonDocument(root).toJson(QJsonDocument::Compact));+ auto r = SecureStorage::instance().store(QString::fromLatin1(kStorageKey), blob);+ if (r.is_err()) {+ LOG_WARN("TokenMetadata",+ "failed to persist token cache: " + QString::fromStdString(r.error()));+ } else {+ LOG_INFO("TokenMetadata",+ QStringLiteral("persisted %1 tokens (%2 KB)")+ .arg(entries.size())+ .arg(blob.size() / 1024));+ }+}++void TokenMetadataService::refresh_from_jupiter_async() {+ if (refresh_in_flight_) return;+ if (!cache_is_stale()) {+ LOG_DEBUG("TokenMetadata", "cache fresh; skipping Jupiter refresh");+ return;+ }+ refresh_in_flight_ = true;++ QNetworkRequest req{QUrl(QString::fromLatin1(kJupiterTokensUrl))};+ req.setRawHeader(QByteArrayLiteral("Accept"), QByteArrayLiteral("application/json"));+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,+ QNetworkRequest::NoLessSafeRedirectPolicy);+ auto* reply = nam_->get(req);++ QPointer<TokenMetadataService> self = this;+ connect(reply, &QNetworkReply::finished, this, [self, reply]() {+ reply->deleteLater();+ if (!self) return;+ self->refresh_in_flight_ = false;+ if (reply->error() != QNetworkReply::NoError) {+ LOG_WARN("TokenMetadata",+ "Jupiter fetch failed: " + reply->errorString());+ return;+ }+ const auto payload = reply->readAll();+ QJsonParseError pe;+ const auto doc = QJsonDocument::fromJson(payload, &pe);+ if (pe.error != QJsonParseError::NoError) {+ LOG_WARN("TokenMetadata", "Jupiter response is malformed JSON");+ return;+ }+ // Endpoint returns a top-level array of token objects.+ const auto arr = doc.isArray() ? doc.array()+ : doc.object()+ .value(QStringLiteral("data")).toArray();+ if (arr.isEmpty()) {+ LOG_WARN("TokenMetadata", "Jupiter returned 0 tokens; keeping old cache");+ return;+ }++ QHash<QString, TokenMetadata> next;+ next.reserve(arr.size());+ for (const auto& v : arr) {+ const auto obj = v.toObject();+ TokenMetadata m;+ // Jupiter v2 uses `id` for the mint; v1 used `address`.+ m.mint = obj.value(QStringLiteral("id")).toString();+ if (m.mint.isEmpty()) {+ m.mint = obj.value(QStringLiteral("address")).toString();+ }+ if (m.mint.isEmpty()) continue;+ m.symbol = obj.value(QStringLiteral("symbol")).toString();+ m.name = obj.value(QStringLiteral("name")).toString();+ m.decimals = obj.value(QStringLiteral("decimals")).toInt();+ m.icon_url = obj.value(QStringLiteral("icon")).toString();+ if (m.icon_url.isEmpty()) {+ m.icon_url = obj.value(QStringLiteral("logoURI")).toString();+ }+ m.verified = true; // we explicitly fetched the verified-tagged set+ next.insert(m.mint, std::move(m));+ }++ {+ QWriteLocker wl(&self->lock_);+ self->cache_ = std::move(next);+ self->last_refreshed_ms_ = QDateTime::currentMSecsSinceEpoch();+ }+ self->persist_to_storage();+ LOG_INFO("TokenMetadata",+ QStringLiteral("refreshed: %1 verified tokens").arg(self->size()));+ emit self->metadata_changed();+ });+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/TokenMetadataService.h b/fincept-qt/src/services/wallet/TokenMetadataService.hnew file mode 100644index 000000000..b674e559c--- /dev/null+++ b/fincept-qt/src/services/wallet/TokenMetadataService.h@@ -0,0 +1,73 @@+#pragma once++#include "services/wallet/WalletTypes.h"++#include <QHash>+#include <QObject>+#include <QReadWriteLock>+#include <QString>+#include <optional>++class QNetworkAccessManager;++namespace fincept::wallet {++/// Singleton lookup service for SPL token metadata (symbol, name, decimals,+/// icon, verified flag).+///+/// Why not a Producer: callers need a synchronous lookup keyed by mint —+/// "given this mint, what's the symbol?" — which doesn't fit DataHub's+/// pub/sub shape. Instead this is a read-mostly cache with one slow+/// background refresh per day, persisted to SecureStorage so cold starts+/// don't block on a 1 MB download.+///+/// Source: Jupiter's verified-tagged token list at+/// `https://api.jup.ag/tokens/v2/tagged/verified`. Anything not in the+/// list is treated as unverified and falls back to a truncated mint as+/// the symbol.+class TokenMetadataService : public QObject {+ Q_OBJECT+ public:+ static TokenMetadataService& instance();++ /// Restore the cache from SecureStorage. Cheap (<5 ms even at 1 MB).+ /// Idempotent. Called once from `main()` before WalletService boots.+ void load_from_storage();++ /// Async background fetch from Jupiter. Refreshes the cache and+ /// re-persists. Fires `metadata_changed()` on success. Idempotent on+ /// failure (we keep whatever we had).+ void refresh_from_jupiter_async();++ /// Synchronous lookup. Returns metadata if known, nullopt otherwise.+ /// Thread-safe (read lock).+ std::optional<TokenMetadata> lookup(const QString& mint) const;++ /// Convenience: is this mint in the verified list?+ bool is_verified(const QString& mint) const;++ /// Number of cached tokens (for diagnostics).+ int size() const;++ signals:+ /// Fired after a successful refresh. UI should re-render any rows that+ /// previously showed truncated mints.+ void metadata_changed();++ private:+ explicit TokenMetadataService(QObject* parent = nullptr);+ ~TokenMetadataService() override;+ TokenMetadataService(const TokenMetadataService&) = delete;+ TokenMetadataService& operator=(const TokenMetadataService&) = delete;++ void persist_to_storage();+ bool cache_is_stale() const; ///< true if last refresh > 24h ago or never++ mutable QReadWriteLock lock_;+ QHash<QString, TokenMetadata> cache_;+ qint64 last_refreshed_ms_ = 0;+ QNetworkAccessManager* nam_ = nullptr;+ bool refresh_in_flight_ = false;+};++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/TokenPriceProducer.cpp b/fincept-qt/src/services/wallet/TokenPriceProducer.cppnew file mode 100644index 000000000..247b522d9--- /dev/null+++ b/fincept-qt/src/services/wallet/TokenPriceProducer.cpp@@ -0,0 +1,127 @@+#include "services/wallet/TokenPriceProducer.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"++#include <QDateTime>+#include <QJsonDocument>+#include <QJsonObject>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QPointer>+#include <QSet>+#include <QString>+#include <QUrl>+#include <QVariant>++namespace fincept::wallet {++namespace {++constexpr const char* kFamilyPrefix = "market:price:token:";+constexpr const char* kFncptAlias = "market:price:fncpt";+// Jupiter Lite Price API v3. Same host we already use; the response shape+// keys results by mint, so a single call serves any number of mints.+constexpr const char* kJupiterPriceBase = "https://lite-api.jup.ag/price/v3?ids=";++} // namespace++TokenPriceProducer::TokenPriceProducer(QObject* parent) : QObject(parent) {+ nam_ = new QNetworkAccessManager(this);+}++TokenPriceProducer::~TokenPriceProducer() = default;++QStringList TokenPriceProducer::topic_patterns() const {+ return QStringList{+ QStringLiteral("market:price:token:*"),+ QStringLiteral("market:price:fncpt"), // back-compat alias+ };+}++QString TokenPriceProducer::mint_for_topic(const QString& topic) {+ if (topic == QString::fromLatin1(kFncptAlias)) {+ return QString::fromLatin1(kFncptMint);+ }+ if (topic.startsWith(QString::fromLatin1(kFamilyPrefix))) {+ return topic.mid(static_cast<int>(qstrlen(kFamilyPrefix)));+ }+ return {};+}++QString TokenPriceProducer::topic_for_mint(const QString& mint) {+ return QString::fromLatin1(kFamilyPrefix) + mint;+}++void TokenPriceProducer::refresh(const QStringList& topics) {+ // Collect the unique mints we need to fetch in this cycle, plus a+ // mint→topic-list map so the publish leg knows where to fan out.+ QSet<QString> mints;+ QHash<QString, QStringList> topic_by_mint;+ for (const auto& t : topics) {+ const auto m = mint_for_topic(t);+ if (m.isEmpty()) continue;+ mints.insert(m);+ topic_by_mint[m].append(t);+ }+ if (mints.isEmpty()) return;++ // Build `?ids=<m1>,<m2>,…`. Jupiter handles arbitrary lengths up to+ // ~60 mints in one call; nothing in this codebase ever asks for that+ // many at once.+ QStringList ids(mints.constBegin(), mints.constEnd());+ const QString url = QString::fromLatin1(kJupiterPriceBase) + ids.join(QLatin1Char(','));++ QNetworkRequest req{QUrl(url)};+ req.setRawHeader(QByteArrayLiteral("Accept"), QByteArrayLiteral("application/json"));+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,+ QNetworkRequest::NoLessSafeRedirectPolicy);+ auto* reply = nam_->get(req);++ QPointer<TokenPriceProducer> self = this;+ connect(reply, &QNetworkReply::finished, this,+ [self, reply, topic_by_mint, ids]() {+ reply->deleteLater();+ if (!self) return;+ auto& hub = fincept::datahub::DataHub::instance();+ if (reply->error() != QNetworkReply::NoError) {+ const auto err = reply->errorString();+ LOG_WARN("TokenPrice", "Jupiter fetch failed: " + err);+ for (auto it = topic_by_mint.constBegin();+ it != topic_by_mint.constEnd(); ++it) {+ for (const auto& t : it.value()) hub.publish_error(t, err);+ }+ return;+ }+ QJsonParseError pe;+ const auto doc = QJsonDocument::fromJson(reply->readAll(), &pe);+ if (pe.error != QJsonParseError::NoError || !doc.isObject()) {+ LOG_WARN("TokenPrice", "invalid JSON from Jupiter");+ return;+ }+ const auto root = doc.object();++ // Find the SOL entry for the SOL/FNCPT cross-rate that legacy+ // FncptPrice consumers expect on the `sol` field.+ const auto sol_obj =+ root.value(QString::fromLatin1(kWrappedSolMint)).toObject();+ const double sol_usd = sol_obj.value(QStringLiteral("usdPrice")).toDouble();++ for (const auto& mint : ids) {+ const auto entry = root.value(mint).toObject();+ TokenPrice tp;+ tp.mint = mint;+ tp.usd = entry.value(QStringLiteral("usdPrice")).toDouble();+ tp.sol = (sol_usd > 0.0 && tp.usd > 0.0) ? tp.usd / sol_usd : 0.0;+ tp.ts_ms = QDateTime::currentMSecsSinceEpoch();+ tp.valid = tp.usd > 0.0;+ const auto v = QVariant::fromValue(tp);+ for (const auto& t : topic_by_mint.value(mint)) {+ hub.publish(t, v);+ }+ }+ });+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/TokenPriceProducer.h b/fincept-qt/src/services/wallet/TokenPriceProducer.hnew file mode 100644index 000000000..f8dfd753f--- /dev/null+++ b/fincept-qt/src/services/wallet/TokenPriceProducer.h@@ -0,0 +1,46 @@+#pragma once++#include "datahub/Producer.h"+#include "services/wallet/WalletTypes.h"++#include <QObject>+#include <QStringList>++class QNetworkAccessManager;++namespace fincept::wallet {++/// Owns the `market:price:token:<mint>` topic family and the legacy+/// `market:price:fncpt` alias. Phase 2 §2A.5 — replaces `FncptPriceProducer`.+///+/// Topic policy:+/// - TTL 60 s, min_interval 30 s, coalesce 250 ms+/// - max_requests_per_sec = 2 (one batched call per refresh cycle is plenty)+///+/// Batching: one Jupiter Lite Price API call covers every mint that has at+/// least one subscriber, regardless of how many topics fire at once. The+/// producer's `refresh(topics)` argument is the union of stale topics; we+/// extract their mints, build `?ids=<m1>,<m2>,…`, and publish per-mint.+class TokenPriceProducer : public QObject, public fincept::datahub::Producer {+ Q_OBJECT+ public:+ explicit TokenPriceProducer(QObject* parent = nullptr);+ ~TokenPriceProducer() override;++ QStringList topic_patterns() const override;+ void refresh(const QStringList& topics) override;+ int max_requests_per_sec() const override { return 2; }++ private:+ /// Extract the mint from `market:price:token:<mint>` or return the+ /// canonical FNCPT mint for the legacy `market:price:fncpt` alias.+ /// Empty string for anything else.+ static QString mint_for_topic(const QString& topic);++ /// Inverse of `mint_for_topic`. Always returns the new family form.+ static QString topic_for_mint(const QString& mint);++ QNetworkAccessManager* nam_ = nullptr;+};++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/WalletActivityProducer.cpp b/fincept-qt/src/services/wallet/WalletActivityProducer.cppnew file mode 100644index 000000000..114a0fac7--- /dev/null+++ b/fincept-qt/src/services/wallet/WalletActivityProducer.cpp@@ -0,0 +1,290 @@+#include "services/wallet/WalletActivityProducer.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "services/wallet/SolanaRpcClient.h"+#include "services/wallet/TokenMetadataService.h"+#include "storage/secure/SecureStorage.h"++#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QPointer>+#include <QUrl>+#include <QUrlQuery>+#include <QVariant>+#include <QVector>++#include <cmath>++namespace fincept::wallet {++// Inner named namespace avoids a unity-build collision with+// WalletBalanceProducer.cpp which also has anonymous-namespace `kTopicPrefix`.+namespace activity_producer_internal {++constexpr const char* kTopicPrefix = "wallet:activity:";+constexpr const char* kHeliusKeyName = "solana.helius_api_key";+constexpr int kFetchLimit = 50;++QString format_token_amount(double v, int max_dp = 4) {+ if (v <= 0.0) return QStringLiteral("0");+ if (v < 0.0001) return QString::number(v, 'g', 4);+ return QString::number(v, 'f', max_dp);+}++QString resolve_symbol(const QString& mint) {+ if (mint.isEmpty()) return QString();+ if (auto m = TokenMetadataService::instance().lookup(mint)) {+ return m->symbol;+ }+ if (mint.size() >= 12) {+ return mint.left(4) + QStringLiteral("…") + mint.right(4);+ }+ return mint;+}++/// Parse one Helius transaction object into a ParsedActivity row. The+/// classification logic is intentionally narrow — we only extract what+/// the ActivityTab needs to render:+/// - SWAP rows from `events.swap` (Helius's pre-parsed swap events)+/// - SEND/RECEIVE rows from `nativeTransfers` and `tokenTransfers`+/// - Everything else maps to `Other` so the row still shows up+/// (with a Solscan link) instead of silently disappearing.+ParsedActivity parse_helius_tx(const QJsonObject& tx, const QString& owner) {+ ParsedActivity out;+ out.signature = tx.value(QStringLiteral("signature")).toString();++ const auto ts_sec = static_cast<qint64>(+ tx.value(QStringLiteral("timestamp")).toDouble());+ if (ts_sec > 0) out.ts_ms = ts_sec * 1000;++ const bool failed = tx.value(QStringLiteral("transactionError")).isObject();+ out.status = failed ? QStringLiteral("failed") : QStringLiteral("confirmed");++ // Try the classified `events.swap` block first.+ const auto events = tx.value(QStringLiteral("events")).toObject();+ const auto swap = events.value(QStringLiteral("swap")).toObject();+ if (!swap.isEmpty()) {+ out.kind = ParsedActivity::Kind::Swap;+ // Helius swap events expose nativeInput/Output (SOL legs) and+ // tokenInputs/Outputs (SPL legs). One side is "in", the other "out".+ QString in_sym, out_sym;+ QString in_amt, out_amt;+ const auto native_in = swap.value(QStringLiteral("nativeInput")).toObject();+ if (!native_in.isEmpty()) {+ in_sym = QStringLiteral("SOL");+ const auto lamports = native_in.value(QStringLiteral("amount"))+ .toString().toLongLong();+ in_amt = format_token_amount(lamports / 1e9, 4);+ } else {+ const auto token_in = swap.value(QStringLiteral("tokenInputs")).toArray();+ if (!token_in.isEmpty()) {+ const auto first = token_in.at(0).toObject();+ in_sym = resolve_symbol(first.value(QStringLiteral("mint")).toString());+ const auto raw = first.value(QStringLiteral("rawTokenAmount")).toObject();+ bool ok = false;+ const auto qty = raw.value(QStringLiteral("tokenAmount"))+ .toString().toLongLong(&ok);+ const int dp = raw.value(QStringLiteral("decimals")).toInt();+ if (ok) in_amt = format_token_amount(qty / std::pow(10.0, dp), 4);+ }+ }+ const auto native_out = swap.value(QStringLiteral("nativeOutput")).toObject();+ if (!native_out.isEmpty()) {+ out_sym = QStringLiteral("SOL");+ const auto lamports = native_out.value(QStringLiteral("amount"))+ .toString().toLongLong();+ out_amt = format_token_amount(lamports / 1e9, 4);+ } else {+ const auto token_out = swap.value(QStringLiteral("tokenOutputs")).toArray();+ if (!token_out.isEmpty()) {+ const auto first = token_out.at(0).toObject();+ out_sym = resolve_symbol(first.value(QStringLiteral("mint")).toString());+ const auto raw = first.value(QStringLiteral("rawTokenAmount")).toObject();+ bool ok = false;+ const auto qty = raw.value(QStringLiteral("tokenAmount"))+ .toString().toLongLong(&ok);+ const int dp = raw.value(QStringLiteral("decimals")).toInt();+ if (ok) out_amt = format_token_amount(qty / std::pow(10.0, dp), 2);+ }+ }+ out.asset = QStringLiteral("%1 → %2").arg(in_sym, out_sym);+ out.amount_ui = QStringLiteral("%1 → %2").arg(in_amt, out_amt);+ return out;+ }++ // Token transfers — narrow to ones involving the owner.+ const auto token_transfers =+ tx.value(QStringLiteral("tokenTransfers")).toArray();+ for (const auto& v : token_transfers) {+ const auto t = v.toObject();+ const auto from = t.value(QStringLiteral("fromUserAccount")).toString();+ const auto to = t.value(QStringLiteral("toUserAccount")).toString();+ const auto mint = t.value(QStringLiteral("mint")).toString();+ const double amt = t.value(QStringLiteral("tokenAmount")).toDouble();+ const auto sym = resolve_symbol(mint);+ if (to == owner) {+ out.kind = ParsedActivity::Kind::Receive;+ out.asset = sym;+ out.amount_ui = format_token_amount(amt, 4);+ out.counterparty = from;+ return out;+ }+ if (from == owner) {+ out.kind = ParsedActivity::Kind::Send;+ out.asset = sym;+ out.amount_ui = format_token_amount(amt, 4);+ out.counterparty = to;+ return out;+ }+ }++ // Native SOL transfers.+ const auto native_transfers =+ tx.value(QStringLiteral("nativeTransfers")).toArray();+ for (const auto& v : native_transfers) {+ const auto t = v.toObject();+ const auto from = t.value(QStringLiteral("fromUserAccount")).toString();+ const auto to = t.value(QStringLiteral("toUserAccount")).toString();+ const auto lamports = static_cast<qint64>(+ t.value(QStringLiteral("amount")).toDouble());+ if (to == owner) {+ out.kind = ParsedActivity::Kind::Receive;+ out.asset = QStringLiteral("SOL");+ out.amount_ui = format_token_amount(lamports / 1e9, 4);+ out.counterparty = from;+ return out;+ }+ if (from == owner) {+ out.kind = ParsedActivity::Kind::Send;+ out.asset = QStringLiteral("SOL");+ out.amount_ui = format_token_amount(lamports / 1e9, 4);+ out.counterparty = to;+ return out;+ }+ }++ // Couldn't classify — leave as Other but keep the signature so the row+ // still renders and Solscan opens.+ return out;+}++} // namespace activity_producer_internal++namespace api = activity_producer_internal;++WalletActivityProducer::WalletActivityProducer(QObject* parent) : QObject(parent) {+ nam_ = new QNetworkAccessManager(this);+ rpc_ = new SolanaRpcClient(this);+}++WalletActivityProducer::~WalletActivityProducer() = default;++QStringList WalletActivityProducer::topic_patterns() const {+ return QStringList{QStringLiteral("wallet:activity:*")};+}++QString WalletActivityProducer::pubkey_from_topic(const QString& topic) {+ return topic.mid(static_cast<int>(qstrlen(api::kTopicPrefix)));+}++void WalletActivityProducer::refresh(const QStringList& topics) {+ auto helius_key_res = SecureStorage::instance().retrieve(+ QString::fromLatin1(api::kHeliusKeyName));+ const QString helius_key = (helius_key_res.is_ok())+ ? helius_key_res.value()+ : QString();+ for (const auto& topic : topics) {+ const auto pubkey = pubkey_from_topic(topic);+ if (pubkey.isEmpty()) {+ fincept::datahub::DataHub::instance().publish_error(+ topic, QStringLiteral("invalid topic"));+ continue;+ }+ if (!helius_key.isEmpty()) {+ refresh_via_helius(topic, pubkey, helius_key);+ } else {+ refresh_via_rpc(topic, pubkey);+ }+ }+}++void WalletActivityProducer::refresh_via_helius(const QString& topic,+ const QString& pubkey,+ const QString& helius_key) {+ QUrl url(QStringLiteral("https://api.helius.xyz/v0/addresses/%1/transactions")+ .arg(pubkey));+ QUrlQuery q;+ q.addQueryItem(QStringLiteral("limit"), QString::number(api::kFetchLimit));+ q.addQueryItem(QStringLiteral("api-key"), helius_key);+ url.setQuery(q);++ QNetworkRequest req(url);+ req.setRawHeader(QByteArrayLiteral("Accept"), QByteArrayLiteral("application/json"));+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,+ QNetworkRequest::NoLessSafeRedirectPolicy);+ auto* reply = nam_->get(req);++ QPointer<WalletActivityProducer> self = this;+ connect(reply, &QNetworkReply::finished, this,+ [self, reply, topic, pubkey]() {+ reply->deleteLater();+ if (!self) return;+ auto& hub = fincept::datahub::DataHub::instance();+ if (reply->error() != QNetworkReply::NoError) {+ const auto err = reply->errorString();+ LOG_WARN("WalletActivity",+ "Helius fetch failed: " + err);+ hub.publish_error(topic, err);+ return;+ }+ QJsonParseError pe;+ const auto doc = QJsonDocument::fromJson(reply->readAll(), &pe);+ if (pe.error != QJsonParseError::NoError || !doc.isArray()) {+ hub.publish_error(topic, QStringLiteral("invalid_helius_json"));+ return;+ }+ const auto arr = doc.array();+ QVector<ParsedActivity> out;+ out.reserve(arr.size());+ for (const auto& v : arr) {+ out.append(api::parse_helius_tx(v.toObject(), pubkey));+ }+ hub.publish(topic, QVariant::fromValue(out));+ });+}++void WalletActivityProducer::refresh_via_rpc(const QString& topic,+ const QString& pubkey) {+ rpc_->reload_endpoint();+ QPointer<WalletActivityProducer> self = this;+ rpc_->get_signatures_for_address(+ pubkey, api::kFetchLimit, QString(),+ [self, topic](Result<std::vector<SolanaRpcClient::SignatureRow>> r) {+ if (!self) return;+ auto& hub = fincept::datahub::DataHub::instance();+ if (r.is_err()) {+ hub.publish_error(topic, QString::fromStdString(r.error()));+ return;+ }+ QVector<ParsedActivity> out;+ out.reserve(static_cast<int>(r.value().size()));+ for (const auto& row : r.value()) {+ ParsedActivity a;+ a.signature = row.signature;+ a.ts_ms = row.block_time > 0 ? row.block_time * 1000 : 0;+ a.kind = ParsedActivity::Kind::Other;+ a.status = row.err.isEmpty() ? QStringLiteral("confirmed")+ : QStringLiteral("failed");+ out.append(std::move(a));+ }+ hub.publish(topic, QVariant::fromValue(out));+ });+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/WalletActivityProducer.h b/fincept-qt/src/services/wallet/WalletActivityProducer.hnew file mode 100644index 000000000..3e3114c94--- /dev/null+++ b/fincept-qt/src/services/wallet/WalletActivityProducer.h@@ -0,0 +1,58 @@+#pragma once++#include "datahub/Producer.h"+#include "services/wallet/WalletTypes.h"++#include <QObject>+#include <QString>++class QNetworkAccessManager;++namespace fincept::wallet {++class SolanaRpcClient;++/// Producer for `wallet:activity:<pubkey>` — last 50 parsed wallet+/// operations. Phase 2 §2B.+///+/// Source priority:+/// - **Helius parsed-tx** (`api.helius.xyz/v0/addresses/<pk>/transactions`)+/// when `solana.helius_api_key` is set in SecureStorage. Helius+/// classifies SWAP / RECEIVE / SEND directly and resolves token symbols+/// server-side.+/// - **Fallback**: `SolanaRpcClient::get_signatures_for_address` returns+/// raw signatures + slot + block_time. `kind` defaults to `Other`,+/// `asset`/`amount_ui` are empty. The ActivityTab shows a footer hint+/// "Add a Helius key for parsed activity".+///+/// The producer never blocks: each refresh fires one HTTP call (or one RPC+/// call in fallback mode). Topics that haven't published yet show empty in+/// the table; subscribers see the first publish on the next 30 s tick.+class WalletActivityProducer : public QObject, public fincept::datahub::Producer {+ Q_OBJECT+ public:+ explicit WalletActivityProducer(QObject* parent = nullptr);+ ~WalletActivityProducer() override;++ QStringList topic_patterns() const override;+ void refresh(const QStringList& topics) override;+ int max_requests_per_sec() const override { return 4; }++ private:+ /// Extract the pubkey from `wallet:activity:<pubkey>`. Empty if invalid.+ static QString pubkey_from_topic(const QString& topic);++ /// Helius parsed-tx path. Calls `api.helius.xyz/v0/addresses/<pk>/transactions`+ /// and publishes a vector of fully-classified activities.+ void refresh_via_helius(const QString& topic, const QString& pubkey,+ const QString& helius_key);++ /// Fallback path. Uses our existing RPC wrapper to fetch raw signatures.+ /// Each row carries `kind=Other`, the signature, and a unix block_time.+ void refresh_via_rpc(const QString& topic, const QString& pubkey);++ QNetworkAccessManager* nam_ = nullptr;+ SolanaRpcClient* rpc_ = nullptr;+};++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/WalletBalanceProducer.cpp b/fincept-qt/src/services/wallet/WalletBalanceProducer.cppnew file mode 100644index 000000000..528cef1c9--- /dev/null+++ b/fincept-qt/src/services/wallet/WalletBalanceProducer.cpp@@ -0,0 +1,537 @@+#include "services/wallet/WalletBalanceProducer.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "datahub/TopicPolicy.h"+#include "network/websocket/WebSocketClient.h"+#include "services/wallet/SolanaRpcClient.h"+#include "services/wallet/TokenMetadataService.h"+#include "services/wallet/WalletTypes.h"+#include "storage/secure/SecureStorage.h"++#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QJsonValue>+#include <QPointer>+#include <QTimer>+#include <QVariant>++#include <algorithm>++namespace fincept::wallet {++namespace {++// $FNCPT mint is the canonical inline constexpr in WalletTypes.h — re-using it+// here avoids a unity-build ambiguity when this TU and that header collide.+constexpr const char* kTopicPrefix = "wallet:balance:";+constexpr const char* kModeSettingsKey = "wallet.balance_mode";+constexpr int kFncptHeartbeatMs = 30 * 1000; // re-poll FNCPT in stream mode++quint64 parse_uint64(const QJsonValue& v) {+ if (v.isDouble()) {+ return static_cast<quint64>(v.toDouble());+ }+ if (v.isString()) {+ bool ok = false;+ const auto n = v.toString().toULongLong(&ok);+ return ok ? n : 0;+ }+ return 0;+}++} // namespace++WalletBalanceProducer::WalletBalanceProducer(QObject* parent) : QObject(parent) {+ rpc_ = new SolanaRpcClient(this);+ reload_mode();+}++WalletBalanceProducer::~WalletBalanceProducer() {+ stop_all_streams();+}++QStringList WalletBalanceProducer::topic_patterns() const {+ return QStringList{QStringLiteral("wallet:balance:*")};+}++QString WalletBalanceProducer::pubkey_from_topic(const QString& topic) const {+ return topic.mid(static_cast<int>(qstrlen(kTopicPrefix)));+}++QString WalletBalanceProducer::topic_for_pubkey(const QString& pubkey) const {+ return QString::fromLatin1(kTopicPrefix) + pubkey;+}++bool WalletBalanceProducer::endpoint_supports_streaming() const {+ if (!rpc_) return false;+ const auto http = rpc_->http_endpoint();+ // The public mainnet endpoint advertises wss:// but is rate-limited so+ // aggressively that accountSubscribe is unreliable in practice. Force+ // the caller to fall back to polling for that case.+ if (http.contains(QStringLiteral("api.mainnet-beta.solana.com"),+ Qt::CaseInsensitive)) {+ return false;+ }+ const auto ws = rpc_->ws_endpoint();+ return !ws.isEmpty() && (ws.startsWith(QStringLiteral("ws://"))+ || ws.startsWith(QStringLiteral("wss://")));+}++void WalletBalanceProducer::force_refresh(const QString& pubkey) {+ if (pubkey.isEmpty()) {+ return;+ }+ if (mode_ == BalanceMode::Poll) {+ refresh_one_poll(topic_for_pubkey(pubkey));+ return;+ }+ // Stream mode — re-run the seed so SOL + FNCPT both refresh now.+ if (streams_.contains(pubkey)) {+ seed_stream_state(pubkey);+ } else {+ // No active session yet; spin one up. start_stream_for() seeds.+ start_stream_for(pubkey);+ }+}++// ── Mode switching ─────────────────────────────────────────────────────────++void WalletBalanceProducer::reload_mode() {+ auto r = SecureStorage::instance().retrieve(QString::fromLatin1(kModeSettingsKey));+ BalanceMode wanted = BalanceMode::Poll;+ if (r.is_ok() && r.value().compare(QStringLiteral("stream"), Qt::CaseInsensitive) == 0) {+ wanted = BalanceMode::Stream;+ }+ if (wanted != mode_) {+ set_mode(wanted);+ }+}++void WalletBalanceProducer::set_mode(BalanceMode mode) {+ if (mode == mode_) {+ return;+ }+ LOG_INFO("WalletBalanceProducer",+ QStringLiteral("mode switch: %1")+ .arg(mode == BalanceMode::Stream ? "stream" : "poll"));+ mode_ = mode;++ auto& hub = fincept::datahub::DataHub::instance();+ fincept::datahub::TopicPolicy policy;+ if (mode_ == BalanceMode::Stream) {+ policy.push_only = true;+ policy.coalesce_within_ms = 250;+ policy.refresh_timeout_ms = 30 * 1000;+ } else {+ policy.ttl_ms = 30 * 1000;+ policy.min_interval_ms = 10 * 1000;+ policy.refresh_timeout_ms = 15 * 1000;+ policy.push_only = false;+ }+ hub.set_policy_pattern(QStringLiteral("wallet:balance:*"), policy);++ if (mode_ == BalanceMode::Poll) {+ // Tear down any active streams; the hub scheduler will resume polling.+ stop_all_streams();+ }+}++// ── Hub entry point ────────────────────────────────────────────────────────++void WalletBalanceProducer::refresh(const QStringList& topics) {+ for (const auto& topic : topics) {+ if (mode_ == BalanceMode::Poll) {+ refresh_one_poll(topic);+ } else {+ const auto pubkey = pubkey_from_topic(topic);+ if (pubkey.isEmpty()) {+ continue;+ }+ // Stream mode is push-only; the hub still calls refresh() once+ // when the first subscriber attaches. Use that opportunity to+ // ensure the WS session is up.+ if (!streams_.contains(pubkey)) {+ start_stream_for(pubkey);+ } else if (streams_.value(pubkey)->seeded) {+ // Re-publish last cached value so a freshly subscribing+ // consumer sees current data immediately.+ fincept::datahub::DataHub::instance().publish(+ topic, QVariant::fromValue(streams_.value(pubkey)->latest));+ }+ }+ }+}++// ── Polling path ───────────────────────────────────────────────────────────++void WalletBalanceProducer::refresh_one_poll(const QString& topic) {+ const QString pubkey = pubkey_from_topic(topic);+ if (pubkey.isEmpty()) {+ fincept::datahub::DataHub::instance().publish_error(topic,+ QStringLiteral("invalid topic"));+ return;+ }+ rpc_->reload_endpoint();++ QPointer<WalletBalanceProducer> self = this;+ auto state = std::make_shared<WalletBalance>();+ state->pubkey_b58 = pubkey;+ state->ts_ms = QDateTime::currentMSecsSinceEpoch();+ auto pending = std::make_shared<int>(2);+ auto fail = std::make_shared<bool>(false);++ auto try_publish = [self, topic, state, pending, fail]() {+ if (!self) {+ return;+ }+ if (--(*pending) > 0) {+ return;+ }+ auto& hub = fincept::datahub::DataHub::instance();+ if (*fail) {+ // partial success: publish what we have anyway so the UI shows+ // last-known-good. publish_error already emitted in the failing+ // branch, so the topic_error signal fires in parallel.+ }+ hub.publish(topic, QVariant::fromValue(*state));+ };++ rpc_->get_sol_balance(pubkey, [self, topic, state, try_publish, fail](Result<quint64> r) {+ if (!self) {+ return;+ }+ if (r.is_err()) {+ *fail = true;+ fincept::datahub::DataHub::instance().publish_error(+ topic, QString::fromStdString(r.error()));+ } else {+ state->sol_lamports = r.value();+ }+ try_publish();+ });++ // Phase 2 §2A.5: fetch every SPL token the wallet holds in one call,+ // then merge with TokenMetadataService for symbol/name/icon. Tokens+ // are sorted at publish time; the price-based sort happens upstream+ // once TokenPriceProducer has cached USD values, so here we only+ // ensure FNCPT and any verified token surface above unverified junk.+ rpc_->get_all_token_balances(+ pubkey,+ [self, topic, state, try_publish, fail](Result<std::vector<SplTokenBalance>> r) {+ if (!self) {+ return;+ }+ if (r.is_err()) {+ *fail = true;+ fincept::datahub::DataHub::instance().publish_error(+ topic, QString::fromStdString(r.error()));+ try_publish();+ return;+ }+ auto& meta = fincept::wallet::TokenMetadataService::instance();+ for (const auto& b : r.value()) {+ if (b.amount_raw.isEmpty() || b.amount_raw == QStringLiteral("0")) {+ continue;+ }+ fincept::wallet::TokenHolding h;+ h.mint = b.mint;+ h.amount_raw = b.amount_raw;+ h.decimals = b.decimals;+ if (auto m = meta.lookup(b.mint)) {+ h.symbol = m->symbol;+ h.name = m->name;+ h.icon_url = m->icon_url;+ h.verified = m->verified;+ } else {+ // Fallback: truncated mint as the symbol so the row is+ // still readable. Verified flag stays false.+ if (b.mint.size() >= 12) {+ h.symbol = b.mint.left(4) + QStringLiteral("…")+ + b.mint.right(4);+ } else {+ h.symbol = b.mint;+ }+ h.verified = false;+ }+ state->tokens.append(std::move(h));+ }++ // Sort: verified first, then by raw atomic amount as a rough+ // proxy until TokenPriceProducer's cache lets us re-sort by+ // USD value upstream. FNCPT always pinned to position 0 so+ // legacy fncpt_holding() consumers find it cheaply.+ std::sort(state->tokens.begin(), state->tokens.end(),+ [](const fincept::wallet::TokenHolding& a,+ const fincept::wallet::TokenHolding& b) {+ const auto fncpt = QString::fromLatin1(+ fincept::wallet::kFncptMint);+ if (a.mint == fncpt) return true;+ if (b.mint == fncpt) return false;+ if (a.verified != b.verified) return a.verified;+ return a.ui_amount() > b.ui_amount();+ });++ try_publish();+ });+}++// ── Streaming path ─────────────────────────────────────────────────────────++void WalletBalanceProducer::stop_all_streams() {+ for (auto* s : streams_) {+ if (s->fncpt_heartbeat) {+ s->fncpt_heartbeat->stop();+ s->fncpt_heartbeat->deleteLater();+ }+ if (s->ws) {+ s->ws->disconnect();+ s->ws->deleteLater();+ }+ delete s;+ }+ streams_.clear();+}++void WalletBalanceProducer::stop_stream_for(const QString& pubkey) {+ auto* s = streams_.take(pubkey);+ if (!s) {+ return;+ }+ if (s->fncpt_heartbeat) {+ s->fncpt_heartbeat->stop();+ s->fncpt_heartbeat->deleteLater();+ }+ if (s->ws) {+ s->ws->disconnect();+ s->ws->deleteLater();+ }+ delete s;+}++void WalletBalanceProducer::seed_stream_state(const QString& pubkey) {+ rpc_->reload_endpoint();+ QPointer<WalletBalanceProducer> self = this;++ // Step 1: get SOL balance to bootstrap the stat box.+ rpc_->get_sol_balance(pubkey, [self, pubkey](Result<quint64> r) {+ if (!self) {+ return;+ }+ auto it = self->streams_.find(pubkey);+ if (it == self->streams_.end()) {+ return;+ }+ auto* s = it.value();+ if (r.is_ok()) {+ s->latest.sol_lamports = r.value();+ }+ s->latest.pubkey_b58 = pubkey;+ s->latest.ts_ms = QDateTime::currentMSecsSinceEpoch();+ if (s->seeded) {+ fincept::datahub::DataHub::instance().publish(+ self->topic_for_pubkey(pubkey), QVariant::fromValue(s->latest));+ }+ });++ // Step 2: locate the FNCPT token account address + amount.+ rpc_->get_token_balance(+ pubkey, QString::fromLatin1(kFncptMint),+ [self, pubkey](Result<std::vector<SplTokenBalance>> r) {+ if (!self) {+ return;+ }+ auto it = self->streams_.find(pubkey);+ if (it == self->streams_.end()) {+ return;+ }+ auto* s = it.value();+ quint64 total = 0;+ int decimals = 0;+ for (const auto& b : r.is_ok() ? r.value() : std::vector<SplTokenBalance>{}) {+ bool ok = false;+ const auto v = b.amount_raw.toULongLong(&ok);+ if (ok) {+ total += v;+ }+ decimals = b.decimals;+ }+ // Stage 2A.5: WalletBalance.tokens carries every holding. The+ // streaming path still only refreshes FNCPT; replace the FNCPT+ // entry in `tokens` (or append it) instead of writing the old+ // dedicated fields.+ const auto fncpt_mint = QString::fromLatin1(fincept::wallet::kFncptMint);+ bool replaced = false;+ for (auto& t : s->latest.tokens) {+ if (t.mint == fncpt_mint) {+ t.amount_raw = QString::number(total);+ if (decimals > 0) t.decimals = decimals;+ replaced = true;+ break;+ }+ }+ if (!replaced) {+ fincept::wallet::TokenHolding t;+ t.mint = fncpt_mint;+ t.symbol = QStringLiteral("$FNCPT");+ t.name = QStringLiteral("FinceptTerminal");+ t.amount_raw = QString::number(total);+ t.decimals = decimals > 0 ? decimals : 6;+ s->latest.tokens.append(std::move(t));+ }+ s->seeded = true;++ // We need the on-chain token-account address to subscribe by+ // account — but our `get_token_balance` doesn't return it.+ // For Phase 1 streaming, we subscribe to the wallet pubkey for+ // SOL only; FNCPT updates fall back to a per-30s poll inside+ // the same producer (driven from the WS heartbeat below). A+ // future enhancement is to surface the token account address+ // via SolanaRpcClient and `accountSubscribe` on it.++ fincept::datahub::DataHub::instance().publish(+ self->topic_for_pubkey(pubkey), QVariant::fromValue(s->latest));+ });+}++void WalletBalanceProducer::start_stream_for(const QString& pubkey) {+ if (streams_.contains(pubkey)) {+ return;+ }+ rpc_->reload_endpoint();++ // Block streaming on RPC endpoints that don't reliably serve+ // accountSubscribe (today: the public mainnet RPC). Surface the reason+ // through the hub so the screen can show it (bug fix #6).+ if (!endpoint_supports_streaming()) {+ LOG_WARN("WalletBalanceProducer",+ "stream mode unavailable on current RPC — falling back to poll for "+ + pubkey);+ fincept::datahub::DataHub::instance().publish_error(+ topic_for_pubkey(pubkey),+ QStringLiteral("STREAM unavailable on this RPC — using poll. "+ "Add a Helius API key in Settings for live updates."));+ refresh_one_poll(topic_for_pubkey(pubkey));+ return;+ }++ const QString ws_url = rpc_->ws_endpoint();++ auto* s = new StreamSession;+ s->pubkey = pubkey;+ s->ws = new WebSocketClient(this);+ streams_.insert(pubkey, s);++ // Per-session FNCPT heartbeat — there's no per-account WS subscription+ // for the FNCPT token account in this phase, so we re-fetch via REST+ // on a slow cadence (bug fix #5).+ s->fncpt_heartbeat = new QTimer(this);+ s->fncpt_heartbeat->setInterval(kFncptHeartbeatMs);+ s->fncpt_heartbeat->setSingleShot(false);+ QPointer<WalletBalanceProducer> hb_self = this;+ QObject::connect(s->fncpt_heartbeat, &QTimer::timeout, this, [hb_self, pubkey]() {+ if (!hb_self) return;+ if (!hb_self->streams_.contains(pubkey)) return;+ hb_self->seed_stream_state(pubkey);+ });+ s->fncpt_heartbeat->start();++ QPointer<WalletBalanceProducer> self = this;++ QObject::connect(s->ws, &WebSocketClient::connected, this, [self, pubkey]() {+ if (!self) {+ return;+ }+ auto it = self->streams_.find(pubkey);+ if (it == self->streams_.end()) {+ return;+ }+ auto* sess = it.value();+ // accountSubscribe(pubkey) — get notified on every lamport change.+ QJsonObject opts;+ opts[QStringLiteral("encoding")] = QStringLiteral("jsonParsed");+ opts[QStringLiteral("commitment")] = QStringLiteral("confirmed");+ QJsonObject req{+ {QStringLiteral("jsonrpc"), QStringLiteral("2.0")},+ {QStringLiteral("id"), sess->next_request_id++},+ {QStringLiteral("method"), QStringLiteral("accountSubscribe")},+ {QStringLiteral("params"), QJsonArray{pubkey, opts}}};+ sess->ws->send(QString::fromUtf8(QJsonDocument(req).toJson(QJsonDocument::Compact)));+ LOG_INFO("WalletBalanceProducer", "WS connected, subscribed to " + pubkey);++ // Bootstrap balances with one REST round-trip.+ self->seed_stream_state(pubkey);+ });++ QObject::connect(s->ws, &WebSocketClient::disconnected, this, [self, pubkey]() {+ if (!self) {+ return;+ }+ LOG_WARN("WalletBalanceProducer", "WS disconnected for " + pubkey);+ // The WebSocketClient auto-reconnects with exponential backoff.+ });++ QObject::connect(s->ws, &WebSocketClient::error_occurred, this,+ [self, pubkey](const QString& err) {+ if (!self) {+ return;+ }+ LOG_WARN("WalletBalanceProducer",+ QStringLiteral("WS error (%1): %2").arg(pubkey).arg(err));+ fincept::datahub::DataHub::instance().publish_error(+ self->topic_for_pubkey(pubkey), err);+ });++ QObject::connect(s->ws, &WebSocketClient::message_received, this,+ [self, pubkey](const QString& msg) {+ if (!self) {+ return;+ }+ auto it = self->streams_.find(pubkey);+ if (it == self->streams_.end()) {+ return;+ }+ auto* sess = it.value();+ QJsonParseError pe;+ const auto doc = QJsonDocument::fromJson(msg.toUtf8(), &pe);+ if (pe.error != QJsonParseError::NoError || !doc.isObject()) {+ return;+ }+ const auto root = doc.object();+ // Subscription confirmation: { result: <int>, id: ... }+ if (root.contains(QStringLiteral("id"))) {+ const auto sub_id = root.value(QStringLiteral("result")).toInt();+ if (sub_id > 0 && sess->sol_sub_id == 0) {+ sess->sol_sub_id = sub_id;+ LOG_INFO("WalletBalanceProducer",+ QStringLiteral("subscription %1 active for %2")+ .arg(sub_id)+ .arg(pubkey));+ }+ return;+ }+ // Notification: { method: "accountNotification",+ // params: { result: { value: { lamports: N, ... } } } }+ if (root.value(QStringLiteral("method")).toString()+ != QStringLiteral("accountNotification")) {+ return;+ }+ const auto params = root.value(QStringLiteral("params")).toObject();+ const auto result = params.value(QStringLiteral("result")).toObject();+ const auto value = result.value(QStringLiteral("value")).toObject();+ const auto lamports =+ parse_uint64(value.value(QStringLiteral("lamports")));+ sess->latest.pubkey_b58 = pubkey;+ sess->latest.sol_lamports = lamports;+ sess->latest.ts_ms = QDateTime::currentMSecsSinceEpoch();+ fincept::datahub::DataHub::instance().publish(+ self->topic_for_pubkey(pubkey),+ QVariant::fromValue(sess->latest));+ });++ s->ws->connect_to(ws_url);+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/WalletBalanceProducer.h b/fincept-qt/src/services/wallet/WalletBalanceProducer.hnew file mode 100644index 000000000..b76221068--- /dev/null+++ b/fincept-qt/src/services/wallet/WalletBalanceProducer.h@@ -0,0 +1,92 @@+#pragma once++#include "datahub/Producer.h"+#include "services/wallet/WalletTypes.h"++#include <QHash>+#include <QObject>+#include <QString>++class QTimer;++namespace fincept {+class WebSocketClient;+}++namespace fincept::wallet {++class SolanaRpcClient;++/// Refresh strategy for wallet balance data.+/// Poll — REST refresh on hub TTL (default, simplest).+/// Stream — WebSocket `accountSubscribe`, push-only updates.+enum class BalanceMode {+ Poll,+ Stream,+};++/// Owns the `wallet:balance:<pubkey>` topic family. Two modes:+///+/// Poll: `refresh()` hits Solana RPC for SOL + FNCPT, publishes a+/// WalletBalance. Hub TTL/min_interval drives cadence.+///+/// Stream: Per-pubkey WebSocket connection to the RPC's WS endpoint.+/// `accountSubscribe` on the wallet pubkey (SOL) and on the+/// FNCPT associated token account (FNCPT). Push-only — every+/// update is published immediately, hub coalesces 250 ms.+class WalletBalanceProducer : public QObject, public fincept::datahub::Producer {+ Q_OBJECT+ public:+ explicit WalletBalanceProducer(QObject* parent = nullptr);+ ~WalletBalanceProducer() override;++ QStringList topic_patterns() const override;+ void refresh(const QStringList& topics) override;+ int max_requests_per_sec() const override { return 4; }++ /// Set the active refresh strategy. Live — switching while subscribers+ /// exist tears down/spins up streams as needed.+ void set_mode(BalanceMode mode);+ BalanceMode mode() const noexcept { return mode_; }++ /// Reload mode from SecureStorage. Defaults to Poll. Idempotent.+ void reload_mode();++ /// User-driven hard refresh. In Poll mode this is equivalent to+ /// `refresh_one_poll(topic)`. In Stream mode it re-runs the seed (the+ /// only way to refresh FNCPT, which has no per-account WS subscription).+ /// Safe to call when not connected — it's a no-op.+ void force_refresh(const QString& pubkey);++ private:+ // Polling path+ void refresh_one_poll(const QString& topic);++ // Streaming path+ void start_stream_for(const QString& pubkey);+ void stop_stream_for(const QString& pubkey);+ void stop_all_streams();+ void seed_stream_state(const QString& pubkey);+ bool endpoint_supports_streaming() const;++ QString pubkey_from_topic(const QString& topic) const;+ QString topic_for_pubkey(const QString& pubkey) const;++ SolanaRpcClient* rpc_ = nullptr;+ BalanceMode mode_ = BalanceMode::Poll;++ struct StreamSession {+ WebSocketClient* ws = nullptr;+ QString pubkey;+ QString fncpt_token_account; ///< owner's associated FNCPT token account+ WalletBalance latest;+ int sol_sub_id = 0;+ int fncpt_sub_id = 0;+ int next_request_id = 1;+ bool seeded = false;+ QTimer* fncpt_heartbeat = nullptr; ///< re-polls FNCPT every ~30s+ };+ QHash<QString, StreamSession*> streams_; ///< keyed by pubkey+};++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/WalletService.cpp b/fincept-qt/src/services/wallet/WalletService.cppnew file mode 100644index 000000000..adc828c7a--- /dev/null+++ b/fincept-qt/src/services/wallet/WalletService.cpp@@ -0,0 +1,232 @@+#include "services/wallet/WalletService.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "datahub/TopicPolicy.h"+#include "services/wallet/ConnectWalletDialog.h"+#include "services/wallet/TokenPriceProducer.h"+#include "services/wallet/WalletActivityProducer.h"+#include "services/wallet/PumpFunSwapService.h"+#include "services/wallet/SignTransactionDialog.h"+#include "services/wallet/WalletBalanceProducer.h"+#include "storage/secure/SecureStorage.h"++#include "datahub/DataHub.h"++#include <QDateTime>+#include <QPointer>+#include <QWidget>++namespace fincept::wallet {++namespace {+// Persisted SecureStorage keys. See plan §4 for rationale.+constexpr const char* kKeyPubkey = "wallet.solana.pubkey";+constexpr const char* kKeyLabel = "wallet.solana.label";+constexpr const char* kKeyConnectedAt = "wallet.solana.connected_at";+} // namespace++WalletService& WalletService::instance() {+ static WalletService s;+ return s;+}++WalletService::WalletService() {+ balance_producer_ = new WalletBalanceProducer(this);+ price_producer_ = new TokenPriceProducer(this);+ swap_service_ = new PumpFunSwapService(this);+ activity_producer_ = new WalletActivityProducer(this);+}++WalletService::~WalletService() = default;++void WalletService::ensure_registered_with_hub() {+ if (hub_registered_) {+ return;+ }+ auto& hub = fincept::datahub::DataHub::instance();+ hub.register_producer(balance_producer_);+ hub.register_producer(price_producer_);+ hub.register_producer(activity_producer_);+ // PumpFunSwapService is one-shot (user-initiated build_swap call); it+ // doesn't expose any hub topics and is not registered as a Producer.+ // See CLAUDE.md D2 exception clause.++ fincept::datahub::TopicPolicy balance_policy;+ balance_policy.ttl_ms = 30 * 1000;+ balance_policy.min_interval_ms = 10 * 1000;+ balance_policy.refresh_timeout_ms = 15 * 1000;+ hub.set_policy_pattern(QStringLiteral("wallet:balance:*"), balance_policy);++ fincept::datahub::TopicPolicy price_policy;+ price_policy.ttl_ms = 60 * 1000;+ price_policy.min_interval_ms = 30 * 1000;+ price_policy.refresh_timeout_ms = 15 * 1000;+ price_policy.coalesce_within_ms = 250; // batch concurrent mint subscribes+ // Phase 2 §2A.5: generalised topic family for any token's USD price.+ hub.set_policy_pattern(QStringLiteral("market:price:token:*"), price_policy);+ // Backward-compat alias kept for one phase. Removed in Phase 3.+ hub.set_policy(QStringLiteral("market:price:fncpt"), price_policy);++ // Phase 2 §2B: parsed activity feed.+ fincept::datahub::TopicPolicy activity_policy;+ activity_policy.ttl_ms = 30 * 1000;+ activity_policy.min_interval_ms = 10 * 1000;+ activity_policy.refresh_timeout_ms = 15 * 1000;+ hub.set_policy_pattern(QStringLiteral("wallet:activity:*"), activity_policy);++ hub_registered_ = true;+ LOG_INFO("WalletService",+ "Registered with DataHub (wallet:balance:*, market:price:token:*, "+ "market:price:fncpt[deprecated alias], wallet:activity:*)");+}++void WalletService::restore_from_storage() {+ auto pk_res = SecureStorage::instance().retrieve(QString::fromLatin1(kKeyPubkey));+ if (pk_res.is_err() || pk_res.value().isEmpty()) {+ return;+ }+ WalletState s;+ s.pubkey_b58 = pk_res.value();++ auto lbl_res = SecureStorage::instance().retrieve(QString::fromLatin1(kKeyLabel));+ if (lbl_res.is_ok()) {+ s.label = lbl_res.value();+ }+ auto ts_res = SecureStorage::instance().retrieve(QString::fromLatin1(kKeyConnectedAt));+ if (ts_res.is_ok()) {+ bool ok = false;+ const auto v = ts_res.value().toLongLong(&ok);+ if (ok) {+ s.connected_at_ms = v;+ }+ }+ s.soft_connected = true;+ set_state(std::move(s));+ LOG_INFO("WalletService", "Restored soft-connected wallet: " + state_.pubkey_b58);+ emit wallet_connected(state_.pubkey_b58, state_.label);+}++void WalletService::connect_with_dialog(QWidget* parent) {+ auto* dlg = new ConnectWalletDialog(parent);+ dlg->setAttribute(Qt::WA_DeleteOnClose);+ QPointer<WalletService> self = this;+ connect(dlg, &ConnectWalletDialog::connected, this,+ [self](QString pubkey, QString label) {+ if (!self) {+ return;+ }+ WalletState s;+ s.pubkey_b58 = std::move(pubkey);+ s.label = std::move(label);+ s.connected_at_ms = QDateTime::currentMSecsSinceEpoch();+ s.soft_connected = false;+ self->set_state(std::move(s));+ self->persist_state();+ LOG_INFO("WalletService", "Wallet connected: " + self->state_.pubkey_b58);+ emit self->wallet_connected(self->state_.pubkey_b58, self->state_.label);+ });+ connect(dlg, &ConnectWalletDialog::failed, this,+ [self](QString reason) {+ if (!self) {+ return;+ }+ LOG_WARN("WalletService", "Connect failed: " + reason);+ emit self->connect_failed(reason);+ });+ dlg->open();+}++void WalletService::disconnect() {+ if (!state_.is_connected()) {+ return;+ }+ LOG_INFO("WalletService", "Disconnecting wallet: " + state_.pubkey_b58);+ clear_persisted_state();+ state_ = {};+ emit wallet_disconnected();+}++void WalletService::set_state(WalletState s) {+ state_ = std::move(s);+}++void WalletService::persist_state() {+ auto& store = SecureStorage::instance();+ store.store(QString::fromLatin1(kKeyPubkey), state_.pubkey_b58);+ store.store(QString::fromLatin1(kKeyLabel), state_.label);+ store.store(QString::fromLatin1(kKeyConnectedAt),+ QString::number(state_.connected_at_ms));+}++void WalletService::clear_persisted_state() {+ auto& store = SecureStorage::instance();+ store.remove(QString::fromLatin1(kKeyPubkey));+ store.remove(QString::fromLatin1(kKeyLabel));+ store.remove(QString::fromLatin1(kKeyConnectedAt));+}++void WalletService::set_balance_mode(bool stream) {+ const auto wanted = stream ? BalanceMode::Stream : BalanceMode::Poll;+ if (!balance_producer_) {+ return;+ }+ if (balance_producer_->mode() == wanted) {+ return;+ }+ SecureStorage::instance().store(QStringLiteral("wallet.balance_mode"),+ stream ? QStringLiteral("stream") : QStringLiteral("poll"));+ balance_producer_->set_mode(wanted);+ LOG_INFO("WalletService", QStringLiteral("balance mode set to %1").arg(stream ? "stream" : "poll"));++ // Force a refresh so subscribers see fresh data via the new path.+ if (state_.is_connected()) {+ const auto topic = QStringLiteral("wallet:balance:%1").arg(state_.pubkey_b58);+ fincept::datahub::DataHub::instance().request(topic, /*force=*/true);+ }+ emit balance_mode_changed(stream);+}++bool WalletService::balance_mode_is_stream() const noexcept {+ return balance_producer_ && balance_producer_->mode() == BalanceMode::Stream;+}++void WalletService::force_balance_refresh() {+ if (!balance_producer_ || !state_.is_connected()) {+ return;+ }+ balance_producer_->force_refresh(state_.pubkey_b58);+}++void WalletService::sign_and_send(const QString& tx_base64,+ const QString& dialog_title,+ const QString& dialog_lede,+ QWidget* parent,+ std::function<void(Result<QString>)> cb) {+ if (tx_base64.isEmpty()) {+ if (cb) cb(Result<QString>::err("empty_tx"));+ return;+ }+ if (!state_.is_connected()) {+ if (cb) cb(Result<QString>::err("not_connected"));+ return;+ }++ auto* dlg = new SignTransactionDialog(tx_base64, dialog_title, dialog_lede, parent);+ dlg->setAttribute(Qt::WA_DeleteOnClose);++ QPointer<SignTransactionDialog> guard = dlg;+ connect(dlg, &QDialog::accepted, this, [guard, cb]() {+ if (!cb || !guard) return;+ cb(Result<QString>::ok(guard->signature()));+ });+ connect(dlg, &QDialog::rejected, this, [guard, cb]() {+ if (!cb || !guard) return;+ const auto reason = guard->failure_reason();+ cb(Result<QString>::err(reason.isEmpty() ? std::string("rejected")+ : reason.toStdString()));+ });+ dlg->open();+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/WalletService.h b/fincept-qt/src/services/wallet/WalletService.hnew file mode 100644index 000000000..01c1e52fe--- /dev/null+++ b/fincept-qt/src/services/wallet/WalletService.h@@ -0,0 +1,121 @@+#pragma once++#include "core/result/Result.h"++#include <QObject>+#include <QString>++#include <functional>++class QWidget;++namespace fincept::wallet {++class WalletBalanceProducer;+class TokenPriceProducer;+class WalletActivityProducer;++/// In-memory wallet state. Persisted across runs (pubkey + label only;+/// **never** keys, signatures, or session secrets).+struct WalletState {+ QString pubkey_b58;+ QString label; ///< wallet name as reported by the connect page (e.g. "phantom")+ qint64 connected_at_ms = 0;+ bool soft_connected = false; ///< restored from SecureStorage but not yet re-challenged+ bool is_connected() const noexcept { return !pubkey_b58.isEmpty(); }+};++/// Singleton owning the user's connected wallet identity.+///+/// Phase 1 scope: read-only — pubkey, label, balance display.+/// No transaction signing or fund movement happens here.+///+/// Persisted state lives in `SecureStorage`. We restore it on startup as a+/// "soft-connected" session: balances are visible but the next operation that+/// requires user authority will trigger a fresh sign-message challenge.+class WalletService : public QObject {+ Q_OBJECT+ public:+ static WalletService& instance();++ /// Ensure the producers are registered with DataHub. Idempotent.+ /// Called once from main.cpp during startup.+ void ensure_registered_with_hub();++ /// Restore pubkey from SecureStorage if present. No network calls.+ /// Idempotent. Emits `wallet_connected` if a saved state was restored.+ void restore_from_storage();++ /// Spawn the connect dialog modally on `parent`. Async — returns+ /// immediately. On success, emits `wallet_connected(pubkey)`.+ void connect_with_dialog(QWidget* parent);++ /// Forget the current wallet. Clears SecureStorage state and emits+ /// `wallet_disconnected()`. Safe to call when not connected.+ void disconnect();++ /// Current state snapshot. Read on the main thread.+ const WalletState& state() const noexcept { return state_; }+ bool is_connected() const noexcept { return state_.is_connected(); }+ QString current_pubkey() const noexcept { return state_.pubkey_b58; }++ /// Switch the balance producer between polling and streaming mode.+ /// Persists the choice to SecureStorage so it survives restart.+ /// Emits balance_mode_changed.+ void set_balance_mode(bool stream);+ bool balance_mode_is_stream() const noexcept;++ /// User-driven hard refresh of the balance topic. In Poll mode this is a+ /// REST round-trip; in Stream mode it re-runs the seed (the only way+ /// to refresh FNCPT, which has no per-account WS subscription). No-op+ /// when not connected.+ void force_balance_refresh();++ /// The PumpPortal swap service owned by this WalletService. One-shot;+ /// not a Producer (per CLAUDE.md D2 exception). `SwapPanel` calls+ /// `build_swap()` directly when the user clicks SWAP.+ class PumpFunSwapService* swap_service() noexcept { return swap_service_; }++ /// Forward `tx_base64` to the user's wallet for `signAndSendTransaction`.+ ///+ /// Opens a small modal `SignTransactionDialog` parented to `parent` (or+ /// `nullptr` for a top-level dialog), spins up a per-call `WalletTxBridge`,+ /// and launches the wallet HTML page in the user's default browser.+ ///+ /// `dialog_title` and `dialog_lede` are the user-facing strings shown on+ /// the wait dialog (e.g. "Sign swap" / "Approve in Phantom to complete+ /// the trade.").+ ///+ /// `cb` resolves with the base58 signature on success, or an error code+ /// on cancel / timeout / wallet error. Always called on the UI thread.+ void sign_and_send(const QString& tx_base64,+ const QString& dialog_title,+ const QString& dialog_lede,+ QWidget* parent,+ std::function<void(Result<QString>)> cb);++ signals:+ void wallet_connected(QString pubkey_b58, QString label);+ void wallet_disconnected();+ void connect_failed(QString reason);+ void balance_mode_changed(bool is_stream);++ private:+ WalletService();+ ~WalletService() override;+ WalletService(const WalletService&) = delete;+ WalletService& operator=(const WalletService&) = delete;++ void persist_state();+ void clear_persisted_state();+ void set_state(WalletState s);++ WalletState state_;+ bool hub_registered_ = false;+ WalletBalanceProducer* balance_producer_ = nullptr;+ TokenPriceProducer* price_producer_ = nullptr;+ class PumpFunSwapService* swap_service_ = nullptr;+ WalletActivityProducer* activity_producer_ = nullptr;+};++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/WalletTxBridge.cpp b/fincept-qt/src/services/wallet/WalletTxBridge.cppnew file mode 100644index 000000000..934be8680--- /dev/null+++ b/fincept-qt/src/services/wallet/WalletTxBridge.cpp@@ -0,0 +1,388 @@+#include "services/wallet/WalletTxBridge.h"++#include "core/logging/Logger.h"++#include <QByteArray>+#include <QCoreApplication>+#include <QDateTime>+#include <QFile>+#include <QHostAddress>+#include <QJsonDocument>+#include <QJsonObject>+#include <QRandomGenerator>+#include <QTcpServer>+#include <QTcpSocket>+#include <QTimerEvent>+#include <QUrlQuery>+#include <QUuid>++namespace fincept::wallet {++namespace {++constexpr int kSweepIntervalMs = 5 * 1000; // purge expired requests every 5s+constexpr int kMaxRequestBytes = 32 * 1024;++QByteArray tx_random_token_hex(int n_bytes) {+ QByteArray buf;+ buf.resize(n_bytes);+ QRandomGenerator::system()->generate(reinterpret_cast<quint32*>(buf.data()),+ reinterpret_cast<quint32*>(buf.data() + n_bytes));+ return buf.toHex();+}++QString new_request_id() {+ return QUuid::createUuid().toString(QUuid::WithoutBraces);+}++bool tx_path_starts_with(const QByteArray& path, const char* prefix) {+ return path.startsWith(QByteArray::fromRawData(prefix, qstrlen(prefix)));+}++QByteArray tx_query_param(const QByteArray& path, const char* key) {+ const auto idx = path.indexOf('?');+ if (idx < 0) {+ return {};+ }+ QUrlQuery q(QString::fromLatin1(path.mid(idx + 1)));+ return q.queryItemValue(QString::fromLatin1(key)).toLatin1();+}++QByteArray load_swap_html() {+ const QString path = QCoreApplication::applicationDirPath()+ + QStringLiteral("/resources/wallet/swap.html");+ QFile f(path);+ if (!f.open(QIODevice::ReadOnly)) {+ LOG_WARN("WalletTxBridge", "swap.html not found at " + path);+ return {};+ }+ return f.readAll();+}++} // namespace++WalletTxBridge::WalletTxBridge(QObject* parent) : QObject(parent) {}++WalletTxBridge::~WalletTxBridge() {+ // Resolve any outstanding requests as cancelled so callers don't dangle.+ for (auto it = requests_.constBegin(); it != requests_.constEnd(); ++it) {+ if (it.value().cb) {+ it.value().cb(Result<QString>::err("bridge_destroyed"));+ }+ }+ requests_.clear();+ stop_server();+}++Result<QString> WalletTxBridge::request_signature(const QString& tx_base64,+ SignatureCallback cb,+ int timeout_seconds) {+ if (tx_base64.isEmpty()) {+ return Result<QString>::err("empty_tx");+ }+ if (!ensure_server_started()) {+ return Result<QString>::err("bridge_listen_failed");+ }+ purge_expired_requests();++ PendingRequest pr;+ pr.tx_base64 = tx_base64;+ pr.cb = std::move(cb);+ pr.created_at_ms = QDateTime::currentMSecsSinceEpoch();+ pr.timeout_seconds = timeout_seconds > 0 ? timeout_seconds : 60;++ const QString req_id = new_request_id();+ requests_.insert(req_id, std::move(pr));++ const quint16 port = server_->serverPort();+ const QString url = QStringLiteral("http://127.0.0.1:%1/swap?req=%2&token=%3")+ .arg(port)+ .arg(req_id, QString::fromLatin1(session_token_));+ LOG_INFO("WalletTxBridge",+ QStringLiteral("registered sign request %1 (expires %2s)")+ .arg(req_id)+ .arg(pr.timeout_seconds));+ return Result<QString>::ok(url);+}++void WalletTxBridge::cancel(const QString& request_id) {+ if (!requests_.contains(request_id)) {+ return;+ }+ LOG_INFO("WalletTxBridge", "cancel request " + request_id);+ resolve_request(request_id, Result<QString>::err("user_cancelled"));+}++bool WalletTxBridge::is_listening() const noexcept {+ return server_ != nullptr && server_->isListening();+}++bool WalletTxBridge::ensure_server_started() {+ if (server_ && server_->isListening()) {+ return true;+ }+ session_token_ = tx_random_token_hex(16);+ server_ = new QTcpServer(this);+ connect(server_, &QTcpServer::newConnection, this, &WalletTxBridge::on_new_connection);++ if (!server_->listen(QHostAddress::LocalHost, 0)) {+ const QString err = server_->errorString();+ LOG_ERROR("WalletTxBridge", "listen() failed: " + err);+ emit bridge_error(err);+ stop_server();+ return false;+ }+ if (sweep_timer_id_ == 0) {+ sweep_timer_id_ = startTimer(kSweepIntervalMs);+ }+ LOG_INFO("WalletTxBridge",+ QStringLiteral("listening on 127.0.0.1:%1").arg(server_->serverPort()));+ return true;+}++void WalletTxBridge::stop_server() {+ if (sweep_timer_id_ != 0) {+ killTimer(sweep_timer_id_);+ sweep_timer_id_ = 0;+ }+ if (server_) {+ server_->close();+ server_->deleteLater();+ server_ = nullptr;+ }+ session_token_.clear();+}++void WalletTxBridge::purge_expired_requests() {+ const auto now = QDateTime::currentMSecsSinceEpoch();+ QStringList expired;+ for (auto it = requests_.constBegin(); it != requests_.constEnd(); ++it) {+ const auto& pr = it.value();+ const auto age_ms = now - pr.created_at_ms;+ if (age_ms > qint64(pr.timeout_seconds) * 1000) {+ expired.append(it.key());+ }+ }+ for (const auto& id : expired) {+ LOG_WARN("WalletTxBridge", "expired request " + id);+ resolve_request(id, Result<QString>::err("timeout"));+ }+}++void WalletTxBridge::resolve_request(const QString& request_id, Result<QString> result) {+ auto it = requests_.find(request_id);+ if (it == requests_.end()) {+ return;+ }+ auto cb = std::move(it.value().cb);+ requests_.erase(it);+ if (requests_.isEmpty()) {+ stop_server();+ }+ if (cb) {+ cb(std::move(result));+ }+}++void WalletTxBridge::timerEvent(QTimerEvent* e) {+ if (e->timerId() == sweep_timer_id_) {+ purge_expired_requests();+ }+}++void WalletTxBridge::on_new_connection() {+ if (!server_) {+ return;+ }+ while (auto* socket = server_->nextPendingConnection()) {+ connect(socket, &QTcpSocket::disconnected, socket, &QObject::deleteLater);+ connect(socket, &QTcpSocket::readyRead, this, [this, socket]() {+ const QByteArray buf = socket->peek(kMaxRequestBytes);+ const int header_end = buf.indexOf("\r\n\r\n");+ if (header_end < 0) {+ if (buf.size() >= kMaxRequestBytes) {+ write_response(socket, 413, "text/plain", "request too large");+ socket->disconnectFromHost();+ }+ return;+ }+ const QByteArray header_block = buf.left(header_end);+ int content_length = 0;+ for (const auto& line : header_block.split('\n')) {+ const auto trimmed = line.trimmed();+ if (trimmed.toLower().startsWith("content-length:")) {+ content_length = trimmed.mid(15).trimmed().toInt();+ break;+ }+ }+ const int total_required = header_end + 4 + content_length;+ if (buf.size() < total_required) {+ return;+ }+ socket->read(total_required);++ const auto first_line = header_block.split('\n').value(0).trimmed();+ const auto parts = first_line.split(' ');+ if (parts.size() < 2) {+ write_response(socket, 400, "text/plain", "bad request");+ socket->disconnectFromHost();+ return;+ }+ const QByteArray method = parts.value(0);+ const QByteArray path = parts.value(1);+ const QByteArray body = buf.mid(header_end + 4, content_length);+ handle_request(socket, body, path, method);+ });+ }+}++void WalletTxBridge::handle_request(QTcpSocket* socket,+ const QByteArray& body,+ const QByteArray& path,+ const QByteArray& method) {+ LOG_INFO("WalletTxBridge",+ QStringLiteral("request %1 %2 (body=%3)")+ .arg(QString::fromLatin1(method),+ QString::fromLatin1(path))+ .arg(body.size()));++ if (method == "OPTIONS") {+ write_response(socket, 204, "text/plain", QByteArray());+ socket->disconnectFromHost();+ return;+ }+ if (method == "GET" && path == "/favicon.ico") {+ write_response(socket, 204, "image/x-icon", QByteArray());+ socket->disconnectFromHost();+ return;+ }++ // Static asset: vendored @solana/web3.js. Served without a per-request+ // token because the <script> tag in swap.html cannot carry one (the+ // page URL has it, the relative script src does not). The asset itself+ // is read-only, embedded in the binary's resource directory, and only+ // reachable from 127.0.0.1 — no privilege boundary is crossed.+ if (method == "GET" && tx_path_starts_with(path, "/vendor/web3.js")) {+ const QString abs_path = QCoreApplication::applicationDirPath()+ + QStringLiteral("/resources/wallet/vendor/web3.js");+ QFile f(abs_path);+ if (!f.open(QIODevice::ReadOnly)) {+ LOG_WARN("WalletTxBridge", "vendored web3.js missing at " + abs_path);+ write_response(socket, 404, "text/plain", "vendor asset missing");+ } else {+ write_response(socket, 200,+ "application/javascript; charset=utf-8",+ f.readAll());+ }+ socket->disconnectFromHost();+ return;+ }++ const auto token_in_query = tx_query_param(path, "token");+ if (token_in_query != session_token_) {+ LOG_WARN("WalletTxBridge", "token mismatch — rejecting");+ write_response(socket, 403, "text/plain", "forbidden");+ socket->disconnectFromHost();+ return;+ }+ const auto req_id = QString::fromLatin1(tx_query_param(path, "req"));+ if (req_id.isEmpty()) {+ write_response(socket, 400, "text/plain", "missing req");+ socket->disconnectFromHost();+ return;+ }+ if (!requests_.contains(req_id)) {+ // Either expired or unknown. Either way, single-use and gone.+ LOG_WARN("WalletTxBridge", "unknown / expired request " + req_id);+ write_response(socket, 410, "text/plain", "gone");+ socket->disconnectFromHost();+ return;+ }++ if (method == "GET" && tx_path_starts_with(path, "/swap")) {+ const auto html = render_swap_page();+ write_response(socket, 200, "text/html; charset=utf-8", html);+ socket->disconnectFromHost();+ return;+ }++ if (method == "GET" && tx_path_starts_with(path, "/tx")) {+ const auto& pr = requests_.value(req_id);+ QJsonObject out;+ out[QStringLiteral("tx_base64")] = pr.tx_base64;+ write_response(socket, 200, "application/json",+ QJsonDocument(out).toJson(QJsonDocument::Compact));+ socket->disconnectFromHost();+ return;+ }++ if (method == "POST" && tx_path_starts_with(path, "/result")) {+ QJsonParseError pe;+ const auto doc = QJsonDocument::fromJson(body, &pe);+ if (pe.error != QJsonParseError::NoError || !doc.isObject()) {+ write_response(socket, 400, "text/plain", "bad json");+ socket->disconnectFromHost();+ return;+ }+ const auto obj = doc.object();+ const auto err_str = obj.value(QStringLiteral("error")).toString();+ if (!err_str.isEmpty()) {+ resolve_request(req_id, Result<QString>::err(err_str.toStdString()));+ } else {+ const auto sig = obj.value(QStringLiteral("signature")).toString();+ if (sig.isEmpty()) {+ resolve_request(req_id, Result<QString>::err("empty signature"));+ } else {+ resolve_request(req_id, Result<QString>::ok(sig));+ }+ }+ write_response(socket, 200, "application/json",+ QByteArrayLiteral("{\"ok\":true}"));+ socket->disconnectFromHost();+ return;+ }++ write_response(socket, 404, "text/plain", "not found");+ socket->disconnectFromHost();+}++QByteArray WalletTxBridge::render_swap_page() const {+ auto html = load_swap_html();+ if (html.isEmpty()) {+ // Defensive: until Stage 2.2 ships swap.html, return a clear stub.+ // Won't be reached in normal builds — CMakeLists copies the page.+ return QByteArrayLiteral(+ "<!doctype html><meta charset='utf-8'><title>Sign</title>"+ "<body style='background:#0a0a0a;color:#d97706;font-family:monospace;"+ "padding:20px'>swap.html missing — Stage 2.2 work-in-progress</body>");+ }+ return html;+}++void WalletTxBridge::write_response(QTcpSocket* socket, int status,+ const QByteArray& content_type,+ const QByteArray& body) {+ QByteArray reason;+ switch (status) {+ case 200: reason = "OK"; break;+ case 204: reason = "No Content"; break;+ case 400: reason = "Bad Request"; break;+ case 403: reason = "Forbidden"; break;+ case 404: reason = "Not Found"; break;+ case 410: reason = "Gone"; break;+ case 413: reason = "Payload Too Large"; break;+ default: reason = "Error"; break;+ }+ QByteArray header;+ header += "HTTP/1.1 " + QByteArray::number(status) + " " + reason + "\r\n";+ header += "Content-Type: " + content_type + "\r\n";+ header += "Content-Length: " + QByteArray::number(body.size()) + "\r\n";+ header += "Cache-Control: no-store\r\n";+ header += "Connection: close\r\n";+ header += "\r\n";+ socket->write(header);+ socket->write(body);+ socket->flush();+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/WalletTxBridge.h b/fincept-qt/src/services/wallet/WalletTxBridge.hnew file mode 100644index 000000000..22c25ff92--- /dev/null+++ b/fincept-qt/src/services/wallet/WalletTxBridge.h@@ -0,0 +1,99 @@+#pragma once++#include "core/result/Result.h"++#include <QByteArray>+#include <QHash>+#include <QObject>+#include <QString>++class QTcpServer;+class QTcpSocket;++namespace fincept::wallet {++/// Loopback HTTP bridge for **transaction signing**, distinct from the+/// connect-handshake bridge. Phase 2 introduces this so that the connect+/// flow's threat model (sign-message handshake, single-use connect token,+/// 30 s lifetime) remains untouched by the new sign-tx capability.+///+/// Lifecycle of a single sign request:+/// 1. C++ caller invokes `request_signature(tx_b64)` and receives a+/// `request_id`. The bridge mints a single-use UUID, records the+/// pending tx, and starts listening on a random ephemeral loopback+/// port if it isn't already.+/// 2. The caller opens `swap.html` in the wallet dialog with+/// `?req=<request_id>&token=<token>`.+/// 3. The page fetches `GET /tx?req=<id>&token=<token>` to retrieve the+/// base64 transaction. The page never receives any other tx.+/// 4. The page signs via the wallet adapter and POSTs+/// `{ signature: "<b58>" }` (or `{ error: "..." }`) to+/// `/result?req=<id>&token=<token>`.+/// 5. Bridge resolves `request_signature`'s callback with the result and+/// retires the request_id (single-use). UUIDs older than 60 s are+/// auto-purged on every new request.+///+/// Security properties:+/// - listens only on `QHostAddress::LocalHost`.+/// - random port; random 32-byte token in URL query.+/// - per-request UUID; one request_id services exactly one signature+/// attempt; expired ids return 410 Gone, never reuse a previously-seen+/// transaction body.+/// - the page is loaded from `qrc://`, never `https://`. The bridge only+/// ever serves pre-built embedded HTML and the requested tx body.+/// - server self-stops when no in-flight requests remain.+class WalletTxBridge : public QObject {+ Q_OBJECT+ public:+ using SignatureCallback = std::function<void(Result<QString>)>;++ explicit WalletTxBridge(QObject* parent = nullptr);+ ~WalletTxBridge() override;++ /// Register a tx for signing. Returns `Result<QString>` containing the+ /// browser URL to open in the wallet dialog. Calls `cb` later with the+ /// base58 signature on success, or an error string. UUIDs expire after+ /// 60 s if no result is delivered.+ Result<QString> request_signature(const QString& tx_base64,+ SignatureCallback cb,+ int timeout_seconds = 60);++ /// Cancel a pending request. Idempotent — the cb fires with err+ /// "user_cancelled" if it hadn't already resolved.+ void cancel(const QString& request_id);++ /// True if the loopback server is currently listening for any request.+ bool is_listening() const noexcept;++ signals:+ void bridge_error(QString message);++ private:+ struct PendingRequest {+ QString tx_base64;+ SignatureCallback cb;+ qint64 created_at_ms = 0;+ int timeout_seconds = 60;+ };++ void on_new_connection();+ void handle_request(QTcpSocket* socket, const QByteArray& body,+ const QByteArray& path, const QByteArray& method);+ QByteArray render_swap_page() const;+ void write_response(QTcpSocket* socket, int status,+ const QByteArray& content_type, const QByteArray& body);+ bool ensure_server_started();+ void stop_server();+ void purge_expired_requests();+ void resolve_request(const QString& request_id, Result<QString> result);++ QTcpServer* server_ = nullptr;+ QByteArray session_token_;+ QHash<QString, PendingRequest> requests_;+ int sweep_timer_id_ = 0;++ protected:+ void timerEvent(QTimerEvent* e) override;+};++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/WalletTypes.cpp b/fincept-qt/src/services/wallet/WalletTypes.cppnew file mode 100644index 000000000..f2eb1ede7--- /dev/null+++ b/fincept-qt/src/services/wallet/WalletTypes.cpp@@ -0,0 +1,36 @@+#include "services/wallet/WalletTypes.h"++#include <cmath>++namespace fincept::wallet {++double TokenHolding::ui_amount() const noexcept {+ if (amount_raw.isEmpty()) return 0.0;+ bool ok = false;+ const auto raw = amount_raw.toLongLong(&ok);+ if (!ok) return 0.0;+ return static_cast<double>(raw) / std::pow(10.0, decimals);+}++const TokenHolding* WalletBalance::fncpt_holding() const noexcept {+ const auto fncpt = QString::fromLatin1(kFncptMint);+ for (const auto& t : tokens) {+ if (t.mint == fncpt) return &t;+ }+ return nullptr;+}++double WalletBalance::fncpt_ui() const noexcept {+ const auto* h = fncpt_holding();+ return h ? h->ui_amount() : 0.0;+}++int WalletBalance::fncpt_decimals() const noexcept {+ const auto* h = fncpt_holding();+ // Pump.fun mints default to 6 decimals; if we don't hold the token we+ // still need to scale balance amounts correctly (e.g. for Settings'+ // "1,000 $FNCPT" threshold), so fall back to 6.+ return (h && h->decimals > 0) ? h->decimals : 6;+}++} // namespace fincept::walletdiff --git a/fincept-qt/src/services/wallet/WalletTypes.h b/fincept-qt/src/services/wallet/WalletTypes.hnew file mode 100644index 000000000..072bb9125--- /dev/null+++ b/fincept-qt/src/services/wallet/WalletTypes.h@@ -0,0 +1,144 @@+#pragma once++#include <QMetaType>+#include <QString>+#include <QStringList>+#include <QVector>++namespace fincept::wallet {++/// $FNCPT canonical mint. Used by the back-compat accessors on `WalletBalance`+/// and by the price-topic alias mapping.+inline constexpr const char* kFncptMint =+ "9LUqJ5aQTjQiUCL93gi33LZcscUoSBJNhVCYpPzEpump";++/// Wrapped-SOL mint. SOL itself isn't an SPL token (it's the native asset),+/// but most pricing APIs key it by the wSOL mint.+inline constexpr const char* kWrappedSolMint =+ "So11111111111111111111111111111111111111112";++/// Display metadata for a single SPL token. Provided by `TokenMetadataService`+/// (2A.5.2). Cached daily; persisted to SecureStorage between runs.+struct TokenMetadata {+ QString mint;+ QString symbol;+ QString name;+ int decimals = 0;+ QString icon_url;+ bool verified = false; ///< present in Jupiter's verified tagged list+};++/// One asset held by a wallet — SOL or any SPL token. SOL is represented+/// as a `TokenHolding` with `mint = kWrappedSolMint` and `symbol = "SOL"`+/// inside `WalletBalance::tokens`, with the actual lamports also surfaced+/// via the dedicated `sol_lamports` field for callers that want native SOL+/// distinct from a wrapped-SOL holding.+struct TokenHolding {+ QString mint; ///< base58 SPL mint+ QString symbol; ///< resolved via TokenMetadataService; truncated mint if unknown+ QString name; ///< full name; "" if unknown+ QString amount_raw; ///< integer string (atomic, not decimal-shifted)+ int decimals = 0; ///< from on-chain parsed token-account info+ bool verified = false;+ QString icon_url; ///< empty if unknown++ /// `amount_raw / 10^decimals`. 0.0 if amount_raw is empty / unparseable.+ double ui_amount() const noexcept;+};++/// One snapshot of a wallet's balances. Published to `wallet:balance:<pubkey>`.+///+/// Shape upgraded in Phase 2 Stage 2A.5: `tokens` carries every SPL token+/// account the wallet holds, sorted by USD value at publish time. The legacy+/// `fncpt_*` fields are gone; existing callers should use the back-compat+/// accessors `fncpt_holding()` / `fncpt_ui()` / `fncpt_decimals()`.+struct WalletBalance {+ QString pubkey_b58;+ quint64 sol_lamports = 0;+ QVector<TokenHolding> tokens; ///< sorted by USD value desc at publish time+ qint64 ts_ms = 0;++ double sol() const noexcept { return static_cast<double>(sol_lamports) / 1e9; }++ /// Find the FNCPT entry in `tokens`, or nullptr if the wallet doesn't+ /// hold any FNCPT.+ const TokenHolding* fncpt_holding() const noexcept;++ /// Convenience: 0.0 if not held.+ double fncpt_ui() const noexcept;++ /// Convenience: returns the on-chain decimals if FNCPT is held; otherwise+ /// the canonical FNCPT decimals (6, pump.fun standard).+ int fncpt_decimals() const noexcept;+};++/// Price snapshot for a single token mint. Published to+/// `market:price:token:<mint>` (and aliased to `market:price:fncpt` for the+/// canonical FNCPT mint, deprecated for one phase).+struct TokenPrice {+ QString mint;+ double usd = 0.0;+ double sol = 0.0;+ qint64 ts_ms = 0;+ bool valid = false;+};++/// Back-compat alias. Existing call sites that read `FncptPrice` continue to+/// compile against the new `TokenPrice` shape — same fields, same semantics.+/// Removed in Phase 3 cleanup once all consumers migrate.+using FncptPrice = TokenPrice;++/// Fee-discount eligibility for a wallet. Published on+/// `billing:fncpt_discount:<pubkey>` (Phase 2 §2C).+///+/// Derived state: `FeeDiscountService` subscribes to `wallet:balance:<pk>`+/// and republishes a `FncptDiscount` whenever the held FNCPT amount crosses+/// the threshold (or the balance topic emits anew at the same eligibility+/// state — consumers re-render either way; cheap).+struct FncptDiscount {+ bool eligible = false;+ quint64 threshold_raw = 0; ///< from FeeDiscountConfig::kThresholdRaw+ int threshold_decimals = 6;+ int discount_pct = 0;+ QStringList applied_skus; ///< stable SKU ids; panel maps to labels+ QString pubkey_b58; ///< for diagnostics; the topic also encodes it+ qint64 ts_ms = 0;+};++/// One parsed on-chain operation involving the wallet. Published as part of+/// `QVector<ParsedActivity>` on `wallet:activity:<pubkey>` (Phase 2 §2B).+///+/// Source priority:+/// - Helius parsed-tx (`api.helius.xyz/v0/addresses/<pk>/transactions`)+/// when `solana.helius_api_key` is set in SecureStorage. Helius classifies+/// SWAP / RECEIVE / SEND directly.+/// - Fallback: `SolanaRpcClient::get_signatures_for_address` returns raw+/// signatures only; `kind` defaults to `Other` and `asset`/`amount_ui`+/// are empty in that case.+struct ParsedActivity {+ enum class Kind {+ Swap, ///< token-for-token (or SOL) swap on a DEX+ Receive, ///< incoming transfer+ Send, ///< outgoing transfer+ Other ///< Helius didn't classify, or fallback path+ };++ qint64 ts_ms = 0; ///< unix ms; 0 if Helius didn't include block time+ Kind kind = Kind::Other;+ QString asset; ///< e.g. "SOL → $FNCPT" or just "SOL"+ QString amount_ui; ///< pre-formatted amount string, e.g. "0.50 → 12,304"+ QString signature; ///< base58 tx signature (clickable to Solscan)+ QString status; ///< "confirmed" / "failed" / "" if unknown+ QString counterparty; ///< for SEND/RECEIVE; empty otherwise+};++} // namespace fincept::wallet++Q_DECLARE_METATYPE(fincept::wallet::WalletBalance)+Q_DECLARE_METATYPE(fincept::wallet::TokenHolding)+Q_DECLARE_METATYPE(fincept::wallet::TokenPrice)+Q_DECLARE_METATYPE(fincept::wallet::TokenMetadata)+Q_DECLARE_METATYPE(fincept::wallet::ParsedActivity)+Q_DECLARE_METATYPE(QVector<fincept::wallet::ParsedActivity>)+Q_DECLARE_METATYPE(fincept::wallet::FncptDiscount)+// FncptPrice is `TokenPrice`; no separate metatype needed.diff --git a/fincept-qt/src/storage/secure/SecureStorage.cpp b/fincept-qt/src/storage/secure/SecureStorage.cppindex 5be87511b..83c785638 100644--- a/fincept-qt/src/storage/secure/SecureStorage.cpp+++ b/fincept-qt/src/storage/secure/SecureStorage.cpp@@ -2,19 +2,15 @@#include "core/logging/Logger.h"-#include <QCryptographicHash>-#include <QSettings>-#include <QSysInfo>-// ── Platform-specific credential storage ──────────────────────────────────────//// Windows : Windows Credential Manager (DPAPI-backed, encrypted at rest)-// macOS : Security.framework Keychain (encrypted, user-unlocked)-// Linux : XOR-obfuscated QSettings with machine-unique key derivation.-// NOTE: This is NOT cryptographically secure — it prevents casual-// inspection but not a determined attacker with filesystem access.-// For full security, use libsecret/Secret Service when available.-// A proper libsecret backend should be added in a future release.+// macOS : Security.framework SecItem API (SecItemAdd/Update/CopyMatching)+// Linux : libsecret / Secret Service when available (GNOME Keyring, KWallet+// via the Secret Service compatibility layer), falling back to+// XOR-obfuscated QSettings when libsecret is absent.+// The XOR fallback is NOT cryptographically secure — it only stops+// casual inspection. Build with libsecret-1-dev for production.#ifdef Q_OS_WIN# include <windows.h>@@ -24,9 +20,19 @@#endif#ifdef Q_OS_MAC+# include <CoreFoundation/CoreFoundation.h># include <Security/Security.h>#endif+#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)+# include <QCryptographicHash>+# include <QSettings>+# include <QSysInfo>+# ifdef FINCEPT_HAVE_LIBSECRET+# include <libsecret/secret.h>+# endif+#endif+static constexpr auto TAG = "SecureStorage";static constexpr const char* kService = "com.fincept.terminal";@@ -35,30 +41,51 @@ namespace fincept {SecureStorage& SecureStorage::instance() {static SecureStorage s;-#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)- // One-time honest warning on Linux: the backend here is XOR-obfuscated- // QSettings, not real encryption. Emit at first access so it always- // shows up in the startup log for operators, and only once per process.+#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC) && !defined(FINCEPT_HAVE_LIBSECRET)+ // Warn once at startup when running on Linux without libsecret. Operators+ // should install libsecret-1-dev and rebuild for production deployments.static bool warned_once = false;if (!warned_once) {warned_once = true;- LOG_WARN("SecureStorage",- "Linux backend is XOR-obfuscated QSettings — NOT cryptographically "- "secure. Anyone with read access to the user profile can recover "- "stored secrets. libsecret/KWallet backend is planned.");+ LOG_WARN(TAG,+ "Linux credential storage is using XOR-obfuscated QSettings — "+ "NOT cryptographically secure. Install libsecret-1-dev and rebuild "+ "to enable the Secret Service (GNOME Keyring / KWallet) backend.");}#endifreturn s;}-// ── Linux helpers ─────────────────────────────────────────────────────────────+// ─────────────────────────────────────────────────────────────────────────────+// Linux helpers+// ─────────────────────────────────────────────────────────────────────────────#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)+#ifdef FINCEPT_HAVE_LIBSECRET++// Schema describing the structure of secrets we store. The single attribute+// "fincept-key" holds the per-secret name (e.g. FRED_API_KEY) so we can look+// it up later without scanning the whole keyring.+static const SecretSchema* fincept_schema() {+ static const SecretSchema schema = {+ "com.fincept.terminal",+ SECRET_SCHEMA_NONE,+ {+ {"fincept-key", SECRET_SCHEMA_ATTRIBUTE_STRING},+ {nullptr, SecretSchemaAttributeType(0)},+ },+ };+ return &schema;+}++#else // XOR fallback helpers+// Derive a machine-unique obfuscation key from stable system identifiers.// Not a secret — just prevents the file being readable at a glance.static QByteArray machine_key() {- const QString seed = QSysInfo::machineUniqueId() + QSysInfo::productType() + QLatin1String(kService);+ const QString seed = QSysInfo::machineUniqueId() + QSysInfo::productType()+ + QLatin1String(kService);return QCryptographicHash::hash(seed.toUtf8(), QCryptographicHash::Sha256);}@@ -67,14 +94,18 @@ static QByteArray xor_obfuscate(const QByteArray& data) {QByteArray out;out.resize(data.size());for (int i = 0; i < data.size(); ++i)- out[i] =- static_cast<char>(static_cast<unsigned char>(data[i]) ^ static_cast<unsigned char>(key[i % key.size()]));+ out[i] = static_cast<char>(+ static_cast<unsigned char>(data[i]) ^+ static_cast<unsigned char>(key[i % key.size()]));return out;}+#endif // FINCEPT_HAVE_LIBSECRET#endif // Linux helpers-// ── store ─────────────────────────────────────────────────────────────────────+// ─────────────────────────────────────────────────────────────────────────────+// store+// ─────────────────────────────────────────────────────────────────────────────Result<void> SecureStorage::store(const QString& key, const QString& value) {#ifdef Q_OS_WIN@@ -96,50 +127,108 @@ Result<void> SecureStorage::store(const QString& key, const QString& value) {return Result<void>::ok();#elif defined(Q_OS_MAC)- // macOS Keychain — encrypted, user-unlocked.- // NOTE: Using legacy SecKeychain* API (deprecated in 10.10). The modern- // SecItem* API is a larger port; suppressing the warning locally keeps- // CI green. TODO: migrate to SecItemAdd / SecItemCopyMatching.- const QByteArray svc = QByteArray(kService);- const QByteArray acct = key.toUtf8();- const QByteArray data = value.toUtf8();-- OSStatus status;-# pragma clang diagnostic push-# pragma clang diagnostic ignored "-Wdeprecated-declarations"- // Delete any existing item first (SecItemUpdate is more complex)- SecKeychainItemRef existing = nullptr;- OSStatus del_status =- SecKeychainFindGenericPassword(nullptr, static_cast<UInt32>(svc.size()), svc.constData(),- static_cast<UInt32>(acct.size()), acct.constData(), nullptr, nullptr, &existing);- if (del_status == errSecSuccess && existing) {- SecKeychainItemDelete(existing);- CFRelease(existing);+ // macOS Keychain via modern SecItem API. Try SecItemUpdate first; if no+ // existing item, fall through to SecItemAdd. Any other status is logged+ // (it indicates a real Keychain problem we don't want to silently mask+ // by overwriting with Add).+ const QByteArray svc_bytes = QByteArray(kService);+ const QByteArray acct_bytes = key.toUtf8();+ const QByteArray data_bytes = value.toUtf8();++ CFStringRef service = CFStringCreateWithBytes(+ nullptr, reinterpret_cast<const UInt8*>(svc_bytes.constData()),+ svc_bytes.size(), kCFStringEncodingUTF8, false);+ CFStringRef account = CFStringCreateWithBytes(+ nullptr, reinterpret_cast<const UInt8*>(acct_bytes.constData()),+ acct_bytes.size(), kCFStringEncodingUTF8, false);+ CFDataRef secret_data = CFDataCreate(+ nullptr, reinterpret_cast<const UInt8*>(data_bytes.constData()),+ static_cast<CFIndex>(data_bytes.size()));++ const void* find_keys[] = {kSecClass, kSecAttrService, kSecAttrAccount};+ const void* find_vals[] = {kSecClassGenericPassword, service, account};+ CFDictionaryRef find_query = CFDictionaryCreate(+ nullptr, find_keys, find_vals, 3,+ &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);++ const void* upd_keys[] = {kSecValueData};+ const void* upd_vals[] = {secret_data};+ CFDictionaryRef upd_attrs = CFDictionaryCreate(+ nullptr, upd_keys, upd_vals, 1,+ &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);++ OSStatus status = SecItemUpdate(find_query, upd_attrs);+ CFRelease(upd_attrs);++ if (status == errSecItemNotFound) {+ // No existing item — add a new one.+ const void* add_keys[] = {kSecClass, kSecAttrService, kSecAttrAccount, kSecValueData};+ const void* add_vals[] = {kSecClassGenericPassword, service, account, secret_data};+ CFDictionaryRef add_attrs = CFDictionaryCreate(+ nullptr, add_keys, add_vals, 4,+ &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);+ status = SecItemAdd(add_attrs, nullptr);+ CFRelease(add_attrs);+ } else if (status != errSecSuccess) {+ // Update returned an unexpected status — log it. Do NOT fall through+ // to Add: if the item exists but Update is rejected (ACL, locked+ // keychain, etc.) the right answer is to surface the failure, not+ // create a duplicate item.+ LOG_WARN(TAG, QString("SecItemUpdate returned unexpected OSStatus %1 for key %2")+ .arg(status).arg(key));}- status = SecKeychainAddGenericPassword(nullptr, static_cast<UInt32>(svc.size()), svc.constData(),- static_cast<UInt32>(acct.size()), acct.constData(),- static_cast<UInt32>(data.size()), data.constData(), nullptr);-# pragma clang diagnostic pop+ CFRelease(find_query);+ CFRelease(secret_data);+ CFRelease(account);+ CFRelease(service);if (status != errSecSuccess) {- LOG_ERROR(TAG, QString("Keychain store failed (OSStatus %1) for key: %2").arg(status).arg(key));+ LOG_ERROR(TAG, QString("Keychain store failed (OSStatus %1) for key: %2")+ .arg(status).arg(key));return Result<void>::err("Failed to store in Keychain");}return Result<void>::ok();#else- // Linux — XOR-obfuscated QSettings.- // WARNING: Not cryptographically secure. Prevents casual inspection only.- // TODO: Add libsecret backend for proper encryption on Linux.+# ifdef FINCEPT_HAVE_LIBSECRET+ // Linux — Secret Service (GNOME Keyring / KWallet compatibility layer).+ GError* err = nullptr;+ const QByteArray key_bytes = key.toUtf8();+ const QByteArray val_bytes = value.toUtf8();+ const QByteArray label = ("Fincept Terminal: " + key).toUtf8();++ secret_password_store_sync(+ fincept_schema(),+ SECRET_COLLECTION_DEFAULT,+ label.constData(),+ val_bytes.constData(),+ nullptr,+ &err,+ "fincept-key", key_bytes.constData(),+ nullptr);++ if (err) {+ QString msg = QString::fromUtf8(err->message);+ g_error_free(err);+ LOG_ERROR(TAG, "libsecret store failed for key " + key + ": " + msg);+ return Result<void>::err("Failed to store in Secret Service: " + msg.toStdString());+ }+ return Result<void>::ok();++# else+ // XOR-obfuscated QSettings fallback — NOT cryptographically secure.QSettings s("Fincept", "FinceptTerminal-Secure");const QByteArray obfuscated = xor_obfuscate(value.toUtf8()).toBase64();s.setValue("secure/" + key, QString::fromLatin1(obfuscated));return Result<void>::ok();+# endif#endif}-// ── retrieve ──────────────────────────────────────────────────────────────────+// ─────────────────────────────────────────────────────────────────────────────+// retrieve+// ─────────────────────────────────────────────────────────────────────────────Result<QString> SecureStorage::retrieve(const QString& key) {#ifdef Q_OS_WIN@@ -156,45 +245,83 @@ Result<QString> SecureStorage::retrieve(const QString& key) {return Result<QString>::ok(value);#elif defined(Q_OS_MAC)- const QByteArray svc = QByteArray(kService);- const QByteArray acct = key.toUtf8();-- UInt32 data_len = 0;- void* data_ptr = nullptr;- OSStatus status;-# pragma clang diagnostic push-# pragma clang diagnostic ignored "-Wdeprecated-declarations"- status = SecKeychainFindGenericPassword(nullptr, static_cast<UInt32>(svc.size()), svc.constData(),- static_cast<UInt32>(acct.size()), acct.constData(), &data_len,- &data_ptr, nullptr);-# pragma clang diagnostic pop-- if (status != errSecSuccess) {+ const QByteArray svc_bytes = QByteArray(kService);+ const QByteArray acct_bytes = key.toUtf8();++ CFStringRef service = CFStringCreateWithBytes(+ nullptr, reinterpret_cast<const UInt8*>(svc_bytes.constData()),+ svc_bytes.size(), kCFStringEncodingUTF8, false);+ CFStringRef account = CFStringCreateWithBytes(+ nullptr, reinterpret_cast<const UInt8*>(acct_bytes.constData()),+ acct_bytes.size(), kCFStringEncodingUTF8, false);++ const void* keys[] = {kSecClass, kSecAttrService, kSecAttrAccount,+ kSecReturnData, kSecMatchLimit};+ const void* vals[] = {kSecClassGenericPassword, service, account,+ kCFBooleanTrue, kSecMatchLimitOne};+ CFDictionaryRef query = CFDictionaryCreate(+ nullptr, keys, vals, 5,+ &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);++ CFTypeRef result_ref = nullptr;+ OSStatus status = SecItemCopyMatching(query, &result_ref);+ CFRelease(query);+ CFRelease(account);+ CFRelease(service);++ if (status != errSecSuccess || !result_ref) {return Result<QString>::err("Credential not found in Keychain");}- QString value = QString::fromUtf8(static_cast<const char*>(data_ptr), static_cast<int>(data_len));-# pragma clang diagnostic push-# pragma clang diagnostic ignored "-Wdeprecated-declarations"- SecKeychainItemFreeContent(nullptr, data_ptr);-# pragma clang diagnostic pop+ CFDataRef data = static_cast<CFDataRef>(result_ref);+ QString value = QString::fromUtf8(+ reinterpret_cast<const char*>(CFDataGetBytePtr(data)),+ static_cast<int>(CFDataGetLength(data)));+ CFRelease(result_ref);return Result<QString>::ok(value);#else+# ifdef FINCEPT_HAVE_LIBSECRET+ GError* err = nullptr;+ const QByteArray key_bytes = key.toUtf8();++ gchar* password = secret_password_lookup_sync(+ fincept_schema(),+ nullptr,+ &err,+ "fincept-key", key_bytes.constData(),+ nullptr);++ if (err) {+ QString msg = QString::fromUtf8(err->message);+ g_error_free(err);+ return Result<QString>::err("libsecret lookup failed: " + msg.toStdString());+ }+ if (!password) {+ return Result<QString>::err("Not found");+ }++ QString value = QString::fromUtf8(password);+ secret_password_free(password);+ return Result<QString>::ok(value);++# elseQSettings s("Fincept", "FinceptTerminal-Secure");QVariant v = s.value("secure/" + key);if (!v.isValid())return Result<QString>::err("Not found");- // Deobfuscate: base64-decode then XORconst QByteArray raw = QByteArray::fromBase64(v.toString().toLatin1());if (raw.isEmpty())return Result<QString>::err("Not found");return Result<QString>::ok(QString::fromUtf8(xor_obfuscate(raw)));+# endif#endif}-// ── remove ────────────────────────────────────────────────────────────────────+// ─────────────────────────────────────────────────────────────────────────────+// remove+// ─────────────────────────────────────────────────────────────────────────────Result<void> SecureStorage::remove(const QString& key) {#ifdef Q_OS_WIN@@ -205,27 +332,49 @@ Result<void> SecureStorage::remove(const QString& key) {return Result<void>::ok();#elif defined(Q_OS_MAC)- const QByteArray svc = QByteArray(kService);- const QByteArray acct = key.toUtf8();--# pragma clang diagnostic push-# pragma clang diagnostic ignored "-Wdeprecated-declarations"- SecKeychainItemRef item = nullptr;- OSStatus status =- SecKeychainFindGenericPassword(nullptr, static_cast<UInt32>(svc.size()), svc.constData(),- static_cast<UInt32>(acct.size()), acct.constData(), nullptr, nullptr, &item);-- if (status == errSecSuccess && item) {- SecKeychainItemDelete(item);- CFRelease(item);- }-# pragma clang diagnostic pop+ const QByteArray svc_bytes = QByteArray(kService);+ const QByteArray acct_bytes = key.toUtf8();++ CFStringRef service = CFStringCreateWithBytes(+ nullptr, reinterpret_cast<const UInt8*>(svc_bytes.constData()),+ svc_bytes.size(), kCFStringEncodingUTF8, false);+ CFStringRef account = CFStringCreateWithBytes(+ nullptr, reinterpret_cast<const UInt8*>(acct_bytes.constData()),+ acct_bytes.size(), kCFStringEncodingUTF8, false);++ const void* keys[] = {kSecClass, kSecAttrService, kSecAttrAccount};+ const void* vals[] = {kSecClassGenericPassword, service, account};+ CFDictionaryRef query = CFDictionaryCreate(+ nullptr, keys, vals, 3,+ &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);++ SecItemDelete(query);+ CFRelease(query);+ CFRelease(account);+ CFRelease(service);return Result<void>::ok();#else+# ifdef FINCEPT_HAVE_LIBSECRET+ GError* err = nullptr;+ const QByteArray key_bytes = key.toUtf8();++ secret_password_clear_sync(+ fincept_schema(),+ nullptr,+ &err,+ "fincept-key", key_bytes.constData(),+ nullptr);++ if (err)+ g_error_free(err); // not fatal — item may simply not have existed+ return Result<void>::ok();++# elseQSettings s("Fincept", "FinceptTerminal-Secure");s.remove("secure/" + key);return Result<void>::ok();+# endif#endif}diff --git a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.hindex 1a152a0be..06397b96c 100644--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h@@ -67,5 +67,6 @@ void register_migration_v017();void register_migration_v018();void register_migration_v019();void register_migration_v020();+void register_migration_v021();} // namespace finceptdiff --git a/fincept-qt/src/storage/sqlite/migrations/v021_max_tokens_default.cpp b/fincept-qt/src/storage/sqlite/migrations/v021_max_tokens_default.cppnew file mode 100644index 000000000..79cea6dd6--- /dev/null+++ b/fincept-qt/src/storage/sqlite/migrations/v021_max_tokens_default.cpp@@ -0,0 +1,63 @@+// v021_max_tokens_default — Reset legacy 2000-token defaults so they fall+// back to ModelCatalog::output_cap(provider, model) at runtime.+//+// Background: v002 created llm_global_settings with `max_tokens INTEGER+// DEFAULT 2000` and v010 carried that value into per-profile rows. The+// 2000 figure was a debug holdover that throttled every LLM reply to+// 2000 tokens regardless of model. Modern models support far more+// (Kimi K2.6 → 256k context / 65k+ output, Sonnet 4.6 → 64k, gpt-5 →+// 128k, etc.). LlmService now resolves max_tokens dynamically via+// ModelCatalog when the stored value is 0/NULL.+//+// This migration:+// 1. Sets the global default row's max_tokens from 2000 → 0.+// 2. Sets every llm_profiles row that still has the seeded 2000 to 0.+//+// Users who deliberately configured 2000 are indistinguishable from+// users who never touched the setting — that's fine. 2000 was never a+// reasonable user choice, so resetting them all to "use model default"+// is the right call.++#include "storage/sqlite/migrations/MigrationRunner.h"++#include <QSqlError>+#include <QSqlQuery>++namespace fincept {+namespace {++static Result<void> sql(QSqlDatabase& db, const char* stmt) {+ QSqlQuery q(db);+ if (!q.exec(stmt))+ return Result<void>::err(q.lastError().text().toStdString());+ return Result<void>::ok();+}++static Result<void> apply_v021(QSqlDatabase& db) {+ // Reset legacy 2000 in global settings. Use 0 as the "no override —+ // resolve from ModelCatalog" sentinel.+ if (auto r = sql(db, "UPDATE llm_global_settings SET max_tokens = 0 WHERE max_tokens = 2000");+ r.is_err())+ return r;++ // Same for per-profile rows. The table only exists from v010 onward;+ // a fresh DB will pass through v010 before reaching v021, so this+ // statement is always safe.+ if (auto r = sql(db, "UPDATE llm_profiles SET max_tokens = 0 WHERE max_tokens = 2000");+ r.is_err())+ return r;++ return Result<void>::ok();+}++} // anonymous namespace++void register_migration_v021() {+ static bool done = false;+ if (done)+ return;+ done = true;+ MigrationRunner::register_migration({21, "max_tokens_default", apply_v021});+}++} // namespace finceptdiff --git a/fincept-qt/src/ui/navigation/ToolBar.cpp b/fincept-qt/src/ui/navigation/ToolBar.cppindex 6c573a57c..66dda02cf 100644--- a/fincept-qt/src/ui/navigation/ToolBar.cpp+++ b/fincept-qt/src/ui/navigation/ToolBar.cpp@@ -351,6 +351,10 @@ QMenu* ToolBar::build_navigate_menu() {nav(trd, "Derivatives", "derivatives");nav(trd, "Watchlist", "watchlist");+ // Crypto / on-chain identity+ auto* crypto = add_sub("Crypto");+ nav(crypto, "Crypto Center", "crypto_center");+// Research & Intelligenceauto* res = add_sub("Research & Intelligence");nav(res, "Equity Research", "equity_research");diff --git a/fincept-qt/src/ui/pushpins/SymbolChip.cpp b/fincept-qt/src/ui/pushpins/SymbolChip.cppindex 7baca7e52..ca4df2f1b 100644--- a/fincept-qt/src/ui/pushpins/SymbolChip.cpp+++ b/fincept-qt/src/ui/pushpins/SymbolChip.cpp@@ -2,6 +2,7 @@#include "core/symbol/SymbolContext.h"#include "core/symbol/SymbolDragSource.h"+#include "core/symbol/SymbolGroupRegistry.h"#include "services/pushpins/PushpinService.h"#include <QAction>@@ -70,8 +71,11 @@ void SymbolChip::contextMenuEvent(QContextMenuEvent* e) {});menu.addSeparator();- for (SymbolGroup g : all_symbol_groups()) {- auto* act = menu.addAction(QString("Broadcast to Group %1").arg(symbol_group_letter(g)));+ auto& registry = SymbolGroupRegistry::instance();+ for (SymbolGroup g : registry.enabled_groups()) {+ auto* act = menu.addAction(QStringLiteral("Broadcast to %1 (%2)")+ .arg(registry.name(g))+ .arg(symbol_group_letter(g)));connect(act, &QAction::triggered, this, [this, g]() { broadcast_to_group(g); });}menu.exec(e->globalPos());diff --git a/fincept-qt/src/ui/theme/StyleSheets.cpp b/fincept-qt/src/ui/theme/StyleSheets.cppindex 1dcd5385d..ed98ebfd9 100644--- a/fincept-qt/src/ui/theme/StyleSheets.cpp+++ b/fincept-qt/src/ui/theme/StyleSheets.cpp@@ -209,7 +209,13 @@ QString news_screen_styles() {"#newsTickerStrip { background: %1; border-top: 1px solid %3; }"/* ── Skeleton ── */- "#newsSkeletonOverlay { background: %1; }")+ "#newsSkeletonOverlay { background: %1; }"++ /* ── Empty state ── */+ "#newsEmptyState { background: %1; }"+ "#newsEmptyStateTitle { color: %12; font-size: 13px; font-weight: 700; "+ " letter-spacing: 0.5px; background: transparent; }"+ "#newsEmptyStateHint { color: %6; font-size: 11px; background: transparent; }").arg(colors::BG_BASE()) // %1.arg(colors::BG_SURFACE()) // %2.arg(colors::BORDER_DIM()) // %3diff --git a/fincept-qt/src/ui/widgets/GroupBadge.cpp b/fincept-qt/src/ui/widgets/GroupBadge.cppindex df7776795..278739cc7 100644--- a/fincept-qt/src/ui/widgets/GroupBadge.cpp+++ b/fincept-qt/src/ui/widgets/GroupBadge.cpp@@ -1,45 +1,51 @@#include "ui/widgets/GroupBadge.h"+#include "core/symbol/SymbolGroupRegistry.h"+#include <QAction>+#include <QColorDialog>#include <QContextMenuEvent>+#include <QInputDialog>+#include <QLineEdit>#include <QMenu>#include <QMouseEvent>#include <QPainter>#include <QPainterPath>+#include <QPointer>namespace fincept::ui {GroupBadge::GroupBadge(QWidget* parent) : QWidget(parent) {setCursor(Qt::PointingHandCursor);- setToolTip("Symbol link group — click to cycle, right-click for menu");setAttribute(Qt::WA_Hover);++ // Repaint + refresh tooltip when any registry mutation lands. Cheap —+ // the slot count is at most 10 and we only repaint our own widget.+ connect(&SymbolGroupRegistry::instance(),+ &SymbolGroupRegistry::group_metadata_changed, this,+ [this](SymbolGroup) { set_group_silent(group_); });++ set_group_silent(SymbolGroup::None); // seeds the tooltip}QColor GroupBadge::color_for_group(SymbolGroup g) {- // Bloomberg-ish six-colour palette, tuned to remain readable on both- // dark and light themes.- switch (g) {- case SymbolGroup::A: return QColor("#d97706"); // amber- case SymbolGroup::B: return QColor("#0891b2"); // cyan- case SymbolGroup::C: return QColor("#c026d3"); // magenta- case SymbolGroup::D: return QColor("#16a34a"); // green- case SymbolGroup::E: return QColor("#7c3aed"); // purple- case SymbolGroup::F: return QColor("#dc2626"); // red- case SymbolGroup::None: return QColor("#4b5563"); // slate (unlinked)- }- return QColor("#4b5563");+ if (g == SymbolGroup::None)+ return QColor("#4b5563");+ return SymbolGroupRegistry::instance().color(g);}void GroupBadge::set_group_silent(SymbolGroup g) {- if (group_ == g)- return;group_ = g;+ const QString state = (g == SymbolGroup::None)+ ? QStringLiteral("Unlinked")+ : SymbolGroupRegistry::instance().name(g);+ setToolTip(QStringLiteral("Symbol link group: %1\nClick to cycle • Right-click for menu").arg(state));update();}void GroupBadge::mousePressEvent(QMouseEvent* e) {if (e->button() == Qt::LeftButton) {- emit group_change_requested(next_symbol_group(group_));+ emit group_change_requested(SymbolGroupRegistry::instance().next_enabled(group_));e->accept();return;}@@ -47,18 +53,74 @@ void GroupBadge::mousePressEvent(QMouseEvent* e) {}void GroupBadge::contextMenuEvent(QContextMenuEvent* e) {+ auto& registry = SymbolGroupRegistry::instance();QMenu menu(this);+auto* unlink = menu.addAction("Unlink");unlink->setEnabled(group_ != SymbolGroup::None);connect(unlink, &QAction::triggered, this,[this]() { emit group_change_requested(SymbolGroup::None); });+menu.addSeparator();++ // Link-to-<group> entries. All ten slots are listed; disabled slots are+ // shown greyed out so users can see the full inventory but can't cycle+ // into them. Names come from the registry so renames show up immediately.for (SymbolGroup g : all_symbol_groups()) {- auto* act = menu.addAction(QString("Link to Group %1").arg(symbol_group_letter(g)));+ const bool en = registry.enabled(g);+ QString label = QStringLiteral("%1 (%2)").arg(registry.name(g)).arg(symbol_group_letter(g));+ if (!en)+ label += QStringLiteral(" — disabled");+ auto* act = menu.addAction(label);act->setCheckable(true);act->setChecked(g == group_);+ act->setEnabled(en);connect(act, &QAction::triggered, this, [this, g]() { emit group_change_requested(g); });}++ menu.addSeparator();++ // Customisation actions — only meaningful for a concrete slot.+ const SymbolGroup target = group_ == SymbolGroup::None ? SymbolGroup::A : group_;++ auto* rename = menu.addAction(QStringLiteral("Rename %1…").arg(registry.name(target)));+ QPointer<GroupBadge> self = this;+ connect(rename, &QAction::triggered, this, [self, target]() {+ if (!self) return;+ bool ok = false;+ const QString current = SymbolGroupRegistry::instance().name(target);+ const QString name = QInputDialog::getText(self, QStringLiteral("Rename Group"),+ QStringLiteral("New name for %1:")+ .arg(symbol_group_letter(target)),+ QLineEdit::Normal, current, &ok);+ if (ok)+ SymbolGroupRegistry::instance().set_name(target, name);+ });++ auto* recolor = menu.addAction(QStringLiteral("Change Colour for %1…").arg(registry.name(target)));+ connect(recolor, &QAction::triggered, this, [self, target]() {+ if (!self) return;+ const QColor current = SymbolGroupRegistry::instance().color(target);+ const QColor picked = QColorDialog::getColor(current, self,+ QStringLiteral("Group %1 Colour")+ .arg(symbol_group_letter(target)));+ if (picked.isValid())+ SymbolGroupRegistry::instance().set_color(target, picked);+ });++ auto* toggle = menu.addAction(registry.enabled(target) ? QStringLiteral("Disable Slot %1")+ .arg(symbol_group_letter(target))+ : QStringLiteral("Enable Slot %1")+ .arg(symbol_group_letter(target)));+ connect(toggle, &QAction::triggered, this, [target]() {+ auto& r = SymbolGroupRegistry::instance();+ r.set_enabled(target, !r.enabled(target));+ });++ auto* reset = menu.addAction(QStringLiteral("Reset %1 to Defaults").arg(symbol_group_letter(target)));+ connect(reset, &QAction::triggered, this,+ [target]() { SymbolGroupRegistry::instance().reset_to_default(target); });+menu.exec(e->globalPos());}diff --git a/setup.sh b/setup.shindex bb016c454..9fb9b882c 100755--- a/setup.sh+++ b/setup.sh@@ -61,6 +61,9 @@ if [ "$PLATFORM" = "linux" ]; thenlibgl1-mesa-dev libglu1-mesa-dev \libxkbcommon-dev libxkbcommon-x11-dev \libfontconfig1 libdbus-1-3 \+ libssl-dev \+ libxcb-cursor0 \+ libsecret-1-dev \pkg-config curlelif command -v pacman &>/dev/null; thensudo pacman -Sy --noconfirm --needed \@@ -68,6 +71,7 @@ if [ "$PLATFORM" = "linux" ]; thenpython python-pip \mesa glu libxkbcommon \fontconfig dbus \+ libsecret \pkgconf curlelif command -v dnf &>/dev/null; thensudo dnf install -y \@@ -76,6 +80,7 @@ if [ "$PLATFORM" = "linux" ]; thenmesa-libGL-devel mesa-libGLU-devel \libxkbcommon-devel \fontconfig dbus-libs \+ libsecret-devel \pkgconfig curlelseinfo "No recognised package manager found. Ensure cmake, ninja, g++, python3, and Qt build dependencies are installed manually."@@ -145,12 +150,15 @@ elseAQT="$AQT_VENV/bin/aqt"[ -x "$AQT" ] || fail "aqtinstall did not install correctly."# Qt host/target/arch- # AQT_ARCH is the argument passed to aqt (aqtinstall 3.x uses linux_gcc_64 on Linux).- # QT_KIT is the subdirectory aqtinstall actually creates on disk (always gcc_64).+ # AQT_ARCH is the argument passed to aqt; QT_KIT is the subdirectory aqtinstall+ # actually creates on disk. They differ on every platform — aqtinstall maps the+ # arch argument to the on-disk dir internally:+ # Linux : aqt arg "linux_gcc_64" → on-disk "gcc_64"+ # macOS : aqt arg "clang_64" → on-disk "macos" (Qt >= 6.1.2 only)if [ "$PLATFORM" = "linux" ]; thenAQT_HOST="linux" ; AQT_TARGET="desktop" ; AQT_ARCH="linux_gcc_64"else- AQT_HOST="mac" ; AQT_TARGET="desktop" ; AQT_ARCH="macos"+ AQT_HOST="mac" ; AQT_TARGET="desktop" ; AQT_ARCH="clang_64"fi# Modules required to compile Fincept (match find_package COMPONENTS)AQT_MODULES="qtcharts qtwebsockets qtmultimedia qtspeech"