Skip to content

Commit

Permalink
refactor: remove RegisterAllCommands
Browse files Browse the repository at this point in the history
  • Loading branch information
b00f committed Jan 2, 2025
1 parent e6b52b3 commit e6208f4
Show file tree
Hide file tree
Showing 31 changed files with 106 additions and 126 deletions.
1 change: 0 additions & 1 deletion cmd/cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ func run(cmd *cobra.Command, _ []string) {
botEngine, err := engine.NewBotEngine(configs)
pagucmd.ExitOnError(cmd, err)

botEngine.RegisterAllCommands()
botEngine.Start()

reader := bufio.NewReader(os.Stdin)
Expand Down
1 change: 0 additions & 1 deletion cmd/discord/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ func runCommand(parentCmd *cobra.Command) {
botEngine, err := engine.NewBotEngine(configs)
pagucmd.ExitOnError(cmd, err)

botEngine.RegisterAllCommands()
botEngine.Start()

discordBot, err := discord.NewDiscordBot(botEngine, configs.DiscordBot, configs.BotName)
Expand Down
1 change: 0 additions & 1 deletion cmd/grpc/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ func runCommand(parentCmd *cobra.Command) {
botEngine, err := engine.NewBotEngine(config)
pagucmd.ExitOnError(cmd, err)

botEngine.RegisterAllCommands()
botEngine.Start()

grpcServer := grpc.NewServer(botEngine, config.GRPC)
Expand Down
1 change: 0 additions & 1 deletion cmd/http/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ func runCommand(parentCmd *cobra.Command) {
botEngine, err := engine.NewBotEngine(configs)
pagucmd.ExitOnError(cmd, err)

botEngine.RegisterAllCommands()
botEngine.Start()

httpServer := http.NewHTTPServer(botEngine, configs.HTTP)
Expand Down
1 change: 0 additions & 1 deletion cmd/telegram/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ func runCommand(parentCmd *cobra.Command) {

log.InitGlobalLogger(configs.Logger)

botEngine.RegisterAllCommands()
botEngine.Start()

telegramBot, err := telegram.NewTelegramBot(botEngine, configs.Telegram.BotToken, configs)
Expand Down
8 changes: 4 additions & 4 deletions internal/engine/command/calculator/calculator.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@ const (
HelpCommandName = "help"
)

type Calculator struct {
type CalculatorCmd struct {
clientMgr client.IManager
}

func NewCalculator(clientMgr client.IManager) *Calculator {
return &Calculator{
func NewCalculatorCmd(clientMgr client.IManager) *CalculatorCmd {
return &CalculatorCmd{
clientMgr: clientMgr,
}
}

func (bc *Calculator) GetCommand() *command.Command {
func (bc *CalculatorCmd) GetCommand() *command.Command {
subCmdCalcReward := &command.Command{
Name: CalcRewardCommandName,
Help: "Calculate how many PAC coins you will earn with your validator stake",
Expand Down
2 changes: 1 addition & 1 deletion internal/engine/command/calculator/fee.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/pagu-project/pagu/pkg/amount"
)

func (bc *Calculator) calcFeeHandler(
func (bc *CalculatorCmd) calcFeeHandler(
_ *entity.User,
cmd *command.Command,
args map[string]string,
Expand Down
2 changes: 1 addition & 1 deletion internal/engine/command/calculator/reward.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/pagu-project/pagu/pkg/utils"
)

func (bc *Calculator) calcRewardHandler(
func (bc *CalculatorCmd) calcRewardHandler(
_ *entity.User,
cmd *command.Command,
args map[string]string,
Expand Down
2 changes: 1 addition & 1 deletion internal/engine/command/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ type Command struct {
Color color.ColorCode
Name string
Help string
Args []Args // should be nil for commands.
Args []Args
AppIDs []entity.PlatformID
SubCommands []*Command
Middlewares []MiddlewareFunc
Expand Down
2 changes: 1 addition & 1 deletion internal/engine/command/crowdfund/crowdfund.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type Crowdfund struct {
nowPayments nowpayments.INowpayments
}

func NewCrowdfundCommand(ctx context.Context, nowPayments nowpayments.INowpayments) *Crowdfund {
func NewCrowdfundCmd(ctx context.Context, nowPayments nowpayments.INowpayments) *Crowdfund {
return &Crowdfund{
ctx: ctx,
nowPayments: nowPayments,
Expand Down
10 changes: 5 additions & 5 deletions internal/engine/command/market/market.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,26 @@ const (
HelpCommandName = "help"
)

type Market struct {
type MarketCmd struct {
clientMgr client.IManager
priceCache cache.Cache[string, entity.Price]
}

func NewMarket(clientMgr client.IManager, priceCache cache.Cache[string, entity.Price]) *Market {
return &Market{
func NewMarketCmd(clientMgr client.IManager, priceCache cache.Cache[string, entity.Price]) *MarketCmd {
return &MarketCmd{
clientMgr: clientMgr,
priceCache: priceCache,
}
}

func (m *Market) GetCommand() *command.Command {
func (m *MarketCmd) GetCommand() *command.Command {
subCmdPrice := &command.Command{
Name: PriceCommandName,
Help: "Shows the last price of PAC coin on the markets",
Args: []command.Args{},
SubCommands: nil,
AppIDs: entity.AllAppIDs(),
Handler: m.getPrice,
Handler: m.handlerPrice,
TargetFlag: command.TargetMaskMainnet,
}

Expand Down
2 changes: 1 addition & 1 deletion internal/engine/command/market/price.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/pagu-project/pagu/internal/entity"
)

func (m *Market) getPrice(_ *entity.User, cmd *command.Command, _ map[string]string) command.CommandResult {
func (m *MarketCmd) handlerPrice(_ *entity.User, cmd *command.Command, _ map[string]string) command.CommandResult {
priceData, ok := m.priceCache.Get(config.PriceCacheKey)
if !ok {
return cmd.ErrorResult(fmt.Errorf("failed to get price from markets. please try again later"))
Expand Down
24 changes: 10 additions & 14 deletions internal/engine/command/market/price_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,22 @@ import (
"github.com/stretchr/testify/assert"
)

func setup() (*Market, *command.Command) {
func setup() *MarketCmd {
priceCache := cache.NewBasic[string, entity.Price](1 * time.Second)
priceJob := job.NewPrice(priceCache)
priceJobSched := job.NewScheduler()
priceJobSched.Submit(priceJob)
go priceJobSched.Run()
m := NewMarket(nil, priceCache)
priceJobScheduler := job.NewScheduler()
priceJobScheduler.Submit(priceJob)
go priceJobScheduler.Run()
m := NewMarketCmd(nil, priceCache)

return m, &command.Command{
Name: PriceCommandName,
Help: "Shows the last price of PAC coin on the markets",
Args: []command.Args{},
SubCommands: nil,
AppIDs: entity.AllAppIDs(),
}
return m
}

func TestGetPrice(t *testing.T) {
market, cmd := setup()
market := setup()
time.Sleep(10 * time.Second)
result := market.getPrice(nil, cmd, nil)

cmd := &command.Command{}
result := market.handlerPrice(nil, cmd, nil)
assert.Equal(t, result.Successful, true)
}
2 changes: 1 addition & 1 deletion internal/engine/command/network/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
utils2 "github.com/pagu-project/pagu/pkg/utils"
)

func (n *Network) networkHealthHandler(
func (n *NetworkCmd) networkHealthHandler(
_ *entity.User,
cmd *command.Command,
_ map[string]string,
Expand Down
8 changes: 4 additions & 4 deletions internal/engine/command/network/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ const (
HelpCommandName = "help"
)

type Network struct {
type NetworkCmd struct {
ctx context.Context
clientMgr client.IManager
}

func NewNetwork(ctx context.Context, clientMgr client.IManager) *Network {
return &Network{
func NewNetworkCmd(ctx context.Context, clientMgr client.IManager) *NetworkCmd {
return &NetworkCmd{
ctx: ctx,
clientMgr: clientMgr,
}
Expand Down Expand Up @@ -58,7 +58,7 @@ type NetStatus struct {
CirculatingSupply int64
}

func (n *Network) GetCommand() *command.Command {
func (n *NetworkCmd) GetCommand() *command.Command {
subCmdNodeInfo := &command.Command{
Name: NodeInfoCommandName,
Help: "View the information of a node",
Expand Down
4 changes: 3 additions & 1 deletion internal/engine/command/network/node_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import (
utils2 "github.com/pagu-project/pagu/pkg/utils"
)

func (n *Network) nodeInfoHandler(_ *entity.User, cmd *command.Command, args map[string]string) command.CommandResult {
func (n *NetworkCmd) nodeInfoHandler(_ *entity.User,
cmd *command.Command, args map[string]string,
) command.CommandResult {
valAddress := args["validator_address"]

peerInfo, err := n.clientMgr.GetPeerInfo(valAddress)
Expand Down
2 changes: 1 addition & 1 deletion internal/engine/command/network/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
utils2 "github.com/pagu-project/pagu/pkg/utils"
)

func (n *Network) networkStatusHandler(
func (n *NetworkCmd) networkStatusHandler(
_ *entity.User,
cmd *command.Command,
_ map[string]string,
Expand Down
2 changes: 1 addition & 1 deletion internal/engine/command/phoenix/faucet.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/pagu-project/pagu/internal/entity"
)

func (pt *Phoenix) faucetHandler(
func (pt *PhoenixCmd) faucetHandler(
caller *entity.User,
cmd *command.Command,
args map[string]string,
Expand Down
2 changes: 1 addition & 1 deletion internal/engine/command/phoenix/network_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
utils2 "github.com/pagu-project/pagu/pkg/utils"
)

func (pt *Phoenix) networkStatusHandler(
func (pt *PhoenixCmd) networkStatusHandler(
_ *entity.User,
cmd *command.Command,
_ map[string]string,
Expand Down
10 changes: 5 additions & 5 deletions internal/engine/command/phoenix/phoenix.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,18 @@ const (
HelpCommandName = "help"
)

type Phoenix struct {
type PhoenixCmd struct {
ctx context.Context
wallet wallet.IWallet
db *repository.Database
clientMgr client.IManager
faucetAmount amount.Amount
}

func NewPhoenix(ctx context.Context, wlt wallet.IWallet, faucetAmount amount.Amount,
func NewPhoenixCmd(ctx context.Context, wlt wallet.IWallet, faucetAmount amount.Amount,
clientMgr client.IManager, db *repository.Database,
) *Phoenix {
return &Phoenix{
) *PhoenixCmd {
return &PhoenixCmd{
ctx: ctx,
wallet: wlt,
clientMgr: clientMgr,
Expand All @@ -42,7 +42,7 @@ func NewPhoenix(ctx context.Context, wlt wallet.IWallet, faucetAmount amount.Amo
}
}

func (pt *Phoenix) GetCommand() *command.Command {
func (pt *PhoenixCmd) GetCommand() *command.Command {
middlewareHandler := command.NewMiddlewareHandler(pt.db, pt.wallet)

subCmdStatus := &command.Command{
Expand Down
2 changes: 1 addition & 1 deletion internal/engine/command/phoenix/wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
)

//nolint:unused // remove me after I am used
func (pt *Phoenix) walletHandler(cmd *command.Command,
func (pt *PhoenixCmd) walletHandler(cmd *command.Command,
_ entity.PlatformID, _ string, _ ...string,
) command.CommandResult {
return cmd.SuccessfulResultF(
Expand Down
2 changes: 1 addition & 1 deletion internal/engine/command/voucher/claim.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/pagu-project/pagu/pkg/log"
)

func (v *Voucher) claimHandler(
func (v *VoucherCmd) claimHandler(
caller *entity.User,
cmd *command.Command,
args map[string]string,
Expand Down
30 changes: 17 additions & 13 deletions internal/engine/command/voucher/claim_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,28 @@ func TestClaim(t *testing.T) {
cmd := &command.Command{}

t.Run("Invalid Voucher Code", func(t *testing.T) {
args := make(map[string]string)
args["code"] = "0"
args["address"] = "pc1z"
args := map[string]string{
"code": "0",
"address": "pc1p...",
}
result := td.voucherCmd.claimHandler(caller, cmd, args)
assert.False(t, result.Successful)
assert.Equal(t, result.Message, "An error occurred: voucher code is not valid, length must be 8")
})

t.Run("Voucher Code Not Issued Yet", func(t *testing.T) {
args := make(map[string]string)
args["code"] = voucherCode
args["address"] = "pc1z"
args := map[string]string{
"code": voucherCode,
"address": "pc1p...",
}
result := td.voucherCmd.claimHandler(caller, cmd, args)
assert.False(t, result.Successful)
assert.Equal(t, result.Message, "An error occurred: voucher code is not valid, no voucher found")
})

t.Run("Claim a Voucher", func(t *testing.T) {
testVoucher := td.createTestVoucher(t, WithCode(voucherCode))
validatorAddr := "pc1p123"
validatorAddr := "pc1p..."

td.clientManager.EXPECT().GetValidatorInfo(validatorAddr).Return(
nil, nil,
Expand All @@ -51,18 +53,20 @@ func TestClaim(t *testing.T) {
"0x1", nil,
).AnyTimes()

args := make(map[string]string)
args["code"] = testVoucher.Code
args["address"] = validatorAddr
args := map[string]string{
"code": voucherCode,
"address": validatorAddr,
}
result := td.voucherCmd.claimHandler(caller, cmd, args)
assert.True(t, result.Successful)
assert.Equal(t, result.Message, "Voucher claimed successfully!\n\n https://pacviewer.com/transaction/0x1")
})

t.Run("Claim again", func(t *testing.T) {
args := make(map[string]string)
args["code"] = voucherCode
args["address"] = "pc1z"
args := map[string]string{
"code": voucherCode,
"address": "pc1p...",
}
result := td.voucherCmd.claimHandler(caller, cmd, args)
assert.False(t, result.Successful)
assert.Equal(t, result.Message, "An error occurred: voucher code claimed before")
Expand Down
8 changes: 4 additions & 4 deletions internal/engine/command/voucher/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ type BulkRecorder struct {
Description string `csv:"Description"`
}

func (v *Voucher) createOneHandler(
func (v *VoucherCmd) createOneHandler(
caller *entity.User,
cmd *command.Command,
args map[string]string,
Expand Down Expand Up @@ -71,7 +71,7 @@ func (v *Voucher) createOneHandler(
return cmd.SuccessfulResultF("Voucher created successfully! \n Code: %s", vch.Code)
}

func (v *Voucher) createBulkHandler(
func (v *VoucherCmd) createBulkHandler(
caller *entity.User,
cmd *command.Command,
args map[string]string,
Expand Down Expand Up @@ -148,7 +148,7 @@ func (v *Voucher) createBulkHandler(
return cmd.SuccessfulResult("Vouchers created successfully!")
}

func (v *Voucher) createBulkVoucher(records []BulkRecorder, callerID uint) ([]*entity.Voucher, error) {
func (v *VoucherCmd) createBulkVoucher(records []BulkRecorder, callerID uint) ([]*entity.Voucher, error) {
vouchers := make([]*entity.Voucher, 0)
for index, record := range records {
code := utils.RandomString(8, utils.CapitalAlphanumerical)
Expand Down Expand Up @@ -189,7 +189,7 @@ func (v *Voucher) createBulkVoucher(records []BulkRecorder, callerID uint) ([]*e
return vouchers, nil
}

func (v *Voucher) createNotification(email, code, recipient string, amt float64) error {
func (v *VoucherCmd) createNotification(email, code, recipient string, amt float64) error {
notificationData := entity.VoucherNotificationData{
Code: code,
Recipient: recipient,
Expand Down
Loading

0 comments on commit e6208f4

Please sign in to comment.