-
Notifications
You must be signed in to change notification settings - Fork 1
/
grpc_query_get_twaps.go
51 lines (46 loc) · 1.78 KB
/
grpc_query_get_twaps.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package query
import (
"context"
"github.com/Timwood0x10/sei-chain/x/dex/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func (k KeeperWrapper) GetTwaps(goCtx context.Context, req *types.QueryGetTwapsRequest) (*types.QueryGetTwapsResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
allRegisteredPairs := k.GetAllRegisteredPairs(ctx, req.ContractAddr)
twaps := []*types.Twap{}
for _, pair := range allRegisteredPairs {
prices := k.GetPricesForTwap(ctx, req.ContractAddr, pair, req.LookbackSeconds)
twaps = append(twaps, &types.Twap{
Pair: &pair, //nolint:gosec,exportloopref // USING THE POINTER HERE COULD BE BAD, LET'S CHECK IT.
Twap: calculateTwap(ctx, prices, req.LookbackSeconds),
LookbackSeconds: req.LookbackSeconds,
})
}
return &types.QueryGetTwapsResponse{
Twaps: twaps,
}, nil
}
func calculateTwap(ctx sdk.Context, prices []*types.Price, lookback uint64) sdk.Dec {
if len(prices) == 0 {
return sdk.ZeroDec()
}
weightedPriceSum := sdk.ZeroDec()
lastTimestamp := ctx.BlockTime().Unix()
for _, price := range prices {
if uint64(ctx.BlockTime().Unix())-price.SnapshotTimestampInSeconds > lookback {
weight := lastTimestamp - ctx.BlockTime().Unix() + int64(lookback)
weightedPriceSum = weightedPriceSum.Add(price.Price.MulInt64(weight))
break
}
weightedPriceSum = weightedPriceSum.Add(
price.Price.MulInt64(lastTimestamp - int64(price.SnapshotTimestampInSeconds)),
)
lastTimestamp = int64(price.SnapshotTimestampInSeconds)
}
// not possible for division by 0 here since prices have unique timestamps
totalTimeSpan := ctx.BlockTime().Unix() - int64(prices[len(prices)-1].SnapshotTimestampInSeconds)
if totalTimeSpan > int64(lookback) {
totalTimeSpan = int64(lookback)
}
return weightedPriceSum.QuoInt64(totalTimeSpan)
}