Creating the nestjs-web3js Package: Integrating NestJS with Web3.js

Cláudio Rapôso
4 min readJul 3, 2023

NestJS is a framework for building scalable and efficient Node.js applications. On the other hand, Web3.js is a JavaScript library for interacting with the Ethereum blockchain. In this article, we will explore how to create a package called nestjs-web3js that allows for easy and efficient integration of NestJS with Web3.js.

If you want to understand how web3.js works in NestJS, check out the articles:

Integrating MetaMask with NestJS and Web3.js: A Detailed Guide | by Cláudio Rapôso | Jun, 2023 | Medium

Minting NFTs with NestJS and web3.js | by Cláudio Rapôso | Jul, 2023 | Medium

Package Overview

The nestjs-web3js package is designed to provide a NestJS module called Web3jsModule and a corresponding service called Web3jsService. It allows developers to access the Web3.js instance in a centralized and convenient way in their NestJS applications.

Package Structure

The basic structure of the nestjs-web3js package is as follows:

nestjs-web3js
├── src
│ └── web3js
│ ├── dto
│ │ └── create-web3js-service.dto.ts
│ ├── web3js.module.ts
│ └── web3js.service.ts
└── index.ts

The src folder contains all the source code of the package, and the index.ts file is used to export the main components of the package.

Main Components

Let’s take a look at the main components of the nestjs-web3js package:

Web3jsModule

The Web3jsModule is a NestJS module that provides the Web3jsService to the entire application. It is designed to be imported into the main module of NestJS using the forRoot method.

Here is the implementation of the Web3jsModule:

import { DynamicModule, Global, Module } from '@nestjs/common';
import { Web3jsService } from './web3js.service';
import Web3 from 'web3';
import { CreateWeb3jsServiceDto } from './dto/create-web3js-service.dto';

@Global()
@Module({
providers: [Web3jsService],
exports: [Web3jsService],
})
export class Web3jsModule {
static forRoot({ infuraUrl }: CreateWeb3jsServiceDto): DynamicModule {
return {
module: Web3jsModule,
providers: [
{
provide: Web3jsService,
useFactory: () => new Web3jsService(new Web3(infuraUrl)),
},
],
};
}
}

The Web3jsModule is marked with the @Global decorator to allow the Web3jsService to be shared among different NestJS modules.

Web3jsService

The Web3jsService is a NestJS service that encapsulates the Web3.js instance. It provides a convenient interface for interacting with the Ethereum blockchain in a NestJS application.

Here is the implementation of the Web3jsService:

import { Injectable } from '@nestjs/common';
import Web3 from 'web3';

@Injectable()
export class Web3jsService {
private readonly props: Required<Web3>;
constructor(web3: Web3) {
this.props = web3;
}
get web3(): Required<Web3> {
return this.props;
}
}

The Web3jsService is injectable using the @Injectable decorator from NestJS. It receives a Web3.js instance in the constructor and provides a web3 property to access the Web3.js instance.

create-web3js-service.dto.ts

The create-web3js-service.dto.ts file defines the validation schema and creation of a configuration object for the Web3jsService. It uses the nestjs-zod library to create the schema.

Here is the implementation of the create-web3js-service.dto.ts:

import { createZodDto } from 'nestjs-zod';
import { z } from 'nestjs-zod/z';

export const CreateWeb3jsServiceSchema = z
.object({
infuraUrl: z.string().url().min(3),
})
.required();

// class is required for using DTO as a type
export class CreateWeb3jsServiceDto extends createZodDto(
CreateWeb3jsServiceSchema,
) {}

The CreateWeb3jsServiceSchema schema defines an infuraUrl property that must be a string containing a valid URL with a minimum length of 3 characters. The CreateWeb3jsServiceDto is created using the createZodDto function from nestjs-zod to apply the validation schema.

Using the nestjs-web3js Package

Now that the nestjs-web3js package is ready, let's see how to use it in a NestJS application.

Installation

To get started, you need to install the nestjs-web3js package in your NestJS application. Open a terminal at the root of your project and run the following command:

npm install nestjs-web3js

Import and Configuration

After installation, you can import the Web3jsModule into your NestJS main module. Make sure to provide the necessary configuration when using the forRoot method.

Here is an example of how to import and configure the Web3jsModule:

import { Module } from '@nestjs/common';
import { Web3jsModule, CreateWeb3jsServiceDto } from 'nestjs-web3js';

@Module({
imports: [
Web3jsModule.forRoot({
infuraUrl: 'https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY',
} as CreateWeb3jsServiceDto),
],
})
export class AppModule {}

Make sure to replace 'https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY' with the Infura URL corresponding to your API key.

Using the Service

Once configured, you can inject the Web3jsService into your controllers, services, or other NestJS components.

Here is an example of using the Web3jsService in a controller:

import { Controller, Get } from '@nestjs/common';
import { Web3jsService } from 'nestjs-web3js';

@Controller('example')
export class ExampleController {
constructor(private readonly web3jsService: Web3jsService) {}

@Get()
async getBlockNumber(): Promise<number> {
const web3 = this.web3jsService.web3;
const blockNumber = await web3.eth.getBlockNumber();
return blockNumber;
}
}

In this example, the ExampleController injects the Web3jsService through the constructor and uses the web3 property to interact with the Web3.js instance.

Conclusion

In this article, we explored the creation of the nestjs-web3js package, which provides an easy and efficient integration of NestJS with Web3.js. We saw how to import, configure, and use the package in a NestJS application. Now, you can leverage the powerful features of Web3.js in your NestJS applications in a simple and organized manner. For more information and usage examples, refer to the official documentation of NestJS and Web3.js.

I hope this article has been helpful, and you can make the most of the nestjs-web3js package in your projects.

The source code: engcfraposo/nestjs-web3js: The nestjs-web3js is a NestJS module that provides a connection to Ethereum’s blockchain. It uses the web3.js library, which is a collection of libraries that allow you to interact with a local or remote Ethereum node using HTTP, IPC, or WebSocket. (github.com)

The package: nestjs-web3js — npm (npmjs.com)

If you want to listen in portuguese, follow the link: Criando o pacote nestjs-web3js: Integração do NestJS com Web3.js | by Cláudio Rapôso | Jul, 2023 | Medium

--

--

Cláudio Rapôso

Microsoft MVP | Software Architect | Teacher | Book Author | MCT | 12x Microsoft Certified Connect with me in https://www.linkedin.com/in/cfraposo