M1 local end-to-end review: DEX (RFP-004), TWAP oracle (RFP-019), stablecoin (RFP-013)
Date: 2026-10-15. Reviewer: laptop/SPEL (Václav's agent).
Target:
logos-blockchain/lez-programs@64c0121, LEZ v0.2.4.- Local standalone sequencer with proving disabled (
RISC0_DEV_MODE=1), 15 s blocks.
Aim: find where these programs break, not confirm they run. Every action was logged with a state snapshot. Raw data:
run/log.jsonl: one record per action. Each has the tx hash, the outcome, and a snapshot of pool, vaults, current tick, observation buffer, price account, protocol-fee holdings and user balances.run/timeline.txt: the same data as a table.run/sequencer.log: the real rejection reasons. The CLI never shows them; see F-DX1.
All findings below were observed on chain unless marked (code), which means read from source.
0. Setup and what was exercised
| Piece | How | Result |
|---|---|---|
| LEZ v0.2.4 sequencer + wallet | built from tag, standalone | ok |
| 6 guest programs | make build-programs (Docker, release profile) |
ok. token / amm / twap_oracle ImageIDs are identical to DEPLOYMENTS.md, so the build is reproducible. token_mint_authority differs (1ea6d932… vs b0163189…), meaning its source changed since the Sep-10 deploy. |
| Unit + integration tests | cargo test --workspace (dev mode) |
~950 tests, 0 failures. They miss every critical finding below (§4). |
| Program CLI | SPEL v0.7.0, then SPEL 415b7bc (see F-ST3) |
ok |
| AMM core module | nix build .#amm-module + lez_core @ acf0cd5 + logoscore daemon |
works: config read, pool resolve, quote, swap submit |
| Stablecoin module | not driven: today it only exposes discovery, param reads and init (see the module issues on GitHub) | n/a |
| TWAP module | does not exist. The AMM module only has the two setup calls. | gap |
apps/amm UI in real Basecamp |
Basecamp-Desktop v0.3.2 AppImage, own --user-dir, on an isolated Xvfb display, driven with xdotool, full screen recording |
works: swap, add liquidity, remove liquidity, create pool, all verified on chain. Serious UX bugs, see §2b |
Note on the restarted sequencer: it hit a 2-hour tool limit once and was restarted on the same state directory. All state survived.
1. TWAP oracle (RFP-019): the core design does not produce a manipulation-resistant TWAP
Pool TKA/TKB started at 1e18 A / 2e18 B (spot 2.0, tick 6932). The window was 600,000 ms (10 min), observation capacity 2048, so min_interval = 292 ms.
Observation buffer, reconstructed from the account itself (exact, not from snapshots)
| obs | tick credited | price | credited for | what really happened in that interval |
|---|---|---|---|---|
| 1 | 6932 | 2.000 | 214.6 s | true price ≈ 2.0. Correct. |
| 2 | -976 | 0.907 | 654.5 s | Price was ≈ 2.0 for almost all of it. 0.907 existed only between the attacker's 5e17 A swap (A1a) and the attacker's own record_tick (A1b), about one block. |
| 3 | 8140 | 2.257 | 32.1 s | True tick after unwind was 9013. The clamp anchored on the manipulated -976, so honest recovery was capped at -976 + 9116 = 8140. |
| 4 | 9857 | 2.680 | 66.0 s | A second manipulation (A2a, tick 408) was never recorded because nobody recorded before the unwind. Whoever times record_tick decides which prices exist. |
| 5 | 741 (clamped) | 1.077 | 4803 s (80 min) | First record after the pool was drained (§2). A value that never existed, credited for 80 minutes. |
| 6-8 | -131,245 | 0.000002 | 15-17 s each | Pool drained to 750/1641 units, then a 1e6-unit swap. The clamp was already gone by the second record. |
The published price fell from 2.0 to 1.131 (-43%) right after A1 (one manipulated block plus an attacker-timed record), and stayed at 1.128 after the price recovered.
Findings
- T1.
record_tickis not time-weighted. Critical, observed (obs 2, 5).cumulative += current_tick × (now − last_record). The tick at the moment of recording is credited for the whole gap since the previous record.CurrentTickAccount.last_updatedis ignored (record_tick.rs). Uniswap accumulates the price that held before each change. Here an attacker moves spot, records, and unwinds; the manipulated price is weighted over the entire gap, which can be longer than the window.publish_pricedoes uselast_updatedfor its tail, so the two functions disagree. - T2. The
MAX_TICK_DELTAclamp protects exactly one observation. Critical, observed (obs 5 → 6). After clamping the credited tick,record_ticksetslast_recorded_tick = current_tick(unclamped). The next record is measured from the manipulated anchor, so an attacker just records twice. Meanwhile the clamp does slow honest recovery (obs 3). - T3.
record_tickandpublish_priceare permissionless. High. No signer. Combined with T1 and T2, the attacker controls both the sampling times and the price at those times. - T4.
publish_priceignoreswindow_duration. High (code + observed). It averages from the oldest buffered entry to now.window_durationonly selects the PDA andmin_interval. Before the buffer fills, a "10-min TWAP" is the average since creation (≈ 87 min in this run). After it fills, it covers 2048 records at whatever cadence people call it, e.g. ≈ 8.5 h at one record per 15 s block. - T5. The published timestamp masks staleness. High.
price_account.timestamp = nowat publish, not the age of the underlying observations. Anyone can callpublish_price, so a consumer'smaxAgecheck passes on data that is hours old or attacker-shaped. The stablecoin relies on exactly this check (§3). - T6. No liquidity awareness. High, observed. After the LP withdrew everything (only the 1000 locked LP units left: 750 A / 1641 B), a 1,000,000-unit swap set the current tick to -131,245. Nothing gates a feed on pool depth, and the TWAP followed it (obs 6-8).
- T7. Price feeds can be spoofed one-shot. Medium, observed (S1'). A brand-new account created an
OraclePriceAccountfor the real TKA/TKB pair at price 1000,source_id= itself, in one tx. The canonical standard has no registry; consumers must pinsource_idor the account id. (The stablecoin pins the account id at rotation time, which makes it an admin-trust problem.) - T8. Donation plus
sync_reservesmoves the price without a trade. Low/medium, observed (S2). 2e17 A donated to the vault, then the permissionlesssync_reserves: spot 2.68 → 2.19, current tick 9857 → 7832. It costs the donation (it goes to LPs), so it is more expensive than T1, but it is a second lever. - T9. Silent no-op with fewer than 2 observations. Low (code).
publish_pricereturns the account unchanged with no error. The account keeps the creation-time price and timestamp. - T10.
confidence_intervalis always 0. Info. Allowed by the RFP ("zero otherwise"), but the TWAP could provide one.
Against RFP-019 hard requirements (code + observed)
| Requirement | Status |
|---|---|
| Recording must not depend on a keeper or crank; captured as a side effect of pool activity | Not met. Pool ops only update the current tick; observations require separate record_tick calls (verified: swaps never added entries). |
| Cardinality default 1, expandable to 65,535 | Not met. Fixed 2048, no expansion instruction. |
Read-only query interface (pool + window → TWAP + timestamps used), maxAge |
Not met. Only the state-writing publish_price; the window is ignored (T4). |
Owner registers feed sources; per-pool params (e.g. MAX_TICK_DELTA) governed via RFP-001 |
Not met. No owner or registration; anyone with a signer can create feeds (T7); MAX_TICK_DELTA is a compile-time const. |
| Canonical price account struct with base/quote/price/timestamp/source/confidence; reject zero/invalid | Struct present; zero rejected (S1d). No scale/decimals field (see F-ST1). Not published as a standalone SPEL IDL. |
| SDK/module, dashboard mini-app, CLI, reference consumer + multi-source example, clear errors | Mostly missing: module has setup only, no dashboard, generic spel CLI only, errors invisible (F-DX1). |
2. DEX / AMM (RFP-004): the core mechanics hold
Verified working (observed):
- Initialize; pool create (LP = √(a·b), 1000 locked); add/remove liquidity proportional; both swap kinds;
sync_reservesno-op without donation. - Protocol fee: the 10% share of the 0.30% fee lands in the per-token PDA holding.
- Authority-gated withdrawal works, and a non-authority signer is rejected ("caller is not the configured admin authority").
- Protocol-fee redirect blocked (A3): the holding must equal
compute_protocol_fee_pda(config, token_in). - Slippage and deadline guards hold (A5a/A5b).
- Dust rounding favours the pool: 1 A and 1-2 B swaps are rejected ("Effective swap amount should be nonzero" / "less than minimal amount out"); 2 A gave 2 B at spot 2.68.
- Module (
amm_modulevialogoscore):configAccount,resolvePoolAccount,swapExactInQuote,swapExactInputall work. The on-chain delta matched the quote exactly (−2,988,020,943,119,709 D).
Findings:
- D1. Spot is cheap to move when liquidity is thin (observed §1 T6), and the oracle consumes it. That is the expected AMM property, but it combines with T1-T6.
- D2. "Privacy-preserving DEX" is not achievable on 0.2.4. Private txs can't share pool state; M1 should be scoped as public swaps (agree with fryorcraken).
- D3. Quote UX.
priceImpactBps: 40for a 0.1%-of-reserves trade; 30 of the 40 bps is the fee. Label or split it. - D4. Runbook drift (
docs/testnet-runbook.md).new_fungible_definitionnow requires--mint-authority(passnone).amm_pdasnow needs the instance owner (namespacing, #357).- The runbook points to an old SPEL fork branch.
- D5. Module README drift.
- It tells you to build
lez_corefrom a personal fork branch, while the flake pins upstreamacf0cd5. - It's macOS-only (
.dylib,darwin-arm64-dev) and documents the oldlogoscore -l/-cCLI; the current one is daemon-based (-D,load-module,call). - The plugin is called
lez_core_plugin.so, notlogos_execution_zone_plugin. - The wallet must be opened and synced by hand.
- It tells you to build
2b. DEX UI in real Basecamp (RFP-004 M1 "UI working")
Setup:
- Basecamp: the Basecamp-Desktop v0.3.2 AppImage with its own
--user-dir. It ran on an isolated virtual display (Xvfb:99), driven by xdotool clicks and recorded by ffmpeg. - Packages:
amm_ui,amm_moduleandlez_core, installed withlgpm(portable variant). - Chain and data: the local v0.2.4 sequencer, the repo's isolated test wallet, and its token/pool registry (
apps/amm/tests/testnet/setup-amm-testnet.sh). - Verification: every action below was checked against chain state with
spel inspect. - Screenshots are in
gui/shots/; recordings are ingui/rec/, including the whole session: full session recording.
What works (observed on chain)
| Flow | UI preview | On-chain result |
|---|---|---|
| Load app | Wallet auto-adopted, lez_core synced to the chain head |
ok (01) |
| Swap 100 TKA → TKB | buy 98, min 97 | reserves 10000/10000 → 10100/9902, i.e. +100 A, -98 B, exactly as quoted (05, 06, video) |
| Add liquidity 1000 TKA | auto-filled 683 TKB, deposit 999 + 683, LP 825 | +999 A, +683 B, +825 LP, exact (21, 22b, video) |
| Remove liquidity 50% | 5943 A + 4060 B | −4912 LP, −5943 A, −4060 B, exact (25, video) |
| Create pool TKA/TKC | 1001 + 1001, 1 LP | pool ikunktkb… created, reserves 1001/1001, LP supply 1001 (32, 34, video) |
| Guards | "Amount too small" for dust; Add-liquidity CTA disabled with empty fields | ok (10, 20) |
UI findings
- U1. A swap the chain rejected shows the same green "Swap submitted" toast as one that succeeded. High, observed.
- How: a front-run. Quote 100 TKA (min 95 TKB), push 2000 A through the pool from the CLI, then confirm in the UI.
- Chain: rejected it,
Withdraw amount is less than minimal amount out(the slippage guard working correctly). - UI: a green "Swap submitted · tx 0adda2dd…" toast, then the form reset. No error ever appears, and the pool and balances never change. The module's reply was
"success": true. - Cause: v0.2.4 leaves no receipt for rejected txs (F-DX1), and the app treats "submitted" as success.
- Evidence: toast, video. The successful swap's toast is identical: 08c.
- U2. Create pool defaults lock 99.9% of the creator's deposit. High, observed.
- What happened: the form defaults to the minimum (1001 + 1001); the creator receives 1 LP while 1000 LP are locked forever. The confirm dialog only says "Expected LP 1 raw LP"; there's no warning.
- Why so severe here: because amounts are base units (U4), the 1000-unit
MINIMUM_LIQUIDITYlock, negligible at 18 decimals, dominates.
- U3. Pools created in the app don't appear anywhere in the app. Medium, observed. The new TKA/TKC pool is missing from Positions and Explore, which only show pools from the static config. The creator can't see or manage their position (37, 38).
- U4. Decimals are ignored. Medium. The registry declares
decimals: 18, but amounts are entered and shown in base units ("100 TKA" = 100 base units). The loader says so: "the app doesn't use it yet". For real tokens a user would type 10^18 to trade one token. - U5. The displayed fee understates the real fee by 100x for small trades. Medium, observed.
- Shown: fee "0.010000 TKA" on a 100-unit swap.
- Actual: the chain rounds the fee up to 1 whole unit (out = 98, not 99), and the pool's "Accumulated fees" correctly shows 1.
- Also: "Price impact 2.00%" includes the fee rounding; the real impact is about 1%.
- U6. Balances on the Trade and New-position screens are stale. Medium, observed.
- Trade: the holding chip shows
3b11459.....999990000, i.e. the account-id prefix glued to the last 9 digits of the launch-time balance. It never refreshed after two confirmed swaps; the real balance had moved to …987900. - New position: "Balance 999999999999999990000" is stale the same way.
- Positions/pool detail read fresh data, so the screens contradict each other.
- Trade: the holding chip shows
- U7. The Add-liquidity preview with empty inputs shows a full-balance spend. Low/medium, observed. With both fields at 0, "Expected spend: 999999999999999990000 TOKEN A + 683140495867768588209 TOKEN B", ~8.26e20 LP. The CTA is disabled, so it can't be submitted, but it is alarming (19).
- U8. Smaller issues.
- "Tokens by 24H volume" heading with no volume data.
- The two token pickers differ (order, headings).
- The buy picker offers the sell token, and choosing it is silently ignored.
- Mixed locale formatting on one screen (
0.68314049vs0,01%,10 890). - The "Pool balances" bar splits by token units and claims this "reflects the pool's own price" (in a CPMM the value split is always 50/50).
- The wallet chip alternates between the account id and "Connected".
- Explore lists pools without reserves/price/volume ("Pools / Pools").
- The typed amount 1000 is silently trimmed to a 999 deposit.
- U9. No oracle/TWAP surface anywhere in the UI. Confirms the missing RFP-019 dashboard from the user side.
- U10. Build and install drift. Medium, observed.
- The app README builds
lez_coreatd70225c, which installs aslogos_execution_zone. Bothamm_moduleandamm_uidepend onlez_core, so following the README yields "Failed to load core dependencies". - The flake-pinned
acf0cd5is the one that works; the module README points to a third (fork) revision.
- The app README builds
- U11. Basecamp log warnings.
RemoveLiquidityDialog.qml:443"Qt Quick Layouts: Detected recursive rearrange";- the sandbox redirects the plugin's bundled
Logos.Theme/Controls/Iconsto the vetted copies, so the plugin ships modules that Basecamp ignores.
3. Stablecoin (RFP-013): two critical bugs, a bootstrap trap, and a fund lock
Setup: collateral = TKA, redemption price 0.5, CR 1.5x, Kp = 1.0 (RAY), Ki = 0, fee 1 + 1.5e-12 /ms (≈ 4.8%/yr).
| step | result | detail |
|---|---|---|
| SC0 oracle (fresh person-fed source) | ok | Price account base = future stablecoin PDA, quote = TKA, price 0.5 in Q64.64 |
SC1 initialize_program |
ok only with SPEL 415b7bc |
SPEL v0.7.0 CLI cannot encode i128 (F-ST3) |
SC3 open_position (fresh owner) |
ok | 1e18 A locked |
SC4 generate_debt (same owner) |
rejected | DeclaredAccountMissingFromOutput for the owner (F-ST2) |
SC5 accrue_stability_fee |
ok | rate 1.000000841 after 561 s, matches (1 + 1.5e-12)^561000 |
SC6 update_redemption_rate |
ok but wrong | rate became 1.00001 /ms instead of 1.0 (F-ST1) |
SC7 refresh_globals ~20 min later |
ok | redemption price 0.5 → 91,499.8 (×183,000) |
SC8 open_position (auth-transfer-initialized owner) |
ok | |
SC9 generate_debt 1e15 vs 1e18 collateral |
rejected | "Position is undercollateralized": minting bricked by F-ST1 |
SC10 deposit_collateral (same owner, 2nd op) |
ok | confirms the auth-transfer workaround for owners |
SC11 admin set_controller_gains (admin's 2nd action) |
rejected | "invalid length: expected 32 bytes, got 0". Unexplained; admin can never act again (see also F-ST2) |
| auth-transfer init on the stuck owner | rejected | "Account must be uninitialized": the SC3 position's 1e18 collateral is permanently locked |
- F-ST1. Price-scale mismatch between oracle and stablecoin. Critical, observed. The TWAP writes
pricein Q64.64 (1.0 = 2^64); the controller usesoracle.pricedirectly as RAY (1.0 = 1e27):error = redemption − market. A real 0.5 reads as 9.2e-9, so the controller saturates. The redemption price compounds ×1.82/minute (10^15.6 per hour); within minutes every position is undercollateralized and minting is impossible.- Why tests pass: stablecoin tests inject oracle fixtures written in RAY (
FIXED_POINT_ONE / 2) and never use the real TWAP program. - Fix: convert at the boundary, and add a scale/decimals field to the canonical price account (this is exactly what RFP-019's standard is meant to prevent).
- Why tests pass: stablecoin tests inject oracle fixtures written in RAY (
- F-ST2. Plain signer accounts work only once (SPEL × LEZ v0.2.4). Critical, observed.
- Which code: stablecoin (
owner,admin,caller) and twap_oracle (price_source) checkis_authorizedmanually instead of declaring#[account(signer)], so SPEL never claims them. - Mechanism: after their first tx they are default-owned with nonce > 0. SPEL's generated
maindrops such accounts from the output ("rule 7" filter). LEZ v0.2.4 then rejects withDeclaredAccountMissingFromOutput. - Impact on admin: the admin gets exactly one action (init), so it can never rotate the oracle, change params, or freeze.
- Impact on owners: a position owner can open and then nothing else. Withdraw and close need the owner, so collateral is locked forever, and the account can't be rescued afterwards.
- Impact on the oracle: a person-fed price source can make one call ever.
- Workaround:
wallet auth-transfer initthe account before first use (verified, SC8/SC10). - Tests hide it: fixtures set
program_owner: [7u32; 8], and the test's own comment says LEZ would reject otherwise. - Fix options: SPEL should keep unclaimed default-owned accounts in the output (they're legal on v0.2.4 as long as the program doesn't modify them), or programs declare these as SPEL signers (that triggers the signer-claim trap, so docs/UI must handle it). This is partly a SPEL bug; ours to file.
- Which code: stablecoin (
- F-ST3. No released SPEL can initialize the stablecoin. High.
- SPEL v0.7.0's CLI fails with
type mismatch: expected i128on the controller gains. - Signed-int support (#289) landed after v0.7.0.
- SPEL
mainhas since merged #290 (LEZ v0.2.5-rc2), so it no longer talks to v0.2.4. - The only working build is the unreleased
415b7bc. M1 needs a SPEL release on the v0.2.4 line (e.g. v0.7.1 from415b7bc).
- SPEL v0.7.0's CLI fails with
- F-ST4. Bootstrap needs an oracle quoting a token that doesn't exist yet. Medium.
initialize_programrequires an existing price account withbase_asset= the stablecoin definition PDA it is about to create. No AMM-sourced TWAP can satisfy that, so launch needs a person-fed feed. Given F-ST2, that feed can never be updated, so the protocol goes stale aftermaximum_oracle_price_ageunless the (also stuck) admin rotates it. - F-ST5. The staleness gate inherits T5.
now − oracle.timestamp ≤ maxAgepasses whenever anyone has re-published, regardless of observation age. Combined with T1-T3, the redemption rate is steerable. - F-ST6. Issue #95 ("feedback controller") looks stale. The PI controller exists (
update_redemption_rate, design §6.4). Verify and close.
4. Cross-cutting
- F-DX1. Failures are invisible. High (and visible to end users in the UI as U1). On v0.2.4 a rejected tx leaves no receipt; the CLI waits 15 blocks (~4 min) and prints "Transaction not found". The actual reason (guest panic text,
DeclaredAccountMissingFromOutput,OutOfValidityWindow) exists only in the sequencer's own log. Every module/UI built on this inherits it. RFP-019 explicitly requires clear errors. - F-DX2. Tx hashes collide for unsigned calls. Medium. Identical
record_tick/publish_pricecalls (no signers, no nonce) produce identical bytes, so the same hash (e.g.ecae42cc…for 7 different records). Each executed. Explorers/indexers keyed by hash and the wallet's confirmation-by-hash can't tell them apart (the CLI reported "confirmed" before the new state was visible). - F-DX3. Tests are green but miss every critical issue. The unit and integration tests use hand-built fixtures that are internally consistent but don't match what the real programs produce: RAY-scaled oracles, fake non-default owners. A small e2e suite against a real sequencer (like this run) would have caught F-ST1, F-ST2, T1 and T2.
5. What M1 needs (proposal)
-
Blockers before any testnet deploy:
- F-ST1 (scale);
- F-ST2 (signer accounts; SPEL issue + program-side declaration or onboarding with auth-transfer);
- T1 + T2 (accumulate the pre-change tick using
last_updated; clamp against the clamped anchor); - F-ST3 (cut SPEL v0.7.1 on the v0.2.4 line);
- UI: U1 (track inclusion, never show a rejected tx as success), U2 (pool-creation lock warning/defaults), U10 (fix the
lez_corerevision in the app README).
-
Agree with fryorcraken on M1 scope:
- RFP-019 hard requirements unmet (keeper-free recording, cardinality, query interface, registration/governance, dashboard);
- "privacy-preserving" DEX not possible on 0.2.4.
Either fix them or explicitly descope them for M1.
-
Docs: update the runbook and module README (D4, D5); add a local e2e script (this harness is a start:
harness/). -
Then deploy to
testnet-legacy.lez.logos.co(nothing is deployed there today).
6. Reproduce
The local environment is in /home/vpavlin/devel/m1-local:
- LEZ v0.2.4 build in
lez/; SPEL415b7bcinspel/; programs and binaries inlez-programs/target/guest/; - the sequencer state in
run/seq/; - the logoscore modules in
modules/.
Harness scripts:
harness/h.py: action + snapshot logger.attack1.py: manipulation, protocol-fee redirect, rounding, guards.attack2.py/attack3.py: spoofing, zero price, donation + sync, drain.stable.py/stable2.py: stablecoin.table.py: printsrun/timeline.txt.
Background processes still running: the sequencer (port 3040) and the logoscore daemon. Stop them with pkill -f sequencer_service and result-logoscore/bin/logoscore stop.