Warm tip: This article is reproduced from stackoverflow.com, please click
blockchain go hyperledger-chaincode hyperledger-fabric

How to calculate average price with FabCar

发布于 2020-04-23 12:56:36

I'm using the fabcar project (https://github.com/IBM/blockchain-application-using-fabric-java-sdk)

I added "Price" as a new argument for the car structure.

I would like to obtain the average price of cars in my blockchain network.

Is there any go function to do so?

Questioner
Pablo Bonet
Viewed
32
RicNtt 2020-02-11 22:54

You can use GetHistoryForKey() to retrieve all the cars and next calculate the average price ciclying on them.

Supposing you want to know the maximum price you can do:

resultsIterator, err := stub.GetHistoryForKey(id)
    if err != nil {
        return shim.Error('Error')
    }

var max = nil;
for resultsIterator.HasNext() {
        response, err := resultsIterator.Next()

        if err != nil {
            return shim.Error(err.Error())
        }

        if (response.Value.Price > max)
           max = response.Value.Price
}

return shim.Success(max)

Something like this in Go. Easy to change in average price.