github.com/hashgraph/hedera-sdk-go/v2@v2.48.0/examples/serialize-deserialize/example2/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/hashgraph/hedera-sdk-go/v2"
     6  	"os"
     7  )
     8  
     9  func main() {
    10  	var client *hedera.Client
    11  	var err error
    12  
    13  	// Retrieving network type from environment variable HEDERA_NETWORK
    14  	client, err = hedera.ClientForName(os.Getenv("HEDERA_NETWORK"))
    15  	if err != nil {
    16  		panic(fmt.Sprintf("%v : error creating client", err))
    17  	}
    18  
    19  	// Retrieving operator ID from environment variable OPERATOR_ID
    20  	operatorAccountID, err := hedera.AccountIDFromString(os.Getenv("OPERATOR_ID"))
    21  	if err != nil {
    22  		panic(fmt.Sprintf("%v : error converting string to AccountID", err))
    23  	}
    24  
    25  	// Retrieving operator key from environment variable OPERATOR_KEY
    26  	operatorKey, err := hedera.PrivateKeyFromString(os.Getenv("OPERATOR_KEY"))
    27  	if err != nil {
    28  		panic(fmt.Sprintf("%v : error converting string to PrivateKey", err))
    29  	}
    30  
    31  	// Setting the client operator ID and key
    32  	client.SetOperator(operatorAccountID, operatorKey)
    33  
    34  	// Generate new key to use with new account
    35  	newKey, err := hedera.GeneratePrivateKey()
    36  	if err != nil {
    37  		panic(err)
    38  	}
    39  	resp, err := hedera.NewAccountCreateTransaction().SetKey(newKey).Execute(client)
    40  	receipt, err := resp.GetReceipt(client)
    41  	newAccountId := *receipt.AccountID
    42  
    43  	// Prepare and sign the tx and send it to be signed by another actor
    44  	fmt.Println("Creating a transfer transaction, signing it with operator and serializing it to bytes...")
    45  	bytes, err := hedera.NewTransferTransaction().AddHbarTransfer(operatorAccountID, hedera.NewHbar(1)).AddHbarTransfer(newAccountId, hedera.NewHbar(-1)).
    46  		Sign(operatorKey).ToBytes()
    47  
    48  	FromBytes, err := hedera.TransactionFromBytes(bytes)
    49  	if err != nil {
    50  		panic(err)
    51  	}
    52  	txFromBytes := FromBytes.(hedera.TransferTransaction)
    53  	// New Account add his sign and execute the tx:
    54  	fmt.Println("Signing deserialized transaction with `newAccount` private key and executing it...")
    55  	executed, err := txFromBytes.Sign(newKey).SetMaxTransactionFee(hedera.NewHbar(2)).Execute(client)
    56  	if err != nil {
    57  		panic(err)
    58  	}
    59  	receipt, err = executed.GetReceipt(client)
    60  	if err != nil {
    61  		panic(err)
    62  	}
    63  	fmt.Println("Tx successfully executed. Here is receipt:", receipt)
    64  }