From 5078a0238d46dcc2302eee370c69bec4bb2a2b95 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sat, 2 Nov 2024 18:50:03 +0700 Subject: [PATCH] tidy --- go.mod | 2 +- lib/lib.go | 2 +- main.go | 135 ++++++++++++++--------------------------------------- 3 files changed, 38 insertions(+), 101 deletions(-) diff --git a/go.mod b/go.mod index 8e8cc1f..c975ea2 100644 --- a/go.mod +++ b/go.mod @@ -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 ) @@ -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 diff --git a/lib/lib.go b/lib/lib.go index 8e0ab26..ae7b0c1 100644 --- a/lib/lib.go +++ b/lib/lib.go @@ -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) diff --git a/main.go b/main.go index 86f3a00..e93b624 100644 --- a/main.go +++ b/main.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "log" "os" "sync" "time" @@ -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" @@ -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 @@ -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) @@ -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, @@ -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) @@ -79,7 +74,7 @@ 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 @@ -87,7 +82,7 @@ func main() { 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) @@ -98,7 +93,7 @@ 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) } } @@ -106,10 +101,16 @@ func main() { 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 { @@ -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, @@ -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:") @@ -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 { @@ -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) } @@ -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] -}