Creating an asset

Now that we can implement our first chaincode function, we will move on and implement a requestTrade function, which will create a new trade agreement with the status REQUESTED and then record that agreement on the ledger.

The implementation of the function is shown in the following snippet. As you will see, in line 9 we verify that the invoker is a member of ImporterOrg and has permission to invoke the function. From lines 13 to 21 we validate and extract the arguments. In line 23, we create a new instance of TradeAgreement initiated with the received arguments. As we learned earlier, the ledger stores values in the form of arrays of bytes. Thus, in line 24 we serialize TradeAgreement with JSON into an array of bytes. In line 32, we create a unique key, under which we will store TradeAgreement. Finally, in line 37, we use the key and serialized TradeAgreement alongside the function PutState to store the value into the WriteSet.

The following snippet illustrates the requestTrade function:

func (t *TradeWorkflowChaincode) requestTrade(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response { 
   var tradeKey string 
   var tradeAgreement *TradeAgreement 
   var tradeAgreementBytes []byte 
   var amount int 
   var err error 
 
   // Access control: Only an Importer Org member can invoke this transaction 
   if !t.testMode && !authenticateImporterOrg(creatorOrg, creatorCertIssuer) { 
         return shim.Error("Caller not a member of Importer Org. Access denied.") 
   } 
 
   if len(args) != 3 { 
         err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 3: {ID, Amount, Description of Goods}. Found %d", len(args))) 
         return shim.Error(err.Error()) 
   } 
 
   amount, err = strconv.Atoi(string(args[1])) 
   if err != nil { 
         return shim.Error(err.Error()) 
   } 
 
   tradeAgreement = &TradeAgreement{amount, args[2], REQUESTED, 0} 
   tradeAgreementBytes, err = json.Marshal(tradeAgreement) 
   if err != nil { 
         return shim.Error("Error marshaling trade agreement structure") 
   } 
 
   // Write the state to the ledger 
   tradeKey, err = getTradeKey(stub, args[0]) 
   if err != nil { 
         return shim.Error(err.Error()) 
   } 
   err = stub.PutState(tradeKey, tradeAgreementBytes) 
   if err != nil { 
         return shim.Error(err.Error()) 
   } 
   fmt.Printf("Trade %s request recorded", args[0]) 
 
   return shim.Success(nil) 
}