From 1bdbe8ba48aac12e49019de0864214f2f213869d Mon Sep 17 00:00:00 2001 From: moscowchill <72578879+moscowchill@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:41:19 +0200 Subject: [PATCH 1/2] fix(frontend): plain first-screen copy on the Stake page (#58) * fix(frontend): plain first-screen copy on the Stake page The Stake page led with a shield badge reading "No upgrade authority" and a card listing every admin role the contracts lack. That reads as defensive. Remove the badge and replace the card with a short "Before you stake" note: variable returns that can be negative, the withdrawal queue, and the operator's role in validator performance and execution-tip routing, with a link to How it works. The position small print keeps its facts in plainer words. Other pages are unchanged. * fix(frontend): keep the position-to-wallet binding on the Stake page The removed badge was the page's only note that a position is not transferable. Say it plainly in Before you stake: the position stays with the depositing wallet and payouts go to that wallet. --- frontend/src/pages/StakePage.tsx | 32 +++++++++++--------------------- 1 file changed, 11 insertions(+), 21 deletions(-) diff --git a/frontend/src/pages/StakePage.tsx b/frontend/src/pages/StakePage.tsx index 4d1f9de..c819191 100644 --- a/frontend/src/pages/StakePage.tsx +++ b/frontend/src/pages/StakePage.tsx @@ -1,7 +1,7 @@ import { useState } from "react"; import { observer } from "mobx-react-lite"; import { Link } from "react-router"; -import { ArrowDownToLine, ShieldCheck } from "lucide-react"; +import { ArrowDownToLine } from "lucide-react"; import { Button } from "@/components/UI/Button"; import { Card, @@ -76,10 +76,6 @@ export const StakePage = observer(() => { withdrawals are accounted for on chain, with native QRL returned to your wallet.

-

- Non-transferable positions ยท No - upgrade authority -

@@ -205,7 +201,7 @@ export const StakePage = observer(() => {

{pool?.recovering ? "Frozen checkpoint value and principal basis are historical references that remain unchanged after recovery payments. Your frozen position determines your portion of later returned cash." - : "Unreserved earnings and principal remain exposed to validator losses. A withdrawal request stays exposed until native cash is reserved. Principal basis is an accounting reference, not a guaranteed payout."} + : "Unreserved earnings and principal remain exposed to validator losses. A withdrawal request stays exposed until native cash is reserved. Principal basis is an accounting reference, and your payout can be lower than it."}

{
- - What the operator cannot change - + Before you stake - The native pool is designed so deployment fixes the rules that - control user funds. + Returns are variable and can be negative after validator penalties + or losses.

- There is no owner, upgrader, proxy admin, pauser, arbitrary fund - rescue, balance setter or mutable fee role. The operator cannot - replace the deployed pool logic, change the 10% fee or redirect - validator withdrawals away from the pool. -

-

- The operator still runs validator signing infrastructure, so - validator performance, penalties and execution-tip routing remain - operational trust assumptions.{" "} + Your position stays with the wallet you deposit from and cannot be + moved to another wallet. Payouts go to that wallet. Withdrawals + wait in a queue and can depend on validator exits. The operator + runs the validators, so their performance and execution-tip + routing affect returns.{" "} - See the full control and recovery model. + How the pool works

From bade19ff8d478191700d71f73fe5186b775d7f4b Mon Sep 17 00:00:00 2001 From: moscowchill <72578879+moscowchill@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:07:07 +0200 Subject: [PATCH 2/2] fix(pool): price admissions and reservations at the newest completed portfolio (#59) A superseded but still-fresh stage kept admitting deposits and reserving withdrawals at its older economics after a newer portfolio was verified. That moved part of a proven loss or reward between holders: in the 2026-10-20 review a withdrawer avoided 200 of a 520 QRL loss, and a newcomer captured 2,600 of income proven before its admission. Each admission or reservation batch now applies the newest completed portfolio first. The stage keeps its cutoff, FIFO order, batch bounds and phase; reserved claims, earned fees and pending refunds stay as they are. Repeated supersession cannot restart processing, and stale stages stay abortable. Tests on native bytecode: both review scenarios (the withdrawer receives 19,800; existing holders keep all income proven before the admission), freshness at ages 64 and 65, newer snapshots sharing an execution cutoff, renewal at the recovery deadline and recovery one slot later, and 65 admissions in bounded batches followed by FIFO withdrawals under repeated supersession. Gas: ordinary batches cost 5,571 more; a batch that refreshes costs about 75k to 94k more; pool runtime grows 278 bytes to 21,906. --- docs/architecture.md | 6 +- native/IMPLEMENTATION.md | 2 +- native/REVIEW.md | 47 ++- native/accounting-model.js | 40 ++- native/accounting-model.test.js | 132 +++++++++ native/contracts/NativeCheckpointExecutor.hyp | 2 +- native/contracts/NativeLedger.hyp | 30 +- native/contracts/NativeQrlPool.hyp | 3 + native/proofs/CHECKPOINT-EXECUTION.md | 2 +- native/proofs/README.md | 2 + native/proofs/gate_fixture_test.go | 63 ++++- native/proofs/make-adapter-plan.js | 9 +- native/proofs/make-stage-window-plan.js | 267 ++++++++++++++++++ native/proofs/run.js | 10 + native/testing/LedgerFixture.hyp | 1 + native/testing/README.md | 3 + native/testing/make-ledger-plan.js | 57 ++++ prototype/native/DECISIONS.md | 2 + 18 files changed, 639 insertions(+), 39 deletions(-) create mode 100644 native/proofs/make-stage-window-plan.js diff --git a/docs/architecture.md b/docs/architecture.md index 048876a..e5fe617 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -51,11 +51,13 @@ Multiplication uses native 512-bit intermediates. Admissions round internal unit ## Withdrawals and rewards -`requestWithdrawal(amount)` and `requestRewards(amount)` join the same global FIFO. The maximum integer requests the full available amount. Requests retain their stake exposure until a strictly later authenticated execution cutoff and successful cash reservation. A deposit made just before settlement cannot capture earlier rewards; a request made after a loss cannot use an earlier cutoff to avoid it. +`requestWithdrawal(amount)` and `requestRewards(amount)` join the same global FIFO. The maximum integer requests the full available amount. Requests retain their stake exposure until a strictly later authenticated execution cutoff and successful cash reservation. Admissions and reservations use the newest completed portfolio, including any rewards or losses proved while an earlier stage was still open. Anyone can stage a checkpoint, process bounded admissions and process the FIFO. A head request without enough free cash stays first. The keeper processes available cash before requesting further validator exits; public signed exits remain independently usable. Once reserved, principal and reward claims are fixed and fully cash-backed. `claim()` pays only the original beneficiary. A failing recipient does not block other reserved claims. No administrator can reorder or selectively compensate requests. Owners can cancel their own unprocessed requests and cash-backed pending deposits. -Staged work has its own authenticated freshness check. Anyone may abandon a stale stage while preserving completed admissions and reserved payouts, then continue from a new verified snapshot. A newer finality root cannot make an old pricing stage fresh again. +Before each admission or withdrawal batch, the ledger atomically applies the latest completed portfolio if its snapshot ID has advanced. `settleCheckpoint()` also permits this refresh during staging. Refreshing preserves the stage's original eligibility cutoff, frozen queue bounds, heads and phase. Requests at or after that cutoff wait for a later stage opened by another completed snapshot. Each batch still visits at most 32 entries. A newer beacon snapshot may share the applied execution cutoff; its snapshot ID must increase and its execution block must remain nondecreasing. Already completed admissions retain their units, and reserved user claims, earned fees and pending principal retain their balances. + +Repeated portfolio completion therefore refreshes the price without restarting admission work ahead of withdrawals. Refresh and processing share one transaction, so a newly completed snapshot cannot interleave between them. An illiquid FIFO head or an unrepresentable admission finishes its current phase through the existing bounded path, preserving cancellation and refund access when staging ends. Supersession alone does not permit a fresh-stage abort. Anyone may abandon a stage whose applied checkpoint has become stale or whose authority is unavailable, preserving completed work. A refresh still requires a fresh complete snapshot and healthy authority before the pool's existing recovery deadline. Successful application renews that deadline; portfolio completion alone leaves it unchanged. At deadline plus one slot, refresh fails and recovery remains available directly from staging. ## Operator fee diff --git a/native/IMPLEMENTATION.md b/native/IMPLEMENTATION.md index 9c33bc7..980ab99 100644 --- a/native/IMPLEMENTATION.md +++ b/native/IMPLEMENTATION.md @@ -50,7 +50,7 @@ The compiler places pool position, pending-deposit, request and historical-flow 3. Pool funding is counted once: native cash before transfer, explicit in-flight principal while unconsumed, then canonical validator balance after consumption. 4. Historical gross assets are normalized by recorded later external deposits and actual cash payouts. Returned principal and newly adopted preparation capital never enter the consensus fee base. 5. Aggregate unreserved position entitlements are bounded by risk assets. Cash reservations remove the corresponding units/value before payment; repeated claims cannot reuse an entitlement. -6. Deposits and withdrawal/reward requests require a strictly later cutoff. Queued users bear gains and losses until reservation; newcomers cannot buy earlier settled rewards. +6. Deposits and withdrawal/reward requests require a strictly later eligibility cutoff. Every admission and reservation batch atomically applies the newest completed portfolio while preserving its stage's cutoff, bounds and phase. Queued users bear the proved gains and losses until reservation; newcomers receive no income already proved before admission. 7. Earned operator fees are bounded by realized taxable gain and eligible net consensus income, after prior-loss recovery. No key can edit the fee or its recipient. 8. A normal final exit requires the priced snapshot to prove terminal zero validators and no pool funding in flight. Zero-value users retain late-return rights while validators remain outstanding. 9. Recovery freezes existing units, preserves already segregated reserves and pays cumulative available cash minus prior claims. Late cash remains claimable and earns no new fee. diff --git a/native/REVIEW.md b/native/REVIEW.md index c5940c7..6b6b15c 100644 --- a/native/REVIEW.md +++ b/native/REVIEW.md @@ -61,7 +61,7 @@ Relevant review categories include OWASP A01:2021 Broken Access Control and A04: ## Remaining verification gaps - The original frozen graph has now completed consumed top-up, real validator rewards, independent exit, authenticated terminal withdrawal, fee reservation and final user payouts with zero residue. [The implementation report](IMPLEMENTATION.md#real-network-milestones) records exact reconciliation and a resolved payout gas-estimation failure. A full funded validator lifecycle on the final hardened bytecode remains a separate pre-launch qualification; its native-VM regressions and actual liquid-principal recovery run do not imply that additional result. -- The integrated staging-race regression now executes completion of a newer portfolio while the old ledger stage remains open, rejects early overwrite, completes the old stage and consumes the new snapshot once. Final-user terminal checks still require the priced and latest portfolio to agree, so completion scheduling can defer the last exit. +- The integrated staging-race regression completes a newer portfolio while an older stage remains open, applies the new economics once, and preserves the original eligibility cutoff and phase. The pricing-window regressions below additionally change economic value and exercise automatic refresh before admission and reservation. - Cover multiple admissions, multiple registered validators, an external top-up and a native withdrawal across the same interval, including skipped slots and aborted portfolio generations. The current adapter plan primarily exercises one admitted validator. - Preserve bytecode-executed malformed-proof, wrong-recipient, wrong-index/domain, replay, stale-cutoff, reentrancy, zero-loss-cohort, fee-carry and cash-conservation checks as required release gates. - Measure complete occupied-header history proof cost and keeper completion latency at realistic pool/network scale. Per-call batch limits alone do not establish that the entire interval can finish within the freshness window. @@ -101,3 +101,48 @@ The lifetime cap bounds validator work; it does not establish an adequate produc The new timeout repairs the distinction between pool accounting health and global finality health. The fresh source deliberately winds down irreversibly when that accounting deadline passes. No operator can extend it through finality-only or portfolio-only work. Users must review the selected freshness/recovery windows, initial anchor, sampled-committee assumptions and supported fork before depositing. README and architecture correctly identify operator tip routing, initial configuration trust, sampled and potentially repeated committee keys, fixed-fork limitations, public early exits, preparation risk and indefinite native return timing. Keep the enforced lifetime cap, independent pool timeout and immutable enrollment role explicit in those documents. Available-cash-first exit scheduling is a keeper policy: public exit signatures permit independent early exits, and gate exit-work events require queued demand without proving a liquidity deficit. The implementation supplies no legal classification or regulatory clearance. + +## Superseded pricing window, 2026-10-20 + +**High, resolved in source:** A still-fresh stage previously admitted pending deposits and reserved withdrawals after a newer completed portfolio had proved changed economics. The stage used its older price with current free cash. The earlier staging-race regression permitted this coexistence and checked sequencing without changing economic value. + +`NativeLedger` now checks the latest completed portfolio ID before every bounded admission and reservation batch. It applies an advancing snapshot atomically before processing any entry. Permissionless `settleCheckpoint()` can also refresh an unfinished stage. `NativeQrlPool` supplies the authenticated latest ID through an internal hook. Snapshot IDs must increase, and execution cutoffs must remain nondecreasing; a newer beacon snapshot sharing the applied execution cutoff can therefore refresh successfully. There are no new public methods or storage fields. + +Refresh preserves the current phase, original eligibility cutoff, queue ends and heads. Already admitted units, fixed user claims, earned fees and pending principal remain intact through the economic update. The ordinary batch then performs only its authorized admissions or reservations. Entries at or after the original cutoff remain deferred until a later stage opened by another completed snapshot. The executor checks the current phase before calling either batch, including an existing withdrawal phase. + +The updated staging-race test explicitly refreshes the open stage and rejects duplicate application. The production-bytecode pricing plans reuse the review's synthetic economic histories and regenerate their native SSZ and account proofs: + +| Scenario | Allocation after the fix | +| --- | --- | +| 52,000 QRL cohort, 12,000 cash, 40,000 validator balance; a queued 20,000 QRL position; later return of 39,480 after a 520 loss | The remaining queue batch first applies the cutoff-128 loss. The withdrawer receives 19,800 QRL and bears 200 of the loss. The other 30,000 QRL holder retains 29,700 and the 2,000 QRL operator position retains 1,980, totaling 31,680. Fees remain zero. | +| 52,000 QRL cohort; pending newcomer supplies 52,000; cutoff 128 proves 5,200 income before admission | Existing positions become 55,000 and 2,200 QRL. The newcomer receives units worth 52,000 QRL less one base unit (`10^-18 QRL`) of admission rounding and captures zero proved income. Its subsequent full claim has the same amount and zero fee. | + +**Liveness:** Portfolio churn adds one refresh to the next batch, with no loop over intermediate snapshots. Cumulative portfolio counters reconcile skipped snapshots. A fresh-stage abort remains unavailable solely because a newer portfolio exists, preventing an added reset mechanism. Churn tests complete 65 admissions in batches of 32, 32 and 1, then two FIFO reward requests in single-entry batches while newer portfolios keep completing. Both explicit refresh and automatic refresh preserve the withdrawal phase. A blocked FIFO head ends staging under the existing rule; a complete loss or unrepresentable admission also releases staging while preserving refunds and late-return rights. Permissionless transaction inclusion, usable proofs and actual validator liquidity remain operating assumptions. + +The latest completed snapshot must still be within its freshness window. Tests accept age 64 and reject age 65 while global finality stays healthy; failed refresh leaves accounting and the pool deadline unchanged, and stale-stage abort permits the pending refund. Portfolio completion alone cannot extend the independent pool deadline. An atomic refresh at slot 4224 renews it to 8320; at slot 4225, the same unapplied portfolio cannot revive the pool, and recovery starts directly from the unfinished stage. Separate ledger-bytecode cases preserve and pay existing 90-unit user claims, 10-unit earned fees and 17-unit pending refunds through supersession, including a complete loss. + +**Measured gas:** The comparison uses the unchanged starting revision `49814cc03f7a757304f1e5cb3ffc7df2819b63af`, the pinned compiler, identical native runner settings and regenerated public fixtures. Values include intrinsic gas and precede refunds. The ordinary admission benchmark queues 65 deposits for one beneficiary; it demonstrates the per-batch change for that fixture, with the bound still fixed at 32. + +| Operation | Before | After | Change | +| --- | ---: | ---: | ---: | +| First 32-entry admission batch, no refresh | 579,616 | 585,187 | +5,571 | +| Second 32-entry admission batch, no refresh | 545,416 | 550,987 | +5,571 | +| Two-entry FIFO batch, no refresh | 139,671 | 145,242 | +5,571 | +| Loss-scenario reservation batch | 157,731 | 232,559 | +74,828, including automatic loss settlement | +| Income-scenario single admission | 141,822 | 235,554 | +93,732, including automatic income settlement | + +A 32-entry admission batch that also applies the superseding income snapshot uses 673,348 gas in the churn fixture. Refresh performs one existing economic settlement, including logarithmic historical-flow and funding lookups, then visits at most the requested 32 entries. The pool runtime grows from 21,628 to 21,906 bytes and remains below the 24,576-byte limit. The portfolio runtime and its existing headroom are unchanged. + +The ten focused pricing-window plans pass 950 native QRVM steps with 67 expected reverts. The original review scenarios also reproduce their old allocations against the unchanged starting bytecode. This is local native-bytecode qualification with synthetic finality authority and economic states. The earlier funded local-network graphs retain their separately documented bytecode and evidence. + +The complete gate passes 43 model tests, 32 tooling tests and 66,455 native QRVM steps, including 458 expected reverts. The VM total comprises 2,357 deterministic ledger steps, 62,164 randomized ledger steps, 1,779 portfolio/gate/adapter/recovery/capacity/executor steps and 155 finality steps. Go runner and proof-package tests also pass. Commands used `nice -n 10`, `GOMAXPROCS=2`, `GOFLAGS=-buildvcs=false` and Go package parallelism of two; the full gate additionally used a two-CPU affinity limit. + +| Gate | Exit code | +| --- | ---: | +| `npm ci` | 0 | +| `npm test` | 0 | +| `npm run test:model` | 0 | +| `npm run test:tooling` | 0 | +| Ten focused native pricing-window plans | 0 | +| Original review replay and paired gas comparison | 0 | +| `git diff --check` and added-text scan | 0 | diff --git a/native/accounting-model.js b/native/accounting-model.js index 069a76c..d518479 100644 --- a/native/accounting-model.js +++ b/native/accounting-model.js @@ -65,6 +65,9 @@ class NativeAccountingModel { this.eligibleConsensusRewardBudget = 0n; this.consensusLossCarry = 0n; this.lastCheckpoint = 0n; + this.lastCheckpointId = 0; + this.fixtureSequence = 0; + this.latestCheckpointFixture = null; this.stage = null; this.fixtureAuthorityStatus = 0; this.fixtureStagingFresh = true; @@ -275,16 +278,18 @@ class NativeAccountingModel { this.exemptReceived += amount; } - fixtureCheckpoint() { - return Object.freeze({ + fixtureCheckpoint({ executionBlock = this.block } = {}) { + this.latestCheckpointFixture = Object.freeze({ [FIXTURE]: true, - block: this.block, + id: ++this.fixtureSequence, + block: uint(executionBlock), cash: this.cash, validatorAssets: this.validatorAssets, inFlight: this.inFlight, consensusDelta: this.consensusDelta, exemptReceived: this.exemptReceived, }); + return this.latestCheckpointFixture; } freeCash() { @@ -292,12 +297,15 @@ class NativeAccountingModel { } settleCheckpoint(fixture) { - this._open(); + assert(!this.recovering && this.fixtureAuthorityStatus === 0, 'normal actions unavailable'); assert(fixture[FIXTURE] === true, 'verified fixture input required'); assert( - fixture.block > this.lastCheckpoint && fixture.block < this.block, + fixture.id > this.lastCheckpointId && + fixture.block >= this.lastCheckpoint && fixture.block < this.block, 'cutoff must be finalized, increasing and earlier than execution' ); + assert.equal(fixture, this.latestCheckpointFixture, 'latest completed fixture required'); + assert(this.fixtureStagingFresh, 'staged checkpoint stale'); const flow = this._flowAt(fixture.block); const gross = fixture.cash + @@ -348,7 +356,8 @@ class NativeAccountingModel { this.settledConsensus = fixture.consensusDelta; this.settledExempt = fixture.exemptReceived; this.lastCheckpoint = fixture.block; - this.stage = { + this.lastCheckpointId = fixture.id; + this.stage ??= { phase: 'deposits', cutoff: fixture.block, pendingEnd: this.pending.length, @@ -356,13 +365,19 @@ class NativeAccountingModel { }; } - activateDeposits(limit = 16) { - assert(this.stage?.phase === 'deposits', 'not admitting deposits'); + _refreshStagingCheckpoint() { + if (this.latestCheckpointFixture?.id > this.lastCheckpointId) + this.settleCheckpoint(this.latestCheckpointFixture); assert( this.fixtureAuthorityStatus === 0 && this.fixtureStagingFresh, 'staged checkpoint stale' ); - assert(Number.isSafeInteger(limit) && limit > 0, 'invalid batch bound'); + } + + activateDeposits(limit = 16) { + assert(this.stage?.phase === 'deposits', 'not admitting deposits'); + assert(Number.isSafeInteger(limit) && limit > 0 && limit <= 32, 'invalid batch bound'); + this._refreshStagingCheckpoint(); let processed = 0; while (processed < limit && this.pendingHead < this.stage.pendingEnd) { const item = this.pending[this.pendingHead]; @@ -419,11 +434,8 @@ class NativeAccountingModel { processQueue(limit = 16) { assert(this.stage?.phase === 'queue', 'not processing withdrawal queue'); - assert( - this.fixtureAuthorityStatus === 0 && this.fixtureStagingFresh, - 'staged checkpoint stale' - ); - assert(Number.isSafeInteger(limit) && limit > 0, 'invalid batch bound'); + assert(Number.isSafeInteger(limit) && limit > 0 && limit <= 32, 'invalid batch bound'); + this._refreshStagingCheckpoint(); let processed = 0; while (processed < limit && this.queueHead < this.stage.queueEnd) { const request = this.requests[this.queueHead]; diff --git a/native/accounting-model.test.js b/native/accounting-model.test.js index 6a5d2c0..9c3c95c 100644 --- a/native/accounting-model.test.js +++ b/native/accounting-model.test.js @@ -532,6 +532,138 @@ test('stale staged batches abort permissionlessly while preserving already admit model.audit(); }); +test('superseded withdrawal pricing allocates proven loss before reserving returned cash', () => { + const model = pool({ alice: 20_000n, bob: 30_000n, operator: 2_000n }); + model.fixtureFund(40_000n); + model.fixtureConsumeFunding(40_000n); + model.fixtureAllValidatorsTerminal = false; + model.requestWithdrawal('alice'); + model.advance(); + const older = model.fixtureCheckpoint(); + model.advance(); + model.settleCheckpoint(older); + model.activateDeposits(); + assert.equal(model.freeCash(), 12_000n); + model.fixtureConsensus(-520n); + model.fixtureReturnPrincipal(39_480n); + model.fixtureCheckpoint(); + model.advance(); + assert.equal(model.processQueue(1), 1); + assert.equal(model.claim('alice'), 19_800n); + assert.equal(model.riskAssets, 31_680n); + assert.equal(model.position('bob').value, 29_700n); + assert.equal(model.position('operator').value, 1_980n); + assert.equal(model.consensusLossCarry, 520n); + assert.equal(model.feeReserve, 0n); + model.audit(); +}); + +test('superseded admission pricing leaves all already-proven income with existing holders', () => { + const U = 10n ** 18n; + const model = pool({ alice: 50_000n * U, operator: 2_000n * U }); + model.deposit('bob', 52_000n * U); + model.advance(); + const older = model.fixtureCheckpoint(); + model.advance(); + model.settleCheckpoint(older); + model.fixtureConsensus(5_200n * U, { liquid: true }); + model.fixtureCheckpoint(); + model.advance(); + finish(model); + assert.equal(model.position('alice').value, 55_000n * U); + assert.equal(model.position('operator').value, 2_200n * U); + assert.equal(model.position('bob').value, 52_000n * U - 1n); + assert.equal(model.position('bob').rewards, 0n); + model.requestWithdrawal('bob'); + settle(model); + assert.equal(model.claim('bob'), 52_000n * U - 1n); + assert.equal(model.feeReserve, 0n); + model.audit(); +}); + +test('repeated repricing preserves bounded work, cutoff and FIFO phase', () => { + const model = pool({ alice: 1000n, bob: 1000n }); + for (let i = 0; i < 65; i++) model.deposit(`pending-${i}`, 10n); + model.requestWithdrawal('alice', 10n); + model.requestWithdrawal('bob', 10n); + model.advance(); + // This entry shares the original cutoff and waits for a later stage. + const deferred = model.deposit('deferred', 7n); + const older = model.fixtureCheckpoint(); + model.advance(); + model.settleCheckpoint(older); + const cutoff = model.stage.cutoff; + const pendingEnd = model.stage.pendingEnd; + for (const processed of [32, 32, 1]) { + model.fixtureCheckpoint(); + model.advance(); + assert.throws(() => model.activateDeposits(33), /batch bound/); + assert.equal(model.activateDeposits(32), processed); + assert.equal(model.stage.cutoff, cutoff); + assert.equal(model.stage.pendingEnd, pendingEnd); + assert.throws(() => model.abortStaging(), /remains fresh/); + } + assert.equal(model.stage.phase, 'queue'); + for (const id of ['alice', 'bob']) { + const newer = model.fixtureCheckpoint(); + model.advance(); + model.settleCheckpoint(newer); + assert.equal(model.stage.phase, 'queue'); + assert.equal(model.stage.cutoff, cutoff); + assert.equal(model.processQueue(1), 1); + assert.equal(model.claim(id), 10n); + } + assert.equal(model.stage, null); + assert.equal(model.user('deferred').pending, 7n); + model.cancelPending('deferred', deferred); + model.audit(); +}); + +test('repricing a complete loss finishes the stage and preserves pending refunds and late rights', () => { + const model = pool({ alice: 100n }); + model.fixtureFund(100n); + model.fixtureConsumeFunding(100n); + model.fixtureAllValidatorsTerminal = false; + model.deposit('bob', 10n); + model.requestWithdrawal('alice'); + model.advance(); + const older = model.fixtureCheckpoint(); + model.advance(); + model.settleCheckpoint(older); + model.fixtureConsensus(-100n); + model.fixtureCheckpoint(); + model.advance(); + assert.equal(model.activateDeposits(1), 0); + assert.equal(model.processQueue(1), 1); + assert.equal(model.stage, null); + assert.equal(model.user('alice').shares, 100n * SHARE_SCALE); + assert.equal(model.claimReserve, 0n); + model.cancelPending('bob', 1); + assert.equal(model.user('bob').paid, 10n); + model.audit(); +}); + +test('a newer completed snapshot at the same execution cutoff advances economic pricing', () => { + const model = pool({ alice: 1000n }); + model.fixtureFund(500n); + model.fixtureConsumeFunding(500n); + model.deposit('bob', 1000n); + model.advance(); + const older = model.fixtureCheckpoint(); + model.advance(); + model.settleCheckpoint(older); + model.fixtureConsensus(200n); + const newer = model.fixtureCheckpoint({ executionBlock: older.block }); + model.advance(); + finish(model); + assert.equal(model.lastCheckpoint, older.block); + assert.equal(model.lastCheckpointId, newer.id); + assert.equal(model.position('alice').value, 1200n); + assert.equal(model.position('bob').rewards, 0n); + assert.throws(() => model.settleCheckpoint(newer), /increasing/); + model.audit(); +}); + test('operator preparation adoption adds principal once and cannot subsidize losses or fees', () => { const model = pool({ alice: 38_000n }); model.fixtureAdmitCapital('operator', 2_000n); diff --git a/native/contracts/NativeCheckpointExecutor.hyp b/native/contracts/NativeCheckpointExecutor.hyp index 91b1966..c7dee2f 100644 --- a/native/contracts/NativeCheckpointExecutor.hyp +++ b/native/contracts/NativeCheckpointExecutor.hyp @@ -33,7 +33,7 @@ contract NativeCheckpointExecutor { if (finish) { portfolio.finalizeCheckpoint(); pool.settleCheckpoint(); - pool.activateDeposits(32); + if (pool.stage() == 1) pool.activateDeposits(32); if (pool.stage() == 2) pool.processQueue(32); } } diff --git a/native/contracts/NativeLedger.hyp b/native/contracts/NativeLedger.hyp index c520f8f..c2545b9 100644 --- a/native/contracts/NativeLedger.hyp +++ b/native/contracts/NativeLedger.hyp @@ -112,6 +112,7 @@ abstract contract NativeLedger { } function _authorityStatus() internal view virtual returns (uint8); + function _latestCheckpointId() internal view virtual returns (uint64); function _consumeCheckpoint() internal virtual returns (Checkpoint memory); function _allValidatorsTerminal() internal view virtual returns (bool); function _stagingCheckpointFresh(uint64 id) internal view virtual returns (bool); @@ -259,9 +260,13 @@ abstract contract NativeLedger { } function settleCheckpoint() external guarded { - _normalOpen(); + _settleCheckpoint(); + } + + function _settleCheckpoint() private { + require(!recovering && _authorityStatus() == 0, "normal actions unavailable"); Checkpoint memory point = _consumeCheckpoint(); - require(point.id > lastCheckpointId && point.executionBlock > lastCheckpointBlock && + require(point.id > lastCheckpointId && point.executionBlock >= lastCheckpointBlock && point.executionBlock < block.number, "checkpoint must advance"); FlowPoint memory flow = _flowAt(point.executionBlock); uint256 normalizedGross = point.grossAssetsAtCutoff + (cumulativeExternalDeposits - flow.externalDeposits) - @@ -302,16 +307,25 @@ abstract contract NativeLedger { _assertCashReserves(); lastCheckpointId = point.id; lastCheckpointBlock = point.executionBlock; - stageCutoff = point.executionBlock; - _pendingEnd = _pending.length; - _queueEnd = _requests.length; - stage = 1; + // A newer price preserves the current work set and phase. Repeated + // portfolio completion cannot restart admissions ahead of withdrawals. + if (stage == 0) { + stageCutoff = point.executionBlock; + _pendingEnd = _pending.length; + _queueEnd = _requests.length; + stage = 1; + } emit CheckpointSettled(point.id, point.executionBlock, riskAssets, exemptGain); } + function _refreshStagingCheckpoint() private { + if (_latestCheckpointId() > lastCheckpointId) _settleCheckpoint(); + require(_authorityStatus() == 0 && _stagingCheckpointFresh(lastCheckpointId), "staged checkpoint stale"); + } + function activateDeposits(uint256 limit) external guarded returns (uint256 processed) { require(stage == 1 && limit != 0 && limit <= MAX_BATCH, "invalid admission batch"); - require(_authorityStatus() == 0 && _stagingCheckpointFresh(lastCheckpointId), "staged checkpoint stale"); + _refreshStagingCheckpoint(); while (processed < limit && pendingHead < _pendingEnd) { PendingDeposit storage item = _pending[pendingHead]; if (item.requestedBlock >= stageCutoff) break; @@ -341,7 +355,7 @@ abstract contract NativeLedger { function processQueue(uint256 limit) external guarded returns (uint256 processed) { require(stage == 2 && limit != 0 && limit <= MAX_BATCH, "invalid withdrawal batch"); - require(_authorityStatus() == 0 && _stagingCheckpointFresh(lastCheckpointId), "staged checkpoint stale"); + _refreshStagingCheckpoint(); while (processed < limit && queueHead < _queueEnd) { WithdrawalRequest storage request = _requests[queueHead]; if (request.requestedBlock >= stageCutoff) break; diff --git a/native/contracts/NativeQrlPool.hyp b/native/contracts/NativeQrlPool.hyp index 4d68b22..acf9f6e 100644 --- a/native/contracts/NativeQrlPool.hyp +++ b/native/contracts/NativeQrlPool.hyp @@ -130,6 +130,9 @@ contract NativeQrlPool is NativeLedger { return finality.status(); } function _authorityStatus() internal view override returns (uint8) { return poolStatus(); } + function _latestCheckpointId() internal view override returns (uint64) { return portfolio.snapshotId(); } + // Timing eligibility also governs aborts. Batches atomically consume any + // newer completed portfolio before checking this applied checkpoint's age. function _stagingCheckpointFresh(uint64 id) internal view override returns (bool) { return id != 0 && id == lastCheckpointId && _slotFresh(appliedSlot) && poolStatus() == 0; } diff --git a/native/proofs/CHECKPOINT-EXECUTION.md b/native/proofs/CHECKPOINT-EXECUTION.md index fd07758..5d2f743 100644 --- a/native/proofs/CHECKPOINT-EXECUTION.md +++ b/native/proofs/CHECKPOINT-EXECUTION.md @@ -2,7 +2,7 @@ `NativeCheckpointExecutor` is an optional immutable mechanical caller bound to one portfolio and its pool. It accepts up to three typed groups of block witnesses. Each group still passes through the portfolio's existing four-block bound, canonical header ancestry, complete native withdrawal and deposit lists, and checkpoint freshness checks. It holds no QRL and exposes no authority, generic call, recipient change, accounting setter or upgrade. -The final group can atomically append its proofs, finalize the complete portfolio, settle the pool, activate at most 32 eligible deposits, and process at most 32 FIFO requests when the pool reaches that stage. If any step fails, the complete transaction reverts. Larger queues remain available through the existing bounded permissionless functions. A fresh checkpoint is still required; the helper cannot extend its age limit. +The final group can atomically append its proofs, finalize the complete portfolio, settle the pool, activate at most 32 eligible deposits, and process at most 32 FIFO requests when the pool reaches that stage. Settlement can refresh an unfinished stage while preserving its cutoff, bounds and phase. The helper checks the phase before each batch, including a stage already processing withdrawals. If any step fails, the complete transaction reverts. Larger queues remain available through the existing bounded permissionless functions. A fresh checkpoint is still required; the helper cannot extend its age limit. The initial local attempt authenticated all 552 occupied blocks but its separate finalization transaction arrived at age 66 against a 64-slot limit. No snapshot was committed and the 42,000 QRL of pending user deposits stayed reserved. The helper removes the final confirmation and submission gap. A later live checkpoint committed the complete 1,184-block interval and activated the pending 42,000 QRL in its final transaction at age 62; measured costs and capacity limits are in `SCALE.md`. Three ordinary four-block groups measured 106,564 calldata bytes and approximately 4.60 million gas in the pinned QRVM; the final group with completion used approximately 4.70 million gas with the isolated staging fixture. Deposits and withdrawals can increase encoded block size, so callers must enforce the native signed-transaction and gas limits when choosing groups. diff --git a/native/proofs/README.md b/native/proofs/README.md index 83473ec..01ecbf1 100644 --- a/native/proofs/README.md +++ b/native/proofs/README.md @@ -8,6 +8,8 @@ The current candidate also restricts preparation to the immutable validator oper Five additional plans execute the real pool's independent accounting timeout: no first settlement; successful renewal exactly at the deadline; newer complete portfolio work without pool application; expiry during ledger staging; and preservation of pending refunds, reserved user claims, earned fees and late recovery cash. Fixture finality remains healthy in these tests. The current gate rejects preparation after pool timeout, and expired pool settlement cannot revive normal operation. These are VM regressions with explicit synthetic native state and timing; actual network timeout evidence is recorded separately. +The pricing-window plans reuse the reviewed loss and income histories with regenerated native proofs. They verify automatic repricing, explicit refresh during staging, the executor's existing-withdrawal-phase path, 65 admissions across bounded batches despite repeated newer portfolios, FIFO progress, original-cutoff deferral, a newer snapshot sharing the execution cutoff, freshness at age 64 and rejection at age 65, and recovery at the exact deadline and one slot later. The loss history reserves 19,800 QRL for the withdrawing holder and leaves 31,680 QRL for the others. The income history retains all 5,200 QRL of already-proved income for the existing cohort; the newcomer receives its 52,000 QRL principal less one base unit of admission rounding, with zero fee. + The Go module pins Qrysm `3b816311ac3e86b7a7af40a062ae290318554f7a` and go-qrl `9b404c38a63bfebe07cfd07b5f5d144d1c2cf9b9`. The contract compiler pin and binary hash come from `config/hyperion-toolchain.json`; the runner enforces them before compiling. Generated fixtures, plans and reports are under ignored `findings/native-proof-tests/`. The portfolio binds the immutable finality verifier, pool and validator gate. The gate is its only registration caller. Admission requires a full canonical public key, pool withdrawal recipient, exact 2,000 QRL balance and effective balance, and an unslashed validator without activation or exit. The gate records the original bootstrap payer, publishes an epoch-zero signed exit, and forwards exactly 38,000 QRL from the pool to the pinned deposit contract. Failed proof, signature, pool release or native deposit execution reverts the entire admission. The pool chooses when its liquidity and withdrawal queue permit funding. diff --git a/native/proofs/gate_fixture_test.go b/native/proofs/gate_fixture_test.go index c18ab15..0ba3f2d 100644 --- a/native/proofs/gate_fixture_test.go +++ b/native/proofs/gate_fixture_test.go @@ -26,6 +26,25 @@ import ( ) func TestGatePublicFixture(t *testing.T) { + testGateFixture(t, "", os.Getenv("QUANTAPOOL_GATE_FIXTURE")) +} + +// The pricing-window histories reuse the adapter's native proof construction. +// All economic states and finality authority remain explicit synthetic inputs. +func TestStageWindowFixtures(t *testing.T) { + for _, mode := range []string{"loss", "reward", "churn", "same-cutoff"} { + t.Run(mode, func(t *testing.T) { + output := "" + if directory := os.Getenv("QUANTAPOOL_STAGE_WINDOW_FIXTURES"); directory != "" { + output = filepath.Join(directory, "stage-"+mode+"-fixture.json") + } + testGateFixture(t, mode, output) + }) + } +} + +func testGateFixture(t *testing.T, mode, output string) { + t.Helper() origin := common.BytesToAddress(bytes.Repeat([]byte{0x11}, 64)) pool := crypto.CreateAddress(origin, 4) gate := crypto.CreateAddress(origin, 3) @@ -90,14 +109,35 @@ func TestGatePublicFixture(t *testing.T) { // deliberately matched to actual QRVM cash transfers in that plan. parent := initialRoot points := []any{} - for _, point := range []struct { + type economicPoint struct { slot, cash, balance, cursor uint64 included *pb.Deposit_Data - }{ + } + history := []economicPoint{ {80, 50000, 2000, 1, bootstrap}, {96, 12000, 2000, 1, nil}, {112, 12000, 40000, 2, topup}, {128, 13000, 42000, 3, bootstrap}, {144, 14000, 42000, 3, nil}, {4224, 14000, 42000, 3, nil}, - } { + } + withdrawalSlot, withdrawalAmount := uint64(144), uint64(1000) + if mode != "" { + entryCash, windowCash, windowBalance := uint64(12000), uint64(51480), uint64(0) + withdrawalSlot, withdrawalAmount = 128, 39480 + if mode != "loss" { + entryCash, windowCash, windowBalance = 64000, 64000, 45200 + withdrawalSlot = 0 + } + history[2] = economicPoint{112, entryCash, 40000, 2, topup} + history[3] = economicPoint{128, windowCash, windowBalance, 2, nil} + history[4] = economicPoint{144, windowCash, windowBalance, 2, nil} + history[5] = economicPoint{4224, windowCash, windowBalance, 2, nil} + if mode == "churn" { + history = history[:5] + for _, slot := range []uint64{160, 176, 192} { + history = append(history, economicPoint{slot, windowCash, windowBalance, 2, nil}) + } + } + } + for _, point := range history { amount := new(big.Int).Mul(new(big.Int).SetUint64(point.cash), big.NewInt(1000000000000000000)) a, err := rlp.EncodeToBytes(&types.StateAccount{Nonce: 1, Balance: amount, Root: types.EmptyRootHash, CodeHash: types.EmptyCodeHash.Bytes()}) Must(err) @@ -105,6 +145,9 @@ func TestGatePublicFixture(t *testing.T) { Must(err) h.StateRoot = crypto.Keccak256(n) h.BlockNumber = point.slot + if mode == "same-cutoff" && point.slot == 144 { + h.BlockNumber = 128 + } wrapped, err := consensus.WrappedExecutionPayloadHeaderZond(h, 0) Must(err) Must(s.SetLatestExecutionPayloadHeader(wrapped)) @@ -120,8 +163,8 @@ func TestGatePublicFixture(t *testing.T) { block.Slot = primitives.Slot(point.slot) block.ParentRoot = parent block.StateRoot = common.FromHex(state.StateRoot) - if point.slot == 144 { - block.Body.ExecutionPayload.Withdrawals = []*engine.Withdrawal{{Index: 0, ValidatorIndex: 0, Address: pool.Bytes(), Amount: 1000 * 1000000000}} + if point.slot == withdrawalSlot { + block.Body.ExecutionPayload.Withdrawals = []*engine.Withdrawal{{Index: 0, ValidatorIndex: 0, Address: pool.Bytes(), Amount: withdrawalAmount * 1000000000}} } if point.included != nil { proof := make([][]byte, 33) @@ -135,11 +178,13 @@ func TestGatePublicFixture(t *testing.T) { } // A fresh checkpoint at the pool's initial applied deadline spans both // explicit occupied blocks since slot 128; the intervening slots are empty. - late := points[len(points)-1].(map[string]any) - prior := points[len(points)-2].(map[string]any) - late["blocks"] = append(late["blocks"].([]BlockWitness), prior["blocks"].([]BlockWitness)...) + if mode != "churn" { + late := points[len(points)-1].(map[string]any) + prior := points[len(points)-2].(map[string]any) + late["blocks"] = append(late["blocks"].([]BlockWitness), prior["blocks"].([]BlockWitness)...) + } out["productionPoints"] = points - if output := os.Getenv("QUANTAPOOL_GATE_FIXTURE"); output != "" { + if output != "" { raw, err := json.MarshalIndent(out, "", " ") Must(err) Must(os.WriteFile(output, append(raw, '\n'), 0644)) diff --git a/native/proofs/make-adapter-plan.js b/native/proofs/make-adapter-plan.js index 6935f5a..e0130b8 100644 --- a/native/proofs/make-adapter-plan.js +++ b/native/proofs/make-adapter-plan.js @@ -40,6 +40,7 @@ function build(fixture, output, { stageRace = true } = {}) { call(`prove complete interval ${slot}`, '@portfolio', 'appendBlocks', [point.blocks]); call(`commit complete portfolio ${slot}`, '@portfolio', 'finalizeCheckpoint'); } + if (alreadyCommitted) return; call(`real pool settles matched portfolio ${slot}`, '@pool', 'settleCheckpoint'); if (stageRace && point === inFlight) { steps.push({ name: 'new finality arrives during older ledger staging', op: 'time', time: 1000 + Number(consumed.state.slot) * 3 }); @@ -52,7 +53,11 @@ function build(fixture, output, { stageRace = true } = {}) { call('portfolio advanced to third checkpoint', '@portfolio', 'snapshotId', [], { want: ['3'] }); call('old ledger remains explicitly bound to second checkpoint', '@pool', 'lastCheckpointId', [], { want: ['2'] }); call('old ledger keeps its original applied slot', '@pool', 'appliedSlot', [], { want: ['96'] }); - reject('new snapshot cannot overwrite unfinished ledger staging', '@pool', 'settleCheckpoint'); + call('new snapshot reprices unfinished ledger staging', '@pool', 'settleCheckpoint'); + call('repricing preserves admission phase', '@pool', 'stage', [], { want: ['1'] }); + call('repricing preserves original eligibility cutoff', '@pool', 'stageCutoff', [], { want: ['96'] }); + call('newer economics applied before remaining work', '@pool', 'appliedSlot', [], { want: ['112'] }); + reject('same snapshot cannot reprice twice during staging', '@pool', 'settleCheckpoint'); precommitted = true; } call(`real pool activates eligible deposits ${slot}`, '@pool', 'activateDeposits', ['4']); @@ -74,7 +79,7 @@ function build(fixture, output, { stageRace = true } = {}) { call('operator bootstrap admission produces no fee entitlement', '@pool', 'eligibleConsensusRewardBudget', [], { want: ['0'] }); settle(consumed, true); if (stageRace) { - call('newer snapshot consumed exactly once after old stage closes', '@pool', 'lastCheckpointId', [], { want: ['3'] }); + call('newer snapshot consumed exactly once while preserving staged work', '@pool', 'lastCheckpointId', [], { want: ['3'] }); reject('same newer snapshot cannot settle twice', '@pool', 'settleCheckpoint'); } call('consumed funding leaves aggregate principal unchanged', '@pool', 'riskAssets', [], { want: [base(52000)] }); diff --git a/native/proofs/make-stage-window-plan.js b/native/proofs/make-stage-window-plan.js new file mode 100644 index 0000000..da05de9 --- /dev/null +++ b/native/proofs/make-stage-window-plan.js @@ -0,0 +1,267 @@ +'use strict'; + +// Reuse the reviewed pricing-window histories with production pool, gate, +// portfolio, SSZ and account-proof bytecode. Finality and states are synthetic. +const path = require('node:path'); +const { build: adapter } = require('./make-adapter-plan'); +const { cash, witness } = require('./make-plan'); +const U = 10n ** 18n; +const S = 10n ** 27n; +const base = n => String(BigInt(n) * U); +const max = String((1n << 256n) - 1n); +const user = `Q${'22'.repeat(64)}`; +const newcomer = `Q${'33'.repeat(64)}`; +const otherHolder = `Q${'55'.repeat(64)}`; + +function build(fixture, output, mode) { + const loss = mode.startsWith('loss'); + const churn = mode === 'churn'; + const executor = mode === 'loss-executor'; + const plan = adapter(fixture, output, { stageRace: false }); + const end = plan.steps.findIndex(s => s.name === 'real pool activates eligible deposits 112'); + if (end < 0) throw new Error('Adapter admission boundary changed'); + plan.steps = plan.steps.slice(0, end); + if (loss) { + const at = plan.steps.findIndex(s => s.name === 'real user deposits native QRL before cutoff'); + plan.steps[at].value = base(20000); + plan.steps.splice(at + 1, 0, { + name: 'second holder supplies remaining 30k before initial cutoff', + op: 'call', target: '@pool', method: 'deposit', args: [], + from: otherHolder, value: base(30000), want: ['1'], + }); + plan.accounts[otherHolder] = base(1000000); + for (const step of plan.steps) + if (step.method === 'positionValue' && step.args[0] === user && step.want) + step.want = [base(20000)]; + } + plan.accounts[newcomer] = base(1000000); + const before = plan.steps.findIndex(s => s.name === 'advance synthetic time to finalized slot 112'); + const queued = loss + ? [{ name: 'holder queues full 20k position before cutoff 112', op: 'call', target: '@pool', + method: 'requestWithdrawal', args: [max], from: user, want: ['0'] }] + : Array.from({ length: churn ? 65 : 1 }, (_, i) => ({ + name: `newcomer queues pending principal ${i} before cutoff 112`, op: 'call', + target: '@pool', method: 'deposit', args: [], from: newcomer, + value: base(churn ? 800 : 52000), want: [String(i + 1)], + })); + if (churn) { + queued.push(...[user, fixture.origin].map((from, i) => ({ + name: `holder queues bounded reward withdrawal ${i}`, op: 'call', target: '@pool', + method: 'requestRewards', args: [base(100)], from, want: [String(i)], + }))); + } + if (mode === 'reward-cutoff') { + queued.unshift({ name: 'requests land exactly at original cutoff', op: 'block', value: '112' }); + queued.push({ name: 'operator reward request lands exactly at cutoff', op: 'call', + target: '@pool', method: 'requestRewards', args: [base(100)], want: ['0'] }); + // The clock operation also advances the runner's execution block. + plan.steps.find(s => s.name === 'live execution block after cutoff 112').value = '114'; + } + plan.steps.splice(before, 0, ...queued); + if (executor) { + const at = plan.steps.findIndex(s => s.id === 'pool'); + plan.steps.splice(at + 1, 0, { + name: 'deploy executor for superseded withdrawal phase', op: 'deploy', id: 'executor', + artifact: path.relative(path.dirname(output), + path.resolve(__dirname, '../../build/native-stage-window/NativeCheckpointExecutor')), + args: ['@portfolio', '@pool'], + }); + } + const call = (name, target, method, args = [], extra = {}) => + plan.steps.push({ name, op: 'call', target, method, args, ...extra }); + const pool = (name, method, args = [], extra = {}) => call(name, '@pool', method, args, extra); + const read = (method, want, args = []) => + pool(`${mode}: ${method} equals ${want.join(', ')}`, method, args, { want }); + const reject = (method, args = [], reason = '*') => + pool(`${mode}: reject ${method}`, method, args, { revert: reason }); + function time(slot) { + plan.steps.push({ name: `synthetic clock advances to ${slot}`, op: 'time', time: 1000 + slot * 3 }); + } + function commit(point, atomic = false) { + const slot = Number(point.state.slot); + time(slot); + if (loss && slot === 128) { + plan.steps.push({ name: 'execution block containing native exit receipt', op: 'block', value: '128' }); + plan.steps.push({ name: 'synthetic exit credit after 520 QRL validator loss', + op: 'withdrawal-credit', target: '@pool', value: base(39480) }); + } + plan.steps.push({ name: `execution block after ${slot}`, op: 'block', value: String(slot + 1) }); + call('synthetic authority supplies newer complete economics', '@anchor', 'set', + [point.state.slot, point.state.stateRoot, point.headerRoot]); + call('begin matched cash and state proof', '@portfolio', 'beginCheckpoint', + [cash(point.state, point.accountProof)]); + call('authenticate entire registered portfolio', '@portfolio', 'appendValidators', + [[witness(point.state.validators[0])]]); + call('authenticate complete parent-linked cash-flow interval', '@portfolio', 'appendBlocks', [point.blocks]); + if (atomic) + call('executor reprices and processes the existing withdrawal phase', + '@executor', 'appendAndSettle', [[], true]); + else call('commit newer portfolio before staged processing', '@portfolio', 'finalizeCheckpoint'); + } + if (loss) { + pool('advance old stage to withdrawals', 'activateDeposits', ['32']); + read('freeCash', [base(12000)]); + read('claimable', ['0'], [user]); + } + commit(fixture.productionPoints[3], executor); + call('newer complete economics are public', '@portfolio', 'snapshotId', [], { want: ['4'] }); + if (!executor) { + read('lastCheckpointId', ['3']); + read('appliedSlot', ['112']); + read('poolRecoveryDeadlineSlot', ['4208']); + // Supersession cannot reset bounded progress through a fresh-stage abort. + reject('abortStaging', [], 'staging remains fresh'); + } + if (mode === 'reward-stale' || mode === 'reward-fresh-boundary') { + const slot = mode === 'reward-stale' ? 193 : 192; + time(slot); + call('global finality stays healthy while snapshot ages', '@anchor', 'set', + [String(slot), fixture.productionPoints[3].state.stateRoot, fixture.productionPoints[3].headerRoot]); + if (mode === 'reward-stale') { + reject('activateDeposits', ['32'], 'portfolio stale'); + reject('settleCheckpoint', [], 'portfolio stale'); + read('lastCheckpointId', ['3']); + read('pendingTotal', [base(52000)]); + read('poolRecoveryDeadlineSlot', ['4208']); + pool('stale superseded stage remains abortable', 'abortStaging'); + pool('owner refunds unchanged pending principal', 'cancelPending', ['1'], { from: newcomer }); + read('pendingTotal', ['0']); + return plan; + } + } + if (churn) { + reject('activateDeposits', ['33'], 'invalid admission batch'); + read('lastCheckpointId', ['3']); + for (const [index, count, head] of [[3, 32, 33], [4, 32, 65], [5, 1, 66]]) { + if (index > 3) commit(fixture.productionPoints[index]); + pool('bounded admission progresses despite portfolio churn', 'activateDeposits', + ['32'], { want: [String(count)] }); + read('pendingHead', [String(head)]); + read('stageCutoff', ['112']); + read('lastCheckpointId', [String(index + 1)]); + read('stage', [index === 5 ? '2' : '1']); + reject('settleCheckpoint', [], 'checkpoint must advance'); + } + for (const index of [6, 7]) { + commit(fixture.productionPoints[index]); + reject('processQueue', ['33'], 'invalid withdrawal batch'); + // Explicit repricing also preserves the withdrawal phase. + if (index === 6) pool('keeper explicitly refreshes withdrawal economics', 'settleCheckpoint'); + read('stage', ['2']); + pool('FIFO progresses despite another newer portfolio', 'processQueue', ['1'], { want: ['1'] }); + read('queueHead', [String(index - 5)]); + read('stageCutoff', ['112']); + read('lastCheckpointId', [String(index + 1)]); + } + read('stage', ['0']); + read('pendingTotal', ['0']); + read('claimReserve', [base(180)]); + read('feeReserve', [base(20)]); + read('riskAssets', [base(109000)]); + return plan; + } + if (!loss) pool('admit only original eligible entries after atomic repricing', + 'activateDeposits', ['32'], { want: [mode === 'reward-cutoff' ? '0' : '1'] }); + if (mode === 'reward-same-cutoff') { + commit(fixture.productionPoints[4]); + pool('newer slot at the same execution cutoff refreshes and completes', 'processQueue', + ['32'], { want: ['0'] }); + read('lastCheckpointId', ['5']); + read('lastCheckpointBlock', ['128']); + read('appliedSlot', ['144']); + read('stageCutoff', ['112']); + read('stage', ['0']); + read('rewardValue', ['0'], [newcomer]); + reject('settleCheckpoint', [], 'checkpoint must advance'); + return plan; + } + if (mode === 'reward-cutoff') { + pool('request at original cutoff still waits after repricing', 'processQueue', ['32'], { want: ['0'] }); + read('pendingTotal', [base(52000)]); + read('queueHead', ['0']); + read('claimReserve', ['0']); + read('stageCutoff', ['112']); + read('lastCheckpointId', ['4']); + commit(fixture.productionPoints[4]); + pool('next stage uses its own later eligibility cutoff', 'settleCheckpoint'); + read('stageCutoff', ['144']); + pool('deferred deposit remains at the newer economic price', 'activateDeposits', ['32'], { want: ['1'] }); + pool('deferred reward request now reserves in FIFO order', 'processQueue', ['32'], { want: ['1'] }); + read('claimable', [base(90)], [fixture.origin]); + read('feeReserve', [base(10)]); + read('rewardValue', ['0'], [newcomer]); + read('pendingTotal', ['0']); + read('queueHead', ['1']); + return plan; + } + if (mode === 'reward-recovery-boundary' || mode === 'reward-recovery-expired') { + read('stage', ['2']); + read('poolRecoveryDeadlineSlot', ['4224']); + commit(fixture.productionPoints[4]); + read('poolRecoveryDeadlineSlot', ['4224']); + const boundary = fixture.productionPoints[5]; + commit({ ...boundary, blocks: boundary.blocks.slice(0, 1) }); + read('poolRecoveryDeadlineSlot', ['4224']); + read('poolStatus', ['0']); + if (mode === 'reward-recovery-expired') { + time(4225); + read('poolStatus', ['2']); + reject('processQueue', ['32'], 'normal actions unavailable'); + reject('settleCheckpoint', [], 'normal actions unavailable'); + read('lastCheckpointId', ['4']); + pool('recovery is available directly from the superseded stage', 'beginRecovery', [], { from: newcomer }); + read('stage', ['0']); + read('recovering', [true]); + read('feeReserve', ['0']); + reject('activateDeposits', ['32']); + return plan; + } + pool('exact deadline refresh and queue completion are atomic', 'processQueue', ['32'], { want: ['0'] }); + read('poolRecoveryDeadlineSlot', ['8320']); + read('lastCheckpointId', ['6']); + read('stage', ['0']); + return plan; + } + if (!executor) pool('remaining queue uses newest completed economics', 'processQueue', ['32']); + read('lastCheckpointId', ['4']); + read('stageCutoff', ['112']); + read('stage', ['0']); + reject('settleCheckpoint', [], 'checkpoint must advance'); + if (loss) { + read('riskAssets', [base(31680)]); + read('claimable', [base(19800)], [user]); + read('positionValue', [base(29700)], [otherHolder]); + read('positionValue', [base(1980)], [fixture.origin]); + read('feeReserve', ['0']); + pool('withdrawer bears exactly 200 QRL of proven loss', 'claim', [], + { from: user, want: [base(19800)] }); + pool('reserved claim pays once', 'claim', [], { from: user, revert: '*' }); + plan.steps.push({ name: 'remaining cash belongs to remaining holders', + op: 'balance', target: '@pool', value: base(31680) }); + } else { + const oldShares = 52000n * U * S; + const newShares = 52000n * U * oldShares / (57200n * U); + const value = 109200n * U * newShares / (oldShares + newShares); + read('positionValue', [String(value)], [newcomer]); + read('rewardValue', ['0'], [newcomer]); + read('positionValue', [base(55000)], [user]); + read('positionValue', [base(2200)], [fixture.origin]); + read('eligibleConsensusRewardBudget', [base(5200)]); + // The boundary-only case has deliberately advanced beyond slot 144. + if (mode === 'reward-fresh-boundary') return plan; + pool('newcomer requests its admitted principal', 'requestWithdrawal', [max], { from: newcomer }); + commit(fixture.productionPoints[4]); + pool('apply next cutoff after newcomer request', 'settleCheckpoint'); + pool('complete admission phase', 'activateDeposits', ['32']); + pool('reserve newcomer at the unchanged price', 'processQueue', ['32']); + read('claimable', [String(value)], [newcomer]); + read('feeReserve', ['0']); + pool('newcomer receives its principal with admission rounding', 'claim', [], + { from: newcomer, want: [String(value)] }); + plan.steps.push({ name: 'newcomer captures zero pre-admission income', op: 'balance', + target: newcomer, value: String(1000000n * U - 52000n * U + value) }); + } + return plan; +} + +module.exports = { build }; diff --git a/native/proofs/run.js b/native/proofs/run.js index cbec413..bb1bd05 100644 --- a/native/proofs/run.js +++ b/native/proofs/run.js @@ -8,6 +8,7 @@ const { build: gatePlan } = require('./make-gate-plan'); const { build: adapterPlan } = require('./make-adapter-plan'); const { build: recoveryPlan } = require('./make-recovery-plan'); const { build: capacityPlan } = require('./make-capacity-plan'); +const { build: stageWindowPlan } = require('./make-stage-window-plan'); const repo = path.resolve(__dirname, '../..'); const output = path.join(repo, 'findings/native-proof-tests'); @@ -21,6 +22,10 @@ execFileSync(compiler, ['--abi', '--bin', '--bin-runtime', '--optimize', '--opti '--base-path', __dirname, '--output-dir', artifacts, '--overwrite', path.join(__dirname, 'FixtureFinality.hyp'), path.join(__dirname, 'GatePoolFixture.hyp'), path.join(__dirname, 'GateCapacityFixture.hyp')], { stdio: 'inherit' }); +execFileSync(compiler, ['--abi', '--bin', '--optimize', '--optimize-runs=1', '--via-ir', + '--base-path', path.join(repo, 'native/contracts'), '--allow-paths', repo, + '--output-dir', path.join(repo, 'build/native-stage-window'), '--overwrite', + path.join(repo, 'native/contracts/NativeCheckpointExecutor.hyp')], { stdio: 'inherit' }); const environment = { ...process.env, GOWORK: 'off', GOMAXPROCS: '2' }; execFileSync('go', ['build', '-mod=readonly', '-p=2', '-o', path.join(artifacts, 'execution'), '.'], { cwd: path.join(repo, 'native/testing/execution'), env: environment, stdio: 'inherit' }); @@ -28,6 +33,7 @@ execFileSync('go', ['test', '-mod=readonly', '-p=2', '-count=1', './...'], { cwd: __dirname, env: { ...environment, QUANTAPOOL_PORTFOLIO_FIXTURE: path.join(output, 'portfolio-fixtures.json'), QUANTAPOOL_GATE_FIXTURE: path.join(output, 'gate-fixture.json'), + QUANTAPOOL_STAGE_WINDOW_FIXTURES: output, QUANTAPOOL_CAPACITY_FIXTURE: path.join(output, 'capacity-fixture.json'), QUANTAPOOL_NATIVE_DEPOSIT_ARTIFACT: artifacts }, stdio: 'inherit' }); @@ -36,6 +42,10 @@ for (const [name, fixtureName, build] of [['portfolio', 'portfolio-fixtures', po ['gate', 'gate-fixture', gatePlan], ['adapter', 'gate-fixture', adapterPlan], ['capacity-registry', 'capacity-fixture', capacityPlan], ['capacity-gate', 'gate-fixture', (fixture, destination) => capacityPlan(fixture, destination, 'gate')], + ...['loss', 'loss-executor', 'reward', 'churn', 'reward-cutoff', 'reward-same-cutoff', 'reward-fresh-boundary', 'reward-stale', + 'reward-recovery-boundary', 'reward-recovery-expired'].map(mode => + [`stage-${mode}`, `stage-${mode === 'reward-same-cutoff' ? 'same-cutoff' : mode.split('-')[0]}-fixture`, + (fixture, destination) => stageWindowPlan(fixture, destination, mode)]), ...['initial', 'boundary', 'portfolio-only', 'staged', 'claims'].map(mode => [`recovery-${mode}`, 'gate-fixture', (fixture, destination) => recoveryPlan(fixture, destination, mode)])]) { const planPath = path.join(output, `${name}-plan.json`); diff --git a/native/testing/LedgerFixture.hyp b/native/testing/LedgerFixture.hyp index f8ba6cc..8744226 100644 --- a/native/testing/LedgerFixture.hyp +++ b/native/testing/LedgerFixture.hyp @@ -17,6 +17,7 @@ contract LedgerFixture is NativeLedger { function setFresh(bool value) external { fixtureFresh = value; } function setTerminal(bool value) external { fixtureTerminal = value; } function _authorityStatus() internal view override returns (uint8) { return fixtureStatus; } + function _latestCheckpointId() internal view override returns (uint64) { return selected.id; } function _consumeCheckpoint() internal view override returns (Checkpoint memory) { return selected; } function _allValidatorsTerminal() internal view override returns (bool) { return fixtureTerminal; } function _stagingCheckpointFresh(uint64) internal view override returns (bool) { return fixtureFresh; } diff --git a/native/testing/README.md b/native/testing/README.md index 14aa20f..ab28b7f 100644 --- a/native/testing/README.md +++ b/native/testing/README.md @@ -24,12 +24,15 @@ The plans cover: - A zero-rounded FIFO head in a pool with positive assets and available cash, followed by a paid user withdrawal and later recovery of the preserved residual position. - A 40,000-unit multi-user pool with validator funding, rewards, losses, partial validator returns, and a complete terminal drain. - A historical execution cutoff normalized for a later deposit and an already paid claim. +- Superseded pricing that preserves reserved user claims, earned fees and pending refunds, including a complete loss that finishes staging while retaining late-return rights. - A recipient which rejects payment, proving claim state and cash rollback, followed by a successful payment whose reentrant claim is rejected. Each differential scenario independently computes expected user positions, fee basis including fractional carry, claims, global reserves, reward budget, loss carry, and physical cash through the BigInt specification. Assertions are encoded as expected native ABI values and checked against actual return bytes. Expected failures must return the QRVM execution-reverted error; out-of-gas errors and other faults fail the test. The runner accounts for intrinsic gas and the 20-million gas ceiling, finalizes state after each action, and does not deduct fictitious transaction fees from the component cash ledger. The independent model also runs 100 seeded histories with 20,000 economic actions and conservation checks after every action. It covers 200 zero-consensus rounding cycles, exact 512-bit multiplication, same-block cutoff rules, proportional losses, fee carry, full validator loss, terminal gating, and ownerless dust. User enumeration occurs only in this reference model's assertions. Contract operations use constant-cost position accounting, binary-searched flow history, and bounded admission and withdrawal batches. +The pricing-window model regressions reproduce the 52,000 QRL cohort with a 520 QRL loss and the separate 5,200 QRL income case. Additional cases cover repeated portfolio supersession, frozen eligibility, the 32-entry bound, preserved withdrawal phase, complete loss and a newer snapshot sharing an execution cutoff. Production pool/proof bytecode versions of these histories run through `native/proofs/make-stage-window-plan.js`. + A zero-valued position retains its shares while any owned validator remains nonterminal. Its zero-payout request completes so later FIFO entries can use available cash; its position, fee basis and fee carry remain intact. The beneficiary can request again after its value changes. Once every validator is authenticated terminal, normal exits can retire the position. Expiry recovery freezes the existing shares and allocates later cash proportionally. Rounding in recovery can leave less than one smallest native unit per participant; unowned cash remains quarantined and has no operator withdrawal path. ## Bounded randomized native execution diff --git a/native/testing/make-ledger-plan.js b/native/testing/make-ledger-plan.js index 90b2f23..ddf92c6 100644 --- a/native/testing/make-ledger-plan.js +++ b/native/testing/make-ledger-plan.js @@ -411,6 +411,61 @@ function makePlan(kind) { drain(); call('claimFees', [], { from: F, revert: '*' }); call('claim', [], { from: B, revert: '*' }); + } else if (kind === 'superseded-reserves' || kind === 'superseded-full-loss') { + deposit(A, 1000n); + deposit(B, 1000n); + settle(); + gain(200n); + request(A, 'requestRewards'); + settle(); + assert.equal(model.claimReserve, 90n); + assert.equal(model.feeReserve, 10n); + const pending = deposit(C, 17n); + if (kind === 'superseded-full-loss') { + request(B, 'requestWithdrawal'); + time(); + terminal(false); + } + // In the reserves case the pending deposit shares the original cutoff. + // In the full-loss case it is eligible but must retain its refund rights. + const older = model.fixtureCheckpoint(); + time(); + model.settleCheckpoint(older); + call('setCheckpoint', [ + String(++checkpointId), String(older.block), String(older.cash), + String(older.consensusDelta - priorConsensus), + ]); + priorConsensus = older.consensusDelta; + call('settleCheckpoint'); + loss(kind === 'superseded-full-loss' ? model.riskAssets : 100n); + const newer = model.fixtureCheckpoint(); + time(); + call('setCheckpoint', [ + String(++checkpointId), String(newer.block), String(newer.cash), + String(newer.consensusDelta - priorConsensus), + ]); + priorConsensus = newer.consensusDelta; + call('abortStaging', [], { revert: 'staging remains fresh' }); + const admitted = model.activateDeposits(1); + call('activateDeposits', ['1'], { want: [String(admitted)] }); + assert.equal(admitted, 0); + assert.equal(model.claimReserve, 90n); + assert.equal(model.feeReserve, 10n); + assert.equal(model.pendingTotal, 17n); + check(); + claim(A); + fees(); + call('claim', [], { from: A, revert: '*' }); + call('claimFees', [], { revert: '*' }); + finish(); + model.cancelPending(C, pending); + call('cancelPending', [String(pending)], { from: C }); + if (kind === 'superseded-full-loss') { + assert(model.user(B).shares > 0n); + assert.equal(model.user(B).activeRequest, false); + assert.equal(model.riskAssets, 0n); + } + check(); } else if (kind === 'flow-cutoff') { deposit(A, 100n); settle(); @@ -455,6 +510,8 @@ const scenarios = [ 'zero-rounded-head', 'multi-user-drain', 'flow-cutoff', + 'superseded-reserves', + 'superseded-full-loss', ].map(makePlan); const callbackSteps = [ { op: 'deploy', id: 'ledger', artifact: 'LedgerFixture', args: [F] }, diff --git a/prototype/native/DECISIONS.md b/prototype/native/DECISIONS.md index abbaffa..7b856bc 100644 --- a/prototype/native/DECISIONS.md +++ b/prototype/native/DECISIONS.md @@ -36,6 +36,8 @@ Use one finalized beacon state to authenticate the pool's execution account, all Preserve an on-chain history of cumulative external deposits, user payments, funding and fee liabilities. Use it at the same authenticated execution block as the cash proof. Pending deposits remain separate until their admission checkpoint settles. Unfunded withdrawal requests retain their risk shares until deterministic queue processing reserves cash. This prevents later deposits or payments from distorting an earlier finalized balance sheet. Current live cash cannot simply be added to a historical validator balance. +The current ledger makes the reservation boundary explicit: every admission and reservation batch first applies the newest completed portfolio. A superseded stage retains its original cutoff, queue bounds and phase while its remaining entries use the refreshed price. Existing cash reservations and earned fees stay fixed. This preserves exposure to all losses and rewards proved before the membership change. Fresh supersession is handled atomically with processing; stale stages retain the permissionless abort path. The [current architecture](../../docs/architecture.md#withdrawals-and-rewards) describes freshness, deferred entries and the independent recovery deadline. + Before production use, the next coherent implementation must connect those components into one native ledger and demonstrate: complete portfolio coverage, pending-deposit timing, proportional loss allocation, deterministic FIFO liquidity, no settlement front-running, loss-aware fee extraction, and O(1) recovery with existing cash reserves. The isolated recovery contract deliberately lacks normal-state withdrawals and must never receive public user funds. ## Remaining trust and operating limits