Smart contract or chaincode developers should adhere to strict development guidelines and rules.
With Turing complete languages like Go Lang becoming the defacto standard for chaincode development and high interest from developers to get into this exciting space.
I am writing down some of the Don’ts and Best Practices to consider while developing your chaincode.
func addToAccount(stub shim.ChaincodeStubInterface, account *string, amount int){
balance,_ := stub.GetState(*account)
stub.PutState(*account, balance + amount)
}
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface)
pb.Response {
args := stub.GetArgs()
// assume args match addToAccount
addToAccount(stub,"AccountNo1", args[0])
// babalce == 150
// do more actions
addToAccount(stub,"AccountNo1", args[1])
// balance == 175
return shim.Success(nil)
}
type BadChaincode struct{
}
var myMap = map[int]int{
1:1,
2:5,
3:10,
4:50,
}
func (t *BadChaincode) Invoke (stub shim.ChaincodeStubInterface) peer.Response{
returnValue := 0
for i,ii := range myMap{
returnValue = returnValue * i - ii
}
return shim.Success([]byte("value: " + string(returnValue)))
}
func (t *BadChaincode) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
args := stub.GetStringArgs()
// by assuming passed len(args) == 2 but only 1 argument is passed
result,err := stub.GetState(args[0])
if err != nil{
return shim.Error(err.Error())
}else {
return shim.Success(result)
}
}
package main
import (
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
)
var globalValue = ""
func (t *BadChaincode) Invoke(stub shim.ChaincodeStubInterface){
}
iterator,_ := stub.GetHistoryForKey("key")
data,_ := iterator.Next()
err, := stub.PutState("key", data.Value)
package main
import (
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
)
type BadChainCode struct{
}
func (t *BadChainCode) Invoke(stub shim.ChaincodeStubInterface){
go writeToLedger(stub, "data1")
go writeToLedger(stub, "data2")
}
func writeToLedger(stub shim.ChaincodeStubInterface, data string){
stub.PutState("key",[]byte(data))
}
Last words: Have your development reviewed by an experienced blockchain developer to avoid loss of resources
Disclaimer : This is not intended to be an exhaustive list so don’t treat it as one.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
25 | |
16 | |
14 | |
12 | |
10 | |
9 | |
9 | |
8 | |
8 | |
8 |