Skip to main content

Write a Node.js project utilizing Nil.js

This short recipe shows how Nil.js can be used in a small-scale Node.js project.

Project set-up

First, create a new file titled server.js in an environment where Node.js is installed.

Then, import the following components and initialize the following variables:

const { createServer } = require("node:http");
const {
Faucet,
HttpTransport,
LocalECDSAKeySigner,
PublicClient,
WalletV1,
generateRandomPrivateKey,
convertEthToWei,
} = require("@nilfoundation/niljs");

const hostname = "127.0.0.1";
const port = 3000;

Server code

Our server will initialize a new wallet and, once wallet creation ends, show its address in the browser window:

const server = createServer((req, res) => {
(async () => {
try {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
const client = new PublicClient({
transport: new HttpTransport({
endpoint: RPC_ENDPOINT,
}),
shardId: 1,
});

const faucet = new Faucet(client);
const signer = new LocalECDSAKeySigner({
privateKey: generateRandomPrivateKey(),
});

const pubkey = signer.getPublicKey();
const wallet = new WalletV1({
pubkey: pubkey,
salt: BigInt(Math.floor(Math.random() * 10000)),
shardId: 1,
client,
signer,
});

const walletAddress = wallet.address;
await faucet.withdrawToWithRetry(walletAddress, convertEthToWei(1));
await wallet.selfDeploy(true);

res.write(`New wallet address: ${walletAddress}\n`);
res.on("finish", () => {
console.log(`New wallet address: ${walletAddress}`);
});
res.end();
} catch (error) {
console.error(error);
res.statusCode = 500;
res.write("An error occurred while creating the wallet.");
res.end();
}
})();
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

Interacting with the server

To launch the server:

node path/to/server.js

After the server is launched, open http://127.0.0.1:3000/ in the browser and wait a couple of seconds while the project creates a new wallet.

Alternatively, run the following snippet to fetch the wallet address once the server calculates it:

const response = await fetch("http://127.0.0.1:3000/");
const text = await response.text();
console.log(test);