Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: implement multi-send transaction command #11738

Merged
merged 22 commits into from
Apr 29, 2022
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ Ref: https://keepachangelog.com/en/1.0.0/

### Features

* (grpc) [\#11642](https://github.com/cosmos/cosmos-sdk/pull/11642) Implement `ABCIQuery` in the Tendermint gRPC service, which proxies ABCI `Query` requests directly to the application.
* (cli) [\#11738](https://github.com/cosmos/cosmos-sdk/pull/11738) Add `tx bank multi-send` command for bulk send of coins to multiple accounts.
* (grpc) [11642](https://github.com/cosmos/cosmos-sdk/pull/11642) Implement `ABCIQuery` in the Tendermint gRPC service, which proxies ABCI `Query` requests directly to the application.
* (x/upgrade) [\#11551](https://github.com/cosmos/cosmos-sdk/pull/11551) Update `ScheduleUpgrade` for chains to schedule an automated upgrade on `BeginBlock` without having to go though governance.
* (cli) [\#11548](https://github.com/cosmos/cosmos-sdk/pull/11548) Add Tendermint's `inspect` command to the `tendermint` sub-command.
* (tx) [#\11533](https://github.com/cosmos/cosmos-sdk/pull/11533) Register [`EIP191`](https://eips.ethereum.org/EIPS/eip-191) as an available `SignMode` for chains to use.
Expand Down
65 changes: 65 additions & 0 deletions types/coin.go
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,71 @@ func (coins Coins) SafeSub(coinsB ...Coin) (Coins, bool) {
return diff, diff.IsAnyNegative()
}

// MulInt performs the scalar multiplication of coins with a `multiplier`
// All coins are multipled by x
// e.g.
// {2A, 3B} * 2 = {4A, 6B}
// {2A} * 0 panics
// Note, if IsValid was true on Coins, IsValid stays true.
func (coins Coins) MulInt(x Int) Coins {
coins, ok := coins.SafeMulInt(x)
if !ok {
panic("multiplying by zero is an invalid operation on coins")
}

return coins
}

// SafeMulInt performs the same arithmetic as MulInt but returns false
// if the `multiplier` is zero because it makes IsValid return false.
func (coins Coins) SafeMulInt(x Int) (Coins, bool) {
julienrbrt marked this conversation as resolved.
Show resolved Hide resolved
if x.IsNil() || x.IsZero() {
julienrbrt marked this conversation as resolved.
Show resolved Hide resolved
return nil, false
}

res := make(Coins, len(coins))
for i, coin := range coins {
coin := coin
res[i] = NewCoin(coin.Denom, coin.Amount.Mul(x))
}

return res, true
}

// QuoInt performs the scalar division of coins with a `divisor`
// All coins are divided by x and trucated.
// e.g.
// {2A, 30B} / 2 = {1A, 15B}
// {2A} / 2 = {1A}
// {4A} / {8A} = {0A}
// {2A} / 0 = panics
// Note, if IsValid was true on Coins, IsValid stays true,
// unless the `divisor` is greater than the smallest coin amount.
Copy link
Member Author

@julienrbrt julienrbrt Apr 24, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am uncertain if we actually want this behavior, but I created these helpers function for avoiding having to do for every coin:

sendCoins := coins
if split && !coins.IsZero() {
    sendCoins[0].Amount = coins[0].Amount.Quo(totalAddr)
}

If you find this better, then I can modify it and remove the changes in coins.

func (coins Coins) QuoInt(x Int) Coins {
coins, ok := coins.SafeQuoInt(x)
if !ok {
panic("dividing by zero is an invalid operation on coins")
}

return coins
}

// SafeQuoInt performs the same arithmetic as QuoInt but returns an error
julienrbrt marked this conversation as resolved.
Show resolved Hide resolved
// if the division cannot be done.
func (coins Coins) SafeQuoInt(x Int) (Coins, bool) {
if x.IsNil() || x.IsZero() {
julienrbrt marked this conversation as resolved.
Show resolved Hide resolved
return nil, false
}

var res Coins
for _, coin := range coins {
coin := coin
res = append(res, NewCoin(coin.Denom, coin.Amount.Quo(x)))
}

return res, true
}

// Max takes two valid Coins inputs and returns a valid Coins result
// where for every denom D, AmountOf(D) of the result is the maximum
// of AmountOf(D) of the inputs. Note that the result might be not
Expand Down
60 changes: 57 additions & 3 deletions types/coin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ var (

type coinTestSuite struct {
suite.Suite
ca0, ca1, ca2, cm0, cm1, cm2 sdk.Coin
ca0, ca1, ca2, ca4, cm0, cm1, cm2, cm4 sdk.Coin
}

func TestCoinTestSuite(t *testing.T) {
Expand All @@ -30,8 +30,10 @@ func (s *coinTestSuite) SetupSuite() {
zero := sdk.NewInt(0)
one := sdk.OneInt()
two := sdk.NewInt(2)
s.ca0, s.ca1, s.ca2 = sdk.Coin{testDenom1, zero}, sdk.Coin{testDenom1, one}, sdk.Coin{testDenom1, two}
s.cm0, s.cm1, s.cm2 = sdk.Coin{testDenom2, zero}, sdk.Coin{testDenom2, one}, sdk.Coin{testDenom2, two}
four := sdk.NewInt(4)

s.ca0, s.ca1, s.ca2, s.ca4 = sdk.NewCoin(testDenom1, zero), sdk.NewCoin(testDenom1, one), sdk.NewCoin(testDenom1, two), sdk.NewCoin(testDenom1, four)
s.cm0, s.cm1, s.cm2, s.cm4 = sdk.NewCoin(testDenom2, zero), sdk.NewCoin(testDenom2, one), sdk.NewCoin(testDenom2, two), sdk.NewCoin(testDenom2, four)
}

// ----------------------------------------------------------------------------
Expand Down Expand Up @@ -224,6 +226,58 @@ func (s *coinTestSuite) TestSubCoinAmount() {
}
}

func (s *coinTestSuite) TestMulIntCoins() {
testCases := []struct {
input sdk.Coins
multiplier sdk.Int
expected sdk.Coins
shouldPanic bool
}{
{sdk.Coins{s.ca2}, sdk.NewInt(0), sdk.Coins{s.ca0}, true},
{sdk.Coins{s.ca2}, sdk.NewInt(2), sdk.Coins{s.ca4}, false},
{sdk.Coins{s.ca1, s.cm2}, sdk.NewInt(2), sdk.Coins{s.ca2, s.cm4}, false},
}

assert := s.Assert()
for i, tc := range testCases {
tc := tc
if tc.shouldPanic {
assert.Panics(func() { tc.input.MulInt(tc.multiplier) })
} else {
res := tc.input.MulInt(tc.multiplier)
assert.True(res.IsValid())
assert.Equal(tc.expected, res, "multiplication of coins is incorrect, tc #%d", i)
}
}
}

func (s *coinTestSuite) TestQuoIntCoins() {
testCases := []struct {
input sdk.Coins
divisor sdk.Int
expected sdk.Coins
isValid bool
shouldPanic bool
}{
{sdk.Coins{s.ca2, s.ca1}, sdk.NewInt(0), sdk.Coins{s.ca0, s.ca0}, true, true},
{sdk.Coins{s.ca2}, sdk.NewInt(4), sdk.Coins{s.ca0}, false, false},
{sdk.Coins{s.ca2, s.cm4}, sdk.NewInt(2), sdk.Coins{s.ca1, s.cm2}, true, false},
{sdk.Coins{s.ca4}, sdk.NewInt(2), sdk.Coins{s.ca2}, true, false},
}

assert := s.Assert()
for i, tc := range testCases {
tc := tc
if tc.shouldPanic {
assert.Panics(func() { tc.input.QuoInt(tc.divisor) })
} else {
res := tc.input.QuoInt(tc.divisor)
assert.Equal(tc.isValid, res.IsValid())
assert.Equal(tc.expected, res, "quotient of coins is incorrect, tc #%d", i)
}
}
}

func (s *coinTestSuite) TestIsGTECoin() {
cases := []struct {
inputOne sdk.Coin
Expand Down
93 changes: 88 additions & 5 deletions x/bank/client/cli/tx.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cli

import (
"fmt"

"github.com/spf13/cobra"

"github.com/cosmos/cosmos-sdk/client"
Expand All @@ -10,6 +12,8 @@ import (
"github.com/cosmos/cosmos-sdk/x/bank/types"
)

var FlagSplit = "split"

// NewTxCmd returns a root CLI command handler for all x/bank transaction commands.
func NewTxCmd() *cobra.Command {
txCmd := &cobra.Command{
Expand All @@ -20,18 +24,23 @@ func NewTxCmd() *cobra.Command {
RunE: client.ValidateCmd,
}

txCmd.AddCommand(NewSendTxCmd())
txCmd.AddCommand(
NewSendTxCmd(),
NewMultiSendTxCmd(),
)

return txCmd
}

// NewSendTxCmd returns a CLI command handler for creating a MsgSend transaction.
func NewSendTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "send [from_key_or_address] [to_address] [amount]",
Short: `Send funds from one account to another.
Note, the '--from' flag is ignored as it is implied from [from_key_or_address].
When using '--dry-run' a key name cannot be used, only a bech32 address.`,
Use: "send [from_key_or_address] [to_address] [amount]",
Short: "Send funds from one account to another.",
Long: `Send funds from one account to another.
Note, the '--from' flag is ignored as it is implied from [from_key_or_address].
When using '--dry-run' a key name cannot be used, only a bech32 address.
`,
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
cmd.Flags().Set(flags.FlagFrom, args[0])
Expand Down Expand Up @@ -60,3 +69,77 @@ func NewSendTxCmd() *cobra.Command {

return cmd
}

// NewMultiSendTxCmd returns a CLI command handler for creating a MsgMultiSend transaction.
// For a better UX this command is limited to send one coin from one address to multiple addresses.
julienrbrt marked this conversation as resolved.
Show resolved Hide resolved
func NewMultiSendTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "multi-send [from_key_or_address] [to_address_1, to_address_2, ...] [amount]",
Short: "Send funds from one account to multiple others.",
Long: `Send funds from one account multiple others.
By default, sends the [amount] to each address of the list.
Using the '--split' flag, the [amount] is split equally between the addresses.
Note, the '--from' flag is ignored as it is implied from [from_key_or_address].
When using '--dry-run' a key name cannot be used, only a bech32 address.
`,
Args: cobra.MinimumNArgs(4),
julienrbrt marked this conversation as resolved.
Show resolved Hide resolved
RunE: func(cmd *cobra.Command, args []string) error {
cmd.Flags().Set(flags.FlagFrom, args[0])
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}

coins, err := sdk.ParseCoinsNormalized(args[len(args)-1])
if err != nil {
return err
}

if coins.IsZero() {
return fmt.Errorf("must send positive amount")
}

split, err := cmd.Flags().GetBool(FlagSplit)
if err != nil {
return err
}

totalAddrs := sdk.NewInt(int64(len(args) - 2))
// coins to be received by the addresses
sendCoins := coins
if split {
sendCoins = coins.QuoInt(totalAddrs)
}

var output []types.Output
for _, arg := range args[1 : len(args)-1] {
toAddr, err := sdk.AccAddressFromBech32(arg)
if err != nil {
return err
}

output = append(output, types.NewOutput(toAddr, sendCoins))
}

// amount to be send from the from address
var amount sdk.Coins
if split {
// user input: 1000stake to send to 3 addresses
// actual: 333stake to each address (=> 999stake actually sent)
amount = sendCoins.MulInt(totalAddrs)
} else {
amount = coins.MulInt(totalAddrs)
}

msg := types.NewMsgMultiSend([]types.Input{types.NewInput(clientCtx.FromAddress, amount)}, output)

return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
},
}

cmd.Flags().Bool(FlagSplit, false, "Send the equally split token amount to each address")

flags.AddTxFlagsToCmd(cmd)

return cmd
}
53 changes: 38 additions & 15 deletions x/bank/types/msgs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/stretchr/testify/require"

sdk "github.com/cosmos/cosmos-sdk/types"
types "github.com/cosmos/cosmos-sdk/types"
)

func TestMsgSendRoute(t *testing.T) {
Expand Down Expand Up @@ -184,24 +185,46 @@ func TestMsgMultiSendValidation(t *testing.T) {
{false, MsgMultiSend{}}, // no input or output
{false, MsgMultiSend{Inputs: []Input{input1}}}, // just input
{false, MsgMultiSend{Outputs: []Output{output1}}}, // just output
{false, MsgMultiSend{
Inputs: []Input{NewInput(emptyAddr, atom123)}, // invalid input
Outputs: []Output{output1}}},
{false, MsgMultiSend{
Inputs: []Input{input1},
Outputs: []Output{{emptyAddr.String(), atom123}}}, // invalid output
{
false,
MsgMultiSend{
Inputs: []Input{NewInput(emptyAddr, atom123)}, // invalid input
Outputs: []Output{output1}},
},
{false, MsgMultiSend{
Inputs: []Input{input1},
Outputs: []Output{output2}}, // amounts dont match
{
false,
MsgMultiSend{
Inputs: []Input{input1},
Outputs: []Output{{emptyAddr.String(), atom123}}, // invalid output
},
},
{true, MsgMultiSend{
Inputs: []Input{input1},
Outputs: []Output{output1}},
{
false,
MsgMultiSend{
Inputs: []Input{input1},
Outputs: []Output{output2}, // amounts dont match
},
},
{true, MsgMultiSend{
Inputs: []Input{input1, input2},
Outputs: []Output{outputMulti}},
{
true,
MsgMultiSend{
Inputs: []Input{input1},
Outputs: []Output{output1},
},
},
{
true,
MsgMultiSend{
Inputs: []Input{input1, input2},
Outputs: []Output{outputMulti},
},
},
{
true,
MsgMultiSend{
Inputs: []Input{NewInput(addr2, atom123.MulInt(types.NewInt(2)))},
Outputs: []Output{output1, output1},
},
},
}

Expand Down