Reading and modifying an asset
After we have implemented the function to create a trade agreement, we need to implement a function to accept the trade agreement. This function will retrieve the agreement, modify its status to ACCEPTED, and put it back on the ledger.
The implementation of this function is shown in the following snippet. In the code, we construct the unique composite key of the trade agreement we want to retrieve. In line 22, we retrieve the value with the function GetState. In line 33, we deserialize the array of bytes into the instance of the TradeAgreement struct. In line 41, we modify the status so it reads ACCEPTED; finally, in line 47, we store the updated value on the ledger, as follows:
func (t *TradeWorkflowChaincode) acceptTrade(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response { var tradeKey string var tradeAgreement *TradeAgreement var tradeAgreementBytes []byte var err error // Access control: Only an Exporting Entity Org member can invoke this transaction if !t.testMode && !authenticateExportingEntityOrg(creatorOrg, creatorCertIssuer) { return shim.Error("Caller not a member of Exporting Entity Org. Access denied.") } if len(args) != 1 { err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 1: {ID}. Found %d", len(args))) return shim.Error(err.Error()) } // Get the state from the ledger tradeKey, err = getTradeKey(stub, args[0]) if err != nil { return shim.Error(err.Error()) } tradeAgreementBytes, err = stub.GetState(tradeKey) if err != nil { return shim.Error(err.Error()) } if len(tradeAgreementBytes) == 0 { err = errors.New(fmt.Sprintf("No record found for trade ID %s", args[0])) return shim.Error(err.Error()) } // Unmarshal the JSON err = json.Unmarshal(tradeAgreementBytes, &tradeAgreement) if err != nil { return shim.Error(err.Error()) } if tradeAgreement.Status == ACCEPTED { fmt.Printf("Trade %s already accepted", args[0]) } else { tradeAgreement.Status = ACCEPTED tradeAgreementBytes, err = json.Marshal(tradeAgreement) if err != nil { return shim.Error("Error marshaling trade agreement structure") } // Write the state to the ledger err = stub.PutState(tradeKey, tradeAgreementBytes) if err != nil { return shim.Error(err.Error()) } } fmt.Printf("Trade %s acceptance recordedn", args[0]) return shim.Success(nil) }