Node.js Chaincode Structure

Node.js Chaincode Structure

Now that we have a Javascript SimpleContract implementation, let’s learn how to make it a part of a Node.js chaincode.

From the Node.js perspective, a chaincode is an npm package. Therefore, package.json and index.js files are required. A basic package.json file looks as follows:

package.json
{
    "name": "simple_chaincode",
    "version": "1.0.0",
    "main": "index.js",
    "scripts": {
      "start": "fabric-chaincode-node start"
    },
    "engines": {
      "node": ">=12",
      "npm": ">=5"
    },
    "dependencies": {
      "fabric-contract-api": "^2.2.0",
      "fabric-shim": "^2.2.0"
    }
}

The chaincode package should import fabric-contract-api and fabric-shim modules. These modules require specific versions of engines provided above.

The start script must be set to fabric-chaincode-node start. It is called by a peer during the chaincode startup. The main entry point of a chaincode package should be set to index.js containing exports of an npm module.

index.js
'use strict'; 

const simpleContract = require('./lib/simpleContract'); 

module.exports.SimpleContract = simpleContract;
module.exports.contracts = [simpleContract];

It is mandatory to have the contracts element exported in index.js. contracts is an array of classes that are inheritors of the Contract class.

Last updated

Was this helpful?