-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathserialize-deserialize-5.js
78 lines (64 loc) · 2.37 KB
/
serialize-deserialize-5.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import {
AccountId,
TransferTransaction,
Hbar,
Client,
PrivateKey,
Logger,
LogLevel,
Timestamp,
Transaction,
TransactionId,
} from "@hashgraph/sdk";
import dotenv from "dotenv";
/**
* @description Serialize and deserialize so-called incomplete transaction, set transaction id and execute it
*/
async function main() {
// Ensure required environment variables are available
dotenv.config();
if (
!process.env.OPERATOR_KEY ||
!process.env.OPERATOR_ID ||
!process.env.ALICE_KEY ||
!process.env.ALICE_ID ||
!process.env.HEDERA_NETWORK
) {
throw new Error("Please set required keys in .env file.");
}
const network = process.env.HEDERA_NETWORK;
// Configure client using environment variables
const operatorId = AccountId.fromString(process.env.OPERATOR_ID);
const operatorKey = PrivateKey.fromStringED25519(process.env.OPERATOR_KEY);
const aliceId = AccountId.fromString(process.env.ALICE_ID);
const aliceKey = PrivateKey.fromStringED25519(process.env.ALICE_KEY);
const client = Client.forName(network).setOperator(operatorId, operatorKey);
// Set logger
const infoLogger = new Logger(LogLevel.Info);
client.setLogger(infoLogger);
try {
// 1. Create transaction
const transaction = new TransferTransaction()
.addHbarTransfer(operatorId, new Hbar(-1))
.addHbarTransfer(aliceId, new Hbar(1));
// 2. Serialize transaction into bytes
const transactionBytes = transaction.toBytes();
// 3. Deserialize transaction from bytes
let transactionFromBytes = Transaction.fromBytes(transactionBytes);
// 4. Set transaction id
const validStart = new Timestamp(Math.floor(Date.now() / 1000), 0);
const transactionId = new TransactionId(operatorId, validStart);
transactionFromBytes.setTransactionId(transactionId);
// 5. Freeze, sign and execute transaction
const executedTransaction = await (
await transactionFromBytes.freezeWith(client).sign(aliceKey)
).execute(client);
// 6. Get a receipt
const receipt = await executedTransaction.getReceipt(client);
console.log(`Transaction status: ${receipt.status.toString()}!`);
} catch (error) {
console.log(error);
}
client.close();
}
void main();