github.com/MetalBlockchain/metalgo@v1.11.9/vms/example/xsvm/cmd/chain/create/cmd.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package create
     5  
     6  import (
     7  	"log"
     8  	"time"
     9  
    10  	"github.com/spf13/cobra"
    11  
    12  	"github.com/MetalBlockchain/metalgo/utils/constants"
    13  	"github.com/MetalBlockchain/metalgo/utils/set"
    14  	"github.com/MetalBlockchain/metalgo/vms/example/xsvm/genesis"
    15  	"github.com/MetalBlockchain/metalgo/vms/secp256k1fx"
    16  	"github.com/MetalBlockchain/metalgo/wallet/subnet/primary"
    17  	"github.com/MetalBlockchain/metalgo/wallet/subnet/primary/common"
    18  )
    19  
    20  func Command() *cobra.Command {
    21  	c := &cobra.Command{
    22  		Use:   "create",
    23  		Short: "Creates a new chain",
    24  		RunE:  createFunc,
    25  	}
    26  	flags := c.Flags()
    27  	AddFlags(flags)
    28  	return c
    29  }
    30  
    31  func createFunc(c *cobra.Command, args []string) error {
    32  	flags := c.Flags()
    33  	config, err := ParseFlags(flags, args)
    34  	if err != nil {
    35  		return err
    36  	}
    37  
    38  	ctx := c.Context()
    39  	kc := secp256k1fx.NewKeychain(config.PrivateKey)
    40  
    41  	// NewWalletFromURI fetches the available UTXOs owned by [kc] on the network
    42  	// that [uri] is hosting.
    43  	walletSyncStartTime := time.Now()
    44  	wallet, err := primary.MakeWallet(ctx, &primary.WalletConfig{
    45  		URI:              config.URI,
    46  		AVAXKeychain:     kc,
    47  		EthKeychain:      kc,
    48  		PChainTxsToFetch: set.Of(config.SubnetID),
    49  	})
    50  	if err != nil {
    51  		return err
    52  	}
    53  	log.Printf("synced wallet in %s\n", time.Since(walletSyncStartTime))
    54  
    55  	// Get the P-chain wallet
    56  	pWallet := wallet.P()
    57  
    58  	genesisBytes, err := genesis.Codec.Marshal(genesis.CodecVersion, &genesis.Genesis{
    59  		Timestamp: 0,
    60  		Allocations: []genesis.Allocation{
    61  			{
    62  				Address: config.Address,
    63  				Balance: config.Balance,
    64  			},
    65  		},
    66  	})
    67  	if err != nil {
    68  		return err
    69  	}
    70  
    71  	createChainStartTime := time.Now()
    72  	createChainTxID, err := pWallet.IssueCreateChainTx(
    73  		config.SubnetID,
    74  		genesisBytes,
    75  		constants.XSVMID,
    76  		nil,
    77  		config.Name,
    78  		common.WithContext(ctx),
    79  	)
    80  	if err != nil {
    81  		return err
    82  	}
    83  	log.Printf("created chain %s in %s\n", createChainTxID, time.Since(createChainStartTime))
    84  	return nil
    85  }