Skip to content

Instantly share code, notes, and snippets.

@michielmulders
Created March 5, 2018 14:23
Show Gist options
  • Save michielmulders/f4c0ee9dfc761228fb08510472fb4076 to your computer and use it in GitHub Desktop.
Save michielmulders/f4c0ee9dfc761228fb08510472fb4076 to your computer and use it in GitHub Desktop.
Hyperledger not-complete chaincode example from Fabcar
// Define the Smart Contract structure
type SmartContract struct { }
// Define the car structure, with 4 properties.
type Car struct {
Make string `json:"make"`
Model string `json:"model"`
Colour string `json:"colour"`
Owner string `json:"owner"`
}
/*
* The Invoke method is called as a result of an application request to run the Smart Contract "fabcar"
* The calling application program has also specified the particular smart contract function to be called, with arguments
*/
func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response {
// Retrieve the requested Smart Contract function and arguments
function, args := APIstub.GetFunctionAndParameters()
// Route to the appropriate handler function to interact with the ledger appropriately
if function == "initLedger" {
return s.initLedger(APIstub)
} else if function == "createCar" {
return s.createCar(APIstub, args)
}
return shim.Error("Invalid Smart Contract function name.")
}
func (s *SmartContract) initLedger(APIstub shim.ChaincodeStubInterface) sc.Response {
return shim.Success([]byte("Ledger is now running, success!"))
}
// Add new car to database with obtained arguments
func (s *SmartContract) createCar(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 5 {
return shim.Error("Incorrect number of arguments. Expecting 5")
}
var car = Car{Make: args[1], Model: args[2], Colour: args[3], Owner: args[4]}
carAsBytes, _ := json.Marshal(car)
APIstub.PutState(args[0], carAsBytes)
return shim.Success(nil)
}
func main() {
// Create a new Smart Contract
err := shim.Start(new(SmartContract))
if err != nil {
fmt.Printf("Error creating new Smart Contract: %s", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment