From 92e1f387b0c222dd2cc44c7df7981b0ca96a27f5 Mon Sep 17 00:00:00 2001 From: Nikolas De Giorgis Date: Tue, 23 Jul 2024 10:28:07 +0100 Subject: [PATCH] (feat) Add possibility to transfer entire balance. (#6877) * Add possibility to transfer entire balance. * Added entry to the Changelog. * Added e2e test * Added forwarding * Update modules/apps/transfer/keeper/relay.go Co-authored-by: DimitrisJim * Move UnboundedSpendLimit to token.go * add documentation * add test to compatibility matrices * PR Feedback. --------- Co-authored-by: DimitrisJim Co-authored-by: Carlos Rodriguez --- .../main/transfer-v2-multidenom-chain-a.json | 1 + .../transfer-v2-multidenom-chain-a.json | 1 + .../unreleased/transfer-v2-multidenom.json | 1 + CHANGELOG.md | 1 + docs/docs/02-apps/01-transfer/04-messages.md | 7 +- .../01-transfer/10-ICS20-v1/04-messages.md | 2 + e2e/tests/transfer/base_test.go | 89 +++++++++++++++++++ modules/apps/transfer/keeper/relay.go | 5 ++ modules/apps/transfer/keeper/relay_test.go | 10 +++ modules/apps/transfer/types/token.go | 14 +++ .../transfer/types/transfer_authorization.go | 14 --- testing/chain.go | 6 +- 12 files changed, 133 insertions(+), 18 deletions(-) diff --git a/.github/compatibility-test-matrices/main/transfer-v2-multidenom-chain-a.json b/.github/compatibility-test-matrices/main/transfer-v2-multidenom-chain-a.json index 95ca1fcfe0f..fb04ec8ba4d 100644 --- a/.github/compatibility-test-matrices/main/transfer-v2-multidenom-chain-a.json +++ b/.github/compatibility-test-matrices/main/transfer-v2-multidenom-chain-a.json @@ -10,6 +10,7 @@ ], "test": [ "TestMsgTransfer_Succeeds_Nonincentivized_MultiDenom", + "TestMsgTransfer_EntireBalance", "TestMsgTransfer_Fails_InvalidAddress_MultiDenom" ], "relayer-type": [ diff --git a/.github/compatibility-test-matrices/release-v9.0.x/transfer-v2-multidenom-chain-a.json b/.github/compatibility-test-matrices/release-v9.0.x/transfer-v2-multidenom-chain-a.json index 60de14c5609..e75a7b6c73e 100644 --- a/.github/compatibility-test-matrices/release-v9.0.x/transfer-v2-multidenom-chain-a.json +++ b/.github/compatibility-test-matrices/release-v9.0.x/transfer-v2-multidenom-chain-a.json @@ -10,6 +10,7 @@ ], "test": [ "TestMsgTransfer_Succeeds_Nonincentivized_MultiDenom", + "TestMsgTransfer_EntireBalance", "TestMsgTransfer_Fails_InvalidAddress_MultiDenom" ], "relayer-type": [ diff --git a/.github/compatibility-test-matrices/unreleased/transfer-v2-multidenom.json b/.github/compatibility-test-matrices/unreleased/transfer-v2-multidenom.json index 23484ea3cd0..da1134e3fa6 100644 --- a/.github/compatibility-test-matrices/unreleased/transfer-v2-multidenom.json +++ b/.github/compatibility-test-matrices/unreleased/transfer-v2-multidenom.json @@ -10,6 +10,7 @@ ], "test": [ "TestMsgTransfer_Succeeds_Nonincentivized_MultiDenom", + "TestMsgTransfer_EntireBalance", "TestMsgTransfer_Fails_InvalidAddress_MultiDenom" ], "relayer-type": [ diff --git a/CHANGELOG.md b/CHANGELOG.md index 016eb0a9acb..ee56fa3031e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -82,6 +82,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (apps/transfer) [\#6492](https://github.com/cosmos/ibc-go/pull/6492) Added new `Tokens` field to `MsgTransfer` to enable sending of multiple denoms, and deprecated the `Token` field. * (apps/transfer) [\#6693](https://github.com/cosmos/ibc-go/pull/6693) Added new `Forwarding` field to `MsgTransfer` to enable forwarding tokens through multiple intermediary chains with a single transaction. This also enables automatic unwinding of tokens to their native chain. `x/authz` support for transfer allows granters to specify a set of possible forwarding hops that are allowed for grantees. +* (apps/transfer) [\#6877](https://github.com/cosmos/ibc-go/pull/6877) Added the possibility to transfer the entire user balance of a particular denomination by using [`UnboundedSpendLimit`](https://github.com/cosmos/ibc-go/blob/715f00eef8727da41db25fdd4763b709bdbba07e/modules/apps/transfer/types/transfer_authorization.go#L253-L255) as the token amount. ### Bug Fixes diff --git a/docs/docs/02-apps/01-transfer/04-messages.md b/docs/docs/02-apps/01-transfer/04-messages.md index 2d9c28bf38d..4d121985fdc 100644 --- a/docs/docs/02-apps/01-transfer/04-messages.md +++ b/docs/docs/02-apps/01-transfer/04-messages.md @@ -57,13 +57,14 @@ If `Forwarding` is `nil`, this message is expected to fail if: If `Forwarding` is not `nil`, then to use forwarding you must either set `Unwind` to true or provide a non-empty list of `Hops`. Setting both `Unwind` to true and providing a non-empty list of `Hops` is allowed, but the total number of hops that is formed as a combination of the hops needed to unwind the tokens and the hops to forward them afterwards to the final destination must not exceed 8. When using forwarding, timeout must be specified using only `TimeoutTimestamp` (i.e. `TimeoutHeight` must be zero). Please note that the timeout timestamp must take into account the time that it may take tokens to be forwarded through the intermediary chains. Additionally, please note that the `MsgTransfer` will fail if: - `Hops` is not empty, and the number of elements of `Hops` is greater than 8, or either the `PortId` or `ChannelId` of any of the `Hops` is not a valid identifier. -- `Unwind` is true, and either the coins to be transfered have different denomination traces, or `SourcePort` and `SourceChannel` are not empty strings (they must be empty because they are set by the transfer module, since it has access to the denomination trace information and is thus able to know the source port ID, channel ID to use in order to unwind the tokens). If `Unwind` is true, the transfer module expects the tokens in `MsgTransfer` to not be native to the sending chain (i.e. they must be IBC vouchers). +- `Unwind` is true, and either the coins to be transferred have different denomination traces, or `SourcePort` and `SourceChannel` are not empty strings (they must be empty because they are set by the transfer module, since it has access to the denomination trace information and is thus able to know the source port ID, channel ID to use in order to unwind the tokens). If `Unwind` is true, the transfer module expects the tokens in `MsgTransfer` to not be native to the sending chain (i.e. they must be IBC vouchers). -Please note that the `Token` field is deprecated and users should now use `Tokens` instead. If `Token` is used then `Tokens` must be empty. Similarly, if `Tokens` is used then `Token` should be left empty. -This message will send a fungible token to the counterparty chain represented by the counterparty Channel End connected to the Channel End with the identifiers `SourcePort` and `SourceChannel`. +Please note that the `Token` field is deprecated and users should now use `Tokens` instead. If `Token` is used then `Tokens` must be empty. Similarly, if `Tokens` is used then `Token` should be left empty. This message will send a fungible token to the counterparty chain represented by the counterparty Channel End connected to the Channel End with the identifiers `SourcePort` and `SourceChannel`. The denomination provided for transfer should correspond to the same denomination represented on this chain. The prefixes will be added as necessary upon by the receiving chain. +If the `Amount` is set to the maximum value for a 256-bit unsigned integer (i.e. 2^256 - 1), then the whole balance of the corrsponding denomination will be transferred. The helper function `UnboundedSpendLimit` in the `types` package of the `transfer` module provides the sentinel value that can be used. + ### Memo The memo field was added to allow applications and users to attach metadata to transfer packets. The field is optional and may be left empty. When it is used to attach metadata for a particular middleware, the memo field should be represented as a json object where different middlewares use different json keys. diff --git a/docs/docs/02-apps/01-transfer/10-ICS20-v1/04-messages.md b/docs/docs/02-apps/01-transfer/10-ICS20-v1/04-messages.md index 703054ae1ec..08fc05e88c3 100644 --- a/docs/docs/02-apps/01-transfer/10-ICS20-v1/04-messages.md +++ b/docs/docs/02-apps/01-transfer/10-ICS20-v1/04-messages.md @@ -44,6 +44,8 @@ This message will send a fungible token to the counterparty chain represented by The denomination provided for transfer should correspond to the same denomination represented on this chain. The prefixes will be added as necessary upon by the receiving chain. +If the `Amount` is set to the maximum value for a 256-bit unsigned integer (i.e. 2^256 - 1), then the whole balance of the corrsponding denomination will be transferred. The helper function `UnboundedSpendLimit` in the `types` package of the `transfer` module provides the sentinel value that can be used. + ### Memo The memo field was added to allow applications and users to attach metadata to transfer packets. The field is optional and may be left empty. When it is used to attach metadata for a particular middleware, the memo field should be represented as a json object where different middlewares use different json keys. diff --git a/e2e/tests/transfer/base_test.go b/e2e/tests/transfer/base_test.go index af140a4f19b..745a0d57f07 100644 --- a/e2e/tests/transfer/base_test.go +++ b/e2e/tests/transfer/base_test.go @@ -553,3 +553,92 @@ func (s *TransferTestSuite) TestMsgTransfer_WithMemo() { s.Require().Equal(testvalues.IBCTransferAmount, actualBalance.Int64()) }) } + +// TestMsgTransfer_EntireBalance tests that it is possible to transfer the entire balance +// of a given denom by using types.UnboundedSpendLimit as the amount. +func (s *TransferTestSuite) TestMsgTransfer_EntireBalance() { + t := s.T() + ctx := context.TODO() + + testName := t.Name() + t.Parallel() + relayer, channelA := s.CreateTransferPath(testName) + + 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() + + coinFromA := testvalues.DefaultTransferAmount(chainADenom) + + s.Require().NoError(test.WaitForBlocks(ctx, 1, chainA, chainB), "failed to wait for blocks") + + t.Run("IBC token transfer from chainA to chainB", func(t *testing.T) { + transferTxResp := s.Transfer(ctx, chainA, chainAWallet, channelA.PortID, channelA.ChannelID, sdk.NewCoins(coinFromA), chainAAddress, chainBAddress, s.GetTimeoutHeight(ctx, chainA), 0, "", nil) + s.AssertTxSuccess(transferTxResp) + }) + + t.Run("tokens are escrowed", func(t *testing.T) { + actualBalance, err := s.GetChainANativeBalance(ctx, chainAWallet) + s.Require().NoError(err) + + s.Require().Equal(testvalues.StartingTokenAmount-coinFromA.Amount.Int64(), actualBalance) + }) + + t.Run("start relayer", func(t *testing.T) { + s.StartRelayer(relayer, testName) + }) + + chainBIBCToken := testsuite.GetIBCToken(chainADenom, channelA.Counterparty.PortID, channelA.Counterparty.ChannelID) + + t.Run("packets relayed", func(t *testing.T) { + s.AssertPacketRelayed(ctx, chainA, channelA.PortID, channelA.ChannelID, 1) + actualBalance, err := query.Balance(ctx, chainB, chainBAddress, chainBIBCToken.IBCDenom()) + + s.Require().NoError(err) + s.Require().Equal(coinFromA.Amount.Int64(), actualBalance.Int64()) + + actualBalance, err = query.Balance(ctx, chainA, chainAAddress, chainADenom) + + s.Require().NoError(err) + s.Require().Equal(testvalues.StartingTokenAmount-coinFromA.Amount.Int64(), actualBalance.Int64()) + }) + + t.Run("send entire balance from B to A", func(t *testing.T) { + transferCoins := sdk.NewCoins((sdk.NewCoin(chainBIBCToken.IBCDenom(), transfertypes.UnboundedSpendLimit())), sdk.NewCoin(chainB.Config().Denom, transfertypes.UnboundedSpendLimit())) + transferTxResp := s.Transfer(ctx, chainB, chainBWallet, channelA.Counterparty.PortID, channelA.Counterparty.ChannelID, transferCoins, chainBAddress, chainAAddress, s.GetTimeoutHeight(ctx, chainB), 0, "", nil) + s.AssertTxSuccess(transferTxResp) + }) + + chainAIBCToken := testsuite.GetIBCToken(chainB.Config().Denom, channelA.PortID, channelA.ChannelID) + t.Run("packets relayed", func(t *testing.T) { + // test that chainA has the entire balance back of its native token. + s.AssertPacketRelayed(ctx, chainA, channelA.PortID, channelA.ChannelID, 1) + actualBalance, err := query.Balance(ctx, chainA, chainAAddress, chainADenom) + + s.Require().NoError(err) + s.Require().Equal(testvalues.StartingTokenAmount, actualBalance.Int64()) + + // test that chainA has the entirety of chainB's token IBC denom. + actualBalance, err = query.Balance(ctx, chainA, chainAAddress, chainAIBCToken.IBCDenom()) + + s.Require().NoError(err) + s.Require().Equal(testvalues.StartingTokenAmount, actualBalance.Int64()) + + // Tests that chainB has a zero balance for both. + actualBalance, err = query.Balance(ctx, chainB, chainBAddress, chainBIBCToken.IBCDenom()) + + s.Require().NoError(err) + s.Require().Zero(actualBalance.Int64()) + + actualBalance, err = query.Balance(ctx, chainB, chainBAddress, chainB.Config().Denom) + + s.Require().NoError(err) + s.Require().Zero(actualBalance.Int64()) + }) +} diff --git a/modules/apps/transfer/keeper/relay.go b/modules/apps/transfer/keeper/relay.go index f41cacebd2e..122e4501fae 100644 --- a/modules/apps/transfer/keeper/relay.go +++ b/modules/apps/transfer/keeper/relay.go @@ -98,6 +98,11 @@ func (k Keeper) sendTransfer( tokens := make([]types.Token, 0, len(coins)) for _, coin := range coins { + // Using types.UnboundedSpendLimit allows us to send the entire balance of a given denom. + if coin.Amount.Equal(types.UnboundedSpendLimit()) { + coin.Amount = k.bankKeeper.GetBalance(ctx, sender, coin.Denom).Amount + } + token, err := k.tokenFromCoin(ctx, coin) if err != nil { return 0, err diff --git a/modules/apps/transfer/keeper/relay_test.go b/modules/apps/transfer/keeper/relay_test.go index ef49f1cdf64..b1bc29f9ec0 100644 --- a/modules/apps/transfer/keeper/relay_test.go +++ b/modules/apps/transfer/keeper/relay_test.go @@ -113,6 +113,16 @@ func (suite *KeeperTestSuite) TestSendTransfer() { }, nil, }, + { + "successful transfer of entire balance", + func() { + coins = sdk.NewCoins(sdk.NewCoin(coins[0].Denom, types.UnboundedSpendLimit())) + var ok bool + expEscrowAmounts[0], ok = sdkmath.NewIntFromString(ibctesting.DefaultGenesisAccBalance) + suite.Require().True(ok) + }, + nil, + }, { "failure: source channel not found", func() { diff --git a/modules/apps/transfer/types/token.go b/modules/apps/transfer/types/token.go index 0f8b361516d..d30a765f0f2 100644 --- a/modules/apps/transfer/types/token.go +++ b/modules/apps/transfer/types/token.go @@ -1,6 +1,8 @@ package types import ( + "math/big" + errorsmod "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" @@ -10,6 +12,9 @@ import ( // Tokens is a slice of Tokens type Tokens []Token +// maxUint256 is the maximum value for a 256 bit unsigned integer. +var maxUint256 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1)) + // Validate validates a token denomination and amount. func (t Token) Validate() error { if err := t.Denom.Validate(); err != nil { @@ -42,3 +47,12 @@ func (t Token) ToCoin() (sdk.Coin, error) { coin := sdk.NewCoin(t.Denom.IBCDenom(), transferAmount) return coin, nil } + +// UnboundedSpendLimit returns the sentinel value that can be used +// as the amount for a denomination's spend limit for which spend limit updating +// should be disabled. Please note that using this sentinel value means that a grantee +// will be granted the privilege to do ICS20 token transfers for the total amount +// of the denomination available at the granter's account. +func UnboundedSpendLimit() sdkmath.Int { + return sdkmath.NewIntFromBigInt(maxUint256) +} diff --git a/modules/apps/transfer/types/transfer_authorization.go b/modules/apps/transfer/types/transfer_authorization.go index 0332ef53b3d..6e166fe63b9 100644 --- a/modules/apps/transfer/types/transfer_authorization.go +++ b/modules/apps/transfer/types/transfer_authorization.go @@ -2,14 +2,12 @@ package types import ( "context" - "math/big" "slices" "strings" "github.com/cosmos/gogoproto/proto" errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/authz" @@ -25,9 +23,6 @@ const ( allocationNotFound = -1 ) -// maxUint256 is the maximum value for a 256 bit unsigned integer. -var maxUint256 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1)) - // NewTransferAuthorization creates a new TransferAuthorization object. func NewTransferAuthorization(allocations ...Allocation) *TransferAuthorization { return &TransferAuthorization{ @@ -244,15 +239,6 @@ func validateMemo(ctx sdk.Context, memo string, allowedMemos []string) error { return nil } -// UnboundedSpendLimit returns the sentinel value that can be used -// as the amount for a denomination's spend limit for which spend limit updating -// should be disabled. Please note that using this sentinel value means that a grantee -// will be granted the privilege to do ICS20 token transfers for the total amount -// of the denomination available at the granter's account. -func UnboundedSpendLimit() sdkmath.Int { - return sdkmath.NewIntFromBigInt(maxUint256) -} - // getAllocationIndex ranges through a set of allocations, and returns the index of the allocation if found. If not, returns -1. func getAllocationIndex(msg MsgTransfer, allocations []Allocation) int { for index, allocation := range allocations { diff --git a/testing/chain.go b/testing/chain.go index d9aff925a42..cda9fe83b4c 100644 --- a/testing/chain.go +++ b/testing/chain.go @@ -45,6 +45,10 @@ type SenderAccount struct { SenderAccount sdk.AccountI } +const ( + DefaultGenesisAccBalance = "10000000000000000000" +) + // TestChain is a testing struct that wraps a simapp with the last TM Header, the current ABCI // header and the validators of the TestChain. It also contains a field called ChainID. This // is the clientID that *other* chains use to refer to this TestChain. The SenderAccount @@ -107,7 +111,7 @@ func NewTestChainWithValSet(tb testing.TB, coord *Coordinator, chainID string, v for i := 0; i < MaxAccounts; i++ { senderPrivKey := secp256k1.GenPrivKey() acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), uint64(i), 0) - amount, ok := sdkmath.NewIntFromString("10000000000000000000") + amount, ok := sdkmath.NewIntFromString(DefaultGenesisAccBalance) require.True(tb, ok) // add sender account