Skip to content

Comments

[DRAFT] Extract ALP components into separate contracts#160

Open
jordanschalm wants to merge 36 commits intomainfrom
jord/split-contracts
Open

[DRAFT] Extract ALP components into separate contracts#160
jordanschalm wants to merge 36 commits intomainfrom
jord/split-contracts

Conversation

@jordanschalm
Copy link
Member

@jordanschalm jordanschalm commented Feb 12, 2026

This PR refactors ALP types and state fields. The goal is to:

  • Use interface types to store state to enable future upgrades (see pattern in https://github.com/jordanschalm/cadence-interface-upgrade-pattern)
  • Reduce the size of the main FlowALPv1 contract by moving code into separate contracts
  • Avoid substantial logic changes as part of this PR, to make review easier. I have tried to limit logic changes to removing layers of duplicated functions, or consolidating very simple functions.

Changes

  • Move InterestCurve interface, FixedRateInterestCurve, and KinkInterestCurve from FlowALPv1 into a new standalone FlowALPRateCurves contract
  • Move all event type definitions into a new standalone FlowALPEvents contract
  • Move most model types into a separate contract: FlowALPModels
  • Convert most model types which are directly or indirectly stored in storage to interface types, so that they can be upgraded in the future
    • I did not apply this pattern to "view" types that are not stored (for example, TokenSnapshot)
    • I also did not apply this pattern to simple types that are stored within a type that does have the pattern applied. (For example, InternalBalance remains a struct type. But, since it is stored as part of InternalPosition which uses the interface pattern, we can if necessary update InternalBalance while updating InternalPosition.)
  • Added the EImplementation to all state-mutating functions moved to FlowALPModels, and document that this entitlement is strictly for internal implementation use (we should never grant the entitlement outside of contract code.)
  • Moved some math functions to FlowALPMath. In this PR we decided to retain the separate Math contract. Given that, I think it makes sense to delegate pure math-related functions into that contract.

jordanschalm and others added 6 commits February 12, 2026 10:37
Move InterestCurve interface, FixedRateInterestCurve, and KinkInterestCurve
from FlowALPv1 into a new standalone FlowALPRateCurves contract to improve
modularity and allow rate curve types to be reused independently.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…rve to FixedCurve, KinkInterestCurve to KinkCurve

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Move 9 pool config fields (priceOracle, collateralFactor, borrowFactor,
positionsProcessedPerCallback, liquidationTargetHF, warmupSec,
lastUnpausedAt, dex, dexOracleDeviationBps) into a PoolConfigImpl struct
in a new FlowALPModels contract, centralizing config validation logic.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace pure-delegation Pool wrapper functions (setDexOracleDeviationBps,
setDEX) with a single borrowConfig() function that returns a mutable
reference to the pool's PoolConfig. Callers can now invoke config setters
directly. Wrapper functions with events/side effects are preserved.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Move TokenState struct and EImplementation entitlement to FlowALPModels.
Create PoolStateImpl resource in FlowALPModels to hold Pool's movable
state fields (globalLedger, reserves, insuranceFund, etc.).
Move pure utility functions (perSecondInterestRate, compoundInterestIndex,
dexOraclePriceDeviationInRange) to FlowALPMath, keeping thin wrappers
in FlowALPv1 for backwards compatibility.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@jordanschalm jordanschalm changed the title [DRAFT] Extract InterestCurve types into FlowALPRateCurves contract [DRAFT] Extract ALP components into separate contracts Feb 13, 2026
jordanschalm and others added 6 commits February 13, 2026 09:38
Pool.state is now typed as @{FlowALPModels.PoolState} instead of the
concrete @FlowALPModels.PoolStateImpl, matching the PoolConfig/PoolConfigImpl
pattern and allowing the implementation to be swapped in future upgrades.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
These are configuration fields, not state fields. Moving them to PoolConfig
with getter/setter methods ensures they are upgradeable.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
All fields on the PoolState interface are now accessed through getter/setter
methods rather than direct field access. This ensures the interface is
upgradeable - fields cannot be changed in interface upgrades, but function
signatures can evolve.

Also fixes a test that relied on dictionary key ordering for position
balances.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
These functions interact with pool-level state (reserves, insurance fund)
and are better suited as Pool methods that accept a TokenState reference.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Base supported token logic on collateralFactor dictionary keys in PoolConfig
rather than globalLedger keys in PoolState. Pool methods now delegate to config.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Move _borrowOrCreateReserveVault to PoolState as borrowOrCreateReserve
- Move _getSwapperForLiquidation to PoolConfig as getSwapperForLiquidation
- Remove setLiquidationParams, setPauseParams, pausePool wrappers
- Remove setDebugLogging wrapper (callers use borrowConfig() directly)
- Remove unused events: LiquidationParamsUpdated, PauseParamsUpdated, PoolPaused
- Update transactions to use borrowConfig() for pause and debug logging

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
let diffPct: UFix64 = dexPrice < oraclePrice ? diff / dexPrice : diff / oraclePrice
let diffBps = UInt16(diffPct * 10_000.0)
return diffBps <= maxDeviationBps
return FlowALPMath.dexOraclePriceDeviationInRange(dexPrice: dexPrice, oraclePrice: oraclePrice, maxDeviationBps: maxDeviationBps)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix this duplication

@bluesign
Copy link

bluesign commented Feb 14, 2026

I did something similar, MVC pattern ( like https://github.com/jordanschalm/cadence-interface-upgrade-pattern)

I took a different approach ( used attachments basically ) and state code is generated. ( just pushed maybe inspires something: https://github.com/bluesign/upgradeable

Also my old splitting attempt on credit market ( https://github.com/bluesign/fcm-core/tree/master/cadence/contracts ) ( not using the upgradeable but similar ideas )

Copy link
Member

@joshuahannan joshuahannan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Really good changes! I think you're on the right track

self.yearlyRate = yearlyRate
}

access(all) fun interestRate(creditBalance: UFix128, debitBalance: UFix128): UFix128 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what are the parameters here for?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See https://github.com/onflow/FlowALP/pull/160/changes/BASE..dc21efb1e2fefca3fd6435033e721c0b468b9f97#diff-b68530c0b2e0dcf9d373ec5938f2b1f6222bb11bfb19e8dc333bcae7e48e9e35R10-R11.

(I'm trying to mainly move existing code and not add anything right now to keep the diff clean, but agree there should be documentation here.)

access(all) let baseRate: UFix128

/// The slope of the interest curve before the optimal point (gentle slope)
access(all) let slope1: UFix128
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should these be called gentleSlope and steepSlope instead?

///
/// This entitlement is used internally by the protocol to maintain state consistency
/// and process queued operations. It should not be granted to external users.
access(all) entitlement EImplementation
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like using E for entitlement names. I think it should just be Implementation, or something else. Typically we use verbs and sometimes nouns

Comment on lines 42 to 52
access(all) fun setPriceOracle(_ newOracle: {DeFiActions.PriceOracle}, defaultToken: Type)
access(all) fun setCollateralFactor(tokenType: Type, factor: UFix64)
access(all) fun setBorrowFactor(tokenType: Type, factor: UFix64)
access(all) fun setPositionsProcessedPerCallback(_ count: UInt64)
access(all) fun setLiquidationTargetHF(_ targetHF: UFix128)
access(all) fun setWarmupSec(_ warmupSec: UInt64)
access(all) fun setLastUnpausedAt(_ time: UInt64?)
access(all) fun setDex(_ dex: {DeFiActions.SwapperProvider})
access(all) fun setDexOracleDeviationBps(_ bps: UInt16)
access(all) fun setPaused(_ paused: Bool)
access(all) fun setDebugLogging(_ enabled: Bool)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it safe to make all these access(all)? Should they be access(contract) or access(account) instead just to be safe?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have gone through and made all state-modifying functions on types that are stored EImplementation-entitled.

Copy link
Member

@joshuahannan joshuahannan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just realized that we should do this for the auto balancer RecurringConfig also

jordanschalm and others added 7 commits February 18, 2026 11:08
Move scaledBalanceToTrueBalance, trueBalanceToScaledBalance, effectiveCollateral, effectiveDebt, and healthComputation from FlowALPv1 to FlowALPMath. Update all internal callers in FlowALPv1 to reference FlowALPMath directly. This eliminates the circular dependency that would arise when moving types to FlowALPModels.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add RiskParams interface and RiskParamsImplv1 to FlowALPModels.
Update FlowALPv1 to use interface type for fields and impl for
construction. Field access replaced with getter methods.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add TokenSnapshot interface and TokenSnapshotImplv1 to FlowALPModels.
Update FlowALPv1 to use interface type for fields and impl for
construction. Field access replaced with getter methods.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
jordanschalm and others added 17 commits February 18, 2026 11:47
…nDetails to FlowALPModels

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…Pv0 naming

- Resolve all 23 conflicted files from merging main
- Keep split-contract architecture: FlowALPModels, FlowALPInterestRates, FlowALPMath
- Apply FlowALPv1 → FlowALPv0 rename throughout (from main)
- Incorporate rebalancer contracts, global pause updates, new tests from main
- Add PoolPaused event and pausePool() governance function to FlowALPv0
- All 38 tests pass

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
These were created on a separate branch (and gitignored here), then
added inadvertently here while merging.
Extract events from FlowALPv0 and FlowALPModels into a dedicated
FlowALPEvents contract with access(account)-scoped emission functions.
This centralizes event definitions and ensures only co-deployed contracts
can emit protocol events.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add /// doc comments with @param lines for each event type and its
corresponding emission function, describing the purpose and parameters.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace concrete TokenState struct with a TokenState struct interface
and TokenStateImplv1 implementation, following the same pattern used
for RiskParams, TokenSnapshot, and PoolConfig. All fields are now
private (access(self)) and accessed via getter/setter functions,
enabling future implementation upgrades without breaking consumers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Create InternalPosition resource interface and InternalPositionImplv1
implementation in FlowALPModels, replacing the concrete resource in
FlowALPv0. Remove the ImplementationUpdates entitlement mapping, as
interface methods now encapsulate all field access.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…plementations

Ensure interface getters and struct fields have matching documentation
for all pairs: RiskParams, TokenSnapshot, PoolConfig, TokenState,
PoolState, and InternalPosition. Standardize setter documentation to
reference corresponding getters and document constraints.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Move EPosition, ERebalance, EGovernance, EParticipant, and
EPositionAdmin entitlements to FlowALPModels alongside EImplementation.
Update all references across contracts, transactions, and tests to use
the FlowALPModels prefix, adding imports where needed.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
TokenSnapshot is an immutable value type with no need for implementation
swapping, so the interface indirection was unnecessary.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ion entitlement

All setter and state-mutating functions on PoolConfig, TokenState (impl),
InternalPosition interfaces and their implementations now require
EImplementation entitlement instead of access(all). Updated corresponding
reference return types and parameters in FlowALPv0 to propagate authorized
references where needed.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…odels

Ensures every function and field across all interface and implementation
types has a /// doc comment. For impl types, docs are derived from their
corresponding interface declarations.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@jordanschalm
Copy link
Member Author

I just realized that we should do this for the auto balancer RecurringConfig also

Did this in a separate PR: #179

@jordanschalm jordanschalm marked this pull request as ready for review February 21, 2026 02:24
@jordanschalm jordanschalm requested a review from a team as a code owner February 21, 2026 02:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants