tencent cloud

Tencent Cloud Blockchain as a Service

Release Notes
Product Introduction
Overview
Product Features
Underlying Engine
Strengths
Scenarios
Basic Concepts
Purchase Guide
Purchase Page Description
Overdue Payment Instructions
Pricing and Specification Description
Getting Started
Hyperledger Fabric
Operation Guide
Consortium
Event Center
Network Overview
Connection Management
Contract Management
Organization Management
Node Management
Blockchain Browser
Certificate management
Audit Log
Node Monitoring and Logs
Development Guide
Hyperledger Fabric
Application System Integration
API Documentation
History
Introduction
API Category
Making API Requests
Hyperledger Fabric 2.3 APIs
Data Types
Error Codes
FAQs
Product Policy
Data Processing And Security Agreement
Contact Us

Contract Example

PDF
포커스 모드
폰트 크기
마지막 업데이트 시간: 2025-04-10 00:41:07

Basic Example

This example takes a basic smart contract use case as an example. It only contains the necessary parts of a smart contract and does not implement any business logic.
package main import ( "errors" "fmt" "strconv" "github.com/hyperledger/fabric-contract-api-go/contractapi" ) // ABstore Chaincode implementation type ABstore struct { contractapi.Contract } func main() { cc, err := contractapi.NewChaincode(new(ABstore)) if err != nil { panic(err.Error()) } if err := cc.Start(); err != nil { fmt.Printf("Error starting ABstore chaincode: %s", err) } }

Official Examples

Hyperledger Fabric provides many official smart contract examples, seefabric official examples fordetails. This example takes the ABstore sample officially provided by Hyperledger Fabric as an example. The Init function of this example is used to initialize two key/value pairs, and the Invoke function is used to subdivide calls according to different business logics, and finally call the following business logic interfaces:
1. Init: Used to initialize key-value pairs.
2. Invoke: transfer values between keys.
3. Delete: Used to delete a key-value pair.
4. Query: Used for querying the corresponding value of a key.

Init Function Example

The Init function will be called when the smart contract is instantiated and upgraded. In this example, the data is written to the ledger by calling the API PutState. The specific code is as follows:
// Init is used to initialize two key-value pairs. The parameters entered by the user are KEY1_NAME, VALUE1, KEY2_NAME, VALUE2. func (t *ABstore) Init(ctx contractapi.TransactionContextInterface, A string, Aval int, B string, Bval int) error { fmt.Println("ABstore Init") var err error // Initialize the chaincode fmt.Printf("Aval = %d, Bval = %d\\n", Aval, Bval) // Write the state to the ledger err = ctx.GetStub().PutState(A, []byte(strconv.Itoa(Aval))) if err != nil { return err } err = ctx.GetStub().PutState(B, []byte(strconv.Itoa(Bval))) if err != nil { return err } return nil }

Invoke Function Sample Code

User business logic invokes function is mainly used to implement asset transfer in business logic. In this example, the total asset value corresponding to the KEY is obtained by calling the API GetState. Asset transfer is implemented through user business logic. The user's final asset is written to the ledger by calling the API PutState. The specific code is as follows:
// invoke to transfer value between two keys, enter KEY1_NAME, KEY2_NAME, VALUE func (t *ABstore) Invoke(ctx contractapi.TransactionContextInterface, A, B string, X int) error { var err error var Aval int var Bval int // Get the state from the ledger // TODO: will be nice to have a GetAllState call to ledger Avalbytes, err := ctx.GetStub().GetState(A) if err != nil { return fmt.Errorf("Failed to get state") } if Avalbytes == nil { return fmt.Errorf("Entity not found") } Aval, _ = strconv.Atoi(string(Avalbytes)) Bvalbytes, err := ctx.GetStub().GetState(B) if err != nil { return fmt.Errorf("Failed to get state") } if Bvalbytes == nil { return fmt.Errorf("Entity not found") } Bval, _ = strconv.Atoi(string(Bvalbytes)) // Perform the execution Aval = Aval - X Bval = Bval + X fmt.Printf("Aval = %d, Bval = %d\\n", Aval, Bval) // Write the state back to the ledger err = ctx.GetStub().PutState(A, []byte(strconv.Itoa(Aval))) if err != nil { return err } err = ctx.GetStub().PutState(B, []byte(strconv.Itoa(Bval))) if err != nil { return err } return nil }

Delete Function Example

The delete function in business logic is mainly used to implement the account deletion feature in business logic. In this example, the corresponding account is deleted by calling the API DelState. The specific code is as follows:
// delete is used to delete the specified key from the ledger. Enter KEY_NAME. func (t *ABstore) Delete(ctx contractapi.TransactionContextInterface, A string) error { // Delete the key from the state in ledger err := ctx.GetStub().DelState(A) if err != nil { return fmt.Errorf("Failed to delete state") } return nil }

Query Function Example

The query function in business logic is mainly used to implement the account inquiry functionality. In this example, the API GetState is called to search for corresponding account assets. The specific code is as follows:
// query is mainly the value corresponding to the query key. Enter KEY_NAME. func (t *ABstore) Query(ctx contractapi.TransactionContextInterface, A string) (string, error) { var err error // Get the state from the ledger Avalbytes, err := ctx.GetStub().GetState(A) if err != nil { jsonResp := "{\\"Error\\":\\"Failed to get state for " + A + "\\"}" return "", errors.New(jsonResp) } if Avalbytes == nil { jsonResp := "{\\"Error\\":\\"Nil amount for " + A + "\\"}" return "", errors.New(jsonResp) } jsonResp := "{\\"Name\\":\\"" + A + "\\",\\"Amount\\":\\"" + string(Avalbytes) + "\\"}" fmt.Printf("Query Response:%s\\n", jsonResp) return string(Avalbytes), nil }


도움말 및 지원

문제 해결에 도움이 되었나요?

피드백