Skip to content

Commit

Permalink
refactor: move sub-commands into seperated files
Browse files Browse the repository at this point in the history
fixed #120
  • Loading branch information
mj committed May 22, 2024
1 parent 6a8bec4 commit 82c6352
Show file tree
Hide file tree
Showing 16 changed files with 513 additions and 447 deletions.
59 changes: 0 additions & 59 deletions internal/engine/command/blockchain/blockchain.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
package blockchain

import (
"fmt"
"strconv"

"github.com/pactus-project/pactus/types/amount"
"github.com/pagu-project/Pagu/internal/engine/command"
"github.com/pagu-project/Pagu/pkg/client"
"github.com/pagu-project/Pagu/pkg/utils"
)

const (
Expand Down Expand Up @@ -82,57 +77,3 @@ func (bc *Blockchain) GetCommand() command.Command {

return cmdBlockchain
}

func (bc *Blockchain) calcRewardHandler(cmd command.Command, _ command.AppID, _ string, args ...string) command.CommandResult {
stake, err := strconv.Atoi(args[0])
if err != nil {
return cmd.ErrorResult(err)
}

time := args[1]

if stake < 1 || stake > 1_000 {
return cmd.ErrorResult(fmt.Errorf("%v is invalid amount; minimum stake amount is 1 PAC and maximum is 1,000 PAC", stake))
}

var blocks int
switch time {
case "day":
blocks = 8640
case "month":
blocks = 259200
case "year":
blocks = 3110400
default:
blocks = 8640
time = "day"
}

bi, err := bc.clientMgr.GetBlockchainInfo()
if err != nil {
return cmd.ErrorResult(err)
}

reward := int64(stake*blocks) / int64(amount.Amount(bi.TotalPower).ToPAC())

return cmd.SuccessfulResult("Approximately you earn %v PAC reward, with %v PAC stake 🔒 on your validator in one %s ⏰ with %s total power ⚡ of committee."+
"\n\n> Note📝: This number is just an estimation. It will vary depending on your stake amount and total network power.",
utils.FormatNumber(reward), utils.FormatNumber(int64(stake)), time, utils.FormatNumber(int64(amount.Amount(bi.TotalPower).ToPAC())))
}

func (bc *Blockchain) calcFeeHandler(cmd command.Command, _ command.AppID, _ string, args ...string) command.CommandResult {
amt, err := amount.FromString(args[0])
if err != nil {
return cmd.ErrorResult(err)
}

fee, err := bc.clientMgr.GetFee(int64(amt))
if err != nil {
return cmd.ErrorResult(err)
}

calcedFee := amount.Amount(fee)

return cmd.SuccessfulResult("Sending %s will cost %s with current fee percentage."+
"\n> Note: Consider unbond and sortition transaction fee is 0 PAC always.", amt, calcedFee.String())
}
23 changes: 23 additions & 0 deletions internal/engine/command/blockchain/calc_fee.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package blockchain

import (
"github.com/pactus-project/pactus/types/amount"
"github.com/pagu-project/Pagu/internal/engine/command"
)

func (bc *Blockchain) calcFeeHandler(cmd command.Command, _ command.AppID, _ string, args ...string) command.CommandResult {
amt, err := amount.FromString(args[0])
if err != nil {
return cmd.ErrorResult(err)
}

fee, err := bc.clientMgr.GetFee(int64(amt))
if err != nil {
return cmd.ErrorResult(err)
}

calcedFee := amount.Amount(fee)

return cmd.SuccessfulResult("Sending %s will cost %s with current fee percentage."+
"\n> Note: Consider unbond and sortition transaction fee is 0 PAC always.", amt, calcedFee.String())
}
47 changes: 47 additions & 0 deletions internal/engine/command/blockchain/calc_reward.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package blockchain

import (
"fmt"
"strconv"

"github.com/pactus-project/pactus/types/amount"
"github.com/pagu-project/Pagu/internal/engine/command"
"github.com/pagu-project/Pagu/pkg/utils"
)

func (bc *Blockchain) calcRewardHandler(cmd command.Command, _ command.AppID, _ string, args ...string) command.CommandResult {
stake, err := strconv.Atoi(args[0])
if err != nil {
return cmd.ErrorResult(err)
}

time := args[1]

if stake < 1 || stake > 1_000 {
return cmd.ErrorResult(fmt.Errorf("%v is invalid amount; minimum stake amount is 1 PAC and maximum is 1,000 PAC", stake))
}

var blocks int
switch time {
case "day":
blocks = 8640
case "month":
blocks = 259200
case "year":
blocks = 3110400
default:
blocks = 8640
time = "day"
}

bi, err := bc.clientMgr.GetBlockchainInfo()
if err != nil {
return cmd.ErrorResult(err)
}

reward := int64(stake*blocks) / int64(amount.Amount(bi.TotalPower).ToPAC())

return cmd.SuccessfulResult("Approximately you earn %v PAC reward, with %v PAC stake 🔒 on your validator in one %s ⏰ with %s total power ⚡ of committee."+
"\n\n> Note📝: This number is just an estimation. It will vary depending on your stake amount and total network power.",
utils.FormatNumber(reward), utils.FormatNumber(int64(stake)), time, utils.FormatNumber(int64(amount.Amount(bi.TotalPower).ToPAC())))
}
31 changes: 31 additions & 0 deletions internal/engine/command/network/health.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package network

import (
"time"

"github.com/pagu-project/Pagu/internal/engine/command"
utils2 "github.com/pagu-project/Pagu/pkg/utils"
)

func (n *Network) networkHealthHandler(cmd command.Command, _ command.AppID, _ string, _ ...string) command.CommandResult {
lastBlockTime, lastBlockHeight := n.clientMgr.GetLastBlockTime()
lastBlockTimeFormatted := time.Unix(int64(lastBlockTime), 0).Format("02/01/2006, 15:04:05")
currentTime := time.Now()

timeDiff := (currentTime.Unix() - int64(lastBlockTime))

healthStatus := true
if timeDiff > 15 {
healthStatus = false
}

var status string
if healthStatus {
status = "Healthy✅"
} else {
status = "UnHealthy❌"
}

return cmd.SuccessfulResult("Network is %s\nCurrentTime: %v\nLastBlockTime: %v\nTime Diff: %v\nLast Block Height: %v",
status, currentTime.Format("02/01/2006, 15:04:05"), lastBlockTimeFormatted, timeDiff, utils2.FormatNumber(int64(lastBlockHeight)))
}
136 changes: 0 additions & 136 deletions internal/engine/command/network/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,9 @@ package network

import (
"context"
"fmt"
"time"

"github.com/libp2p/go-libp2p/core/peer"
"github.com/pactus-project/pactus/types/amount"
"github.com/pagu-project/Pagu/internal/engine/command"
"github.com/pagu-project/Pagu/pkg/client"
utils2 "github.com/pagu-project/Pagu/pkg/utils"
)

const (
Expand Down Expand Up @@ -117,134 +112,3 @@ func (n *Network) GetCommand() command.Command {

return cmdNetwork
}

func (n *Network) networkHealthHandler(cmd command.Command, _ command.AppID, _ string, _ ...string) command.CommandResult {
lastBlockTime, lastBlockHeight := n.clientMgr.GetLastBlockTime()
lastBlockTimeFormatted := time.Unix(int64(lastBlockTime), 0).Format("02/01/2006, 15:04:05")
currentTime := time.Now()

timeDiff := (currentTime.Unix() - int64(lastBlockTime))

healthStatus := true
if timeDiff > 15 {
healthStatus = false
}

var status string
if healthStatus {
status = "Healthy✅"
} else {
status = "UnHealthy❌"
}

return cmd.SuccessfulResult("Network is %s\nCurrentTime: %v\nLastBlockTime: %v\nTime Diff: %v\nLast Block Height: %v",
status, currentTime.Format("02/01/2006, 15:04:05"), lastBlockTimeFormatted, timeDiff, utils2.FormatNumber(int64(lastBlockHeight)))
}

func (be *Network) networkStatusHandler(cmd command.Command, _ command.AppID, _ string, _ ...string) command.CommandResult {
netInfo, err := be.clientMgr.GetNetworkInfo()
if err != nil {
return cmd.ErrorResult(err)
}

chainInfo, err := be.clientMgr.GetBlockchainInfo()
if err != nil {
return cmd.ErrorResult(err)
}

cs, err := be.clientMgr.GetCirculatingSupply()
if err != nil {
cs = 0
}

// Convert NanoPAC to PAC using the Amount type.
totalNetworkPower := amount.Amount(chainInfo.TotalPower).ToPAC()
totalCommitteePower := amount.Amount(chainInfo.CommitteePower).ToPAC()
circulatingSupply := amount.Amount(cs).ToPAC()

net := NetStatus{
ValidatorsCount: chainInfo.TotalValidators,
CurrentBlockHeight: chainInfo.LastBlockHeight,
TotalNetworkPower: int64(totalNetworkPower),
TotalCommitteePower: int64(totalCommitteePower),
NetworkName: netInfo.NetworkName,
TotalAccounts: chainInfo.TotalAccounts,
CirculatingSupply: int64(circulatingSupply),
}

return cmd.SuccessfulResult("Network Name: %s\nConnected Peers: %v\n"+
"Validators Count: %v\nAccounts Count: %v\nCurrent Block Height: %v\nTotal Power: %v PAC\nTotal Committee Power: %v PAC\nCirculating Supply: %v PAC\n"+
"\n> Note📝: This info is from one random network node. Non-blockchain data may not be consistent.",
net.NetworkName,
utils2.FormatNumber(int64(net.ConnectedPeersCount)),
utils2.FormatNumber(int64(net.ValidatorsCount)),
utils2.FormatNumber(int64(net.TotalAccounts)),
utils2.FormatNumber(int64(net.CurrentBlockHeight)),
utils2.FormatNumber(net.TotalNetworkPower),
utils2.FormatNumber(net.TotalCommitteePower),
utils2.FormatNumber(net.CirculatingSupply),
)
}

func (n *Network) nodeInfoHandler(cmd command.Command, _ command.AppID, _ string, args ...string) command.CommandResult {
valAddress := args[0]

peerInfo, err := n.clientMgr.GetPeerInfo(valAddress)
if err != nil {
return cmd.ErrorResult(err)
}

peerID, err := peer.IDFromBytes(peerInfo.PeerId)
if err != nil {
return cmd.ErrorResult(err)
}

ip := utils2.ExtractIPFromMultiAddr(peerInfo.Address)
geoData := utils2.GetGeoIP(ip)

nodeInfo := &NodeInfo{
PeerID: peerID.String(),
IPAddress: peerInfo.Address,
Agent: peerInfo.Agent,
Moniker: peerInfo.Moniker,
Country: geoData.CountryName,
City: geoData.City,
RegionName: geoData.RegionName,
TimeZone: geoData.TimeZone,
ISP: geoData.ISP,
}

// here we check if the node is also a validator.
// if its a validator , then we populate the validator data.
// if not validator then we set everything to 0/empty .
val, err := n.clientMgr.GetValidatorInfo(valAddress)
if err == nil && val != nil {
nodeInfo.ValidatorNum = val.Validator.Number
nodeInfo.AvailabilityScore = val.Validator.AvailabilityScore
// Convert NanoPAC to PAC using the Amount type and then to int64.
stakeAmount := amount.Amount(val.Validator.Stake).ToPAC()
nodeInfo.StakeAmount = int64(stakeAmount) // Convert float64 to int64.
nodeInfo.LastBondingHeight = val.Validator.LastBondingHeight
nodeInfo.LastSortitionHeight = val.Validator.LastSortitionHeight
} else {
nodeInfo.ValidatorNum = 0
nodeInfo.AvailabilityScore = 0
nodeInfo.StakeAmount = 0
nodeInfo.LastBondingHeight = 0
nodeInfo.LastSortitionHeight = 0
}

var pip19Score string
if nodeInfo.AvailabilityScore >= 0.9 {
pip19Score = fmt.Sprintf("%v✅", nodeInfo.AvailabilityScore)
} else {
pip19Score = fmt.Sprintf("%v⚠️", nodeInfo.AvailabilityScore)
}

return cmd.SuccessfulResult("PeerID: %s\nIP Address: %s\nAgent: %s\n"+
"Moniker: %s\nCountry: %s\nCity: %s\nRegion Name: %s\nTimeZone: %s\n"+
"ISP: %s\n\nValidator Info🔍\nNumber: %v\nPIP-19 Score: %s\nStake: %v PAC's\n",
nodeInfo.PeerID, nodeInfo.IPAddress, nodeInfo.Agent, nodeInfo.Moniker, nodeInfo.Country,
nodeInfo.City, nodeInfo.RegionName, nodeInfo.TimeZone, nodeInfo.ISP, utils2.FormatNumber(int64(nodeInfo.ValidatorNum)),
pip19Score, utils2.FormatNumber(nodeInfo.StakeAmount))
}
73 changes: 73 additions & 0 deletions internal/engine/command/network/node_info.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package network

import (
"fmt"

"github.com/libp2p/go-libp2p/core/peer"
"github.com/pactus-project/pactus/types/amount"
"github.com/pagu-project/Pagu/internal/engine/command"
utils2 "github.com/pagu-project/Pagu/pkg/utils"
)

func (n *Network) nodeInfoHandler(cmd command.Command, _ command.AppID, _ string, args ...string) command.CommandResult {
valAddress := args[0]

peerInfo, err := n.clientMgr.GetPeerInfo(valAddress)
if err != nil {
return cmd.ErrorResult(err)
}

peerID, err := peer.IDFromBytes(peerInfo.PeerId)
if err != nil {
return cmd.ErrorResult(err)
}

ip := utils2.ExtractIPFromMultiAddr(peerInfo.Address)
geoData := utils2.GetGeoIP(ip)

nodeInfo := &NodeInfo{
PeerID: peerID.String(),
IPAddress: peerInfo.Address,
Agent: peerInfo.Agent,
Moniker: peerInfo.Moniker,
Country: geoData.CountryName,
City: geoData.City,
RegionName: geoData.RegionName,
TimeZone: geoData.TimeZone,
ISP: geoData.ISP,
}

// here we check if the node is also a validator.
// if its a validator , then we populate the validator data.
// if not validator then we set everything to 0/empty .
val, err := n.clientMgr.GetValidatorInfo(valAddress)
if err == nil && val != nil {
nodeInfo.ValidatorNum = val.Validator.Number
nodeInfo.AvailabilityScore = val.Validator.AvailabilityScore
// Convert NanoPAC to PAC using the Amount type and then to int64.
stakeAmount := amount.Amount(val.Validator.Stake).ToPAC()
nodeInfo.StakeAmount = int64(stakeAmount) // Convert float64 to int64.
nodeInfo.LastBondingHeight = val.Validator.LastBondingHeight
nodeInfo.LastSortitionHeight = val.Validator.LastSortitionHeight
} else {
nodeInfo.ValidatorNum = 0
nodeInfo.AvailabilityScore = 0
nodeInfo.StakeAmount = 0
nodeInfo.LastBondingHeight = 0
nodeInfo.LastSortitionHeight = 0
}

var pip19Score string
if nodeInfo.AvailabilityScore >= 0.9 {
pip19Score = fmt.Sprintf("%v✅", nodeInfo.AvailabilityScore)
} else {
pip19Score = fmt.Sprintf("%v⚠️", nodeInfo.AvailabilityScore)
}

return cmd.SuccessfulResult("PeerID: %s\nIP Address: %s\nAgent: %s\n"+
"Moniker: %s\nCountry: %s\nCity: %s\nRegion Name: %s\nTimeZone: %s\n"+
"ISP: %s\n\nValidator Info🔍\nNumber: %v\nPIP-19 Score: %s\nStake: %v PAC's\n",
nodeInfo.PeerID, nodeInfo.IPAddress, nodeInfo.Agent, nodeInfo.Moniker, nodeInfo.Country,
nodeInfo.City, nodeInfo.RegionName, nodeInfo.TimeZone, nodeInfo.ISP, utils2.FormatNumber(int64(nodeInfo.ValidatorNum)),
pip19Score, utils2.FormatNumber(nodeInfo.StakeAmount))
}
Loading

0 comments on commit 82c6352

Please sign in to comment.