Skip to content

Commit 92e1f38

Browse files
Nikolas De GiorgisDimitrisJimcrodriguezvega
authored
(feat) Add possibility to transfer entire balance. (cosmos#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 <[email protected]> * Move UnboundedSpendLimit to token.go * add documentation * add test to compatibility matrices * PR Feedback. --------- Co-authored-by: DimitrisJim <[email protected]> Co-authored-by: Carlos Rodriguez <[email protected]>
1 parent 6aa61af commit 92e1f38

File tree

12 files changed

+133
-18
lines changed

12 files changed

+133
-18
lines changed

.github/compatibility-test-matrices/main/transfer-v2-multidenom-chain-a.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
],
1111
"test": [
1212
"TestMsgTransfer_Succeeds_Nonincentivized_MultiDenom",
13+
"TestMsgTransfer_EntireBalance",
1314
"TestMsgTransfer_Fails_InvalidAddress_MultiDenom"
1415
],
1516
"relayer-type": [

.github/compatibility-test-matrices/release-v9.0.x/transfer-v2-multidenom-chain-a.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
],
1111
"test": [
1212
"TestMsgTransfer_Succeeds_Nonincentivized_MultiDenom",
13+
"TestMsgTransfer_EntireBalance",
1314
"TestMsgTransfer_Fails_InvalidAddress_MultiDenom"
1415
],
1516
"relayer-type": [

.github/compatibility-test-matrices/unreleased/transfer-v2-multidenom.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
],
1111
"test": [
1212
"TestMsgTransfer_Succeeds_Nonincentivized_MultiDenom",
13+
"TestMsgTransfer_EntireBalance",
1314
"TestMsgTransfer_Fails_InvalidAddress_MultiDenom"
1415
],
1516
"relayer-type": [

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
8282

8383
* (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.
8484
* (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.
85+
* (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.
8586

8687
### Bug Fixes
8788

docs/docs/02-apps/01-transfer/04-messages.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,14 @@ If `Forwarding` is `nil`, this message is expected to fail if:
5757
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:
5858

5959
- `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.
60-
- `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).
60+
- `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).
6161

62-
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.
63-
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`.
62+
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`.
6463

6564
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.
6665

66+
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.
67+
6768
### Memo
6869

6970
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.

docs/docs/02-apps/01-transfer/10-ICS20-v1/04-messages.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ This message will send a fungible token to the counterparty chain represented by
4444

4545
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.
4646

47+
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.
48+
4749
### Memo
4850

4951
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.

e2e/tests/transfer/base_test.go

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,3 +553,92 @@ func (s *TransferTestSuite) TestMsgTransfer_WithMemo() {
553553
s.Require().Equal(testvalues.IBCTransferAmount, actualBalance.Int64())
554554
})
555555
}
556+
557+
// TestMsgTransfer_EntireBalance tests that it is possible to transfer the entire balance
558+
// of a given denom by using types.UnboundedSpendLimit as the amount.
559+
func (s *TransferTestSuite) TestMsgTransfer_EntireBalance() {
560+
t := s.T()
561+
ctx := context.TODO()
562+
563+
testName := t.Name()
564+
t.Parallel()
565+
relayer, channelA := s.CreateTransferPath(testName)
566+
567+
chainA, chainB := s.GetChains()
568+
569+
chainADenom := chainA.Config().Denom
570+
571+
chainAWallet := s.CreateUserOnChainA(ctx, testvalues.StartingTokenAmount)
572+
chainAAddress := chainAWallet.FormattedAddress()
573+
574+
chainBWallet := s.CreateUserOnChainB(ctx, testvalues.StartingTokenAmount)
575+
chainBAddress := chainBWallet.FormattedAddress()
576+
577+
coinFromA := testvalues.DefaultTransferAmount(chainADenom)
578+
579+
s.Require().NoError(test.WaitForBlocks(ctx, 1, chainA, chainB), "failed to wait for blocks")
580+
581+
t.Run("IBC token transfer from chainA to chainB", func(t *testing.T) {
582+
transferTxResp := s.Transfer(ctx, chainA, chainAWallet, channelA.PortID, channelA.ChannelID, sdk.NewCoins(coinFromA), chainAAddress, chainBAddress, s.GetTimeoutHeight(ctx, chainA), 0, "", nil)
583+
s.AssertTxSuccess(transferTxResp)
584+
})
585+
586+
t.Run("tokens are escrowed", func(t *testing.T) {
587+
actualBalance, err := s.GetChainANativeBalance(ctx, chainAWallet)
588+
s.Require().NoError(err)
589+
590+
s.Require().Equal(testvalues.StartingTokenAmount-coinFromA.Amount.Int64(), actualBalance)
591+
})
592+
593+
t.Run("start relayer", func(t *testing.T) {
594+
s.StartRelayer(relayer, testName)
595+
})
596+
597+
chainBIBCToken := testsuite.GetIBCToken(chainADenom, channelA.Counterparty.PortID, channelA.Counterparty.ChannelID)
598+
599+
t.Run("packets relayed", func(t *testing.T) {
600+
s.AssertPacketRelayed(ctx, chainA, channelA.PortID, channelA.ChannelID, 1)
601+
actualBalance, err := query.Balance(ctx, chainB, chainBAddress, chainBIBCToken.IBCDenom())
602+
603+
s.Require().NoError(err)
604+
s.Require().Equal(coinFromA.Amount.Int64(), actualBalance.Int64())
605+
606+
actualBalance, err = query.Balance(ctx, chainA, chainAAddress, chainADenom)
607+
608+
s.Require().NoError(err)
609+
s.Require().Equal(testvalues.StartingTokenAmount-coinFromA.Amount.Int64(), actualBalance.Int64())
610+
})
611+
612+
t.Run("send entire balance from B to A", func(t *testing.T) {
613+
transferCoins := sdk.NewCoins((sdk.NewCoin(chainBIBCToken.IBCDenom(), transfertypes.UnboundedSpendLimit())), sdk.NewCoin(chainB.Config().Denom, transfertypes.UnboundedSpendLimit()))
614+
transferTxResp := s.Transfer(ctx, chainB, chainBWallet, channelA.Counterparty.PortID, channelA.Counterparty.ChannelID, transferCoins, chainBAddress, chainAAddress, s.GetTimeoutHeight(ctx, chainB), 0, "", nil)
615+
s.AssertTxSuccess(transferTxResp)
616+
})
617+
618+
chainAIBCToken := testsuite.GetIBCToken(chainB.Config().Denom, channelA.PortID, channelA.ChannelID)
619+
t.Run("packets relayed", func(t *testing.T) {
620+
// test that chainA has the entire balance back of its native token.
621+
s.AssertPacketRelayed(ctx, chainA, channelA.PortID, channelA.ChannelID, 1)
622+
actualBalance, err := query.Balance(ctx, chainA, chainAAddress, chainADenom)
623+
624+
s.Require().NoError(err)
625+
s.Require().Equal(testvalues.StartingTokenAmount, actualBalance.Int64())
626+
627+
// test that chainA has the entirety of chainB's token IBC denom.
628+
actualBalance, err = query.Balance(ctx, chainA, chainAAddress, chainAIBCToken.IBCDenom())
629+
630+
s.Require().NoError(err)
631+
s.Require().Equal(testvalues.StartingTokenAmount, actualBalance.Int64())
632+
633+
// Tests that chainB has a zero balance for both.
634+
actualBalance, err = query.Balance(ctx, chainB, chainBAddress, chainBIBCToken.IBCDenom())
635+
636+
s.Require().NoError(err)
637+
s.Require().Zero(actualBalance.Int64())
638+
639+
actualBalance, err = query.Balance(ctx, chainB, chainBAddress, chainB.Config().Denom)
640+
641+
s.Require().NoError(err)
642+
s.Require().Zero(actualBalance.Int64())
643+
})
644+
}

modules/apps/transfer/keeper/relay.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,11 @@ func (k Keeper) sendTransfer(
9898
tokens := make([]types.Token, 0, len(coins))
9999

100100
for _, coin := range coins {
101+
// Using types.UnboundedSpendLimit allows us to send the entire balance of a given denom.
102+
if coin.Amount.Equal(types.UnboundedSpendLimit()) {
103+
coin.Amount = k.bankKeeper.GetBalance(ctx, sender, coin.Denom).Amount
104+
}
105+
101106
token, err := k.tokenFromCoin(ctx, coin)
102107
if err != nil {
103108
return 0, err

modules/apps/transfer/keeper/relay_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,16 @@ func (suite *KeeperTestSuite) TestSendTransfer() {
113113
},
114114
nil,
115115
},
116+
{
117+
"successful transfer of entire balance",
118+
func() {
119+
coins = sdk.NewCoins(sdk.NewCoin(coins[0].Denom, types.UnboundedSpendLimit()))
120+
var ok bool
121+
expEscrowAmounts[0], ok = sdkmath.NewIntFromString(ibctesting.DefaultGenesisAccBalance)
122+
suite.Require().True(ok)
123+
},
124+
nil,
125+
},
116126
{
117127
"failure: source channel not found",
118128
func() {

modules/apps/transfer/types/token.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package types
22

33
import (
4+
"math/big"
5+
46
errorsmod "cosmossdk.io/errors"
57
sdkmath "cosmossdk.io/math"
68

@@ -10,6 +12,9 @@ import (
1012
// Tokens is a slice of Tokens
1113
type Tokens []Token
1214

15+
// maxUint256 is the maximum value for a 256 bit unsigned integer.
16+
var maxUint256 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1))
17+
1318
// Validate validates a token denomination and amount.
1419
func (t Token) Validate() error {
1520
if err := t.Denom.Validate(); err != nil {
@@ -42,3 +47,12 @@ func (t Token) ToCoin() (sdk.Coin, error) {
4247
coin := sdk.NewCoin(t.Denom.IBCDenom(), transferAmount)
4348
return coin, nil
4449
}
50+
51+
// UnboundedSpendLimit returns the sentinel value that can be used
52+
// as the amount for a denomination's spend limit for which spend limit updating
53+
// should be disabled. Please note that using this sentinel value means that a grantee
54+
// will be granted the privilege to do ICS20 token transfers for the total amount
55+
// of the denomination available at the granter's account.
56+
func UnboundedSpendLimit() sdkmath.Int {
57+
return sdkmath.NewIntFromBigInt(maxUint256)
58+
}

0 commit comments

Comments
 (0)