Skip to content

Commit

Permalink
refactor: use builtin coins method instead of asset index
Browse files Browse the repository at this point in the history
  • Loading branch information
cosmic-vagabond committed Nov 29, 2023
1 parent 2c0f700 commit e8c9928
Show file tree
Hide file tree
Showing 11 changed files with 153 additions and 163 deletions.
30 changes: 20 additions & 10 deletions proto/elys/margin/types.proto
Original file line number Diff line number Diff line change
Expand Up @@ -16,30 +16,36 @@ enum Position {
message MTP {
string address = 1;
repeated cosmos.base.v1beta1.Coin collaterals = 2 [
(gogoproto.nullable) = false
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
string liabilities = 3 [
(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int",
(gogoproto.nullable) = false
];
repeated cosmos.base.v1beta1.Coin borrow_interest_paid_collaterals = 4 [
(gogoproto.nullable) = false
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
repeated cosmos.base.v1beta1.Coin borrow_interest_paid_custodies = 5 [
(gogoproto.nullable) = false
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
repeated cosmos.base.v1beta1.Coin borrow_interest_unpaid_collaterals = 6 [
(gogoproto.nullable) = false
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
repeated cosmos.base.v1beta1.Coin custodies = 7 [
(gogoproto.nullable) = false
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
string take_profit_liabilities = 8 [
(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int",
(gogoproto.nullable) = false
];
repeated cosmos.base.v1beta1.Coin take_profit_custodies = 9 [
(gogoproto.nullable) = false
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
repeated string leverages = 10 [
(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",
Expand Down Expand Up @@ -70,17 +76,21 @@ message MTP {
];
// funding fee paid
repeated cosmos.base.v1beta1.Coin funding_fee_paid_collaterals = 19 [
(gogoproto.nullable) = false
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
repeated cosmos.base.v1beta1.Coin funding_fee_paid_custodies = 20 [
(gogoproto.nullable) = false
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
// funding fee received
repeated cosmos.base.v1beta1.Coin funding_fee_received_collaterals = 21 [
(gogoproto.nullable) = false
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
repeated cosmos.base.v1beta1.Coin funding_fee_received_custodies = 22 [
(gogoproto.nullable) = false
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
}

Expand Down
7 changes: 3 additions & 4 deletions x/margin/keeper/calc_mtp_interest_liabilities.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,13 @@ func (k Keeper) CalcMTPBorrowInterestLiabilities(ctx sdk.Context, mtp *types.MTP

rate.SetFloat64(borrowInterestRate.MustFloat64())

collateralIndex, _ := types.GetMTPAssetIndex(mtp, collateralAsset, "")
unpaidCollaterals := sdk.ZeroInt()
// Calculate collateral borrow interests in base currency
if mtp.Collaterals[collateralIndex].Denom == baseCurrency {
unpaidCollaterals = unpaidCollaterals.Add(mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount)
if collateralAsset == baseCurrency {
unpaidCollaterals = unpaidCollaterals.Add(mtp.BorrowInterestUnpaidCollaterals.AmountOf(collateralAsset))
} else {
// Liability is in base currency, so convert it to base currency
unpaidCollateralIn := sdk.NewCoin(mtp.Collaterals[collateralIndex].Denom, mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount)
unpaidCollateralIn := sdk.NewCoin(collateralAsset, mtp.BorrowInterestUnpaidCollaterals.AmountOf(collateralAsset))
C, err := k.EstimateSwapGivenOut(ctx, unpaidCollateralIn, baseCurrency, ammPool)
if err != nil {
return sdk.ZeroInt(), err
Expand Down
8 changes: 5 additions & 3 deletions x/margin/keeper/estimate_and_repay.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import (
)

func (k Keeper) EstimateAndRepay(ctx sdk.Context, mtp types.MTP, pool types.Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string) (sdk.Int, error) {
collateralIndex, custodyIndex := types.GetMTPAssetIndex(&mtp, collateralAsset, custodyAsset)
cutodyAmtTokenIn := sdk.NewCoin(mtp.Custodies[custodyIndex].Denom, mtp.Custodies[custodyIndex].Amount)
repayAmount, err := k.EstimateSwap(ctx, cutodyAmtTokenIn, mtp.Collaterals[collateralIndex].Denom, ammPool)
ok, custodyAmtTokemIn := mtp.Custodies.Find(custodyAsset)
if !ok {
return sdk.ZeroInt(), types.ErrDenomNotFound
}
repayAmount, err := k.EstimateSwap(ctx, custodyAmtTokemIn, collateralAsset, ammPool)
if err != nil {
return sdk.ZeroInt(), err
}
Expand Down
22 changes: 10 additions & 12 deletions x/margin/keeper/handle_borrow_interest_payment.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,22 @@ func (k Keeper) HandleBorrowInterestPayment(ctx sdk.Context, collateralAsset str
return finalBorrowInterestPayment
}
} else { // else update unpaid mtp interest
collateralIndex, _ := types.GetMTPAssetIndex(mtp, collateralAsset, "")
if collateralIndex < 0 {
return sdk.ZeroInt()
}

// collateralAsset is in base currency
if mtp.Collaterals[collateralIndex].Denom == baseCurrency {
mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount = borrowInterestPayment
} else {
// collateralAsset is not in base currency
if collateralAsset != baseCurrency {
// swap
amtTokenIn := sdk.NewCoin(baseCurrency, borrowInterestPayment)
borrowInterestPayment, err := k.EstimateSwap(ctx, amtTokenIn, collateralAsset, ammPool) // may need spot price here to not deduct fee
var err error
borrowInterestPayment, err = k.EstimateSwap(ctx, amtTokenIn, collateralAsset, ammPool) // may need spot price here to not deduct fee
if err != nil {
return sdk.ZeroInt()
}

mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount = borrowInterestPayment
}

mtp.BorrowInterestUnpaidCollaterals = mtp.BorrowInterestUnpaidCollaterals.Sub(
sdk.NewCoin(collateralAsset, mtp.BorrowInterestUnpaidCollaterals.AmountOf(collateralAsset)),
).Add(
sdk.NewCoin(collateralAsset, borrowInterestPayment),
)
}
return sdk.ZeroInt()
}
15 changes: 9 additions & 6 deletions x/margin/keeper/handle_funding_fee_collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,14 @@ func (k Keeper) HandleFundingFeeCollection(ctx sdk.Context, mtp *types.MTP, pool
return nil
}

// get indexes
collateralIndex, custodyIndex := types.GetMTPAssetIndex(mtp, collateralAsset, custodyAsset)
// get custody coin
ok, custodyAmt := mtp.Custodies.Find(custodyAsset)
if !ok {
return types.ErrDenomNotFound
}

// Calculate the take amount in custody asset
takeAmountCustody := types.CalcTakeAmount(mtp.Custodies[custodyIndex], custodyAsset, fundingRate)
takeAmountCustody := types.CalcTakeAmount(custodyAmt, custodyAsset, fundingRate)

// Swap the take amount to collateral asset
takeAmountCollateralAmount, err := k.EstimateSwap(ctx, takeAmountCustody, collateralAsset, ammPool)
Expand All @@ -46,13 +49,13 @@ func (k Keeper) HandleFundingFeeCollection(ctx sdk.Context, mtp *types.MTP, pool
}

// update mtp custody
mtp.Custodies[custodyIndex] = mtp.Custodies[custodyIndex].Sub(takeAmountCustody)
mtp.Custodies = mtp.Custodies.Sub(takeAmountCustody)

// add payment to total funding fee paid in collateral asset
mtp.FundingFeePaidCollaterals[collateralIndex] = mtp.FundingFeePaidCollaterals[collateralIndex].Add(takeAmountCollateral)
mtp.FundingFeePaidCollaterals = mtp.FundingFeePaidCollaterals.Add(takeAmountCollateral)

// add payment to total funding fee paid in custody asset
mtp.FundingFeePaidCustodies[custodyIndex] = mtp.FundingFeePaidCustodies[custodyIndex].Add(takeAmountCustody)
mtp.FundingFeePaidCustodies = mtp.FundingFeePaidCustodies.Add(takeAmountCustody)

// emit event
if !takeAmountCollateral.IsZero() {
Expand Down
56 changes: 26 additions & 30 deletions x/margin/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,14 +166,9 @@ func (k Keeper) Borrow(ctx sdk.Context, collateralAsset string, custodyAsset str
liabilitiesDec = sdk.NewDecFromInt(liabilityAmt)
}

collateralIndex, custodyIndex := types.GetMTPAssetIndex(mtp, collateralAsset, custodyAsset)
if collateralIndex < 0 || custodyIndex < 0 {
return sdkerrors.Wrap(types.ErrBalanceNotAvailable, "MTP collateral or custody invalid!")
}

mtp.Collaterals[collateralIndex].Amount = mtp.Collaterals[collateralIndex].Amount.Add(collateralAmount)
mtp.Collaterals = mtp.Collaterals.Add(sdk.NewCoin(collateralAsset, collateralAmount))
mtp.Liabilities = mtp.Liabilities.Add(sdk.NewIntFromBigInt(liabilitiesDec.TruncateInt().BigInt()))
mtp.Custodies[custodyIndex].Amount = mtp.Custodies[custodyIndex].Amount.Add(custodyAmount)
mtp.Custodies = mtp.Custodies.Add(sdk.NewCoin(custodyAsset, custodyAmount))

// calculate mtp take profit custody, delta y_tp_c = delta x_l / take profit price (take profit custody = liabilities / take profit price)
mtp.TakeProfitCustodies = types.CalcMTPTakeProfitCustodies(mtp)
Expand All @@ -186,9 +181,6 @@ func (k Keeper) Borrow(ctx sdk.Context, collateralAsset string, custodyAsset str

mtp.Leverages = append(mtp.Leverages, eta.Add(sdk.OneDec()))

// print mtp.CustodyAmount
ctx.Logger().Info(fmt.Sprintf("mtp.CustodyAmount: %s", mtp.Custodies[custodyIndex].Amount.String()))

h, err := k.UpdateMTPHealth(ctx, *mtp, *ammPool, baseCurrency) // set mtp in func or return h?
if err != nil {
return err
Expand Down Expand Up @@ -225,7 +217,7 @@ func (k Keeper) Borrow(ctx sdk.Context, collateralAsset string, custodyAsset str
}

// All take profit custody has to be in base currency
err = pool.UpdateTakeProfitCustody(ctx, baseCurrency, mtp.TakeProfitCustodies[custodyIndex].Amount, true, mtp.Position)
err = pool.UpdateTakeProfitCustody(ctx, baseCurrency, mtp.TakeProfitCustodies.AmountOf(custodyAsset), true, mtp.Position)
if err != nil {
return err
}
Expand Down Expand Up @@ -296,15 +288,13 @@ func (k Keeper) TakeInCustody(ctx sdk.Context, mtp types.MTP, pool *types.Pool)
}

func (k Keeper) IncrementalBorrowInterestPayment(ctx sdk.Context, collateralAsset string, custodyAsset string, borrowInterestPayment sdk.Int, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) (sdk.Int, error) {
collateralIndex, custodyIndex := types.GetMTPAssetIndex(mtp, collateralAsset, custodyAsset)

// if mtp has unpaid borrow interest, add to payment
// convert it into base currency
if mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount.GT(sdk.ZeroInt()) {
if mtp.Collaterals[collateralIndex].Denom == baseCurrency {
borrowInterestPayment = borrowInterestPayment.Add(mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount)
if mtp.BorrowInterestUnpaidCollaterals.AmountOf(collateralAsset).IsPositive() {
if collateralAsset == baseCurrency {
borrowInterestPayment = borrowInterestPayment.Add(mtp.BorrowInterestUnpaidCollaterals.AmountOf(collateralAsset))
} else {
unpaidCollateralIn := sdk.NewCoin(mtp.Collaterals[collateralIndex].Denom, mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount)
unpaidCollateralIn := sdk.NewCoin(collateralAsset, mtp.BorrowInterestUnpaidCollaterals.AmountOf(collateralAsset))
C, err := k.EstimateSwapGivenOut(ctx, unpaidCollateralIn, baseCurrency, ammPool)
if err != nil {
return sdk.ZeroInt(), err
Expand All @@ -316,7 +306,7 @@ func (k Keeper) IncrementalBorrowInterestPayment(ctx sdk.Context, collateralAsse

borrowInterestPaymentTokenIn := sdk.NewCoin(baseCurrency, borrowInterestPayment)
// swap borrow interest payment to custody asset for payment
borrowInterestPaymentCustody, err := k.EstimateSwap(ctx, borrowInterestPaymentTokenIn, mtp.Custodies[custodyIndex].Denom, ammPool)
borrowInterestPaymentCustody, err := k.EstimateSwap(ctx, borrowInterestPaymentTokenIn, custodyAsset, ammPool)
if err != nil {
return sdk.ZeroInt(), err
}
Expand All @@ -332,49 +322,55 @@ func (k Keeper) IncrementalBorrowInterestPayment(ctx sdk.Context, collateralAsse
}

// if paying unpaid borrow interest reset to 0
mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount = sdk.ZeroInt()
mtp.BorrowInterestUnpaidCollaterals = mtp.BorrowInterestUnpaidCollaterals.Sub(
sdk.NewCoin(collateralAsset, mtp.BorrowInterestUnpaidCollaterals.AmountOf(collateralAsset)),
)

// edge case, not enough custody to cover payment
if borrowInterestPaymentCustody.GT(mtp.Custodies[custodyIndex].Amount) {
if borrowInterestPaymentCustody.GT(mtp.Custodies.AmountOf(custodyAsset)) {
// swap custody amount to collateral for updating borrow interest unpaid
custodyAmtTokenIn := sdk.NewCoin(mtp.Custodies[custodyIndex].Denom, mtp.Custodies[custodyIndex].Amount)
custodyAmtTokenIn := sdk.NewCoin(custodyAsset, mtp.Custodies.AmountOf(custodyAsset))
custodyAmountCollateral, err := k.EstimateSwap(ctx, custodyAmtTokenIn, collateralAsset, ammPool) // may need spot price here to not deduct fee
if err != nil {
return sdk.ZeroInt(), err
}
mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount = borrowInterestPayment.Sub(custodyAmountCollateral)
mtp.BorrowInterestUnpaidCollaterals = mtp.BorrowInterestUnpaidCollaterals.Add(
sdk.NewCoin(collateralAsset, borrowInterestPayment),
).Sub(
sdk.NewCoin(collateralAsset, custodyAmountCollateral),
)

borrowInterestPayment = custodyAmountCollateral
borrowInterestPaymentCustody = mtp.Custodies[custodyIndex].Amount
borrowInterestPaymentCustody = mtp.Custodies.AmountOf(custodyAsset)
}

// add payment to total paid - collateral
mtp.BorrowInterestPaidCollaterals[collateralIndex].Amount = mtp.BorrowInterestPaidCollaterals[collateralIndex].Amount.Add(borrowInterestPayment)
mtp.BorrowInterestPaidCollaterals = mtp.BorrowInterestPaidCollaterals.Add(sdk.NewCoin(collateralAsset, borrowInterestPayment))

// add payment to total paid - custody
mtp.BorrowInterestPaidCustodies[custodyIndex].Amount = mtp.BorrowInterestPaidCustodies[custodyIndex].Amount.Add(borrowInterestPaymentCustody)
mtp.BorrowInterestPaidCustodies = mtp.BorrowInterestPaidCustodies.Add(sdk.NewCoin(custodyAsset, borrowInterestPaymentCustody))

// deduct borrow interest payment from custody amount
mtp.Custodies[custodyIndex].Amount = mtp.Custodies[custodyIndex].Amount.Sub(borrowInterestPaymentCustody)
mtp.Custodies = mtp.Custodies.Sub(sdk.NewCoin(custodyAsset, borrowInterestPaymentCustody))

takePercentage := k.GetIncrementalBorrowInterestPaymentFundPercentage(ctx)
fundAddr := k.GetIncrementalBorrowInterestPaymentFundAddress(ctx)
takeAmount, err := k.TakeFundPayment(ctx, borrowInterestPaymentCustody, mtp.Custodies[custodyIndex].Denom, takePercentage, fundAddr, &ammPool)
takeAmount, err := k.TakeFundPayment(ctx, borrowInterestPaymentCustody, custodyAsset, takePercentage, fundAddr, &ammPool)
if err != nil {
return sdk.ZeroInt(), err
}
actualBorrowInterestPaymentCustody := borrowInterestPaymentCustody.Sub(takeAmount)

if !takeAmount.IsZero() {
k.EmitFundPayment(ctx, mtp, takeAmount, mtp.Custodies[custodyIndex].Denom, types.EventIncrementalPayFund)
k.EmitFundPayment(ctx, mtp, takeAmount, custodyAsset, types.EventIncrementalPayFund)
}

err = pool.UpdateCustody(ctx, mtp.Custodies[custodyIndex].Denom, borrowInterestPaymentCustody, false, mtp.Position)
err = pool.UpdateCustody(ctx, custodyAsset, borrowInterestPaymentCustody, false, mtp.Position)
if err != nil {
return sdk.ZeroInt(), err
}

err = pool.UpdateBalance(ctx, mtp.Custodies[custodyIndex].Denom, actualBorrowInterestPaymentCustody, true, mtp.Position)
err = pool.UpdateBalance(ctx, custodyAsset, actualBorrowInterestPaymentCustody, true, mtp.Position)
if err != nil {
return sdk.ZeroInt(), err
}
Expand Down
12 changes: 7 additions & 5 deletions x/margin/keeper/repay.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ import (
)

func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, repayAmount sdk.Int, takeFundPayment bool, collateralAsset string) error {
collateralIndex, _ := types.GetMTPAssetIndex(mtp, collateralAsset, "")
// nolint:staticcheck,ineffassign
returnAmount := sdk.ZeroInt()
Liabilities := mtp.Liabilities
BorrowInterestUnpaidCollateral := mtp.BorrowInterestUnpaidCollaterals[collateralIndex]
ok, BorrowInterestUnpaidCollateral := mtp.BorrowInterestUnpaidCollaterals.Find(collateralAsset)
if !ok {
return types.ErrDenomNotFound
}

entry, found := k.apKeeper.GetEntry(ctx, ptypes.BaseCurrency)
if !found {
Expand All @@ -24,7 +26,7 @@ func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool

if collateralAsset != baseCurrency {
// swap to base currency
unpaidCollateralIn := sdk.NewCoin(mtp.Collaterals[collateralIndex].Denom, mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount)
unpaidCollateralIn := sdk.NewCoin(collateralAsset, mtp.BorrowInterestUnpaidCollaterals.AmountOf(collateralAsset))
C, err := k.EstimateSwapGivenOut(ctx, unpaidCollateralIn, baseCurrency, ammPool)
if err != nil {
return err
Expand Down Expand Up @@ -115,7 +117,7 @@ func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool
returnAmount = C
}

err = pool.UpdateBalance(ctx, mtp.Collaterals[collateralIndex].Denom, returnAmount, false, mtp.Position)
err = pool.UpdateBalance(ctx, collateralAsset, returnAmount, false, mtp.Position)
if err != nil {
return err
}
Expand All @@ -131,7 +133,7 @@ func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool
return err
}

err = pool.UpdateTakeProfitCustody(ctx, baseCurrency, mtp.TakeProfitCustodies[collateralIndex].Amount, false, mtp.Position)
err = pool.UpdateTakeProfitCustody(ctx, baseCurrency, mtp.TakeProfitCustodies.AmountOf(collateralAsset), false, mtp.Position)
if err != nil {
return err
}
Expand Down
5 changes: 2 additions & 3 deletions x/margin/keeper/take_out_custody.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ import (
)

func (k Keeper) TakeOutCustody(ctx sdk.Context, mtp types.MTP, pool *types.Pool, custodyAsset string) error {
_, custodyIndex := types.GetMTPAssetIndex(&mtp, "", custodyAsset)
err := pool.UpdateBalance(ctx, mtp.Custodies[custodyIndex].Denom, mtp.Custodies[custodyIndex].Amount, true, mtp.Position)
err := pool.UpdateBalance(ctx, custodyAsset, mtp.Custodies.AmountOf(custodyAsset), true, mtp.Position)
if err != nil {
return err
}

err = pool.UpdateCustody(ctx, mtp.Custodies[custodyIndex].Denom, mtp.Custodies[custodyIndex].Amount, false, mtp.Position)
err = pool.UpdateCustody(ctx, custodyAsset, mtp.Custodies.AmountOf(custodyAsset), false, mtp.Position)
if err != nil {
return err
}
Expand Down
1 change: 1 addition & 0 deletions x/margin/types/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ var (
ErrBalanceNotAvailable = sdkerrors.Register(ModuleName, 18, "user does not have enough balance of the required coin")
ErrAmountTooLow = sdkerrors.Register(ModuleName, 32, "Tx amount is too low")
ErrMarginDisabled = sdkerrors.Register(ModuleName, 33, "margin disabled pool")
ErrDenomNotFound = sdkerrors.Register(ModuleName, 34, "denom not found")
)
22 changes: 0 additions & 22 deletions x/margin/types/get_mtp_asset_index.go

This file was deleted.

Loading

0 comments on commit e8c9928

Please sign in to comment.