Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reduced CalcTWAP to only one snapshots range #1801

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 5 additions & 22 deletions x/perp/v2/keeper/twap.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,37 +46,20 @@ func (k Keeper) CalcTwap(
EndInclusive(ctx.BlockTime()).
Descending(),
)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
s := iter.Value()
snapshots = append(snapshots, s)
if s.TimestampMs <= lowerLimitTimestampMs {
break
}
}
snapshots = iter.Values()
Copy link
Contributor

Choose a reason for hiding this comment

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

The direct assignment of values from the iterator to snapshots simplifies the logic for collecting snapshot data. This change should improve readability and potentially performance by eliminating explicit iteration. However, ensure that the iter.Values() method efficiently handles large datasets without significant memory overhead.


if len(snapshots) == 0 {
return sdk.OneDec().Neg(), types.ErrNoValidTWAP
}

// circuit-breaker when there's only one snapshot to process
if len(snapshots) == 1 {
return getPriceWithSnapshot(
snapshots[0],
snapshotPriceOps{
twapCalcOption: twapCalcOption,
direction: direction,
assetAmt: assetAmt,
},
)
}

// else, iterate over all snapshots and calculate TWAP
prevTimestampMs := ctx.BlockTime().UnixMilli()
cumulativePrice := sdk.ZeroDec()
cumulativePeriodMs := int64(0)
count := int64(0)

for _, snapshot := range snapshots {
count++
if snapshot.TimestampMs == prevTimestampMs {
// in some extreme cases, 2 reserves snapshots can have the same timestamp which would cause a divide by zero error
// in this case, we skip the second snapshot
Expand Down Expand Up @@ -112,8 +95,8 @@ func (k Keeper) CalcTwap(
prevTimestampMs = snapshot.TimestampMs
}

if cumulativePeriodMs == 0 {
// Should not be reachable
// circuit-breaker when there's only one snapshot to process
if count == 1 || cumulativePeriodMs == 0 {
return getPriceWithSnapshot(
snapshots[0],
snapshotPriceOps{
Expand Down
Loading