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.
/* * SimpleAssetDemo implements a simple chaincode to manage an asset */ public class SimpleAssetDemo extends ChaincodeBase { /* * Init is called during chaincode instantiation to initialize any data. */ @Override public Response init(ChaincodeStub stub) { } /* * Invoke is called per transaction on the chaincode. Each transaction is * either a 'get' or a 'set' on the asset created by Init function. The 'set' * method may create a new asset by specifying a new key-value pair. */ @Override public Response invoke(ChaincodeStub stub) { } public static void main(String[] args) { new SimpleAssetDemo().start(args); } }

Official Examples

Hyperledger Fabric provides many official smart contract samples. For details, reference Fabric official samples. This example uses the ABstore sample officially provided by Hyperledger Fabric. The init function of this sample is used to initialize two key-value pairs. The invoke function is used to perform subdivided calls according to different business logics. Finally, call the following business logic APIs:
invoke: transfer values between keys.
delete: delete a key-value pair.
query: query 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 user input parameters are obtained by calling the APIs getFunction and getParameters. After obtaining the user input parameters, the data is written to the ledger by calling the API putStringState. The specific code is as follows:
/* * The init function is used to initialize two key-value pairs. The user-provided input parameters are KEY1_NAME, VALUE1, * KEY2_NAME, VALUE2 */ @Override public Response init(ChaincodeStub stub) { try { _logger.info("Init java simple chaincode"); List<String> args = stub.getParameters(); if (args.size() != 4) { newErrorResponse("Incorrect number of arguments. Expecting 4"); } // Initialize the chaincode String account1Key = args.get(0); int account1Value = Integer.parseInt(args.get(1)); String account2Key = args.get(2); int account2Value = Integer.parseInt(args.get(3)); _logger.info(String.format("account %s, value = %s; account %s, value %s", account1Key, account1Value, account2Key, account2Value)); stub.putStringState(account1Key, args.get(1)); stub.putStringState(account2Key, args.get(3)); return newSuccessResponse(); } catch (Throwable e) { return newErrorResponse(e); } }

Function Invocation Example

The invoke function splits the user's different smart contract business logic. In this example, the user's specific business type and parameters are obtained by calling the APIs getFunction and getParameters. According to the user's different business types, different business functions are called respectively, such as the invoke, delete and query functions. The specific code is as follows:
// The invoke function subdivides the user-called function into several sub-functions, including invoke, delete, and query. @Override public Response invoke(ChaincodeStub stub) { try { _logger.info("Invoke java simple chaincode"); String func = stub.getFunction(); List<String> params = stub.getParameters(); if (func.equals("invoke")) { return invoke(stub, params); } if (func.equals("delete")) { return delete(stub, params); } if (func.equals("query")) { return query(stub, params); } return newErrorResponse("Invalid invoke function name. Expecting one of: [\\"invoke\\", \\"delete\\", \\"query\\"]"); } catch (Throwable e) { return newErrorResponse(e); } }

Business Logic invoke Function Example

The invoke function of business logic 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 getStringState. Asset transfer is implemented through user business logic. The user's final asset is written to the ledger by calling the API putStringState. The specific code is as follows:
// The invoke function realizes the transfer of values between two keys. The input includes KEY1_NAME, KEY2_NAME, and VALUE. private Response invoke(ChaincodeStub stub, List<String> args) { if (args.size() != 3) { return newErrorResponse("Incorrect number of arguments. Expecting 3"); } String accountFromKey = args.get(0); String accountToKey = args.get(1); String accountFromValueStr = stub.getStringState(accountFromKey); if (accountFromValueStr == null) { return newErrorResponse(String.format("Entity %s not found", accountFromKey)); } int accountFromValue = Integer.parseInt(accountFromValueStr); String accountToValueStr = stub.getStringState(accountToKey); if (accountToValueStr == null) { return newErrorResponse(String.format("Entity %s not found", accountToKey)); } int accountToValue = Integer.parseInt(accountToValueStr); int amount = Integer.parseInt(args.get(2)); if (amount > accountFromValue) { return newErrorResponse(String.format("not enough money in account %s", accountFromKey)); } accountFromValue -= amount; accountToValue += amount; _logger.info(String.format("new value of A: %s", accountFromValue)); _logger.info(String.format("new value of B: %s", accountToValue)); stub.putStringState(accountFromKey, Integer.toString(accountFromValue)); stub.putStringState(accountToKey, Integer.toString(accountToValue)); _logger.info("Transfer complete"); return newSuccessResponse("invoke finished successfully", ByteString.copyFrom(accountFromKey + ": " + accountFromValue + " " + accountToKey + ": " + accountToValue, UTF_8).toByteArray()); }

delete Function Sample Code

The delete function of business logic is mainly used to implement the account deletion functionality in business logic. In this example, the corresponding account is deleted by calling the API delState. The specific code is as follows:
// The delete function is used to delete the specified key from the ledger. The input is KEY_NAME. private Response delete(ChaincodeStub stub, List<String> args) { if (args.size() != 1) { return newErrorResponse("Incorrect number of arguments. Expecting 1"); } String key = args.get(0); // Delete the key from the state in ledger stub.delState(key); return newSuccessResponse(); }

query Function Example

The query function of business logic is mainly used to implement the account query functionality in business logic. In this example, the asset of the corresponding account is queried by calling the API getStringState. The specific code is as follows:
// query mainly retrieves the corresponding value of a KEY. the input is KEY_NAME. private Response query(ChaincodeStub stub, List<String> args) { if (args.size() != 1) { return newErrorResponse("Incorrect number of arguments. Expecting NAME of the person to query"); } String KEY = args.get(0); // byte[] stateBytes String val = stub.getStringState(KEY); if (val == null) { return newErrorResponse(String.format("Error: state for %s is null", KEY)); } _logger.info(String.format("query Response: NAME: %s, Amount: %s ", KEY, val)); return newSuccessResponse(val, ByteString.copyFrom(val, UTF_8).toByteArray()); }


도움말 및 지원

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

피드백