Skip to content

Commit

Permalink
tidy
Browse files Browse the repository at this point in the history
  • Loading branch information
faddat committed Nov 2, 2024
1 parent db5c184 commit 5078a02
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 101 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ require (
github.com/cosmos/go-bip39 v1.0.0
github.com/cosmos/ibc-go/v7 v7.8.0
github.com/prometheus/client_golang v1.20.4
golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa
google.golang.org/grpc v1.67.0
)

Expand Down Expand Up @@ -172,6 +171,7 @@ require (
go.uber.org/atomic v1.10.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/crypto v0.27.0 // indirect
golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa // indirect
golang.org/x/net v0.29.0 // indirect
golang.org/x/oauth2 v0.22.0 // indirect
golang.org/x/sync v0.8.0 // indirect
Expand Down
2 changes: 1 addition & 1 deletion lib/lib.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func GetAccountInfo(address string, config types.Config) (seqint, accnum uint64,

// Check if account is nil or sequence/account_number is empty
if accountRes.Account.Sequence == "" || accountRes.Account.AccountNumber == "" {
return 0, 0, fmt.Errorf("account does not exist or has no sequence/account_number")
return 0, 0, errors.New("account does not exist or has no sequence/account_number")
}

seqint, err = strconv.ParseUint(accountRes.Account.Sequence, 10, 64)
Expand Down
135 changes: 36 additions & 99 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"log"
"os"
"sync"
"time"
Expand All @@ -13,9 +14,7 @@ import (
"github.com/somatic-labs/meteorite/client"
"github.com/somatic-labs/meteorite/lib"
"github.com/somatic-labs/meteorite/types"
"golang.org/x/exp/rand"

"cosmossdk.io/log"
sdkmath "cosmossdk.io/math"

sdk "github.com/cosmos/cosmos-sdk/types"
Expand All @@ -27,18 +26,14 @@ const (
)

func main() {
logger := log.NewLogger(os.Stdout)

config := types.Config{}
if _, err := toml.DecodeFile("nodes.toml", &config); err != nil {
logger.Error("Failed to load config", "error", err)
log.Fatalf("Failed to load config: %v", err)
}

config.Logger = logger

mnemonic, err := os.ReadFile("seedphrase")
if err != nil {
logger.Error("Failed to read seed phrase", "error", err)
log.Fatalf("Failed to read seed phrase: %v", err)
}

// Set Bech32 prefixes and seal the configuration once
Expand All @@ -51,7 +46,7 @@ func main() {
positions := config.Positions
const MaxPositions = 100 // Adjust based on requirements
if positions <= 0 || positions > MaxPositions {
logger.Error(fmt.Sprintf("Number of positions must be between 1 and %d, got: %d", MaxPositions, positions))
log.Fatalf("Number of positions must be between 1 and %d, got: %d", MaxPositions, positions)
}
fmt.Println("Positions", positions)

Expand All @@ -60,7 +55,7 @@ func main() {
position := uint32(i)
privKey, pubKey, acctAddress := lib.GetPrivKey(config, mnemonic, position)
if privKey == nil || pubKey == nil || len(acctAddress) == 0 {
logger.Error(fmt.Sprintf("Failed to generate keys for position %d", position))
log.Fatalf("Failed to generate keys for position %d", position)
}
accounts = append(accounts, types.Account{
PrivKey: privKey,
Expand All @@ -70,7 +65,7 @@ func main() {
})
}

// Print addresses and positions at startup
// **Print addresses and positions at startup**
fmt.Println("Addresses and Positions:")
for _, acct := range accounts {
fmt.Printf("Position %d: Address: %s\n", acct.Position, acct.Address)
Expand All @@ -79,15 +74,15 @@ func main() {
// Get balances and ensure they are within 10% of each other
balances, err := lib.GetBalances(accounts, config)
if err != nil {
logger.Error("Failed to get balances", "error", err)
log.Fatalf("Failed to get balances: %v", err)
}

// Print addresses and balances
fmt.Println("Wallets and Balances:")
for _, acct := range accounts {
balance, err := lib.GetAccountBalance(acct.Address, config)
if err != nil {
logger.Error("Failed to get balance", "address", acct.Address, "error", err)
log.Printf("Failed to get balance for %s: %v", acct.Address, err)
continue
}
fmt.Printf("Position %d: Address: %s, Balance: %s %s\n", acct.Position, acct.Address, balance.String(), config.Denom)
Expand All @@ -98,18 +93,24 @@ func main() {
if !lib.CheckBalancesWithinThreshold(balances, 0.10) {
fmt.Println("Account balances are not within 10% of each other. Adjusting balances...")
if err := handleBalanceAdjustment(accounts, balances, config); err != nil {
logger.Error("Failed to handle balance adjustment", "error", err)
log.Fatalf("Failed to handle balance adjustment: %v", err)
}
}

nodeURL := config.Nodes.RPC[0] // Use the first node

chainID, err := lib.GetChainID(nodeURL)
if err != nil {
logger.Error("Failed to get chain ID", "error", err)
log.Fatalf("Failed to get chain ID: %v", err)
}

// msgParams := config.MsgParams
msgParams := config.MsgParams

// Initialize gRPC client
// grpcClient, err := client.NewGRPCClient(config.Nodes.GRPC)
// if err != nil {
// log.Fatalf("Failed to create gRPC client: %v", err)
// }

var wg sync.WaitGroup
for _, account := range accounts {
Expand All @@ -120,33 +121,10 @@ func main() {
// Get account info
sequence, accNum, err := lib.GetAccountInfo(acct.Address, config)
if err != nil {
logger.Error("Failed to get account info", "address", acct.Address, "error", err)
log.Printf("Failed to get account info for %s: %v", acct.Address, err)
return
}

// Copy msgParams for this account
accountMsgParams := config.MsgParams

if config.Greed {
// When greed is true, send only to our generated addresses
toAcct := pickAnotherAccount(acct, accounts)
if toAcct == nil {
logger.Error("No other accounts to send to", "address", acct.Address)
return
}
accountMsgParams.ToAddress = toAcct.Address
logger.Info("Greed mode: Sending to address", "from", acct.Address, "to", toAcct.Address)
} else {
if accountMsgParams.ToAddress == "" {
// When greed is false and ToAddress is empty, send to random address
// The existing logic in send.go will handle generating a random address
logger.Info("Sending to random address because ToAddress is empty")
} else {
// Use the configured ToAddress
logger.Info("Sending to configured ToAddress", "to", accountMsgParams.ToAddress)
}
}

txParams := types.TransactionParams{
Config: config,
NodeURL: nodeURL,
Expand All @@ -157,11 +135,11 @@ func main() {
PubKey: acct.PubKey,
AcctAddress: acct.Address,
MsgType: config.MsgType,
MsgParams: accountMsgParams,
MsgParams: msgParams,
}

// Broadcast transactions
successfulTxns, failedTxns, responseCodes, _ := broadcast.Loop(txParams, BatchSize, int(acct.Position), config.BroadcastModes[0])
successfulTxns, failedTxns, responseCodes, _ := broadcast.Loop(txParams, BatchSize, int(acct.Position), config.Denom)

fmt.Printf("Account %s: Successful transactions: %d, Failed transactions: %d\n", acct.Address, successfulTxns, failedTxns)
fmt.Println("Response code breakdown:")
Expand Down Expand Up @@ -358,18 +336,23 @@ func TransferFunds(sender types.Account, receiverAddress string, amount sdkmath.

resp, _, err := broadcast.SendTransactionViaGRPC(ctx, txParams, sequence, grpcClient)
if err != nil {
config.Logger.Error("Transaction failed",
"error", err,
"sequence", sequence)
} else if resp != nil && resp.Code == 0 {
config.Logger.Info("Transaction successful",
"txhash", resp.TxHash,
"sequence", sequence,
"gas_used", resp.GasUsed)
}
fmt.Printf("Transaction failed: %v\n", err)

// Check if the error is a sequence mismatch error (code 32)
if resp != nil && resp.Code == 32 {
expectedSeq, parseErr := lib.ExtractExpectedSequence(resp.RawLog)
if parseErr != nil {
return fmt.Errorf("failed to parse expected sequence: %v", parseErr)
}

// Update sequence and retry
sequence = expectedSeq
txParams.Sequence = sequence
fmt.Printf("Sequence mismatch detected. Updating sequence to %d and retrying...\n", sequence)
continue
}

if resp.Code == 0 {
fmt.Printf("Transaction successful - TxHash: %s\n", resp.TxHash)
return fmt.Errorf("failed to send transaction: %v", err)
}

if resp.Code != 0 {
Expand All @@ -389,25 +372,6 @@ func TransferFunds(sender types.Account, receiverAddress string, amount sdkmath.
continue
}

// Assuming you are inside the loop where you handle the transaction response
if resp.Code == 41 {
fmt.Printf("Transaction failed with code %d: %s\n", resp.Code, resp.RawLog)
maxBlockGas := 75000000
newGasLimit := maxBlockGas - 1000000
txParams.Config.Gas.Limit = int64(newGasLimit)
fmt.Printf("Reducing gas limit to %d and retrying...\n", newGasLimit)

// Retry sending the transaction
resp, _, err = broadcast.SendTransactionViaGRPC(ctx, txParams, sequence, grpcClient)
if resp.Code != 0 {
fmt.Printf("Transaction failed with code %d: %s\n", resp.Code, resp.RawLog)
continue
}
if err != nil {
return fmt.Errorf("failed to send transaction: %v", err)
}
}

return fmt.Errorf("transaction failed with code %d: %s", resp.Code, resp.RawLog)
}

Expand Down Expand Up @@ -458,30 +422,3 @@ func shouldProceedWithBalances(balances map[string]sdkmath.Int) bool {

return false
}

func displayStats(stats map[string]types.TransmissionStats) {
fmt.Println("Transmission Stats:")
for mode, stat := range stats {
fmt.Printf("Mode: %s\n", mode)
fmt.Printf(" Successful Transactions: %d\n", stat.Successful)
fmt.Printf(" Failed Transactions: %d\n", stat.Failed)
for code, count := range stat.ResponseCodes {
fmt.Printf(" Response Code %d: %d times\n", code, count)
}
}
}

func pickAnotherAccount(current types.Account, accounts []types.Account) *types.Account {
var otherAccounts []types.Account
for _, acct := range accounts {
if acct.Address != current.Address {
otherAccounts = append(otherAccounts, acct)
}
}
if len(otherAccounts) == 0 {
return nil
}
rand.Seed(uint64(time.Now().UnixNano()))
index := rand.Intn(len(otherAccounts))
return &otherAccounts[index]
}

0 comments on commit 5078a02

Please sign in to comment.