Skip to content

Commit

Permalink
feat: Add a no-output flag to roller init and register (#406)
Browse files Browse the repository at this point in the history
  • Loading branch information
ItayLevyOfficial authored Aug 21, 2023
1 parent ec6cd87 commit 7624ca9
Show file tree
Hide file tree
Showing 9 changed files with 171 additions and 109 deletions.
2 changes: 2 additions & 0 deletions cmd/config/init/consts.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ var FlagNames = struct {
Interactive string
DAType string
VMType string
NoOutput string
}{
TokenSupply: "token-supply",
RollappBinary: "rollapp-binary",
Expand All @@ -18,6 +19,7 @@ var FlagNames = struct {
Decimals: "decimals",
DAType: "da",
VMType: "vm-type",
NoOutput: "no-output",
}

const (
Expand Down
23 changes: 23 additions & 0 deletions cmd/config/init/dir_not_empty.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package initconfig

import (
"fmt"
"os"
)

func dirNotEmpty(path string) (bool, error) {
info, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}

if !info.IsDir() {
return false, fmt.Errorf("%s is not a directory", path)
}

files, err := os.ReadDir(path)
return len(files) > 0, err
}
2 changes: 1 addition & 1 deletion cmd/config/init/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ func addFlags(cmd *cobra.Command) error {
cmd.Flags().StringP(FlagNames.VMType, "", string(config.EVM_ROLLAPP), "The rollapp type [evm, sdk]. Defaults to evm")
cmd.Flags().StringP(FlagNames.TokenSupply, "", defaultTokenSupply, "The total token supply of the RollApp")
cmd.Flags().BoolP(FlagNames.Interactive, "i", false, "Run roller in interactive mode")
cmd.Flags().BoolP(FlagNames.NoOutput, "", false, "Run init without any output")
cmd.Flags().UintP(FlagNames.Decimals, "", 18,
"The precision level of the RollApp's token defined by the number of decimal places. "+
"It should be an integer ranging between 1 and 18. This is akin to how 1 Ether equates to 10^18 Wei in Ethereum. "+
"Note: EVM RollApps must set this value to 18.")

cmd.Flags().StringP(FlagNames.DAType, "", "Celestia", "The DA layer for the RollApp. Can be one of 'Celestia, Avail, Mock'")

// TODO: Expose when supporting custom sdk rollapps.
Expand Down
46 changes: 46 additions & 0 deletions cmd/config/init/format.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package initconfig

import (
"fmt"
"github.com/dymensionxyz/roller/cmd/consts"
"github.com/dymensionxyz/roller/cmd/utils"
"github.com/dymensionxyz/roller/config"
datalayer "github.com/dymensionxyz/roller/data_layer"
"strings"
)

func formatAddresses(rollappConfig config.RollappConfig, addresses []utils.AddressData) []utils.AddressData {
damanager := datalayer.NewDAManager(rollappConfig.DA, rollappConfig.Home)
requireFundingKeys := map[string]string{
consts.KeysIds.HubSequencer: fmt.Sprintf("Sequencer, %s Hub", rollappConfig.HubData.ID),
consts.KeysIds.HubRelayer: fmt.Sprintf("Relayer, %s Hub", rollappConfig.HubData.ID),
damanager.GetKeyName(): fmt.Sprintf("DA, %s Network", damanager.GetNetworkName()),
}
filteredAddresses := make([]utils.AddressData, 0)
for _, address := range addresses {
if newName, ok := requireFundingKeys[address.Name]; ok {
address.Name = newName
filteredAddresses = append(filteredAddresses, address)
}
}
return filteredAddresses
}

func FormatTokenSupplyLine(rollappConfig config.RollappConfig) string {
displayDenom := strings.ToUpper(rollappConfig.Denom[1:])
return fmt.Sprintf("💰 Total Token Supply: %s %s. Note that 1 %s == 1 * 10^%d %s (like 1 ETH == 1 * 10^18 wei).",
addCommasToNum(rollappConfig.TokenSupply), displayDenom, displayDenom, rollappConfig.Decimals, "u"+displayDenom)
}

func addCommasToNum(number string) string {
var result strings.Builder
n := len(number)

for i := 0; i < n; i++ {
if i > 0 && (n-i)%3 == 0 {
result.WriteString(",")
}
result.WriteByte(number[i])
}
return result.String()
}
25 changes: 13 additions & 12 deletions cmd/config/init/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,18 @@ A valid denom should consist of 3-6 English alphabet letters, for example, 'btc'
}

func runInit(cmd *cobra.Command, args []string) error {
noOutput, err := cmd.Flags().GetBool(FlagNames.NoOutput)
if err != nil {
return err
}
initConfig, err := GetInitConfig(cmd, args)
if err != nil {
return err
}
spin := utils.GetLoadingSpinner()
spin.Suffix = consts.SpinnerMsgs.UniqueIdVerification
utils.RunOnInterrupt(spin.Stop)
spin.Start()
defer spin.Stop()
outputHandler := NewOutputHandler(noOutput)
defer outputHandler.StopSpinner()
utils.RunOnInterrupt(outputHandler.StopSpinner)
outputHandler.StartSpinner(consts.SpinnerMsgs.UniqueIdVerification)
err = initConfig.Validate()
if err != nil {
return err
Expand All @@ -77,8 +80,8 @@ func runInit(cmd *cobra.Command, args []string) error {
return err
}
if isRootExist {
spin.Stop()
shouldOverwrite, err := promptOverwriteConfig(initConfig.Home)
outputHandler.StopSpinner()
shouldOverwrite, err := outputHandler.PromptOverwriteConfig(initConfig.Home)
if err != nil {
return err
}
Expand All @@ -90,15 +93,13 @@ func runInit(cmd *cobra.Command, args []string) error {
} else {
os.Exit(0)
}
spin.Start()
}
err = os.MkdirAll(initConfig.Home, 0755)
if err != nil {
return err
}
//TODO: create all dirs here
spin.Suffix = " Initializing RollApp configuration files..."
spin.Restart()
outputHandler.StartSpinner(" Initializing RollApp configuration files...")
/* ---------------------------- Initialize relayer --------------------------- */
rollappPrefix, err := utils.GetAddressPrefix(initConfig.RollappBinary)
utils.PrettifyErrorIfExists(err)
Expand Down Expand Up @@ -167,8 +168,8 @@ func runInit(cmd *cobra.Command, args []string) error {
}

/* ------------------------------ Print output ------------------------------ */
spin.Stop()
printInitOutput(initConfig, addresses, initConfig.RollappID)
outputHandler.StopSpinner()
outputHandler.printInitOutput(initConfig, addresses, initConfig.RollappID)

return nil
}
62 changes: 27 additions & 35 deletions cmd/config/init/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,54 +2,46 @@ package initconfig

import (
"fmt"
"strings"

"github.com/dymensionxyz/roller/cmd/consts"
"github.com/dymensionxyz/roller/cmd/utils"
"github.com/dymensionxyz/roller/config"
datalayer "github.com/dymensionxyz/roller/data_layer"
"github.com/manifoldco/promptui"
)

func printInitOutput(rollappConfig config.RollappConfig, addresses []utils.AddressData, rollappId string) {
type OutputHandler struct {
*utils.OutputHandler
}

func NewOutputHandler(noOutput bool) *OutputHandler {
return &OutputHandler{
OutputHandler: utils.NewOutputHandler(noOutput),
}
}

func (o *OutputHandler) printInitOutput(rollappConfig config.RollappConfig, addresses []utils.AddressData, rollappId string) {
if o.NoOutput {
return
}
fmt.Printf("💈 RollApp '%s' configuration files have been successfully generated on your local machine. Congratulations!\n\n", rollappId)
fmt.Println(FormatTokenSupplyLine(rollappConfig))
fmt.Println()
utils.PrintAddresses(formatAddresses(rollappConfig, addresses))
fmt.Printf("\n🔔 Please fund these addresses to register and run the rollapp.\n")
}

func formatAddresses(rollappConfig config.RollappConfig, addresses []utils.AddressData) []utils.AddressData {
damanager := datalayer.NewDAManager(rollappConfig.DA, rollappConfig.Home)
requireFundingKeys := map[string]string{
consts.KeysIds.HubSequencer: fmt.Sprintf("Sequencer, %s Hub", rollappConfig.HubData.ID),
consts.KeysIds.HubRelayer: fmt.Sprintf("Relayer, %s Hub", rollappConfig.HubData.ID),
damanager.GetKeyName(): fmt.Sprintf("DA, %s Network", damanager.GetNetworkName()),
func (o *OutputHandler) PromptOverwriteConfig(home string) (bool, error) {
if o.NoOutput {
return true, nil
}
filteredAddresses := make([]utils.AddressData, 0)
for _, address := range addresses {
if newName, ok := requireFundingKeys[address.Name]; ok {
address.Name = newName
filteredAddresses = append(filteredAddresses, address)
}
prompt := promptui.Prompt{
Label: fmt.Sprintf("Directory %s is not empty. Do you want to overwrite", home),
IsConfirm: true,
}
return filteredAddresses
}

func FormatTokenSupplyLine(rollappConfig config.RollappConfig) string {
displayDenom := strings.ToUpper(rollappConfig.Denom[1:])
return fmt.Sprintf("💰 Total Token Supply: %s %s. Note that 1 %s == 1 * 10^%d %s (like 1 ETH == 1 * 10^18 wei).",
addCommasToNum(rollappConfig.TokenSupply), displayDenom, displayDenom, rollappConfig.Decimals, "u"+displayDenom)
}

func addCommasToNum(number string) string {
var result strings.Builder
n := len(number)

for i := 0; i < n; i++ {
if i > 0 && (n-i)%3 == 0 {
result.WriteString(",")
_, err := prompt.Run()
if err != nil {
if err == promptui.ErrAbort {
return false, nil
}
result.WriteByte(number[i])
return false, err
}
return result.String()
return true, nil
}
39 changes: 0 additions & 39 deletions cmd/config/init/prompt_existing_root.go

This file was deleted.

45 changes: 23 additions & 22 deletions cmd/register/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,13 @@ import (
// TODO: Test registration on 35-C and update the price
var registerUdymPrice = big.NewInt(1)

const (
flagForceSeqRegistration = "force"
)
var flagNames = struct {
NoOutput string
forceSeqRegistration string
}{
NoOutput: "no-output",
forceSeqRegistration: "force",
}

func Cmd() *cobra.Command {
registerCmd := &cobra.Command{
Expand All @@ -32,16 +36,20 @@ func Cmd() *cobra.Command {
},
}

registerCmd.Flags().BoolP(flagForceSeqRegistration, "f", false, "force sequencer registration even if the rollapp is already registered")
registerCmd.Flags().BoolP(flagNames.forceSeqRegistration, "f", false, "force sequencer registration even if the rollapp is already registered")
registerCmd.Flags().BoolP(flagNames.NoOutput, "", false, "Register the rollapp without output.")
return registerCmd
}

func register(cmd *cobra.Command, args []string) error {
spin := utils.GetLoadingSpinner()
spin.Suffix = consts.SpinnerMsgs.BalancesVerification
spin.Start()
defer spin.Stop()
utils.RunOnInterrupt(spin.Stop)
noOutput, err := cmd.Flags().GetBool(flagNames.NoOutput)
outputHandler := utils.NewOutputHandler(noOutput)
if err != nil {
return err
}
defer outputHandler.StopSpinner()
utils.RunOnInterrupt(outputHandler.StopSpinner)
outputHandler.StartSpinner(consts.SpinnerMsgs.BalancesVerification)
home := cmd.Flag(utils.FlagNames.Home).Value.String()
rollappConfig, err := config.LoadConfigFromTOML(home)
if err != nil {
Expand All @@ -52,15 +60,13 @@ func register(cmd *cobra.Command, args []string) error {
return err
}
if len(notFundedAddrs) > 0 {
spin.Stop()
outputHandler.StopSpinner()
utils.PrintInsufficientBalancesIfAny(notFundedAddrs, rollappConfig)
}

spin.Suffix = " Registering RollApp to hub...\n"
spin.Restart()
outputHandler.StartSpinner(" Registering RollApp to hub...\n")
registerRollappCmd := getRegisterRollappCmd(rollappConfig)
if err := runcCommandWithErrorChecking(registerRollappCmd); err != nil {
if cmd.Flag(flagForceSeqRegistration).Changed {
if cmd.Flag(flagNames.forceSeqRegistration).Changed {
fmt.Println("RollApp is already registered. Attempting to register sequencer anyway...")
} else {
return err
Expand All @@ -70,14 +76,13 @@ func register(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
spin.Suffix = " Registering RollApp sequencer...\n"
spin.Restart()
outputHandler.StartSpinner(" Registering RollApp sequencer...\n")
err = runcCommandWithErrorChecking(registerSequencerCmd)
if err != nil {
return err
}
spin.Stop()
printRegisterOutput(rollappConfig)
outputHandler.StopSpinner()
outputHandler.DisplayMessage(fmt.Sprintf("💈 Rollapp '%s' has been successfully registered on the hub.", rollappConfig.RollappID))
return nil
}

Expand Down Expand Up @@ -118,7 +123,3 @@ func handleStdOut(stdout bytes.Buffer) error {

return nil
}

func printRegisterOutput(rollappConfig config.RollappConfig) {
fmt.Printf("💈 Rollapp '%s' has been successfully registered on the hub.\n", rollappConfig.RollappID)
}
Loading

0 comments on commit 7624ca9

Please sign in to comment.