How To Create a Smart Contract


In this tutorial, we will introduce you step by step to create a chaincode in Hyperledger Fabric 1.4.0 using VS Code. As an example, we will make a control system for library books belonging to a university.

1. Check the minimum requirements

Windows 10, major Linux distributions or newer versions of macOS

VS Code 1.36

Node.js 8

NPM 5 (already included in Node.js)

Docker v17

Docker Composer v.1.14

2. Install the IBM Blockchain Platform plugin

After opening VS Code, click on the extensions icon;

Search for and install the IBM Blockchain Platform plugin;

Restart the VS Code.

3. Create the project

Click on the IBM Blockchain Platform symbol on the panel;

Clicking on the three dots, select “Create Smart Contract Project”;

Choose “JavaScript”;

As an asset, define “University”;

Save the project;

Choose how the new project will open.

4. Configure the chaincode

The project opens with a standard Node application structure;

Select, in the “lib” folder, “university-contract.js” (which is the chaincode);

A code template with five operations will be opened.

5. Adapt operations

Replace all “universityId” with “CNPJ”, to allow identifying each university in the network;

In “exist”, replace “value” with “universityName”;

In “asset”, replace “value” with “cnpj: cnpj, name: universityName, library []”, to link the university to a book database;

In the “read” operation, replace “pubState” with “getState”, so that the most updated information is shown;

In the “update” operation, to update the library books without losing the history, add the commands:

var university = await (ctx.stub.getstate (cnpj));

university = JSON.parse: university);

const asset = {cnpj: cnpj,

name: universityName,

library: university.library}

6. Generate the chaincode

Click on the three dots and select “Package a Smart Contract Project”;

After generating [email protected], provision a local network by clicking on “Local Fabric …”;

To install chaincode, click on “Smart Contracts and install”;

Then, instantiate the same chaincode by clicking on “Instantiale”.

7. Create a smart contract

In “Fabric Gateways”, click on “local_fabric, mychannel, [email protected]”; then, in “createUniversity”; finally, in “Submit Transaction”;

Generate a string id for the university, such as [“12.234.5679 / 0001-01”, “Name of the University];

Double-enter and, ready, a smart contract was generated.

Want to read more specialized programming content? Discover the IBM Blue Profile and access exclusive materials, new knowledge journeys and personalized tests. Check it out right now, get the badges and upgrade your career!


Please enter your comment!
Please enter your name here