Perf/lending pool optimizations#646
Merged
Smartdevs17 merged 5 commits intoJun 28, 2026
Merged
Conversation
…artdevs17#631) Add interest.rs implementing a cached cumulative interest index advanced incrementally instead of recomputing the full accrual each interaction. - Cache: last_update_block, last_update_time, cumulative_index, last_cached_rate - Incremental delta accrual via advance_index (pure, unit-tested) - Batch: same-block operations skip the write (charged once per ledger) - Invalidation hook on rate/parameter/oracle change - Read-optimised current_index for view calls (no storage write) - Reorg safety: monotonic index, StaleSnapshot guard on rewound positions
…7#632) Add liquidation.rs that front-loads validation cheapest-first so doomed liquidations abort before any storage write or token transfer. - Batched PositionSnapshot read instead of per-check reads - Checks ordered ascending by gas cost: amount, health factor, close-factor clamp, oracle freshness, gas-vs-profit guard - abort_if_unprofitable rejects when bonus < estimated gas cost - Pure pricing/validation helpers, unit-tested
Add storage.rs packing pool configuration into two words to cut storage rent (~5+ slots -> 2) with no read-gas overhead. - Rate word (u128): LTV, liq threshold, reserve factor, close factor, liq incentive as five 16-bit bps fields - Status word (u64): 40-bit timestamp + 8 status-flag bits - Overflow guards: BpsFieldOverflow / TimestampOverflow before any corruption - Idempotent migrate_from_legacy from existing loose values - Pure pack/unpack, heavily unit-tested for field independence
) Add lazy.rs deferring storage allocation for non-essential pool fields until first use, reducing storage rent over a pool's lifetime. - Deferrable fields: reserves, fees, liquidation counter, borrow index - Check-exists reads return default_for without allocating storage - ensure_initialized is idempotent (safe under concurrent first-use) - add() front-loads cost to first real accrual - migrate_initialize_all eagerly materialises fields for existing pools
…martdevs17#631 Smartdevs17#632 Smartdevs17#633 Smartdevs17#634) - Register interest/liquidation/storage/lazy modules in lib.rs - Expose entry points: interest_index, accrue_interest, invalidate_interest_cache, plan_liquidation, get/migrate packed config, get/migrate lazy fields - Add PERF_OPTIMIZATION_BENCHMARKS.md with gas-diff and storage-rent reports
|
@Joycejay17 is attempting to deploy a commit to the smartdevs17's projects Team on Vercel. A member of the Team first needs to authorize it. |
|
@Joycejay17 Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
perf(lending): pool performance optimization suite (#631 #632 #633 #634)
Summary
Implements four performance optimizations for the lending pool contract
(
stellar-lend/contracts/lending), each as a focused, self-contained modulewith pure, unit-tested core logic and contract entry points wired into
lib.rs.Closes #631
Closes #632
Closes #633
Closes #634
What's included
#631 — Incremental interest calculation with caching —
interest.rsindex_n = index_{n-1} + index_{n-1} * rate * dt / (BPS * SECONDS_PER_YEAR).last_update_block,last_update_time,cumulative_index,last_cached_rate.dt == 0andskip the write — interest is charged once per block.
invalidatecloses the open segment at the old rate, thenre-anchors the cached rate (call on rate-model / parameter / oracle change).
current_indexcomputes the index forviewcallswithout writing storage.
interest_forflags a position whoseentry index is newer than a rewound global index (
StaleSnapshot).interest_index,accrue_interest,invalidate_interest_cache.#632 — Gas-optimized liquidation —
liquidation.rsplan_liquidationvalidates cheapest-first and returns before any statemutation: amount → health factor → close-factor clamp → oracle freshness →
gas-vs-profit.
PositionSnapshotreplaces per-check reads.abort_if_unprofitablerejects when the seize bonus can't cover estimated gas.health_factor_bps,max_repay_value,seize_value,is_oracle_fresh) for reuse by an off-chain benchmark harness.plan_liquidation.#633 — Storage slot packing —
storage.rsu128rate word(LTV ∥ liq-threshold ∥ reserve-factor ∥ close-factor ∥ liq-incentive, five
16-bit bps fields) and a
u64status word (40-bit timestamp ∥ 8 flag bits).BpsFieldOverflow,TimestampOverflow) before any field cancorrupt a neighbour. Unpack is shift+mask — no extra read gas.
migrate_from_legacyrepacks a pool's current loose values.get_packed_config,migrate_packed_config.#634 — Lazy state initialization —
lazy.rsliquidation counter, total reserves, borrow-index snapshot) until first use.
default_forwith no allocation;ensure_initializedis idempotent (safe under concurrent first-use);addfront-loads cost to the first real accrual.migrate_initialize_alleagerly materializes fields for pre-existing pools.get_lazy_field,migrate_lazy_fields.Benchmarks
stellar-lend/contracts/lending/docs/PERF_OPTIMIZATION_BENCHMARKS.md—gas-diff and storage-rent reports for all four optimizations, including the
documented edge cases (no-op update, reorg consistency, failed-liquidation
early exit, packed-field overflow, concurrent first-use).
Testing
Each module ships a
#[cfg(test)] mod unitcovering the core logic and edgecases. The pure cost-driving logic (bit-packing, index math, liquidation
pricing/ordering) was additionally verified in isolation — 20/20 standalone
tests pass.
Acceptance criteria
InterestCacheadvance_indexinvalidatecurrent_index(no write)plan_liquidationPositionSnapshotabort_if_unprofitableu128rate wordu64status wordFLAG_*migrate_from_legacyLazyFieldgetensure_initializedaddmigrate_initialize_all