I was reading my feed and very interesting post come up. I think all forms of incentive to show users how to create dApps in Hive blockchain is valid. We for sure need more devs, and as the Challenge post say, now with help of AI we can vibe code some dApps and maybe also games.
So, I decided to accept this challenge and start from zero this project.
As a senior dev, usually I never start from zero, and wondered to use some codes from others projects i made, but after preparing my coffee (sugestion from hivedevchallenge) I decided to start from scratch and teach how to configure typescript, install libs and the basics anyone need to start a Hive dApp.
https://peakd.com/hivedevchallenge/@hiveblocks-es/hive-dev-challenge-1-unete-al-desafio
There are 2 libs I like to use for Hive, hivejs and dhive. this time, i decided go to dhive.
So, here is my tutorial to help others participate in Hive Dev Challenge 1 proposed by @hiveblocks-es.
The goal is to store your favorite sentence in a Hive blockchain custom JSON.
During the coding, i decided do enhance it a little bit, and instead of just writing a hardcoded sentence, ask the user, so, each time it run the script, it can create a fresh new sentence (please do not spam)
Let`s Build?!
Step 1: Create a project folder
Create a new folder for the project and initialize it:
mkdir hive-dev-challenge
cd hive-dev-challenge
pnpm init
Step 2: Install TypeScript
Let`s use TypeScript for this project:
pnpm add -D typescript
pnpm add -D ts-node
pnpm tsc --init
After this, you should have a package.json
and tsconfig.json
in your project folder.
Step 3: Install dhive library
Let's use the lib @hiveio/dhive
to connect to Hive Blockchain:
pnpm add @hiveio/dhive
Step 4: Create the source folder and index.ts
mkdir src
echo "console.log('Hello Hive!');" > src/index.ts
Compile and run to test:
pnpm tsc
node dist/index.js
If you configure everything right, you will see on the terminal:
Hello Hive!
Step 5: Configure package.json scripts
So you dont need to write the compile or run commands everythime, its a good practive to create at least these 3 run scripts on the package.json
:
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "ts-node src/index.ts"
}
Step 6: Configure TypeScript
Edit tsconfig.json
for Node.js ESM and async iterators:
{
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"target": "es2017",
"module": "esnext",
"moduleResolution": "node",
"types": ["node"],
"sourceMap": true,
"declaration": true,
"declarationMap": true,
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"noUncheckedSideEffectImports": true,
"moduleDetection": "force",
"skipLibCheck": true
},
"include": ["src/**/*"]
}
Step 7: Test connection to Hive
Create a simple script to connect and show blockchain info:
import { Client } from "@hiveio/dhive";
const client = new Client([
"https://api.hive.blog",
"https://api.hivekings.com",
"https://anyx.io",
"https://api.openhive.network"
]);
async function main() {
const props = await client.database.getChainProperties();
console.log(`Maximum blocksize: ${props.maximum_block_size} bytes`);
}
main().catch(console.error);
Run:
pnpm dev
Step 8: Show last 5 blocks
We can stream blocks from Hive:
import { Client } from "@hiveio/dhive";
const client = new Client([
"https://api.hive.blog",
"https://api.hivekings.com",
"https://anyx.io",
"https://api.openhive.network"
]);
async function main() {
let count = 0;
for await (const block of client.blockchain.getBlocks()) {
console.log(`Block ${count + 1}: ${block.block_id}`);
count++;
if (count >= 5) break;
}
}
main().catch(console.error);
Step 9: Setup git and .env
Never put private keys in Git. Use .env
:
git init
pnpm add dotenv
Create .env
:
HIVE_USERNAME=your-hive-user
HIVE_POSTING_KEY=5XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Add .env to .gitignore:
node_modules
dist
.env
Step 10: Build interactive script
Install readline to interact to user input from terminal:
pnpm add readline
Create src/index.ts
:
import "dotenv/config";
import { Client, PrivateKey } from "@hiveio/dhive";
import * as readline from "readline";
const client = new Client([
"https://api.hive.blog",
"https://api.hivekings.com",
"https://anyx.io",
"https://api.openhive.network",
]);
const HIVE_USERNAME = process.env.HIVE_USERNAME!;
const HIVE_POSTING_KEY = process.env.HIVE_POSTING_KEY!;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
function ask(question: string): Promise<string> {
return new Promise(resolve => rl.question(question, resolve));
}
function wait(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main() {
try {
console.log("Connecting to Hive blockchain, showing last 5 blocks...");
let count = 0;
for await (const block of client.blockchain.getBlocks()) {
console.log(`Block ${count + 1}: ${block.block_id}`);
count++;
if (count >= 5) break;
}
await wait(500);
const sentence = await ask(`Hey ${HIVE_USERNAME}, write your favorite sentence: `);
const payload = { Reto: "HiveDevChallenge", Frase: sentence };
const customJson = {
id: "holamundo",
json: JSON.stringify(payload),
required_auths: [] as string[],
required_posting_auths: [HIVE_USERNAME] as string[],
};
console.log("\nThis is the JSON that will be broadcast:");
console.log(JSON.stringify(payload, null, 2));
const confirm = await ask("\nDo you want to broadcast this to Hive? (Y/N): ");
if (confirm.toLowerCase() !== "y") {
console.log("Submission cancelled");
return;
}
const postingKey = PrivateKey.fromString(HIVE_POSTING_KEY);
const result = await client.broadcast.json(customJson, postingKey);
console.log("Broadcast successful!");
console.log(result);
} catch (err) {
console.error("Error:", err);
} finally {
rl.close();
}
}
main();
Step 11: Test the script
Run it using pnpm dev and see if it will ask you to type your favorite sentence, confirm, and it will be broadcast to Hive.
I decided to first do not confirm, so we can test if it will not post in case of respond N.
Then I went to full testing, first updating with my user and keys constants in .env file. Now it show my username correctly and...
You can check the transaction using Hive explorers like https://hivehub.dev/
by pasting the transaction id.
Here is my step by step how to start your first custom json stored in the Hive Blockchain, you can use it to store your future dApp informations or just to participate in Hive Dev Challenge 1, creating a basic TypeScript project, connect to Hive, and safely broadcast your favorite sentence as a custom JSON.
If you came up with any error in this script, fell free to ask me tagging me on the comments bellow. I`ll be happy to help.
Errors and Debugging
While building this project, I faced some errors configuring typescript in node (always a pain) and here is how to fix them. The list of the main issues I faced while building this project:
TypeScript unknown file extension
TypeError: Unknown file extension ".ts"
Cause: Node.js does not know how to run TypeScript files by default.
Solution: Use ts-node with ESM loader:
Make sure package.json has:
"type": "module",
"scripts": {
"dev": "node --loader ts-node/esm src/index.ts"
}
And tsconfig.json uses "module": "esnext".
Private key network mismatch
AssertionError [ERR_ASSERTION]: private key network id mismatch
Cause: The Hive private key is missing, incorrect, or for the wrong network.
Solution: Check your .env file and make sure HIVE_POSTING_KEY is your correct Hive posting key. Never share it.
Read only array error in TypeScript
Type 'readonly []' is not assignable to parameter of type 'string[]'
Cause: TypeScript sees readonly []
and expects a mutable array.
Solution: Add a type cast:
required_auths: [] as string[],
required_posting_auths: [HIVE_USERNAME] as string[],
Deprecation warnings
[DEP0040] The `punycode` module is deprecated.
[DEP0180] fs.Stats constructor is deprecated
Cause: These are know warnings from dhive libraries.
Solution: You can ignore them for now. They do not block the script. Later, library updates may remove them.
Using .env and gitignore
IMPORTANT: Never hardcode your keys. Always use a .env
file and add it to .gitignore
:
node_modules
dist
.env
Good Challenge!
Bacana demais mano, mandou bem! Eu fiz scripts para fazer power up diario e jogar parte do meu hbd no savings, toda vez que ligo meu notebook ele ja faz tudo hehe, é uma mão na roda
bom demais, segui la no github, mas nao instalei, faco manualmente mesmo...
mas segue esse tutorial e manda ver, talvez vc tenha alguma ideia nova.
Obrigado por promover a comunidade Hive-BR em suas postagens.
Vamos seguir fortalecendo a Hive