-
Notifications
You must be signed in to change notification settings - Fork 3
/
alliance_protocols_info.go
306 lines (260 loc) · 9.5 KB
/
alliance_protocols_info.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package alliance_provider
import (
"context"
"fmt"
"strconv"
"strings"
alliancetypes "github.com/terra-money/alliance/x/alliance/types"
"github.com/terra-money/oracle-feeder-go/config"
"github.com/terra-money/oracle-feeder-go/internal/provider/internal"
types "github.com/terra-money/oracle-feeder-go/internal/types"
pkgtypes "github.com/terra-money/oracle-feeder-go/pkg/types"
"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
sdktypes "github.com/cosmos/cosmos-sdk/types"
mintypes "github.com/cosmos/cosmos-sdk/x/mint/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/terra-money/oracle-feeder-go/internal/provider"
"github.com/terra-money/oracle-feeder-go/internal/provider/internal/carbon"
)
type allianceProtocolsInfo struct {
internal.BaseGrpc
provider.LSDProvider
carbon.CarbonProvider
config *config.AllianceConfig
providerManager *provider.ProviderManager
}
func NewAllianceProtocolsInfo(config *config.AllianceConfig, providerManager *provider.ProviderManager) *allianceProtocolsInfo {
return &allianceProtocolsInfo{
BaseGrpc: *internal.NewBaseGrpc(),
LSDProvider: *provider.NewLSDProvider(),
CarbonProvider: *carbon.NewCarbonProvider(),
config: config,
providerManager: providerManager,
}
}
func (p *allianceProtocolsInfo) GetProtocolsInfo(ctx context.Context) (*pkgtypes.MsgUpdateChainsInfo, error) {
protocolRes := types.DefaultAllianceProtocolRes()
// Query the all prices at the beginning
// to cache the data and avoid querying
// the prices each time we query the protocols info.
pricesRes := p.providerManager.GetPrices(ctx)
// Given the default list of LSTSData this method
// queries the blockchain for the rebase factor of the LSD.
lstsData, err := p.queryRebaseFactors(ctx, p.config.LSTSData)
if err != nil {
fmt.Printf("queryRebaseFactors: %v \n", err)
return nil, err
}
// Given the default list of LSTSData this method
// queries the blockchain for the rebase factor of the LSD.
lstsDataOnPhoenix, err := p.queryRebaseFactorsForLstsOnPhoenix(ctx, p.config.LSTOnPhoenix)
if err != nil {
fmt.Printf("queryRebaseFactors: %v \n", err)
return nil, err
}
// Setup Luna price
for _, price := range pricesRes.Prices {
if strings.EqualFold(price.Denom, "LUNA") {
luna, err := sdktypes.NewDecFromStr(strconv.FormatFloat(price.Price, 'f', -1, 64))
if err != nil {
fmt.Printf("parse price error for: %s %v \n", price.Denom, err)
return nil, err
}
protocolRes.LunaPrice = luna
}
}
// Iterate over all configured nodes in the config file,
// create a grpcConnection to each node and query the required data.
for _, grpcUrl := range p.config.GRPCUrls {
grpcConn, err := p.BaseGrpc.Connection(ctx, grpcUrl)
if err != nil {
return nil, err
}
defer grpcConn.Close()
// Create the QueryClients for the necessary modules.
nodeClient := tmservice.NewServiceClient(grpcConn)
mintClient := mintypes.NewQueryClient(grpcConn)
stakingClient := stakingtypes.NewQueryClient(grpcConn)
allianceClient := alliancetypes.NewQueryClient(grpcConn)
// Request alliances from the origin chain.
allianceRes, err := allianceClient.Alliances(ctx, &alliancetypes.QueryAlliancesRequest{})
if err != nil {
fmt.Printf("allianceRes for %s: %v \n", grpcUrl, err)
return nil, err
}
if len(allianceRes.Alliances) == 0 {
fmt.Printf("No alliances found on: %s \n", grpcUrl)
continue
}
allianceParamsRes, err := allianceClient.Params(ctx, &alliancetypes.QueryParamsRequest{})
if err != nil {
fmt.Printf("allianceParamsRes: %v \n", err)
return nil, err
}
nodeRes, err := nodeClient.GetNodeInfo(ctx, &tmservice.GetNodeInfoRequest{})
if err != nil {
fmt.Printf("nodeRes: %v \n", err)
return nil, err
}
stakingParamsRes, err := stakingClient.Params(ctx, &stakingtypes.QueryParamsRequest{})
if err != nil {
fmt.Printf("stakingParamsRes: %v \n", err)
return nil, err
}
var annualProvisionsRes *mintypes.QueryAnnualProvisionsResponse
if strings.Contains(grpcUrl, "carbon") {
annualProvisionsRes, err = p.CarbonProvider.GetAnnualProvisions(ctx)
} else {
annualProvisionsRes, err = mintClient.AnnualProvisions(ctx, &mintypes.QueryAnnualProvisionsRequest{})
annualProvisionsRes.AnnualProvisions = annualProvisionsRes.AnnualProvisions.QuoInt64(1000000)
}
if err != nil {
fmt.Printf("annualProvisionsRes: %v \n", err)
return nil, err
}
// Remove the "u" prefix from the bond denom and
// search for the price of the native token in
// the prices response.
bondDenom := strings.Replace(stakingParamsRes.GetParams().BondDenom, "u", "", 1)
var priceRes pkgtypes.PriceOfCoin
for _, price := range pricesRes.Prices {
if strings.EqualFold(price.Denom, bondDenom) {
priceRes = price
}
}
if priceRes.Denom == "" {
return nil, fmt.Errorf("price not found for: %s", bondDenom)
}
price, err := sdktypes.NewDecFromStr(strconv.FormatFloat(priceRes.Price, 'f', -1, 64))
if err != nil {
fmt.Printf("parse price error for: %s %v \n", bondDenom, err)
return nil, err
}
nativeToken := types.NewNativeToken(
stakingParamsRes.GetParams().BondDenom,
price,
annualProvisionsRes.AnnualProvisions,
)
normalizedLunaAlliance := p.parseLunaAlliances(allianceParamsRes.Params, allianceRes.Alliances, lstsData)
alliancesOnPhoenix := p.parseAlliancesOnPhoenix(nodeRes, lstsDataOnPhoenix)
protocolRes.ProtocolsInfo = append(protocolRes.ProtocolsInfo, types.NewProtocolInfo(
nodeRes.DefaultNodeInfo.Network,
nativeToken,
normalizedLunaAlliance,
alliancesOnPhoenix,
))
}
res := pkgtypes.NewMsgUpdateChainsInfo(protocolRes)
return &res, nil
}
func (p *allianceProtocolsInfo) queryRebaseFactors(ctx context.Context, configLST []config.LSTData) ([]config.LSTData, error) {
for i, lst := range configLST {
rebaseFactor, err := p.LSDProvider.QueryLSTRebaseFactor(ctx, lst.Symbol)
if err != nil {
fmt.Printf("queryRebaseFactors: %v \n", err)
continue
}
configLST[i].RebaseFactor = *rebaseFactor
}
return configLST, nil
}
func (p *allianceProtocolsInfo) queryRebaseFactorsForLstsOnPhoenix(ctx context.Context, configLST []config.LSTOnPhoenix) ([]config.LSTOnPhoenix, error) {
for i, lst := range configLST {
rebaseFactor, err := p.LSDProvider.QueryLSTRebaseFactor(ctx, lst.Symbol)
if err != nil {
fmt.Printf("queryRebaseFactorsForLstsOnPhoenix: %v \n", err)
continue
}
configLST[i].RebaseFactor = *rebaseFactor
}
return configLST, nil
}
func (p *allianceProtocolsInfo) parseAlliancesOnPhoenix(
nodeRes *tmservice.GetNodeInfoResponse,
phoenixLSTParsedData []config.LSTOnPhoenix,
) []types.BaseAlliance {
baseAlliances := []types.BaseAlliance{}
for _, allianceOnPhoenix := range p.config.LSTOnPhoenix {
for _, lstData := range phoenixLSTParsedData {
if lstData.IBCDenom == allianceOnPhoenix.IBCDenom &&
allianceOnPhoenix.CounterpartyChainId == nodeRes.DefaultNodeInfo.Network {
baseAlliances = append(baseAlliances, types.BaseAlliance{
IBCDenom: lstData.IBCDenom,
RebaseFactor: lstData.RebaseFactor,
})
}
}
}
return baseAlliances
}
func (p *allianceProtocolsInfo) parseLunaAlliances(
allianceParams alliancetypes.Params,
alliances []alliancetypes.AllianceAsset,
lstsData []config.LSTData,
) []types.LunaAlliance {
lunaAlliances := []types.LunaAlliance{}
for _, lstData := range lstsData {
for _, alliance := range alliances {
// When an alliance is whitelisted in lstData which
// means that it is an alliance with an LSD of luna
// so it must be included to the lunaAlliances.
if strings.EqualFold(lstData.IBCDenom, alliance.Denom) {
annualTakeRate := calculateAnnualizedTakeRate(allianceParams, alliance)
normalizedRewardWeight := calculateNormalizedRewardWeight(allianceParams, alliances, alliance)
lunaAlliances = append(lunaAlliances, types.NewLunaAlliance(
alliance.Denom,
normalizedRewardWeight,
annualTakeRate,
sdktypes.NewDecFromIntWithPrec(alliance.TotalTokens, 6),
lstData.RebaseFactor,
))
}
}
}
return lunaAlliances
}
func calculateAnnualizedTakeRate(
params alliancetypes.Params,
alliance alliancetypes.AllianceAsset,
) sdktypes.Dec {
// When TakeRateClaimInterval is zero it means that users are not
// receiving any rewards so annualized take rate is zero (right now).
if params.TakeRateClaimInterval == 0 {
return sdktypes.ZeroDec()
}
// Parse the take rate from any interval to takeRatePerYear ...
takeRatePerYear := 365 / params.TakeRateClaimInterval.Hours() * 24
// ... return the annualized take rate.
return sdktypes.OneDec().
Sub(sdktypes.
OneDec().
Sub(alliance.TakeRate).
Power(uint64(takeRatePerYear)))
}
func calculateNormalizedRewardWeight(
params alliancetypes.Params,
alliances []alliancetypes.AllianceAsset,
alliance alliancetypes.AllianceAsset,
) sdktypes.Dec {
// If alliance, is not initiated return zero.
if !alliance.IsInitialized {
return sdktypes.ZeroDec()
}
// We should consider that reward weight
// starts at one because it also takes in
// consideration the OneDec.
rewardsWeight := sdktypes.OneDec()
for _, alliance := range alliances {
// When an alliance is not initialized, it means that users are not
// receiving rewards so NormalizedRewardWeight for this alliance shouldn't
// be considered.
if !alliance.IsInitialized {
continue
}
// If an alliance is not initialized it means that
// rewards are not distributed to that alliance so
// it has a reward weight of zero.
rewardsWeight = rewardsWeight.Add(alliance.RewardWeight)
}
return alliance.RewardWeight.Quo(rewardsWeight)
}