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: support WeaveVM #1287

Merged
merged 4 commits into from
Mar 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions cmd/consts/da.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const (
Local DAType = "mock"
Celestia DAType = "celestia"
Avail DAType = "avail"
WeaveVM DAType = "weavevm"
)

type DaNetwork string
Expand All @@ -34,6 +35,8 @@ const (
CelestiaMainnet DaNetwork = "celestia"
AvailTestnet DaNetwork = "avail"
AvailMainnet DaNetwork = "avail-1" // change this with correct mainnet id
WeaveVMTestnet DaNetwork = "alphanet"
WeaveVMMainnet DaNetwork = "weavevm" // change this with correct mainnet id
)

var DaNetworks = map[string]DaData{
Expand Down Expand Up @@ -93,4 +96,22 @@ var DaNetworks = map[string]DaData{
StateNodes: []string{},
GasPrice: "",
},
string(WeaveVMTestnet): {
Backend: WeaveVM,
ApiUrl: "https://testnet-rpc.wvm.dev",
ID: WeaveVMTestnet,
RpcUrl: "wss://testnet-rpc.wvm.dev/ws",
CurrentStateNode: "",
StateNodes: []string{},
GasPrice: "",
},
string(WeaveVMMainnet): {
Backend: WeaveVM,
ApiUrl: "",
ID: WeaveVMMainnet,
RpcUrl: "",
CurrentStateNode: "",
StateNodes: []string{},
GasPrice: "",
},
}
17 changes: 17 additions & 0 deletions cmd/rollapp/init/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,23 @@ func runInit(
return fmt.Errorf("failed to get Avail account address: %w", err)
}

// Append DA account address if available
if daAddress != nil {
addresses = append(addresses, keys.KeyInfo{
Name: damanager.GetKeyName(),
Address: daAddress.Address,
})
}
case consts.WeaveVM:
// Initialize DAManager for WeaveVM
damanager := datalayer.NewDAManager(consts.WeaveVM, home, kb)

// Retrieve DA account address
daAddress, err := damanager.GetDAAccountAddress()
if err != nil {
return fmt.Errorf("failed to get WeaveVM account address: %w", err)
}

// Append DA account address if available
if daAddress != nil {
addresses = append(addresses, keys.KeyInfo{
Expand Down
9 changes: 9 additions & 0 deletions data_layer/da_layer.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/dymensionxyz/roller/data_layer/avail"
"github.com/dymensionxyz/roller/data_layer/celestia"
"github.com/dymensionxyz/roller/data_layer/damock"
"github.com/dymensionxyz/roller/data_layer/weavevm"
"github.com/dymensionxyz/roller/utils/keys"
"github.com/dymensionxyz/roller/utils/roller"
)
Expand Down Expand Up @@ -45,6 +46,8 @@ func NewDAManager(datype consts.DAType, home string, kb consts.SupportedKeyringB
dalayer = celestia.NewCelestia(home, kb)
case consts.Avail:
dalayer = avail.NewAvail(home)
case consts.WeaveVM:
dalayer = weavevm.NewWeaveVM(home)
case consts.Local:
dalayer = &damock.DAMock{}
default:
Expand All @@ -67,6 +70,8 @@ func GetDaInfo(env, daBackend string) (*consts.DaData, error) {
daNetwork = string(consts.CelestiaTestnet)
case string(consts.Avail):
daNetwork = string(consts.AvailTestnet)
case string(consts.WeaveVM):
daNetwork = string(consts.WeaveVMTestnet)
default:
return nil, fmt.Errorf("unsupported DA backend: %s", daBackend)
}
Expand All @@ -76,6 +81,8 @@ func GetDaInfo(env, daBackend string) (*consts.DaData, error) {
daNetwork = string(consts.CelestiaMainnet)
case string(consts.Avail):
daNetwork = string(consts.AvailMainnet)
case string(consts.WeaveVM):
daNetwork = string(consts.WeaveVMMainnet)
default:
return nil, fmt.Errorf("unsupported DA backend: %s", daBackend)
}
Expand All @@ -85,6 +92,8 @@ func GetDaInfo(env, daBackend string) (*consts.DaData, error) {
daNetwork = string(consts.CelestiaTestnet)
case string(consts.Avail):
daNetwork = string(consts.AvailTestnet)
case string(consts.WeaveVM):
daNetwork = string(consts.WeaveVMTestnet)
default:
return nil, fmt.Errorf("unsupported DA backend: %s", daBackend)
}
Expand Down
47 changes: 47 additions & 0 deletions data_layer/weavevm/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package weavevm

import (
"os"
"path/filepath"

"github.com/pelletier/go-toml"

"github.com/dymensionxyz/roller/cmd/consts"
)

func writeConfigToTOML(path string, w WeaveVM) error {
tomlBytes, err := toml.Marshal(w)
if err != nil {
return err
}
dir := filepath.Dir(path)
// nolint:gofumpt
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
// nolint:gofumpt
err = os.WriteFile(path, tomlBytes, 0o644)
if err != nil {
return err
}

return nil
}

func loadConfigFromTOML(path string) (WeaveVM, error) {
var config WeaveVM
tomlBytes, err := os.ReadFile(path)
if err != nil {
return config, err
}
err = toml.Unmarshal(tomlBytes, &config)
if err != nil {
return config, err
}

return config, nil
}

func GetCfgFilePath(rollerHome string) string {
return filepath.Join(rollerHome, consts.ConfigDirName.DALightNode, ConfigFileName)
}
239 changes: 239 additions & 0 deletions data_layer/weavevm/weavevm.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
package weavevm

import (
"bytes"
"crypto/ecdsa"
"encoding/json"
"fmt"
"io"
"math/big"
"net/http"
"os/exec"

"github.com/dymensionxyz/roller/cmd/consts"
"github.com/dymensionxyz/roller/utils/errorhandling"
"github.com/dymensionxyz/roller/utils/keys"
"github.com/dymensionxyz/roller/utils/roller"
"github.com/pterm/pterm"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)

const (
ConfigFileName = "weavevm.toml"
mnemonicEntropySize = 256
keyringNetworkID uint16 = 42
requiredAVL = 1
DefaultTestnetChainID = 9496
)

type RequestPayload struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params []interface{} `json:"params"`
ID int `json:"id"`
}

type EthBalanceResponse struct {
ID int `json:"id"`
JsonRPC string `json:"jsonrpc"`
Result string `json:"result"`
}

type WeaveVM struct {
Root string
PrivateKey string
RpcEndpoint string
ChainID uint32
}

func (w *WeaveVM) GetPrivateKey() (string, error) {
return w.PrivateKey, nil
}

func (w *WeaveVM) SetMetricsEndpoint(endpoint string) {
}

func NewWeaveVM(root string) *WeaveVM {
var daNetwork string

rollerData, err := roller.LoadConfig(root)
errorhandling.PrettifyErrorIfExists(err)

cfgPath := GetCfgFilePath(root)
weavevmConfig, err := loadConfigFromTOML(cfgPath)
if err != nil {
if rollerData.HubData.Environment == "mainnet" {
daNetwork = string(consts.WeaveVMMainnet)
} else {
daNetwork = string(consts.WeaveVMTestnet)
}

weavevmConfig.PrivateKey, _ = pterm.DefaultInteractiveTextInput.WithDefaultText(
"> Enter your PrivateKey without 0x",
).Show()

proceed, _ := pterm.DefaultInteractiveConfirm.WithDefaultValue(false).
WithDefaultText(
"press 'y' when the wallet are funded",
).Show()

Copy link
Collaborator

Choose a reason for hiding this comment

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

needs to have retry with balance check

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Do u have any idea for it? Im feeling a bit stuck

Copy link
Collaborator

Choose a reason for hiding this comment

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

something similar that we already have for balance checks:

https://github.com/dymensionxyz/roller/blob/main/cmd/eibc/init/init.go#L161-L189

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I mean how to query balance of weavevm?

if !proceed {
panic(fmt.Errorf("WeaveVM wallet need to be fund!"))
}

daData, exists := consts.DaNetworks[daNetwork]
if !exists {
panic(fmt.Errorf("DA network configuration not found for: %s", daNetwork))
}

balance, err := GetBalance(daData.ApiUrl, weavevmConfig.PrivateKey)
if err != nil {
panic(err)
}
if balance == "" {
panic(fmt.Errorf("WeaveVM wallet need to be fund!"))
}

pterm.Println("WeaveVM Balance: ", balance)

weavevmConfig.RpcEndpoint = daData.ApiUrl
weavevmConfig.Root = root
weavevmConfig.ChainID = DefaultTestnetChainID

err = writeConfigToTOML(cfgPath, weavevmConfig)
if err != nil {
panic(err)
}
}
return &weavevmConfig
}

func (w *WeaveVM) InitializeLightNodeConfig() (string, error) {
return "", nil
}

func (w *WeaveVM) GetDAAccountAddress() (*keys.KeyInfo, error) {
return nil, nil
}

func (w *WeaveVM) GetRootDirectory() string {
return w.Root
}

func (w *WeaveVM) CheckDABalance() ([]keys.NotFundedAddressData, error) {
return nil, nil
}

func (w *WeaveVM) GetStartDACmd() *exec.Cmd {
return nil
}

func (w *WeaveVM) GetDAAccData(cfg roller.RollappConfig) ([]keys.AccountData, error) {
return nil, nil
}

func (w *WeaveVM) GetSequencerDAConfig(_ string) string {
return fmt.Sprintf(
`{"endpoint": "%s", "chain_id": %d,"private_key_hex": %s}`,
w.RpcEndpoint,
w.ChainID,
w.PrivateKey,
)
}

func (w *WeaveVM) SetRPCEndpoint(rpc string) {
w.RpcEndpoint = rpc
}

func (w *WeaveVM) GetLightNodeEndpoint() string {
return ""
}

func (w *WeaveVM) GetNetworkName() string {
return "weavevm"
}

func (w *WeaveVM) GetStatus(c roller.RollappConfig) string {
return "Active"
}

func (w *WeaveVM) GetKeyName() string {
return "weavevm"
}

func (w *WeaveVM) GetNamespaceID() string {
return ""
}

func (w *WeaveVM) GetAppID() uint32 {
return 0
}

func getAddressFromPrivateKey(privKey string) (common.Address, *ecdsa.PrivateKey, error) {
// Getting public address from private key
pKeyBytes, err := hexutil.Decode("0x" + privKey)
if err != nil {
return common.Address{}, nil, err
}
// Convert the private key bytes to an ECDSA private key.
ecdsaPrivateKey, err := crypto.ToECDSA(pKeyBytes)
if err != nil {
return common.Address{}, nil, err
}
// Extract the public key from the ECDSA private key.
publicKey := ecdsaPrivateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
return common.Address{}, nil, fmt.Errorf("error casting public key to ECDSA")
}

// Compute the Ethereum address of the signer from the public key.
fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)
return fromAddress, ecdsaPrivateKey, nil
}

func GetBalance(jsonRPCURL, key string) (string, error) {
address, _, err := getAddressFromPrivateKey(key)
if err != nil {
return "", err
}
payload := RequestPayload{
JSONRPC: "2.0",
Method: "eth_getBalance",
Params: []interface{}{address, "latest"},
ID: 1,
}

jsonData, err := json.Marshal(payload)
if err != nil {
return "", err
}

resp, err := http.Post(jsonRPCURL, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
return "", err
}
defer resp.Body.Close()

Check failure on line 219 in data_layer/weavevm/weavevm.go

View workflow job for this annotation

GitHub Actions / lint

Error return value of `resp.Body.Close` is not checked (errcheck)

var response EthBalanceResponse

body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}

err = json.Unmarshal(body, &response)
if err != nil {
return "", err
}

balance := new(big.Int)
balance.SetString(response.Result[2:], 16)

ethBalance := new(big.Float).Quo(new(big.Float).SetInt(balance), big.NewFloat(1e18))

return ethBalance.Text('f', 6), nil
}
Loading