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

EVM-720 Implement json output for all commands #1724

Merged
merged 11 commits into from
Jul 24, 2023
2 changes: 1 addition & 1 deletion command/json_output.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func (jo *jsonOutput) WriteOutput() {

// WriteCommandResult implements OutputFormatter interface
func (jo *jsonOutput) WriteCommandResult(result CommandResult) {
_, _ = fmt.Fprintln(os.Stdout, result.GetOutput())
_, _ = fmt.Fprintln(os.Stdout, marshalJSONToString(result))
}

// WriteOutput implements OutputFormatter plus io.Writer interfaces
Expand Down
56 changes: 36 additions & 20 deletions command/rootchain/deploy/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,12 @@ var (
}
)

type deploymentResultInfo struct {
RootchainCfg *polybft.RootchainConfig
SupernetID int64
CommandResults []command.CommandResult
}

// GetCommand returns the rootchain deploy command
func GetCommand() *cobra.Command {
cmd := &cobra.Command{
Expand Down Expand Up @@ -337,16 +343,17 @@ func runCommand(cmd *cobra.Command, _ []string) {
}
}

rootchainCfg, supernetID, err := deployContracts(outputter, client,
deploymentResultInfo, err := deployContracts(outputter, client,
chainConfig.Params.ChainID, consensusCfg.InitialValidatorSet, cmd.Context())
if err != nil {
outputter.SetError(fmt.Errorf("failed to deploy rootchain contracts: %w", err))
outputter.SetCommandResult(command.Results(deploymentResultInfo.CommandResults))

return
}

// populate bridge configuration
bridgeConfig := rootchainCfg.ToBridgeConfig()
bridgeConfig := deploymentResultInfo.RootchainCfg.ToBridgeConfig()
if consensusCfg.Bridge != nil {
// only true if stake-manager-deploy command was executed
// users can still deploy stake manager manually
Expand All @@ -365,9 +372,9 @@ func runCommand(cmd *cobra.Command, _ []string) {
}

consensusCfg.Bridge.EventTrackerStartBlocks = map[types.Address]uint64{
rootchainCfg.StateSenderAddress: blockNum,
deploymentResultInfo.RootchainCfg.StateSenderAddress: blockNum,
}
consensusCfg.SupernetID = supernetID
consensusCfg.SupernetID = deploymentResultInfo.SupernetID

// write updated consensus configuration
chainConfig.Params.Engine[polybft.ConsensusName] = consensusCfg
Expand All @@ -378,31 +385,32 @@ func runCommand(cmd *cobra.Command, _ []string) {
return
}

outputter.SetCommandResult(&helper.MessageResult{
deploymentResultInfo.CommandResults = append(deploymentResultInfo.CommandResults, &helper.MessageResult{
Message: fmt.Sprintf("%s finished. All contracts are successfully deployed and initialized.",
contractsDeploymentTitle),
})
outputter.SetCommandResult(command.Results(deploymentResultInfo.CommandResults))
}

// deployContracts deploys and initializes rootchain smart contracts
func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client, chainID int64,
initialValidators []*validator.GenesisValidator, cmdCtx context.Context) (*polybft.RootchainConfig, int64, error) {
initialValidators []*validator.GenesisValidator, cmdCtx context.Context) (deploymentResultInfo, error) {
txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(client), txrelayer.WithWriter(outputter))
if err != nil {
return nil, 0, fmt.Errorf("failed to initialize tx relayer: %w", err)
return deploymentResultInfo{nil, 0, nil}, fmt.Errorf("failed to initialize tx relayer: %w", err)
}

deployerKey, err := helper.DecodePrivateKey(params.deployerKey)
if err != nil {
return nil, 0, fmt.Errorf("failed to initialize deployer key: %w", err)
return deploymentResultInfo{nil, 0, nil}, fmt.Errorf("failed to initialize deployer key: %w", err)
}

if params.isTestMode {
deployerAddr := deployerKey.Address()
txn := &ethgo.Transaction{To: &deployerAddr, Value: ethgo.Ether(1)}

if _, err = txRelayer.SendTransactionLocal(txn); err != nil {
return nil, 0, err
return deploymentResultInfo{nil, 0, nil}, err
}
}

Expand All @@ -425,7 +433,7 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client,
// use existing root chain ERC20 token
if err := populateExistingTokenAddr(client.Eth(),
params.rootERC20TokenAddr, rootERC20Name, rootchainConfig); err != nil {
return nil, 0, err
return deploymentResultInfo{nil, 0, nil}, err
}
} else {
// deploy MockERC20 as a root chain root native token
Expand Down Expand Up @@ -501,6 +509,7 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client,

g, ctx := errgroup.WithContext(cmdCtx)
results := make([]*deployContractResult, len(allContracts))
commandResults := make([]command.CommandResult, len(allContracts))

for i, contract := range allContracts {
i := i
Expand Down Expand Up @@ -536,28 +545,35 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client,
}

if err := g.Wait(); err != nil {
_, _ = outputter.Write([]byte("[ROOTCHAIN - DEPLOY] Successfully deployed the following contracts\n"))
results := []command.CommandResult{}
Stefan-Ethernal marked this conversation as resolved.
Show resolved Hide resolved

for _, result := range results {
messageResult := helper.MessageResult{
Message: "[ROOTCHAIN - DEPLOY] Successfully deployed the following contracts\n"}
results = append(results, messageResult)

for i, result := range results {
if result != nil {
// In case an error happened, some of the indices may not be populated.
// Filter those out.
outputter.WriteCommandResult(result)
commandResults[i] = result
}
Stefan-Ethernal marked this conversation as resolved.
Show resolved Hide resolved
}

return nil, 0, err
results = append(results, commandResults...)

return deploymentResultInfo{nil, 0, results}, err
Stefan-Ethernal marked this conversation as resolved.
Show resolved Hide resolved
}

for _, result := range results {
for i, result := range results {
populatorFn, ok := metadataPopulatorMap[result.Name]
if !ok {
return nil, 0, fmt.Errorf("rootchain metadata populator not registered for contract '%s'", result.Name)
return deploymentResultInfo{nil, 0, nil},
fmt.Errorf("rootchain metadata populator not registered for contract '%s'", result.Name)
}

populatorFn(rootchainConfig, result.Address)

outputter.WriteCommandResult(result)
commandResults[i] = result
}

g, ctx = errgroup.WithContext(cmdCtx)
Expand All @@ -581,16 +597,16 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client,
}

if err := g.Wait(); err != nil {
return nil, 0, err
return deploymentResultInfo{nil, 0, nil}, err
}

// register supernets manager on stake manager
supernetID, err := registerChainOnStakeManager(txRelayer, rootchainConfig, deployerKey)
if err != nil {
return nil, 0, err
return deploymentResultInfo{nil, 0, nil}, err
}

return rootchainConfig, supernetID, nil
return deploymentResultInfo{rootchainConfig, supernetID, commandResults}, nil
}

// populateExistingTokenAddr checks whether given token is deployed on the provided address.
Expand Down
2 changes: 1 addition & 1 deletion command/rootchain/deploy/deploy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func TestDeployContracts_NoPanics(t *testing.T) {
}

require.NotPanics(t, func() {
_, _, err = deployContracts(outputter, client, 1, []*validator.GenesisValidator{}, context.Background())
_, err = deployContracts(outputter, client, 1, []*validator.GenesisValidator{}, context.Background())
})
require.NoError(t, err)
}
4 changes: 2 additions & 2 deletions command/rootchain/staking/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ func (sp *stakeParams) validateFlags() (err error) {
}

type stakeResult struct {
validatorAddress string
amount *big.Int
validatorAddress string `json:"validatorAddress"`
amount *big.Int `json:"amount"`
}

func (sr stakeResult) GetOutput() string {
Expand Down
8 changes: 4 additions & 4 deletions command/rootchain/supernet/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ func (sp *supernetParams) validateFlags() error {
}

type supernetResult struct {
isGenesisSetFinalized bool
isStakingEnabled bool
IsGenesisSetFinalized bool `json:"isGenesisSetFinalized"`
IsStakingEnabled bool `json:"isStakingEnabled"`
}

func (sr supernetResult) GetOutput() string {
Expand All @@ -54,11 +54,11 @@ func (sr supernetResult) GetOutput() string {

buffer.WriteString("\n[SUPERNET COMMAND]\n")

if sr.isGenesisSetFinalized {
if sr.IsGenesisSetFinalized {
vals = append(vals, "Genesis validator set finalized on supernet manager")
}

if sr.isStakingEnabled {
if sr.IsStakingEnabled {
vals = append(vals, "Staking enabled on supernet manager")
}

Expand Down
4 changes: 2 additions & 2 deletions command/rootchain/supernet/supernet.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,8 +225,8 @@ func runCommand(cmd *cobra.Command, _ []string) error {
}

result := &supernetResult{
isGenesisSetFinalized: params.finalizeGenesisSet,
isStakingEnabled: params.enableStaking,
IsGenesisSetFinalized: params.finalizeGenesisSet,
IsStakingEnabled: params.enableStaking,
}

outputter.WriteCommandResult(result)
Expand Down
16 changes: 8 additions & 8 deletions command/rootchain/validators/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ func (v *validatorInfoParams) validateFlags() error {
}

type validatorsInfoResult struct {
address string
stake uint64
active bool
whitelisted bool
Address string `json:"address"`
Stake uint64 `json:"stake"`
Active bool `json:"active"`
Whitelisted bool `json:"whitelisted"`
}

func (vr validatorsInfoResult) GetOutput() string {
Expand All @@ -34,10 +34,10 @@ func (vr validatorsInfoResult) GetOutput() string {
buffer.WriteString("\n[VALIDATOR INFO]\n")

vals := make([]string, 4)
vals[0] = fmt.Sprintf("Validator Address|%s", vr.address)
vals[1] = fmt.Sprintf("Stake|%v", vr.stake)
vals[2] = fmt.Sprintf("Is Whitelisted|%v", vr.whitelisted)
vals[3] = fmt.Sprintf("Is Active|%v", vr.active)
vals[0] = fmt.Sprintf("Validator Address|%s", vr.Address)
vals[1] = fmt.Sprintf("Stake|%v", vr.Stake)
vals[2] = fmt.Sprintf("Is Whitelisted|%v", vr.Whitelisted)
vals[3] = fmt.Sprintf("Is Active|%v", vr.Active)

buffer.WriteString(helper.FormatKV(vals))
buffer.WriteString("\n")
Expand Down
8 changes: 4 additions & 4 deletions command/rootchain/validators/validator_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,10 @@ func runCommand(cmd *cobra.Command, _ []string) error {
}

outputter.WriteCommandResult(&validatorsInfoResult{
address: validatorInfo.Address.String(),
stake: validatorInfo.Stake.Uint64(),
active: validatorInfo.IsActive,
whitelisted: validatorInfo.IsWhitelisted,
Address: validatorInfo.Address.String(),
Stake: validatorInfo.Stake.Uint64(),
Active: validatorInfo.IsActive,
Whitelisted: validatorInfo.IsWhitelisted,
})

return nil
Expand Down
6 changes: 3 additions & 3 deletions command/rootchain/whitelist/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,16 @@ func (ep *whitelistParams) validateFlags() error {
}

type whitelistResult struct {
newValidatorAddresses []string
NewValidatorAddresses []string `json:"newValidatorAddresses"`
}

func (wr whitelistResult) GetOutput() string {
var buffer bytes.Buffer

buffer.WriteString("\n[WHITELIST VALIDATORS]\n")

vals := make([]string, len(wr.newValidatorAddresses))
for i, addr := range wr.newValidatorAddresses {
vals := make([]string, len(wr.NewValidatorAddresses))
for i, addr := range wr.NewValidatorAddresses {
vals[i] = fmt.Sprintf("Validator address|%s", addr)
}

Expand Down
4 changes: 2 additions & 2 deletions command/rootchain/whitelist/whitelist_validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,10 @@ func runCommand(cmd *cobra.Command, _ []string) error {
return err
}

result.newValidatorAddresses = append(result.newValidatorAddresses, whitelistEvent.Validator.String())
result.NewValidatorAddresses = append(result.NewValidatorAddresses, whitelistEvent.Validator.String())
}

if len(result.newValidatorAddresses) != len(params.newValidatorAddresses) {
if len(result.NewValidatorAddresses) != len(params.newValidatorAddresses) {
return fmt.Errorf("whitelist of validators did not pass successfully")
}

Expand Down
12 changes: 6 additions & 6 deletions command/rootchain/withdraw/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ func (v *withdrawParams) validateFlags() (err error) {
}

type withdrawResult struct {
validatorAddress string
amount uint64
withdrawnTo string
ValidatorAddress string `json:"validatorAddress"`
Amount uint64 `json:"amount"`
WithdrawnTo string `json:"withdrawnTo"`
}

func (wr withdrawResult) GetOutput() string {
Expand All @@ -44,9 +44,9 @@ func (wr withdrawResult) GetOutput() string {
buffer.WriteString("\n[WITHDRAWN AMOUNT]\n")

vals := make([]string, 0, 3)
vals = append(vals, fmt.Sprintf("Validator Address|%s", wr.validatorAddress))
vals = append(vals, fmt.Sprintf("Amount Withdrawn|%v", wr.amount))
vals = append(vals, fmt.Sprintf("Withdrawn To|%s", wr.withdrawnTo))
vals = append(vals, fmt.Sprintf("Validator Address|%s", wr.ValidatorAddress))
vals = append(vals, fmt.Sprintf("Amount Withdrawn|%v", wr.Amount))
vals = append(vals, fmt.Sprintf("Withdrawn To|%s", wr.WithdrawnTo))

buffer.WriteString(helper.FormatKV(vals))
buffer.WriteString("\n")
Expand Down
6 changes: 3 additions & 3 deletions command/rootchain/withdraw/withdraw.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ func runCommand(cmd *cobra.Command, _ []string) error {
}

result := &withdrawResult{
validatorAddress: validatorAccount.Ecdsa.Address().String(),
ValidatorAddress: validatorAccount.Ecdsa.Address().String(),
}

var (
Expand All @@ -137,8 +137,8 @@ func runCommand(cmd *cobra.Command, _ []string) error {
return err
}

result.amount = withdrawalEvent.Amount.Uint64()
result.withdrawnTo = withdrawalEvent.Recipient.String()
result.Amount = withdrawalEvent.Amount.Uint64()
result.WithdrawnTo = withdrawalEvent.Recipient.String()
foundLog = true

break
Expand Down
8 changes: 4 additions & 4 deletions command/sidechain/rewards/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ type withdrawRewardsParams struct {
}

type withdrawRewardResult struct {
validatorAddress string
rewardAmount uint64
ValidatorAddress string `json:"validatorAddress"`
RewardAmount uint64 `json:"rewardAmount"`
}

func (w *withdrawRewardsParams) validateFlags() error {
Expand All @@ -29,8 +29,8 @@ func (wr withdrawRewardResult) GetOutput() string {
buffer.WriteString("\n[WITHDRAW REWARDS]\n")

vals := make([]string, 0, 2)
vals = append(vals, fmt.Sprintf("Validator Address|%s", wr.validatorAddress))
vals = append(vals, fmt.Sprintf("Amount Withdrawn|%v", wr.rewardAmount))
vals = append(vals, fmt.Sprintf("Validator Address|%s", wr.ValidatorAddress))
vals = append(vals, fmt.Sprintf("Amount Withdrawn|%v", wr.RewardAmount))

buffer.WriteString(helper.FormatKV(vals))
buffer.WriteString("\n")
Expand Down
4 changes: 2 additions & 2 deletions command/sidechain/rewards/rewards.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ func runCommand(cmd *cobra.Command, _ []string) error {
}

result := &withdrawRewardResult{
validatorAddress: validatorAccount.Ecdsa.Address().String(),
rewardAmount: amount.Uint64(),
ValidatorAddress: validatorAccount.Ecdsa.Address().String(),
RewardAmount: amount.Uint64(),
}

outputter.WriteCommandResult(result)
Expand Down
Loading