github.com/MetalBlockchain/metalgo@v1.11.9/wallet/subnet/primary/examples/c-chain-import/main.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package main
     5  
     6  import (
     7  	"context"
     8  	"log"
     9  	"time"
    10  
    11  	"github.com/MetalBlockchain/coreth/plugin/evm"
    12  
    13  	"github.com/MetalBlockchain/metalgo/genesis"
    14  	"github.com/MetalBlockchain/metalgo/ids"
    15  	"github.com/MetalBlockchain/metalgo/utils/constants"
    16  	"github.com/MetalBlockchain/metalgo/utils/units"
    17  	"github.com/MetalBlockchain/metalgo/vms/components/avax"
    18  	"github.com/MetalBlockchain/metalgo/vms/secp256k1fx"
    19  	"github.com/MetalBlockchain/metalgo/wallet/subnet/primary"
    20  )
    21  
    22  func main() {
    23  	key := genesis.EWOQKey
    24  	uri := primary.LocalAPIURI
    25  	kc := secp256k1fx.NewKeychain(key)
    26  	avaxAddr := key.Address()
    27  	ethAddr := evm.PublicKeyToEthAddress(key.PublicKey())
    28  
    29  	ctx := context.Background()
    30  
    31  	// MakeWallet fetches the available UTXOs owned by [kc] on the network that
    32  	// [uri] is hosting.
    33  	walletSyncStartTime := time.Now()
    34  	wallet, err := primary.MakeWallet(ctx, &primary.WalletConfig{
    35  		URI:          uri,
    36  		AVAXKeychain: kc,
    37  		EthKeychain:  kc,
    38  	})
    39  	if err != nil {
    40  		log.Fatalf("failed to initialize wallet: %s\n", err)
    41  	}
    42  	log.Printf("synced wallet in %s\n", time.Since(walletSyncStartTime))
    43  
    44  	// Get the P-chain wallet
    45  	pWallet := wallet.P()
    46  	cWallet := wallet.C()
    47  
    48  	// Pull out useful constants to use when issuing transactions.
    49  	cContext := cWallet.Builder().Context()
    50  	cChainID := cContext.BlockchainID
    51  	avaxAssetID := cContext.AVAXAssetID
    52  	owner := secp256k1fx.OutputOwners{
    53  		Threshold: 1,
    54  		Addrs: []ids.ShortID{
    55  			avaxAddr,
    56  		},
    57  	}
    58  
    59  	exportStartTime := time.Now()
    60  	exportTx, err := pWallet.IssueExportTx(cChainID, []*avax.TransferableOutput{{
    61  		Asset: avax.Asset{ID: avaxAssetID},
    62  		Out: &secp256k1fx.TransferOutput{
    63  			Amt:          units.Avax,
    64  			OutputOwners: owner,
    65  		},
    66  	}})
    67  	if err != nil {
    68  		log.Fatalf("failed to issue export transaction: %s\n", err)
    69  	}
    70  	log.Printf("issued export %s in %s\n", exportTx.ID(), time.Since(exportStartTime))
    71  
    72  	importStartTime := time.Now()
    73  	importTx, err := cWallet.IssueImportTx(constants.PlatformChainID, ethAddr)
    74  	if err != nil {
    75  		log.Fatalf("failed to issue import transaction: %s\n", err)
    76  	}
    77  	log.Printf("issued import %s to %s in %s\n", importTx.ID(), ethAddr.Hex(), time.Since(importStartTime))
    78  }