DevProvider

Hyperledger fabric chaincode basics

Smart Contracts are becoming increasingly popular everyday because of their automated nature. In Hyperledger Fabric terms, Smart Contracts are referred to as Hyperledger Fabric Chaincode. And developers have the option to write their chaincode logic in either Golang, NodeJS, or Java.

It is important to note that in order to build a complete blockchain-based application, three layers of code need to be Implemented:

  • Chaincode (For Interaction with the Blockchain & Ledger)
  • SDK (For Interaction between Application & Chaincode)
  • Application (For Interaction between User & Blockchain Backend)

We will be focusing on Chaincode for this tutorial, and our language of choice will be Golang. So let’s get into it.

To start off with our chaincode, we will need to import two libraries into our code.

After this, we need to define a simple struct for our Smart Contracts like this:

Like all code, our chaincode needs a main function as well. The main function is defined something like this

Now, we get to the ‘Real’ parts of the chaincode. When a chaincode is called, either one of the following two functions is called

  • Init
  • Invoke

Init is called when chaincode is deployed for the first time, or is upgraded to a newer version. This function can have any logic that you want to implement, or it can be left empty. Example of a simple init function is the following:

Next up is the invoke function. This is the function you actually call to interact with your deployed logic or Smart Contracts. The invoke function separates the function to be invoked and its arguments through this line

function, args := stub.GetFunctionAndParameters()

Next, it passes the arguments to the specified function. Example is the following

Now if you call the addAsset method, you can define some logic in it to add your asset to the Ledger. Similarly, you can use the queryAsset method to query the Ledger for a specific asset, or you can run the deleteAsset method to delete any existing asset.

You can find more examples of Chaincodes here.

If you need help with Hyperledger fabric chaincode, please feel free to discuss it with our blockchain development company.