From 262db757e8cf597ccf8ae8e7962cf0bb90f761f3 Mon Sep 17 00:00:00 2001 From: b-l-u-e Date: Mon, 14 Oct 2024 15:37:09 +0300 Subject: [PATCH 1/8] Add get-file-contents.js Signed-off-by: b-l-u-e --- examples/get-file-contents.js | 112 ++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 examples/get-file-contents.js diff --git a/examples/get-file-contents.js b/examples/get-file-contents.js new file mode 100644 index 000000000..8999c0474 --- /dev/null +++ b/examples/get-file-contents.js @@ -0,0 +1,112 @@ +import { + PrivateKey, + FileContentsQuery, + Hbar, + FileCreateTransaction, + FileDeleteTransaction, + Client, + AccountId, +} from "@hashgraph/sdk"; +import dotenv from "dotenv"; + +dotenv.config(); + +/** + * How to get file contents + * + */ + +async function main() { + /** + * Step 0: + * Create and configure the SDK Client + */ + if ( + process.env.OPERATOR_ID == null || + process.env.OPERATOR_KEY == null || + process.env.HEDERA_NETWORK == null + ) { + throw new Error( + "Environment variables OPERATOR_ID, HEDERA_NETWORK, and OPERATOR_KEY are required.", + ); + } + + const operatorId = AccountId.fromString(process.env.OPERATOR_ID); + const operatorKey = PrivateKey.fromStringED25519(process.env.OPERATOR_KEY); + + // Create a client for the local Hedera network + const client = Client.forNetwork({ + [process.env.HEDERA_NETWORK]: new AccountId(3), + }); + client.setOperator(operatorId, operatorKey); + + // Increase the timeout settings + client.setRequestTimeout(120000); + + /** + * Step 1: Submit the file create transaction + */ + + // Content to be stored in the file. + const fileContents = Buffer.from("Hedera is great!", "utf-8"); + + try { + console.log("Creating new file..."); + + // Create the transaction + let transaction = new FileCreateTransaction() + .setKeys([operatorKey.publicKey]) // The public key of the owner of the file. + .setContents(fileContents) + .setMaxTransactionFee(new Hbar(2)) // Change the default max transaction fee to 2 hbars + .freezeWith(client); // Freeze with client + + transaction = await transaction.sign(operatorKey); + + const response = await transaction.execute(client); + + const receipt = await response.getReceipt(client); + + // Get the file ID + const newFileId = receipt.fileId; + + if (newFileId) { + console.log(`Created new file with ID: ${newFileId.toString()}`); + } else { + throw new Error("Failed to retrieve new file ID"); + } + + /** + * Step 2: Get file contents and print them + */ + + const fileContentsQuery = await new FileContentsQuery() + .setFileId(newFileId) + .execute(client); + + if (fileContentsQuery) { + console.log("File contents: " + fileContentsQuery.toString()); + } else { + throw new Error("Failed to retrieve file contents"); + } + + // Clean up: Delete created file + const fileDeleteTxResponse = await new FileDeleteTransaction() + .setFileId(newFileId) + .execute(client); + + await fileDeleteTxResponse.getReceipt(client); + + console.log("File deleted successfully"); + } catch (error) { + console.error("Error occurred during file creation:", error); + } finally { + // Close the client + client.close(); + console.log("Get File Contents Example Complete!"); + } +} + +main().catch((error) => { + console.error("Unhandled error:", error); + process.exit(1); +}); From f43666c01861aefa08e3d72f1203a0f15fe881c9 Mon Sep 17 00:00:00 2001 From: b-l-u-e Date: Tue, 15 Oct 2024 13:06:45 +0300 Subject: [PATCH 2/8] modified Client with access to mainnet, localnet, testnet and made some few other changes Signed-off-by: b-l-u-e --- examples/get-file-contents.js | 61 ++++++++++++++++++----------------- 1 file changed, 32 insertions(+), 29 deletions(-) diff --git a/examples/get-file-contents.js b/examples/get-file-contents.js index 8999c0474..f71dd436a 100644 --- a/examples/get-file-contents.js +++ b/examples/get-file-contents.js @@ -22,12 +22,12 @@ async function main() { * Create and configure the SDK Client */ if ( - process.env.OPERATOR_ID == null || - process.env.OPERATOR_KEY == null || - process.env.HEDERA_NETWORK == null + !process.env.OPERATOR_ID || + !process.env.OPERATOR_KEY || + !process.env.HEDERA_NETWORK ) { throw new Error( - "Environment variables OPERATOR_ID, HEDERA_NETWORK, and OPERATOR_KEY are required.", + "Environment variables OPERATOR_ID, OPERATOR_KEY, and HEDERA_NETWORK are required.", ); } @@ -35,14 +35,30 @@ async function main() { const operatorKey = PrivateKey.fromStringED25519(process.env.OPERATOR_KEY); // Create a client for the local Hedera network - const client = Client.forNetwork({ - [process.env.HEDERA_NETWORK]: new AccountId(3), - }); + let client; + + switch (process.env.HEDERA_NETWORK) { + case "mainnet": + client = Client.forMainnet(); + break; + case "testnet": + client = Client.forTestnet(); + break; + case "previewnet": + client = Client.forPreviewnet(); + break; + case "local-node": + client = Client.forNetwork({ + "127.0.0.1:50211": new AccountId(3), + }); + break; + default: + throw new Error( + "Unsupported HEDERA_NETWORK value. Please set it to 'mainnet', 'testnet', 'previewnet', or 'local-node'.", + ); + } client.setOperator(operatorId, operatorKey); - // Increase the timeout settings - client.setRequestTimeout(120000); - /** * Step 1: Submit the file create transaction */ @@ -55,10 +71,10 @@ async function main() { // Create the transaction let transaction = new FileCreateTransaction() - .setKeys([operatorKey.publicKey]) // The public key of the owner of the file. + .setKeys([operatorKey.publicKey]) .setContents(fileContents) - .setMaxTransactionFee(new Hbar(2)) // Change the default max transaction fee to 2 hbars - .freezeWith(client); // Freeze with client + .setMaxTransactionFee(new Hbar(2)) + .freezeWith(client); transaction = await transaction.sign(operatorKey); @@ -68,12 +84,7 @@ async function main() { // Get the file ID const newFileId = receipt.fileId; - - if (newFileId) { - console.log(`Created new file with ID: ${newFileId.toString()}`); - } else { - throw new Error("Failed to retrieve new file ID"); - } + console.log(`Created new file with ID: ${newFileId.toString()}`); /** * Step 2: Get file contents and print them @@ -83,11 +94,7 @@ async function main() { .setFileId(newFileId) .execute(client); - if (fileContentsQuery) { - console.log("File contents: " + fileContentsQuery.toString()); - } else { - throw new Error("Failed to retrieve file contents"); - } + console.log("File contents: " + fileContentsQuery.toString()); // Clean up: Delete created file const fileDeleteTxResponse = await new FileDeleteTransaction() @@ -100,13 +107,9 @@ async function main() { } catch (error) { console.error("Error occurred during file creation:", error); } finally { - // Close the client client.close(); console.log("Get File Contents Example Complete!"); } } -main().catch((error) => { - console.error("Unhandled error:", error); - process.exit(1); -}); +void main(); From 427b57ce0b959dfbc1623f54e7f9ff887a61f24a Mon Sep 17 00:00:00 2001 From: b-l-u-e Date: Tue, 15 Oct 2024 13:09:03 +0300 Subject: [PATCH 3/8] modified file Signed-off-by: b-l-u-e --- examples/get-file-contents.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/get-file-contents.js b/examples/get-file-contents.js index f71dd436a..56769814e 100644 --- a/examples/get-file-contents.js +++ b/examples/get-file-contents.js @@ -34,7 +34,7 @@ async function main() { const operatorId = AccountId.fromString(process.env.OPERATOR_ID); const operatorKey = PrivateKey.fromStringED25519(process.env.OPERATOR_KEY); - // Create a client for the local Hedera network + let client; switch (process.env.HEDERA_NETWORK) { From d7e83d0a1d6724ce100f5cf53d76af33b401bcc2 Mon Sep 17 00:00:00 2001 From: b-l-u-e Date: Tue, 15 Oct 2024 14:50:52 +0300 Subject: [PATCH 4/8] updated client configuration, replaced console logs with logger Signed-off-by: b-l-u-e --- examples/get-file-contents.js | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/examples/get-file-contents.js b/examples/get-file-contents.js index 56769814e..023223d6b 100644 --- a/examples/get-file-contents.js +++ b/examples/get-file-contents.js @@ -11,6 +11,9 @@ import dotenv from "dotenv"; dotenv.config(); +// Removed pino logger initialization +const logger = console; + /** * How to get file contents * @@ -26,17 +29,22 @@ async function main() { !process.env.OPERATOR_KEY || !process.env.HEDERA_NETWORK ) { - throw new Error( + logger.error( "Environment variables OPERATOR_ID, OPERATOR_KEY, and HEDERA_NETWORK are required.", ); + throw new Error("Missing required environment variables."); } const operatorId = AccountId.fromString(process.env.OPERATOR_ID); const operatorKey = PrivateKey.fromStringED25519(process.env.OPERATOR_KEY); - let client; + // Adjust this as needed for your local network + const localNetworkConfig = { + "127.0.0.1:50211": new AccountId(3), + }; + switch (process.env.HEDERA_NETWORK) { case "mainnet": client = Client.forMainnet(); @@ -48,13 +56,12 @@ async function main() { client = Client.forPreviewnet(); break; case "local-node": - client = Client.forNetwork({ - "127.0.0.1:50211": new AccountId(3), - }); + client = Client.forNetwork(localNetworkConfig); break; default: + logger.error("Unsupported HEDERA_NETWORK value."); throw new Error( - "Unsupported HEDERA_NETWORK value. Please set it to 'mainnet', 'testnet', 'previewnet', or 'local-node'.", + "Unsupported HEDERA_NETWORK value. Set to 'mainnet', 'testnet', 'previewnet', or 'local-node'.", ); } client.setOperator(operatorId, operatorKey); @@ -67,7 +74,7 @@ async function main() { const fileContents = Buffer.from("Hedera is great!", "utf-8"); try { - console.log("Creating new file..."); + logger.info("Creating new file..."); // Create the transaction let transaction = new FileCreateTransaction() @@ -84,7 +91,7 @@ async function main() { // Get the file ID const newFileId = receipt.fileId; - console.log(`Created new file with ID: ${newFileId.toString()}`); + logger.info(`Created new file with ID: ${newFileId.toString()}`); /** * Step 2: Get file contents and print them @@ -94,7 +101,7 @@ async function main() { .setFileId(newFileId) .execute(client); - console.log("File contents: " + fileContentsQuery.toString()); + logger.info("File contents: " + fileContentsQuery.toString()); // Clean up: Delete created file const fileDeleteTxResponse = await new FileDeleteTransaction() @@ -103,12 +110,12 @@ async function main() { await fileDeleteTxResponse.getReceipt(client); - console.log("File deleted successfully"); + logger.info("File deleted successfully"); } catch (error) { - console.error("Error occurred during file creation:", error); + logger.error("Error occurred during file creation:", error); } finally { client.close(); - console.log("Get File Contents Example Complete!"); + logger.info("Get File Contents Example Complete!"); } } From 288e078a6b24e6e1d88133bc310d9d07014638b7 Mon Sep 17 00:00:00 2001 From: b-l-u-e Date: Tue, 15 Oct 2024 20:50:21 +0300 Subject: [PATCH 5/8] client configuration and logger updated Signed-off-by: b-l-u-e --- examples/get-file-contents.js | 49 +++++++++++++++-------------------- 1 file changed, 21 insertions(+), 28 deletions(-) diff --git a/examples/get-file-contents.js b/examples/get-file-contents.js index 023223d6b..afc2506bb 100644 --- a/examples/get-file-contents.js +++ b/examples/get-file-contents.js @@ -1,3 +1,4 @@ +/* eslint-disable n/no-extraneous-import */ import { PrivateKey, FileContentsQuery, @@ -9,10 +10,25 @@ import { } from "@hashgraph/sdk"; import dotenv from "dotenv"; +import pino from "pino"; +import pinoPretty from "pino-pretty"; + dotenv.config(); -// Removed pino logger initialization -const logger = console; +// Set default log level to 'silent' if SDK_LOG_LEVEL is not specified in .env +const SDK_LOG_LEVEL = process.env.SDK_LOG_LEVEL || "silent"; + +// Logger configuration based on SDK_LOG_LEVEL +const logger = pino( + { + level: SDK_LOG_LEVEL.toLowerCase(), + }, + pinoPretty({ + colorize: true, + translateTime: "SYS:standard", + ignore: "pid,hostname", + }), +); /** * How to get file contents @@ -38,32 +54,9 @@ async function main() { const operatorId = AccountId.fromString(process.env.OPERATOR_ID); const operatorKey = PrivateKey.fromStringED25519(process.env.OPERATOR_KEY); - let client; - - // Adjust this as needed for your local network - const localNetworkConfig = { - "127.0.0.1:50211": new AccountId(3), - }; - - switch (process.env.HEDERA_NETWORK) { - case "mainnet": - client = Client.forMainnet(); - break; - case "testnet": - client = Client.forTestnet(); - break; - case "previewnet": - client = Client.forPreviewnet(); - break; - case "local-node": - client = Client.forNetwork(localNetworkConfig); - break; - default: - logger.error("Unsupported HEDERA_NETWORK value."); - throw new Error( - "Unsupported HEDERA_NETWORK value. Set to 'mainnet', 'testnet', 'previewnet', or 'local-node'.", - ); - } + // Create the client based on the HEDERA_NETWORK environment variable + let client = Client.forName(process.env.HEDERA_NETWORK); + client.setOperator(operatorId, operatorKey); /** From 485878809228331763dfb7b5dfc73800830e75bd Mon Sep 17 00:00:00 2001 From: b-l-u-e Date: Tue, 15 Oct 2024 21:01:11 +0300 Subject: [PATCH 6/8] logger updated Signed-off-by: b-l-u-e --- examples/get-file-contents.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/get-file-contents.js b/examples/get-file-contents.js index afc2506bb..7a64c1497 100644 --- a/examples/get-file-contents.js +++ b/examples/get-file-contents.js @@ -16,12 +16,12 @@ import pinoPretty from "pino-pretty"; dotenv.config(); // Set default log level to 'silent' if SDK_LOG_LEVEL is not specified in .env -const SDK_LOG_LEVEL = process.env.SDK_LOG_LEVEL || "silent"; +const SDK_LOG_LEVEL = process.env.SDK_LOG_LEVEL || "SILENT"; // Logger configuration based on SDK_LOG_LEVEL const logger = pino( { - level: SDK_LOG_LEVEL.toLowerCase(), + level: SDK_LOG_LEVEL.toUpperCase(), }, pinoPretty({ colorize: true, From f354af4e5d541e49d217860a32502c95b7e88979 Mon Sep 17 00:00:00 2001 From: b-l-u-e Date: Wed, 16 Oct 2024 17:18:06 +0300 Subject: [PATCH 7/8] updated logger Signed-off-by: b-l-u-e --- examples/get-file-contents.js | 38 ++++++++++++++--------------------- 1 file changed, 15 insertions(+), 23 deletions(-) diff --git a/examples/get-file-contents.js b/examples/get-file-contents.js index 7a64c1497..56d388a16 100644 --- a/examples/get-file-contents.js +++ b/examples/get-file-contents.js @@ -1,4 +1,3 @@ -/* eslint-disable n/no-extraneous-import */ import { PrivateKey, FileContentsQuery, @@ -7,28 +6,18 @@ import { FileDeleteTransaction, Client, AccountId, + Logger, + LogLevel, } from "@hashgraph/sdk"; import dotenv from "dotenv"; -import pino from "pino"; -import pinoPretty from "pino-pretty"; - dotenv.config(); // Set default log level to 'silent' if SDK_LOG_LEVEL is not specified in .env const SDK_LOG_LEVEL = process.env.SDK_LOG_LEVEL || "SILENT"; -// Logger configuration based on SDK_LOG_LEVEL -const logger = pino( - { - level: SDK_LOG_LEVEL.toUpperCase(), - }, - pinoPretty({ - colorize: true, - translateTime: "SYS:standard", - ignore: "pid,hostname", - }), -); +// Initialize Logger with the specified log level from the environment variable +const logger = new Logger(LogLevel._fromString(SDK_LOG_LEVEL)); /** * How to get file contents @@ -45,7 +34,7 @@ async function main() { !process.env.OPERATOR_KEY || !process.env.HEDERA_NETWORK ) { - logger.error( + console.error( "Environment variables OPERATOR_ID, OPERATOR_KEY, and HEDERA_NETWORK are required.", ); throw new Error("Missing required environment variables."); @@ -55,10 +44,13 @@ async function main() { const operatorKey = PrivateKey.fromStringED25519(process.env.OPERATOR_KEY); // Create the client based on the HEDERA_NETWORK environment variable - let client = Client.forName(process.env.HEDERA_NETWORK); + const client = Client.forName(process.env.HEDERA_NETWORK); client.setOperator(operatorId, operatorKey); + // Attach your custom logger to the SDK client + client.setLogger(logger); + /** * Step 1: Submit the file create transaction */ @@ -67,7 +59,7 @@ async function main() { const fileContents = Buffer.from("Hedera is great!", "utf-8"); try { - logger.info("Creating new file..."); + console.log("Creating new file..."); // Create the transaction let transaction = new FileCreateTransaction() @@ -84,7 +76,7 @@ async function main() { // Get the file ID const newFileId = receipt.fileId; - logger.info(`Created new file with ID: ${newFileId.toString()}`); + console.log(`Created new file with ID: ${newFileId.toString()}`); /** * Step 2: Get file contents and print them @@ -94,7 +86,7 @@ async function main() { .setFileId(newFileId) .execute(client); - logger.info("File contents: " + fileContentsQuery.toString()); + console.log("File contents: " + fileContentsQuery.toString()); // Clean up: Delete created file const fileDeleteTxResponse = await new FileDeleteTransaction() @@ -103,12 +95,12 @@ async function main() { await fileDeleteTxResponse.getReceipt(client); - logger.info("File deleted successfully"); + console.log("File deleted successfully"); } catch (error) { - logger.error("Error occurred during file creation:", error); + console.error("Error occurred during file creation:", error); } finally { client.close(); - logger.info("Get File Contents Example Complete!"); + console.log("Get File Contents Example Complete!"); } } From d6514fb02709c530ada222c4e40758b4ebc2d630 Mon Sep 17 00:00:00 2001 From: b-l-u-e Date: Thu, 17 Oct 2024 08:47:13 +0300 Subject: [PATCH 8/8] updated logger Signed-off-by: b-l-u-e --- examples/get-file-contents.js | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/examples/get-file-contents.js b/examples/get-file-contents.js index 56d388a16..7e175ef08 100644 --- a/examples/get-file-contents.js +++ b/examples/get-file-contents.js @@ -12,13 +12,6 @@ import { import dotenv from "dotenv"; dotenv.config(); - -// Set default log level to 'silent' if SDK_LOG_LEVEL is not specified in .env -const SDK_LOG_LEVEL = process.env.SDK_LOG_LEVEL || "SILENT"; - -// Initialize Logger with the specified log level from the environment variable -const logger = new Logger(LogLevel._fromString(SDK_LOG_LEVEL)); - /** * How to get file contents * @@ -48,8 +41,9 @@ async function main() { client.setOperator(operatorId, operatorKey); - // Attach your custom logger to the SDK client - client.setLogger(logger); + // Set logger + const infoLogger = new Logger(LogLevel.Info); + client.setLogger(infoLogger); /** * Step 1: Submit the file create transaction