From fa9418f5ba39de38d995ec83d9abd289dfab5f9f Mon Sep 17 00:00:00 2001 From: Sishir Giri Date: Sat, 22 Apr 2023 13:54:05 -0700 Subject: [PATCH] feat: make a state entry to find total amount of native assets IBC'd out (#3019) --- .github/workflows/e2e-upgrade.yaml | 2 +- e2e/go.mod | 2 +- e2e/tests/transfer/base_test.go | 17 + e2e/tests/upgrades/upgrade_test.go | 68 +- e2e/testsuite/grpc_query.go | 17 + modules/apps/transfer/client/cli/cli.go | 1 + modules/apps/transfer/client/cli/query.go | 33 + modules/apps/transfer/keeper/genesis.go | 13 +- modules/apps/transfer/keeper/genesis_test.go | 39 +- modules/apps/transfer/keeper/grpc_query.go | 19 + .../apps/transfer/keeper/grpc_query_test.go | 97 +++ modules/apps/transfer/keeper/keeper.go | 73 ++- modules/apps/transfer/keeper/keeper_test.go | 166 +++++ modules/apps/transfer/keeper/migrations.go | 20 + .../apps/transfer/keeper/migrations_test.go | 82 +++ modules/apps/transfer/keeper/relay.go | 18 +- modules/apps/transfer/keeper/relay_test.go | 581 ++++++++++++++++-- modules/apps/transfer/module.go | 6 +- .../apps/transfer/types/expected_keepers.go | 3 + modules/apps/transfer/types/genesis.go | 23 +- modules/apps/transfer/types/genesis.pb.go | 111 +++- modules/apps/transfer/types/keys.go | 8 + modules/apps/transfer/types/query.pb.go | 478 ++++++++++++-- modules/apps/transfer/types/query.pb.gw.go | 101 +++ modules/apps/transfer/types/trace.go | 5 + .../applications/transfer/v1/genesis.proto | 5 + .../ibc/applications/transfer/v1/query.proto | 20 + .../applications/transfer/v1/transfer.proto | 2 +- 28 files changed, 1840 insertions(+), 170 deletions(-) diff --git a/.github/workflows/e2e-upgrade.yaml b/.github/workflows/e2e-upgrade.yaml index d36f379949f..4193ab2522c 100644 --- a/.github/workflows/e2e-upgrade.yaml +++ b/.github/workflows/e2e-upgrade.yaml @@ -55,5 +55,5 @@ jobs: chain-upgrade-tag: pr-3164 # TODO: needs v7.1.0 when cut upgrade-plan-name: "v7.1" test-entry-point: "TestUpgradeTestSuite" - test: "TestV7ChainUpgradeAddLocalhost" + test: "TestV7ToV7_1ChainUpgrade" upload-logs: true diff --git a/e2e/go.mod b/e2e/go.mod index 224ab9e9e29..1b02a631303 100644 --- a/e2e/go.mod +++ b/e2e/go.mod @@ -3,6 +3,7 @@ module github.com/cosmos/ibc-go/e2e go 1.19 require ( + cosmossdk.io/math v1.0.0 github.com/cometbft/cometbft v0.37.0 github.com/cosmos/cosmos-sdk v0.47.0 github.com/cosmos/gogoproto v1.4.8 @@ -27,7 +28,6 @@ require ( cosmossdk.io/core v0.6.0 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect cosmossdk.io/errors v1.0.0-beta.7 // indirect - cosmossdk.io/math v1.0.0 // indirect cosmossdk.io/tools/rosetta v0.2.1 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect diff --git a/e2e/tests/transfer/base_test.go b/e2e/tests/transfer/base_test.go index d858bc04058..577f4a89bd1 100644 --- a/e2e/tests/transfer/base_test.go +++ b/e2e/tests/transfer/base_test.go @@ -6,6 +6,7 @@ import ( "testing" "time" + // "cosmossdk.io/math" paramsproposaltypes "github.com/cosmos/cosmos-sdk/x/params/types/proposal" "github.com/strangelove-ventures/interchaintest/v7/ibc" test "github.com/strangelove-ventures/interchaintest/v7/testutil" @@ -88,6 +89,12 @@ func (s *TransferTestSuite) TestMsgTransfer_Succeeds_Nonincentivized() { expected := testvalues.StartingTokenAmount - testvalues.IBCTransferAmount s.Require().Equal(expected, actualBalance) + + // actualTotalEscrow, err := s.QueryTotalEscrowForDenom(ctx, chainA, chainADenom) + // s.Require().NoError(err) + + // expectedTotalEscrow := math.NewInt(testvalues.IBCTransferAmount) + // s.Require().Equal(expectedTotalEscrow, actualTotalEscrow) }) t.Run("start relayer", func(t *testing.T) { @@ -117,6 +124,10 @@ func (s *TransferTestSuite) TestMsgTransfer_Succeeds_Nonincentivized() { s.Require().NoError(err) s.Require().Equal(int64(0), actualBalance) + + // actualTotalEscrow, err := s.QueryTotalEscrowForDenom(ctx, chainB, chainBIBCToken.IBCDenom()) + // s.Require().NoError(err) + // s.Require().Equal(math.ZeroInt(), actualTotalEscrow) // total escrow is zero because sending chain is not source for tokens }) s.Require().NoError(test.WaitForBlocks(ctx, 5, chainA, chainB), "failed to wait for blocks") @@ -130,6 +141,12 @@ func (s *TransferTestSuite) TestMsgTransfer_Succeeds_Nonincentivized() { expected := testvalues.StartingTokenAmount s.Require().Equal(expected, actualBalance) }) + + // t.Run("tokens are un-escrowed", func(t *testing.T) { + // actualTotalEscrow, err := s.QueryTotalEscrowForDenom(ctx, chainA, chainADenom) + // s.Require().NoError(err) + // s.Require().Equal(math.ZeroInt(), actualTotalEscrow) // total escrow is zero because tokens have come back + // }) } // TestMsgTransfer_Fails_InvalidAddress attempts to send an IBC transfer to an invalid address and ensures diff --git a/e2e/tests/upgrades/upgrade_test.go b/e2e/tests/upgrades/upgrade_test.go index 8571f0e3326..b51adb601a7 100644 --- a/e2e/tests/upgrades/upgrade_test.go +++ b/e2e/tests/upgrades/upgrade_test.go @@ -6,6 +6,7 @@ import ( "testing" "time" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" @@ -605,33 +606,86 @@ func (s *UpgradeTestSuite) TestV6ToV7ChainUpgrade() { }) } -func (s *UpgradeTestSuite) TestV7ChainUpgradeAddLocalhost() { +func (s *UpgradeTestSuite) TestV7ToV7_1ChainUpgrade() { t := s.T() testCfg := testconfig.LoadConfig() ctx := context.Background() - _, _ = s.SetupChainsRelayerAndChannel(ctx) - chain, _ := s.GetChains() + relayer, channelA := s.SetupChainsRelayerAndChannel(ctx) + chainA, chainB := s.GetChains() + + chainADenom := chainA.Config().Denom + + chainAWallet := s.CreateUserOnChainA(ctx, testvalues.StartingTokenAmount) + chainAAddress := chainAWallet.FormattedAddress() + + chainBWallet := s.CreateUserOnChainB(ctx, testvalues.StartingTokenAmount) + chainBAddress := chainBWallet.FormattedAddress() + + s.Require().NoError(test.WaitForBlocks(ctx, 1, chainA, chainB), "failed to wait for blocks") + + t.Run("transfer native tokens from chainA to chainB", func(t *testing.T) { + transferTxResp, err := s.Transfer(ctx, chainA, chainAWallet, channelA.PortID, channelA.ChannelID, testvalues.DefaultTransferAmount(chainADenom), chainAAddress, chainBAddress, s.GetTimeoutHeight(ctx, chainB), 0, "") + s.Require().NoError(err) + s.AssertValidTxResponse(transferTxResp) + }) + + t.Run("tokens are escrowed", func(t *testing.T) { + actualBalance, err := s.GetChainANativeBalance(ctx, chainAWallet) + s.Require().NoError(err) + + expected := testvalues.StartingTokenAmount - testvalues.IBCTransferAmount + s.Require().Equal(expected, actualBalance) + + // Escrow amount for native denom is not stored in state because pre-upgrade version did not support this feature + actualTotalEscrow, err := s.QueryTotalEscrowForDenom(ctx, chainA, chainADenom) + s.Require().NoError(err) + s.Require().Equal(math.ZeroInt(), actualTotalEscrow) + }) + + t.Run("start relayer", func(t *testing.T) { + s.StartRelayer(relayer) + }) + + chainBIBCToken := testsuite.GetIBCToken(chainADenom, channelA.Counterparty.PortID, channelA.Counterparty.ChannelID) + + t.Run("packet is relayed", func(t *testing.T) { + s.AssertPacketRelayed(ctx, chainA, channelA.PortID, channelA.ChannelID, 1) - s.Require().NoError(test.WaitForBlocks(ctx, 5, chain), "failed to wait for blocks") + actualBalance, err := chainB.GetBalance(ctx, chainBAddress, chainBIBCToken.IBCDenom()) + s.Require().NoError(err) + + expected := testvalues.IBCTransferAmount + s.Require().Equal(expected, actualBalance) + }) + + s.Require().NoError(test.WaitForBlocks(ctx, 5, chainA), "failed to wait for blocks") t.Run("upgrade chain", func(t *testing.T) { govProposalWallet := s.CreateUserOnChainA(ctx, testvalues.StartingTokenAmount) - s.UpgradeChain(ctx, chain, govProposalWallet, testCfg.UpgradeConfig.PlanName, testCfg.ChainConfigs[0].Tag, testCfg.UpgradeConfig.Tag) + s.UpgradeChain(ctx, chainA, govProposalWallet, testCfg.UpgradeConfig.PlanName, testCfg.ChainConfigs[0].Tag, testCfg.UpgradeConfig.Tag) }) t.Run("ensure the localhost client is active and sentinel connection is stored in state", func(t *testing.T) { - status, err := s.QueryClientStatus(ctx, chain, exported.LocalhostClientID) + status, err := s.QueryClientStatus(ctx, chainA, exported.LocalhostClientID) s.Require().NoError(err) s.Require().Equal(exported.Active.String(), status) - connectionEnd, err := s.QueryConnection(ctx, chain, exported.LocalhostConnectionID) + connectionEnd, err := s.QueryConnection(ctx, chainA, exported.LocalhostConnectionID) s.Require().NoError(err) s.Require().Equal(connectiontypes.OPEN, connectionEnd.State) s.Require().Equal(exported.LocalhostClientID, connectionEnd.ClientId) s.Require().Equal(exported.LocalhostClientID, connectionEnd.Counterparty.ClientId) s.Require().Equal(exported.LocalhostConnectionID, connectionEnd.Counterparty.ConnectionId) }) + + t.Run("ensure escrow amount for native denom is stored in state", func(t *testing.T) { + actualTotalEscrow, err := s.QueryTotalEscrowForDenom(ctx, chainA, chainADenom) + s.Require().NoError(err) + + expectedTotalEscrow := math.NewInt(testvalues.IBCTransferAmount) + s.Require().Equal(expectedTotalEscrow, actualTotalEscrow) // migration has run and total escrow amount has been set + }) } // RegisterInterchainAccount will attempt to register an interchain account on the counterparty chain. diff --git a/e2e/testsuite/grpc_query.go b/e2e/testsuite/grpc_query.go index ea1e21675ca..4a83d863897 100644 --- a/e2e/testsuite/grpc_query.go +++ b/e2e/testsuite/grpc_query.go @@ -5,6 +5,7 @@ import ( "fmt" "sort" + "cosmossdk.io/math" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/client/grpc/tmservice" sdk "github.com/cosmos/cosmos-sdk/types" @@ -22,6 +23,7 @@ import ( controllertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" feetypes "github.com/cosmos/ibc-go/v7/modules/apps/29-fee/types" + transfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" connectiontypes "github.com/cosmos/ibc-go/v7/modules/core/03-connection/types" channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" @@ -35,6 +37,7 @@ type GRPCClients struct { ClientQueryClient clienttypes.QueryClient ConnectionQueryClient connectiontypes.QueryClient ChannelQueryClient channeltypes.QueryClient + TransferQueryClient transfertypes.QueryClient FeeQueryClient feetypes.QueryClient ICAQueryClient controllertypes.QueryClient InterTxQueryClient intertxtypes.QueryClient @@ -72,6 +75,7 @@ func (s *E2ETestSuite) InitGRPCClients(chain *cosmos.CosmosChain) { s.grpcClients[chain.Config().ChainID] = GRPCClients{ ClientQueryClient: clienttypes.NewQueryClient(grpcConn), ChannelQueryClient: channeltypes.NewQueryClient(grpcConn), + TransferQueryClient: transfertypes.NewQueryClient(grpcConn), FeeQueryClient: feetypes.NewQueryClient(grpcConn), ICAQueryClient: controllertypes.NewQueryClient(grpcConn), InterTxQueryClient: intertxtypes.NewQueryClient(grpcConn), @@ -158,6 +162,19 @@ func (s *E2ETestSuite) QueryPacketCommitment(ctx context.Context, chain ibc.Chai return res.Commitment, nil } +// QueryTotalEscrowForDenom queries the total amount of tokens in escrow for a denom +func (s *E2ETestSuite) QueryTotalEscrowForDenom(ctx context.Context, chain ibc.Chain, denom string) (math.Int, error) { + queryClient := s.GetChainGRCPClients(chain).TransferQueryClient + res, err := queryClient.TotalEscrowForDenom(ctx, &transfertypes.QueryTotalEscrowForDenomRequest{ + Denom: denom, + }) + if err != nil { + return math.ZeroInt(), err + } + + return res.Amount, nil +} + // QueryInterchainAccount queries the interchain account for the given owner and connectionID. func (s *E2ETestSuite) QueryInterchainAccount(ctx context.Context, chain ibc.Chain, owner, connectionID string) (string, error) { queryClient := s.GetChainGRCPClients(chain).ICAQueryClient diff --git a/modules/apps/transfer/client/cli/cli.go b/modules/apps/transfer/client/cli/cli.go index 52102df81a1..8412c331fc8 100644 --- a/modules/apps/transfer/client/cli/cli.go +++ b/modules/apps/transfer/client/cli/cli.go @@ -20,6 +20,7 @@ func GetQueryCmd() *cobra.Command { GetCmdParams(), GetCmdQueryEscrowAddress(), GetCmdQueryDenomHash(), + GetCmdQueryTotalEscrowForDenom(), ) return queryCmd diff --git a/modules/apps/transfer/client/cli/query.go b/modules/apps/transfer/client/cli/query.go index e87998e5573..d8d90b9dfee 100644 --- a/modules/apps/transfer/client/cli/query.go +++ b/modules/apps/transfer/client/cli/query.go @@ -167,3 +167,36 @@ func GetCmdQueryDenomHash() *cobra.Command { flags.AddQueryFlagsToCmd(cmd) return cmd } + +// GetCmdQueryTotalEscrowForDenom defines the command to query the total amount of tokens in escrow for a denom +func GetCmdQueryTotalEscrowForDenom() *cobra.Command { + cmd := &cobra.Command{ + Use: "token-escrow [denom]", + Short: "Query the total amount of tokens in escrow for a denom", + Long: "Query the total amount of tokens in escrow for a denom", + Example: fmt.Sprintf("%s query ibc-transfer token-escrow uosmo", version.AppName), + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + req := &types.QueryTotalEscrowForDenomRequest{ + Denom: args[0], + } + + res, err := queryClient.TotalEscrowForDenom(cmd.Context(), req) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + return cmd +} diff --git a/modules/apps/transfer/keeper/genesis.go b/modules/apps/transfer/keeper/genesis.go index 5a7778341a4..b31f53229e2 100644 --- a/modules/apps/transfer/keeper/genesis.go +++ b/modules/apps/transfer/keeper/genesis.go @@ -28,13 +28,20 @@ func (k Keeper) InitGenesis(ctx sdk.Context, state types.GenesisState) { } k.SetParams(ctx, state.Params) + + // Every denom will have only one total escrow amount, since any + // duplicate entry will fail validation in Validate of GenesisState + for _, denomEscrow := range state.TotalEscrowed { + k.SetTotalEscrowForDenom(ctx, denomEscrow.Denom, denomEscrow.Amount) + } } // ExportGenesis exports ibc-transfer module's portID and denom trace info into its genesis state. func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { return &types.GenesisState{ - PortId: k.GetPort(ctx), - DenomTraces: k.GetAllDenomTraces(ctx), - Params: k.GetParams(ctx), + PortId: k.GetPort(ctx), + DenomTraces: k.GetAllDenomTraces(ctx), + Params: k.GetParams(ctx), + TotalEscrowed: k.GetAllTotalEscrowed(ctx), } } diff --git a/modules/apps/transfer/keeper/genesis_test.go b/modules/apps/transfer/keeper/genesis_test.go index 3bc35144943..e878ffbe229 100644 --- a/modules/apps/transfer/keeper/genesis_test.go +++ b/modules/apps/transfer/keeper/genesis_test.go @@ -3,35 +3,52 @@ package keeper_test import ( "fmt" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" ) func (suite *KeeperTestSuite) TestGenesis() { - var ( - path string - traces types.Traces - ) + getTrace := func(index uint) string { + return fmt.Sprintf("transfer/channelToChain%d", index) + } - for i := 0; i < 5; i++ { - prefix := fmt.Sprintf("transfer/channelToChain%d", i) - if i == 0 { - path = prefix - } else { - path = prefix + "/" + path + var ( + traces types.Traces + escrows sdk.Coins + pathsAndEscrowAmounts = []struct { + path string + escrow string + }{ + {getTrace(0), "10"}, + {fmt.Sprintf("%s/%s", getTrace(1), getTrace(0)), "100000"}, + {fmt.Sprintf("%s/%s/%s", getTrace(2), getTrace(1), getTrace(0)), "10000000000"}, + {fmt.Sprintf("%s/%s/%s/%s", getTrace(3), getTrace(2), getTrace(1), getTrace(0)), "1000000000000000"}, + {fmt.Sprintf("%s/%s/%s/%s/%s", getTrace(4), getTrace(3), getTrace(2), getTrace(1), getTrace(0)), "100000000000000000000"}, } + ) + for _, pathAndEscrowMount := range pathsAndEscrowAmounts { denomTrace := types.DenomTrace{ BaseDenom: "uatom", - Path: path, + Path: pathAndEscrowMount.path, } traces = append(types.Traces{denomTrace}, traces...) suite.chainA.GetSimApp().TransferKeeper.SetDenomTrace(suite.chainA.GetContext(), denomTrace) + + denom := denomTrace.IBCDenom() + amount, ok := math.NewIntFromString(pathAndEscrowMount.escrow) + suite.Require().True(ok) + escrows = append(sdk.NewCoins(sdk.NewCoin(denom, amount)), escrows...) + suite.chainA.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(suite.chainA.GetContext(), denom, amount) } genesis := suite.chainA.GetSimApp().TransferKeeper.ExportGenesis(suite.chainA.GetContext()) suite.Require().Equal(types.PortID, genesis.PortId) suite.Require().Equal(traces.Sort(), genesis.DenomTraces) + suite.Require().Equal(escrows.Sort(), genesis.TotalEscrowed) suite.Require().NotPanics(func() { suite.chainA.GetSimApp().TransferKeeper.InitGenesis(suite.chainA.GetContext(), *genesis) diff --git a/modules/apps/transfer/keeper/grpc_query.go b/modules/apps/transfer/keeper/grpc_query.go index ed81c7b4bab..256df6ee1f6 100644 --- a/modules/apps/transfer/keeper/grpc_query.go +++ b/modules/apps/transfer/keeper/grpc_query.go @@ -121,3 +121,22 @@ func (k Keeper) EscrowAddress(c context.Context, req *types.QueryEscrowAddressRe EscrowAddress: addr.String(), }, nil } + +// TotalEscrowForDenom implements the TotalEscrowForDenom gRPC method. +func (k Keeper) TotalEscrowForDenom(c context.Context, req *types.QueryTotalEscrowForDenomRequest) (*types.QueryTotalEscrowForDenomResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + if err := sdk.ValidateDenom(req.Denom); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + denomAmount := k.GetTotalEscrowForDenom(ctx, req.Denom) + + return &types.QueryTotalEscrowForDenomResponse{ + Amount: denomAmount, + }, nil +} diff --git a/modules/apps/transfer/keeper/grpc_query_test.go b/modules/apps/transfer/keeper/grpc_query_test.go index 7270cd5bf5a..32fa80b7f3c 100644 --- a/modules/apps/transfer/keeper/grpc_query_test.go +++ b/modules/apps/transfer/keeper/grpc_query_test.go @@ -3,6 +3,7 @@ package keeper_test import ( "fmt" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" @@ -261,3 +262,99 @@ func (suite *KeeperTestSuite) TestEscrowAddress() { }) } } + +func (suite *KeeperTestSuite) TestTotalEscrowForDenom() { + var ( + req *types.QueryTotalEscrowForDenomRequest + expEscrowAmount math.Int + ) + + testCases := []struct { + msg string + malleate func() + expPass bool + }{ + { + "valid native denom with escrow amount < 2^63", + func() { + req = &types.QueryTotalEscrowForDenomRequest{ + Denom: sdk.DefaultBondDenom, + } + + expEscrowAmount = math.NewInt(100) + suite.chainA.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(suite.chainA.GetContext(), sdk.DefaultBondDenom, expEscrowAmount) + }, + true, + }, + { + "valid ibc denom with escrow amount > 2^63", + func() { + denomTrace := types.DenomTrace{ + Path: "transfer/channel-0", + BaseDenom: sdk.DefaultBondDenom, + } + + suite.chainA.GetSimApp().TransferKeeper.SetDenomTrace(suite.chainA.GetContext(), denomTrace) + expEscrowAmount, ok := math.NewIntFromString("100000000000000000000") + suite.Require().True(ok) + suite.chainA.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(suite.chainA.GetContext(), sdk.DefaultBondDenom, expEscrowAmount) + + req = &types.QueryTotalEscrowForDenomRequest{ + Denom: denomTrace.IBCDenom(), + } + }, + true, + }, + { + "valid ibc denom treated as native denom", + func() { + denomTrace := types.DenomTrace{ + Path: "transfer/channel-0", + BaseDenom: sdk.DefaultBondDenom, + } + + req = &types.QueryTotalEscrowForDenomRequest{ + Denom: denomTrace.IBCDenom(), + } + }, + true, // denom trace is not found, thus the denom is considered a native token + }, + { + "invalid ibc denom treated as valid native denom", + func() { + req = &types.QueryTotalEscrowForDenomRequest{ + Denom: "ibc/123", + } + }, + true, // the ibc denom does not contain a valid hash, thus the denom is considered a native token + }, + { + "invalid denom", + func() { + req = &types.QueryTotalEscrowForDenomRequest{ + Denom: "??𓃠🐾??", + } + }, + false, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { + suite.SetupTest() // reset + + expEscrowAmount = math.ZeroInt() + tc.malleate() + ctx := sdk.WrapSDKContext(suite.chainA.GetContext()) + + res, err := suite.chainA.GetSimApp().TransferKeeper.TotalEscrowForDenom(ctx, req) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(expEscrowAmount, res.Amount) + } else { + suite.Require().Error(err) + } + }) + } +} diff --git a/modules/apps/transfer/keeper/keeper.go b/modules/apps/transfer/keeper/keeper.go index 335be921c33..9b54521d352 100644 --- a/modules/apps/transfer/keeper/keeper.go +++ b/modules/apps/transfer/keeper/keeper.go @@ -1,6 +1,10 @@ package keeper import ( + "fmt" + "strings" + + "cosmossdk.io/math" tmbytes "github.com/cometbft/cometbft/libs/bytes" "github.com/cometbft/cometbft/libs/log" "github.com/cosmos/cosmos-sdk/codec" @@ -133,7 +137,6 @@ func (k Keeper) IterateDenomTraces(ctx sdk.Context, cb func(denomTrace types.Den defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { - denomTrace := k.MustUnmarshalDenomTrace(iterator.Value()) if cb(denomTrace) { break @@ -141,6 +144,74 @@ func (k Keeper) IterateDenomTraces(ctx sdk.Context, cb func(denomTrace types.Den } } +// GetTotalEscrowForDenom gets the total amount of source chain tokens that +// are in escrow, keyed by the denomination. +func (k Keeper) GetTotalEscrowForDenom(ctx sdk.Context, denom string) math.Int { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.TotalEscrowForDenomKey(denom)) + if bz == nil { + return math.ZeroInt() + } + + amount := sdk.IntProto{} + k.cdc.MustUnmarshal(bz, &amount) + + return amount.Int +} + +// SetTotalEscrowForDenom stores the total amount of source chain tokens that are in escrow. +func (k Keeper) SetTotalEscrowForDenom(ctx sdk.Context, denom string, amount math.Int) { + if amount.IsNegative() { + panic(fmt.Sprintf("amount cannot be negative: %s", amount)) + } + + store := ctx.KVStore(k.storeKey) + bz := k.cdc.MustMarshal(&sdk.IntProto{Int: amount}) + store.Set(types.TotalEscrowForDenomKey(denom), bz) +} + +// GetAllTotalEscrowed returns the escrow information for all the denominations. +func (k Keeper) GetAllTotalEscrowed(ctx sdk.Context) sdk.Coins { + var escrows sdk.Coins + k.IterateTokensInEscrow(ctx, []byte(types.KeyTotalEscrowPrefix), func(denomEscrow sdk.Coin) bool { + escrows = append(escrows, denomEscrow) + return false + }) + + return escrows +} + +// IterateTokensInEscrow iterates over the denomination escrows in the store +// and performs a callback function. Denominations for which an invalid value +// (i.e. not integer) is stored, will be skipped. +func (k Keeper) IterateTokensInEscrow(ctx sdk.Context, prefix []byte, cb func(denomEscrow sdk.Coin) bool) { + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, prefix) + + defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + for ; iterator.Valid(); iterator.Next() { + keySplit := strings.Split(string(iterator.Key()), "/") + if len(keySplit) < 2 { + continue // key doesn't conform to expected format + } + + denom := strings.Join(keySplit[1:], "/") + if strings.TrimSpace(denom) == "" { + continue // denom is empty + } + + amount := sdk.IntProto{} + if err := k.cdc.Unmarshal(iterator.Value(), &amount); err != nil { + continue // total escrow amount cannot be unmarshalled to integer + } + + denomEscrow := sdk.NewCoin(denom, amount.Int) + if cb(denomEscrow) { + break + } + } +} + // AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function func (k Keeper) AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool { return k.scopedKeeper.AuthenticateCapability(ctx, cap, name) diff --git a/modules/apps/transfer/keeper/keeper_test.go b/modules/apps/transfer/keeper/keeper_test.go index 0d2e9cf9a4d..9c3a7a2e4fd 100644 --- a/modules/apps/transfer/keeper/keeper_test.go +++ b/modules/apps/transfer/keeper/keeper_test.go @@ -1,9 +1,14 @@ package keeper_test import ( + "fmt" "testing" + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" @@ -44,3 +49,164 @@ func NewTransferPath(chainA, chainB *ibctesting.TestChain) *ibctesting.Path { func TestKeeperTestSuite(t *testing.T) { suite.Run(t, new(KeeperTestSuite)) } + +func (suite *KeeperTestSuite) TestSetGetTotalEscrowForDenom() { + const denom = "atom" + var expAmount math.Int + + testCases := []struct { + name string + malleate func() + expPass bool + }{ + { + "success: with 0 escrow amount", + func() {}, + true, + }, + { + "success: with escrow amount > 2^63", + func() { + expAmount, _ = math.NewIntFromString("100000000000000000000") + }, + true, + }, + { + "failure: setter panics with negative escrow amount", + func() { + expAmount = math.NewInt(-1) + }, + false, + }, + } + + for _, tc := range testCases { + tc := tc + + suite.Run(tc.name, func() { + suite.SetupTest() // reset + expAmount = math.ZeroInt() + ctx := suite.chainA.GetContext() + + tc.malleate() + + if tc.expPass { + suite.chainA.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(ctx, denom, expAmount) + total := suite.chainA.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(ctx, denom) + suite.Require().Equal(expAmount, total) + } else { + suite.Require().PanicsWithValue("amount cannot be negative: -1", func() { + suite.chainA.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(ctx, denom, expAmount) + }) + total := suite.chainA.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(ctx, denom) + suite.Require().Equal(math.ZeroInt(), total) + } + }) + } +} + +func (suite *KeeperTestSuite) TestGetAllDenomEscrows() { + var ( + store storetypes.KVStore + cdc codec.Codec + expDenomEscrows sdk.Coins + ) + + testCases := []struct { + name string + malleate func() + expPass bool + }{ + { + "success", + func() { + denom := "uatom" + amount := math.NewInt(100) + expDenomEscrows = append(expDenomEscrows, sdk.NewCoin(denom, amount)) + + bz := cdc.MustMarshal(&sdk.IntProto{Int: amount}) + store.Set(types.TotalEscrowForDenomKey(denom), bz) + }, + true, + }, + { + "success: multiple denoms", + func() { + denom := "uatom" + amount := math.NewInt(100) + expDenomEscrows = append(expDenomEscrows, sdk.NewCoin(denom, amount)) + + bz := cdc.MustMarshal(&sdk.IntProto{Int: amount}) + store.Set(types.TotalEscrowForDenomKey(denom), bz) + + denom = "bar/foo" + amount = math.NewInt(50) + expDenomEscrows = append(expDenomEscrows, sdk.NewCoin(denom, amount)) + + bz = cdc.MustMarshal(&sdk.IntProto{Int: amount}) + store.Set(types.TotalEscrowForDenomKey(denom), bz) + }, + true, + }, + { + "success: denom with non-alphanumeric characters", + func() { + denom := "ibc/123-456" + amount := math.NewInt(100) + expDenomEscrows = append(expDenomEscrows, sdk.NewCoin(denom, amount)) + + bz := cdc.MustMarshal(&sdk.IntProto{Int: amount}) + store.Set(types.TotalEscrowForDenomKey(denom), bz) + }, + true, + }, + { + "failure: empty denom", + func() { + denom := "" + amount := math.ZeroInt() + + bz := cdc.MustMarshal(&sdk.IntProto{Int: amount}) + store.Set(types.TotalEscrowForDenomKey(denom), bz) + }, + false, + }, + { + "failure: wrong prefix key", + func() { + denom := "uatom" + amount := math.ZeroInt() + + bz := cdc.MustMarshal(&sdk.IntProto{Int: amount}) + store.Set([]byte(fmt.Sprintf("wrong-prefix/%s", denom)), bz) + }, + false, + }, + } + + for _, tc := range testCases { + tc := tc + + suite.Run(tc.name, func() { + suite.SetupTest() // reset + + expDenomEscrows = sdk.Coins{} + ctx := suite.chainA.GetContext() + + storeKey := suite.chainA.GetSimApp().GetKey(types.ModuleName) + store = ctx.KVStore(storeKey) + cdc = suite.chainA.App.AppCodec() + + tc.malleate() + + denomEscrows := suite.chainA.GetSimApp().TransferKeeper.GetAllTotalEscrowed(ctx) + + if tc.expPass { + suite.Require().Len(expDenomEscrows, len(denomEscrows)) + suite.Require().ElementsMatch(expDenomEscrows, denomEscrows) + } else { + suite.Require().Empty(denomEscrows) + } + }) + } +} diff --git a/modules/apps/transfer/keeper/migrations.go b/modules/apps/transfer/keeper/migrations.go index c0399a2ad34..d9dfdcfb398 100644 --- a/modules/apps/transfer/keeper/migrations.go +++ b/modules/apps/transfer/keeper/migrations.go @@ -53,6 +53,26 @@ func (m Migrator) MigrateTraces(ctx sdk.Context) error { return nil } +// MigrateTotalEscrowForDenom migrates the total amount of source chain tokens in escrow. +func (m Migrator) MigrateTotalEscrowForDenom(ctx sdk.Context) error { + var totalEscrowed sdk.Coins + portID := m.keeper.GetPort(ctx) + + transferChannels := m.keeper.channelKeeper.GetAllChannelsWithPortPrefix(ctx, portID) + for _, channel := range transferChannels { + escrowAddress := types.GetEscrowAddress(portID, channel.ChannelId) + escrowBalances := m.keeper.bankKeeper.GetAllBalances(ctx, escrowAddress) + + totalEscrowed = totalEscrowed.Add(escrowBalances...) + } + + for _, totalEscrow := range totalEscrowed { + m.keeper.SetTotalEscrowForDenom(ctx, totalEscrow.Denom, totalEscrow.Amount) + } + + return nil +} + func equalTraces(dtA, dtB types.DenomTrace) bool { return dtA.BaseDenom == dtB.BaseDenom && dtA.Path == dtB.Path } diff --git a/modules/apps/transfer/keeper/migrations_test.go b/modules/apps/transfer/keeper/migrations_test.go index ac0097e617a..23564dece4e 100644 --- a/modules/apps/transfer/keeper/migrations_test.go +++ b/modules/apps/transfer/keeper/migrations_test.go @@ -3,8 +3,13 @@ package keeper_test import ( "fmt" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" + transferkeeper "github.com/cosmos/ibc-go/v7/modules/apps/transfer/keeper" transfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" + ibctesting "github.com/cosmos/ibc-go/v7/testing" ) func (suite *KeeperTestSuite) TestMigratorMigrateTraces() { @@ -119,3 +124,80 @@ func (suite *KeeperTestSuite) TestMigratorMigrateTracesCorruptionDetection() { migrator.MigrateTraces(suite.chainA.GetContext()) //nolint:errcheck // we shouldn't check the error here because we want to ensure that a panic occurs. }) } + +func (suite *KeeperTestSuite) TestMigrateTotalEscrowForDenom() { + var ( + path *ibctesting.Path + denom string + ) + + testCases := []struct { + msg string + malleate func() + expectedEscrowAmt math.Int + }{ + { + "success: one native denom escrowed in one channel", + func() { + denom = sdk.DefaultBondDenom + escrowAddress := transfertypes.GetEscrowAddress(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID) + coin := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) + + // funds the escrow account to have balance + suite.Require().NoError(banktestutil.FundAccount(suite.chainA.GetSimApp().BankKeeper, suite.chainA.GetContext(), escrowAddress, sdk.NewCoins(coin))) + }, + math.NewInt(100), + }, + { + "success: one native denom escrowed in two channels", + func() { + denom = sdk.DefaultBondDenom + extraPath := NewTransferPath(suite.chainA, suite.chainB) + suite.coordinator.Setup(extraPath) + + escrowAddress1 := transfertypes.GetEscrowAddress(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID) + escrowAddress2 := transfertypes.GetEscrowAddress(extraPath.EndpointA.ChannelConfig.PortID, extraPath.EndpointA.ChannelID) + coin1 := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) + coin2 := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) + + // funds the escrow accounts to have balance + suite.Require().NoError(banktestutil.FundAccount(suite.chainA.GetSimApp().BankKeeper, suite.chainA.GetContext(), escrowAddress1, sdk.NewCoins(coin1))) + suite.Require().NoError(banktestutil.FundAccount(suite.chainA.GetSimApp().BankKeeper, suite.chainA.GetContext(), escrowAddress2, sdk.NewCoins(coin2))) + }, + math.NewInt(200), + }, + { + "success: valid ibc denom escrowed in one channel", + func() { + escrowAddress := transfertypes.GetEscrowAddress(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID) + trace := transfertypes.ParseDenomTrace(transfertypes.GetPrefixedDenom(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, sdk.DefaultBondDenom)) + coin := sdk.NewCoin(trace.IBCDenom(), sdk.NewInt(100)) + denom = trace.IBCDenom() + + suite.chainA.GetSimApp().TransferKeeper.SetDenomTrace(suite.chainA.GetContext(), trace) + + // funds the escrow account to have balance + suite.Require().NoError(banktestutil.FundAccount(suite.chainA.GetSimApp().BankKeeper, suite.chainA.GetContext(), escrowAddress, sdk.NewCoins(coin))) + }, + sdk.NewInt(100), + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { + suite.SetupTest() // reset + + path = NewTransferPath(suite.chainA, suite.chainB) + suite.coordinator.Setup(path) + + tc.malleate() // explicitly fund escrow account + + migrator := transferkeeper.NewMigrator(suite.chainA.GetSimApp().TransferKeeper) + suite.Require().NoError(migrator.MigrateTotalEscrowForDenom(suite.chainA.GetContext())) + + // check that the migration set the expected amount for both native and IBC tokens + amount := suite.chainA.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(suite.chainA.GetContext(), denom) + suite.Require().Equal(tc.expectedEscrowAmt, amount) + }) + } +} diff --git a/modules/apps/transfer/keeper/relay.go b/modules/apps/transfer/keeper/relay.go index 62d4135e072..6a7c6b140df 100644 --- a/modules/apps/transfer/keeper/relay.go +++ b/modules/apps/transfer/keeper/relay.go @@ -110,6 +110,11 @@ func (k Keeper) sendTransfer( ); err != nil { return 0, err } + + // track the total amount in escrow keyed by denomination to allow for efficient iteration + currentTotalEscrow := k.GetTotalEscrowForDenom(ctx, token.GetDenom()) + newTotalEscrow := currentTotalEscrow.Add(token.Amount) + k.SetTotalEscrowForDenom(ctx, token.GetDenom(), newTotalEscrow) } else { labels = append(labels, telemetry.NewLabel(coretypes.LabelSource, "false")) @@ -197,7 +202,6 @@ func (k Keeper) OnRecvPacket(ctx sdk.Context, packet channeltypes.Packet, data t // NOTE: We use SourcePort and SourceChannel here, because the counterparty // chain would have prefixed with DestPort and DestChannel when originally // receiving this coin as seen in the "sender chain is the source" condition. - if types.ReceiverChainIsSource(packet.GetSourcePort(), packet.GetSourceChannel(), data.Denom) { // sender chain is not the source, unescrow tokens @@ -211,7 +215,7 @@ func (k Keeper) OnRecvPacket(ctx sdk.Context, packet channeltypes.Packet, data t // The denomination used to send the coins is either the native denom or the hash of the path // if the denomination is not native. denomTrace := types.ParseDenomTrace(unprefixedDenom) - if denomTrace.Path != "" { + if !denomTrace.IsNativeDenom() { denom = denomTrace.IBCDenom() } token := sdk.NewCoin(denom, transferAmount) @@ -230,6 +234,11 @@ func (k Keeper) OnRecvPacket(ctx sdk.Context, packet channeltypes.Packet, data t return errorsmod.Wrap(err, "unable to unescrow tokens, this may be caused by a malicious counterparty module or a bug: please open an issue on counterparty module") } + // track the total amount in escrow keyed by denomination to allow for efficient iteration + currentTotalEscrow := k.GetTotalEscrowForDenom(ctx, token.GetDenom()) + newTotalEscrow := currentTotalEscrow.Sub(token.Amount) + k.SetTotalEscrowForDenom(ctx, token.GetDenom(), newTotalEscrow) + defer func() { if transferAmount.IsInt64() { telemetry.SetGaugeWithLabels( @@ -366,6 +375,11 @@ func (k Keeper) refundPacketToken(ctx sdk.Context, packet channeltypes.Packet, d return errorsmod.Wrap(err, "unable to unescrow tokens, this may be caused by a malicious counterparty module or a bug: please open an issue on counterparty module") } + // track the total amount in escrow keyed by denomination to allow for efficient iteration + currentTotalEscrow := k.GetTotalEscrowForDenom(ctx, token.GetDenom()) + newTotalEscrow := currentTotalEscrow.Sub(token.Amount) + k.SetTotalEscrowForDenom(ctx, token.GetDenom(), newTotalEscrow) + return nil } diff --git a/modules/apps/transfer/keeper/relay_test.go b/modules/apps/transfer/keeper/relay_test.go index 2682e57595d..ddda92004ca 100644 --- a/modules/apps/transfer/keeper/relay_test.go +++ b/modules/apps/transfer/keeper/relay_test.go @@ -17,11 +17,12 @@ import ( // chainA and coin that orignate on chainB func (suite *KeeperTestSuite) TestSendTransfer() { var ( - coin sdk.Coin - path *ibctesting.Path - sender sdk.AccAddress - timeoutHeight clienttypes.Height - memo string + coin sdk.Coin + path *ibctesting.Path + sender sdk.AccAddress + timeoutHeight clienttypes.Height + memo string + expEscrowAmount math.Int // total amount in escrow for denom on receiving chain ) testCases := []struct { @@ -31,17 +32,19 @@ func (suite *KeeperTestSuite) TestSendTransfer() { }{ { "successful transfer with native token", - func() {}, true, + func() { + expEscrowAmount = math.NewInt(100) + }, true, }, { "successful transfer from source chain with memo", func() { memo = "memo" //nolint:goconst + expEscrowAmount = math.NewInt(100) }, true, }, { "successful transfer with IBC token", - func() { // send IBC token back to chainB coin = types.GetTransferCoin(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, coin.Denom, coin.Amount) @@ -99,6 +102,7 @@ func (suite *KeeperTestSuite) TestSendTransfer() { "SendPacket fails, timeout height and timeout timestamp are zero", func() { timeoutHeight = clienttypes.ZeroHeight() + expEscrowAmount = math.NewInt(100) }, false, }, } @@ -114,6 +118,7 @@ func (suite *KeeperTestSuite) TestSendTransfer() { sender = suite.chainA.SenderAccount.GetAddress() memo = "" timeoutHeight = suite.chainB.GetTimeoutHeight() + expEscrowAmount = math.ZeroInt() // create IBC token on chainA transferMsg := types.NewMsgTransfer(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, coin, suite.chainB.SenderAccount.GetAddress().String(), suite.chainA.SenderAccount.GetAddress().String(), suite.chainA.GetTimeoutHeight(), 0, "") @@ -138,6 +143,10 @@ func (suite *KeeperTestSuite) TestSendTransfer() { res, err := suite.chainA.GetSimApp().TransferKeeper.Transfer(sdk.WrapSDKContext(suite.chainA.GetContext()), msg) + // check total amount in escrow of sent token denom on sending chain + amount := suite.chainA.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(suite.chainA.GetContext(), coin.GetDenom()) + suite.Require().Equal(expEscrowAmount, amount) + if tc.expPass { suite.Require().NoError(err) suite.Require().NotNil(res) @@ -149,16 +158,95 @@ func (suite *KeeperTestSuite) TestSendTransfer() { } } +func (suite *KeeperTestSuite) TestSendTransferSetsTotalEscrowAmountForSourceIBCToken() { + /* + Given the following flow of tokens: + + chain A (channel 0) -> (channel-0) chain B (channel-1) -> (channel-1) chain A + stake transfer/channel-0/stake transfer/channel-1/transfer/channel-0/stake + ^ + | + SendTransfer + + This test will transfer vouchers of denom "transfer/channel-0/stake" from chain B + to chain A over channel-1 to assert that total escrow amount is stored on chain B + for vouchers of denom "transfer/channel-0/stake" because chain B acts as source + in this case. + + Set up: + - Two transfer channels between chain A and chain B (channel-0 and channel-1). + - Tokens of native denom "stake" on chain A transferred to chain B over channel-0 + and vouchers minted with denom trace "tranfer/channel-0/stake". + + Execute: + - Transfer vouchers of denom trace "tranfer/channel-0/stake" from chain B to chain A + over channel-1. + + Assert: + - The vouchers are not of a native denom (because they are of an IBC denom), but chain B + is the source, then the value for total escrow amount should still be stored for the IBC + denom that corresponds to the trace "tranfer/channel-0/stake". + */ + + // set up + // 2 transfer channels between chain A and chain B + path1 := NewTransferPath(suite.chainA, suite.chainB) + suite.coordinator.Setup(path1) + + path2 := NewTransferPath(suite.chainA, suite.chainB) + suite.coordinator.Setup(path2) + + // create IBC token on chain B with denom trace "transfer/channel-0/stake" + coin := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) + transferMsg := types.NewMsgTransfer( + path1.EndpointA.ChannelConfig.PortID, + path1.EndpointA.ChannelID, + coin, + suite.chainA.SenderAccount.GetAddress().String(), + suite.chainB.SenderAccount.GetAddress().String(), + suite.chainB.GetTimeoutHeight(), 0, "", + ) + result, err := suite.chainA.SendMsgs(transferMsg) + suite.Require().NoError(err) // message committed + + packet, err := ibctesting.ParsePacketFromEvents(result.GetEvents()) + suite.Require().NoError(err) + + err = path1.RelayPacket(packet) + suite.Require().NoError(err) + + // execute + trace := types.ParseDenomTrace(types.GetPrefixedDenom(path1.EndpointB.ChannelConfig.PortID, path1.EndpointB.ChannelID, sdk.DefaultBondDenom)) + coin = sdk.NewCoin(trace.IBCDenom(), sdk.NewInt(100)) + msg := types.NewMsgTransfer( + path2.EndpointB.ChannelConfig.PortID, + path2.EndpointB.ChannelID, + coin, + suite.chainB.SenderAccount.GetAddress().String(), + suite.chainA.SenderAccount.GetAddress().String(), + suite.chainA.GetTimeoutHeight(), 0, "", + ) + + res, err := suite.chainB.GetSimApp().TransferKeeper.Transfer(sdk.WrapSDKContext(suite.chainB.GetContext()), msg) + suite.Require().NoError(err) + suite.Require().NotNil(res) + + // check total amount in escrow of sent token on sending chain + totalEscrow := suite.chainB.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(suite.chainB.GetContext(), coin.GetDenom()) + suite.Require().Equal(math.NewInt(100), totalEscrow) +} + // test receiving coin on chainB with coin that orignate on chainA and -// coin that orignated on chainB (source). The bulk of the testing occurs +// coin that originated on chainB (source). The bulk of the testing occurs // in the test case for loop since setup is intensive for all cases. The // malleate function allows for testing invalid cases. func (suite *KeeperTestSuite) TestOnRecvPacket() { var ( - trace types.DenomTrace - amount math.Int - receiver string - memo string + trace types.DenomTrace + amount math.Int + receiver string + memo string + expEscrowAmount math.Int // total amount in escrow for denom on receiving chain ) testCases := []struct { @@ -167,42 +255,83 @@ func (suite *KeeperTestSuite) TestOnRecvPacket() { recvIsSource bool // the receiving chain is the source of the coin originally expPass bool }{ - {"success receive on source chain", func() {}, true, true}, - {"success receive on source chain with memo", func() { - memo = "memo" - }, true, true}, - {"success receive with coin from another chain as source", func() {}, false, true}, - {"success receive with coin from another chain as source with memo", func() { - memo = "memo" - }, false, true}, - {"empty coin", func() { - trace = types.DenomTrace{} - amount = sdk.ZeroInt() - }, true, false}, - {"invalid receiver address", func() { - receiver = "gaia1scqhwpgsmr6vmztaa7suurfl52my6nd2kmrudl" - }, true, false}, + { + "success receive on source chain", + func() {}, true, true, + }, + { + "success receive on source chain of half the amount", + func() { + amount = math.NewInt(50) + expEscrowAmount = math.NewInt(50) + }, true, true, + }, + { + "success receive on source chain with memo", + func() { + memo = "memo" + }, true, true, + }, + { + "success receive with coin from another chain as source", + func() {}, false, true, + }, + { + "success receive with coin from another chain as source with memo", + func() { + memo = "memo" + }, false, true, + }, + { + "empty coin", + func() { + trace = types.DenomTrace{} + amount = sdk.ZeroInt() + expEscrowAmount = math.NewInt(100) + }, true, false, + }, + { + "invalid receiver address", + func() { + receiver = "gaia1scqhwpgsmr6vmztaa7suurfl52my6nd2kmrudl" + expEscrowAmount = math.NewInt(100) + }, true, false, + }, // onRecvPacket // - coin from chain chainA - {"failure: mint zero coin", func() { - amount = sdk.ZeroInt() - }, false, false}, + { + "failure: mint zero coin", + func() { + amount = sdk.ZeroInt() + }, false, false, + }, // - coin being sent back to original chain (chainB) - {"tries to unescrow more tokens than allowed", func() { - amount = sdk.NewInt(1000000) - }, true, false}, + { + "tries to unescrow more tokens than allowed", + func() { + amount = sdk.NewInt(1000000) + expEscrowAmount = math.NewInt(100) + }, true, false, + }, // - coin being sent to module address on chainA - {"failure: receive on module account", func() { - receiver = suite.chainA.GetSimApp().AccountKeeper.GetModuleAddress(types.ModuleName).String() - }, false, false}, + { + "failure: receive on module account", + func() { + receiver = suite.chainA.GetSimApp().AccountKeeper.GetModuleAddress(types.ModuleName).String() + }, false, false, + }, // - coin being sent back to original chain (chainB) to module address - {"failure: receive on module account on source chain", func() { - receiver = suite.chainB.GetSimApp().AccountKeeper.GetModuleAddress(types.ModuleName).String() - }, true, false}, + { + "failure: receive on module account on source chain", + func() { + receiver = suite.chainB.GetSimApp().AccountKeeper.GetModuleAddress(types.ModuleName).String() + expEscrowAmount = math.NewInt(100) + }, true, false, + }, } for _, tc := range testCases { @@ -215,8 +344,9 @@ func (suite *KeeperTestSuite) TestOnRecvPacket() { suite.coordinator.Setup(path) receiver = suite.chainB.SenderAccount.GetAddress().String() // must be explicitly changed in malleate - memo = "" // can be explicitly changed in malleate - amount = sdk.NewInt(100) // must be explicitly changed in malleate + memo = "" // can be explicitly changed in malleate + amount = sdk.NewInt(100) // must be explicitly changed in malleate + expEscrowAmount = math.ZeroInt() // total amount in escrow of voucher denom on receiving chain seq := uint64(1) if tc.recvIsSource { @@ -241,7 +371,8 @@ func (suite *KeeperTestSuite) TestOnRecvPacket() { } // send coin from chainA to chainB - transferMsg := types.NewMsgTransfer(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, sdk.NewCoin(trace.IBCDenom(), amount), suite.chainA.SenderAccount.GetAddress().String(), receiver, clienttypes.NewHeight(1, 110), 0, memo) + coin := sdk.NewCoin(trace.IBCDenom(), amount) + transferMsg := types.NewMsgTransfer(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, coin, suite.chainA.SenderAccount.GetAddress().String(), receiver, clienttypes.NewHeight(1, 110), 0, memo) _, err := suite.chainA.SendMsgs(transferMsg) suite.Require().NoError(err) // message committed @@ -252,6 +383,17 @@ func (suite *KeeperTestSuite) TestOnRecvPacket() { err = suite.chainB.GetSimApp().TransferKeeper.OnRecvPacket(suite.chainB.GetContext(), packet, data) + // check total amount in escrow of received token denom on receiving chain + var denom string + var totalEscrow math.Int + if tc.recvIsSource { + denom = sdk.DefaultBondDenom + } else { + denom = trace.IBCDenom() + } + totalEscrow = suite.chainB.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(suite.chainB.GetContext(), denom) + suite.Require().Equal(expEscrowAmount, totalEscrow) + if tc.expPass { suite.Require().NoError(err) } else { @@ -261,17 +403,111 @@ func (suite *KeeperTestSuite) TestOnRecvPacket() { } } +func (suite *KeeperTestSuite) TestOnRecvPacketSetsTotalEscrowAmountForSourceIBCToken() { + /* + Given the following flow of tokens: + + chain A (channel 0) -> (channel-0) chain B (channel-1) -> (channel-1) chain A (channel-1) -> (channel-1) chain B + stake transfer/channel-0/stake transfer/channel-1/transfer/channel-0/stake transfer/channel-0/stake + ^ + | + OnRecvPacket + + This test will assert that on receiving vouchers of denom "transfer/channel-0/stake" + on chain B the total escrow amount is updated on because chain B acted as source + when vouchers were transferred to chain A over channel-1. + + Setup: + - Two transfer channels between chain A and chain B. + - Vouchers of denom trace "transfer/channel-0/stake" on chain B are in escrow + account for port ID transfer and channel ID channel-1. + + Execute: + - Receive vouchers of denom trace "transfer/channel-0/stake" from chain A to chain B + over channel-1. + + Assert: + - The vouchers are not of a native denom (because they are of an IBC denom), but chain B + is the source, then the value for total escrow amount should still be updated for the IBC + denom that corresponds to the trace "tranfer/channel-0/stake" when the vouchers are + received back on chain B. + */ + + seq := uint64(1) + amount := math.NewInt(100) + timeout := suite.chainA.GetTimeoutHeight() + + // setup + // 2 transfer channels between chain A and chain B + path1 := NewTransferPath(suite.chainA, suite.chainB) + suite.coordinator.Setup(path1) + + path2 := NewTransferPath(suite.chainA, suite.chainB) + suite.coordinator.Setup(path2) + + // denomTrace path: {transfer/channel-1/transfer/channel-0} + denomTrace := types.DenomTrace{ + BaseDenom: sdk.DefaultBondDenom, + Path: fmt.Sprintf("%s/%s/%s/%s", path2.EndpointA.ChannelConfig.PortID, path2.EndpointA.ChannelID, path1.EndpointB.ChannelConfig.PortID, path1.EndpointB.ChannelID), + } + data := types.NewFungibleTokenPacketData( + denomTrace.GetFullDenomPath(), + amount.String(), + suite.chainA.SenderAccount.GetAddress().String(), + suite.chainB.SenderAccount.GetAddress().String(), "", + ) + packet := channeltypes.NewPacket( + data.GetBytes(), + seq, + path2.EndpointA.ChannelConfig.PortID, + path2.EndpointA.ChannelID, + path2.EndpointB.ChannelConfig.PortID, + path2.EndpointB.ChannelID, + timeout, 0, + ) + + // fund escrow account for transfer and channel-1 on chain B + // denomTrace path: transfer/channel-0 + denomTrace = types.DenomTrace{ + BaseDenom: sdk.DefaultBondDenom, + Path: fmt.Sprintf("%s/%s", path1.EndpointB.ChannelConfig.PortID, path1.EndpointB.ChannelID), + } + escrowAddress := types.GetEscrowAddress(path2.EndpointB.ChannelConfig.PortID, path2.EndpointB.ChannelID) + coin := sdk.NewCoin(denomTrace.IBCDenom(), amount) + suite.Require().NoError( + banktestutil.FundAccount( + suite.chainB.GetSimApp().BankKeeper, + suite.chainB.GetContext(), + escrowAddress, + sdk.NewCoins(coin), + ), + ) + + suite.chainB.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(suite.chainB.GetContext(), coin.GetDenom(), coin.Amount) + totalEscrowChainB := suite.chainB.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(suite.chainB.GetContext(), coin.GetDenom()) + suite.Require().Equal(math.NewInt(100), totalEscrowChainB) + + // execute onRecvPacket, when chaninB receives the source token the escrow amount should decrease + err := suite.chainB.GetSimApp().TransferKeeper.OnRecvPacket(suite.chainB.GetContext(), packet, data) + suite.Require().NoError(err) + + // check total amount in escrow of sent token on reveiving chain + totalEscrowChainB = suite.chainB.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(suite.chainB.GetContext(), coin.GetDenom()) + suite.Require().Equal(math.ZeroInt(), totalEscrowChainB) +} + // TestOnAcknowledgementPacket tests that successful acknowledgement is a no-op // and failure acknowledment leads to refund when attempting to send from chainA -// to chainB. If sender is source than the denomination being refunded has no -// trace. +// to chainB. If sender is source then the denomination being refunded has no +// trace func (suite *KeeperTestSuite) TestOnAcknowledgementPacket() { var ( - successAck = channeltypes.NewResultAcknowledgement([]byte{byte(1)}) - failedAck = channeltypes.NewErrorAcknowledgement(fmt.Errorf("failed packet transfer")) - trace types.DenomTrace - amount math.Int - path *ibctesting.Path + successAck = channeltypes.NewResultAcknowledgement([]byte{byte(1)}) + failedAck = channeltypes.NewErrorAcknowledgement(fmt.Errorf("failed packet transfer")) + trace types.DenomTrace + amount math.Int + path *ibctesting.Path + expEscrowAmount math.Int ) testCases := []struct { @@ -281,24 +517,41 @@ func (suite *KeeperTestSuite) TestOnAcknowledgementPacket() { success bool // success of ack expPass bool }{ - {"success ack causes no-op", successAck, func() { - trace = types.ParseDenomTrace(types.GetPrefixedDenom(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, sdk.DefaultBondDenom)) - }, true, true}, - {"successful refund from source chain", failedAck, func() { - escrow := types.GetEscrowAddress(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID) - trace = types.ParseDenomTrace(sdk.DefaultBondDenom) - coin := sdk.NewCoin(sdk.DefaultBondDenom, amount) - - suite.Require().NoError(banktestutil.FundAccount(suite.chainA.GetSimApp().BankKeeper, suite.chainA.GetContext(), escrow, sdk.NewCoins(coin))) - }, false, true}, { - "unsuccessful refund from source", failedAck, + "success ack causes no-op", + successAck, + func() { + trace = types.ParseDenomTrace(types.GetPrefixedDenom(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, sdk.DefaultBondDenom)) + }, true, true, + }, + { + "successful refund from source chain", + failedAck, func() { + escrow := types.GetEscrowAddress(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID) trace = types.ParseDenomTrace(sdk.DefaultBondDenom) + coin := sdk.NewCoin(sdk.DefaultBondDenom, amount) + + suite.Require().NoError(banktestutil.FundAccount(suite.chainA.GetSimApp().BankKeeper, suite.chainA.GetContext(), escrow, sdk.NewCoins(coin))) + + // set escrow amount that would have been stored after successful execution of MsgTransfer + suite.chainA.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(suite.chainA.GetContext(), sdk.DefaultBondDenom, amount) + }, false, true, + }, + { + "unsuccessful refund from source", + failedAck, + func() { + trace = types.ParseDenomTrace(sdk.DefaultBondDenom) + + // set escrow amount that would have been stored after successful execution of MsgTransfer + suite.chainA.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(suite.chainA.GetContext(), sdk.DefaultBondDenom, amount) + expEscrowAmount = math.NewInt(100) }, false, false, }, { - "successful refund from with coin from external chain", failedAck, + "successful refund with coin from external chain", + failedAck, func() { escrow := types.GetEscrowAddress(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID) trace = types.ParseDenomTrace(types.GetPrefixedDenom(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, sdk.DefaultBondDenom)) @@ -317,15 +570,20 @@ func (suite *KeeperTestSuite) TestOnAcknowledgementPacket() { path = NewTransferPath(suite.chainA, suite.chainB) suite.coordinator.Setup(path) amount = sdk.NewInt(100) // must be explicitly changed + expEscrowAmount = math.ZeroInt() tc.malleate() data := types.NewFungibleTokenPacketData(trace.GetFullDenomPath(), amount.String(), suite.chainA.SenderAccount.GetAddress().String(), suite.chainB.SenderAccount.GetAddress().String(), "") packet := channeltypes.NewPacket(data.GetBytes(), 1, path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, clienttypes.NewHeight(1, 100), 0) - preCoin := suite.chainA.GetSimApp().BankKeeper.GetBalance(suite.chainA.GetContext(), suite.chainA.SenderAccount.GetAddress(), trace.IBCDenom()) err := suite.chainA.GetSimApp().TransferKeeper.OnAcknowledgementPacket(suite.chainA.GetContext(), packet, data, tc.ack) + + // check total amount in escrow of sent token denom on sending chain + totalEscrow := suite.chainA.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(suite.chainA.GetContext(), trace.IBCDenom()) + suite.Require().Equal(expEscrowAmount, totalEscrow) + if tc.expPass { suite.Require().NoError(err) postCoin := suite.chainA.GetSimApp().BankKeeper.GetBalance(suite.chainA.GetContext(), suite.chainA.SenderAccount.GetAddress(), trace.IBCDenom()) @@ -336,7 +594,6 @@ func (suite *KeeperTestSuite) TestOnAcknowledgementPacket() { } else { suite.Require().Equal(amount, deltaAmount, "failed ack did not trigger refund") } - } else { suite.Require().Error(err) } @@ -344,16 +601,103 @@ func (suite *KeeperTestSuite) TestOnAcknowledgementPacket() { } } +func (suite *KeeperTestSuite) TestOnAcknowledgementPacketSetsTotalEscrowAmountForSourceIBCToken() { + /* + This test is testing the following scenario. Given tokens travelling like this: + + chain A (channel 0) -> (channel-0) chain B (channel-1) -> (channel-1) chain A (channel-1) + stake transfer/channel-0/stake transfer/channel-1/transfer/channel-0/stake + ^ + | + OnAcknowledgePacket + + We want to assert that on failed acknowledgment of vouchers sent with denom trace + "transfer/channel-0/stake" on chain B the total escrow amount is updated. + + Set up: + - Two transfer channels between chain A and chain B. + - Vouckers of denom "transfer/channel-0/stake" on chain B are in escrow + account for port ID transfer and channel ID channel-1. + + Execute: + - Acknowledge vouchers of denom trace "tranfer/channel-0/stake" sent from chain B + to chain B over channel-1. + + Assert: + - The vouchers are not of a native denom (because they are of an IBC denom), but chain B + is the source, then the value for total escrow amount should still be updated for the IBC + denom that corresponds to the trace "tranfer/channel-0/stake" when processing the failed + acknowledgement. + */ + + seq := uint64(1) + amount := math.NewInt(100) + ack := channeltypes.NewErrorAcknowledgement(fmt.Errorf("failed packet transfer")) + + // set up + // 2 transfer channels between chain A and chain B + path1 := NewTransferPath(suite.chainA, suite.chainB) + suite.coordinator.Setup(path1) + + path2 := NewTransferPath(suite.chainA, suite.chainB) + suite.coordinator.Setup(path2) + + // fund escrow account for transfer and channel-1 on chain B + // denomTrace path = transfer/channel-0 + denomTrace := types.DenomTrace{ + BaseDenom: sdk.DefaultBondDenom, + Path: fmt.Sprintf("%s/%s", path1.EndpointB.ChannelConfig.PortID, path1.EndpointB.ChannelID), + } + escrowAddress := types.GetEscrowAddress(path2.EndpointB.ChannelConfig.PortID, path2.EndpointB.ChannelID) + coin := sdk.NewCoin(denomTrace.IBCDenom(), amount) + suite.Require().NoError( + banktestutil.FundAccount( + suite.chainB.GetSimApp().BankKeeper, + suite.chainB.GetContext(), + escrowAddress, + sdk.NewCoins(coin), + ), + ) + + data := types.NewFungibleTokenPacketData( + denomTrace.GetFullDenomPath(), + amount.String(), + suite.chainB.SenderAccount.GetAddress().String(), + suite.chainA.SenderAccount.GetAddress().String(), "", + ) + packet := channeltypes.NewPacket( + data.GetBytes(), + seq, + path2.EndpointB.ChannelConfig.PortID, + path2.EndpointB.ChannelID, + path2.EndpointA.ChannelConfig.PortID, + path2.EndpointA.ChannelID, + suite.chainA.GetTimeoutHeight(), 0, + ) + + suite.chainB.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(suite.chainB.GetContext(), coin.GetDenom(), coin.Amount) + totalEscrowChainB := suite.chainB.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(suite.chainB.GetContext(), coin.GetDenom()) + suite.Require().Equal(math.NewInt(100), totalEscrowChainB) + + err := suite.chainB.GetSimApp().TransferKeeper.OnAcknowledgementPacket(suite.chainB.GetContext(), packet, data, ack) + suite.Require().NoError(err) + + // check total amount in escrow of sent token on sending chain + totalEscrowChainB = suite.chainB.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(suite.chainB.GetContext(), coin.GetDenom()) + suite.Require().Equal(math.ZeroInt(), totalEscrowChainB) +} + // TestOnTimeoutPacket test private refundPacket function since it is a simple // wrapper over it. The actual timeout does not matter since IBC core logic // is not being tested. The test is timing out a send from chainA to chainB // so the refunds are occurring on chainA. func (suite *KeeperTestSuite) TestOnTimeoutPacket() { var ( - trace types.DenomTrace - path *ibctesting.Path - amount math.Int - sender string + trace types.DenomTrace + path *ibctesting.Path + amount math.Int + sender string + expEscrowAmount math.Int ) testCases := []struct { @@ -367,8 +711,12 @@ func (suite *KeeperTestSuite) TestOnTimeoutPacket() { escrow := types.GetEscrowAddress(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID) trace = types.ParseDenomTrace(sdk.DefaultBondDenom) coin := sdk.NewCoin(trace.IBCDenom(), amount) + expEscrowAmount = math.ZeroInt() + // funds the escrow account to have balance suite.Require().NoError(banktestutil.FundAccount(suite.chainA.GetSimApp().BankKeeper, suite.chainA.GetContext(), escrow, sdk.NewCoins(coin))) + // set escrow amount that would have been stored after successful execution of MsgTransfer + suite.chainA.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(suite.chainA.GetContext(), coin.GetDenom(), coin.Amount) }, true, }, { @@ -377,7 +725,9 @@ func (suite *KeeperTestSuite) TestOnTimeoutPacket() { escrow := types.GetEscrowAddress(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID) trace = types.ParseDenomTrace(types.GetPrefixedDenom(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, sdk.DefaultBondDenom)) coin := sdk.NewCoin(trace.IBCDenom(), amount) + expEscrowAmount = math.ZeroInt() + // funds the escrow account to have balance suite.Require().NoError(banktestutil.FundAccount(suite.chainA.GetSimApp().BankKeeper, suite.chainA.GetContext(), escrow, sdk.NewCoins(coin))) }, true, }, @@ -385,12 +735,20 @@ func (suite *KeeperTestSuite) TestOnTimeoutPacket() { "no balance for coin denom", func() { trace = types.ParseDenomTrace("bitcoin") + expEscrowAmount = amount + + // set escrow amount that would have been stored after successful execution of MsgTransfer + suite.chainA.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(suite.chainA.GetContext(), trace.IBCDenom(), amount) }, false, }, { "unescrow failed", func() { trace = types.ParseDenomTrace(sdk.DefaultBondDenom) + expEscrowAmount = amount + + // set escrow amount that would have been stored after successful execution of MsgTransfer + suite.chainA.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(suite.chainA.GetContext(), trace.IBCDenom(), amount) }, false, }, { @@ -413,12 +771,12 @@ func (suite *KeeperTestSuite) TestOnTimeoutPacket() { suite.coordinator.Setup(path) amount = sdk.NewInt(100) // must be explicitly changed sender = suite.chainA.SenderAccount.GetAddress().String() + expEscrowAmount = math.ZeroInt() tc.malleate() data := types.NewFungibleTokenPacketData(trace.GetFullDenomPath(), amount.String(), sender, suite.chainB.SenderAccount.GetAddress().String(), "") packet := channeltypes.NewPacket(data.GetBytes(), 1, path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, clienttypes.NewHeight(1, 100), 0) - preCoin := suite.chainA.GetSimApp().BankKeeper.GetBalance(suite.chainA.GetContext(), suite.chainA.SenderAccount.GetAddress(), trace.IBCDenom()) err := suite.chainA.GetSimApp().TransferKeeper.OnTimeoutPacket(suite.chainA.GetContext(), packet, data) @@ -426,6 +784,10 @@ func (suite *KeeperTestSuite) TestOnTimeoutPacket() { postCoin := suite.chainA.GetSimApp().BankKeeper.GetBalance(suite.chainA.GetContext(), suite.chainA.SenderAccount.GetAddress(), trace.IBCDenom()) deltaAmount := postCoin.Amount.Sub(preCoin.Amount) + // check total amount in escrow of sent token denom on sending chain + totalEscrow := suite.chainA.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(suite.chainA.GetContext(), trace.IBCDenom()) + suite.Require().Equal(expEscrowAmount, totalEscrow) + if tc.expPass { suite.Require().NoError(err) suite.Require().Equal(amount.Int64(), deltaAmount.Int64(), "successful timeout did not trigger refund") @@ -435,3 +797,86 @@ func (suite *KeeperTestSuite) TestOnTimeoutPacket() { }) } } + +func (suite *KeeperTestSuite) TestOnTimeoutPacketSetsTotalEscrowAmountForSourceIBCToken() { + /* + Given the following flow of tokens: + + chain A (channel 0) -> (channel-0) chain B (channel-1) -> (channel-1) chain A (channel-1) + stake transfer/channel-0/stake transfer/channel-1/transfer/channel-0/stake + ^ + | + OnTimeoutPacket + + We want to assert that on timeout of vouchers sent with denom trace + "transfer/channel-0/stake" on chain B the total escrow amount is updated. + + Set up: + - Two transfer channels between chain A and chain B. + - Vouckers of denom "transfer/channel-0/stake" on chain B are in escrow + account for port ID transfer and channel ID channel-1. + + Execute: + - Timeout vouchers of denom trace "tranfer/channel-0/stake" sent from chain B + to chain B over channel-1. + + Assert: + - The vouchers are not of a native denom (because they are of an IBC denom), but chain B + is the source, then the value for total escrow amount should still be updated for the IBC + denom that corresponds to the trace "tranfer/channel-0/stake" when processing the timeout. + */ + + seq := uint64(1) + amount := math.NewInt(100) + + // set up + // 2 transfer channels between chain A and chain B + path1 := NewTransferPath(suite.chainA, suite.chainB) + suite.coordinator.Setup(path1) + + path2 := NewTransferPath(suite.chainA, suite.chainB) + suite.coordinator.Setup(path2) + + // fund escrow account for transfer and channel-1 on chain B + denomTrace := types.DenomTrace{ + BaseDenom: sdk.DefaultBondDenom, + Path: fmt.Sprintf("%s/%s", path1.EndpointB.ChannelConfig.PortID, path1.EndpointB.ChannelID), + } + escrowAddress := types.GetEscrowAddress(path2.EndpointB.ChannelConfig.PortID, path2.EndpointB.ChannelID) + coin := sdk.NewCoin(denomTrace.IBCDenom(), amount) + suite.Require().NoError( + banktestutil.FundAccount( + suite.chainB.GetSimApp().BankKeeper, + suite.chainB.GetContext(), + escrowAddress, + sdk.NewCoins(coin), + ), + ) + + data := types.NewFungibleTokenPacketData( + denomTrace.GetFullDenomPath(), + amount.String(), + suite.chainB.SenderAccount.GetAddress().String(), + suite.chainA.SenderAccount.GetAddress().String(), "", + ) + packet := channeltypes.NewPacket( + data.GetBytes(), + seq, + path2.EndpointB.ChannelConfig.PortID, + path2.EndpointB.ChannelID, + path2.EndpointA.ChannelConfig.PortID, + path2.EndpointA.ChannelID, + suite.chainA.GetTimeoutHeight(), 0, + ) + + suite.chainB.GetSimApp().TransferKeeper.SetTotalEscrowForDenom(suite.chainB.GetContext(), coin.GetDenom(), coin.Amount) + totalEscrowChainB := suite.chainB.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(suite.chainB.GetContext(), coin.GetDenom()) + suite.Require().Equal(math.NewInt(100), totalEscrowChainB) + + err := suite.chainB.GetSimApp().TransferKeeper.OnTimeoutPacket(suite.chainB.GetContext(), packet, data) + suite.Require().NoError(err) + + // check total amount in escrow of sent token on sending chain + totalEscrowChainB = suite.chainB.GetSimApp().TransferKeeper.GetTotalEscrowForDenom(suite.chainB.GetContext(), coin.GetDenom()) + suite.Require().Equal(math.ZeroInt(), totalEscrowChainB) +} diff --git a/modules/apps/transfer/module.go b/modules/apps/transfer/module.go index 34a88780c06..0716acc9a93 100644 --- a/modules/apps/transfer/module.go +++ b/modules/apps/transfer/module.go @@ -107,6 +107,10 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { if err := cfg.RegisterMigration(types.ModuleName, 1, m.MigrateTraces); err != nil { panic(fmt.Sprintf("failed to migrate transfer app from version 1 to 2: %v", err)) } + + if err := cfg.RegisterMigration(types.ModuleName, 2, m.MigrateTotalEscrowForDenom); err != nil { + panic(fmt.Sprintf("failed to migrate total escrow amount from version 2 to 3: %v", err)) + } } // InitGenesis performs genesis initialization for the ibc-transfer module. It returns @@ -126,7 +130,7 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw } // ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 2 } +func (AppModule) ConsensusVersion() uint64 { return 3 } // BeginBlock implements the AppModule interface func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { diff --git a/modules/apps/transfer/types/expected_keepers.go b/modules/apps/transfer/types/expected_keepers.go index 425f2b7c9f7..389d423a18f 100644 --- a/modules/apps/transfer/types/expected_keepers.go +++ b/modules/apps/transfer/types/expected_keepers.go @@ -25,12 +25,15 @@ type BankKeeper interface { SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error BlockedAddr(addr sdk.AccAddress) bool IsSendEnabledCoin(ctx sdk.Context, coin sdk.Coin) bool + GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin + GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins } // ChannelKeeper defines the expected IBC channel keeper type ChannelKeeper interface { GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) GetNextSequenceSend(ctx sdk.Context, portID, channelID string) (uint64, bool) + GetAllChannelsWithPortPrefix(ctx sdk.Context, portPrefix string) []channeltypes.IdentifiedChannel } // ClientKeeper defines the expected IBC client keeper diff --git a/modules/apps/transfer/types/genesis.go b/modules/apps/transfer/types/genesis.go index 241a6cff005..65ea8b1f463 100644 --- a/modules/apps/transfer/types/genesis.go +++ b/modules/apps/transfer/types/genesis.go @@ -1,24 +1,28 @@ package types import ( + sdk "github.com/cosmos/cosmos-sdk/types" + host "github.com/cosmos/ibc-go/v7/modules/core/24-host" ) // NewGenesisState creates a new ibc-transfer GenesisState instance. -func NewGenesisState(portID string, denomTraces Traces, params Params) *GenesisState { +func NewGenesisState(portID string, denomTraces Traces, params Params, totalEscrowed sdk.Coins) *GenesisState { return &GenesisState{ - PortId: portID, - DenomTraces: denomTraces, - Params: params, + PortId: portID, + DenomTraces: denomTraces, + Params: params, + TotalEscrowed: totalEscrowed, } } // DefaultGenesisState returns a GenesisState with "transfer" as the default PortID. func DefaultGenesisState() *GenesisState { return &GenesisState{ - PortId: PortID, - DenomTraces: Traces{}, - Params: DefaultParams(), + PortId: PortID, + DenomTraces: Traces{}, + Params: DefaultParams(), + TotalEscrowed: sdk.Coins{}, } } @@ -31,5 +35,8 @@ func (gs GenesisState) Validate() error { if err := gs.DenomTraces.Validate(); err != nil { return err } - return gs.Params.Validate() + if err := gs.Params.Validate(); err != nil { + return err + } + return gs.TotalEscrowed.Validate() // will fail if there are duplicates for any denom } diff --git a/modules/apps/transfer/types/genesis.pb.go b/modules/apps/transfer/types/genesis.pb.go index f1b7fe6555b..be82e834cd0 100644 --- a/modules/apps/transfer/types/genesis.pb.go +++ b/modules/apps/transfer/types/genesis.pb.go @@ -5,6 +5,8 @@ package types import ( fmt "fmt" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types" _ "github.com/cosmos/gogoproto/gogoproto" proto "github.com/cosmos/gogoproto/proto" io "io" @@ -28,6 +30,9 @@ type GenesisState struct { PortId string `protobuf:"bytes,1,opt,name=port_id,json=portId,proto3" json:"port_id,omitempty"` DenomTraces Traces `protobuf:"bytes,2,rep,name=denom_traces,json=denomTraces,proto3,castrepeated=Traces" json:"denom_traces"` Params Params `protobuf:"bytes,3,opt,name=params,proto3" json:"params"` + // total_escrowed contains the total amount of tokens escrowed + // by the transfer module + TotalEscrowed github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=total_escrowed,json=totalEscrowed,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"total_escrowed"` } func (m *GenesisState) Reset() { *m = GenesisState{} } @@ -84,6 +89,13 @@ func (m *GenesisState) GetParams() Params { return Params{} } +func (m *GenesisState) GetTotalEscrowed() github_com_cosmos_cosmos_sdk_types.Coins { + if m != nil { + return m.TotalEscrowed + } + return nil +} + func init() { proto.RegisterType((*GenesisState)(nil), "ibc.applications.transfer.v1.GenesisState") } @@ -93,26 +105,31 @@ func init() { } var fileDescriptor_a4f788affd5bea89 = []byte{ - // 301 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x90, 0xc1, 0x4a, 0x2b, 0x31, - 0x14, 0x86, 0x27, 0xb7, 0x97, 0x11, 0xa7, 0xc5, 0xc5, 0x20, 0x58, 0x8a, 0xa4, 0x45, 0x5c, 0x0c, - 0x8a, 0x09, 0xad, 0x8b, 0xee, 0x07, 0x41, 0xdc, 0x69, 0x75, 0xa5, 0x8b, 0x92, 0xc9, 0xc4, 0x31, - 0xd0, 0x99, 0x13, 0x72, 0xd2, 0x82, 0x6f, 0xe1, 0x73, 0xf8, 0x24, 0x5d, 0x76, 0xe9, 0x4a, 0xa5, - 0x7d, 0x11, 0xc9, 0x54, 0x4b, 0x57, 0xdd, 0x9d, 0x93, 0x7c, 0xff, 0x97, 0xf0, 0x47, 0x67, 0x3a, - 0x93, 0x5c, 0x18, 0x33, 0xd1, 0x52, 0x38, 0x0d, 0x15, 0x72, 0x67, 0x45, 0x85, 0xcf, 0xca, 0xf2, - 0x59, 0x9f, 0x17, 0xaa, 0x52, 0xa8, 0x91, 0x19, 0x0b, 0x0e, 0xe2, 0x63, 0x9d, 0x49, 0xb6, 0xcd, - 0xb2, 0x3f, 0x96, 0xcd, 0xfa, 0x9d, 0xf3, 0x9d, 0xa6, 0x0d, 0x59, 0xab, 0x3a, 0x87, 0x05, 0x14, - 0x50, 0x8f, 0xdc, 0x4f, 0xeb, 0xd3, 0x93, 0x39, 0x89, 0x5a, 0xd7, 0xeb, 0x27, 0xef, 0x9d, 0x70, - 0x2a, 0x3e, 0x8a, 0xf6, 0x0c, 0x58, 0x37, 0xd6, 0x79, 0x9b, 0xf4, 0x48, 0xb2, 0x3f, 0x0a, 0xfd, - 0x7a, 0x93, 0xc7, 0x4f, 0x51, 0x2b, 0x57, 0x15, 0x94, 0x63, 0x67, 0x85, 0x54, 0xd8, 0xfe, 0xd7, - 0x6b, 0x24, 0xcd, 0x41, 0xc2, 0x76, 0xfd, 0x90, 0x5d, 0xf9, 0xc4, 0x83, 0x0f, 0xa4, 0x07, 0xf3, - 0xcf, 0x6e, 0xf0, 0xfe, 0xd5, 0x0d, 0xeb, 0x15, 0x47, 0xcd, 0x7c, 0x73, 0x87, 0x71, 0x1a, 0x85, - 0x46, 0x58, 0x51, 0x62, 0xbb, 0xd1, 0x23, 0x49, 0x73, 0x70, 0xba, 0x5b, 0x7b, 0x5b, 0xb3, 0xe9, - 0x7f, 0xaf, 0x1c, 0xfd, 0x26, 0xd3, 0xbb, 0xf9, 0x92, 0x92, 0xc5, 0x92, 0x92, 0xef, 0x25, 0x25, - 0x6f, 0x2b, 0x1a, 0x2c, 0x56, 0x34, 0xf8, 0x58, 0xd1, 0xe0, 0x71, 0x58, 0x68, 0xf7, 0x32, 0xcd, - 0x98, 0x84, 0x92, 0x4b, 0xc0, 0x12, 0x90, 0xeb, 0x4c, 0x5e, 0x14, 0xc0, 0x67, 0x43, 0x5e, 0x42, - 0x3e, 0x9d, 0x28, 0xf4, 0x3d, 0x6e, 0xf5, 0xe7, 0x5e, 0x8d, 0xc2, 0x2c, 0xac, 0x4b, 0xba, 0xfc, - 0x09, 0x00, 0x00, 0xff, 0xff, 0x16, 0x48, 0xb9, 0x00, 0xb3, 0x01, 0x00, 0x00, + // 377 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x51, 0xb1, 0x8e, 0xd3, 0x40, + 0x10, 0xb5, 0x93, 0xc8, 0x08, 0x27, 0xa4, 0xb0, 0x90, 0x30, 0x11, 0x72, 0x22, 0x44, 0x61, 0x81, + 0xb2, 0x8b, 0x43, 0x91, 0xde, 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8b, 0x9b, 0xa9, 0x63, + 0x5a, 0x4c, 0x86, 0xd9, 0x71, 0x86, 0x5e, 0xec, 0x3a, 0x15, 0x53, 0xac, 0x40, 0xbf, 0x3f, 0xb3, + 0xc3, 0xe1, 0xe2, 0xd5, 0x79, 0xd9, 0x2f, 0x06, 0x1b, 0x0f, 0x1a, 0xc9, 0xa4, 0x63, 0x7a, 0xca, + 0x1d, 0x6b, 0xd0, 0x6c, 0xbd, 0x12, 0xc8, 0x15, 0xfc, 0x15, 0x99, 0x3f, 0x30, 0x27, 0x3e, 0x27, + 0xad, 0x33, 0xa4, 0x71, 0x86, 0x74, 0xce, 0x90, 0xf7, 0x20, 0xcb, 0xf8, 0x6d, 0x77, 0x53, 0x98, + 0x4b, 0xfd, 0x7b, 0x93, 0x12, 0x0e, 0x05, 0xed, 0x6c, 0x6c, 0x3f, 0x73, 0xcc, 0xfe, 0x50, 0xfd, + 0xaf, 0x12, 0x68, 0x08, 0x98, 0x3c, 0x31, 0x2b, 0x3e, 0x76, 0x1b, 0xe2, 0xaf, 0xdb, 0x7d, 0x60, + 0xef, 0xf6, 0x81, 0x7d, 0xbb, 0x0f, 0xec, 0xff, 0x87, 0xc0, 0xda, 0x1d, 0x02, 0xeb, 0xea, 0x10, + 0x58, 0x3f, 0x96, 0x0f, 0x25, 0x65, 0xca, 0xe7, 0x39, 0xd0, 0x7a, 0x49, 0x0b, 0xc8, 0x36, 0x6b, + 0x81, 0x4d, 0xb6, 0x27, 0x99, 0x9a, 0x3d, 0xa9, 0x63, 0x82, 0x79, 0x77, 0x17, 0x00, 0x00, 0xff, + 0xff, 0x5f, 0x34, 0x4a, 0xbc, 0x47, 0x02, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { @@ -135,6 +152,20 @@ func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.TotalEscrowed) > 0 { + for iNdEx := len(m.TotalEscrowed) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.TotalEscrowed[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } { size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) if err != nil { @@ -198,6 +229,12 @@ func (m *GenesisState) Size() (n int) { } l = m.Params.Size() n += 1 + l + sovGenesis(uint64(l)) + if len(m.TotalEscrowed) > 0 { + for _, e := range m.TotalEscrowed { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } return n } @@ -335,6 +372,40 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TotalEscrowed", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TotalEscrowed = append(m.TotalEscrowed, types.Coin{}) + if err := m.TotalEscrowed[len(m.TotalEscrowed)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenesis(dAtA[iNdEx:]) diff --git a/modules/apps/transfer/types/keys.go b/modules/apps/transfer/types/keys.go index c156af3fd88..ec4c76cf596 100644 --- a/modules/apps/transfer/types/keys.go +++ b/modules/apps/transfer/types/keys.go @@ -29,6 +29,8 @@ const ( // DenomPrefix is the prefix used for internal SDK coin representation. DenomPrefix = "ibc" + + KeyTotalEscrowPrefix = "totalEscrowForDenom" ) var ( @@ -53,3 +55,9 @@ func GetEscrowAddress(portID, channelID string) sdk.AccAddress { hash := sha256.Sum256(preImage) return hash[:20] } + +// TotalEscrowForDenomKey returns the store key of under which the total amout of +// source chain tokens in escrow is stored. +func TotalEscrowForDenomKey(denom string) []byte { + return []byte(fmt.Sprintf("%s/%s", KeyTotalEscrowPrefix, denom)) +} diff --git a/modules/apps/transfer/types/query.pb.go b/modules/apps/transfer/types/query.pb.go index f8c4543eee3..ed4becfe8e1 100644 --- a/modules/apps/transfer/types/query.pb.go +++ b/modules/apps/transfer/types/query.pb.go @@ -5,7 +5,9 @@ package types import ( context "context" + cosmossdk_io_math "cosmossdk.io/math" fmt "fmt" + _ "github.com/cosmos/cosmos-proto" query "github.com/cosmos/cosmos-sdk/types/query" _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" @@ -505,6 +507,89 @@ func (m *QueryEscrowAddressResponse) GetEscrowAddress() string { return "" } +// QueryTotalEscrowForDenomRequest is the request type for TotalEscrowForDenom RPC method. +type QueryTotalEscrowForDenomRequest struct { + Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` +} + +func (m *QueryTotalEscrowForDenomRequest) Reset() { *m = QueryTotalEscrowForDenomRequest{} } +func (m *QueryTotalEscrowForDenomRequest) String() string { return proto.CompactTextString(m) } +func (*QueryTotalEscrowForDenomRequest) ProtoMessage() {} +func (*QueryTotalEscrowForDenomRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_a638e2800a01538c, []int{10} +} +func (m *QueryTotalEscrowForDenomRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryTotalEscrowForDenomRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryTotalEscrowForDenomRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryTotalEscrowForDenomRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryTotalEscrowForDenomRequest.Merge(m, src) +} +func (m *QueryTotalEscrowForDenomRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryTotalEscrowForDenomRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryTotalEscrowForDenomRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryTotalEscrowForDenomRequest proto.InternalMessageInfo + +func (m *QueryTotalEscrowForDenomRequest) GetDenom() string { + if m != nil { + return m.Denom + } + return "" +} + +// QueryTotalEscrowForDenomResponse is the response type for TotalEscrowForDenom RPC method. +type QueryTotalEscrowForDenomResponse struct { + Amount cosmossdk_io_math.Int `protobuf:"bytes,1,opt,name=amount,proto3,customtype=cosmossdk.io/math.Int" json:"amount"` +} + +func (m *QueryTotalEscrowForDenomResponse) Reset() { *m = QueryTotalEscrowForDenomResponse{} } +func (m *QueryTotalEscrowForDenomResponse) String() string { return proto.CompactTextString(m) } +func (*QueryTotalEscrowForDenomResponse) ProtoMessage() {} +func (*QueryTotalEscrowForDenomResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_a638e2800a01538c, []int{11} +} +func (m *QueryTotalEscrowForDenomResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryTotalEscrowForDenomResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryTotalEscrowForDenomResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryTotalEscrowForDenomResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryTotalEscrowForDenomResponse.Merge(m, src) +} +func (m *QueryTotalEscrowForDenomResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryTotalEscrowForDenomResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryTotalEscrowForDenomResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryTotalEscrowForDenomResponse proto.InternalMessageInfo + func init() { proto.RegisterType((*QueryDenomTraceRequest)(nil), "ibc.applications.transfer.v1.QueryDenomTraceRequest") proto.RegisterType((*QueryDenomTraceResponse)(nil), "ibc.applications.transfer.v1.QueryDenomTraceResponse") @@ -516,6 +601,8 @@ func init() { proto.RegisterType((*QueryDenomHashResponse)(nil), "ibc.applications.transfer.v1.QueryDenomHashResponse") proto.RegisterType((*QueryEscrowAddressRequest)(nil), "ibc.applications.transfer.v1.QueryEscrowAddressRequest") proto.RegisterType((*QueryEscrowAddressResponse)(nil), "ibc.applications.transfer.v1.QueryEscrowAddressResponse") + proto.RegisterType((*QueryTotalEscrowForDenomRequest)(nil), "ibc.applications.transfer.v1.QueryTotalEscrowForDenomRequest") + proto.RegisterType((*QueryTotalEscrowForDenomResponse)(nil), "ibc.applications.transfer.v1.QueryTotalEscrowForDenomResponse") } func init() { @@ -523,52 +610,60 @@ func init() { } var fileDescriptor_a638e2800a01538c = []byte{ - // 718 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x55, 0x4f, 0x4f, 0xd4, 0x40, - 0x14, 0xdf, 0xa2, 0x2c, 0xd9, 0xb7, 0xc2, 0x61, 0x44, 0xc1, 0x06, 0x0b, 0x69, 0x50, 0xc9, 0x0a, - 0x1d, 0x97, 0x3f, 0xe2, 0x41, 0x0f, 0xe2, 0x5f, 0x8c, 0x07, 0x58, 0x3c, 0xe9, 0x81, 0x4c, 0xdb, - 0xb1, 0xdb, 0x64, 0xb7, 0x53, 0x3a, 0xdd, 0x35, 0x84, 0x70, 0xd1, 0x2f, 0x60, 0xc2, 0x97, 0x30, - 0x26, 0xc6, 0xaf, 0xe0, 0x91, 0x23, 0x89, 0x89, 0xf1, 0xa4, 0x06, 0xfc, 0x20, 0xa6, 0x33, 0xb3, - 0xbb, 0xad, 0x6c, 0x16, 0x7a, 0x9b, 0xce, 0xbc, 0xdf, 0x7b, 0xbf, 0xdf, 0xef, 0xbd, 0x97, 0xc2, - 0x9c, 0x6f, 0x3b, 0x98, 0x84, 0x61, 0xc3, 0x77, 0x48, 0xec, 0xb3, 0x80, 0xe3, 0x38, 0x22, 0x01, - 0x7f, 0x4b, 0x23, 0xdc, 0xae, 0xe2, 0x9d, 0x16, 0x8d, 0x76, 0xad, 0x30, 0x62, 0x31, 0x43, 0x53, - 0xbe, 0xed, 0x58, 0xe9, 0x48, 0xab, 0x13, 0x69, 0xb5, 0xab, 0xfa, 0xb8, 0xc7, 0x3c, 0x26, 0x02, - 0x71, 0x72, 0x92, 0x18, 0xbd, 0xe2, 0x30, 0xde, 0x64, 0x1c, 0xdb, 0x84, 0x53, 0x99, 0x0c, 0xb7, - 0xab, 0x36, 0x8d, 0x49, 0x15, 0x87, 0xc4, 0xf3, 0x03, 0x91, 0x48, 0xc5, 0xde, 0x1e, 0xc8, 0xa4, - 0x5b, 0x4b, 0x06, 0x4f, 0x79, 0x8c, 0x79, 0x0d, 0x8a, 0x49, 0xe8, 0x63, 0x12, 0x04, 0x2c, 0x56, - 0x94, 0xc4, 0xab, 0x39, 0x0f, 0x57, 0x37, 0x93, 0x62, 0x8f, 0x69, 0xc0, 0x9a, 0xaf, 0x22, 0xe2, - 0xd0, 0x1a, 0xdd, 0x69, 0x51, 0x1e, 0x23, 0x04, 0x17, 0xeb, 0x84, 0xd7, 0x27, 0xb5, 0x19, 0x6d, - 0xae, 0x54, 0x13, 0x67, 0xd3, 0x85, 0x89, 0x53, 0xd1, 0x3c, 0x64, 0x01, 0xa7, 0x68, 0x1d, 0xca, - 0x6e, 0x72, 0xbb, 0x1d, 0x27, 0xd7, 0x02, 0x55, 0x5e, 0x9c, 0xb3, 0x06, 0x39, 0x61, 0xa5, 0xd2, - 0x80, 0xdb, 0x3d, 0x9b, 0xe4, 0x54, 0x15, 0xde, 0x21, 0xf5, 0x14, 0xa0, 0xe7, 0x86, 0x2a, 0x72, - 0xd3, 0x92, 0xd6, 0x59, 0x89, 0x75, 0x96, 0xec, 0x83, 0xb2, 0xce, 0xda, 0x20, 0x5e, 0x47, 0x50, - 0x2d, 0x85, 0x34, 0xbf, 0x69, 0x30, 0x79, 0xba, 0x86, 0x92, 0xf2, 0x06, 0x2e, 0xa5, 0xa4, 0xf0, - 0x49, 0x6d, 0xe6, 0x42, 0x1e, 0x2d, 0x6b, 0x63, 0x87, 0xbf, 0xa6, 0x0b, 0x9f, 0x7f, 0x4f, 0x17, - 0x55, 0xde, 0x72, 0x4f, 0x1b, 0x47, 0xcf, 0x32, 0x0a, 0x86, 0x84, 0x82, 0x5b, 0x67, 0x2a, 0x90, - 0xcc, 0x32, 0x12, 0xc6, 0x01, 0x09, 0x05, 0x1b, 0x24, 0x22, 0xcd, 0x8e, 0x41, 0xe6, 0x16, 0x5c, - 0xce, 0xdc, 0x2a, 0x49, 0xf7, 0xa1, 0x18, 0x8a, 0x1b, 0xe5, 0xd9, 0xec, 0x60, 0x31, 0x0a, 0xad, - 0x30, 0xe6, 0x02, 0x5c, 0xe9, 0x99, 0xf5, 0x9c, 0xf0, 0x7a, 0xa7, 0x1d, 0xe3, 0x30, 0xdc, 0x6b, - 0x77, 0xa9, 0x26, 0x3f, 0xb2, 0x33, 0x25, 0xc3, 0x15, 0x8d, 0x7e, 0x33, 0xb5, 0x05, 0xd7, 0x44, - 0xf4, 0x13, 0xee, 0x44, 0xec, 0xdd, 0x43, 0xd7, 0x8d, 0x28, 0xef, 0xf6, 0x7b, 0x02, 0x46, 0x42, - 0x16, 0xc5, 0xdb, 0xbe, 0xab, 0x30, 0xc5, 0xe4, 0x73, 0xdd, 0x45, 0xd7, 0x01, 0x9c, 0x3a, 0x09, - 0x02, 0xda, 0x48, 0xde, 0x86, 0xc4, 0x5b, 0x49, 0xdd, 0xac, 0xbb, 0xe6, 0x23, 0xd0, 0xfb, 0x25, - 0x55, 0x34, 0x6e, 0xc0, 0x18, 0x15, 0x0f, 0xdb, 0x44, 0xbe, 0xa8, 0xe4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, 0x57, 0x73, 0x6d, 0xf3, 0xf0, 0xd8, 0xd0, 0x8e, 0x8e, 0x0d, 0xed, 0xcf, 0xb1, 0xa1, 0x7d, - 0x3c, 0x31, 0x0a, 0x47, 0x27, 0x46, 0xe1, 0xe7, 0x89, 0x51, 0x78, 0xbd, 0xea, 0xf9, 0x71, 0xbd, - 0x65, 0x5b, 0x0e, 0x6b, 0x62, 0xf5, 0xf7, 0xf4, 0x6d, 0x67, 0xc1, 0x63, 0xb8, 0xbd, 0x8a, 0x9b, - 0xcc, 0x6d, 0x35, 0x28, 0xff, 0x8f, 0x44, 0xbc, 0x1b, 0x52, 0x6e, 0x17, 0xc5, 0xbf, 0x6f, 0xe9, - 0x5f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x47, 0x7a, 0xbb, 0x0b, 0xd2, 0x07, 0x00, 0x00, + // 847 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x56, 0x4f, 0x6f, 0xe3, 0x44, + 0x14, 0x8f, 0x0b, 0x1b, 0xc8, 0x0b, 0xbb, 0x87, 0xd9, 0x2e, 0xdb, 0xb5, 0x4a, 0x52, 0x59, 0x05, + 0xaa, 0xec, 0xc6, 0x43, 0x76, 0xd3, 0x86, 0x43, 0x8b, 0x44, 0x0b, 0x85, 0x20, 0x0e, 0x6d, 0xda, + 0x13, 0x1c, 0xa2, 0x89, 0x3d, 0x38, 0x16, 0x89, 0xc7, 0xf5, 0x4c, 0x82, 0xaa, 0xa8, 0x17, 0x3e, + 0x01, 0x52, 0xbf, 0x04, 0x42, 0x42, 0x5c, 0xf8, 0x00, 0x1c, 0x7b, 0xac, 0x8a, 0x84, 0x2a, 0x0e, + 0x05, 0xb5, 0x7c, 0x10, 0xe4, 0x99, 0x49, 0x62, 0xd3, 0x34, 0x4d, 0x38, 0xc5, 0x33, 0xf3, 0x7e, + 0xef, 0xfd, 0x7e, 0xef, 0x9f, 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0x94, 0xb7, 0xb2, 0xf2, 0x2f, 0xc7, + 0xab, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0x14, 0x3b, 0x12, 0x7f, 0x64, 0x09, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -593,6 +688,8 @@ type QueryClient interface { DenomHash(ctx context.Context, in *QueryDenomHashRequest, opts ...grpc.CallOption) (*QueryDenomHashResponse, error) // EscrowAddress returns the escrow address for a particular port and channel id. EscrowAddress(ctx context.Context, in *QueryEscrowAddressRequest, opts ...grpc.CallOption) (*QueryEscrowAddressResponse, error) + // TotalEscrowForDenom returns the total amount of tokens in escrow based on the denom. + TotalEscrowForDenom(ctx context.Context, in *QueryTotalEscrowForDenomRequest, opts ...grpc.CallOption) (*QueryTotalEscrowForDenomResponse, error) } type queryClient struct { @@ -648,6 +745,15 @@ func (c *queryClient) EscrowAddress(ctx context.Context, in *QueryEscrowAddressR return out, nil } +func (c *queryClient) TotalEscrowForDenom(ctx context.Context, in *QueryTotalEscrowForDenomRequest, opts ...grpc.CallOption) (*QueryTotalEscrowForDenomResponse, error) { + out := new(QueryTotalEscrowForDenomResponse) + err := c.cc.Invoke(ctx, "/ibc.applications.transfer.v1.Query/TotalEscrowForDenom", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // QueryServer is the server API for Query service. type QueryServer interface { // DenomTrace queries a denomination trace information. @@ -660,6 +766,8 @@ type QueryServer interface { DenomHash(context.Context, *QueryDenomHashRequest) (*QueryDenomHashResponse, error) // EscrowAddress returns the escrow address for a particular port and channel id. EscrowAddress(context.Context, *QueryEscrowAddressRequest) (*QueryEscrowAddressResponse, error) + // TotalEscrowForDenom returns the total amount of tokens in escrow based on the denom. + TotalEscrowForDenom(context.Context, *QueryTotalEscrowForDenomRequest) (*QueryTotalEscrowForDenomResponse, error) } // UnimplementedQueryServer can be embedded to have forward compatible implementations. @@ -681,6 +789,9 @@ func (*UnimplementedQueryServer) DenomHash(ctx context.Context, req *QueryDenomH func (*UnimplementedQueryServer) EscrowAddress(ctx context.Context, req *QueryEscrowAddressRequest) (*QueryEscrowAddressResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method EscrowAddress not implemented") } +func (*UnimplementedQueryServer) TotalEscrowForDenom(ctx context.Context, req *QueryTotalEscrowForDenomRequest) (*QueryTotalEscrowForDenomResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method TotalEscrowForDenom not implemented") +} func RegisterQueryServer(s grpc1.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) @@ -776,6 +887,24 @@ func _Query_EscrowAddress_Handler(srv interface{}, ctx context.Context, dec func return interceptor(ctx, in, info, handler) } +func _Query_TotalEscrowForDenom_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryTotalEscrowForDenomRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).TotalEscrowForDenom(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/ibc.applications.transfer.v1.Query/TotalEscrowForDenom", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).TotalEscrowForDenom(ctx, req.(*QueryTotalEscrowForDenomRequest)) + } + return interceptor(ctx, in, info, handler) +} + var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "ibc.applications.transfer.v1.Query", HandlerType: (*QueryServer)(nil), @@ -800,6 +929,10 @@ var _Query_serviceDesc = grpc.ServiceDesc{ MethodName: "EscrowAddress", Handler: _Query_EscrowAddress_Handler, }, + { + MethodName: "TotalEscrowForDenom", + Handler: _Query_TotalEscrowForDenom_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "ibc/applications/transfer/v1/query.proto", @@ -1139,6 +1272,69 @@ func (m *QueryEscrowAddressResponse) MarshalToSizedBuffer(dAtA []byte) (int, err return len(dAtA) - i, nil } +func (m *QueryTotalEscrowForDenomRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryTotalEscrowForDenomRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryTotalEscrowForDenomRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Denom) > 0 { + i -= len(m.Denom) + copy(dAtA[i:], m.Denom) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryTotalEscrowForDenomResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryTotalEscrowForDenomResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryTotalEscrowForDenomResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.Amount.Size() + i -= size + if _, err := m.Amount.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { offset -= sovQuery(v) base := offset @@ -1286,6 +1482,30 @@ func (m *QueryEscrowAddressResponse) Size() (n int) { return n } +func (m *QueryTotalEscrowForDenomRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Denom) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryTotalEscrowForDenomResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Amount.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + func sovQuery(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } @@ -2162,6 +2382,172 @@ func (m *QueryEscrowAddressResponse) Unmarshal(dAtA []byte) error { } return nil } +func (m *QueryTotalEscrowForDenomRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryTotalEscrowForDenomRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryTotalEscrowForDenomRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Denom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryTotalEscrowForDenomResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryTotalEscrowForDenomResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryTotalEscrowForDenomResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func skipQuery(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/modules/apps/transfer/types/query.pb.gw.go b/modules/apps/transfer/types/query.pb.gw.go index 35d95239e65..e7b727dbd50 100644 --- a/modules/apps/transfer/types/query.pb.gw.go +++ b/modules/apps/transfer/types/query.pb.gw.go @@ -271,6 +271,60 @@ func local_request_Query_EscrowAddress_0(ctx context.Context, marshaler runtime. } +func request_Query_TotalEscrowForDenom_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryTotalEscrowForDenomRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["denom"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") + } + + protoReq.Denom, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) + } + + msg, err := client.TotalEscrowForDenom(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_TotalEscrowForDenom_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryTotalEscrowForDenomRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["denom"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") + } + + protoReq.Denom, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) + } + + msg, err := server.TotalEscrowForDenom(ctx, &protoReq) + return msg, metadata, err + +} + // RegisterQueryHandlerServer registers the http handlers for service Query to "mux". // UnaryRPC :call QueryServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. @@ -392,6 +446,29 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv }) + mux.Handle("GET", pattern_Query_TotalEscrowForDenom_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_TotalEscrowForDenom_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_TotalEscrowForDenom_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + return nil } @@ -533,6 +610,26 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie }) + mux.Handle("GET", pattern_Query_TotalEscrowForDenom_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_TotalEscrowForDenom_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_TotalEscrowForDenom_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + return nil } @@ -546,6 +643,8 @@ var ( pattern_Query_DenomHash_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 3, 0, 4, 1, 5, 5}, []string{"ibc", "apps", "transfer", "v1", "denom_hashes", "trace"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_EscrowAddress_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5, 2, 6, 1, 0, 4, 1, 5, 7, 2, 8}, []string{"ibc", "apps", "transfer", "v1", "channels", "channel_id", "ports", "port_id", "escrow_address"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_TotalEscrowForDenom_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 3, 0, 4, 1, 5, 5, 2, 6}, []string{"ibc", "apps", "transfer", "v1", "denoms", "denom", "total_escrow"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( @@ -558,4 +657,6 @@ var ( forward_Query_DenomHash_0 = runtime.ForwardResponseMessage forward_Query_EscrowAddress_0 = runtime.ForwardResponseMessage + + forward_Query_TotalEscrowForDenom_0 = runtime.ForwardResponseMessage ) diff --git a/modules/apps/transfer/types/trace.go b/modules/apps/transfer/types/trace.go index 81814fbdc6f..2c9581d9078 100644 --- a/modules/apps/transfer/types/trace.go +++ b/modules/apps/transfer/types/trace.go @@ -75,6 +75,11 @@ func (dt DenomTrace) GetFullDenomPath() string { return dt.GetPrefix() + dt.BaseDenom } +// IsNativeDenom returns true if the denomination is native, thus containing no trace history. +func (dt DenomTrace) IsNativeDenom() bool { + return dt.Path == "" +} + // extractPathAndBaseFromFullDenom returns the trace path and the base denom from // the elements that constitute the complete denom. func extractPathAndBaseFromFullDenom(fullDenomItems []string) (string, string) { diff --git a/proto/ibc/applications/transfer/v1/genesis.proto b/proto/ibc/applications/transfer/v1/genesis.proto index 3e24d1e8236..a7dfc1cbbd3 100644 --- a/proto/ibc/applications/transfer/v1/genesis.proto +++ b/proto/ibc/applications/transfer/v1/genesis.proto @@ -5,6 +5,7 @@ package ibc.applications.transfer.v1; option go_package = "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types"; import "ibc/applications/transfer/v1/transfer.proto"; +import "cosmos/base/v1beta1/coin.proto"; import "gogoproto/gogo.proto"; // GenesisState defines the ibc-transfer genesis state @@ -12,4 +13,8 @@ message GenesisState { string port_id = 1; repeated DenomTrace denom_traces = 2 [(gogoproto.castrepeated) = "Traces", (gogoproto.nullable) = false]; Params params = 3 [(gogoproto.nullable) = false]; + // total_escrowed contains the total amount of tokens escrowed + // by the transfer module + repeated cosmos.base.v1beta1.Coin total_escrowed = 4 + [(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", (gogoproto.nullable) = false]; } diff --git a/proto/ibc/applications/transfer/v1/query.proto b/proto/ibc/applications/transfer/v1/query.proto index 89b70309f15..83b8317def7 100644 --- a/proto/ibc/applications/transfer/v1/query.proto +++ b/proto/ibc/applications/transfer/v1/query.proto @@ -3,6 +3,7 @@ syntax = "proto3"; package ibc.applications.transfer.v1; import "gogoproto/gogo.proto"; +import "cosmos_proto/cosmos.proto"; import "cosmos/base/query/v1beta1/pagination.proto"; import "ibc/applications/transfer/v1/transfer.proto"; import "google/api/annotations.proto"; @@ -35,6 +36,11 @@ service Query { rpc EscrowAddress(QueryEscrowAddressRequest) returns (QueryEscrowAddressResponse) { option (google.api.http).get = "/ibc/apps/transfer/v1/channels/{channel_id}/ports/{port_id}/escrow_address"; } + + // TotalEscrowForDenom returns the total amount of tokens in escrow based on the denom. + rpc TotalEscrowForDenom(QueryTotalEscrowForDenomRequest) returns (QueryTotalEscrowForDenomResponse) { + option (google.api.http).get = "/ibc/apps/transfer/v1/denoms/{denom=**}/total_escrow"; + } } // QueryDenomTraceRequest is the request type for the Query/DenomTrace RPC @@ -102,4 +108,18 @@ message QueryEscrowAddressRequest { message QueryEscrowAddressResponse { // the escrow account address string escrow_address = 1; +} + +// QueryTotalEscrowForDenomRequest is the request type for TotalEscrowForDenom RPC method. +message QueryTotalEscrowForDenomRequest { + string denom = 1; +} + +// QueryTotalEscrowForDenomResponse is the response type for TotalEscrowForDenom RPC method. +message QueryTotalEscrowForDenomResponse { + string amount = 1 [ + (cosmos_proto.scalar) = "cosmos.Int", + (gogoproto.customtype) = "cosmossdk.io/math.Int", + (gogoproto.nullable) = false + ]; } \ No newline at end of file diff --git a/proto/ibc/applications/transfer/v1/transfer.proto b/proto/ibc/applications/transfer/v1/transfer.proto index d64b4a446a4..73a6f759ee3 100644 --- a/proto/ibc/applications/transfer/v1/transfer.proto +++ b/proto/ibc/applications/transfer/v1/transfer.proto @@ -25,4 +25,4 @@ message Params { // receive_enabled enables or disables all cross-chain token transfers to this // chain. bool receive_enabled = 2; -} +} \ No newline at end of file