Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix bug in FindAllRoutes #173

Merged
merged 1 commit into from
Aug 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions x/exchange/keeper/grpc_query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,20 @@ import (
"github.com/crescent-network/crescent/v5/x/exchange/types"
)

func (s *KeeperTestSuite) createLiquidity(
marketId uint64, ordererAddr sdk.AccAddress, centerPrice, totalQty sdk.Dec) {
tick := types.TickAtPrice(centerPrice)
interval := types.PriceIntervalAtTick(tick + 10*10)
for i := 0; i < 10; i++ {
sellPrice := centerPrice.Add(interval.MulInt64(int64(i+1) * 10))
buyPrice := centerPrice.Sub(interval.MulInt64(int64(i+1) * 10))

qty := totalQty.QuoInt64(200).Add(totalQty.QuoInt64(100).MulInt64(int64(i)))
s.PlaceLimitOrder(marketId, ordererAddr, false, sellPrice, qty, time.Hour)
s.PlaceLimitOrder(marketId, ordererAddr, true, buyPrice, qty, time.Hour)
}
}

// SetupSampleScenario creates markets and orders for query tests.
func (s *KeeperTestSuite) SetupSampleScenario() {
s.T().Helper()
Expand Down Expand Up @@ -377,3 +391,26 @@ func (s *KeeperTestSuite) TestQueryOrderBook() {
})
}
}

func (s *KeeperTestSuite) TestFindBestSwapExactAmountInRoutes() {
s.CreateMarket("ucre", "uusd")
s.CreateMarket("uatom", "ucre")
s.CreateMarket("stake", "uatom")
s.CreateMarket("uatom", "stake")

lpAddr := s.FundedAccount(1, enoughCoins)
s.createLiquidity(1, lpAddr, utils.ParseDec("5"), sdk.NewDec(10_000000))
s.createLiquidity(2, lpAddr, utils.ParseDec("2"), sdk.NewDec(10_000000))
s.createLiquidity(3, lpAddr, utils.ParseDec("0.33333"), sdk.NewDec(30_000000))
s.createLiquidity(4, lpAddr, utils.ParseDec("3"), sdk.NewDec(1_000000))

routes := s.keeper.FindAllRoutes(s.Ctx, "uusd", "stake", 3)
s.Require().Equal([][]uint64{{1, 2, 3}, {1, 2, 4}}, routes)

resp, err := s.querier.BestSwapExactAmountInRoutes(sdk.WrapSDKContext(s.Ctx), &types.QueryBestSwapExactAmountInRoutesRequest{
Input: "20000000uusd", // 20_000000uusd
OutputDenom: "stake",
})
s.Require().NoError(err)
s.AssertEqual(utils.ParseDecCoin("5942989stake"), resp.Output)
}
2 changes: 1 addition & 1 deletion x/exchange/keeper/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
)

var enoughCoins = utils.ParseCoins(
"10000_000000000000000000ucre,10000_000000000000000000uatom,10000_000000000000000000uusd")
"10000_000000000000000000ucre,10000_000000000000000000uatom,10000_000000000000000000uusd,10000_000000000000000000stake")

type KeeperTestSuite struct {
testutil.TestSuite
Expand Down
40 changes: 21 additions & 19 deletions x/exchange/keeper/swap.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,21 +94,21 @@ func (k Keeper) SwapExactAmountIn(

func (k Keeper) FindAllRoutes(ctx sdk.Context, fromDenom, toDenom string, maxRoutesLen int) (allRoutes [][]uint64) {
// TODO: cache all routes on-chain?
denomMap := map[string]map[string]uint64{}
denomMap := map[string]map[string][]uint64{}
store := ctx.KVStore(k.storeKey)
iter := sdk.KVStorePrefixIterator(store, types.MarketByDenomsIndexKeyPrefix)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
baseDenom, quoteDenom := types.ParseMarketByDenomsIndexKey(iter.Key())
marketId := sdk.BigEndianToUint64(iter.Value())
if _, ok := denomMap[baseDenom]; !ok {
denomMap[baseDenom] = map[string]uint64{}
denomMap[baseDenom] = map[string][]uint64{}
}
if _, ok := denomMap[quoteDenom]; !ok {
denomMap[quoteDenom] = map[string]uint64{}
denomMap[quoteDenom] = map[string][]uint64{}
}
denomMap[baseDenom][quoteDenom] = marketId
denomMap[quoteDenom][baseDenom] = marketId
denomMap[baseDenom][quoteDenom] = append(denomMap[baseDenom][quoteDenom], marketId)
denomMap[quoteDenom][baseDenom] = append(denomMap[quoteDenom][baseDenom], marketId)
}
var currentRoutes []uint64
visited := map[uint64]struct{}{}
Expand All @@ -118,21 +118,23 @@ func (k Keeper) FindAllRoutes(ctx sdk.Context, fromDenom, toDenom string, maxRou
denoms := maps.Keys(denomMap[currentDenom])
slices.Sort(denoms)
for _, denom := range denoms {
marketId := denomMap[currentDenom][denom]
if _, ok := visited[marketId]; !ok {
if denom == toDenom {
routes := make([]uint64, len(currentRoutes), len(currentRoutes)+1)
copy(routes[:len(currentRoutes)], currentRoutes)
routes = append(routes, marketId)
allRoutes = append(allRoutes, routes)
} else {
visited[marketId] = struct{}{}
currentRoutes = append(currentRoutes, marketId)
if len(currentRoutes) < maxRoutesLen {
backtrack(denom)
marketIds := denomMap[currentDenom][denom]
for _, marketId := range marketIds {
if _, ok := visited[marketId]; !ok {
if denom == toDenom {
routes := make([]uint64, len(currentRoutes), len(currentRoutes)+1)
copy(routes[:len(currentRoutes)], currentRoutes)
routes = append(routes, marketId)
allRoutes = append(allRoutes, routes)
} else {
visited[marketId] = struct{}{}
currentRoutes = append(currentRoutes, marketId)
if len(currentRoutes) < maxRoutesLen {
backtrack(denom)
}
currentRoutes = currentRoutes[:len(currentRoutes)-1]
delete(visited, marketId)
}
currentRoutes = currentRoutes[:len(currentRoutes)-1]
delete(visited, marketId)
}
}
}
Expand Down
Loading