hyperledger / fabric-contract-api-go

Packages for the implementation of the contract API for use in Go chaincode
https://wiki.hyperledger.org/display/fabric
Apache License 2.0
218 stars 100 forks source link

Init fuction not save data #106

Closed tran-the-lam closed 12 months ago

tran-the-lam commented 1 year ago

I have one smart-contract and init function to save data, but smc was deployed then I get value from key, data return "".

type SmartContract struct {
    contractapi.Contract
}

type User struct {
    UserID   string `json:"user_id"`
    Role     string `json:"role"`
    Password string `json:"password"`
}

func (s *SmartContract) Init(ctx contractapi.TransactionContextInterface) error {

    // Create User With Admin Role
    admin := User{
        UserID:   "admin",
        Role:     "admin",
        Password: "7ebd1a9b3dc007e9a9393ab3bd2848c6425f9218a00181775d4d311af048d023",
    }

    adminJSON, err := json.Marshal(admin)
    if err != nil {
        return err
    }

    if err := ctx.GetStub().PutState(admin.UserID, adminJSON); err != nil {
        return fmt.Errorf("failed to put to world state. %s", err.Error())
    }

    return nil
}
/network.sh deployCC -ccn basic -ccp $PWD/smart-contract/chaincode -ccl go

Please help me!

bestbeforetoday commented 12 months ago

How did you invoke your Init transaction function after deploying the smart contract?

tran-the-lam commented 12 months ago

I think Init fuction auto call when smart contract deployed.

bestbeforetoday commented 12 months ago

Using Fabric v2 chaincode lifecycle deployment, the Init function is not called automatically. You can approve chaincode as requiring an initialization transaction function to be called before general use, but you need to invoke that initialization transaction function explicitly. See the chaincode deployment documentation (particularly Step Three: Approve a chaincode definition for your organization) for more details.

Init is a special function name required by the low-level chaincode API but has no special meaning when using the higher-level Contract API. You can use whatever transaction function name you want as an initialization function. You still need to invoke it explicitly.

It is generally recommended to embed initialization logic into your chaincode rather than require invocation of a special initialization function.

tran-the-lam commented 12 months ago

Thanks a lot