Skip to content

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.

crypto, internal mcp, ai quant tabs update

tilakpatel22a68013110832
diff --git a/.gitignore b/.gitignore
index 68fa45be7..73e50489c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -152,3 +152,11 @@ fincept-qt/scripts/exchange/.cache/
# ── Internal planning docs ────────────────────────────────────
fincept-qt/docs/superpowers/
docs/superpowers/
+
+# ── Grill-me session notes ────────────────────────────────────
+.grill-me/
+**/.grill-me/
+
+# ── Local planning docs ───────────────────────────────────────
+plans/
+**/plans/
diff --git a/fincept-qt/.claude/scheduled_tasks.lock b/fincept-qt/.claude/scheduled_tasks.lock
new file mode 100644
index 000000000..ac38e462e
--- /dev/null
+++ b/fincept-qt/.claude/scheduled_tasks.lock
@@ -0,0 +1 @@
+{"sessionId":"f403b37e-7a81-40d6-90d2-7f3206598e30","pid":14420,"acquiredAt":1777643146220}
\ No newline at end of file
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 6ef425886..351ce9e34 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -2269,15 +2269,16 @@ if(WIN32)
"C:/Qt/6.8.2/msvc2022_64/bin"
)
if(WINDEPLOYQT_EXE)
- # Only deploy Qt DLLs when explicitly requested via -DDEPLOY_QT=ON
- # Avoids 10-30s overhead on every incremental build
- if(DEPLOY_QT)
- add_custom_command(TARGET FinceptTerminal POST_BUILD
- COMMAND "${WINDEPLOYQT_EXE}"
- ARGS "--no-translations" "$<TARGET_FILE:FinceptTerminal>"
- COMMENT "Running windeployqt..."
- )
- endif()
+ # Always deploy Qt DLLs/plugins next to the exe. windeployqt is
+ # idempotent and copy_if_different — incremental cost is ~1-2 s
+ # when nothing changed. The previous DEPLOY_QT=ON gate caused the
+ # exe to run against a stale plugin set after a clean rebuild,
+ # producing 0xc0000005 crashes on startup.
+ add_custom_command(TARGET FinceptTerminal POST_BUILD
+ COMMAND "${WINDEPLOYQT_EXE}"
+ ARGS "--no-translations" "--no-compiler-runtime" "$<TARGET_FILE:FinceptTerminal>"
+ COMMENT "Running windeployqt..."
+ )
endif()
# ── Fix: Qt Maintenance Tool partial-update leaves plugins mismatched ──────
diff --git a/fincept-qt/build-msvc-ci.pid b/fincept-qt/build-msvc-ci.pid
deleted file mode 100644
index 371ad1dae..000000000
--- a/fincept-qt/build-msvc-ci.pid
+++ /dev/null
@@ -1 +0,0 @@
-23880
diff --git a/fincept-qt/docs/CRYPTO_CENTER_PHASE_2.md b/fincept-qt/docs/CRYPTO_CENTER_PHASE_2.md
new file mode 100644
index 000000000..021f29d2a
--- /dev/null
+++ b/fincept-qt/docs/CRYPTO_CENTER_PHASE_2.md
@@ -0,0 +1,152 @@
+# Crypto Center — Phase 2 user guide
+
+Phase 2 turns the Crypto Center from a read-only identity surface into a transactional one. You can now:
+
+- See **every token** your wallet holds (SOL + every SPL token), with USD prices and portfolio total.
+- **Buy or sell $FNCPT** for SOL through PumpPortal directly inside the terminal.
+- Browse **the last 50 on-chain operations** for your wallet, parsed into human-readable events.
+- Earn a **30% fee discount** on premium features when you hold ≥ 1,000 $FNCPT.
+
+The terminal never holds your private keys. Every transaction is signed in your wallet (Phantom, Solflare, etc.) — the terminal only forwards the unsigned bytes and waits for the signed result. See `CRYPTO_WALLET_CONNECT.md` for the connection flow.
+
+---
+
+## The screen at a glance
+
+```
+┌─ FINCEPT / CRYPTO CENTER ──────────── ● CONNECTED · 7eV4z…aoowY ────┐
+│ HOLDINGS BAR │
+│ SOL 9.74 · $FNCPT 0 · TOTAL $1,247.82 · ● LIVE · HELIUS │
+├──────┬───────┬─────────┬────────┬───────┬────────┬─────────────────┤
+│ HOME │ TRADE │ ACTIVITY│ SETTINGS│ STAKE│ MARKETS│ ROADMAP │
+└──────┴───────┴─────────┴────────┴───────┴────────┴─────────────────┘
+```
+
+The HOLDINGS BAR sits above every tab — your portfolio total never disappears even when you switch tabs. Stake / Markets / Roadmap are placeholders for Phases 3 / 4 / 5 respectively.
+
+---
+
+## HOME tab
+
+The HOME tab now shows a **holdings table** instead of three stat boxes. One row per asset:
+
+| 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 | 12,304 | $0.0000185 | $0.23 | 0.0% |
+
+Click a row → you're dropped into the **TRADE** tab with that token pre-filled as the FROM side of a swap.
+
+**Verified vs unverified.** By default only Jupiter-verified tokens show — pump.fun wallets accumulate junk airdrops, and showing them all would be noisy. The footer reads `7 verified · 12 unverified hidden` with a **Show all** link. The persistent toggle lives in **Settings**.
+
+**Refresh.** The holdings refresh themselves on a 30-second cadence (or via WebSocket if you're on Helius streaming). Click **REFRESH** to force an immediate re-fetch.
+
+---
+
+## TRADE tab — Swap
+
+```
+┌─ SWAP ──────────────────── via PumpPortal · pool=auto ──┐
+│ YOU PAY [ 0.50 ] SOL ▾ Balance: 1.20 SOL │
+│ [MAX] │
+│ │
+│ YOU RECEIVE (EST.) ≈ 12,304 $FNCPT (~$0.23) │
+│ [$FNCPT ▾] │
+│ ────────────────────────────────────────────────── │
+│ ROUTE PumpSwap (auto) │
+│ PRICE IMPACT set by PumpSwap; capped by slippage │
+│ MAX SLIPPAGE 1.00% │
+│ [SWAP] │
+└─────────────────────────────────────────────────────────┘
+```
+
+**Direction.** The FROM and TO combos are populated from your real holdings (FROM) and from the Jupiter verified list + your holdings (TO). For Phase 2, **PumpPortal only routes SOL ↔ $FNCPT** — selecting any other pair shows a "Phase 3 supports arbitrary pairs" message and disables the SWAP button. The combo plumbing is already there for Phase 3.
+
+**Estimate.** PumpPortal has no quote endpoint, so the "YOU RECEIVE" estimate is computed locally from live spot prices (`market:price:token:<mint>`) times the slippage budget. The actual fill is set by PumpSwap at execution; the wallet shows you the decoded transaction independently.
+
+**Slippage.** Default 1%, adjustable up to 5% in Settings. PumpPortal expects an integer percent.
+
+**The SWAP click flow:**
+
+1. **Build** — terminal asks PumpPortal for an unsigned versioned tx (~1 KB).
+2. **MITM gate** — terminal simulates the tx against your RPC. If the simulation reports a revert, the flow aborts before the wallet ever pops. This catches a malicious PumpPortal response that would drain or otherwise misbehave.
+3. **Confirm dialog** — you see a decoded summary: route, amount paid, estimated received, slippage, priority fee, and the simulation result ("OK · N CU"). The SWAP button has a **1.5-second anti-muscle-memory delay** before it arms.
+4. **Freshness gate** — right after you click SWAP in the dialog, the terminal re-simulates with the tx's own blockhash (no replacement). If the blockhash has expired during the time you were reading the dialog, the flow aborts and asks you to retry.
+5. **Wallet signature** — the terminal forwards the unsigned bytes to your wallet over the local bridge. You sign in the wallet UI.
+6. **Submit + poll** — the terminal sends the signed tx to the network and polls `getSignatureStatuses` every 1.5 seconds. After `confirmed`, your balance refreshes automatically (within ~5 seconds).
+
+If anything goes wrong at any step, you see a red error strip with the specific failure. Funds never leave your wallet without your signature.
+
+---
+
+## ACTIVITY tab
+
+The last 50 on-chain operations involving your wallet, refreshed every 30 seconds:
+
+```
+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
+2026-04-26 11:44:30 SEND USDC 50.00 confirmed
+```
+
+**Filter chips** above the table: ALL · SWAP · SEND · RECEIVE · OTHER.
+
+**Click a row** → opens Solscan in your default browser at the transaction signature.
+
+**Helius parsing.** SWAP / SEND / RECEIVE come from the Helius parsed-tx endpoint (`api.helius.xyz/v0/addresses/<pk>/transactions`). Without a Helius key, the tab falls back to raw signatures only — every event shows as OTHER, but the Solscan link still works. Add a Helius key in **Settings** for real parsing.
+
+---
+
+## Fee discount
+
+Every paid feature in Fincept Terminal — AI reports, deep backtests, premium screens — accepts $FNCPT at a **30% discount** when you hold **≥ 1,000 $FNCPT**.
+
+The eligibility chip lights up on the HOLDINGS BAR (`30% OFF`) and the TRADE tab shows projected savings against your current balance. If your balance drops below the threshold, the chip extinguishes within one publish cycle (~30 seconds).
+
+The threshold and applied SKUs are read from `services/billing/FeeDiscountConfig.h` — header-only constants that get easier to swap as Phase 3's tier system lands.
+
+---
+
+## Settings tab
+
+- **Default slippage** — 1% (default) up to 5%. Stored in SecureStorage as `wallet.default_slippage_bps`.
+- **Solana RPC** — paste a custom RPC URL in `solana.rpc_url`, or a Helius API key in `solana.helius_api_key`. The HOLDINGS BAR shows `PUBLIC` / `HELIUS` / `CUSTOM` so you always know which RPC you're hitting. Helius is recommended — the public mainnet RPC is rate-limited and disables WebSocket streaming.
+- **Show unverified tokens** — toggle for the holdings table and SWAP combos.
+
+Stake / Markets / Roadmap settings ship with their respective phases.
+
+---
+
+## What's not in Phase 2
+
+These ship in later phases:
+
+- **Burn $FNCPT** — deferred to Phase 5 where the buyback worker burns from a treasury account.
+- **Arbitrary pair swaps** — Phase 3 lifts the SOL↔$FNCPT constraint via a generalized router.
+- **Stake / lock** — Phase 3, veFNCPT-style lock with USDC yield.
+- **Prediction markets** — Phase 4, internal venue settling in $FNCPT.
+- **Buyback dashboard** — Phase 5, replaces the static ROADMAP placeholder.
+
+See `plans/crypto-center-future-phases.md` for the full roadmap.
+
+---
+
+## Where to find this in code
+
+- `src/screens/crypto_center/` — screen + tabs + panels
+- `src/services/wallet/PumpFunSwapService.{h,cpp}` — PumpPortal client
+- `src/services/wallet/SolanaRpcClient.{h,cpp}` — RPC wrapper, simulation, status polling
+- `src/services/wallet/WalletActivityProducer.{h,cpp}` — Helius parsed-tx
+- `src/services/wallet/TokenPriceProducer.{h,cpp}` — Jupiter Lite Price API, batched per-mint
+- `src/services/wallet/TokenMetadataService.{h,cpp}` — Jupiter verified token list, daily refresh
+- `src/services/billing/FeeDiscountService.{h,cpp}` — eligibility derived from balance
+- `resources/wallet/swap.html` — wallet-side signing bridge
+- `docs/DATAHUB_TOPICS.md` — every hub topic the screen subscribes to
+- `plans/crypto-center-phase-2.md` — implementation plan
+- `plans/crypto-center-trade-security.md` — security walkthrough
+
+---
+
+**Last updated:** 2026-05-01
diff --git a/fincept-qt/docs/CRYPTO_CENTER_PHASE_3.md b/fincept-qt/docs/CRYPTO_CENTER_PHASE_3.md
new file mode 100644
index 000000000..25eba910c
--- /dev/null
+++ b/fincept-qt/docs/CRYPTO_CENTER_PHASE_3.md
@@ -0,0 +1,90 @@
+# Crypto Center — Phase 3 user guide (STAKE)
+
+The **STAKE** tab lets you lock $FNCPT for 3 months to 4 years in exchange for **veFNCPT weight** — a non-transferable token-account that grants two things:
+
+1. A pro-rata share of **terminal revenue paid in USDC** (real yield), settled per epoch by the buyback worker.
+2. A **billing tier** (Bronze / Silver / Gold) that unlocks paid screens elsewhere in the terminal — AI Quant Lab, Alpha Arena, premium agents.
+
+---
+
+## What you see
+
+```
+┌─ STAKE / LOCK ──────────────────────────────────── DEMO ────────────┐
+│ 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) │
+│ TIER Silver → Gold (after lock) │
+│ [PREVIEW LOCK] [LOCK] │
+└──────────────────────────────────────────────────────────────────────┘
+
+┌─ ACTIVE LOCKS · 3 positions · Σ 4,500 veFNCPT ── DEMO ──────────────┐
+│ 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 │
+└──────────────────────────────────────────────────────────────────────┘
+
+┌─ TIER ────────────────────────────────── current GOLD ──────────────┐
+│ BRONZE 100+ veFNCPT basic API quota │
+│ SILVER 1k+ veFNCPT premium screens │
+│ GOLD 10k+ veFNCPT all agents + arena │
+└──────────────────────────────────────────────────────────────────────┘
+```
+
+---
+
+## Demo mode
+
+Phase 3 ships in **demo mode** today. The on-chain `fincept_lock` Anchor program (the contract that actually escrows your $FNCPT and mints the veFNCPT position NFT) is not yet deployed. While in demo mode:
+
+- Every payload carries `is_mock=true`; the head pill on each panel reads **DEMO**.
+- The **PREVIEW LOCK** button shows the math you'd get from the multiplier table.
+- The **LOCK** button is disabled with a "fincept_lock not deployed" tooltip.
+- `ActiveLocks` shows three illustrative positions so you can see the table layout. These are not your positions; they are the same demo numbers shown to every user.
+
+When the program ships:
+
+1. We'll publish the program ID.
+2. You set `fincept.lock_program_id` in `SecureStorage` (Settings → Crypto → Advanced).
+3. The next refresh moves you off mock data: `wallet:locks:<pubkey>` will query `getProgramAccounts` and render your real positions; the **LOCK** button enables and routes through `WalletService::sign_and_send`.
+
+No code changes on your side — the seam is wired.
+
+---
+
+## How the multiplier works
+
+veFNCPT weight is computed at lock time and **decays linearly to zero** as you approach the unlock date. The duration multipliers (vs. a 4-yr max-weight lock):
+
+| Duration | Multiplier |
+|---|---|
+| 3 months | 0.0625 |
+| 6 months | 0.125 |
+| 1 year | 0.25 |
+| 2 years | 0.5 |
+| 4 years | 1.0 |
+
+Example: locking 1,000 $FNCPT for 1 year = 250 veFNCPT. Locking 1,000 $FNCPT for 4 years = 1,000 veFNCPT.
+
+The expected weekly USDC yield is `your_weight / total_weight × 25 % × terminal_revenue`. 25 % is the staker share of revenue per the Phase 5 buyback split (50 / 25 / 25 across buyback / staker yield / treasury top-up).
+
+---
+
+## Tier-driven gating
+
+Once `billing:tier:<your_pubkey>` lands at Silver+, paid screens that were hidden in the nav appear. Specifically (plan §3.6):
+
+- **Silver** (1k+ veFNCPT) reveals premium screens (AI Quant Lab access).
+- **Gold** (10k+ veFNCPT) reveals Alpha Arena + every agent.
+
+The `TierService` emits `tier_changed(pubkey, tier)` and the gated screens listen for it — so the moment your tier increases, the nav updates without a restart. If you can't see a screen you expect, check the TIER panel on the STAKE tab; the `next_threshold_raw` field tells you exactly how much more veFNCPT you need.
+
+---
+
+## What's not here yet
+
+- **Governance voting.** Phase 3 ships the lock surface only; voting on `fincept_market` listings (Phase 4) and on protocol parameters (Phase 5) lands in a follow-up.
+- **Lock extension UI.** You can only create new locks today. Extending an existing lock will land alongside the program deployment — the helper exists in `StakingService::build_extend_tx` but the UI button is hidden in mock mode.
+- **Withdraw on expiry.** Same as above — the auto-prompt fires when `unlock_ts <= now`, but only against real on-chain positions.
diff --git a/fincept-qt/docs/CRYPTO_CENTER_PHASE_4.md b/fincept-qt/docs/CRYPTO_CENTER_PHASE_4.md
new file mode 100644
index 000000000..3449f740e
--- /dev/null
+++ b/fincept-qt/docs/CRYPTO_CENTER_PHASE_4.md
@@ -0,0 +1,78 @@
+# Crypto Center — Phase 4 user guide (MARKETS)
+
+The **MARKETS** tab is Fincept's **internal prediction market** entry point. Markets are denominated and settled in **$FNCPT only** — no USDC, no off-chain ledger. Examples (curated demo dataset until launch):
+
+- "Fed cuts in May 2026"
+- "NYC max 80F+ on May 1"
+- "$FNCPT > $0.0001 by month end"
+
+This is a third sibling alongside Polymarket and Kalshi in the terminal's prediction-market tooling. Browsing on the MARKETS tab feels identical to those — same `PredictionExchangeAdapter` interface, same data shape, same hub-driven refresh pattern.
+
+---
+
+## What you see today
+
+```
+┌─ MARKETS ────────────────────────────────────────────── DEMO ────────┐
+│ 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│
+│ │
+│ Demo dataset. Set `fincept.markets_endpoint` in SecureStorage and │
+│ deploy the fincept_market Anchor program for live trading. │
+└───────────────────────────────────────────────────────────────────────┘
+```
+
+---
+
+## Demo mode (current)
+
+Phase 4 ships in **demo mode**. Two things have to land before the tab becomes transactional:
+
+1. The Fincept **matching engine** (HTTP + WebSocket on `markets.fincept.in`). When this is up, set `fincept.markets_endpoint` in SecureStorage and the adapter will fetch live markets, books, and price history.
+2. The on-chain **`fincept_market` Anchor program** that escrows YES/NO collateral and resolves payouts. When deployed, set `fincept.market_program_id` and the order-entry path enables.
+
+Until both are present, the MARKETS tab serves the curated three-market dataset baked into `FinceptInternalAdapter` so you can see what the screen will look like and verify the data shapes integrate cleanly with the unified `PredictionExchangeAdapter` (which also serves Polymarket and Kalshi).
+
+---
+
+## How it integrates
+
+The Fincept internal adapter is registered with `PredictionExchangeRegistry` alongside `PolymarketAdapter` and `KalshiAdapter`. Any code that already iterates the registry (Polymarket / Kalshi screen, command bar, MCP tools) can switch to `fincept` without special-casing.
+
+**Hub topics** are reserved (with policies) for the live path:
+
+- `prediction:fincept:markets` — market list, refreshes every 30 s.
+- `prediction:fincept:orderbook:<asset_id>` — per-asset book, WebSocket-driven.
+- `prediction:fincept:price:<asset_id>` — last-trade price scalar.
+
+When the matching engine ships, the adapter will publish to those topics; existing consumers attach automatically.
+
+---
+
+## What you can't do yet
+
+- **Place orders.** `place_order` returns `error_occurred("not deployed", …)` while in demo mode — the order ticket UI shows a clear "service unavailable" banner.
+- **See your positions.** Same gate — needs the on-chain program for any real escrow to exist.
+- **Create markets.** Plan §4.1 reserves market creation for **Gold tier** users; the proposal/vote flow lands with the engine.
+- **Earn from order flow.** veFNCPT lockers will receive a share of trading fees (Phase 3 §3.4) once the engine is settling real volume.
+
+---
+
+## When the engine ships
+
+You won't need to update the terminal — the seam is already in place. Configuration lives in SecureStorage:
+
+- `fincept.markets_endpoint` — base URL of the matching engine. Empty = demo mode.
+- `fincept.market_program_id` — base58 program ID for `fincept_market`. Empty = trading disabled.
+
+Both keys are user-configurable from Settings → Crypto → Advanced. The MARKETS tab will pick them up on the next visibility tick.
+
+---
+
+## Why $FNCPT-only
+
+Real-money prediction markets are regulated as derivatives in many jurisdictions. By denominating in $FNCPT we keep the venue framed as a **play-money internal mechanic** of the terminal, not a regulated financial product. We may geo-block sign-up in regions where legal review concludes otherwise.
+
+This is a policy decision; the engineering plan ships the same regardless. See `plans/crypto-center-future-phases.md` §4.7 for the rationale.
diff --git a/fincept-qt/docs/CRYPTO_CENTER_PHASE_5.md b/fincept-qt/docs/CRYPTO_CENTER_PHASE_5.md
new file mode 100644
index 000000000..701746a29
--- /dev/null
+++ b/fincept-qt/docs/CRYPTO_CENTER_PHASE_5.md
@@ -0,0 +1,112 @@
+# Crypto Center — Phase 5 user guide (Buyback & Burn)
+
+The **ROADMAP** tab in the Crypto Center shows Fincept's **value loop**: how much terminal revenue is being spent buying $FNCPT off the market and burning it. This is the demand engine that justifies the token long-term.
+
+---
+
+## What you see
+
+```
+┌─ BUYBACK & BURN ─ epoch 47 · 2026-04-21 → 2026-04-27 ─── ● LIVE ────┐
+│ THIS EPOCH │
+│ REVENUE $42,310 (subs $32k · pred-mkt $8k · misc $2k) │
+│ BUYBACK $21,155 (50% of revenue) │
+│ $FNCPT BOUGHT 82.4 M $FNCPT (avg $0.0002570) │
+│ $FNCPT BURNED 82.4 M $FNCPT │
+│ BURN TX 5kj3w…XXXX (click to open Solscan) │
+│ ──────────────────────────────────────────────────────── │
+│ ALL-TIME │
+│ BURNED 1.42 B $FNCPT │
+│ SUPPLY REMAINING 8.58 B $FNCPT │
+│ SPENT ON BUYBACK $384,201.00 │
+└──────────────────────────────────────────────────────────────────────┘
+
+┌─ SUPPLY CHART · 12 MONTHS ─── ● TOTAL ● CIRCULATING ● BURNED ─────┐
+│ [ time-series chart, three lines, last 12 months ] │
+└──────────────────────────────────────────────────────────────────────┘
+
+┌─ TREASURY ───────────────────────────────────── ● LIVE ─────────────┐
+│ USDC RESERVES $1.84M │
+│ SOL RESERVES 234.00 SOL ($19.7k) │
+│ TOTAL USD $1.86M │
+│ RUNWAY @ CURRENT 18 months ($100,000/mo) │
+│ MULTI-SIG 3-of-5 (click to open Squads) │
+└──────────────────────────────────────────────────────────────────────┘
+```
+
+Three panels stacked, scrollable on short windows. Each has its own LIVE / DEMO pill showing whether the data is real or mocked (see below).
+
+---
+
+## Where the data comes from
+
+A separate **Fincept buyback worker** (lives outside this repo, in `services/buyback-worker/`) does the heavy lifting:
+
+1. **Tally revenue** — sums Stripe subscriptions + on-chain prediction-market fees + misc, weekly.
+2. **Compute budget** — initial split is **50% buyback / 25% staker yield / 25% treasury**.
+3. **Execute** — splits the budget into hourly chunks and routes through Jupiter to avoid frontrunning a single big buy.
+4. **Burn** — once $FNCPT is in the treasury account, the worker calls SPL Token `burn_checked` to permanently destroy it. The burn transaction signature is the canonical receipt.
+5. **Publish** — the worker POSTs an epoch summary + cumulative totals + 12-month supply history to a Fincept HTTP endpoint that the terminal polls.
+
+The terminal **only reads** — it has no on-chain code in Phase 5, no custodial mechanism, and no signing authority over the treasury vault.
+
+---
+
+## Demo mode
+
+Until the buyback worker endpoint is configured, the dashboard ships built-in mock data so the UI is reviewable. The mock numbers are illustrative:
+
+- **Epoch 47** revenue $42,310 → buyback $21,155 → 82.4 M $FNCPT bought + burned.
+- **All-time** 1.42 B $FNCPT burned, 8.58 B remaining, $384,201 spent.
+- **Treasury** $1.84M USDC + 234 SOL = ~$1.86M total, 18 months runway @ $100k/mo.
+
+Each panel head shows **DEMO** in amber when any data on it is mocked, and the BURN TX link tooltip reads "Demo signature — connect a treasury endpoint for a real burn tx" so nobody mistakes the placeholders for real on-chain receipts.
+
+---
+
+## Configuring real data
+
+When the worker is deployed, configure the following keys in **SecureStorage**:
+
+| Key | Required | Notes |
+|---|---|---|
+| `fincept.treasury_endpoint` | yes | HTTP base URL where the worker publishes summaries. The terminal hits `<endpoint>/buyback/current`, `<endpoint>/burn/total`, `<endpoint>/supply/history`. |
+| `fincept.treasury_pubkey` | yes | base58 pubkey of the Squads multisig vault. Used by `TreasuryService` to fetch SOL + USDC reserves directly from Solana RPC. |
+| `fincept.treasury_monthly_opex_usd` | optional | default $100,000. Used for runway. Update as the team scales. |
+| `fincept.treasury_multisig_label` | optional | default `3-of-5`. Free-form chip text. |
+| `fincept.treasury_multisig_url` | optional | default `https://app.squads.so/squads/<pubkey>`. Override if you point at a different vault UI. |
+
+Once `fincept.treasury_endpoint` is set, the head pill on **Buyback & Burn** flips from `DEMO` to `LIVE`. Same for the treasury card the moment `fincept.treasury_pubkey` is configured.
+
+---
+
+## Hub topics
+
+Five terminal-wide topics power the dashboard. None carry a `<pubkey>` segment — the same numbers are shown to every user.
+
+| Topic | Producer | TTL | Notes |
+|---|---|---|---|
+| `treasury:buyback_epoch` | `BuybackBurnService` | 60 s | Current epoch summary + burn signature |
+| `treasury:burn_total` | `BuybackBurnService` | 5 min | All-time burned + remaining supply |
+| `treasury:supply_history` | `BuybackBurnService` | 1 h | 12-month time-series (`QVector<SupplyHistoryPoint>`) |
+| `treasury:reserves` | `TreasuryService` | 5 min | USDC + SOL + USD value, multisig label/url |
+| `treasury:runway` | `TreasuryService` | 5 min | Derived: `total_usd / monthly_opex_usd` |
+
+See `docs/DATAHUB_TOPICS.md` for full payload shapes.
+
+---
+
+## Where to find this in code
+
+- `src/services/wallet/BuybackBurnService.{h,cpp}` — Producer, three topics, dual real/mock paths
+- `src/services/wallet/TreasuryService.{h,cpp}` — Producer, two topics, peeks SOL price from `market:price:token:<wSOL>`
+- `src/screens/crypto_center/panels/BuybackBurnPanel.{h,cpp}` — top section, Solscan-clickable burn signature
+- `src/screens/crypto_center/panels/SupplyChartPanel.{h,cpp}` — middle section, QtCharts QChartView
+- `src/screens/crypto_center/panels/TreasuryPanel.{h,cpp}` — bottom section, Squads-clickable multisig
+- `src/screens/crypto_center/tabs/RoadmapTab.{h,cpp}` — wraps the three panels in a QScrollArea
+- `plans/crypto-center-future-phases.md` §5 — original plan
+- `docs/DATAHUB_TOPICS.md` "Buyback & burn dashboard" section — topic catalogue
+
+---
+
+**Last updated:** 2026-05-01
diff --git a/fincept-qt/docs/CRYPTO_WALLET_CONNECT.md b/fincept-qt/docs/CRYPTO_WALLET_CONNECT.md
new file mode 100644
index 000000000..b43b67c56
--- /dev/null
+++ b/fincept-qt/docs/CRYPTO_WALLET_CONNECT.md
@@ -0,0 +1,91 @@
+# Connecting your Solana wallet
+
+The **Crypto Center** screen lets you connect a Solana wallet to Fincept Terminal so you can see your $FNCPT and SOL balances, swap, and earn the fee discount on premium features. The terminal **never sees your private keys** — your wallet (Phantom, Solflare, Backpack, etc.) signs every operation locally.
+
+---
+
+## Supported wallets
+
+Any Solana wallet that handles a `signMessage` request in your default browser will work, including:
+
+- **Phantom** — recommended (most active development, broad hardware-wallet support)
+- **Solflare** — desktop + mobile, native Ledger
+- **Backpack** — newer, desktop + mobile
+- **Glow**, **Coinbase Wallet (Solana mode)** — also work
+
+The wallet does **not** need a browser extension to be installed in the same browser as Fincept Terminal — the terminal opens your default browser, the wallet's extension or webapp picks up the request there.
+
+---
+
+## Connecting
+
+1. Open the **Crypto Center** screen from the main nav.
+2. Click **CONNECT WALLET**.
+3. Your default browser opens a one-page Fincept handshake. Click **Connect** there. Your wallet pops a "Sign this message" prompt — approve it.
+4. The browser tab closes automatically and the terminal shows your public key, SOL balance, and $FNCPT balance.
+
+The "Sign this message" prompt is a **one-time identity challenge** — Fincept asks the wallet to sign a random nonce so we know the public key really belongs to you. Nothing is sent on-chain; no SOL leaves your wallet for this step.
+
+---
+
+## What gets stored locally
+
+Fincept Terminal saves only:
+
+- Your **public key** (base58 string)
+- The wallet **label** ("Phantom", "Solflare", etc.)
+- The **timestamp** of the connection
+
+These live in the encrypted **SecureStorage** under the keys `wallet.pubkey`, `wallet.label`, and `wallet.connected_at`. **Private keys, signatures, and seed phrases are never seen by the terminal** — they stay in your wallet's vault.
+
+---
+
+## Reconnecting on next launch
+
+When you restart Fincept Terminal with a previously-connected wallet, the screen restores the public key from SecureStorage and shows balances immediately, **without** prompting your wallet again. This is a "soft connect" — any operation that needs a signature (a swap, for example) re-prompts the wallet at that moment.
+
+---
+
+## Disconnecting
+
+Click **Disconnect** on the wallet status card. The terminal:
+
+1. Wipes the public key, label, and timestamp from SecureStorage.
+2. Stops all subscriptions tied to that wallet (balance, activity, fee discount).
+3. Returns the screen to its empty state.
+
+If you connect a different wallet next time, the new public key replaces the old — the previous one is fully removed.
+
+---
+
+## Security model in one paragraph
+
+The terminal opens a loopback HTTP server on `127.0.0.1` with a random port and a single-use token, then opens your default browser to that URL. The browser-side page handles the wallet adapter handshake (extension or WalletConnect), then POSTs the signed nonce + public key back to the loopback server. The terminal verifies the ed25519 signature against the public key before persisting anything. The bridge port is bound to **localhost only** — other machines on your network cannot see it. The signed nonce is single-use and expires after 60 seconds. See `plans/crypto-center-security-walkthrough.md` for the full threat model and mitigations.
+
+---
+
+## Troubleshooting
+
+**"Connection cancelled"** — you closed the browser tab or clicked Cancel in the wallet. Click **CONNECT WALLET** again to retry.
+
+**"Signature verification failed"** — extremely rare; almost always indicates a wallet bug or a deliberately-malformed signature. Try a different wallet or upgrade your wallet extension.
+
+**Browser doesn't open** — your default browser may not be set, or the OS is blocking handler launches. Set a default browser in OS settings and try again.
+
+**Balances show `—` after connecting** — the RPC may be slow. The Settings tab lets you provide a Helius API key for a faster RPC; without one, the terminal falls back to the public mainnet RPC (rate-limited).
+
+---
+
+## Where to find this in code
+
+- `src/services/wallet/WalletService.{h,cpp}` — connection state machine
+- `src/services/wallet/ConnectWalletDialog.{h,cpp}` — challenge + verification
+- `src/services/wallet/LocalWalletBridge.{h,cpp}` — loopback HTTP server
+- `src/services/wallet/Ed25519Verifier.{h,cpp}` — signature verification (orlp/ed25519)
+- `resources/wallet/connect.html` — browser-side handshake page
+- `plans/crypto-center-wallet-connect.md` — original plan
+- `plans/crypto-center-security-walkthrough.md` — security review
+
+---
+
+**Last updated:** 2026-05-01
diff --git a/fincept-qt/src/app/TerminalShell.cpp b/fincept-qt/src/app/TerminalShell.cpp
index 02f4cd17a..d0cd9fbc3 100644
--- a/fincept-qt/src/app/TerminalShell.cpp
+++ b/fincept-qt/src/app/TerminalShell.cpp
@@ -32,53 +32,70 @@ TerminalShell& TerminalShell::instance() {
return s;
}
+// FT_TS: trace markers identical to FT_MARK in main.cpp, scoped to TerminalShell::initialise.
+#ifdef Q_OS_WIN
+# include <windows.h>
+# include <stdio.h>
+# include <string.h>
+# define FT_TS(n) do { char _msg[64]; _snprintf_s(_msg, 64, _TRUNCATE, "FT_TS %d\n", (n)); OutputDebugStringA(_msg); HANDLE _h = CreateFileA("C:\\Users\\Tilak\\AppData\\Local\\Temp\\ft_marks.txt", FILE_APPEND_DATA, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (_h != INVALID_HANDLE_VALUE) { DWORD _w; SetFilePointer(_h, 0, NULL, FILE_END); WriteFile(_h, _msg, (DWORD)strlen(_msg), &_w, NULL); CloseHandle(_h); } } while(0)
+#else
+# define FT_TS(n) do { fprintf(stderr, "FT_TS %d\n", (n)); fflush(stderr); } while(0)
+#endif
+
void TerminalShell::initialise() {
+ FT_TS(100);
if (initialised_) {
LOG_WARN(kShellTag, "initialise() called twice — ignoring");
return;
}
LOG_INFO(kShellTag, "Shell initialising");
+ FT_TS(101);
// Resolve and cache the active profile UUID so every later phase has
// a stable handle without re-reading the manifest. ProfileManager
// mints + persists a UUID on first read if the manifest is legacy.
active_profile_id_ = ProfileManager::instance().active_profile_id();
+ FT_TS(102);
LOG_INFO(kShellTag, QString("Active profile: %1 (id=%2)")
.arg(ProfileManager::instance().active())
.arg(active_profile_id_.to_string()));
-
+ FT_TS(103);
// Create the new per-profile directory tree (workspace.db, layouts/,
// crashes/). Distinct from AppPaths::ensure_all() which creates the
// legacy tree (data/, logs/, cache/, etc.) — both run, both are
// idempotent.
ProfilePaths::ensure_all();
-
+ FT_TS(104);
// Touch the registries so their static singletons construct *before*
// any WindowFrame tries to register against them. Avoids a startup
// race where the first window's constructor runs faster than the
// registry's singleton init under aggressive optimisation.
(void) WindowRegistry::instance();
+ FT_TS(105);
(void) ActionRegistry::instance();
+ FT_TS(106);
(void) PanelRegistry::instance();
+ FT_TS(107);
(void) ProfileManager::instance();
+ FT_TS(108);
// Phase 6 trim: MonitorWatcher boots here so its QGuiApplication signal
// connections are in place before any frame restores. Phase 6's full
// workspace-variant matcher will subscribe to topology_changed.
(void) MonitorWatcher::instance();
-
+ FT_TS(109);
// Phase 1b skeleton: LockOverlayController construction. Currently a
// no-op — the full lift is deferred (see auth/lock/LockOverlayController.h
// for rationale). Constructing it here keeps the dependency direction
// shell → controller correct so the future lift doesn't have to invert.
auth::LockOverlayController::instance().initialise();
-
+ FT_TS(110);
// Phase 3 final: chat-bubble shell coordinator. Per-frame bubble
// widgets stay where they are; this just centralises the shell-side
// observation surface (frame add/remove tracking, future telemetry,
// future cross-frame chat-session linking).
ai_chat::ChatBubbleController::instance().initialise();
-
+ FT_TS(111);
// Phase 6: open the per-profile LayoutCatalog so Launchpad's recent-
// layouts list + the layout.* actions can read/write immediately.
{
@@ -88,6 +105,7 @@ void TerminalShell::initialise() {
.arg(QString::fromStdString(r.error())));
}
}
+ FT_TS(112);
// Phase 10: install LocalTelemetrySink iff the user opted in. Settings
// → Telemetry section (Phase 9 settings refactor) is the user-facing
@@ -109,11 +127,23 @@ void TerminalShell::initialise() {
// replaced WindowFrame's hard-coded keyboard wiring. Must happen before
// any WindowFrame is constructed so the per-frame hotkey-binding loop
// sees the full action set.
+ FT_TS(113);
actions::register_builtins();
-
+ FT_TS(114);
// ── Phase 2: workspace persistence + crash recovery ────────────────
workspace_db_ = &WorkspaceDb::instance();
- auto db_open = workspace_db_->open(ProfilePaths::workspace_db());
+ FT_TS(115);
+ QString _ws_path = ProfilePaths::workspace_db();
+ FT_TS(1150);
+ char _path_msg[512];
+ _snprintf_s(_path_msg, 512, _TRUNCATE, "FT_TS workspace_db path: %s\n", _ws_path.toUtf8().constData());
+ OutputDebugStringA(_path_msg);
+ {
+ HANDLE _h = CreateFileA("C:\\Users\\Tilak\\AppData\\Local\\Temp\\ft_marks.txt", FILE_APPEND_DATA, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (_h != INVALID_HANDLE_VALUE) { DWORD _w; SetFilePointer(_h, 0, NULL, FILE_END); WriteFile(_h, _path_msg, (DWORD)strlen(_path_msg), &_w, NULL); CloseHandle(_h); }
+ }
+ auto db_open = workspace_db_->open(_ws_path);
+ FT_TS(116);
if (db_open.is_err()) {
LOG_ERROR(kShellTag, QString("Failed to open workspace.db: %1")
.arg(QString::fromStdString(db_open.error())));
@@ -148,9 +178,11 @@ void TerminalShell::initialise() {
}
}
+ FT_TS(120);
initialised_ = true;
LOG_INFO(kShellTag, "Shell initialised");
emit started();
+ FT_TS(121);
}
void TerminalShell::shutdown() {
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index 45839fb5d..fb96f4bca 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -83,7 +83,16 @@
# include <Windows.h>
#endif
+// FT_MARK: write a sequence number to a file so we can see how far startup progressed.
+// GUI-subsystem apps don't have a useful stderr, so we go straight to disk.
+#ifdef Q_OS_WIN
+# define FT_MARK(n) do { char _msg[64]; _snprintf_s(_msg, 64, _TRUNCATE, "FT_MARK %d\n", (n)); OutputDebugStringA(_msg); HANDLE _h = CreateFileA("C:\\Users\\Tilak\\AppData\\Local\\Temp\\ft_marks.txt", FILE_APPEND_DATA, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (_h != INVALID_HANDLE_VALUE) { DWORD _w; SetFilePointer(_h, 0, NULL, FILE_END); WriteFile(_h, _msg, (DWORD)strlen(_msg), &_w, NULL); CloseHandle(_h); } } while(0)
+#else
+# define FT_MARK(n) do { fprintf(stderr, "FT_MARK %d\n", (n)); fflush(stderr); } while(0)
+#endif
+
int main(int argc, char* argv[]) {
+ FT_MARK(1);
// ── Parse --profile <name> from argv before Qt initialises ───────────────
// This must happen first so that:
// 1. AppPaths returns the correct per-profile directories
@@ -100,6 +109,7 @@ int main(int argc, char* argv[]) {
// write the manifest. Create root now (single mkdir, idempotent).
QDir().mkpath(fincept::AppPaths::root());
}
+ FT_MARK(2);
// Install the unhandled-exception filter BEFORE any Qt object is
// constructed. On Windows this writes a minidump to AppPaths::crashdumps()
@@ -149,9 +159,12 @@ int main(int argc, char* argv[]) {
//
// Must run BEFORE any service init so future phases that lift services
// into the shell can rely on it being present.
+ FT_MARK(10);
fincept::TerminalShell::instance().initialise();
+ FT_MARK(11);
QObject::connect(&app, &QCoreApplication::aboutToQuit,
[]() { fincept::TerminalShell::instance().shutdown(); });
+ FT_MARK(12);
// Register DataHub payload meta-types (QuoteData, HistoryPoint, InfoData,
// NewsArticle, EconomicsResult) so they can flow through QVariant-keyed
@@ -171,7 +184,9 @@ int main(int argc, char* argv[]) {
QCoreApplication::applicationDirPath() + "/component_catalog.json",
"resources/component_catalog.json",
});
+ FT_MARK(20);
fincept::services::MarketDataService::instance().ensure_registered_with_hub();
+ FT_MARK(21);
// Phase 2 (multi-broker refactor): ExchangeSessionManager is the hub
// producer for `ws:kraken:*` / `ws:hyperliquid:*`. Individual sessions
// (created lazily by the manager) publish through its SessionPublisher
@@ -235,12 +250,18 @@ int main(int argc, char* argv[]) {
// 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.
+ FT_MARK(30);
fincept::wallet::TokenMetadataService::instance().load_from_storage();
+ FT_MARK(31);
fincept::wallet::TokenMetadataService::instance().refresh_from_jupiter_async();
+ FT_MARK(32);
// Restore_from_storage runs after the hub is up so a soft-connected
// wallet's balance topic resolves to a registered producer immediately.
+ FT_MARK(33);
fincept::wallet::WalletService::instance().ensure_registered_with_hub();
+ FT_MARK(34);
fincept::wallet::WalletService::instance().restore_from_storage();
+ FT_MARK(35);
// Phase 2 §2C: fee-discount eligibility producer. Lives in billing/
// because it's consumed by other paid screens later; for Phase 2 it
@@ -331,8 +352,10 @@ int main(int argc, char* argv[]) {
hub.set_policy_pattern(QStringLiteral("billing:tier:*"), tier_p);
}
+ FT_MARK(40);
// Create all application directories under %LOCALAPPDATA%/com.fincept.terminal
fincept::AppPaths::ensure_all();
+ FT_MARK(41);
// ── One-time migration from legacy %APPDATA% location ─────────────────
// Current locations (under %LOCALAPPDATA%\com.fincept.terminal\):
@@ -380,7 +403,9 @@ int main(int argc, char* argv[]) {
QFile::remove(legacy2 + "-shm");
}
+ FT_MARK(50);
fincept::Logger::instance().set_file(fincept::AppPaths::logs() + "/fincept.log");
+ FT_MARK(51);
// P3.18 — route Qt's own qDebug/qWarning/qCritical messages into our log
// file so framework/3rd-party warnings are visible in Release builds.
diff --git a/fincept-qt/src/storage/workspace/WorkspaceDb.cpp b/fincept-qt/src/storage/workspace/WorkspaceDb.cpp
index 0a62ac577..da591a6d2 100644
--- a/fincept-qt/src/storage/workspace/WorkspaceDb.cpp
+++ b/fincept-qt/src/storage/workspace/WorkspaceDb.cpp
@@ -27,7 +27,7 @@ WorkspaceDb& WorkspaceDb::instance() {
}
Result<void> WorkspaceDb::open(const QString& path) {
- QMutexLocker lock(&mutex_);
+ QMutexLocker<QRecursiveMutex> lock(&mutex_);
// Idempotent: if already open at the same path, nothing to do.
if (db_.isOpen() && db_.databaseName() == path) {
@@ -63,7 +63,7 @@ Result<void> WorkspaceDb::open(const QString& path) {
}
void WorkspaceDb::close() {
- QMutexLocker lock(&mutex_);
+ QMutexLocker<QRecursiveMutex> lock(&mutex_);
if (db_.isOpen())
db_.close();
if (!connection_name_.isEmpty()) {
@@ -73,12 +73,12 @@ void WorkspaceDb::close() {
}
bool WorkspaceDb::is_open() const {
- QMutexLocker lock(&mutex_);
+ QMutexLocker<QRecursiveMutex> lock(&mutex_);
return db_.isOpen();
}
Result<QSqlQuery> WorkspaceDb::execute(const QString& sql, const QVariantList& params) {
- QMutexLocker lock(&mutex_);
+ QMutexLocker<QRecursiveMutex> lock(&mutex_);
QSqlQuery query(db_);
query.prepare(sql);
for (int i = 0; i < params.size(); ++i)
@@ -89,7 +89,7 @@ Result<QSqlQuery> WorkspaceDb::execute(const QString& sql, const QVariantList& p
}
Result<void> WorkspaceDb::exec(const QString& sql) {
- QMutexLocker lock(&mutex_);
+ QMutexLocker<QRecursiveMutex> lock(&mutex_);
QSqlQuery query(db_);
if (!query.exec(sql))
return Result<void>::err(query.lastError().text().toStdString());
@@ -112,7 +112,7 @@ QString WorkspaceDb::meta(const QString& key) const {
// Re-acquire the lock here; execute() locks too, so we go through it.
// This is one of the rare const methods that mutates internal state via
// the mutex; mutable QMutex makes that explicit.
- QMutexLocker lock(&mutex_);
+ QMutexLocker<QRecursiveMutex> lock(&mutex_);
QSqlQuery query(db_);
query.prepare("SELECT value FROM _meta WHERE key = ?");
query.bindValue(0, key);
@@ -135,7 +135,7 @@ Result<void> WorkspaceDb::set_meta(const QString& key, const QString& value) {
}
QString WorkspaceDb::path() const {
- QMutexLocker lock(&mutex_);
+ QMutexLocker<QRecursiveMutex> lock(&mutex_);
return db_.databaseName();
}
diff --git a/fincept-qt/src/storage/workspace/WorkspaceDb.h b/fincept-qt/src/storage/workspace/WorkspaceDb.h
index dd24b2451..37f473c2f 100644
--- a/fincept-qt/src/storage/workspace/WorkspaceDb.h
+++ b/fincept-qt/src/storage/workspace/WorkspaceDb.h
@@ -89,7 +89,11 @@ class WorkspaceDb {
QSqlDatabase db_;
QString connection_name_;
- mutable QMutex mutex_;
+ // Recursive: open() holds the mutex while calling create_tables(),
+ // which routes through exec() that re-acquires the same mutex. With a
+ // non-recursive QMutex this deadlocks the main thread before any window
+ // is shown — see ee4e946e regression.
+ mutable QRecursiveMutex mutex_;
};
} // namespace fincept