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: make helper function for adding accounts to genesis state #13298

Merged
merged 27 commits into from
Sep 23, 2022
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
4f45d36
add genesis account helper
likhita-809 Sep 15, 2022
4660787
wip: clean up
likhita-809 Sep 15, 2022
fbadc23
fix something
likhita-809 Sep 15, 2022
a6dbe27
Merge branch 'main' of https://github.com/cosmos/cosmos-sdk into likh…
likhita-809 Sep 15, 2022
bda760e
wip: move add genesis account helper to auth module
likhita-809 Sep 15, 2022
049c208
wip
likhita-809 Sep 15, 2022
8373828
add inline doc for AddGenesisAccount func
likhita-809 Sep 15, 2022
268c941
address review comments
likhita-809 Sep 15, 2022
ae83616
nit
likhita-809 Sep 15, 2022
1ef0552
wip: use genesisFileUrl instead of config
likhita-809 Sep 20, 2022
10dad63
Merge branch 'main' of https://github.com/cosmos/cosmos-sdk into likh…
likhita-809 Sep 20, 2022
1de8641
add changelog
likhita-809 Sep 20, 2022
1b1cc69
Merge branch 'main' of https://github.com/cosmos/cosmos-sdk into likh…
likhita-809 Sep 20, 2022
abfc581
wip: nit
likhita-809 Sep 20, 2022
968ac50
Merge branch 'main' of https://github.com/cosmos/cosmos-sdk into likh…
likhita-809 Sep 20, 2022
614fb12
Merge branch 'main' of https://github.com/cosmos/cosmos-sdk into likh…
likhita-809 Sep 20, 2022
fcd4461
wip: apply suggestions
likhita-809 Sep 21, 2022
a7cc4a5
Merge branch 'main' of https://github.com/cosmos/cosmos-sdk into likh…
likhita-809 Sep 21, 2022
d86e4d0
address review comments
likhita-809 Sep 21, 2022
5c74c6e
Merge branch 'main' of https://github.com/cosmos/cosmos-sdk into likh…
likhita-809 Sep 21, 2022
8d5937a
fix lint issue
likhita-809 Sep 21, 2022
ca886bf
fix nit
likhita-809 Sep 21, 2022
7b03564
Merge branch 'main' of https://github.com/cosmos/cosmos-sdk into likh…
likhita-809 Sep 22, 2022
62d8a42
fix changelog
likhita-809 Sep 22, 2022
0ac6b78
Merge branch 'main' into likhita/add-genesis-account-helper
julienrbrt Sep 22, 2022
98c9b27
Merge branch 'main' into likhita/add-genesis-account-helper
julienrbrt Sep 23, 2022
723f7e4
Merge branch 'main' into likhita/add-genesis-account-helper
julienrbrt Sep 23, 2022
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Ref: https://keepachangelog.com/en/1.0.0/

### Features

* [#13298](https://github.com/cosmos/cosmos-sdk/pull/13298) Add `AddGenesisAccount` helper func in x/auth module which helps adding accounts to genesis state.
* (cli) [#13304](https://github.com/cosmos/cosmos-sdk/pull/13304) Add `tx gov draft-proposal` command for generating proposal JSONs.
* (cli) [#13207](https://github.com/cosmos/cosmos-sdk/pull/13207) Reduce user's password prompts when calling keyring `List()` function
* (x/authz) [#12648](https://github.com/cosmos/cosmos-sdk/pull/12648) Add an allow list, an optional list of addresses allowed to receive bank assets via authz MsgSend grant.
Expand Down
121 changes: 8 additions & 113 deletions simapp/simd/cmd/genaccounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ package cmd

import (
"bufio"
"encoding/json"
"errors"
"fmt"
"path/filepath"

"github.com/spf13/cobra"

Expand All @@ -13,11 +12,7 @@ import (
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
authvesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
auth "github.com/cosmos/cosmos-sdk/x/auth/helpers"
)

const (
Expand All @@ -39,6 +34,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
var genesisFileUrl string
clientCtx := client.GetClientContextFromCmd(cmd)
serverCtx := server.GetServerContextFromCmd(cmd)
config := serverCtx.Config
Expand Down Expand Up @@ -72,119 +68,18 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
}
}

coins, err := sdk.ParseCoinsNormalized(args[1])
if err != nil {
return fmt.Errorf("failed to parse coins: %w", err)
}

appendflag, _ := cmd.Flags().GetBool(flagAppendMode)

Check warning

Code scanning / gosec

Returned error is not propagated up the stack.

Returned error is not propagated up the stack.
vestingStart, _ := cmd.Flags().GetInt64(flagVestingStart)
vestingEnd, _ := cmd.Flags().GetInt64(flagVestingEnd)
vestingAmtStr, _ := cmd.Flags().GetString(flagVestingAmt)

vestingAmt, err := sdk.ParseCoinsNormalized(vestingAmtStr)
if err != nil {
return fmt.Errorf("failed to parse vesting amount: %w", err)
}

// create concrete account type based on input parameters
var genAccount authtypes.GenesisAccount

balances := banktypes.Balance{Address: addr.String(), Coins: coins.Sort()}
baseAccount := authtypes.NewBaseAccount(addr, nil, 0, 0)

if !vestingAmt.IsZero() {
baseVestingAccount := authvesting.NewBaseVestingAccount(baseAccount, vestingAmt.Sort(), vestingEnd)

if (balances.Coins.IsZero() && !baseVestingAccount.OriginalVesting.IsZero()) ||
baseVestingAccount.OriginalVesting.IsAnyGT(balances.Coins) {
return errors.New("vesting amount cannot be greater than total amount")
}

switch {
case vestingStart != 0 && vestingEnd != 0:
genAccount = authvesting.NewContinuousVestingAccountRaw(baseVestingAccount, vestingStart)

case vestingEnd != 0:
genAccount = authvesting.NewDelayedVestingAccountRaw(baseVestingAccount)

default:
return errors.New("invalid vesting parameters; must supply start and end time or end time")
}
} else {
genAccount = baseAccount
}

if err := genAccount.Validate(); err != nil {
return fmt.Errorf("failed to validate new genesis account: %w", err)
}

genFile := config.GenesisFile()
appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genFile)
if err != nil {
return fmt.Errorf("failed to unmarshal genesis state: %w", err)
}

authGenState := authtypes.GetGenesisStateFromAppState(clientCtx.Codec, appState)

accs, err := authtypes.UnpackAccounts(authGenState.Accounts)
if err != nil {
return fmt.Errorf("failed to get accounts from any: %w", err)
}

bankGenState := banktypes.GetGenesisStateFromAppState(clientCtx.Codec, appState)
if accs.Contains(addr) {
appendflag, _ := cmd.Flags().GetBool(flagAppendMode)
if !appendflag {
return fmt.Errorf("cannot add account at existing address %s", addr)
}

genesisB := banktypes.GetGenesisStateFromAppState(clientCtx.Codec, appState)
for idx, acc := range genesisB.Balances {
if acc.Address != addr.String() {
continue
}

updatedCoins := acc.Coins.Add(coins...)
bankGenState.Balances[idx] = banktypes.Balance{Address: addr.String(), Coins: updatedCoins.Sort()}
break
}
if filepath.IsAbs(config.Genesis) {
likhita-809 marked this conversation as resolved.
Show resolved Hide resolved
genesisFileUrl = config.Genesis
} else {
// Add the new account to the set of genesis accounts and sanitize the accounts afterwards.
accs = append(accs, genAccount)
accs = authtypes.SanitizeGenesisAccounts(accs)

genAccs, err := authtypes.PackAccounts(accs)
if err != nil {
return fmt.Errorf("failed to convert accounts into any's: %w", err)
}
authGenState.Accounts = genAccs

authGenStateBz, err := clientCtx.Codec.MarshalJSON(&authGenState)
if err != nil {
return fmt.Errorf("failed to marshal auth genesis state: %w", err)
}
appState[authtypes.ModuleName] = authGenStateBz

bankGenState.Balances = append(bankGenState.Balances, balances)
}

bankGenState.Balances = banktypes.SanitizeGenesisBalances(bankGenState.Balances)

bankGenState.Supply = bankGenState.Supply.Add(balances.Coins...)

bankGenStateBz, err := clientCtx.Codec.MarshalJSON(bankGenState)
if err != nil {
return fmt.Errorf("failed to marshal bank genesis state: %w", err)
}
appState[banktypes.ModuleName] = bankGenStateBz

appStateJSON, err := json.Marshal(appState)
if err != nil {
return fmt.Errorf("failed to marshal application genesis state: %w", err)
genesisFileUrl = filepath.Join(config.RootDir, config.Genesis)
}

genDoc.AppState = appStateJSON
return genutil.ExportGenesisFile(genDoc, genFile)
return auth.AddGenesisAccount(genesisFileUrl, clientCtx.Codec, addr, args[1], appendflag, vestingStart, vestingEnd, vestingAmtStr)
},
}

Expand Down
126 changes: 126 additions & 0 deletions x/auth/helpers/add_genesis_account_helper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package helpers

import (
"encoding/json"
"errors"
"fmt"

"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
authvesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
)

// AddGenesisAccount adds a genesis account to the genesis state.
func AddGenesisAccount(genesisFileUrl string, cdc codec.Codec, accAddr sdk.AccAddress, amountStr string, appendAcct bool, vestingStart, vestingEnd int64, vestingAmtStr string) error {
likhita-809 marked this conversation as resolved.
Show resolved Hide resolved
coins, err := sdk.ParseCoinsNormalized(amountStr)
if err != nil {
return fmt.Errorf("failed to parse coins: %w", err)
}

vestingAmt, err := sdk.ParseCoinsNormalized(vestingAmtStr)
if err != nil {
return fmt.Errorf("failed to parse vesting amount: %w", err)
}

// create concrete account type based on input parameters
var genAccount authtypes.GenesisAccount

balances := banktypes.Balance{Address: accAddr.String(), Coins: coins.Sort()}
baseAccount := authtypes.NewBaseAccount(accAddr, nil, 0, 0)

if !vestingAmt.IsZero() {
baseVestingAccount := authvesting.NewBaseVestingAccount(baseAccount, vestingAmt.Sort(), vestingEnd)

if (balances.Coins.IsZero() && !baseVestingAccount.OriginalVesting.IsZero()) ||
baseVestingAccount.OriginalVesting.IsAnyGT(balances.Coins) {
return errors.New("vesting amount cannot be greater than total amount")
}

switch {
case vestingStart != 0 && vestingEnd != 0:
genAccount = authvesting.NewContinuousVestingAccountRaw(baseVestingAccount, vestingStart)

case vestingEnd != 0:
genAccount = authvesting.NewDelayedVestingAccountRaw(baseVestingAccount)

default:
return errors.New("invalid vesting parameters; must supply start and end time or end time")
}
} else {
genAccount = baseAccount
}

if err := genAccount.Validate(); err != nil {
return fmt.Errorf("failed to validate new genesis account: %w", err)
}

appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genesisFileUrl)
if err != nil {
return fmt.Errorf("failed to unmarshal genesis state: %w", err)
}

authGenState := authtypes.GetGenesisStateFromAppState(cdc, appState)

accs, err := authtypes.UnpackAccounts(authGenState.Accounts)
if err != nil {
return fmt.Errorf("failed to get accounts from any: %w", err)
}

bankGenState := banktypes.GetGenesisStateFromAppState(cdc, appState)
if accs.Contains(accAddr) {
if !appendAcct {
return fmt.Errorf(" Account %s already exists\nUse `append` flag to append account at existing address", accAddr)
}

genesisB := banktypes.GetGenesisStateFromAppState(cdc, appState)
for idx, acc := range genesisB.Balances {
if acc.Address != accAddr.String() {
continue
}

updatedCoins := acc.Coins.Add(coins...)
bankGenState.Balances[idx] = banktypes.Balance{Address: accAddr.String(), Coins: updatedCoins.Sort()}
break
}
} else {
// Add the new account to the set of genesis accounts and sanitize the accounts afterwards.
accs = append(accs, genAccount)
accs = authtypes.SanitizeGenesisAccounts(accs)

genAccs, err := authtypes.PackAccounts(accs)
if err != nil {
return fmt.Errorf("failed to convert accounts into any's: %w", err)
}
authGenState.Accounts = genAccs

authGenStateBz, err := cdc.MarshalJSON(&authGenState)
if err != nil {
return fmt.Errorf("failed to marshal auth genesis state: %w", err)
}
appState[authtypes.ModuleName] = authGenStateBz

bankGenState.Balances = append(bankGenState.Balances, balances)
}

bankGenState.Balances = banktypes.SanitizeGenesisBalances(bankGenState.Balances)

bankGenState.Supply = bankGenState.Supply.Add(balances.Coins...)

bankGenStateBz, err := cdc.MarshalJSON(bankGenState)
if err != nil {
return fmt.Errorf("failed to marshal bank genesis state: %w", err)
}
appState[banktypes.ModuleName] = bankGenStateBz

appStateJSON, err := json.Marshal(appState)
if err != nil {
return fmt.Errorf("failed to marshal application genesis state: %w", err)
}

genDoc.AppState = appStateJSON
return genutil.ExportGenesisFile(genDoc, genesisFileUrl)
}