Skip to content

Commit

Permalink
update the 47 version's logger
Browse files Browse the repository at this point in the history
  • Loading branch information
faddat committed Nov 2, 2024
1 parent 5078a02 commit d2698d5
Show file tree
Hide file tree
Showing 6 changed files with 170 additions and 42 deletions.
8 changes: 8 additions & 0 deletions broadcast/broadcast.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,19 @@ func Loop(
position int,
mode string,
) (successfulTxns, failedTxns int, responseCodes map[uint32]int, updatedSequence uint64) {
// Initialize return values
successfulTxns = 0
failedTxns = 0
responseCodes = make(map[uint32]int)
sequence := txParams.Sequence

// Add nil checks
if txParams.Config.Logger == nil {
fmt.Printf("Error: Logger is not initialized for position %d\n", position)
failedTxns = batchSize
return successfulTxns, failedTxns, responseCodes, sequence
}

txParams.Config.Logger.Info("Starting transaction loop",
"position", position,
"batch_size", batchSize,
Expand Down
4 changes: 2 additions & 2 deletions configurations/atone/nodes.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ label = "statefilestore"
#amount = 1000

[gas]
low = 1
precision = 3
low = 25
precision = 4
# limit = 75000000

[nodes]
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ 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 @@ -171,7 +172,6 @@ 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
13 changes: 9 additions & 4 deletions lib/lib.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ func GetAccountInfo(address string, config types.Config) (seqint, accnum uint64,
return 0, 0, fmt.Errorf("failed to unmarshal account result: %v", err)
}

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

seqint, err = strconv.ParseUint(accountRes.Account.Sequence, 10, 64)
Expand Down Expand Up @@ -188,6 +188,11 @@ func GetAccountBalance(address string, config types.Config) (sdkmath.Int, error)
return sdkmath.ZeroInt(), err
}

// If balances array is empty, return zero
if len(balanceRes.Balances) == 0 {
return sdkmath.ZeroInt(), nil
}

for _, coin := range balanceRes.Balances {
if coin.Denom == config.Denom {
amount, ok := sdkmath.NewIntFromString(coin.Amount)
Expand All @@ -198,8 +203,8 @@ func GetAccountBalance(address string, config types.Config) (sdkmath.Int, error)
}
}

// If no balance found for the denom, return zero balance
return sdkmath.ZeroInt(), fmt.Errorf("denomination %s not found in account balances", config.Denom)
// If denomination not found but balances exist, return zero
return sdkmath.ZeroInt(), nil
}

func CheckBalancesWithinThreshold(balances map[string]sdkmath.Int, threshold float64) bool {
Expand Down
106 changes: 84 additions & 22 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import (
"context"
"errors"
"fmt"
"log"
"os"
"sync"
"time"

"cosmossdk.io/log"
"github.com/BurntSushi/toml"
"github.com/somatic-labs/meteorite/broadcast"
"github.com/somatic-labs/meteorite/client"
Expand All @@ -26,14 +26,17 @@ const (
)

func main() {

config := types.Config{}
config.Logger = log.NewLogger(os.Stdout)

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

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

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

Expand All @@ -55,7 +58,7 @@ func main() {
position := uint32(i)
privKey, pubKey, acctAddress := lib.GetPrivKey(config, mnemonic, position)
if privKey == nil || pubKey == nil || len(acctAddress) == 0 {
log.Fatalf("Failed to generate keys for position %d", position)
config.Logger.Error("Failed to generate keys for position %d", position)
}
accounts = append(accounts, types.Account{
PrivKey: privKey,
Expand All @@ -74,15 +77,15 @@ func main() {
// Get balances and ensure they are within 10% of each other
balances, err := lib.GetBalances(accounts, config)
if err != nil {
log.Fatalf("Failed to get balances: %v", err)
config.Logger.Error("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 {
log.Printf("Failed to get balance for %s: %v", acct.Address, err)
config.Logger.Error("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 @@ -93,15 +96,15 @@ 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 {
log.Fatalf("Failed to handle balance adjustment: %v", err)
config.Logger.Error("Failed to handle balance adjustment: %v", err)
}
}

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

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

msgParams := config.MsgParams
Expand All @@ -121,8 +124,9 @@ func main() {
// Get account info
sequence, accNum, err := lib.GetAccountInfo(acct.Address, config)
if err != nil {
log.Printf("Failed to get account info for %s: %v", acct.Address, err)
return
config.Logger.Error("Warning: Failed to get account info for %s: %v. Proceeding with sequence 0", acct.Address, err)
sequence = 0
accNum = 0
}

txParams := types.TransactionParams{
Expand Down Expand Up @@ -175,7 +179,7 @@ func adjustBalances(accounts []types.Account, balances map[string]sdkmath.Int, c
fmt.Printf("Number of Accounts: %d, Average Balance per account: %s %s\n", numAccounts.Int64(), averageBalance.String(), config.Denom)

// Define minimum transfer amount to avoid dust transfers
minTransfer := sdkmath.NewInt(1000000) // Adjust based on your token's decimal places
minTransfer := sdkmath.NewInt(10000) // Adjust based on your token's decimal places
fmt.Printf("Minimum Transfer Amount to avoid dust: %s %s\n", minTransfer.String(), config.Denom)

// Create a slice to track balances that need to send or receive funds
Expand Down Expand Up @@ -283,6 +287,35 @@ func adjustBalances(accounts []types.Account, balances map[string]sdkmath.Int, c
return nil
}

func shouldProceedWithBalances(balances map[string]sdkmath.Int) bool {
// Check if balances map is nil or empty
if balances == nil || len(balances) == 0 {

Check failure on line 292 in main.go

View workflow job for this annotation

GitHub Actions / lint

S1009: should omit nil check; len() for map[string]cosmossdk.io/math.Int is defined as zero (gosimple)
fmt.Println("No balances to check")
return false
}

if lib.CheckBalancesWithinThreshold(balances, 0.15) {
fmt.Println("Balances successfully adjusted within acceptable range")
return true
}

var maxBalance sdkmath.Int
for _, balance := range balances {
if balance.IsNil() {
continue // Skip nil balances
}
if maxBalance.IsNil() {
maxBalance = balance
continue
}
if balance.GT(maxBalance) {
maxBalance = balance
}
}

return false
}

func TransferFunds(sender types.Account, receiverAddress string, amount sdkmath.Int, config types.Config) error {
fmt.Printf("\n=== Starting Transfer ===\n")
fmt.Printf("Sender Address: %s\n", sender.Address)
Expand Down Expand Up @@ -400,25 +433,54 @@ func handleBalanceAdjustment(accounts []types.Account, balances map[string]sdkma

return nil
}

func shouldProceedWithBalances(balances map[string]sdkmath.Int) bool {
if lib.CheckBalancesWithinThreshold(balances, 0.15) {
fmt.Println("Balances successfully adjusted within acceptable range")
return true
func CheckBalancesWithinThreshold(balances map[string]sdkmath.Int, threshold float64) bool {
if balances == nil || len(balances) == 0 {

Check failure on line 437 in main.go

View workflow job for this annotation

GitHub Actions / lint

S1009: should omit nil check; len() for map[string]cosmossdk.io/math.Int is defined as zero (gosimple)
return false
}

var maxBalance sdkmath.Int
var minBalance, maxBalance sdkmath.Int
first := true

for _, balance := range balances {
if balance.IsNil() {
continue // Skip nil balances
}

if first {
minBalance = balance
maxBalance = balance
first = false
continue
}

if balance.LT(minBalance) {
minBalance = balance
}
if balance.GT(maxBalance) {
maxBalance = balance
}
}

minSignificantBalance := sdkmath.NewInt(1000000)
if maxBalance.LT(minSignificantBalance) {
fmt.Println("Remaining balance differences are below minimum threshold, proceeding")
// If we didn't find any valid balances
if first {
return false
}

// Skip check if all balances are below minimum threshold
minThreshold := sdkmath.NewInt(1000000) // 1 token assuming 6 decimals
if maxBalance.LT(minThreshold) {
return true
}

return false
// Calculate the difference as a percentage of the max balance
if maxBalance.IsZero() {
return minBalance.IsZero()
}

diff := maxBalance.Sub(minBalance)
diffFloat := float64(diff.Int64())
maxFloat := float64(maxBalance.Int64())

percentage := diffFloat / maxFloat
return percentage <= threshold
}
79 changes: 66 additions & 13 deletions modules/bank/send.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package bank

import (
"fmt"
"os"

"github.com/somatic-labs/meteorite/lib"
types "github.com/somatic-labs/meteorite/types"
"golang.org/x/exp/rand"

sdkmath "cosmossdk.io/math"

Expand All @@ -19,25 +21,76 @@ func CreateBankSendMsg(config types.Config, fromAddress string, msgParams types.
return nil, "", fmt.Errorf("invalid from address: %w", err)
}

toAccAddress, err := sdk.AccAddressFromBech32(msgParams.ToAddress)
if err != nil {
// fmt.Println("invalid to address, in nodes.toml, automatically spamming random new accounts")
toAccAddress, err = lib.GenerateRandomAccount()
var toAccAddress sdk.AccAddress
var toAddress string

// Handle greed mode
if config.Greed {

Check failure on line 28 in modules/bank/send.go

View workflow job for this annotation

GitHub Actions / lint

`if config.Greed` has complex nested blocks (complexity: 12) (nestif)
mnemonic, err := os.ReadFile("seedphrase")
if err != nil {
config.Logger.Error("error generating random account: %w", err)
return nil, "", fmt.Errorf("error generating random account: %w", err)
config.Logger.Error("error reading seedphrase: %w", err)
return nil, "", fmt.Errorf("error reading seedphrase: %w", err)
}

// Keep track of tried positions to avoid infinite loop
triedPositions := make(map[uint32]bool)
maxAttempts := int(config.Positions) // Try all possible positions if needed

for attempt := 0; attempt < maxAttempts; attempt++ {
position := uint32(rand.Intn(int(config.Positions)))

// Skip if we've already tried this position
if triedPositions[position] {
continue
}
triedPositions[position] = true

_, _, randomAddress := lib.GetPrivKey(config, mnemonic, position)

// Don't send to self
if randomAddress == fromAddress {
continue
}

toAccAddress, err = sdk.AccAddressFromBech32(randomAddress)
if err == nil {
toAddress = randomAddress
config.Logger.Info("Selected recipient in greed mode",
"address", toAddress,
"position", position)
break
}
}

if toAddress == "" {
return nil, "", fmt.Errorf("could not find valid recipient after trying all positions")
}
} else {
// Original non-greed mode logic
if msgParams.ToAddress == "" {
toAccAddress, err = lib.GenerateRandomAccount()
if err != nil {
config.Logger.Error("error generating random account: %w", err)
return nil, "", fmt.Errorf("error generating random account: %w", err)
}
toAddress = toAccAddress.String()
} else {
toAccAddress, err = sdk.AccAddressFromBech32(msgParams.ToAddress)
if err != nil {
config.Logger.Error("invalid to address: %w", err)
return nil, "", fmt.Errorf("invalid to address: %w", err)
}
toAddress = msgParams.ToAddress
}
}

amount := sdk.NewCoins(sdk.NewCoin(config.Denom, sdkmath.NewInt(msgParams.Amount)))

msg := banktypes.NewMsgSend(fromAccAddress, toAccAddress, amount)

memo, err := lib.GenerateRandomStringOfLength(256)
if err != nil {
config.Logger.Error("error generating random memo: %w", err)
return nil, "", fmt.Errorf("error generating random memo: %w", err)
}
config.Logger.Info("Creating bank send message",
"from", fromAddress,
"to", toAddress,
"amount", amount.String())

return msg, memo, nil
return msg, "", nil
}

0 comments on commit d2698d5

Please sign in to comment.