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/gardenv1 #6

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
66 changes: 49 additions & 17 deletions fund.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,52 @@ import (

"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/catalogfi/blockchain"
"github.com/catalogfi/blockchain/localnet"
"github.com/ethereum/go-ethereum/common"
"github.com/gagliardetto/solana-go"
"github.com/gagliardetto/solana-go/rpc"
)

func (m *Merry) Fund(to string) error {
if !m.Running {
return fmt.Errorf("merry is not running")
}
_, err := btcutil.DecodeAddress(to, &chaincfg.RegressionNetParams)
if err != nil {
if len(to) == 42 {
to = to[2:]
}
if len(to) == 40 {
_, err := hex.DecodeString(to)
if err != nil {
return fmt.Errorf("to is not an ethereum or a bitcoin regtest address: %s", to)
}
return fundEVM(to)
}
return fmt.Errorf("to is not an ethereum or a bitcoin regtest address: %s", to)
}
return fundBTC(to)

if _, err := btcutil.DecodeAddress(to, &chaincfg.RegressionNetParams); err == nil {
return fundBTC(to)
}

if solAddress, err := solana.PublicKeyFromBase58(to); err == nil {
return fundSolana(solAddress)
}

if len(to) == 42 {
to = to[2:]
}
if _, err := hex.DecodeString(to); err == nil {
return fundEVM(to)
}
Comment on lines +36 to +41
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve Ethereum address handling and validation

The current implementation assumes Ethereum addresses are always 42 characters long with a "0x" prefix and strips the prefix manually. This may lead to errors if the address is provided without the prefix or in an unexpected format.

Consider using common.HexToAddress() from the Ethereum package, which correctly handles addresses with or without the "0x" prefix and ensures proper validation.

Apply this diff to improve address handling:

-	if len(to) == 42 {
-		to = to[2:]
-	}
-	if _, err := hex.DecodeString(to); err == nil {
+	address := common.HexToAddress(to)
+	if address != (common.Address{}) && address.Hex() != "0x0000000000000000000000000000000000000000" {
 		return fundEVM(address.Hex())
 	}

Committable suggestion skipped: line range outside the PR's diff.


return fmt.Errorf("Invalid address %s. Expected a valid ethereum, solana or bitcoin regtest address", to)
}

func fundSolana(to solana.PublicKey) error {
client := rpc.New(rpc.LocalNet_RPC)
amount := uint64(100)
amountLamports := solana.LAMPORTS_PER_SOL * amount

if _, err := client.RequestAirdrop(context.TODO(), to, amountLamports, rpc.CommitmentConfirmed); err != nil {
return fmt.Errorf("Failed to airdrop SOL: %v", err)
}
fmt.Printf("Successfully airdropped %d SOL to %s\n", amount, to.String())
return nil
}

func fundEVM(to string) error {
ethAmount, _ := new(big.Int).SetString("1000000000000000000", 10)
seedAmount, _ := new(big.Int).SetString("1000000000000000000", 10)

wbtcAmount, _ := new(big.Int).SetString("100000000", 10)
wallet, err := localnet.EVMWallet(0)
if err != nil {
Expand All @@ -49,8 +68,11 @@ func fundEVM(to string) error {
if err != nil {
return fmt.Errorf("failed to send eth: %v", err)
}

ethereumWBTCAsset := blockchain.NewERC20(blockchain.NewEvmChain(blockchain.EthereumLocalnet), common.HexToAddress("0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512"), common.HexToAddress("0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0"))

fmt.Printf("Successfully sent %v ETH on Ethereum Localnet at: http://localhost:5100/tx/%s\n", ethAmount, tx.Hash().Hex())
tx2, err := wallet.Send(context.Background(), localnet.WBTC(), common.HexToAddress(to), wbtcAmount)
tx2, err := wallet.Send(context.Background(), ethereumWBTCAsset, common.HexToAddress(to), wbtcAmount)
if err != nil {
return fmt.Errorf("failed to send eth: %v", err)
}
Comment on lines +75 to 78
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Error messages for WBTC transactions reference wrong asset

In the error handling after sending WBTC (tx2 and tx4), the error messages incorrectly state "failed to send eth" instead of "failed to send WBTC". This inconsistency might lead to confusion during error troubleshooting.

Apply this diff to correct the error messages:

// After tx2 (Ethereum Localnet WBTC transaction)
	if err != nil {
-		return fmt.Errorf("failed to send eth: %v", err)
+		return fmt.Errorf("failed to send WBTC: %v", err)
	}

// After tx4 (Arbitrum Localnet WBTC transaction)
	if err != nil {
-		return fmt.Errorf("failed to send eth: %v", err)
+		return fmt.Errorf("failed to send WBTC: %v", err)
	}

Also applies to: 71-74

Expand All @@ -59,12 +81,22 @@ func fundEVM(to string) error {
if err != nil {
return fmt.Errorf("failed to send eth: %v", err)
}

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Incorrect amount displayed in log message

In the fmt.Printf statement logging the ETH transaction on Arbitrum Localnet, wbtcAmount is used instead of ethAmount. This may lead to incorrect information being displayed to the user.

Apply this diff to correct the displayed amount:

	fmt.Printf("Successfully sent %v ETH on Arbitrum Localnet at: http://localhost:5101/tx/%s\n",
-		wbtcAmount, tx3.Hash().Hex())
+		ethAmount, tx3.Hash().Hex())

Committable suggestion was skipped due to low confidence.

fmt.Printf("Successfully sent %v ETH on Arbitrum Localnet at: http://localhost:5101/tx/%s\n", wbtcAmount, tx3.Hash().Hex())
tx4, err := wallet.Send(context.Background(), localnet.ArbitrumWBTC(), common.HexToAddress(to), wbtcAmount)
arbWBTCAsset := blockchain.NewERC20(blockchain.NewEvmChain(blockchain.ArbitrumLocalnet), common.HexToAddress("0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0"), common.HexToAddress("0x0165878A594ca255338adfa4d48449f69242Eb8F"))
tx4, err := wallet.Send(context.Background(), arbWBTCAsset, common.HexToAddress(to), wbtcAmount)
if err != nil {
return fmt.Errorf("failed to send eth: %v", err)
}
fmt.Printf("Successfully sent %v WBTC on Arbitrum Localnet at: http://localhost:5101/tx/%s\n", wbtcAmount, tx4.Hash().Hex())

arbSeedAsset := blockchain.NewERC20(blockchain.NewEvmChain(blockchain.ArbitrumLocalnet), common.HexToAddress("0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512"), common.HexToAddress("0x5FC8d32690cc91D4c39d9d3abcBD16989F875707"))
tx5, err := wallet.Send(context.Background(), arbSeedAsset, common.HexToAddress(to), wbtcAmount)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Incorrect amount used when sending SEED tokens

The wallet.Send function is using wbtcAmount instead of seedAmount when sending SEED tokens (arbSeedAsset). This might result in sending the wrong amount of SEED tokens.

Apply this diff to use seedAmount:

	tx5, err := wallet.Send(context.Background(), arbSeedAsset, common.HexToAddress(to),
-		wbtcAmount)
+		seedAmount)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
tx5, err := wallet.Send(context.Background(), arbSeedAsset, common.HexToAddress(to), wbtcAmount)
tx5, err := wallet.Send(context.Background(), arbSeedAsset, common.HexToAddress(to), seedAmount)

if err != nil {
return fmt.Errorf("failed to send eth: %v", err)
}
Comment on lines +95 to +97
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Inconsistent error handling messages

Several error messages within different transaction blocks use the same generic message "failed to send eth", even when sending different assets like WBTC or SEED tokens. Consistent and specific error messages improve debuggability.

Consider updating all error messages to reflect the specific asset involved in the transaction.


fmt.Printf("Successfully sent %v SEED on Arbitrum Localnet at: http://localhost:5101/tx/%s\n", seedAmount, tx5.Hash().Hex())
return nil
}

Expand Down
19 changes: 14 additions & 5 deletions go.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func (m *Merry) Start() error {
}
composePath := filepath.Join(home, ".merry", "docker-compose.yml")

bashCmd := runDockerCompose(composePath, "up", "-d", "cobi", "esplora", "ethereum-explorer", "arbitrum-explorer", "nginx")
bashCmd := runDockerCompose(composePath, "up", "-d", "cobi", "esplora", "ethereum-explorer", "arbitrum-explorer", "nginx", "garden-evm-watcher", "garden-db", "quote", "bit-ponder", "cobiv2", "relayer", "solana-validator", "virtual-balance", "solana-executor", "solana-relayer", "solana-watcher")
if m.IsHeadless && m.IsBare {
bashCmd = runDockerCompose(composePath, "up", "-d", "chopsticks", "ethereum", "arbitrum", "cosigner")
} else if m.IsHeadless {
Expand All @@ -39,7 +39,7 @@ func (m *Merry) Start() error {
fmt.Println("ENDPOINTS")
for name, endpoint := range m.Services {
if m.IsBare {
if name == "cobi" || name == "redis" || name == "orderbook" || name == "postgres" {
if name == "cobi" || name == "redis" || name == "orderbook" || name == "postgres" || name == "garden-evm-watcher" || name == "garden-db" || name == "matcher" || name == "bit-ponder" {
continue
}
Comment on lines +42 to 44
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Refactor service exclusion logic for maintainability

The condition to exclude services is becoming lengthy and harder to maintain:

if name == "cobi" || name == "redis" || name == "orderbook" || name == "postgres" || name == "garden-evm-watcher" || name == "garden-db" || name == "matcher" || name == "bit-ponder" {
	continue
}

Consider refactoring this by using a slice or map to store the service names and check for inclusion. This approach enhances readability and makes it easier to manage the list of services.

Example using a slice:

excludedServices := []string{"cobi", "redis", "orderbook", "postgres", "garden-evm-watcher", "garden-db", "matcher", "bit-ponder"}

if contains(excludedServices, name) {
	continue
}

func contains(slice []string, item string) bool {
	for _, s := range slice {
		if s == item {
			return true
		}
	}
	return false
}

}
Expand All @@ -56,9 +56,18 @@ func (m *Merry) Start() error {
return err
}

retry(func() error {
return fundBTC("bcrt1q5428vq2uzwhm3taey9sr9x5vm6tk78ew8pf2xw")
})
// Funding
fundAddresses := []string{
"bcrt1qgyf47wrtnr9gsr06gn62ft6m4lzylcnllrf9cf", // cobi btc address
"0x70997970c51812dc3a010c7d01b50e0d17dc79c8", // cobi evm address
"4zvwRjXUKGfvwnParsHAS3HuSVzV5cA4McphgmoCtajS", // cobi sol address
"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9", // solana relayer
}

for _, addr := range fundAddresses {
retry(func() error { return m.Fund(addr) })
}

retry(func() error {
// try establishing connection with the ethereum clients
_, err := localnet.EVMClient()
Expand Down
18 changes: 17 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ require (
github.com/compose-spec/compose-go v0.0.0-20210729195839-de56f4f0cb3c
github.com/ethereum/go-ethereum v1.14.5
github.com/fvbock/endless v0.0.0-20170109170031-447134032cb6
github.com/gagliardetto/solana-go v1.12.0
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Add test coverage and improve error handling for Solana integration

The Solana integration appears to be missing crucial components:

  • Limited error handling found (only address validation)
  • No test files covering Solana functionality
  • Basic configuration exists in docker-compose but no documentation found

Action items:

  • Add comprehensive error handling for Solana operations in fund.go
  • Create test files to cover Solana-related functionality
  • Document Solana configuration and setup requirements
🔗 Analysis chain

Verify Solana integration requirements

The addition of github.com/gagliardetto/solana-go indicates new Solana blockchain support. Please ensure:

  1. All necessary Solana configurations are documented
  2. Error handling for Solana-specific operations is implemented
  3. Tests cover the new Solana functionality

Let me gather more information about the error handling and test coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for Solana-related configurations and tests
rg -g '!go.mod' -g '!go.sum' 'solana|SPL|SystemProgram|TokenProgram' .

Length of output: 1834


Script:

#!/bin/bash
# Check for Solana-related error handling
rg -g '!go.mod' -g '!go.sum' 'err.*solana|error.*solana' .

# Check for Solana-related tests
fd -e test.go -x rg -l 'solana|SPL|SystemProgram|TokenProgram' {}

Length of output: 208

github.com/gin-contrib/cors v1.7.2
github.com/gin-gonic/gin v1.10.0
github.com/logrusorgru/aurora v2.0.3+incompatible
Expand All @@ -19,10 +20,13 @@ require (
)

require (
filippo.io/edwards25519 v1.0.0-rc.1 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/StackExchange/wmi v1.2.1 // indirect
github.com/aead/siphash v1.0.1 // indirect
github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129 // indirect
github.com/bits-and-blooms/bitset v1.10.0 // indirect
github.com/blendle/zapdriver v1.3.1 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.3.3 // indirect
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f // indirect
Expand All @@ -38,6 +42,7 @@ require (
github.com/consensys/bavard v0.1.13 // indirect
github.com/consensys/gnark-crypto v0.12.1 // indirect
github.com/crate-crypto/go-kzg-4844 v1.0.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/deckarep/golang-set/v2 v2.6.0 // indirect
github.com/decred/dcrd/crypto/blake256 v1.0.1 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 // indirect
Expand All @@ -48,20 +53,23 @@ require (
github.com/fatih/color v1.16.0 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gagliardetto/binary v0.8.0 // indirect
github.com/gagliardetto/treeout v0.1.4 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/holiman/uint256 v1.2.4 // indirect
github.com/imdario/mergo v0.3.12 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/joho/godotenv v1.3.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/kkdai/bstream v1.0.0 // indirect
github.com/klauspost/compress v1.15.15 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/lightninglabs/neutrino/cache v1.1.2 // indirect
Expand All @@ -70,16 +78,20 @@ require (
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-shellwords v1.0.12 // indirect
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
github.com/mitchellh/mapstructure v1.4.1 // indirect
github.com/mmcloughlin/addchain v0.4.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mostynb/zstdpool-freelist v0.0.0-20201229113212-927304c0c3b1 // indirect
github.com/mr-tron/base58 v1.2.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/streamingfast/logging v0.0.0-20230608130331-f22c91403091 // indirect
github.com/supranational/blst v0.3.11 // indirect
github.com/tklauser/go-sysconf v0.3.12 // indirect
github.com/tklauser/numcpus v0.6.1 // indirect
Expand All @@ -88,14 +100,18 @@ require (
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
go.mongodb.org/mongo-driver v1.12.2 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/ratelimit v0.2.0 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/term v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
golang.org/x/time v0.5.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
Loading