-
Notifications
You must be signed in to change notification settings - Fork 168
/
inspector.go
238 lines (207 loc) · 6.93 KB
/
inspector.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
package keeper
import (
"context"
"fmt"
"math"
"sort"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/umee-network/umee/v6/util/coin"
"github.com/umee-network/umee/v6/x/leverage/types"
)
type tokenExchangeRate struct {
symbol string
exponent uint32
exchangeRate sdk.Dec
}
// Separated from grpc_query.go
func (q Querier) Inspect(
goCtx context.Context,
req *types.QueryInspect,
) (*types.QueryInspectResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
failures := []string{}
// This query is also disabled by default as a safety measure. Enable with liquidator queries.
if !q.Keeper.liquidatorQueryEnabled {
return nil, types.ErrNotLiquidatorNode
}
k, ctx := q.Keeper, sdk.UnwrapSDKContext(goCtx)
tokens := k.GetAllRegisteredTokens(ctx)
exchangeRates := map[string]tokenExchangeRate{}
for _, t := range tokens {
exchangeRates[t.BaseDenom] = tokenExchangeRate{
symbol: t.SymbolDenom,
exponent: t.Exponent,
exchangeRate: k.DeriveExchangeRate(ctx, t.BaseDenom),
}
if strings.EqualFold(t.SymbolDenom, req.Symbol) {
// convert request to match the case of token registry symbol denom
req.Symbol = t.SymbolDenom
}
}
// inspect every borrower only once
borrowers := []*types.InspectAccount{}
checkedAddrs := map[string]interface{}{}
prefix := types.KeyPrefixAdjustedBorrow
iterator := func(key, _ []byte) error {
// get borrower address from key
addr := types.AddressFromKey(key, prefix)
// if the address is already checked, do not check again
if _, ok := checkedAddrs[addr.String()]; ok {
return nil
}
checkedAddrs[addr.String()] = struct{}{}
borrowedValue, collateralValue, liquidationThreshold := sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()
position, err := k.GetAccountPosition(ctx, addr, true)
if err == nil {
borrowedValue = position.BorrowedValue()
collateralValue = position.CollateralValue()
liquidationThreshold = position.Limit()
} else {
failures = append(failures, addr.String())
}
borrowed := k.GetBorrowerBorrows(ctx, addr)
collateral := k.GetBorrowerCollateral(ctx, addr)
account := types.InspectAccount{
Address: addr.String(),
Analysis: &types.RiskInfo{
Borrowed: neat(borrowedValue),
Liquidation: neat(liquidationThreshold),
Value: neat(collateralValue),
},
Position: &types.DecBalances{
Collateral: symbolDecCoins(collateral, exchangeRates),
Borrowed: symbolDecCoins(borrowed, exchangeRates),
},
Info: "",
}
ok := account.Analysis.Borrowed > req.Borrowed
ok = ok && account.Analysis.Value > req.Collateral
ok = ok && account.Analysis.Borrowed/account.Analysis.Liquidation > req.Danger
ok = ok && account.Analysis.Borrowed/account.Analysis.Value > req.Ltv
if ok {
borrowers = append(borrowers, &account)
}
return nil
}
// collect all accounts (filtered but unsorted)
_ = k.iterate(ctx, prefix, iterator)
// sorts the borrowers
sort.SliceStable(borrowers, func(i, j int) bool {
if req.Symbol != "" {
// for non-empty symbol denom, sorts by borrowed amount (descending) of that token
return borrowers[i].Position.Borrowed.AmountOf(req.Symbol).GTE(borrowers[j].Position.Borrowed.AmountOf(req.Symbol))
}
// otherwise, sorts by borrowed value (descending)
return borrowers[i].Analysis.Borrowed > borrowers[j].Analysis.Borrowed
},
)
// convert from pointers
sortedBorrowers := []types.InspectAccount{}
for _, b := range borrowers {
sortedBorrowers = append(sortedBorrowers, *b)
}
return &types.QueryInspectResponse{Borrowers: sortedBorrowers, Failures: failures}, nil
}
// Separated from grpc_query.go
func (q Querier) InspectAccount(
goCtx context.Context,
req *types.QueryInspectAccount,
) (*types.QueryInspectAccountResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
k, ctx := q.Keeper, sdk.UnwrapSDKContext(goCtx)
tokens := k.GetAllRegisteredTokens(ctx)
exchangeRates := map[string]tokenExchangeRate{}
for _, t := range tokens {
exchangeRates[t.BaseDenom] = tokenExchangeRate{
symbol: t.SymbolDenom,
exponent: t.Exponent,
exchangeRate: k.DeriveExchangeRate(ctx, t.BaseDenom),
}
}
addr, err := sdk.AccAddressFromBech32(req.Address)
if err != nil {
return nil, err
}
position, err := k.GetAccountPosition(ctx, addr, true)
if err != nil {
return nil, err
}
borrowedValue := position.BorrowedValue()
collateralValue := position.CollateralValue()
liquidationThreshold := position.Limit()
borrowPosition, err := k.GetAccountPosition(ctx, addr, false)
if err != nil {
return nil, err
}
borrowed := k.GetBorrowerBorrows(ctx, addr)
collateral := k.GetBorrowerCollateral(ctx, addr)
account := types.InspectAccount{
Address: addr.String(),
Analysis: &types.RiskInfo{
Borrowed: neat(borrowedValue),
Liquidation: neat(liquidationThreshold),
Value: neat(collateralValue),
},
Position: &types.DecBalances{
Collateral: symbolDecCoins(collateral, exchangeRates),
Borrowed: symbolDecCoins(borrowed, exchangeRates),
},
Info: fmt.Sprint(position.String(), "\n", borrowPosition.String()),
}
return &types.QueryInspectAccountResponse{Borrower: account}, nil
}
// symbolDecCoins converts an sdk.Coins containing base tokens or uTokens into an sdk.DecCoins containing symbol denom
// base tokens. for example, 1000u/uumee becomes 0.0015UMEE at an exponent of 6 and uToken exchange rate of 1.5
func symbolDecCoins(
coins sdk.Coins,
tokens map[string]tokenExchangeRate,
) sdk.DecCoins {
symbolCoins := sdk.NewDecCoins()
for _, c := range coins {
exchangeRate := sdk.OneDec()
if coin.HasUTokenPrefix(c.Denom) {
// uTokens will be converted to base tokens
c.Denom = coin.StripUTokenDenom(c.Denom)
exchangeRate = tokens[c.Denom].exchangeRate
}
t, ok := tokens[c.Denom]
if !ok {
// unregistered tokens cannot be converted, but can be returned as base denom
symbolCoins = symbolCoins.Add(sdk.NewDecCoinFromDec(c.Denom, sdk.NewDecFromInt(c.Amount)))
continue
}
exponentMultiplier := ten.Power(uint64(t.exponent))
amount := exchangeRate.MulInt(c.Amount).Quo(exponentMultiplier)
symbolCoins = symbolCoins.Add(sdk.NewDecCoinFromDec(t.symbol, amount))
}
return symbolCoins
}
// neat truncates an sdk.Dec to a common-sense precision based on its size and converts it to float.
// This greatly improves readability when viewing balances.
func neat(num sdk.Dec) float64 {
n := num.MustFloat64()
a := math.Abs(n)
precision := 2 // Round to cents if 0.01 <= n <= 100
if a > 100 {
precision = 0 // above $100: Round to dollar
}
if a > 1_000_000 {
precision = -3 // above $1000000: Round to thousand
}
if a < 0.01 {
precision = 6 // round to millionths
}
if a < 0.000001 {
return n // tiny: maximum precision
}
// Truncate the float at a certain precision (can be negative)
x := math.Pow(10, float64(precision))
return float64(int(n*x)) / x
}