forked from hashgraph/hedera-sdk-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialize-deserialize-2.js
73 lines (59 loc) · 2.13 KB
/
serialize-deserialize-2.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
import {
AccountId,
TransferTransaction,
Hbar,
Client,
PrivateKey,
Logger,
LogLevel,
Transaction,
} from "@hashgraph/sdk";
import dotenv from "dotenv";
/**
* @description Serialize and deserialize the so-called signed transaction after being signed, 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 and freeze it
let transaction = new TransferTransaction()
.addHbarTransfer(operatorId, new Hbar(-1))
.addHbarTransfer(aliceId, new Hbar(1))
.freezeWith(client);
// 2. Sign transaction
await transaction.sign(aliceKey);
// 3. Serialize transaction into bytes
const transactionBytes = transaction.toBytes();
// 4. Deserialize transaction from bytes
const transactionFromBytes = Transaction.fromBytes(transactionBytes);
// 5. Execute transaction
const executedTransaction = await transactionFromBytes.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();