Skip to content

Commit

Permalink
Jkl 119 clean withdraw and deposit tx code (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
dahn510 authored Oct 14, 2022
2 parents 0553b3d + b05661d commit da46e65
Show file tree
Hide file tree
Showing 21 changed files with 384 additions and 339 deletions.
6 changes: 3 additions & 3 deletions docs/static/openapi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58950,7 +58950,9 @@ definitions:
id:
type: string
title: Pool id
jackaldao.canine.lp.MsgDepositLPoolResponse:
jackaldao.canine.lp.MsgExitPoolResponse:
type: object
jackaldao.canine.lp.MsgJoinPoolResponse:
type: object
properties:
shares:
Expand All @@ -58959,8 +58961,6 @@ definitions:
description: Amount of shares given to pool contributor.
jackaldao.canine.lp.MsgSwapResponse:
type: object
jackaldao.canine.lp.MsgWithdrawLPoolResponse:
type: object
jackaldao.canine.lp.Params:
type: object
properties:
Expand Down
14 changes: 7 additions & 7 deletions proto/lp/tx.proto
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ option go_package = "github.com/jackal-dao/canine/x/lp/types";

// Msg defines the Msg service.
service Msg {
rpc CreateLPool(MsgCreateLPool) returns (MsgCreateLPoolResponse);
rpc DepositLPool(MsgDepositLPool) returns (MsgDepositLPoolResponse);
rpc WithdrawLPool(MsgWithdrawLPool) returns (MsgWithdrawLPoolResponse);
rpc CreateLPool(MsgCreateLPool) returns (MsgCreateLPoolResponse);
rpc JoinPool(MsgJoinPool) returns (MsgJoinPoolResponse);
rpc ExitPool(MsgExitPool) returns (MsgExitPoolResponse);
rpc Swap(MsgSwap) returns (MsgSwapResponse);
// this line is used by starport scaffolding # proto/tx/rpc
}
Expand Down Expand Up @@ -42,7 +42,7 @@ message MsgCreateLPoolResponse {
string id = 1;
}

message MsgDepositLPool {
message MsgJoinPool {
string creator = 1;
string poolName = 2;
// Input format:
Expand All @@ -52,18 +52,18 @@ message MsgDepositLPool {
int64 lockDuration = 4;
}

message MsgDepositLPoolResponse {
message MsgJoinPoolResponse {
// Amount of shares given to pool contributor.
uint64 shares = 1;
}

message MsgWithdrawLPool {
message MsgExitPool {
string creator = 1;
string poolName = 2;
int64 shares = 3;
}

message MsgWithdrawLPoolResponse {
message MsgExitPoolResponse {
}

message MsgSwap {
Expand Down
20 changes: 10 additions & 10 deletions x/lp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ parent:
+ [params](#params)
+ [Transactions](#transactions)
+ [create-l-pool](#create-l-pool)
+ [deposit-l-pool](#deposit-l-pool)
+ [withdraw-l-pool](#withdraw-l-pool)
+ [join-pool](#join-pool)
+ [exit-pool](#exit-pool)
+ [swap](#swap)
3. [Development](#development)
+ [Todo](#todo)
Expand Down Expand Up @@ -116,35 +116,35 @@ canined tx lp create-l-pool [pool-coins] [invariant model id] \
"swap-fee-percentage" [pool-lock-time] "withdraw-penalty-percentage"
```

#### deposit-l-pool
#### join-pool

The `deposit-l-pool` command allows users to contribute to a pool and receive
The `join-pool` command allows users to contribute to a pool and receive
liquidity pool token.
Expected format for `[deposit-coins]` (omit curly brackets): "{denom0}{amount0}
...{denomN}{amountN}"

```sh
canined tx lp deposit-l-pool "pool-name" [deposit-coins]
canined tx lp join-pool "pool-name" [deposit-coins]
```

#### withdraw-l-pool
#### exit-pool

The `withdraw-l-pool` command allows users to burn their liquidity pool token
The `exit-pool` command allows users to burn their liquidity pool token
to receive pool coins.
The `[burn-amount]` is an integer.

```sh
canined tx withdraw-l-pool "pool-name" [burn-amount]
canined tx lp exit-pool "pool-name" [burn-amount]
```

#### swap

The `swap` command allows users to swap token in a liquidity pool.
Expected format for `[deposit-coins]` (omit curly brackets): "{denom0}{amount0}
Expected format for `[swap-in]` (omit curly brackets): "{denom0}{amount0}
...{denomN}{amountN}"

```sh
canined tx withdraw-l-pool "pool-name" [deposit-coins]
canined tx lp swap "pool-name" [swap-in]
```

# Development
Expand Down
4 changes: 2 additions & 2 deletions x/lp/client/cli/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ func GetTxCmd() *cobra.Command {
}

cmd.AddCommand(CmdCreateLPool())
cmd.AddCommand(CmdDepositLPool())
cmd.AddCommand(CmdWithdrawLPool())
cmd.AddCommand(CmdJoinPool())
cmd.AddCommand(CmdExitPool())
cmd.AddCommand(CmdSwap())
// this line is used by starport scaffolding # 1

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ import (

var _ = strconv.Itoa(0)

func CmdDepositLPool() *cobra.Command {
func CmdJoinPool() *cobra.Command {
cmd := &cobra.Command{
Use: "deposit-l-pool \"Pool Name\" \"{amount0}{denom0},...,{amountN}{denomN} ...\" [lock duration (sec)]",
Short: "Broadcast message depositLPool",
Use: "join-pool \"Pool Name\" \"{amount0}{denom0},...,{amountN}{denomN} ...\" [lock duration (sec)]",
Short: "join a liquidity pool by depositing pool coins.\n ",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) (err error) {

Expand All @@ -37,7 +37,7 @@ func CmdDepositLPool() *cobra.Command {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, err.Error())
}

msg := types.NewMsgDepositLPool(
msg := types.NewMsgJoinPool(
clientCtx.GetFromAddress().String(),
args[0],
deposit,
Expand Down
8 changes: 4 additions & 4 deletions x/lp/client/cli/tx_withdraw_l_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import (

var _ = strconv.Itoa(0)

func CmdWithdrawLPool() *cobra.Command {
func CmdExitPool() *cobra.Command {
cmd := &cobra.Command{
Use: "withdraw-l-pool \"Pool Name\" [shares]",
Short: "Broadcast message withdrawLPool",
Use: "exit-pool \"Pool Name\" [burn quantity]",
Short: "exit from liquidity pool by burning liquidity pool token",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) (err error) {

Expand All @@ -29,7 +29,7 @@ func CmdWithdrawLPool() *cobra.Command {
return err
}

msg := types.NewMsgWithdrawLPool(
msg := types.NewMsgExitPool(
clientCtx.GetFromAddress().String(),
args[0],
burnShare,
Expand Down
8 changes: 4 additions & 4 deletions x/lp/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ func NewHandler(k keeper.Keeper) sdk.Handler {
case *types.MsgCreateLPool:
res, err := msgServer.CreateLPool(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *types.MsgDepositLPool:
res, err := msgServer.DepositLPool(sdk.WrapSDKContext(ctx), msg)
case *types.MsgJoinPool:
res, err := msgServer.JoinPool(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *types.MsgWithdrawLPool:
res, err := msgServer.WithdrawLPool(sdk.WrapSDKContext(ctx), msg)
case *types.MsgExitPool:
res, err := msgServer.ExitPool(sdk.WrapSDKContext(ctx), msg)
return sdk.WrapServiceResult(ctx, res, err)
case *types.MsgSwap:
res, err := msgServer.Swap(sdk.WrapSDKContext(ctx), msg)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (k Keeper) EstimateSwapOut(
depositCoins, err := sdk.ParseCoinsNormalized(req.InputCoin)

if err != nil || depositCoins.IsAnyNegative() {
return nil, status.Error(codes.InvalidArgument, "invalid deposit coins")
return nil, status.Error(codes.InvalidArgument, "invalid coinIn")
}

AMM, _ := types.GetAMM(pool.AMM_Id)
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/jackal-dao/canine/x/lp/types"
)

func (k Keeper) validateWithdrawLPool(ctx sdk.Context, msg *types.MsgWithdrawLPool) error {
func (k Keeper) validateExitPool(ctx sdk.Context, msg *types.MsgExitPool) error {
pool, found := k.GetLPool(ctx, msg.PoolName)

if !found {
Expand All @@ -35,11 +35,11 @@ func (k Keeper) validateWithdrawLPool(ctx sdk.Context, msg *types.MsgWithdrawLPo
return nil
}

func (k msgServer) WithdrawLPool(goCtx context.Context, msg *types.MsgWithdrawLPool) (*types.MsgWithdrawLPoolResponse, error) {
func (k msgServer) ExitPool(goCtx context.Context, msg *types.MsgExitPool) (*types.MsgExitPoolResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
creatorAcc, _ := sdk.AccAddressFromBech32(msg.Creator)

if err := k.validateWithdrawLPool(ctx, msg); err != nil {
if err := k.validateExitPool(ctx, msg); err != nil {
return nil, err
}

Expand All @@ -48,7 +48,7 @@ func (k msgServer) WithdrawLPool(goCtx context.Context, msg *types.MsgWithdrawLP
totalShares, _ := sdk.NewIntFromString(pool.LPTokenBalance)

// Calculate tokens to return
// If LPToken is still locked, take panelty.
// If LPToken is still locked, apply panelty.
recordKey := types.LProviderRecordKey(pool.Name, creatorAcc.String())
record, _ := k.GetLProviderRecord(ctx, recordKey)

Expand Down Expand Up @@ -98,7 +98,7 @@ func (k msgServer) WithdrawLPool(goCtx context.Context, msg *types.MsgWithdrawLP
return nil, sdkErr
}

// Finally, burn that LPToken :fire:
// Burn the LPToken
sdkErr = k.bankKeeper.BurnCoins(ctx, types.ModuleName, burningCoins)

if sdkErr != nil {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ package keeper

import (
"context"
"errors"
"fmt"

sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/jackal-dao/canine/x/lp/types"
)

func (k Keeper) validateDepositLPoolMsg(ctx sdk.Context, msg *types.MsgDepositLPool) error {
func (k Keeper) validateJoinPoolMsg(ctx sdk.Context, msg *types.MsgJoinPool) error {
if err := msg.ValidateBasic(); err != nil {
return err
}
Expand All @@ -29,20 +31,38 @@ func (k Keeper) validateDepositLPoolMsg(ctx sdk.Context, msg *types.MsgDepositLP
)
}

// Check if existing record unlock time is later than this message
recordKey := types.LProviderRecordKey(pool.Name, msg.Creator)
record, found := k.GetLProviderRecord(ctx, recordKey)
if found {
oldUnlockTime, _ := StringToTime(record.UnlockTime)

newDuration := GetDuration(msg.LockDuration)

newUnlockTime := ctx.BlockTime().Add(newDuration)

if newUnlockTime.Before(oldUnlockTime) {
return errors.New(
fmt.Sprintf("new unlock time must be after old." +
" new: %s, old %s", TimeToString(newUnlockTime),
TimeToString(oldUnlockTime)))
}
}

return nil
}

func (k msgServer) DepositLPool(goCtx context.Context, msg *types.MsgDepositLPool) (*types.MsgDepositLPoolResponse, error) {
func (k msgServer) JoinPool(goCtx context.Context, msg *types.MsgJoinPool) (*types.MsgJoinPoolResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)

err := k.validateDepositLPoolMsg(ctx, msg)
err := k.validateJoinPoolMsg(ctx, msg)

if err != nil {
return nil, err
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error())
}

// Calculate amount of pool share

// Get amount of LPToken to send
pool, _ := k.GetLPool(ctx, msg.PoolName)

coins := sdk.NormalizeCoins(msg.Coins)
Expand All @@ -53,39 +73,8 @@ func (k msgServer) DepositLPool(goCtx context.Context, msg *types.MsgDepositLPoo
return nil, err
}

// Mint and send pool token to depositor (is that even a word?).

creator, _ := sdk.AccAddressFromBech32(msg.Creator)

// Transfer money from depositor to module account
sdkErr := k.bankKeeper.SendCoinsFromAccountToModule(ctx, creator, types.ModuleName, coins)

if sdkErr != nil {
return nil, sdkErr
}

if err := k.MintAndSendLPToken(ctx, pool, creator, shares); err != nil {
return nil, err
}

// Update pool
poolCoins := sdk.NewCoins(pool.Coins...)

for _, c := range coins {
// This works by comparing denoms in poolCoins and doing addition on the first
// denom match.
poolCoins = poolCoins.Add(c)
}

pool.Coins = poolCoins

poolTotalToken, _ := sdk.NewIntFromString(pool.LPTokenBalance)
poolTotalToken = poolTotalToken.Add(shares)

pool.LPTokenBalance = poolTotalToken.String()

k.SetLPool(ctx, pool)

// Initialize LProviderRecord
lockDuration := GetDuration(msg.LockDuration)

Expand All @@ -106,10 +95,38 @@ func (k msgServer) DepositLPool(goCtx context.Context, msg *types.MsgDepositLPoo
err = k.EngageLock(ctx, recordKey)

if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error())
}

// Transfer liquidity from the creator account to module account
sdkErr := k.bankKeeper.SendCoinsFromAccountToModule(ctx, creator, types.ModuleName, coins)

if sdkErr != nil {
return nil, sdkErr
}

if err := k.MintAndSendLPToken(ctx, pool, creator, shares); err != nil {
return nil, err
}

// Update pool liquidity
poolCoins := sdk.NewCoins(pool.Coins...)
// Add liquidity to pool
for _, c := range coins {
poolCoins = poolCoins.Add(c)
}

pool.Coins = poolCoins

// Update LPTokens
netLPToken, _ := sdk.NewIntFromString(pool.LPTokenBalance)
netLPToken = netLPToken.Add(shares)

pool.LPTokenBalance = netLPToken.String()

k.SetLPool(ctx, pool)

EmitPoolJoinedEvent(ctx, creator, pool, coins, msg.LockDuration)

return &types.MsgDepositLPoolResponse{}, nil
return &types.MsgJoinPoolResponse{}, nil
}
Loading

0 comments on commit da46e65

Please sign in to comment.