Skip to content

Commit

Permalink
fix: swap amount out and open estimation (#374)
Browse files Browse the repository at this point in the history
* fix: swap amount out and open estimation

* test: fix tests

* test: fix unit test
  • Loading branch information
cosmic-vagabond authored Feb 14, 2024
1 parent 3662c43 commit b8611af
Show file tree
Hide file tree
Showing 13 changed files with 24 additions and 34 deletions.
3 changes: 0 additions & 3 deletions x/amm/keeper/calc_in_route_spot_price.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,6 @@ func (k Keeper) CalcInRouteSpotPrice(ctx sdk.Context, tokenIn sdk.Coin, routes [
return sdk.ZeroDec(), sdk.Coin{}, sdk.ZeroDec(), sdk.ZeroDec(), sdk.Coin{}, sdk.ZeroDec(), types.ErrAmountTooLow
}

// Subtract the swap fee from the token out amount
tokenOut.Amount = tokenOut.Amount.Sub(sdk.NewDecFromInt(tokenOut.Amount).Mul(swapFee).TruncateInt())

// Use the current swap result as the input for the next iteration
tokensIn = sdk.Coins{tokenOut}

Expand Down
4 changes: 2 additions & 2 deletions x/amm/keeper/keeper_swap_exact_amount_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func (k Keeper) SwapExactAmountIn(

// Settles balances between the tx sender and the pool to match the swap that was executed earlier.
// Also emits a swap event and updates related liquidity metrics.
swapOutFee, err := k.UpdatePoolForSwap(ctx, pool, sender, recipient, tokenIn, tokenOutCoin, sdk.ZeroDec(), swapFee, weightBalanceBonus)
_, err = k.UpdatePoolForSwap(ctx, pool, sender, recipient, tokenIn, tokenOutCoin, sdk.ZeroDec(), swapFee, weightBalanceBonus)
if err != nil {
return math.Int{}, err
}
Expand All @@ -71,5 +71,5 @@ func (k Keeper) SwapExactAmountIn(
k.TrackSlippage(ctx, pool.PoolId, sdk.NewCoin(tokenOutCoin.Denom, slippageAmount.RoundInt()))

// Subtract swap out fee from the token out amount.
return tokenOutAmount.Sub(swapOutFee), nil
return tokenOutAmount, nil
}
2 changes: 1 addition & 1 deletion x/amm/keeper/keeper_swap_exact_amount_in_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (suite *KeeperTestSuite) TestSwapExactAmountIn() {
swapFeeOut: sdk.ZeroDec(),
tokenIn: sdk.NewInt64Coin("uusda", 10000),
tokenOutMin: sdk.ZeroInt(),
tokenOut: sdk.NewInt64Coin(ptypes.BaseCurrency, 9704),
tokenOut: sdk.NewInt64Coin(ptypes.BaseCurrency, 9802),
weightBalanceBonus: sdk.ZeroDec(),
isOraclePool: false,
useNewRecipient: false,
Expand Down
2 changes: 1 addition & 1 deletion x/amm/keeper/msg_server_swap_by_denom_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func (suite *KeeperTestSuite) TestMsgServerSwapByDenom() {
swapFee: sdk.NewDecWithPrec(1, 2), // 1%
tokenIn: sdk.NewInt64Coin(ptypes.Elys, 10000),
tokenOutMin: sdk.ZeroInt(),
tokenOut: sdk.NewInt64Coin(ptypes.BaseCurrency, 9704),
tokenOut: sdk.NewInt64Coin(ptypes.BaseCurrency, 9802),
expSenderBalance: sdk.Coins{sdk.NewInt64Coin(ptypes.Elys, 990000), sdk.NewInt64Coin(ptypes.BaseCurrency, 1009704)},
expPass: true,
},
Expand Down
2 changes: 1 addition & 1 deletion x/amm/keeper/msg_server_swap_exact_amount_in_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (suite *KeeperTestSuite) TestMsgServerSwapExactAmountIn() {
swapFee: sdk.NewDecWithPrec(1, 2), // 1%
tokenIn: sdk.NewInt64Coin(ptypes.Elys, 10000),
tokenOutMin: sdk.ZeroInt(),
tokenOut: sdk.NewInt64Coin(ptypes.BaseCurrency, 9704),
tokenOut: sdk.NewInt64Coin(ptypes.BaseCurrency, 9802),
swapRoute: []types.SwapAmountInRoute{
{
PoolId: 1,
Expand Down
2 changes: 1 addition & 1 deletion x/amm/keeper/route_exact_amount_in_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func (suite *KeeperTestSuite) TestRouteExactAmountIn() {
swapFeeOut: sdk.ZeroDec(),
tokenIn: sdk.NewInt64Coin(ptypes.Elys, 10000),
tokenOutMin: sdk.ZeroInt(),
tokenOut: sdk.NewInt64Coin(ptypes.BaseCurrency, 9704),
tokenOut: sdk.NewInt64Coin(ptypes.BaseCurrency, 9802),
weightBalanceBonus: sdk.ZeroDec(),
expSenderBalance: sdk.Coins{sdk.NewInt64Coin(ptypes.Elys, 990000), sdk.NewInt64Coin(ptypes.BaseCurrency, 1009704)},
expPoolBalance: sdk.Coins{sdk.NewInt64Coin(ptypes.Elys, 1010000), sdk.NewInt64Coin(ptypes.BaseCurrency, 990198)},
Expand Down
9 changes: 6 additions & 3 deletions x/amm/types/calc_out_amt_given_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ func (p Pool) CalcOutAmtGivenIn(

poolTokenOutBalance := sdk.NewDecFromInt(poolAssetOut.Token.Amount)
// accounted pool balance
acountedPoolAssetOutAmt := accountedPool.GetAccountedBalance(ctx, p.PoolId, poolAssetOut.Token.Denom)
if acountedPoolAssetOutAmt.IsPositive() {
poolTokenOutBalance = sdk.NewDecFromInt(acountedPoolAssetOutAmt)
accountedPoolAssetOutAmt := accountedPool.GetAccountedBalance(ctx, p.PoolId, poolAssetOut.Token.Denom)
if accountedPoolAssetOutAmt.IsPositive() {
poolTokenOutBalance = sdk.NewDecFromInt(accountedPoolAssetOutAmt)
}

poolPostSwapInBalance := poolTokenInBalance.Add(tokenAmountInAfterFee)
Expand All @@ -42,6 +42,9 @@ func (p Pool) CalcOutAmtGivenIn(
inWeight := sdk.NewDecFromInt(poolAssetIn.Weight)
if p.PoolParams.UseOracle {
_, poolAssetIn, poolAssetOut, err := snapshot.parsePoolAssets(tokensIn, tokenOutDenom)
if err != nil {
return sdk.Coin{}, err
}
oracleWeights, err := OraclePoolNormalizedWeights(ctx, oracle, []PoolAsset{poolAssetIn, poolAssetOut})
if err != nil {
return sdk.Coin{}, err
Expand Down
6 changes: 0 additions & 6 deletions x/incentive/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,6 @@ func (k Keeper) UpdateStakersRewardsUnclaimed(ctx sdk.Context, stakeIncentive ty
// Calculate new unclaimed Eden tokens from Elys staked
// ----------------------------------------------------------
newUnclaimedEdenTokens, dexRewards, dexRewardsByStakers := k.CalculateRewardsForStakersByElysStaked(ctx, delegatedAmt, stakersEdenAmountPerDistribution, dexRevenueStakersAmtPerDistribution)
fmt.Println("newUnclaimedEdenTokens1", newUnclaimedEdenTokens.String())

// Total
totalEdenGiven = totalEdenGiven.Add(newUnclaimedEdenTokens)
Expand All @@ -201,7 +200,6 @@ func (k Keeper) UpdateStakersRewardsUnclaimed(ctx sdk.Context, stakeIncentive ty
// ----------------------------------------------------------
edenCommitted := commitments.GetCommittedAmountForDenom(ptypes.Eden)
newUnclaimedEdenTokens, dexRewards = k.CalculateRewardsForStakersByCommitted(ctx, edenCommitted, stakersEdenAmountPerDistribution, dexRevenueStakersAmtPerDistribution)
fmt.Println("newUnclaimedEdenTokens2", newUnclaimedEdenTokens.String())

// Total
totalEdenGiven = totalEdenGiven.Add(newUnclaimedEdenTokens)
Expand All @@ -222,7 +220,6 @@ func (k Keeper) UpdateStakersRewardsUnclaimed(ctx sdk.Context, stakeIncentive ty
// ----------------------------------------------------------
edenBoostCommitted := commitments.GetCommittedAmountForDenom(ptypes.EdenB)
newUnclaimedEdenTokens, dexRewards = k.CalculateRewardsForStakersByCommitted(ctx, edenBoostCommitted, stakersEdenAmountPerDistribution, dexRevenueStakersAmtPerDistribution)
fmt.Println("newUnclaimedEdenTokens3", newUnclaimedEdenTokens.String())

// Total
totalEdenGiven = totalEdenGiven.Add(newUnclaimedEdenTokens)
Expand Down Expand Up @@ -286,9 +283,6 @@ func (k Keeper) UpdateStakersRewardsUnclaimed(ctx sdk.Context, stakeIncentive ty
)

// Calcualte the remainings
fmt.Println("totalEdenGiven", totalEdenGiven.String())
fmt.Println("stakersEdenAmountPerDistribution", stakersEdenAmountPerDistribution.String())

edenRemained := stakersEdenAmountPerDistribution.Sub(totalEdenGiven)
dexRewardsRemained := dexRevenueStakersAmtPerDistribution.Sub(sdk.NewDecFromInt(totalRewardsGiven))

Expand Down
8 changes: 0 additions & 8 deletions x/incentive/keeper/params.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package keeper

import (
"fmt"

"cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
ammtypes "github.com/elys-network/elys/x/amm/types"
Expand Down Expand Up @@ -191,8 +189,6 @@ func (k Keeper) CalculateEpochCountsPerYear(ctx sdk.Context, epochIdentifier str
func (k Keeper) UpdateTotalCommitmentInfo(ctx sdk.Context, baseCurrency string) {
// Fetch total staked Elys amount again
k.tci.TotalElysBonded = k.stk.TotalBondedTokens(ctx)
fmt.Println("TotalElysBonded", k.tci.TotalElysBonded.String())

// Initialize with amount zero
k.tci.TotalEdenEdenBoostCommitted = sdk.ZeroInt()
// Initialize with amount zero
Expand All @@ -215,9 +211,6 @@ func (k Keeper) UpdateTotalCommitmentInfo(ctx sdk.Context, baseCurrency string)

k.tci.TotalEdenEdenBoostCommitted = k.tci.TotalEdenEdenBoostCommitted.Add(committedEdenToken).Add(committedEdenBoostToken)

fmt.Println("commitment.owner", commitments.Creator)
fmt.Println("committedEdenToken", committedEdenToken.String())
fmt.Println("committedEdenBoostToken", committedEdenBoostToken.String())
// Iterate to calculate total Lp tokens committed
k.amm.IterateLiquidityPools(ctx, func(p ammtypes.Pool) bool {
lpToken := ammtypes.GetPoolShareDenom(p.GetPoolId())
Expand All @@ -243,5 +236,4 @@ func (k Keeper) UpdateTotalCommitmentInfo(ctx sdk.Context, baseCurrency string)
}
return false
})
fmt.Println("TotalEdenEdenBoostCommitted", k.tci.TotalEdenEdenBoostCommitted.String())
}
2 changes: 1 addition & 1 deletion x/perpetual/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ func (k Keeper) CheckMinLiabilities(ctx sdk.Context, collateralAmount sdk.Coin,

borrowInterestNew := borrowInterestRational.Num().Quo(borrowInterestRational.Num(), borrowInterestRational.Denom())
samplePayment := sdk.NewInt(borrowInterestNew.Int64())
if samplePayment.IsZero() && !minBorrowInterestRate.IsZero() {
if samplePayment.IsZero() {
return types.ErrBorrowTooLow
}

Expand Down
6 changes: 5 additions & 1 deletion x/perpetual/keeper/query_open_estimation.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,14 @@ func (k Keeper) OpenEstimation(goCtx context.Context, req *types.QueryOpenEstima
return nil, err
}

// invert openPrice
openPrice = sdk.OneDec().Quo(openPrice)

// calculate estimated pnl
// estimated_pnl = leveraged_amount * (take_profit_price - open_price)
// estimated_pnl = leveraged_amount * (take_profit_price - open_price) - leveraged_amount
estimatedPnL := sdk.NewDecFromBigInt(leveragedAmount.BigInt())
estimatedPnL = estimatedPnL.Mul(req.TakeProfitPrice.Sub(openPrice))
estimatedPnL = estimatedPnL.Sub(sdk.NewDecFromBigInt(leveragedAmount.BigInt()))
estimatedPnLInt := estimatedPnL.TruncateInt()

if leveragedAmount.IsZero() {
Expand Down
10 changes: 4 additions & 6 deletions x/perpetual/keeper/query_open_estimation_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package keeper_test

import (
"fmt"
"testing"

sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -87,21 +86,20 @@ func TestOpenEstimation_Long5XAtom100Usdc(t *testing.T) {
TakeProfitPrice: sdk.MustNewDecFromStr("2.0"),
})
require.NoError(t, err)
fmt.Println(res)
require.Equal(t, &types.QueryOpenEstimationResponse{
Position: types.Position_LONG,
Leverage: sdk.MustNewDecFromStr("5.0"),
TradingAsset: ptypes.ATOM,
Collateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(100000000)),
MinCollateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(8333333)),
ValidCollateral: true,
PositionSize: sdk.NewCoin(ptypes.ATOM, sdk.NewInt(496520381)),
PositionSize: sdk.NewCoin(ptypes.ATOM, sdk.NewInt(497017398)),
SwapFee: sdk.MustNewDecFromStr("0.001000000000000000"),
Discount: sdk.MustNewDecFromStr("0.000000000000000000"),
OpenPrice: sdk.MustNewDecFromStr("0.993040762000000000"),
OpenPrice: sdk.MustNewDecFromStr("1.006001001196340415"),
TakeProfitPrice: sdk.MustNewDecFromStr("2.000000000000000000"),
LiquidationPrice: sdk.MustNewDecFromStr("0.793040762000000000"),
EstimatedPnl: sdk.NewInt(503479619),
LiquidationPrice: sdk.MustNewDecFromStr("0.806001001196340415"),
EstimatedPnl: sdk.NewInt(-3000500),
AvailableLiquidity: sdk.NewCoin(ptypes.ATOM, sdk.NewInt(100000000000)),
WeightBalanceRatio: sdk.MustNewDecFromStr("0.000000000000000000"),
BorrowInterestRate: sdk.MustNewDecFromStr("0.000000000000000000"),
Expand Down
2 changes: 2 additions & 0 deletions x/perpetual/types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ func NewMTP(signer, collateralAsset, tradingAsset, liabilitiesAsset, custodyAsse
Leverage: leverage,
MtpHealth: sdk.ZeroDec(),
Position: position,
Id: 0,
AmmPoolId: poolId,
ConsolidateLeverage: leverage,
SumCollateral: sdk.ZeroInt(),
Expand All @@ -44,6 +45,7 @@ func NewMTP(signer, collateralAsset, tradingAsset, liabilitiesAsset, custodyAsse
FundingFeePaidCustody: sdk.ZeroInt(),
FundingFeeReceivedCollateral: sdk.ZeroInt(),
FundingFeeReceivedCustody: sdk.ZeroInt(),
OpenPrice: sdk.ZeroDec(),
}
}

Expand Down

0 comments on commit b8611af

Please sign in to comment.