Skip to content

Commit

Permalink
Combine assetpair and tokenpair (#504)
Browse files Browse the repository at this point in the history
* fix linter

* Add newline to satisfy linter

Co-authored-by: Walter White <[email protected]>
  • Loading branch information
AgentSmithMatrix and NibiruHeisenberg authored May 28, 2022
1 parent 3281043 commit f45acfb
Show file tree
Hide file tree
Showing 49 changed files with 498 additions and 390 deletions.
48 changes: 23 additions & 25 deletions x/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ var (
ErrInvalidTokenPair = fmt.Errorf("invalid token pair")
)

func NewAssetPairFromStr(pair string) (AssetPair, error) {
split := strings.Split(pair, PairSeparator)
if len(split) != 2 {
return AssetPair{}, ErrInvalidTokenPair
}

if split[0] == "" || split[1] == "" {
return AssetPair{}, ErrInvalidTokenPair
}

return AssetPair{Token0: split[0], Token1: split[1]}, nil
}

type AssetPair struct {
Token0 string
Token1 string
Expand All @@ -38,7 +51,7 @@ func (pair AssetPair) PairID() string {
}

func (pair AssetPair) String() string {
return fmt.Sprintf("%s:%s", pair.Token0, pair.Token1)
return fmt.Sprintf("%s%s%s", pair.Token0, PairSeparator, pair.Token1)
}

func (pair AssetPair) IsProperOrder() bool {
Expand All @@ -57,6 +70,14 @@ func (pair AssetPair) Proper() AssetPair {
}
}

func (pair AssetPair) GetBaseTokenDenom() string {
return pair.Token0
}

func (pair AssetPair) GetQuoteTokenDenom() string {
return pair.Token1
}

func DenomsFromPoolName(pool string) (denoms []string) {
return strings.Split(pool, ":")
}
Expand All @@ -73,31 +94,8 @@ func RawPoolNameFromDenoms(denoms []string) string {
poolName := denoms[0]
for idx, denom := range denoms {
if idx != 0 {
poolName += fmt.Sprintf(":%s", denom)
poolName += fmt.Sprintf("%s%s", PairSeparator, denom)
}
}
return poolName
}

type TokenPair string

func NewTokenPairFromStr(pair string) (TokenPair, error) {
split := strings.Split(pair, PairSeparator)
if len(split) != 2 {
return "", ErrInvalidTokenPair
}

return TokenPair(pair), nil
}

func (p TokenPair) GetBaseTokenDenom() string {
return strings.Split(string(p), ":")[0]
}

func (p TokenPair) GetQuoteTokenDenom() string {
return strings.Split(string(p), ":")[1]
}

func (p TokenPair) String() string {
return string(p)
}
12 changes: 6 additions & 6 deletions x/common/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ func TestAssetPair(t *testing.T) {
}{
{
name: "proper and improper order pairs are inverses-1",
pair: common.AssetPair{"atom", "osmo"},
pair: common.AssetPair{Token0: "atom", Token1: "osmo"},
proper: true,
},
{
name: "proper and improper order pairs are inverses-2",
pair: common.AssetPair{"osmo", "atom"},
pair: common.AssetPair{Token0: "osmo", Token1: "atom"},
proper: false,
},
}
Expand All @@ -80,7 +80,7 @@ func TestAssetPair(t *testing.T) {
}
}

func TestPair_Constructor(t *testing.T) {
func TestAsset_Constructor(t *testing.T) {
tests := []struct {
name string
tokenPair string
Expand Down Expand Up @@ -112,7 +112,7 @@ func TestPair_Constructor(t *testing.T) {
for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
_, err := common.NewTokenPairFromStr(tc.tokenPair)
_, err := common.NewAssetPairFromStr(tc.tokenPair)
if tc.err != nil {
require.Equal(t, tc.err, err)
} else {
Expand All @@ -122,8 +122,8 @@ func TestPair_Constructor(t *testing.T) {
}
}

func TestPair_GetBaseToken(t *testing.T) {
pair, err := common.NewTokenPairFromStr("uatom:unibi")
func TestAsset_GetQuoteBaseToken(t *testing.T) {
pair, err := common.NewAssetPairFromStr("uatom:unibi")
require.NoError(t, err)

require.Equal(t, "uatom", pair.GetBaseTokenDenom())
Expand Down
15 changes: 9 additions & 6 deletions x/perp/client/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,10 @@ func (s *IntegrationTestSuite) TearDownSuite() {

func (s *IntegrationTestSuite) TestOpenPositionCmd() {
val := s.network.Validators[0]
pair := fmt.Sprintf("%s%s%s", "ubtc", common.PairSeparator, "unibi")
pair := common.AssetPair{
Token0: "ubtc",
Token1: "unibi",
}

info, _, err := val.ClientCtx.Keyring.
NewMnemonic("user1", keyring.English, sdk.FullFundraiserPath, "", hd.Secp256k1)
Expand All @@ -105,7 +108,7 @@ func (s *IntegrationTestSuite) TestOpenPositionCmd() {
s.Require().NoError(err)

// Check vpool balances
reserveAssets, err := testutilcli.QueryVpoolReserveAssets(val.ClientCtx, common.TokenPair(pair))
reserveAssets, err := testutilcli.QueryVpoolReserveAssets(val.ClientCtx, pair)
s.Require().NoError(err)
s.Require().Equal(sdk.MustNewDecFromStr("10000000"), reserveAssets.BaseAssetReserve)
s.Require().Equal(sdk.MustNewDecFromStr("60000000000"), reserveAssets.QuoteAssetReserve)
Expand All @@ -125,23 +128,23 @@ func (s *IntegrationTestSuite) TestOpenPositionCmd() {
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()),
}

_, err = testutilcli.QueryTraderPosition(val.ClientCtx, common.TokenPair(pair), user)
_, err = testutilcli.QueryTraderPosition(val.ClientCtx, pair, user)
s.Require().True(strings.Contains(err.Error(), "no position found"))

_, err = clitestutil.ExecTestCLICmd(val.ClientCtx, cli.OpenPositionCmd(), append(args, commonArgs...))
s.Require().NoError(err)

// Check vpool after opening position
reserveAssets, err = testutilcli.QueryVpoolReserveAssets(val.ClientCtx, "ubtc:unibi")
reserveAssets, err = testutilcli.QueryVpoolReserveAssets(val.ClientCtx, pair)
s.Require().NoError(err)
s.Require().Equal(sdk.MustNewDecFromStr("9999833.336111064815586407"), reserveAssets.BaseAssetReserve)
s.Require().Equal(sdk.MustNewDecFromStr("60001000000"), reserveAssets.QuoteAssetReserve)

// Check position
queryResp, err := testutilcli.QueryTraderPosition(val.ClientCtx, common.TokenPair(pair), user)
queryResp, err := testutilcli.QueryTraderPosition(val.ClientCtx, pair, user)
s.Require().NoError(err)
s.Require().Equal(user, queryResp.Position.TraderAddress)
s.Require().Equal(pair, queryResp.Position.Pair)
s.Require().Equal(pair.String(), queryResp.Position.Pair)
s.Require().Equal(sdk.MustNewDecFromStr("1000000"), queryResp.Position.Margin)
s.Require().Equal(sdk.MustNewDecFromStr("1000000"), queryResp.Position.OpenNotional)
}
Expand Down
2 changes: 1 addition & 1 deletion x/perp/client/cli/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func CmdQueryPosition() *cobra.Command {
return fmt.Errorf("invalid trader address: %w", err)
}

tokenPair, err := common.NewTokenPairFromStr(args[1])
tokenPair, err := common.NewAssetPairFromStr(args[1])
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion x/perp/client/cli/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func OpenPositionCmd() *cobra.Command {
return fmt.Errorf("invalid side: %s", args[0])
}

_, err = common.NewTokenPairFromStr(args[1])
_, err = common.NewAssetPairFromStr(args[1])
if err != nil {
return err
}
Expand Down
6 changes: 3 additions & 3 deletions x/perp/keeper/calc.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func (k Keeper) CalcRemainMarginWithFundingPayment(
marginDelta sdk.Dec,
) (remaining RemainingMarginWithFundingPayment, err error) {
remaining.LatestCumulativePremiumFraction, err = k.
getLatestCumulativePremiumFraction(ctx, common.TokenPair(currentPosition.Pair))
getLatestCumulativePremiumFraction(ctx, currentPosition.GetAssetPair())
if err != nil {
return remaining, err
}
Expand Down Expand Up @@ -85,9 +85,9 @@ position without making it go underwater.
func (k Keeper) calcFreeCollateral(
ctx sdk.Context, pos types.Position, fundingPayment sdk.Dec,
) (accountExcessEquity sdk.Int, err error) {
pair, err := common.NewTokenPairFromStr(pos.Pair)
pair, err := common.NewAssetPairFromStr(pos.Pair)
if err != nil {
return sdk.Int{}, err
return sdk.Int{}, common.ErrInvalidTokenPair
}
err = k.requireVpool(ctx, pair)
if err != nil {
Expand Down
18 changes: 10 additions & 8 deletions x/perp/keeper/calc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ func TestCalcRemainMarginWithFundingPayment(t *testing.T) {

the3pool := "dai:usdc:usdt"
marginDelta := sdk.OneDec()
_, err := nibiruApp.PerpKeeper.CalcRemainMarginWithFundingPayment(
ctx, types.Position{Pair: the3pool}, marginDelta)
require.Error(t, err)
require.ErrorContains(t, err, types.ErrPairMetadataNotFound.Error())
require.Panics(t, func() {
_, _ = nibiruApp.PerpKeeper.CalcRemainMarginWithFundingPayment(
ctx, types.Position{Pair: the3pool}, marginDelta)
})
},
},
{
Expand All @@ -51,13 +51,14 @@ func TestCalcRemainMarginWithFundingPayment(t *testing.T) {
t.Log("Setup Nibiru app, pair, and trader")
nibiruApp, ctx := testutil.NewNibiruApp(true)
alice := sample.AccAddress()
pair := common.TokenPair("osmo:nusd")
pair, err := common.NewAssetPairFromStr("osmo:nusd")
require.NoError(t, err)

t.Log("Set vpool defined by pair on VpoolKeeper")
vpoolKeeper := &nibiruApp.VpoolKeeper
vpoolKeeper.CreatePool(
ctx,
pair.String(),
pair,
sdk.MustNewDecFromStr("0.9"), // 0.9 ratio
/* y */ sdk.NewDec(1_000_000), //
/* x */ sdk.NewDec(1_000_000), //
Expand Down Expand Up @@ -100,13 +101,14 @@ func TestCalcRemainMarginWithFundingPayment(t *testing.T) {
t.Log("Setup Nibiru app, pair, and trader")
nibiruApp, ctx := testutil.NewNibiruApp(true)
alice := sample.AccAddress()
pair := common.TokenPair("osmo:nusd")
pair, err := common.NewAssetPairFromStr("osmo:nusd")
require.NoError(t, err)

t.Log("Set vpool defined by pair on VpoolKeeper")
vpoolKeeper := &nibiruApp.VpoolKeeper
vpoolKeeper.CreatePool(
ctx,
pair.String(),
pair,
sdk.MustNewDecFromStr("0.9"), // 0.9 ratio
/* y */ sdk.NewDec(1_000_000), //
/* x */ sdk.NewDec(1_000_000), //
Expand Down
26 changes: 20 additions & 6 deletions x/perp/keeper/calc_unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ func Test_calcFreeCollateral(t *testing.T) {
test: func() {
k, _, ctx := getKeeper(t)
fundingPayment := sdk.ZeroDec()
the3pool := "dai:usdc:usdt"
alice := sample.AccAddress()
pos := types.ZeroPosition(ctx, common.TokenPair(the3pool), alice)
pos := types.ZeroPosition(ctx, common.AssetPair{
Token0: "",
Token1: "",
}, alice)
_, err := k.calcFreeCollateral(ctx, *pos, fundingPayment)
assert.Error(t, err)
assert.ErrorContains(t, err, common.ErrInvalidTokenPair.Error())
Expand All @@ -35,7 +37,10 @@ func Test_calcFreeCollateral(t *testing.T) {
k, mocks, ctx := getKeeper(t)

fundingPayment := sdk.ZeroDec()
validPair := common.TokenPair("xxx:yyy")
validPair := common.AssetPair{
Token0: "xxx",
Token1: "yyy",
}
alice := sample.AccAddress()
pos := types.ZeroPosition(ctx, validPair, alice)
mocks.mockVpoolKeeper.EXPECT().ExistsPool(ctx, validPair).
Expand All @@ -51,7 +56,10 @@ func Test_calcFreeCollateral(t *testing.T) {
k, mocks, ctx := getKeeper(t)

fundingPayment := sdk.ZeroDec()
validPair := common.TokenPair("xxx:yyy")
validPair := common.AssetPair{
Token0: "xxx",
Token1: "yyy",
}
alice := sample.AccAddress()
pos := types.ZeroPosition(ctx, validPair, alice)
mocks.mockVpoolKeeper.EXPECT().ExistsPool(ctx, validPair).
Expand All @@ -67,7 +75,10 @@ func Test_calcFreeCollateral(t *testing.T) {
k, mocks, ctx := getKeeper(t)

fundingPayment := sdk.NewDec(10)
validPair := common.TokenPair("xxx:yyy")
validPair := common.AssetPair{
Token0: "xxx",
Token1: "yyy",
}
alice := sample.AccAddress()
pos := types.ZeroPosition(ctx, validPair, alice)
mocks.mockVpoolKeeper.EXPECT().ExistsPool(ctx, validPair).
Expand All @@ -83,7 +94,10 @@ func Test_calcFreeCollateral(t *testing.T) {
k, mocks, ctx := getKeeper(t)

fundingPayment := sdk.NewDec(-100)
validPair := common.TokenPair("xxx:yyy")
validPair := common.AssetPair{
Token0: "xxx",
Token1: "yyy",
}
alice := sample.AccAddress()
pos := types.ZeroPosition(ctx, validPair, alice)
mocks.mockVpoolKeeper.EXPECT().ExistsPool(ctx, validPair).
Expand Down
Loading

0 comments on commit f45acfb

Please sign in to comment.