Writing Chaincode

Before we start coding, you can choose to use an IDE for Go, or you may choose the old-fashioned route of Vim or Notepad. There are many popular IDEs which support Go development, for example Visual Studio Code (VSC) (https://code.visualstudio.com/docs/languages/go), JetBrains Goland, or Eclipse with the goEclipse plugin. Here, we recommend using VSC. You can refer to the official VSC documentation for setup and configuration instructions.

To start writing Chaincode, it's recommended that you download the project files from the code file section for this book on the Packt website. There is a starter project called food-supply-chain_start. You can import this project to your VSC and open the foodcontract.go file located under food-supply-chain_start/chaincode/foodcontract.

When writing the Chaincode, we first need to import the necessary Go dependencies – the shim, peer, and protobuf packages – as follows:

package main
import (
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/hyperledger/fabric/core/Chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
)

All Chaincode implements the following interface (from the shim package at https://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim#Chaincode), which declares these three core functions with the following signatures: 

type Chaincode interface {   
Init(stub *ChaincodeStub, function string, args []string) ([]byte, error)
Invoke(stub *ChaincodeStub, function string, args []string) ([]byte, error)
Query(stub *ChaincodeStub, function string, args []string) ([]byte, error)
}

Therefore, any Chaincode should define these main functions in its code. For our first Chaincode, FoodContract, along with the previous package, we will import the following structure:

type FoodContract struct{}
// We declare chaincode objects and variables
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response { return shim.Success([]byte("Init called")) } func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response { return shim.Success([]byte("Invoke called")) }
// We declare other functions func main() { err := shim.Start(new(FoodContract))
if err != nil {
fmt.Printf("Error creating new Food Contract: %s", err)
} }

We now need to fill in this empty Chaincode. Let’s start by implementing the Init() function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset