Skip to content

Commit

Permalink
fix: todos (#5)
Browse files Browse the repository at this point in the history
- DRY
- Configurable tx and block timeouts
  • Loading branch information
fmorency authored Mar 18, 2024
1 parent 8ddc81e commit a2b4a1d
Show file tree
Hide file tree
Showing 9 changed files with 135 additions and 118 deletions.
14 changes: 7 additions & 7 deletions cmd/claim.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,27 +28,27 @@ Trying to claim a work item that is already failed should return an error, unles
}

func ClaimCmdRunE(cmd *cobra.Command, args []string) error {
config := LoadConfigFromCLI("claim-uuid")
slog.Debug("args", "config", config)
if err := config.Validate(); err != nil {
c := LoadConfigFromCLI("claim-uuid")
slog.Debug("args", "c", c)
if err := c.Validate(); err != nil {
return err
}

claimConfig := LoadClaimConfigFromCLI()
slog.Debug("args", "claim-config", claimConfig)
slog.Debug("args", "claim-c", claimConfig)

authConfig := LoadAuthConfigFromCLI()
slog.Debug("args", "auth-config", authConfig)
slog.Debug("args", "auth-c", authConfig)
if err := authConfig.Validate(); err != nil {
return err
}

r := CreateRestClient(cmd.Context(), config.Url, config.Neighborhood)
r := CreateRestClient(cmd.Context(), c.Url, c.Neighborhood)
if err := AuthenticateRestClient(r, authConfig.Username, authConfig.Password); err != nil {
return err
}

item, err := claimWorkItem(r, config.UUID, claimConfig.Force)
item, err := claimWorkItem(r, c.UUID, claimConfig.Force)
if err != nil {
return err
}
Expand Down
47 changes: 47 additions & 0 deletions cmd/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import (

"github.com/go-resty/resty/v2"
"github.com/pkg/errors"
"github.com/spf13/viper"

"github.com/liftedinit/mfx-migrator/internal/config"
"github.com/liftedinit/mfx-migrator/internal/utils"

"github.com/liftedinit/mfx-migrator/internal/store"
)
Expand Down Expand Up @@ -70,3 +74,46 @@ func AuthenticateRestClient(r *resty.Client, username, password string) error {

return nil
}

// LoadConfigFromCLI loads the Config from the CLI flags
//
// `uuidKey` is the name of the viper key that holds the UUID
// This is necessary because the UUID is used in multiple commands
func LoadConfigFromCLI(uuidKey string) config.Config {
return config.Config{
UUID: viper.GetString(uuidKey),
Url: viper.GetString("url"),
Neighborhood: viper.GetUint64("neighborhood"),
}
}

func LoadAuthConfigFromCLI() config.AuthConfig {
return config.AuthConfig{
Username: viper.GetString("username"),
Password: viper.GetString("password"),
}
}

func LoadClaimConfigFromCLI() config.ClaimConfig {
return config.ClaimConfig{
Force: viper.GetBool("force"),
}
}

func LoadMigrationConfigFromCLI() config.MigrateConfig {
var tokenMap map[string]utils.TokenInfo
if err := viper.UnmarshalKey("token-map", &tokenMap); err != nil {
panic(err)
}
return config.MigrateConfig{
ChainID: viper.GetString("chain-id"),
AddressPrefix: viper.GetString("address-prefix"),
NodeAddress: viper.GetString("node-address"),
KeyringBackend: viper.GetString("keyring-backend"),
BankAddress: viper.GetString("bank-address"),
ChainHome: viper.GetString("chain-home"),
TokenMap: tokenMap,
WaitTxTimeout: viper.GetUint("wait-for-tx-timeout"),
WaitBlockTimeout: viper.GetUint("wait-for-block-timeout"),
}
}
61 changes: 40 additions & 21 deletions cmd/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/liftedinit/mfx-migrator/internal/config"

"github.com/liftedinit/mfx-migrator/internal/many"
"github.com/liftedinit/mfx-migrator/internal/utils"

Expand All @@ -27,26 +29,26 @@ var migrateCmd = &cobra.Command{
}

func MigrateCmdRunE(cmd *cobra.Command, args []string) error {
config := LoadConfigFromCLI("migrate-uuid")
slog.Debug("args", "config", config)
if err := config.Validate(); err != nil {
c := LoadConfigFromCLI("migrate-uuid")
slog.Debug("args", "c", c)
if err := c.Validate(); err != nil {
return err
}

migrateConfig := LoadMigrationConfigFromCLI()
slog.Debug("args", "migrate-config", migrateConfig)
slog.Debug("args", "migrate-c", migrateConfig)
if err := migrateConfig.Validate(); err != nil {
return err
}

authConfig := LoadAuthConfigFromCLI()
slog.Debug("args", "auth-config", authConfig)
slog.Debug("args", "auth-c", authConfig)
if err := authConfig.Validate(); err != nil {
return err
}

slog.Info("Loading state...", "uuid", config.UUID)
item, err := store.LoadState(config.UUID)
slog.Info("Loading state...", "uuid", c.UUID)
item, err := store.LoadState(c.UUID)
if err != nil {
return errors.WithMessage(err, "unable to load state")
}
Expand All @@ -55,7 +57,7 @@ func MigrateCmdRunE(cmd *cobra.Command, args []string) error {
return err
}

r := CreateRestClient(cmd.Context(), config.Url, config.Neighborhood)
r := CreateRestClient(cmd.Context(), c.Url, c.Neighborhood)
if err := AuthenticateRestClient(r, authConfig.Username, authConfig.Password); err != nil {
return err
}
Expand Down Expand Up @@ -95,7 +97,7 @@ func compareItems(item *store.WorkItem, remoteItem *store.WorkItem) error {
return nil
}

func SetupMigrateCmdFlags(command *cobra.Command) {
func setupStringCmdFlags(command *cobra.Command) {
args := []struct {
name string
key string
Expand Down Expand Up @@ -125,6 +127,31 @@ func SetupMigrateCmdFlags(command *cobra.Command) {
}
}

func setupUIntCmdFlags(command *cobra.Command) {
args := []struct {
name string
key string
value uint
usage string
}{
{"wait-for-tx-timeout", "wait-for-tx-timeout", 15, "Number of seconds spent waiting for the transaction to be included in a block"},
{"wait-for-block-timeout", "wait-for-block-timeout", 30, "Number of seconds spent waiting for the block to be committed"},
}

for _, arg := range args {
command.Flags().Uint(arg.name, arg.value, arg.usage)
if err := viper.BindPFlag(arg.key, command.Flags().Lookup(arg.name)); err != nil {
slog.Error(ErrorBindingFlag, "error", err)
}
}

}

func SetupMigrateCmdFlags(command *cobra.Command) {
setupStringCmdFlags(command)
setupUIntCmdFlags(command)
}

func mapToken(symbol string, tokenMap map[string]utils.TokenInfo) (*utils.TokenInfo, error) {
if _, ok := tokenMap[symbol]; !ok {
return nil, fmt.Errorf("token %s not found in token map", symbol)
Expand All @@ -134,7 +161,7 @@ func mapToken(symbol string, tokenMap map[string]utils.TokenInfo) (*utils.TokenI
}

// migrate migrates a work item to the Manifest Ledger.
func migrate(r *resty.Client, item *store.WorkItem, config MigrateConfig) error {
func migrate(r *resty.Client, item *store.WorkItem, config config.MigrateConfig) error {
slog.Info("Migrating work item...", "uuid", item.UUID)

remoteItem, err := store.GetWorkItem(r, item.UUID)
Expand Down Expand Up @@ -171,7 +198,7 @@ func migrate(r *resty.Client, item *store.WorkItem, config MigrateConfig) error
slog.Debug("Amount before conversion", "amount", txInfo.Arguments.Amount)

// Convert the amount to the destination chain precision
// TODO: currentPrecision is hardcoded to 9 for now as all tokens on the MANY network have 9 digits places
// NOTE: currentPrecision is hardcoded to 9 for now as all tokens on the MANY network have 9 digits places
amount, err := utils.ConvertPrecision(txInfo.Arguments.Amount, 9, tokenInfo.Precision)
if err != nil {
return errors.WithMessage(err, "error converting token to destination precision")
Expand Down Expand Up @@ -247,16 +274,8 @@ func setAsFailed(r *resty.Client, newItem store.WorkItem, errStr *string) error
}

// sendTokens sends the tokens from the bank account to the user account.
func sendTokens(item *store.WorkItem, config MigrateConfig, denom string, amount *big.Int) (*string, *time.Time, error) {
txResponse, blockTime, err := manifest.Migrate(item, manifest.MigrationConfig{
ChainID: config.ChainID,
NodeAddress: config.NodeAddress,
KeyringBackend: config.KeyringBackend,
ChainHome: config.ChainHome,
AddressPrefix: config.AddressPrefix,
BankAddress: config.BankAddress,
TokenMap: config.TokenMap,
}, denom, amount)
func sendTokens(item *store.WorkItem, config config.MigrateConfig, denom string, amount *big.Int) (*string, *time.Time, error) {
txResponse, blockTime, err := manifest.Migrate(item, config, denom, amount)
if err != nil {
return nil, nil, errors.WithMessage(err, "error during migration, operator intervention required")
}
Expand Down
14 changes: 7 additions & 7 deletions cmd/verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ var verifyCmd = &cobra.Command{
Use: "verify",
Short: "Verify the status of a migration of MFX tokens to the Manifest Ledger",
RunE: func(cmd *cobra.Command, args []string) error {
config := LoadConfigFromCLI("verify-uuid")
slog.Debug("args", "config", config)
if err := config.Validate(); err != nil {
c := LoadConfigFromCLI("verify-uuid")
slog.Debug("args", "c", c)
if err := c.Validate(); err != nil {
return err
}

s, err := store.LoadState(config.UUID)
s, err := store.LoadState(c.UUID)
if err != nil {
slog.Warn("unable to load local state, continuing", "warning", err)
}
Expand All @@ -32,11 +32,11 @@ var verifyCmd = &cobra.Command{
}

// Verify the work item on the remote database
slog.Debug("verifying remote state", "url", config.Url, "uuid", config.UUID)
slog.Debug("verifying remote state", "url", c.Url, "uuid", c.UUID)

r := CreateRestClient(cmd.Context(), config.Url, config.Neighborhood)
r := CreateRestClient(cmd.Context(), c.Url, c.Neighborhood)

item, err := store.GetWorkItem(r, uuid.MustParse(config.UUID))
item, err := store.GetWorkItem(r, uuid.MustParse(c.UUID))
if err != nil {
return errors.WithMessage(err, "unable to get work item")
}
Expand Down
1 change: 0 additions & 1 deletion interchaintest/migrate_on_chain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ func TestMigrateOnChain(t *testing.T) {
Bank: Amounts{Old: defaultGenesisAmtMinOne, New: math.ZeroInt()},
User: Amounts{Old: math.OneInt(), New: DefaultGenesisAmt},
}},
// TODO: Add more test cases
}

for _, tc := range tt {
Expand Down
68 changes: 18 additions & 50 deletions cmd/config.go → internal/config/config.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package cmd
package config

import (
"fmt"
"net/url"

"github.com/google/uuid"
"github.com/spf13/viper"

"github.com/liftedinit/mfx-migrator/internal/utils"
)
Expand Down Expand Up @@ -45,18 +44,6 @@ func (c Config) Validate() error {
return nil
}

// LoadConfigFromCLI loads the Config from the CLI flags
//
// `uuidKey` is the name of the viper key that holds the UUID
// This is necessary because the UUID is used in multiple commands
func LoadConfigFromCLI(uuidKey string) Config {
return Config{
UUID: viper.GetString(uuidKey),
Url: viper.GetString("url"),
Neighborhood: viper.GetUint64("neighborhood"),
}
}

type AuthConfig struct {
Username string // The username to authenticate with
Password string // The password to authenticate with
Expand All @@ -78,47 +65,20 @@ func (c AuthConfig) Validate() error {
return nil
}

func LoadAuthConfigFromCLI() AuthConfig {
return AuthConfig{
Username: viper.GetString("username"),
Password: viper.GetString("password"),
}
}

type ClaimConfig struct {
Force bool // Force re-claiming of a failed work item
}

func LoadClaimConfigFromCLI() ClaimConfig {
return ClaimConfig{
Force: viper.GetBool("force"),
}
}

type MigrateConfig struct {
ChainID string // The destination chain ID
AddressPrefix string // The destination address prefix
NodeAddress string // The destination RPC node address
KeyringBackend string // The destination chain keyring backend to use
BankAddress string // The destination chain address of the bank account to send tokens from
ChainHome string // The root directory of the destination chain configuration
TokenMap map[string]utils.TokenInfo // Map of source token address to destination token info
}

func LoadMigrationConfigFromCLI() MigrateConfig {
var tokenMap map[string]utils.TokenInfo
if err := viper.UnmarshalKey("token-map", &tokenMap); err != nil {
panic(err)
}
return MigrateConfig{
ChainID: viper.GetString("chain-id"),
AddressPrefix: viper.GetString("address-prefix"),
NodeAddress: viper.GetString("node-address"),
KeyringBackend: viper.GetString("keyring-backend"),
BankAddress: viper.GetString("bank-address"),
ChainHome: viper.GetString("chain-home"),
TokenMap: tokenMap,
}
ChainID string // The destination chain ID
AddressPrefix string // The destination address prefix
NodeAddress string // The destination RPC node address
KeyringBackend string // The destination chain keyring backend to use
BankAddress string // The destination chain address of the bank account to send tokens from
ChainHome string // The root directory of the destination chain configuration
TokenMap map[string]utils.TokenInfo // Map of source token address to destination token info
WaitTxTimeout uint // Number of seconds spent waiting for the transaction to be included in a block
WaitBlockTimeout uint // Number of seconds spent waiting for the block to be committed
}

func (c MigrateConfig) Validate() error {
Expand Down Expand Up @@ -146,5 +106,13 @@ func (c MigrateConfig) Validate() error {
return fmt.Errorf("chain home is required")
}

if c.WaitTxTimeout == 0 {
return fmt.Errorf("wait for tx timeout > 0 is required")
}

if c.WaitBlockTimeout == 0 {
return fmt.Errorf("wait for block timeout > 0 is required")
}

return nil
}
Loading

0 comments on commit a2b4a1d

Please sign in to comment.