-
Notifications
You must be signed in to change notification settings - Fork 44
/
invariant_check.go
65 lines (54 loc) · 1.59 KB
/
invariant_check.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
package keeper
import (
"errors"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/elys-network/elys/x/perpetual/types"
)
func (k Keeper) AmmPoolBalanceCheck(ctx sdk.Context, poolId uint64) error {
ammPool, found := k.amm.GetPool(ctx, poolId)
if !found {
return errors.New("pool doesn't exist!")
}
address, err := sdk.AccAddressFromBech32(ammPool.GetAddress())
if err != nil {
return err
}
mtpCollateralBalances := sdk.NewCoins()
mtps := k.GetAllMTPs(ctx)
for _, mtp := range mtps {
ammPoolId := mtp.AmmPoolId
if !k.OpenLongChecker.IsPoolEnabled(ctx, ammPoolId) {
continue
}
if poolId != mtp.AmmPoolId {
continue
}
mtpCollateralBalances = mtpCollateralBalances.Add(sdk.NewCoin(mtp.CollateralAsset, mtp.Collateral))
}
// bank balance should be ammPool balance + collateral balance
// TODO:
// Need to think about correct algorithm of balance checking.
// Important note.
// AMM pool balance differs bank module balance
balances := k.bankKeeper.GetAllBalances(ctx, address)
for _, balance := range balances {
ammBalance, _ := types.GetAmmPoolBalance(ammPool, balance.Denom)
collateralAmt := mtpCollateralBalances.AmountOf(balance.Denom)
diff := ammBalance.Add(collateralAmt).Sub(balance.Amount)
if !diff.IsZero() {
return errors.New("balance mismatch!")
}
}
return nil
}
// Check if amm pool balance in bank module is correct
func (k Keeper) InvariantCheck(ctx sdk.Context) error {
ammPools := k.amm.GetAllPool(ctx)
for _, ammPool := range ammPools {
err := k.AmmPoolBalanceCheck(ctx, ammPool.PoolId)
if err != nil {
return err
}
}
return nil
}