Skip to content

Commit

Permalink
(feat) Add possibility to transfer entire balance. (#6877)
Browse files Browse the repository at this point in the history
* 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 <d.f.hilliard@gmail.com>

* Move UnboundedSpendLimit to token.go

* add documentation

* add test to compatibility matrices

* PR Feedback.

---------

Co-authored-by: DimitrisJim <d.f.hilliard@gmail.com>
Co-authored-by: Carlos Rodriguez <carlos@interchain.io>
(cherry picked from commit 92e1f38)

# Conflicts:
#	.github/compatibility-test-matrices/release-v9.0.x/transfer-v2-multidenom-chain-a.json
  • Loading branch information
bznein authored and mergify[bot] committed Jul 23, 2024
1 parent dca07c4 commit 299167d
Show file tree
Hide file tree
Showing 12 changed files with 151 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
],
"test": [
"TestMsgTransfer_Succeeds_Nonincentivized_MultiDenom",
"TestMsgTransfer_EntireBalance",
"TestMsgTransfer_Fails_InvalidAddress_MultiDenom"
],
"relayer-type": [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"chain-a": [
"release-v9.0.x"
],
"chain-b": [
"release-v9.0.x"
],
"entrypoint": [
"TestTransferTestSuite"
],
"test": [
"TestMsgTransfer_Succeeds_Nonincentivized_MultiDenom",
"TestMsgTransfer_EntireBalance",
"TestMsgTransfer_Fails_InvalidAddress_MultiDenom"
],
"relayer-type": [
"hermes"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
],
"test": [
"TestMsgTransfer_Succeeds_Nonincentivized_MultiDenom",
"TestMsgTransfer_EntireBalance",
"TestMsgTransfer_Fails_InvalidAddress_MultiDenom"
],
"relayer-type": [
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 4 additions & 3 deletions docs/docs/02-apps/01-transfer/04-messages.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/02-apps/01-transfer/10-ICS20-v1/04-messages.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
89 changes: 89 additions & 0 deletions e2e/tests/transfer/base_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
})
}
5 changes: 5 additions & 0 deletions modules/apps/transfer/keeper/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions modules/apps/transfer/keeper/relay_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
14 changes: 14 additions & 0 deletions modules/apps/transfer/types/token.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package types

import (
"math/big"

errorsmod "cosmossdk.io/errors"
sdkmath "cosmossdk.io/math"

Expand All @@ -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 {
Expand Down Expand Up @@ -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)
}
14 changes: 0 additions & 14 deletions modules/apps/transfer/types/transfer_authorization.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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{
Expand Down Expand Up @@ -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 {
Expand Down
6 changes: 5 additions & 1 deletion testing/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 299167d

Please sign in to comment.