/
position_open.go
154 lines (126 loc) · 5.45 KB
/
position_open.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
package keeper
import (
"fmt"
"strconv"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
assetprofiletypes "github.com/elys-network/elys/x/assetprofile/types"
"github.com/elys-network/elys/x/leveragelp/types"
ptypes "github.com/elys-network/elys/x/parameter/types"
)
func (k Keeper) OpenLong(ctx sdk.Context, msg *types.MsgOpen) (*types.Position, error) {
// Determine the maximum leverage available and compute the effective leverage to be used.
maxLeverage := k.GetMaxLeverageParam(ctx)
leverage := sdk.MinDec(msg.Leverage, maxLeverage)
// Convert the collateral amount into a decimal format.
collateralAmountDec := sdk.NewDecFromBigInt(msg.CollateralAmount.BigInt())
// Initialize a new Leveragelp Trading Position (Position).
position := types.NewPosition(msg.Creator, sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount), leverage, msg.AmmPoolId)
position.Id = k.GetPositionCount(ctx) + 1
position.StopLossPrice = msg.StopLossPrice
k.SetPositionCount(ctx, position.Id)
// Call the function to process the open long logic.
return k.ProcessOpenLong(ctx, position, leverage, collateralAmountDec, msg.AmmPoolId, msg)
}
func (k Keeper) OpenConsolidate(ctx sdk.Context, position *types.Position, msg *types.MsgOpen) (*types.MsgOpenResponse, error) {
poolId := position.AmmPoolId
pool, found := k.GetPool(ctx, poolId)
if !found {
return nil, errorsmod.Wrap(types.ErrPoolDoesNotExist, fmt.Sprintf("poolId: %d", poolId))
}
if !k.IsPoolEnabled(ctx, poolId) {
return nil, errorsmod.Wrap(types.ErrPositionDisabled, fmt.Sprintf("poolId: %d", poolId))
}
ammPool, err := k.GetAmmPool(ctx, poolId)
if err != nil {
return nil, err
}
collateralAmountDec := sdk.NewDecFromInt(msg.CollateralAmount)
originCollateral := sdk.NewDecFromInt(position.Collateral.Amount)
position.Collateral = position.Collateral.Add(sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount))
maxLeverage := k.GetMaxLeverageParam(ctx)
leverage := sdk.MinDec(msg.Leverage, maxLeverage)
position.Leverage = leverage
position.StopLossPrice = collateralAmountDec.Mul(msg.StopLossPrice).
Add(originCollateral.Mul(position.StopLossPrice)).
Quo(originCollateral.Add(collateralAmountDec))
position, err = k.ProcessOpenLong(ctx, position, leverage, collateralAmountDec, poolId, msg)
if err != nil {
return nil, err
}
event := sdk.NewEvent(types.EventOpen,
sdk.NewAttribute("id", strconv.FormatInt(int64(position.Id), 10)),
sdk.NewAttribute("address", position.Address),
sdk.NewAttribute("collateral", position.Collateral.String()),
sdk.NewAttribute("leverage", position.Leverage.String()),
sdk.NewAttribute("liabilities", position.Liabilities.String()),
sdk.NewAttribute("health", position.PositionHealth.String()),
)
ctx.EventManager().EmitEvent(event)
if k.hooks != nil {
k.hooks.AfterLeveragelpPositionModified(ctx, ammPool, pool)
}
return &types.MsgOpenResponse{}, nil
}
func (k Keeper) ProcessOpenLong(ctx sdk.Context, position *types.Position, leverage sdk.Dec, collateralAmountDec sdk.Dec, poolId uint64, msg *types.MsgOpen) (*types.Position, error) {
// Fetch the pool associated with the given pool ID.
pool, found := k.GetPool(ctx, poolId)
if !found {
return nil, errorsmod.Wrap(types.ErrPoolDoesNotExist, fmt.Sprintf("poolId: %d", poolId))
}
// Check if the pool is enabled.
if !k.IsPoolEnabled(ctx, poolId) {
return nil, errorsmod.Wrap(types.ErrPositionDisabled, fmt.Sprintf("poolId: %d", poolId))
}
// Fetch the corresponding AMM (Automated Market Maker) pool.
ammPool, err := k.GetAmmPool(ctx, poolId)
if err != nil {
return nil, err
}
entry, found := k.assetProfileKeeper.GetEntry(ctx, ptypes.BaseCurrency)
if !found {
return nil, errorsmod.Wrapf(assetprofiletypes.ErrAssetProfileNotFound, "asset %s not found", ptypes.BaseCurrency)
}
baseCurrency := entry.Denom
if msg.CollateralAsset != baseCurrency {
return nil, types.ErrOnlyBaseCurrencyAllowed
}
// Calculate the leveraged amount based on the collateral provided and the leverage.
leveragedAmount := sdk.NewInt(collateralAmountDec.Mul(leverage).TruncateInt().Int64())
// send collateral coins to Position address from Position owner address
positionOwner := sdk.MustAccAddressFromBech32(position.Address)
err = k.bankKeeper.SendCoins(ctx, positionOwner, position.GetPositionAddress(), sdk.Coins{sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount)})
if err != nil {
return nil, err
}
leverageCoin := sdk.NewCoin(msg.CollateralAsset, leveragedAmount)
// borrow leveragedAmount - collateralAmount
borrowCoin := sdk.NewCoin(msg.CollateralAsset, leveragedAmount.Sub(msg.CollateralAmount))
err = k.stableKeeper.Borrow(ctx, position.GetPositionAddress(), borrowCoin)
if err != nil {
return nil, err
}
_, shares, err := k.amm.JoinPoolNoSwap(ctx, position.GetPositionAddress(), poolId, sdk.OneInt(), sdk.Coins{leverageCoin})
if err != nil {
return nil, err
}
// Update the pool health.
pool.LeveragedLpAmount = pool.LeveragedLpAmount.Add(shares)
k.UpdatePoolHealth(ctx, &pool)
// Get the Position health.
lr, err := k.GetPositionHealth(ctx, *position, ammPool)
if err != nil {
return nil, err
}
// Check if the Position is unhealthy
safetyFactor := k.GetSafetyFactor(ctx)
if lr.LTE(safetyFactor) {
return nil, types.ErrPositionUnhealthy
}
// Set Position
position.LeveragedLpAmount = position.LeveragedLpAmount.Add(shares)
position.Liabilities = position.Liabilities.Add(borrowCoin.Amount)
position.PositionHealth = lr
k.SetPosition(ctx, position)
return position, nil
}