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: adding claim command to bot #25

Merged
merged 5 commits into from
Jan 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
16 changes: 6 additions & 10 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import (
"errors"

"github.com/kehiy/RoboPac/log"
"github.com/pactus-project/pactus/crypto"
"github.com/pactus-project/pactus/crypto/bls"
pactus "github.com/pactus-project/pactus/www/grpc/gen/go"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
Expand Down Expand Up @@ -61,22 +59,20 @@ func (c *Client) GetNetworkInfo() (*pactus.GetNetworkInfoResponse, error) {
return networkInfo, nil
}

func (c *Client) GetPeerInfo(address string) (*pactus.PeerInfo, *bls.PublicKey, error) {
func (c *Client) GetPeerInfo(address string) (*pactus.PeerInfo, error) {
networkInfo, _ := c.GetNetworkInfo()
crypto.PublicKeyHRP = "tpublic"
if networkInfo != nil {
for _, p := range networkInfo.ConnectedPeers {
for _, key := range p.ConsensusKeys {
pub, _ := bls.PublicKeyFromString(key)
if pub != nil {
if pub.ValidatorAddress().String() == address {
return p, pub, nil
for _, addr := range p.ConsensusAddress {
if addr != "" {
if addr == address {
return p, nil
}
}
}
}
}
return nil, nil, errors.New("peer does not exist")
return nil, errors.New("peer does not exist")
}

func (c *Client) IsValidator(address string) (bool, error) {
Expand Down
2 changes: 1 addition & 1 deletion client/client_mgr.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ func (cm *Mgr) GetTransactionData(txID string) (*pactus.GetTransactionResponse,
return nil, errors.New("unable to get transaction data")
}

func (cm *Mgr) Close() {
func (cm *Mgr) Stop() {
for addr, c := range cm.clients {
if err := c.Close(); err != nil {
log.Error("could not close connection to RPC node", "err", err, "RPCAddr", addr)
Expand Down
15 changes: 12 additions & 3 deletions cmd/commands/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/kehiy/RoboPac/client"
"github.com/kehiy/RoboPac/config"
"github.com/kehiy/RoboPac/discord"
"github.com/kehiy/RoboPac/engine"
"github.com/kehiy/RoboPac/log"
"github.com/kehiy/RoboPac/store"
Expand All @@ -21,7 +22,7 @@ func RunCommand(parentCmd *cobra.Command) {
}
parentCmd.AddCommand(run)

run.Run = func(cmd *cobra.Command, args []string) {
run.Run = func(_ *cobra.Command, _ []string) {
// load configuration.
config, err := config.Load()
if err != nil {
Expand Down Expand Up @@ -72,16 +73,24 @@ func RunCommand(parentCmd *cobra.Command) {
// starting botEngine.
botEngine, err := engine.NewBotEngine(eSl, cm, wallet, store)
if err != nil {
log.Panic("could not start discord bot", "err", err)
log.Panic("could not start bot engine", "err", err)
}
botEngine.Start()

discordBot, err := discord.NewDiscordBot(botEngine, config.DiscordBotCfg.DiscordToken,
config.DiscordBotCfg.DiscordGuildID)
if err != nil {
log.Panic("could not start discord bot", "err", err)
}
discordBot.Start()

sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-sigChan

// gracefully shutdown the bot.
discordBot.Stop()
cm.Stop()
botEngine.Stop()
cm.Close()
}
}
14 changes: 14 additions & 0 deletions discord/commands.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package discord

import "github.com/bwmarrin/discordgo"

var commands = []*discordgo.ApplicationCommand{
{
Name: "help",
Description: "Help command for RoboPac",
},
}

var commandHandlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){
"help": helpCommandHandler,
}
55 changes: 54 additions & 1 deletion discord/discord.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,56 @@
package discord

// need implementation.
import (
"github.com/bwmarrin/discordgo"
"github.com/kehiy/RoboPac/engine"
"github.com/kehiy/RoboPac/log"
)

type DiscordBot struct {
Session *discordgo.Session
BotEngine engine.Engine
GuildID string
}

func NewDiscordBot(botEngine engine.Engine, token, guildID string) (*DiscordBot, error) {
s, err := discordgo.New("Bot " + token)
if err != nil {
return nil, err
}

return &DiscordBot{
Session: s,
BotEngine: botEngine,
GuildID: guildID,
}, nil
}

func (db *DiscordBot) Start() {
log.Info("starting Discord Bot...")

db.Session.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
if h, ok := commandHandlers[i.ApplicationCommandData().Name]; ok {
h(s, i)
}
})

err := db.Session.Open()
if err != nil {
log.Panic("can't open discord session", "err", err)
}

registeredCommands := make([]*discordgo.ApplicationCommand, len(commands))
for i, v := range commands {
cmd, err := db.Session.ApplicationCommandCreate(db.Session.State.User.ID, db.GuildID, v)
if err != nil {
log.Panic("can not register discord command", "name", v.Name, "err", err)
}
registeredCommands[i] = cmd
}
}

func (db *DiscordBot) Stop() {
log.Info("shutting down Discord Bot...")

_ = db.Session.Close()
}
16 changes: 16 additions & 0 deletions discord/embeds.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package discord

import "github.com/bwmarrin/discordgo"

func helpEmbed(s *discordgo.Session) *discordgo.MessageEmbed {
return &discordgo.MessageEmbed{
Title: "RoboPac Help",
URL: "https://pactus.org",
Author: &discordgo.MessageEmbedAuthor{
URL: "https://pactus.org",
IconURL: s.State.User.AvatarURL(""),
Name: s.State.User.Username,
},
Description: "RoboPac is a robot that provides support and information about the Pactus Blockchain.",
}
}
7 changes: 7 additions & 0 deletions discord/handlers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package discord

import "github.com/bwmarrin/discordgo"

func helpCommandHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
_, _ = s.ChannelMessageSendEmbedReply(i.ChannelID, helpEmbed(s), i.Message.Reference())
}
14 changes: 8 additions & 6 deletions engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,16 +140,17 @@ func (be *BotEngine) Claim(tokens []string) (*store.ClaimTransaction, error) {
be.Lock()
defer be.Unlock()

if len(tokens) != 2 {
if len(tokens) != 3 {
return nil, errors.New("missing argument: validator address")
}

valAddr := tokens[0]
discordID := tokens[1]
testNetValAddr := tokens[1]
discordID := tokens[2]

be.logger.Info("new claim request", "valAddr", valAddr, "discordID", discordID)
be.logger.Info("new claim request", "valAddr", valAddr, "testNetValAddr", testNetValAddr, "discordID", discordID)

claimer := be.Store.ClaimerInfo(discordID)
claimer := be.Store.ClaimerInfo(testNetValAddr)
if claimer == nil {
return nil, errors.New("claimer not found")
}
Expand Down Expand Up @@ -185,12 +186,13 @@ func (be *BotEngine) Claim(tokens []string) (*store.ClaimTransaction, error) {
return nil, err
}

err = be.Store.AddClaimTransaction(txID, util.ChangeToCoin(txData.Transaction.Value), int64(txData.BlockTime), discordID)
err = be.Store.AddClaimTransaction(util.ChangeToCoin(txData.Transaction.Value),
int64(txData.BlockTime), txID, discordID, testNetValAddr)
if err != nil {
return nil, err
}

claimer = be.Store.ClaimerInfo(discordID)
claimer = be.Store.ClaimerInfo(testNetValAddr)
if claimer == nil {
return nil, errors.New("can't save claim info")
}
Expand Down
28 changes: 16 additions & 12 deletions engine/engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,16 +156,17 @@ func TestClaim(t *testing.T) {

t.Run("everything normal and good", func(t *testing.T) {
valAddress := "pc1p74scge5dyzjktv9q70xtr0pjmyqcqk7nuh8nzp"
testNetValAddr := "tpc1pqn7uaeduklpg00rqt6uq0m9wy5txnyt0kmxmgf"
discordID := "123456789"
txID := "0x123456789"
amount := 74.68
amount := float64(74)
time := time.Now().Unix()

client.EXPECT().IsValidator(valAddress).Return(
true, nil,
)

store.EXPECT().ClaimerInfo(discordID).Return(
store.EXPECT().ClaimerInfo(testNetValAddr).Return(
&rpstore.Claimer{
DiscordID: discordID,
TotalReward: amount,
Expand All @@ -189,11 +190,11 @@ func TestClaim(t *testing.T) {
}, nil,
)

store.EXPECT().AddClaimTransaction(txID, amount, time, discordID).Return(
store.EXPECT().AddClaimTransaction(amount, time, txID, discordID, testNetValAddr).Return(
nil,
)

store.EXPECT().ClaimerInfo(discordID).Return(
store.EXPECT().ClaimerInfo(testNetValAddr).Return(
&rpstore.Claimer{
DiscordID: discordID,
TotalReward: amount,
Expand All @@ -205,7 +206,7 @@ func TestClaim(t *testing.T) {
},
).AnyTimes()

claimTx, err := eng.Claim([]string{valAddress, discordID})
claimTx, err := eng.Claim([]string{valAddress, testNetValAddr, discordID})
assert.NoError(t, err)
assert.NotNil(t, claimTx)

Expand All @@ -214,7 +215,7 @@ func TestClaim(t *testing.T) {
assert.Equal(t, time, claimTx.Time)

//! can't claim twice.
claimTx, err = eng.Claim([]string{valAddress, discordID})
claimTx, err = eng.Claim([]string{valAddress, testNetValAddr, discordID})
assert.EqualError(t, err, "this claimer have already claimed rewards")
assert.Nil(t, claimTx)
})
Expand All @@ -227,23 +228,25 @@ func TestClaim(t *testing.T) {

t.Run("claimer not found", func(t *testing.T) {
valAddress := "pc1p74scge5dyzjktv9q70xtr0pjmyqcqk7nuh8nzp"
testNetValAddr := "tpc1peaeyzmwjqu6nz93c27hr8ad2l265tx4s9v6zhw"
discordID := "987654321"

store.EXPECT().ClaimerInfo(discordID).Return(
store.EXPECT().ClaimerInfo(testNetValAddr).Return(
nil,
)

claimTx, err := eng.Claim([]string{valAddress, discordID})
claimTx, err := eng.Claim([]string{valAddress, testNetValAddr, discordID})
assert.EqualError(t, err, "claimer not found")
assert.Nil(t, claimTx)
})

t.Run("not validator address", func(t *testing.T) {
valAddress := "pc1p74scge5dyzjktv9q70xtr0pjmyqcqk7nuh8nzp"
testNetValAddr := "tpc1p2vx5t8sglhvncmp3en0qhgtxyc59w0gfgnaqe7"
discordID := "1234567890"
amount := 74.68

store.EXPECT().ClaimerInfo(discordID).Return(
store.EXPECT().ClaimerInfo(testNetValAddr).Return(
&rpstore.Claimer{
DiscordID: discordID,
TotalReward: amount,
Expand All @@ -254,21 +257,22 @@ func TestClaim(t *testing.T) {
false, nil,
)

claimTx, err := eng.Claim([]string{valAddress, discordID})
claimTx, err := eng.Claim([]string{valAddress, testNetValAddr, discordID})
assert.EqualError(t, err, "invalid argument: validator address")
assert.Nil(t, claimTx)
})

t.Run("empty transaction ID", func(t *testing.T) {
valAddress := "pc1p74scge5dyzjktv9q70xtr0pjmyqcqk7nuh8nzp"
testNetValAddr := "tpc1pvmundkkp83u5cfz04sem5r7688dc0lef5u0mmv"
discordID := "1234567890"
amount := 74.68

client.EXPECT().IsValidator(valAddress).Return(
true, nil,
)

store.EXPECT().ClaimerInfo(discordID).Return(
store.EXPECT().ClaimerInfo(testNetValAddr).Return(
&rpstore.Claimer{
DiscordID: discordID,
TotalReward: amount,
Expand All @@ -281,7 +285,7 @@ func TestClaim(t *testing.T) {
"", nil,
)

claimTx, err := eng.Claim([]string{valAddress, discordID})
claimTx, err := eng.Claim([]string{valAddress, testNetValAddr, discordID})
assert.EqualError(t, err, "can't send bond transaction")
assert.Nil(t, claimTx)
})
Expand Down
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ require (
google.golang.org/grpc v1.58.3
)

require github.com/gorilla/websocket v1.5.1 // indirect

require (
github.com/bwmarrin/discordgo v0.27.1
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect
github.com/fxamacker/cbor/v2 v2.5.0 // indirect
Expand Down
Loading
Loading