⚠️ Note: Since writing this article, our module has gone through some changes and updates. Please check the github for the latest info.

Writing chaincode shouldn’t be a hassle. Luckily Hyperledger Fabric has introduced Nodejs chaincode in v1.1.0 (official release should be out by the end of this month). Compared to Golang, this is a language more people understand and find easier to use, Including us. To be honest, I got to like Golang (when I understood it eventually). But in my opinion, it’s much more of an overhead to write chaincode than Nodejs. We made the switch when we couldn’t access the ABAC (cid) feature in Golang because the dependency of this package didn’t want to be resolved correctly.

All examples are written in Typescript since all of our packages are also developed in typescript. But by removing the types, you can just use it in your non-typescript application as well. We recommend using typescript because, without typings, your chaincode could more easily introduce bugs.

Components

We created a package which contains a set of helper classes in order for you to write code faster. Compared to Golang, your functions can be reduced from 10 lines to 4.

yarn add @theledger/fabric-chaincode-utils

The Chaincode class is a base class containing handlers for the Invoke() and Init() functions which are required by fabric-shim . The Init() function can be overwritten by just implementing it in your MyChaincode class, this function should be called init and will also be injected with the same arguments as your custom functions.

export class MyChaincode extends Chaincode {

The Chaincode base class also implements the Invoke() method. It will search in your class for existing chaincode methods with the function name you sent. It will also automatically wrap and serialize the response with shim.success() and shim.error() . You can just return the javascript object and it will do the rest, BUT returning a Buffer is still supported as well. So for example, if we invoke our chaincode with function queryCar , the function below will be executed.

export class MyChaincode extends Chaincode {



async queryCar(stubHelper: StubHelper, args: string[]) { // You can just return a javascript object

return car; // Or you can serialize it yourself

return Buffer.from(JSON.stringify(car)); }



}

The StubHelper is a wrapper around the fabric-shim stub. It’s a helper to automatically serialize and deserialize data being saved/retrieved. The full API can be found here.

The Transform class is a helper to provide data transformation to and from the formats required by Hyperledger Fabric. The full API can be found here.