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

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/hashgraph/hedera-sdk-go/v2"
     8  )
     9  
    10  func main() {
    11  	var client *hedera.Client
    12  	var err error
    13  
    14  	// Retrieving network type from environment variable HEDERA_NETWORK
    15  	client, err = hedera.ClientForName(os.Getenv("HEDERA_NETWORK"))
    16  	if err != nil {
    17  		panic(fmt.Sprintf("%v : error creating client", err))
    18  	}
    19  
    20  	// Retrieving operator ID from environment variable OPERATOR_ID
    21  	operatorAccountID, err := hedera.AccountIDFromString(os.Getenv("OPERATOR_ID"))
    22  	if err != nil {
    23  		panic(fmt.Sprintf("%v : error converting string to AccountID", err))
    24  	}
    25  
    26  	// Retrieving operator key from environment variable OPERATOR_KEY
    27  	operatorKey, err := hedera.PrivateKeyFromString(os.Getenv("OPERATOR_KEY"))
    28  	if err != nil {
    29  		panic(fmt.Sprintf("%v : error converting string to PrivateKey", err))
    30  	}
    31  
    32  	// Setting the client operator ID and key
    33  	client.SetOperator(operatorAccountID, operatorKey)
    34  
    35  	aliceKey, err := hedera.PrivateKeyGenerateEd25519()
    36  	if err != nil {
    37  		panic(fmt.Sprintf("%v : error generating PrivateKey", err))
    38  	}
    39  	bobKey, err := hedera.PrivateKeyGenerateEd25519()
    40  	if err != nil {
    41  		panic(fmt.Sprintf("%v : error generating PrivateKey", err))
    42  	}
    43  
    44  	charlieKey, err := hedera.PrivateKeyGenerateEd25519()
    45  	if err != nil {
    46  		panic(fmt.Sprintf("%v : error generating PrivateKey", err))
    47  	}
    48  
    49  	transactionResponse, err := hedera.NewAccountCreateTransaction().
    50  		SetKey(aliceKey.PublicKey()).
    51  		SetInitialBalance(hedera.NewHbar(5)).
    52  		Execute(client)
    53  
    54  	if err != nil {
    55  		panic(fmt.Sprintf("%v : error creating account", err))
    56  	}
    57  
    58  	transactionReceipt, err := transactionResponse.GetReceipt(client)
    59  	if err != nil {
    60  		panic(fmt.Sprintf("%v : error retrieving account creation receipt", err))
    61  	}
    62  
    63  	aliceID := *transactionReceipt.AccountID
    64  
    65  	transactionResponse, err = hedera.NewAccountCreateTransaction().
    66  		SetNodeAccountIDs([]hedera.AccountID{transactionResponse.NodeID}).
    67  		SetKey(bobKey.PublicKey()).
    68  		SetInitialBalance(hedera.NewHbar(5)).
    69  		Execute(client)
    70  	if err != nil {
    71  		panic(fmt.Sprintf("%v : error creating second account", err))
    72  	}
    73  
    74  	transactionReceipt, err = transactionResponse.GetReceipt(client)
    75  	if err != nil {
    76  		panic(fmt.Sprintf("%v : error retrieving second account creation receipt", err))
    77  	}
    78  
    79  	bobID := *transactionReceipt.AccountID
    80  
    81  	transactionResponse, err = hedera.NewAccountCreateTransaction().
    82  		SetNodeAccountIDs([]hedera.AccountID{transactionResponse.NodeID}).
    83  		SetKey(charlieKey.PublicKey()).
    84  		SetInitialBalance(hedera.NewHbar(5)).
    85  		Execute(client)
    86  	if err != nil {
    87  		panic(fmt.Sprintf("%v : error creating second account", err))
    88  	}
    89  
    90  	transactionReceipt, err = transactionResponse.GetReceipt(client)
    91  	if err != nil {
    92  		panic(fmt.Sprintf("%v : error retrieving second account creation receipt", err))
    93  	}
    94  
    95  	charlieID := *transactionReceipt.AccountID
    96  
    97  	println("Alice's ID:", aliceID.String())
    98  	println("Bob's ID:", bobID.String())
    99  	println("Charlie's ID:", charlieID.String())
   100  	println("Initial Balance:")
   101  	err = printBalance(client, aliceID, bobID, charlieID, []hedera.AccountID{transactionResponse.NodeID})
   102  	if err != nil {
   103  		panic(fmt.Sprintf("%v : error retrieving balances", err))
   104  	}
   105  
   106  	println("Approve an allowance of 2 Hbar with owner Alice and spender Bob")
   107  
   108  	approvalFreeze, err := hedera.NewAccountAllowanceApproveTransaction().
   109  		SetNodeAccountIDs([]hedera.AccountID{transactionResponse.NodeID}).
   110  		ApproveHbarAllowance(aliceID, bobID, hedera.NewHbar(2)).
   111  		FreezeWith(client)
   112  	if err != nil {
   113  		panic(fmt.Sprintf("%v : error freezing account allowance approve transaction", err))
   114  	}
   115  
   116  	approvalFreeze.Sign(aliceKey)
   117  
   118  	transactionResponse, err = approvalFreeze.Execute(client)
   119  	if err != nil {
   120  		panic(fmt.Sprintf("%v : error executing account allowance approve transaction", err))
   121  	}
   122  
   123  	transactionReceipt, err = transactionResponse.GetReceipt(client)
   124  	if err != nil {
   125  		panic(fmt.Sprintf("%v : error getting account allowance receipt", err))
   126  	}
   127  
   128  	err = printBalance(client, aliceID, bobID, charlieID, []hedera.AccountID{transactionResponse.NodeID})
   129  	if err != nil {
   130  		panic(fmt.Sprintf("%v : error retrieving balances", err))
   131  	}
   132  
   133  	println("Transferring 1 Hbar from Alice to Charlie, but the transaction is signed _only_ by Bob (Bob is dipping into his allowance from Alice)")
   134  
   135  	transferFreeze, err := hedera.NewTransferTransaction().
   136  		AddApprovedHbarTransfer(aliceID, hedera.NewHbar(1).Negated(), true).
   137  		AddHbarTransfer(charlieID, hedera.NewHbar(1)).
   138  		SetNodeAccountIDs([]hedera.AccountID{transactionResponse.NodeID}).
   139  		SetTransactionID(hedera.TransactionIDGenerate(bobID)).
   140  		FreezeWith(client)
   141  	if err != nil {
   142  		panic(fmt.Sprintf("%v : error freezing transfer transaction", err))
   143  	}
   144  
   145  	transferFreeze.Sign(bobKey)
   146  
   147  	transactionResponse, err = transferFreeze.Execute(client)
   148  	if err != nil {
   149  		panic(fmt.Sprintf("%v : error executing transfer transaction", err))
   150  	}
   151  
   152  	transactionReceipt, err = transactionResponse.GetReceipt(client)
   153  	if err != nil {
   154  		panic(fmt.Sprintf("%v : error retrieving transfer transaction receipt", err))
   155  	}
   156  
   157  	println("Transfer succeeded. Bob should now have 1 Hbar left in his allowance.")
   158  	err = printBalance(client, aliceID, bobID, charlieID, []hedera.AccountID{transactionResponse.NodeID})
   159  	if err != nil {
   160  		panic(fmt.Sprintf("%v : error retrieving balances", err))
   161  	}
   162  
   163  	println("Attempting to transfer 2 Hbar from Alice to Charlie using Bob's allowance.")
   164  	println("This should fail, because there is only 1 Hbar left in Bob's allowance.")
   165  
   166  	transferFreeze, err = hedera.NewTransferTransaction().
   167  		AddApprovedHbarTransfer(aliceID, hedera.NewHbar(2).Negated(), true).
   168  		AddHbarTransfer(charlieID, hedera.NewHbar(2)).
   169  		SetNodeAccountIDs([]hedera.AccountID{transactionResponse.NodeID}).
   170  		SetTransactionID(hedera.TransactionIDGenerate(bobID)).
   171  		FreezeWith(client)
   172  	if err != nil {
   173  		panic(fmt.Sprintf("%v : error freezing transfer transaction", err))
   174  	}
   175  
   176  	transferFreeze.Sign(bobKey)
   177  
   178  	transactionResponse, err = transferFreeze.Execute(client)
   179  	if err != nil {
   180  		panic(fmt.Sprintf("%v : error executing transfer transaction", err))
   181  	}
   182  
   183  	transactionReceipt, err = transactionResponse.GetReceipt(client)
   184  	if err != nil {
   185  		println(err.Error(), ", Transfer failed as expected")
   186  	}
   187  
   188  	println("Adjusting Bob's allowance, increasing it by 2 Hbar. After this, Bob's allowance should be 3 Hbar.")
   189  
   190  	allowanceAdjust, err := hedera.NewAccountAllowanceApproveTransaction().
   191  		SetNodeAccountIDs([]hedera.AccountID{transactionResponse.NodeID}).
   192  		ApproveHbarAllowance(aliceID, bobID, hedera.NewHbar(2)).
   193  		FreezeWith(client)
   194  	if err != nil {
   195  		panic(fmt.Sprintf("%v : error freezing account allowance adjust transaction", err))
   196  	}
   197  
   198  	allowanceAdjust.Sign(aliceKey)
   199  
   200  	transactionResponse, err = allowanceAdjust.Execute(client)
   201  	if err != nil {
   202  		panic(fmt.Sprintf("%v : error executing account allowance adjust transaction", err))
   203  	}
   204  
   205  	transactionReceipt, err = transactionResponse.GetReceipt(client)
   206  	if err != nil {
   207  		panic(fmt.Sprintf("%v : error retrieving account allowance adjust receipt", err))
   208  	}
   209  
   210  	err = printBalance(client, aliceID, bobID, charlieID, []hedera.AccountID{transactionResponse.NodeID})
   211  	if err != nil {
   212  		panic(fmt.Sprintf("%v : error retrieving balances", err))
   213  	}
   214  
   215  	println("Attempting to transfer 2 Hbar from Alice to Charlie using Bob's allowance again.")
   216  	println("This time it should succeed.")
   217  
   218  	transferFreeze, err = hedera.NewTransferTransaction().
   219  		AddApprovedHbarTransfer(aliceID, hedera.NewHbar(2).Negated(), true).
   220  		AddHbarTransfer(charlieID, hedera.NewHbar(2)).
   221  		SetNodeAccountIDs([]hedera.AccountID{transactionResponse.NodeID}).
   222  		SetTransactionID(hedera.TransactionIDGenerate(bobID)).
   223  		FreezeWith(client)
   224  	if err != nil {
   225  		panic(fmt.Sprintf("%v : error freezing transfer transaction", err))
   226  	}
   227  
   228  	transferFreeze.Sign(bobKey)
   229  
   230  	transactionResponse, err = transferFreeze.Execute(client)
   231  	if err != nil {
   232  		panic(fmt.Sprintf("%v : error executing transfer transaction", err))
   233  	}
   234  
   235  	transactionReceipt, err = transactionResponse.GetReceipt(client)
   236  	if err != nil {
   237  		panic(fmt.Sprintf("%v : error retrieving transfer transaction receipt", err))
   238  	}
   239  
   240  	println("Transfer succeeded.")
   241  	err = printBalance(client, aliceID, bobID, charlieID, []hedera.AccountID{transactionResponse.NodeID})
   242  	if err != nil {
   243  		panic(fmt.Sprintf("%v : error retrieving balances", err))
   244  	}
   245  
   246  	println("Deleting Bob's allowance")
   247  
   248  	approvalFreeze, err = hedera.NewAccountAllowanceApproveTransaction().
   249  		SetNodeAccountIDs([]hedera.AccountID{transactionResponse.NodeID}).
   250  		ApproveHbarAllowance(aliceID, bobID, hedera.ZeroHbar).
   251  		FreezeWith(client)
   252  	if err != nil {
   253  		panic(fmt.Sprintf("%v : error freezing account allowance approve transaction", err))
   254  	}
   255  
   256  	approvalFreeze.Sign(aliceKey)
   257  
   258  	transactionResponse, err = approvalFreeze.Execute(client)
   259  	if err != nil {
   260  		panic(fmt.Sprintf("%v : error executing account allowance approve transaction", err))
   261  	}
   262  
   263  	_, err = transactionResponse.GetReceipt(client)
   264  	if err != nil {
   265  		panic(fmt.Sprintf("%v : error getting account allowance receipt", err))
   266  	}
   267  
   268  	println("If Bob tries to use his allowance it should fail.")
   269  
   270  	transferFreeze, err = hedera.NewTransferTransaction().
   271  		AddApprovedHbarTransfer(aliceID, hedera.NewHbar(1).Negated(), true).
   272  		AddHbarTransfer(charlieID, hedera.NewHbar(1)).
   273  		SetNodeAccountIDs([]hedera.AccountID{transactionResponse.NodeID}).
   274  		SetTransactionID(hedera.TransactionIDGenerate(bobID)).
   275  		FreezeWith(client)
   276  	if err != nil {
   277  		panic(fmt.Sprintf("%v : error freezing transfer transaction", err))
   278  	}
   279  
   280  	transferFreeze.Sign(bobKey)
   281  
   282  	transactionResponse, err = transferFreeze.Execute(client)
   283  	if err != nil {
   284  		panic(fmt.Sprintf("%v : error executing transfer transaction", err))
   285  	}
   286  
   287  	transactionReceipt, err = transactionResponse.GetReceipt(client)
   288  	if err != nil {
   289  		println(err.Error(), ": Error just like expected")
   290  	}
   291  
   292  	println("\nCleaning up")
   293  
   294  	accountDelete, err := hedera.NewAccountDeleteTransaction().
   295  		SetAccountID(aliceID).
   296  		SetNodeAccountIDs([]hedera.AccountID{transactionResponse.NodeID}).
   297  		SetTransferAccountID(client.GetOperatorAccountID()).
   298  		FreezeWith(client)
   299  	if err != nil {
   300  		panic(fmt.Sprintf("%v : error freezing alice's account deletion", err))
   301  	}
   302  
   303  	accountDelete.Sign(aliceKey)
   304  
   305  	transactionResponse, err = accountDelete.Execute(client)
   306  	if err != nil {
   307  		panic(fmt.Sprintf("%v : error executing alice's account deletion", err))
   308  	}
   309  
   310  	_, err = transactionResponse.GetReceipt(client)
   311  	if err != nil {
   312  		panic(fmt.Sprintf("%v : error retrieving alice's account deletion receipt", err))
   313  	}
   314  
   315  	accountDelete, err = hedera.NewAccountDeleteTransaction().
   316  		SetAccountID(bobID).
   317  		SetNodeAccountIDs([]hedera.AccountID{transactionResponse.NodeID}).
   318  		SetTransferAccountID(client.GetOperatorAccountID()).
   319  		FreezeWith(client)
   320  	if err != nil {
   321  		panic(fmt.Sprintf("%v : error freezing bob's account deletion", err))
   322  	}
   323  
   324  	accountDelete.Sign(bobKey)
   325  
   326  	transactionResponse, err = accountDelete.Execute(client)
   327  	if err != nil {
   328  		panic(fmt.Sprintf("%v : error executing bob's account deletion", err))
   329  	}
   330  
   331  	_, err = transactionResponse.GetReceipt(client)
   332  	if err != nil {
   333  		panic(fmt.Sprintf("%v : error retrieving bob's account deletion receipt", err))
   334  	}
   335  
   336  	accountDelete, err = hedera.NewAccountDeleteTransaction().
   337  		SetAccountID(charlieID).
   338  		SetNodeAccountIDs([]hedera.AccountID{transactionResponse.NodeID}).
   339  		SetTransferAccountID(client.GetOperatorAccountID()).
   340  		FreezeWith(client)
   341  	if err != nil {
   342  		panic(fmt.Sprintf("%v : error freezing charlie's account deletion", err))
   343  	}
   344  
   345  	accountDelete.Sign(charlieKey)
   346  
   347  	transactionResponse, err = accountDelete.Execute(client)
   348  	if err != nil {
   349  		panic(fmt.Sprintf("%v : error executing charlie's account deletion", err))
   350  	}
   351  
   352  	_, err = transactionResponse.GetReceipt(client)
   353  	if err != nil {
   354  		panic(fmt.Sprintf("%v : error retrieving charlie's account deletion receipt", err))
   355  	}
   356  
   357  	err = client.Close()
   358  	if err != nil {
   359  		panic(fmt.Sprintf("%v : error closing client", err))
   360  	}
   361  }
   362  
   363  func printBalance(client *hedera.Client, alice hedera.AccountID, bob hedera.AccountID, charlie hedera.AccountID, nodeID []hedera.AccountID) error {
   364  	println()
   365  
   366  	balance, err := hedera.NewAccountBalanceQuery().
   367  		SetAccountID(alice).
   368  		SetNodeAccountIDs(nodeID).
   369  		Execute(client)
   370  	if err != nil {
   371  		return err
   372  	}
   373  	println("Alice's balance:", balance.Hbars.String())
   374  
   375  	balance, err = hedera.NewAccountBalanceQuery().
   376  		SetAccountID(bob).
   377  		SetNodeAccountIDs(nodeID).
   378  		Execute(client)
   379  	if err != nil {
   380  		return err
   381  	}
   382  	println("Bob's balance:", balance.Hbars.String())
   383  
   384  	balance, err = hedera.NewAccountBalanceQuery().
   385  		SetAccountID(charlie).
   386  		SetNodeAccountIDs(nodeID).
   387  		Execute(client)
   388  	if err != nil {
   389  		return err
   390  	}
   391  	println("Charlie's balance:", balance.Hbars.String())
   392  
   393  	println()
   394  	return nil
   395  }